From 4947b7d12d2b05d6e75459c9b3082c06f45404b7 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Wed, 11 Nov 2026 16:38:04 +0400 Subject: [PATCH 01/20] feat(ui): draw and offer Georgian with Noto Sans Georgian from craft-fonts (M8) Embeds craft-fonts' NotoSansGeorgian.ttf (Geor) as a fallback face in every family, and offers Georgian (ka) only in builds that embedded it. Without CRAFT_FONTS_DIR nothing changes. --- ATTRIBUTION.md | 1 + build.rs | 5 +++-- docs/development.md | 2 +- docs/localisation.md | 5 +++-- src/i18n/mod.rs | 19 +++++++++++++++++-- src/i18n/tests.rs | 24 ++++++++++++++++++++++++ src/theme.rs | 15 ++++++++++++++- 7 files changed, 63 insertions(+), 8 deletions(-) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 7cc10202..96f798ee 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -57,6 +57,7 @@ here. |---|---|---|---| | Inter Regular | UI prose (primary) | The Inter Project Authors (Rasmus Andersson) | SIL OFL 1.1, shipped as `OFL-Inter.txt` | | JetBrains Mono Regular | UI data: timeline, readouts, values, shortcuts (primary) | The JetBrains Mono Project Authors | SIL OFL 1.1, shipped as `OFL-JetBrainsMono.txt` | +| Noto Sans Georgian (variable) | Fallback face for Georgian (`Geor` in craft-fonts) | The Noto Project Authors | SIL OFL 1.1, shipped as `OFL-noto-sans-georgian.txt` | ### Optional build input: craft-i18n (not files in this repo) diff --git a/build.rs b/build.rs index fbd5c89c..482faedb 100644 --- a/build.rs +++ b/build.rs @@ -3,7 +3,8 @@ //! //! `CRAFT_FONTS_DIR= cargo build` embeds the UI typefaces chosen in //! ADR 0005: Inter (prose) and JetBrains Mono (data), both SIL OFL 1.1. Font files are never -//! committed to this repository. Without the variable the app uses egui's bundled defaults, and +//! committed to this repository. It also embeds Noto Sans Georgian (`Geor` in craft-fonts) as a +//! fallback face, which is what lets the interface offer Georgian. Without the variable the app uses egui's bundled defaults, and //! everything still works. //! //! `CRAFT_I18N_DIR=` embeds the interface catalogs (ADR 0040); without it @@ -12,7 +13,7 @@ use std::path::{Path, PathBuf}; /// Files we look for, and the generated constant each fills. -const FONTS: [(&str, &str); 2] = [("Inter-Regular.ttf", "UI_FONT"), ("JetBrainsMono-Regular.ttf", "MONO_FONT")]; +const FONTS: [(&str, &str); 3] = [("Inter-Regular.ttf", "UI_FONT"), ("JetBrainsMono-Regular.ttf", "MONO_FONT"), ("NotoSansGeorgian.ttf", "GEORGIAN_FONT")]; fn find(dir: &Path, name: &str, depth: u32) -> Option { let entries = std::fs::read_dir(dir).ok()?; diff --git a/docs/development.md b/docs/development.md index 167cd9f7..6a6364ed 100644 --- a/docs/development.md +++ b/docs/development.md @@ -14,7 +14,7 @@ cargo deny check licenses bans sources cargo run --release -p anicraft-cli -- bench # performance probe ``` -Fonts: builds embed Inter and JetBrains Mono when `CRAFT_FONTS_DIR` points at a craft-fonts +Fonts: builds embed Inter, JetBrains Mono and Noto Sans Georgian (the interface offers Georgian only then) when `CRAFT_FONTS_DIR` points at a craft-fonts checkout, or when one is found next to the repository (ADR 0005). Otherwise they use the built-in fallback fonts. diff --git a/docs/localisation.md b/docs/localisation.md index dc658d0b..b99691d6 100644 --- a/docs/localisation.md +++ b/docs/localisation.md @@ -96,7 +96,7 @@ and a trailing `…`. Then open a pull request in craft-i18n. Follow its clean-r from the plain meaning of the English, never from another product's translated interface. A language is offered once craft-i18n has its `anicraft.tsv` and it is in `i18n::READY` -(left-to-right Latin, Greek and Cyrillic scripts today). +(left-to-right Latin, Greek and Cyrillic scripts today, and Georgian in builds with its craft-fonts face). ## Building with translations @@ -118,7 +118,8 @@ shaping. So: | Script | Today | |---|---| | Latin, Greek, Cyrillic | Offered when a catalog exists. | -| Chinese, Japanese, Korean, Georgian | Draw correctly, but need a font the app doesn't bundle (a craft-fonts face), then a `READY` entry. | +| Georgian | Offered when a catalog exists and the build embedded Noto Sans Georgian from craft-fonts (`i18n::ready_codes`); without `CRAFT_FONTS_DIR` it stays hidden. | +| Chinese, Japanese, Korean | Draw correctly, but need a font the app doesn't bundle (a craft-fonts face), then a `READY` entry. | | Arabic, Hebrew, Persian, Urdu, Kurdish, Dhivehi | Not offered: right to left needs bidi and shaping in egui's text layout, and mirrored widgets. We follow upstream egui rather than fork it. | | Devanagari, Bengali, Tamil, Telugu, Thai, Lao | Not offered: they need shaping. | | Vietnamese | Not offered yet: needs a check that every fallback face has its letters. | diff --git a/src/i18n/mod.rs b/src/i18n/mod.rs index fe04cb2b..5d2c4721 100644 --- a/src/i18n/mod.rs +++ b/src/i18n/mod.rs @@ -39,11 +39,26 @@ pub const PSEUDO: &str = "pseudo"; /// Languages the interface can be drawn in today: written left to right, in scripts the bundled /// faces cover and egui lays out a letter at a time (Latin, Greek, Cyrillic). A catalog for any /// other locale is embedded but not offered (docs/localisation.md › Scripts and direction). -/// A regional variant (`es-mx`) is ready when its language is. +/// A regional variant (`es-mx`) is ready when its language is. Georgian is not listed here: its +/// face is not bundled, so [`ready_codes`] adds it only when the build embedded Noto Sans +/// Georgian from craft-fonts. pub const READY: &[&str] = &[ "az", "bg", "bs", "ca", "cs", "da", "de", "el", "es", "et", "fi", "fr", "gl", "hr", "hu", "id", "it", "kk", "lt", "lv", "nb", "nl", "pl", "pt", "pt-br", "ro", "ru", "sk", "sl", "sq", "sr", "sr-latn", "sv", "tr", "uk", ]; +/// [`READY`] plus the languages whose script needs a craft-fonts face this build embedded. +pub fn ready_codes() -> Vec<&'static str> { + ready_with(crate::theme::georgian_font().is_some()) +} + +fn ready_with(georgian_face: bool) -> Vec<&'static str> { + let mut codes = READY.to_vec(); + if georgian_face { + codes.push("ka"); + } + codes +} + enum Kind { English, Pseudo, @@ -177,7 +192,7 @@ impl Languages { static ENGLISH_LANGUAGE: Language = Language { code: String::new(), name: String::new(), kind: Kind::English }; static LANGUAGES: LazyLock = LazyLock::new(|| { - let (languages, problems) = Languages::new(CRAFT_I18N, READY); + let (languages, problems) = Languages::new(CRAFT_I18N, &ready_codes()); for p in problems { eprintln!("interface catalog: {p} (shown in English)"); } diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index 971a0377..9cbd4ff8 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -293,6 +293,30 @@ fn offered_languages_have_their_own_catalog_and_a_ready_script() { assert_eq!(names, ["English", "Deutsch", "Português (Brasil)", "Русский", "Pseudo-locale (layout test)"]); } +#[test] +fn georgian_is_offered_only_when_its_face_is_embedded() { + let ka = [("ka", "", "@id\tlanguage.name\tქართული\n")]; + let offered = |face: bool| Languages::new(&ka, &ready_with(face)).0.list.iter().any(|l| l.code == "ka"); + assert!(!offered(false), "no face, no Georgian"); + assert!(offered(true)); + // The real build agrees with its own face. + assert_eq!(ready_codes().contains(&"ka"), crate::theme::georgian_font().is_some()); + // CRAFT_FONTS_REQUIRED=1 (release builds, CI with craft-fonts) makes a missing face a failure. + let face = crate::theme::georgian_font(); + if std::env::var("CRAFT_FONTS_REQUIRED").is_ok_and(|v| v == "1") && std::env::var_os("CRAFT_FONTS_DIR").is_some() { + assert!(face.is_some(), "CRAFT_FONTS_DIR has no NotoSansGeorgian.ttf (craft-fonts `Geor`)"); + } + let Some(face) = face else { + println!("georgian face test: skipped, this build embeds no Georgian face"); + return; + }; + let letters: String = ('\u{10D0}'..='\u{10FA}').collect(); + let fonts = anicraft_engine::text::Fonts::from_faces([face.to_vec()]); + let laid = fonts.layout(&letters, &anicraft_engine::text::Style::default()).expect("layout"); + assert_eq!(laid.missing, 0, "the face lacks some of U+10D0..U+10FA"); + println!("georgian face test: ran, {} letters covered", letters.chars().count()); +} + #[test] fn lookups_fall_back_from_app_to_shared_to_base_language_to_english() { let l = fixture(); diff --git a/src/theme.rs b/src/theme.rs index 7043277a..1d1fb1fc 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -368,6 +368,12 @@ pub fn embedded_fonts() -> Vec> { [craft_fonts::UI_FONT, craft_fonts::MONO_FONT].into_iter().flatten().map(std::sync::Arc::from).collect() } +/// Noto Sans Georgian (craft-fonts `Geor`) when this build embedded it. The interface offers +/// Georgian only then (`i18n::ready_codes`). +pub fn georgian_font() -> Option<&'static [u8]> { + craft_fonts::GEORGIAN_FONT +} + /// Which typefaces are active (for About and diagnostics), in the interface language. pub fn font_summary() -> String { match (craft_fonts::UI_FONT, craft_fonts::MONO_FONT) { @@ -383,7 +389,8 @@ pub type UserFont = (String, Vec, u32); /// Installs the UI typefaces (ADR 0005). Order in each family: the user's system font (from /// Preferences), then the craft-fonts pair (when embedded at build time), then egui's bundled -/// fonts, which stay as fallbacks for glyph coverage. +/// fonts, which stay as fallbacks for glyph coverage, then Noto Sans Georgian (when embedded) +/// for the letters none of them has. pub fn install_fonts(ctx: &egui::Context, ui_font: Option<&UserFont>, data_font: Option<&UserFont>) { use egui::{FontData, FontDefinitions, FontFamily}; use std::sync::Arc; @@ -394,6 +401,12 @@ pub fn install_fonts(ctx: &egui::Context, ui_font: Option<&UserFont>, data_font: defs.families.entry(family).or_default().insert(0, name.to_owned()); } } + if let Some(b) = craft_fonts::GEORGIAN_FONT { + defs.font_data.insert("craft-noto-sans-georgian".to_owned(), Arc::new(FontData::from_static(b))); + for family in [FontFamily::Proportional, FontFamily::Monospace] { + defs.families.entry(family).or_default().push("craft-noto-sans-georgian".to_owned()); + } + } for (user, family) in [(ui_font, FontFamily::Proportional), (data_font, FontFamily::Monospace)] { if let Some((name, bytes, index)) = user { let key = format!("user:{name}"); From 20cfea4aead772eb838f32b443c6c5a244676ab7 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Wed, 11 Nov 2026 16:49:25 +0400 Subject: [PATCH 02/20] style: wrap the FONTS table at max_width (M8) --- build.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/build.rs b/build.rs index 482faedb..aae5c0d7 100644 --- a/build.rs +++ b/build.rs @@ -13,7 +13,8 @@ use std::path::{Path, PathBuf}; /// Files we look for, and the generated constant each fills. -const FONTS: [(&str, &str); 3] = [("Inter-Regular.ttf", "UI_FONT"), ("JetBrainsMono-Regular.ttf", "MONO_FONT"), ("NotoSansGeorgian.ttf", "GEORGIAN_FONT")]; +const FONTS: [(&str, &str); 3] = + [("Inter-Regular.ttf", "UI_FONT"), ("JetBrainsMono-Regular.ttf", "MONO_FONT"), ("NotoSansGeorgian.ttf", "GEORGIAN_FONT")]; fn find(dir: &Path, name: &str, depth: u32) -> Option { let entries = std::fs::read_dir(dir).ok()?; From 39cc5484d5cb2fe9d1b49f449dac3fab6d04b3ad Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Wed, 11 Nov 2026 20:13:21 +0400 Subject: [PATCH 03/20] fix(i18n): validate the Georgian face before offering or loading it; REQUIRED alone enforces it (M8) --- docs/localisation.md | 2 +- src/i18n/tests.rs | 12 ++++++++++-- src/theme.rs | 24 ++++++++++++++++++++---- 3 files changed, 31 insertions(+), 7 deletions(-) diff --git a/docs/localisation.md b/docs/localisation.md index b99691d6..cbf65cbb 100644 --- a/docs/localisation.md +++ b/docs/localisation.md @@ -118,7 +118,7 @@ shaping. So: | Script | Today | |---|---| | Latin, Greek, Cyrillic | Offered when a catalog exists. | -| Georgian | Offered when a catalog exists and the build embedded Noto Sans Georgian from craft-fonts (`i18n::ready_codes`); without `CRAFT_FONTS_DIR` it stays hidden. | +| Georgian | Offered when a catalog exists and the build embedded a valid Noto Sans Georgian from craft-fonts (via `CRAFT_FONTS_DIR` or the nearby checkout `build.rs` discovers); hidden only when it did not (`i18n::ready_codes`). | | Chinese, Japanese, Korean | Draw correctly, but need a font the app doesn't bundle (a craft-fonts face), then a `READY` entry. | | Arabic, Hebrew, Persian, Urdu, Kurdish, Dhivehi | Not offered: right to left needs bidi and shaping in egui's text layout, and mirrored widgets. We follow upstream egui rather than fork it. | | Devanagari, Bengali, Tamil, Telugu, Thai, Lao | Not offered: they need shaping. | diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index 9cbd4ff8..5680fcbd 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -303,8 +303,8 @@ fn georgian_is_offered_only_when_its_face_is_embedded() { assert_eq!(ready_codes().contains(&"ka"), crate::theme::georgian_font().is_some()); // CRAFT_FONTS_REQUIRED=1 (release builds, CI with craft-fonts) makes a missing face a failure. let face = crate::theme::georgian_font(); - if std::env::var("CRAFT_FONTS_REQUIRED").is_ok_and(|v| v == "1") && std::env::var_os("CRAFT_FONTS_DIR").is_some() { - assert!(face.is_some(), "CRAFT_FONTS_DIR has no NotoSansGeorgian.ttf (craft-fonts `Geor`)"); + if std::env::var("CRAFT_FONTS_REQUIRED").is_ok_and(|v| v == "1") { + assert!(face.is_some(), "CRAFT_FONTS_REQUIRED=1 but this build embeds no valid NotoSansGeorgian.ttf (craft-fonts `Geor`)"); } let Some(face) = face else { println!("georgian face test: skipped, this build embeds no Georgian face"); @@ -314,6 +314,14 @@ fn georgian_is_offered_only_when_its_face_is_embedded() { let fonts = anicraft_engine::text::Fonts::from_faces([face.to_vec()]); let laid = fonts.layout(&letters, &anicraft_engine::text::Style::default()).expect("layout"); assert_eq!(laid.missing, 0, "the face lacks some of U+10D0..U+10FA"); + // ... and through the families the app really builds (Proportional and Monospace). + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx, None, None); + let _ = ctx.run(egui::RawInput::default(), |_| {}); // fonts apply at the start of a frame + for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { + let id = egui::FontId::new(14.0, family.clone()); + assert!(ctx.fonts_mut(|f| f.has_glyphs(&id, &letters)), "{family:?} lacks Georgian letters"); + } println!("georgian face test: ran, {} letters covered", letters.chars().count()); } diff --git a/src/theme.rs b/src/theme.rs index 1d1fb1fc..b5f9541e 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -368,10 +368,26 @@ pub fn embedded_fonts() -> Vec> { [craft_fonts::UI_FONT, craft_fonts::MONO_FONT].into_iter().flatten().map(std::sync::Arc::from).collect() } -/// Noto Sans Georgian (craft-fonts `Geor`) when this build embedded it. The interface offers -/// Georgian only then (`i18n::ready_codes`). +/// Noto Sans Georgian (craft-fonts `Geor`) when this build embedded a face that parses. The +/// interface offers Georgian only then (`i18n::ready_codes`), and `install_fonts` loads the same +/// face: epaint panics on bytes it cannot parse, so a damaged file must never reach it. pub fn georgian_font() -> Option<&'static [u8]> { - craft_fonts::GEORGIAN_FONT + static FACE: std::sync::OnceLock> = std::sync::OnceLock::new(); + *FACE.get_or_init(|| craft_fonts::GEORGIAN_FONT.filter(|b| parses_as_font(b))) +} + +/// Whether `bytes` is a font file (any face in it parses). +fn parses_as_font(bytes: &[u8]) -> bool { + !anicraft_engine::text::Fonts::from_faces([bytes.to_vec()]).families().is_empty() +} + +#[cfg(test)] +mod georgian_face_tests { + #[test] + fn garbage_bytes_are_not_a_font() { + assert!(!super::parses_as_font(b"not a font file at all")); + assert!(!super::parses_as_font(&[])); + } } /// Which typefaces are active (for About and diagnostics), in the interface language. @@ -401,7 +417,7 @@ pub fn install_fonts(ctx: &egui::Context, ui_font: Option<&UserFont>, data_font: defs.families.entry(family).or_default().insert(0, name.to_owned()); } } - if let Some(b) = craft_fonts::GEORGIAN_FONT { + if let Some(b) = georgian_font() { defs.font_data.insert("craft-noto-sans-georgian".to_owned(), Arc::new(FontData::from_static(b))); for family in [FontFamily::Proportional, FontFamily::Monospace] { defs.families.entry(family).or_default().push("craft-noto-sans-georgian".to_owned()); From 55a0b3442b7eca6faefd1ebb827de57a3addd094 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Wed, 11 Nov 2026 20:14:24 +0400 Subject: [PATCH 04/20] fix(i18n): run the headless frame with run_ui (M8) --- src/i18n/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index 5680fcbd..ecce0a7c 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -317,7 +317,7 @@ fn georgian_is_offered_only_when_its_face_is_embedded() { // ... and through the families the app really builds (Proportional and Monospace). let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx, None, None); - let _ = ctx.run(egui::RawInput::default(), |_| {}); // fonts apply at the start of a frame + let _ = ctx.run_ui(egui::RawInput::default(), |_| {}); // fonts apply at the start of a frame for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { let id = egui::FontId::new(14.0, family.clone()); assert!(ctx.fonts_mut(|f| f.has_glyphs(&id, &letters)), "{family:?} lacks Georgian letters"); From 7f649051bc3d2e9a5669a166498a0a77bf9e7727 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Wed, 11 Nov 2026 20:17:36 +0400 Subject: [PATCH 05/20] fix(i18n): clear the headless frame's texture deltas in the font test (M8) --- src/i18n/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index ecce0a7c..ae1bc903 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -317,7 +317,7 @@ fn georgian_is_offered_only_when_its_face_is_embedded() { // ... and through the families the app really builds (Proportional and Monospace). let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx, None, None); - let _ = ctx.run_ui(egui::RawInput::default(), |_| {}); // fonts apply at the start of a frame + ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); // fonts apply at the start of a frame for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { let id = egui::FontId::new(14.0, family.clone()); assert!(ctx.fonts_mut(|f| f.has_glyphs(&id, &letters)), "{family:?} lacks Georgian letters"); From 2be050fcab3a813828caad2a80251d6636df9c09 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Wed, 11 Nov 2026 20:24:57 +0400 Subject: [PATCH 06/20] test(i18n): check Georgian coverage through the Proportional family install_fonts builds (M8) --- src/i18n/tests.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index ae1bc903..221dee02 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -314,14 +314,13 @@ fn georgian_is_offered_only_when_its_face_is_embedded() { let fonts = anicraft_engine::text::Fonts::from_faces([face.to_vec()]); let laid = fonts.layout(&letters, &anicraft_engine::text::Style::default()).expect("layout"); assert_eq!(laid.missing, 0, "the face lacks some of U+10D0..U+10FA"); - // ... and through the families the app really builds (Proportional and Monospace). + // ... and through the Proportional family install_fonts builds. Not Monospace: epaint's + // has_glyph is a false negative there (the Georgian face is that chain's replacement-glyph face). let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx, None, None); ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); // fonts apply at the start of a frame - for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { - let id = egui::FontId::new(14.0, family.clone()); - assert!(ctx.fonts_mut(|f| f.has_glyphs(&id, &letters)), "{family:?} lacks Georgian letters"); - } + let prop = egui::FontId::proportional(14.0); + assert!(ctx.fonts_mut(|f| f.has_glyphs(&prop, &letters)), "Proportional lacks Georgian letters"); println!("georgian face test: ran, {} letters covered", letters.chars().count()); } From 5b352fe2642de4f1cbe44fbd5c4b73acdc36faab Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Wed, 11 Nov 2026 20:36:03 +0400 Subject: [PATCH 07/20] fix(i18n): offer Georgian only when the embedded face covers its letters (M8) --- src/theme.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/theme.rs b/src/theme.rs index b5f9541e..383ae498 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -368,7 +368,8 @@ pub fn embedded_fonts() -> Vec> { [craft_fonts::UI_FONT, craft_fonts::MONO_FONT].into_iter().flatten().map(std::sync::Arc::from).collect() } -/// Noto Sans Georgian (craft-fonts `Geor`) when this build embedded a face that parses. The +/// Noto Sans Georgian (craft-fonts `Geor`) when this build embedded a face that parses and covers +/// the Georgian letters. The /// interface offers Georgian only then (`i18n::ready_codes`), and `install_fonts` loads the same /// face: epaint panics on bytes it cannot parse, so a damaged file must never reach it. pub fn georgian_font() -> Option<&'static [u8]> { @@ -376,9 +377,11 @@ pub fn georgian_font() -> Option<&'static [u8]> { *FACE.get_or_init(|| craft_fonts::GEORGIAN_FONT.filter(|b| parses_as_font(b))) } -/// Whether `bytes` is a font file (any face in it parses). +/// Whether `bytes` is a font file that draws every Georgian letter (U+10D0..U+10FA). fn parses_as_font(bytes: &[u8]) -> bool { - !anicraft_engine::text::Fonts::from_faces([bytes.to_vec()]).families().is_empty() + let letters: String = ('\u{10D0}'..='\u{10FA}').collect(); + let fonts = anicraft_engine::text::Fonts::from_faces([bytes.to_vec()]); + fonts.layout(&letters, &anicraft_engine::text::Style::default()).is_ok_and(|laid| laid.missing == 0) } #[cfg(test)] From 30472641fb3712b65835f46db1ee7e2a8d216edc Mon Sep 17 00:00:00 2001 From: mypenc Date: Wed, 11 Nov 2026 23:28:44 +0000 Subject: [PATCH 08/20] feat(transform): skew/shear by dragging a box edge in Free Transform (#174) --- CHANGELOG.md | 3 +++ src/app.rs | 5 ++++- src/stage.rs | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 65528a94..a18830cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,9 @@ `prefs.recent_pin`, `prefs.recent_remove`, `prefs.recent_clear`; `file.import` takes `cx`/`cy` and `layer: "active"`. +* **Free Transform: skew and shear** (#174). Dragging the line between two handles of the + selection box shears the artwork along that edge, as in Adobe Animate: the opposite edge stays + put and Alt skews about the centre. The cursor shows the direction. * **Buttons, complete: sounds on button frames and hit-area editing** (ADR 0057, M5). * A sound on a button's **Over** or **Down** frame plays when the pointer goes over or presses the button, in Test Movie and in the HTML canvas page (Web Audio). As the SWF format diff --git a/src/app.rs b/src/app.rs index e610aca4..8386fdf9 100644 --- a/src/app.rs +++ b/src/app.rs @@ -129,7 +129,7 @@ impl Tool { Tool::Eraser => tr_noop!("Drag to erase lines and fills drawn with Object Drawing off (drawing objects and symbols are kept). [ and ] change the size; the options set the shape and erase mode, and the Faucet deletes a whole fill or line with a click. Double-click the tool to erase everything on the stage."), Tool::Width => tr_noop!("Hover a stroke to see its width points. Drag a point's handle to widen or narrow the stroke there (Alt: one side only), drag its dot to slide it along, or drag anywhere on the stroke to add a point. Click a point and press Delete to remove it."), Tool::Bone => tr_noop!("Drag from one symbol instance to another to join them with a bone (they move to an armature layer); start on a bone's end to continue the chain. Click a bone to select it. Pose the armature by dragging bones or instances with the Selection tool."), - Tool::Transform => tr_noop!("Drag a corner or edge to scale (Shift keeps proportions, Alt scales from the centre), just outside a corner to rotate (Shift snaps 15°), inside to move."), + Tool::Transform => tr_noop!("Drag a handle to scale (Shift keeps proportions, Alt scales from the centre), a line between handles to skew (Alt skews about the centre), just outside a corner to rotate (Shift snaps 15°), inside to move."), Tool::Rect => tr_noop!("Drag to draw a rectangle. Shift draws a square."), Tool::Oval => tr_noop!("Drag to draw an oval. Shift draws a circle."), Tool::Star => tr_noop!("Drag from the centre to draw a star."), @@ -247,6 +247,9 @@ pub enum XfKind { /// Handle position: -1/0/1 on each axis (corner, edge or centre). Scale { hx: i8, hy: i8 }, Rotate, + /// Dragging the line between two handles shears along that edge (the sign is which edge: + /// `hx` is -1/1 on the left/right edge, `hy` is -1/1 on the top/bottom, the other is 0). + Skew { hx: i8, hy: i8 }, } /// A small text prompt standing in for native file dialogs (M0). diff --git a/src/stage.rs b/src/stage.rs index 583b6e86..f71647ea 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -334,6 +334,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { Some(XfKind::Scale { hx, hy }) if hx * hy < 0 => CursorIcon::ResizeNeSw, Some(XfKind::Scale { hx: 0, .. }) => CursorIcon::ResizeVertical, Some(XfKind::Scale { .. }) => CursorIcon::ResizeHorizontal, + Some(XfKind::Skew { hy: 0, .. }) => CursorIcon::ResizeVertical, + Some(XfKind::Skew { .. }) => CursorIcon::ResizeHorizontal, Some(XfKind::Rotate) => CursorIcon::Alias, Some(XfKind::Move) => CursorIcon::Move, None => CursorIcon::Default, @@ -1398,6 +1400,8 @@ fn text_editor(app: &mut App, ui: &mut egui::Ui, stage_origin: Pos2, zoom: f32) /// Screen-space handle size and the rotation zone just outside each corner. const HANDLE: f32 = 8.0; const ROTATE_ZONE: f32 = 22.0; +/// How far from a box edge line (screen space) a press still grabs it to skew. +const SKEW_ZONE: f32 = 5.0; fn bounds_arr(b: anicraft_engine::geom::Rect) -> Option<[f32; 4]> { (!b.is_empty()).then_some([b.min.x, b.min.y, b.max.x, b.max.y]) @@ -1416,6 +1420,19 @@ fn xf_zone(r: Rect, p: Pos2) -> Option { return Some(XfKind::Scale { hx, hy }); } } + // The line between two handles skews (Animate parity, #174); the handles above win at the ends. + let near = |a: f32, b: f32| (a - b).abs() <= SKEW_ZONE; + if (r.left() - SKEW_ZONE..=r.right() + SKEW_ZONE).contains(&p.x) && (r.top() - SKEW_ZONE..=r.bottom() + SKEW_ZONE).contains(&p.y) { + if near(p.y, r.top()) { + return Some(XfKind::Skew { hx: 0, hy: -1 }); + } else if near(p.y, r.bottom()) { + return Some(XfKind::Skew { hx: 0, hy: 1 }); + } else if near(p.x, r.left()) { + return Some(XfKind::Skew { hx: -1, hy: 0 }); + } else if near(p.x, r.right()) { + return Some(XfKind::Skew { hx: 1, hy: 0 }); + } + } if !r.contains(p) && [r.left_top(), r.right_top(), r.left_bottom(), r.right_bottom()].iter().any(|c| c.distance(p) <= ROTATE_ZONE) { return Some(XfKind::Rotate); } @@ -1463,6 +1480,20 @@ pub(crate) fn xf_total(kind: XfKind, b: [f32; 4], start: Pos2, cur: Pos2, shift: let clamp = |s: f32| if s.abs() < 0.01 { 0.01f32.copysign(if s == 0.0 { 1.0 } else { s }) } else { s }; about(px, py, Affine::scale(clamp(sx), clamp(sy))) } + XfKind::Skew { hx, hy } => { + // Top and bottom edges slide sideways, left and right edges slide up and down; the + // opposite edge stays put (Alt: the centre does), so the grabbed edge follows the pointer. + let k = |moved: f32, arm: f32| if arm.abs() < 1e-3 { 0.0 } else { (moved / arm).clamp(-8.0, 8.0) }; + if hy != 0 { + let py = if alt { cy } else { [y1, cy, y0][(hy + 1) as usize] }; + let shear = k(cur.x - start.x, start.y - py); + about(cx, py, Affine { m: [1.0, 0.0, shear, 1.0, 0.0, 0.0] }) + } else { + let px = if alt { cx } else { [x1, cx, x0][(hx + 1) as usize] }; + let shear = k(cur.y - start.y, start.x - px); + about(px, cy, Affine { m: [1.0, shear, 0.0, 1.0, 0.0, 0.0] }) + } + } XfKind::Rotate => { let a0 = (start.y - cy).atan2(start.x - cx); let a1 = (cur.y - cy).atan2(cur.x - cx); @@ -1601,11 +1632,34 @@ mod xf_tests { assert!((angle / 15.0 - (angle / 15.0).round()).abs() < 1e-3, "{angle}"); } + #[test] + fn dragging_the_top_edge_shears_sideways_about_the_bottom_edge() { + // B is 100 x 50: dragging the top edge 10 right moves the top edge 10 right. + let m = xf_total(XfKind::Skew { hx: 0, hy: -1 }, B, pos2(50.0, 0.0), pos2(60.0, 0.0), false, false); + assert_eq!(apply(&m, 0.0, 0.0), Vec2::new(10.0, 0.0)); + assert_eq!(apply(&m, 0.0, 50.0), Vec2::new(0.0, 50.0), "the opposite edge stays put"); + assert!((m.determinant() - 1.0).abs() < 1e-5, "a shear keeps the area"); + } + + #[test] + fn dragging_the_right_edge_shears_vertically_and_alt_pivots_on_the_centre() { + let m = xf_total(XfKind::Skew { hx: 1, hy: 0 }, B, pos2(100.0, 25.0), pos2(100.0, 35.0), false, false); + assert_eq!(apply(&m, 100.0, 0.0), Vec2::new(100.0, 10.0)); + assert_eq!(apply(&m, 0.0, 0.0), Vec2::new(0.0, 0.0)); + let m = xf_total(XfKind::Skew { hx: 1, hy: 0 }, B, pos2(100.0, 25.0), pos2(100.0, 35.0), false, true); + assert_eq!(apply(&m, 50.0, 25.0), Vec2::new(50.0, 25.0), "centre stays put"); + assert_eq!(apply(&m, 100.0, 25.0), Vec2::new(100.0, 35.0)); + } + #[test] fn zones() { let r = Rect::from_min_max(pos2(100.0, 100.0), pos2(300.0, 200.0)); assert_eq!(xf_zone(r, pos2(300.0, 200.0)), Some(XfKind::Scale { hx: 1, hy: 1 })); assert_eq!(xf_zone(r, pos2(200.0, 100.0)), Some(XfKind::Scale { hx: 0, hy: -1 })); + assert_eq!(xf_zone(r, pos2(150.0, 101.0)), Some(XfKind::Skew { hx: 0, hy: -1 })); + assert_eq!(xf_zone(r, pos2(150.0, 199.0)), Some(XfKind::Skew { hx: 0, hy: 1 })); + assert_eq!(xf_zone(r, pos2(99.0, 130.0)), Some(XfKind::Skew { hx: -1, hy: 0 })); + assert_eq!(xf_zone(r, pos2(301.0, 130.0)), Some(XfKind::Skew { hx: 1, hy: 0 })); assert_eq!(xf_zone(r, pos2(312.0, 212.0)), Some(XfKind::Rotate)); assert_eq!(xf_zone(r, pos2(200.0, 150.0)), Some(XfKind::Move)); assert_eq!(xf_zone(r, pos2(500.0, 500.0)), None); From 882668b88c244f87971db50064860a3dfdbdee35 Mon Sep 17 00:00:00 2001 From: lienatanael1-beep Date: Thu, 12 Nov 2026 15:08:24 +0700 Subject: [PATCH 09/20] feat(control): live control port and MCP bridge `anicraft --control ` opens a JSON-lines control port on 127.0.0.1; `anicraft-cli mcp --bridge ` serves the same five MCP tools against the open window. The app runs the CLI's own `mcp::call_tool` (now generic over a `Host`), so live and headless share one dispatcher. A per-run token is written to control.json in the settings folder and removed on exit. Edits wait while the person drags, so undo steps never merge. ADR 0070, docs/control-protocol.md. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 15 + Cargo.lock | 2 + Cargo.toml | 3 + crates/cli/Cargo.toml | 5 +- crates/cli/src/control.rs | 493 +++++++++++++++++++++++++++++ crates/cli/src/control/tests.rs | 253 +++++++++++++++ crates/cli/src/lib.rs | 14 + crates/cli/src/mcp.rs | 82 ++++- docs/adr/0070-live-control-port.md | 99 ++++++ docs/adr/README.md | 1 + docs/control-protocol.md | 103 ++++++ docs/mcp.md | 30 ++ docs/roadmap.md | 2 +- src/app.rs | 10 + src/main.rs | 42 ++- src/panels.rs | 7 + src/platform.rs | 25 ++ src/remote.rs | 143 +++++++++ 18 files changed, 1308 insertions(+), 21 deletions(-) create mode 100644 crates/cli/src/control.rs create mode 100644 crates/cli/src/control/tests.rs create mode 100644 docs/adr/0070-live-control-port.md create mode 100644 docs/control-protocol.md create mode 100644 src/remote.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index b58bef9f..f521c0a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,21 @@ ## Unreleased +* **Remote control: assistants edit the open window live** (ADR 0070). + * `anicraft --control 9878` opens AniCraft as usual and lets an assistant edit the document you + have open, through a port on this computer only. Its edits appear at once and undo with + Ctrl+Z, like yours; the status bar says "Remote control on (port 9878)" while it is open. Also + `ANICRAFT_CONTROL_PORT`. + * `anicraft-cli mcp --bridge 9878`: the MCP server's five tools, acting on that window. It starts + before AniCraft is open, connects on the first call, says how to start AniCraft when it isn't + running, and reconnects after AniCraft is reopened. + * No setup: each run makes a fresh token and writes it to `control.json` in AniCraft's settings + folder (only you can read it), where the bridge finds it. `ANICRAFT_CONTROL_TOKEN` overrides it. + * While you drag, the assistant's edits wait until you let go, so the two never share an undo step. + * The protocol (`docs/control-protocol.md`): JSON lines on `127.0.0.1`; `hello`, `tools.list`, + `tools.call`; anything that isn't a JSON request (such as a web page's request to localhost) is + refused. + * **The user guide** (ADR 0069, M8). * **Help › User Guide** opens AniCraft's guide in your browser. It comes with the app, so it works offline; the web editor serves it beside the editor. It is also in the command palette. diff --git a/Cargo.lock b/Cargo.lock index c4297341..ed118141 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -219,6 +219,7 @@ name = "anicraft" version = "0.2.1" dependencies = [ "anicraft-audio", + "anicraft-cli", "anicraft-doc", "anicraft-engine", "anicraft-geom", @@ -269,6 +270,7 @@ dependencies = [ "anicraft-geom", "anicraft-guide", "anicraft-render", + "getrandom 0.3.4", "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index 2c6d31cb..334a68e4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -112,6 +112,9 @@ sys-locale = "0.3" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] # The user guide, bundled for Help › User Guide (ADR 0069). The web build serves it as pages instead. anicraft-guide.workspace = true +# The live control port and the tools it serves (ADR 0070): the same dispatcher as the +# headless MCP server, so live and headless never drift. +anicraft-cli = { path = "crates/cli" } craft-update = { git = "https://github.com/storytold/craft-libs", rev = "6ac2a6a34ae83fc0f0bfb25a569ba6388b72266a" } eframe = { workspace = true, features = ["links"] } diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 621e7b3f..4d3a2546 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "anicraft-cli" -description = "AniCraft L4: headless CLI and JSON-lines control channel for agents and pipelines" +description = "AniCraft L4: headless CLI, MCP server and the desktop app's live control channel" version.workspace = true edition.workspace = true license.workspace = true @@ -21,6 +21,9 @@ anicraft-render.workspace = true anicraft-geom.workspace = true anicraft-guide.workspace = true serde_json.workspace = true +# The live control port's per-run token (ADR 0070): the operating system's random numbers. +# MIT OR Apache-2.0, already in the tree. +getrandom = "0.3" [lints] workspace = true diff --git a/crates/cli/src/control.rs b/crates/cli/src/control.rs new file mode 100644 index 00000000..adb1d256 --- /dev/null +++ b/crates/cli/src/control.rs @@ -0,0 +1,493 @@ +//! The live control channel (ADR 0070, `docs/control-protocol.md`): the desktop app's control +//! port, and the client `anicraft-cli mcp --bridge ` uses to reach it. +//! +//! The app listens on `127.0.0.1` only. Each connection carries one JSON object per line each +//! way, answered in order. Every request carries the run's token, which the app writes to +//! `control.json` in the AniCraft settings folder, so a client running as the same user finds it +//! with no setup. The tools are the MCP server's ([`crate::mcp::tools`], [`crate::mcp::call_tool`]), +//! so live and headless never drift. +//! +//! Nothing here touches the window: [`listen`] hands each tool call to whoever drains +//! [`Server::try_recv`] (the app's frame loop), with a channel for the answer. + +use crate::mcp; +use serde_json::{Value, json}; +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener, TcpStream}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel}; +use std::time::{Duration, Instant}; + +/// The wire protocol's version, reported by `hello`. +pub const PROTOCOL: u32 = 1; +/// The port AniCraft's documentation and shortcuts use (VectorCraft 7979, CadCraft 7980, +/// FilmCraft 9876, EffectCraft 9877). +pub const DEFAULT_PORT: u16 = 9878; +/// Longest request or reply line, in bytes. +pub const MAX_LINE: usize = 4 * 1024 * 1024; +/// Most connections open at once. +pub const MAX_CONNECTIONS: usize = 16; +/// How long a tool call may wait for the app (a frame, or the end of the person's drag). +pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(60); +/// Extra time the connection waits past the deadline: a call that started just before it +/// still gets its real answer. +const GRACE: Duration = Duration::from_secs(10); +/// Overrides the generated token on both sides (CI, power users). +pub const TOKEN_ENV: &str = "ANICRAFT_CONTROL_TOKEN"; +/// The port when `--control` isn't given. +pub const PORT_ENV: &str = "ANICRAFT_CONTROL_PORT"; +/// The file the app writes in the settings folder while its control port is open. +pub const CONTROL_FILE: &str = "control.json"; + +/// AniCraft's settings folder: %APPDATA%\AniCraft, ~/Library/Application Support/AniCraft, or +/// $XDG_CONFIG_HOME/anicraft (default ~/.config/anicraft). The shell's `platform::config_dir` +/// owns this rule; a shell test keeps the two the same (this crate can't use the shell). +pub fn settings_dir() -> Option { + let env = |k: &str| std::env::var_os(k).filter(|v| !v.is_empty()).map(PathBuf::from); + if cfg!(windows) { + env("APPDATA").map(|p| p.join("AniCraft")) + } else if cfg!(target_os = "macos") { + env("HOME").map(|p| p.join("Library").join("Application Support").join("AniCraft")) + } else { + env("XDG_CONFIG_HOME").or_else(|| env("HOME").map(|h| h.join(".config"))).map(|p| p.join("anicraft")) + } +} + +/// Where `control.json` lives. +pub fn control_file() -> Option { + settings_dir().map(|d| d.join(CONTROL_FILE)) +} + +/// `ANICRAFT_CONTROL_TOKEN`, when set and not blank. +pub fn token_from_env() -> Option { + std::env::var(TOKEN_ENV).ok().map(|t| t.trim().to_string()).filter(|t| !t.is_empty()) +} + +/// A fresh token: 32 random bytes from the operating system, as 64 hex digits. +pub fn new_token() -> Result { + let mut bytes = [0u8; 32]; + getrandom::fill(&mut bytes).map_err(|e| format!("no random numbers from the system: {e}"))?; + Ok(bytes.iter().map(|b| format!("{b:02x}")).collect()) +} + +/// Reads a port: a number from 1 to 65535. +pub fn parse_port(s: &str) -> Result { + match s.trim().parse::() { + Ok(p) if p > 0 => Ok(p), + _ => Err(format!("'{s}' is not a port: use a number from 1 to 65535, such as {DEFAULT_PORT}")), + } +} + +/// What `control.json` holds. +#[derive(Clone, Debug, PartialEq)] +pub struct ControlFile { + pub port: u16, + pub token: String, + pub pid: u32, + pub version: String, +} + +impl ControlFile { + pub fn to_json(&self) -> Value { + json!({"port": self.port, "token": self.token, "pid": self.pid, "version": self.version}) + } + pub fn parse(text: &str) -> Result { + let v: Value = serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|e| format!("{CONTROL_FILE} is not JSON: {e}"))?; + let token = v.get("token").and_then(Value::as_str).filter(|t| !t.is_empty()).ok_or_else(|| format!("{CONTROL_FILE} has no token"))?; + let port = v.get("port").and_then(Value::as_u64).and_then(|p| u16::try_from(p).ok()).ok_or_else(|| format!("{CONTROL_FILE} has no port"))?; + let pid = v.get("pid").and_then(Value::as_u64).and_then(|p| u32::try_from(p).ok()).unwrap_or(0); + let version = v.get("version").and_then(Value::as_str).unwrap_or("").to_string(); + Ok(ControlFile { port, token: token.to_string(), pid, version }) + } +} + +/// Why a line could not be read. +#[derive(Debug)] +pub enum LineError { + TooLong, + NotText, + Io(std::io::Error), +} + +/// Reads one line (without its line break), at most `limit` bytes; `Ok(None)` at the end. +pub fn read_line(r: &mut R, limit: usize) -> Result, LineError> { + let mut buf = Vec::new(); + let cap = u64::try_from(limit).unwrap_or(u64::MAX).saturating_add(1); + let n = r.by_ref().take(cap).read_until(b'\n', &mut buf).map_err(LineError::Io)?; + if n == 0 { + return Ok(None); + } + if buf.last() == Some(&b'\n') { + buf.pop(); + } else if buf.len() > limit { + return Err(LineError::TooLong); + } + if buf.len() > limit { + return Err(LineError::TooLong); + } + if buf.last() == Some(&b'\r') { + buf.pop(); + } + String::from_utf8(buf).map(Some).map_err(|_| LineError::NotText) +} + +/// One request off the wire. +#[derive(Debug, PartialEq)] +pub struct Incoming { + pub id: Value, + pub token: Option, + pub method: String, + pub params: Value, +} + +/// Reads a request line: a JSON object with a string `method`. Anything else (an HTTP request +/// line, which is how a web page's `fetch` to localhost begins, included) is refused. +pub fn parse_request(line: &str) -> Result { + let v: Value = serde_json::from_str(line.trim_start_matches('\u{feff}')).map_err(|_| "expected one JSON object per line, such as {\"id\":1,\"token\":\"…\",\"method\":\"hello\"}".to_string())?; + let Value::Object(mut o) = v else { return Err("expected a JSON object".into()) }; + let method = match o.remove("method") { + Some(Value::String(m)) => m, + _ => return Err("the request needs a string \"method\"".into()), + }; + let token = match o.remove("token") { + Some(Value::String(t)) => Some(t), + _ => None, + }; + Ok(Incoming { id: o.remove("id").unwrap_or(Value::Null), token, method, params: o.remove("params").unwrap_or_else(|| json!({})) }) +} + +/// Compares tokens in time that doesn't depend on where they differ. +pub fn token_matches(given: Option<&str>, expected: &str) -> bool { + let Some(given) = given else { return false }; + let (a, b) = (given.as_bytes(), expected.as_bytes()); + a.len() == b.len() && !b.is_empty() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + +fn ok(id: &Value, result: Value) -> Value { + json!({"id": id, "ok": true, "result": result}) +} + +fn fail(id: &Value, error: impl Into) -> Value { + json!({"id": id, "ok": false, "error": error.into()}) +} + +/// The message when a tool call never got its turn. +pub const BUSY: &str = "AniCraft was busy for 60 s (an edit in progress in the window, such as a drag, typing or a plug-in dialog), so this call was not run. Try again."; + +/// A tool call waiting for the app's frame loop. +pub struct Request { + pub name: String, + pub arguments: Value, + deadline: Instant, + reply: Sender>, +} + +impl Request { + /// Whether it can change the document (and so waits for the person's own gesture to end). + pub fn changes_document(&self) -> bool { + mcp::tool_changes_document(&self.name) + } + /// Past its deadline: it must not run any more (the client was told it didn't). + pub fn expired(&self) -> bool { + Instant::now() >= self.deadline + } + /// Runs it on `host` and sends the answer; an expired request is refused instead. + pub fn run(self, host: &mut H) { + let result = if self.expired() { Err(BUSY.to_string()) } else { mcp::call_tool(host, &self.name, &self.arguments) }; + let _ = self.reply.send(result); + } + /// Answers without running (the app is closing). + pub fn refuse(self, why: &str) { + let _ = self.reply.send(Err(why.to_string())); + } +} + +/// Wakes the app's frame loop (`egui::Context::request_repaint`), from any thread. +pub type Wake = Arc; + +/// An open control port. +pub struct Server { + pub port: u16, + rx: Receiver, +} + +impl Server { + /// The next waiting tool call, if any. + pub fn try_recv(&self) -> Option { + self.rx.try_recv().ok() + } +} + +/// Opens the control port on `127.0.0.1:port`. Tool calls arrive through [`Server::try_recv`]; +/// `wake` is called whenever one is waiting. +pub fn listen(port: u16, token: String, wake: Wake) -> std::io::Result { + let listener = TcpListener::bind(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port))?; + let port = listener.local_addr()?.port(); + let (tx, rx) = channel(); + let token: Arc = token.into(); + std::thread::Builder::new().name("anicraft-control".into()).spawn(move || accept_loop(&listener, &token, &tx, &wake))?; + Ok(Server { port, rx }) +} + +fn accept_loop(listener: &TcpListener, token: &Arc, tx: &Sender, wake: &Wake) { + let active = Arc::new(AtomicUsize::new(0)); + for stream in listener.incoming() { + let Ok(mut stream) = stream else { continue }; + let _ = stream.set_write_timeout(Some(Duration::from_secs(10))); + if active.fetch_add(1, Ordering::SeqCst) >= MAX_CONNECTIONS { + active.fetch_sub(1, Ordering::SeqCst); + let _ = writeln!(stream, "{}", fail(&Value::Null, format!("too many connections (at most {MAX_CONNECTIONS})"))); + continue; + } + let (token, tx, wake, active2) = (token.clone(), tx.clone(), wake.clone(), active.clone()); + let spawned = std::thread::Builder::new().name("anicraft-control-conn".into()).spawn(move || { + serve_connection(stream, &token, &tx, &wake); + active2.fetch_sub(1, Ordering::SeqCst); + }); + if spawned.is_err() { + active.fetch_sub(1, Ordering::SeqCst); + } + } +} + +/// One connection: requests in order, until the client leaves or sends something it shouldn't. +fn serve_connection(stream: TcpStream, token: &str, tx: &Sender, wake: &Wake) { + let Ok(read_half) = stream.try_clone() else { return }; + let mut reader = BufReader::new(read_half); + let mut out = stream; + loop { + let line = match read_line(&mut reader, MAX_LINE) { + Ok(Some(l)) => l, + Ok(None) | Err(LineError::Io(_)) => return, + Err(LineError::TooLong) => { + let _ = writeln!(out, "{}", fail(&Value::Null, format!("request longer than {} MiB", MAX_LINE / (1024 * 1024)))); + return; + } + Err(LineError::NotText) => { + let _ = writeln!(out, "{}", fail(&Value::Null, "the request is not UTF-8 text")); + return; + } + }; + if line.trim().is_empty() { + continue; + } + let (reply, keep_open) = answer(&line, token, tx, wake); + if writeln!(out, "{reply}").and_then(|()| out.flush()).is_err() || !keep_open { + return; + } + } +} + +/// The reply to one request line, and whether the connection stays open. +fn answer(line: &str, token: &str, tx: &Sender, wake: &Wake) -> (Value, bool) { + let req = match parse_request(line) { + Ok(r) => r, + Err(e) => return (fail(&Value::Null, e), false), + }; + if !token_matches(req.token.as_deref(), token) { + let why = if req.token.is_none() { "missing token" } else { "wrong token" }; + return (fail(&req.id, format!("{why}: send the \"token\" from {CONTROL_FILE} in AniCraft's settings folder (or {TOKEN_ENV})")), false); + } + let id = &req.id; + match req.method.as_str() { + "hello" => (ok(id, json!({"app": "AniCraft", "version": env!("CARGO_PKG_VERSION"), "protocol": PROTOCOL})), true), + "tools.list" => (ok(id, mcp::tools()), true), + "tools.call" => { + let Some(name) = req.params.get("name").and_then(Value::as_str) else { return (fail(id, "tools.call needs a tool \"name\" in params"), true) }; + let arguments = req.params.get("arguments").cloned().unwrap_or_else(|| json!({})); + let (reply, rx) = channel(); + let request = Request { name: name.to_string(), arguments, deadline: Instant::now() + REQUEST_TIMEOUT, reply }; + if tx.send(request).is_err() { + return (fail(id, "AniCraft is closing"), false); + } + wake(); + match rx.recv_timeout(REQUEST_TIMEOUT + GRACE) { + Ok(Ok(result)) => (ok(id, result), true), + Ok(Err(e)) => (fail(id, e), true), + Err(RecvTimeoutError::Timeout) => (fail(id, "AniCraft didn't answer in time; the call may still have run. Check with anicraft_document before trying again."), true), + Err(RecvTimeoutError::Disconnected) => (fail(id, "AniCraft closed before answering"), false), + } + } + other => (fail(id, format!("unknown method '{other}' (hello, tools.list, tools.call)")), true), + } +} + +// ----- the client: `anicraft-cli mcp --bridge` ------------------------------------------------- + +/// Reads `--bridge`'s value: a port, or `127.0.0.1:port` / `localhost:port`. Other hosts are +/// refused: the control port is for this computer only. +pub fn parse_bridge_target(s: &str) -> Result { + let s = s.trim(); + let (host, port) = match s.rsplit_once(':') { + Some((h, p)) => (h, p), + None => ("127.0.0.1", s), + }; + if !matches!(host, "127.0.0.1" | "localhost") { + return Err(format!("--bridge connects to this computer only: give a port, or 127.0.0.1: (not {host})")); + } + Ok(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, parse_port(port)?))) +} + +/// The token to send: `ANICRAFT_CONTROL_TOKEN` when set, else the one in `control.json`. +pub fn find_token(env: Option, file: Option<&Path>) -> Result { + if let Some(t) = env { + return Ok(t); + } + let Some(file) = file else { return Err(not_running(None)) }; + match std::fs::read_to_string(file) { + Ok(text) => ControlFile::parse(&text).map(|c| c.token), + Err(_) => Err(not_running(None)), + } +} + +/// What to tell the person when the app isn't there. +fn not_running(port: Option) -> String { + let port = port.unwrap_or(DEFAULT_PORT); + format!( + "AniCraft isn't open with remote control on. Start it with `anicraft --control {port}` (the \"AniCraft (Claude)\" shortcut), then try again; there is no need to restart the assistant." + ) +} + +/// Why a bridged call failed. +#[derive(Debug, PartialEq)] +pub enum BridgeError { + /// Couldn't reach the app (not running, no token): nothing ran. + NotRunning(String), + /// The connection broke after the request went out: it may have run. + Lost(String), + /// The app refused the call (the headless server's protocol error). + Refused(String), +} + +struct Conn { + reader: BufReader, + writer: TcpStream, +} + +impl Conn { + /// Whether the app is still at the other end (an app that quit leaves the socket closed). + fn alive(&self) -> bool { + if self.writer.set_nonblocking(true).is_err() { + return false; + } + let r = self.writer.peek(&mut [0u8; 1]); + let back = self.writer.set_nonblocking(false).is_ok(); + back && matches!(r, Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock) + } +} + +/// The bridge's link to the app: connected on the first call, again after a break. +pub struct Bridge { + addr: SocketAddr, + conn: Option, + next_id: u64, + /// Where the token comes from (tests point it elsewhere). + token_file: Option, +} + +impl Bridge { + /// Doesn't connect: the assistant starts its servers when it starts, often before AniCraft. + pub fn new(addr: SocketAddr) -> Bridge { + Bridge { addr, conn: None, next_id: 1, token_file: control_file() } + } + + pub fn with_token_file(addr: SocketAddr, file: Option) -> Bridge { + Bridge { addr, conn: None, next_id: 1, token_file: file } + } + + fn connect(&mut self) -> Result { + let token = find_token(token_from_env(), self.token_file.as_deref()).map_err(BridgeError::NotRunning)?; + if self.conn.as_ref().is_some_and(Conn::alive) { + return Ok(token); + } + self.conn = None; + let stream = TcpStream::connect_timeout(&self.addr, Duration::from_secs(3)).map_err(|_| BridgeError::NotRunning(not_running(Some(self.addr.port()))))?; + let _ = stream.set_nodelay(true); + let _ = stream.set_read_timeout(Some(REQUEST_TIMEOUT + GRACE + Duration::from_secs(5))); + let reader = BufReader::new(stream.try_clone().map_err(|e| BridgeError::NotRunning(e.to_string()))?); + self.conn = Some(Conn { reader, writer: stream }); + Ok(token) + } + + /// One round trip; any transport failure drops the connection. + fn round_trip(&mut self, token: &str, method: &str, params: Value) -> Result { + let id = self.next_id; + self.next_id += 1; + let line = json!({"id": id, "token": token, "method": method, "params": params}).to_string(); + let Some(conn) = self.conn.as_mut() else { return Err(BridgeError::NotRunning(not_running(Some(self.addr.port())))) }; + let sent = writeln!(conn.writer, "{line}").and_then(|()| conn.writer.flush()); + let reply = sent.map_err(|e| e.to_string()).and_then(|()| match read_line(&mut conn.reader, MAX_LINE) { + Ok(Some(l)) => Ok(l), + Ok(None) => Err("AniCraft closed the connection".to_string()), + Err(LineError::Io(e)) => Err(e.to_string()), + Err(_) => Err("unreadable reply".to_string()), + }); + let reply = match reply { + Ok(l) => l, + Err(e) => { + self.conn = None; + return Err(BridgeError::Lost(e)); + } + }; + let v: Value = serde_json::from_str(&reply).map_err(|e| { + self.conn = None; + BridgeError::Lost(format!("unreadable reply: {e}")) + })?; + if v.get("ok").and_then(Value::as_bool) == Some(true) { + return Ok(v.get("result").cloned().unwrap_or(Value::Null)); + } + let error = v.get("error").and_then(Value::as_str).unwrap_or("AniCraft refused the request").to_string(); + if v.get("id").is_some_and(Value::is_null) || error.starts_with("missing token") || error.starts_with("wrong token") { + // The app closes the connection after these (an old token: AniCraft was restarted + // and control.json has the new one by the next call). + self.conn = None; + } + Err(BridgeError::Refused(error)) + } + + /// Runs a tool in the app. An edit whose answer was lost is never sent again (the app may + /// have made it); a call that only reads is tried once more on a new connection. + pub fn call_tool(&mut self, name: &str, args: &Value) -> Result { + let retries = if mcp::tool_changes_document(name) { 0 } else { 1 }; + let mut attempt = 0; + loop { + let token = self.connect()?; + match self.round_trip(&token, "tools.call", json!({"name": name, "arguments": args})) { + Err(BridgeError::Lost(_)) if attempt < retries => attempt += 1, + Err(BridgeError::Refused(e)) if e.starts_with("wrong token") && attempt < 1 => attempt += 1, + other => return other, + } + } + } +} + +/// The bridge's instructions: the same tools, acting on the person's open window. +pub const BRIDGE_INSTRUCTIONS: &str = "AniCraft is a 2D animation studio, and these tools act on the AniCraft window the person \ +has open: every edit appears there immediately and can be undone with Ctrl+Z (or edit.undo). Every edit is a command: call \ +anicraft_commands to find one (filter by words such as 'tween' or 'export'), then anicraft_run with its id and params, or \ +anicraft_run_script for several in order. Frames in params are 0-based. Commands act on the current scene, layer, frame and \ +selection, which anicraft_document reports (the person may change them between your calls). Use anicraft_render to see a \ +frame. Commands that would lose work or replace a file refuse until params include \"confirm\": true; ask the person before \ +confirming. If AniCraft isn't open with remote control on, the tools say how to start it."; + +impl mcp::Backend for Bridge { + fn instructions(&self) -> &'static str { + BRIDGE_INSTRUCTIONS + } + fn call(&mut self, name: &str, args: &Value) -> Result { + match self.call_tool(name, args) { + Ok(v) => Ok(v), + Err(BridgeError::Refused(e)) => Err(e), + Err(BridgeError::NotRunning(e)) => Ok(mcp::text_result(&Value::String(e), true)), + Err(BridgeError::Lost(e)) => { + let what = if mcp::tool_changes_document(name) { " It may have been made: check with anicraft_document before trying again." } else { "" }; + Ok(mcp::text_result(&Value::String(format!("The connection to AniCraft broke ({e}).{what}")), true)) + } + } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/cli/src/control/tests.rs b/crates/cli/src/control/tests.rs new file mode 100644 index 00000000..1c136fc6 --- /dev/null +++ b/crates/cli/src/control/tests.rs @@ -0,0 +1,253 @@ +use super::*; +use crate::mcp::Backend; +use anicraft_engine::Session; +use std::sync::atomic::AtomicBool; + +const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + +/// A control port on a free port, with a stand-in for the app's frame loop running each call on +/// its own session (as `App::poll_remote` does). Stops when dropped. +struct App { + port: u16, + stop: Arc, + loop_thread: Option>, +} + +impl App { + fn start(session: Session) -> App { + let server = listen(0, TOKEN.into(), Arc::new(|| {})).unwrap(); + let port = server.port; + let stop = Arc::new(AtomicBool::new(false)); + let stop2 = stop.clone(); + let loop_thread = std::thread::spawn(move || { + let mut s = session; + while !stop2.load(Ordering::SeqCst) { + while let Some(r) = server.try_recv() { + r.run(&mut s); + } + std::thread::sleep(Duration::from_millis(2)); + } + s + }); + App { port, stop, loop_thread: Some(loop_thread) } + } + + fn session(mut self) -> Session { + self.stop.store(true, Ordering::SeqCst); + self.loop_thread.take().unwrap().join().unwrap() + } + + fn connect(&self) -> (BufReader, TcpStream) { + let s = TcpStream::connect(("127.0.0.1", self.port)).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(20))).unwrap(); + (BufReader::new(s.try_clone().unwrap()), s) + } +} + +impl Drop for App { + fn drop(&mut self) { + self.stop.store(true, Ordering::SeqCst); + } +} + +fn send(conn: &mut (BufReader, TcpStream), line: &str) -> Value { + writeln!(conn.1, "{line}").unwrap(); + serde_json::from_str(&read_line(&mut conn.0, MAX_LINE).unwrap().unwrap()).unwrap() +} + +/// The app closed the connection: nothing more to read. +fn closed(conn: &mut (BufReader, TcpStream)) -> bool { + matches!(read_line(&mut conn.0, MAX_LINE), Ok(None) | Err(LineError::Io(_))) +} + +#[test] +fn requests_are_json_objects_with_a_string_method() { + let r = parse_request(r#"{"id":3,"token":"t","method":"hello"}"#).unwrap(); + assert_eq!((r.id, r.token.as_deref(), r.method.as_str(), r.params), (json!(3), Some("t"), "hello", json!({}))); + // A web page's fetch to localhost starts with an HTTP request line: refused. + assert!(parse_request("GET / HTTP/1.1").is_err()); + assert!(parse_request("POST /tools HTTP/1.1").is_err()); + assert!(parse_request("[1,2]").is_err()); + assert!(parse_request(r#"{"id":1}"#).is_err(), "no method"); + assert!(parse_request(r#"{"id":1,"method":7}"#).is_err(), "method must be a string"); +} + +#[test] +fn tokens_must_match_exactly() { + assert!(token_matches(Some(TOKEN), TOKEN)); + assert!(!token_matches(None, TOKEN)); + assert!(!token_matches(Some(""), ""), "an empty token never opens the port"); + assert!(!token_matches(Some(&TOKEN[..63]), TOKEN)); + assert!(!token_matches(Some(&TOKEN.replace('f', "e")), TOKEN)); + let t = new_token().unwrap(); + assert_eq!(t.len(), 64); + assert!(t.bytes().all(|b| b.is_ascii_hexdigit())); + assert_ne!(t, new_token().unwrap(), "fresh each time"); +} + +#[test] +fn lines_are_capped() { + let mut r = &b"one\r\ntwo\nthree"[..]; + assert_eq!(read_line(&mut r, 10).unwrap().as_deref(), Some("one")); + assert_eq!(read_line(&mut r, 10).unwrap().as_deref(), Some("two")); + assert_eq!(read_line(&mut r, 10).unwrap().as_deref(), Some("three")); + assert!(read_line(&mut r, 10).unwrap().is_none()); + let mut exact = &b"0123456789\n"[..]; + assert_eq!(read_line(&mut exact, 10).unwrap().as_deref(), Some("0123456789")); + let mut long = &b"0123456789A\n"[..]; + assert!(matches!(read_line(&mut long, 10), Err(LineError::TooLong))); +} + +#[test] +fn ports_and_bridge_targets() { + assert_eq!(parse_port("9878"), Ok(9878)); + assert!(parse_port("0").is_err()); + assert!(parse_port("70000").is_err()); + assert!(parse_port("port").is_err()); + let local = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 9878)); + assert_eq!(parse_bridge_target("9878"), Ok(local)); + assert_eq!(parse_bridge_target("127.0.0.1:9878"), Ok(local)); + assert_eq!(parse_bridge_target("localhost:9878"), Ok(local)); + assert!(parse_bridge_target("192.168.1.5:9878").is_err(), "this computer only"); + assert!(parse_bridge_target("example.com:9878").is_err()); +} + +#[test] +fn the_control_file_round_trips() { + let c = ControlFile { port: 9878, token: TOKEN.into(), pid: 42, version: "0.2.1".into() }; + assert_eq!(ControlFile::parse(&c.to_json().to_string()), Ok(c)); + assert!(ControlFile::parse("{}").is_err()); + assert!(ControlFile::parse("nonsense").is_err()); +} + +#[test] +fn the_token_comes_from_the_environment_then_the_control_file() { + let dir = std::env::temp_dir().join(format!("anicraft-control-token-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join(CONTROL_FILE); + std::fs::write(&file, ControlFile { port: 9878, token: "from-file".into(), pid: 1, version: String::new() }.to_json().to_string()).unwrap(); + assert_eq!(find_token(Some("from-env".into()), Some(&file)), Ok("from-env".into()), "the environment wins"); + assert_eq!(find_token(None, Some(&file)), Ok("from-file".into())); + let missing = find_token(None, Some(&dir.join("gone.json"))).unwrap_err(); + assert!(missing.contains("anicraft --control"), "{missing}"); + assert!(find_token(None, None).is_err()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_missing_or_wrong_token_is_refused_and_the_connection_closed() { + let app = App::start(Session::default()); + let mut c = app.connect(); + let r = send(&mut c, r#"{"id":1,"method":"tools.call","params":{"name":"anicraft_run","arguments":{"command":"draw.rect","params":{"x":0,"y":0,"w":5,"h":5}}}}"#); + assert_eq!(r["ok"], false); + assert!(r["error"].as_str().unwrap().starts_with("missing token"), "{r}"); + assert!(closed(&mut c)); + let mut c = app.connect(); + let r = send(&mut c, &json!({"id": 2, "token": "nope", "method": "tools.call", "params": {"name": "anicraft_run", "arguments": {"command": "draw.rect", "params": {"x": 0, "y": 0, "w": 5, "h": 5}}}}).to_string()); + assert!(r["error"].as_str().unwrap().starts_with("wrong token"), "{r}"); + assert!(closed(&mut c)); + assert!(app.session().visible_elements().is_empty(), "nothing ran"); +} + +#[test] +fn http_and_oversized_lines_are_refused_and_the_connection_closed() { + let app = App::start(Session::default()); + let mut c = app.connect(); + let r = send(&mut c, "GET / HTTP/1.1\r\nHost: 127.0.0.1\r\n"); + assert_eq!((r["ok"].clone(), r["id"].clone()), (json!(false), Value::Null)); + assert!(closed(&mut c)); + let mut c = app.connect(); + let big = format!(r#"{{"id":1,"token":"{TOKEN}","method":"hello","pad":"{}"}}"#, "x".repeat(MAX_LINE)); + // The app stops reading at the limit and answers; the rest of the write may fail. + let _ = c.1.write_all(big.as_bytes()); + let _ = c.1.write_all(b"\n"); + let reply: Value = serde_json::from_str(&read_line(&mut c.0, MAX_LINE).unwrap().unwrap()).unwrap(); + assert!(reply["error"].as_str().unwrap().contains("longer than 4 MiB"), "{reply}"); + assert!(closed(&mut c)); +} + +#[test] +fn a_call_through_the_port_matches_the_headless_server() { + let app = App::start(Session::default()); + let mut c = app.connect(); + let hello = send(&mut c, &json!({"id": 1, "token": TOKEN, "method": "hello"}).to_string()); + assert_eq!(hello, json!({"id": 1, "ok": true, "result": {"app": "AniCraft", "version": env!("CARGO_PKG_VERSION"), "protocol": PROTOCOL}})); + let list = send(&mut c, &json!({"id": 2, "token": TOKEN, "method": "tools.list"}).to_string()); + assert_eq!(list["result"], mcp::tools()); + let args = json!({"command": "draw.rect", "params": {"x": 10, "y": 10, "w": 50, "h": 40, "fill": "#ff0000"}}); + let live = send(&mut c, &json!({"id": 3, "token": TOKEN, "method": "tools.call", "params": {"name": "anicraft_run", "arguments": args}}).to_string()); + assert_eq!(live["ok"], true, "{live}"); + let mut headless = Session::default(); + assert_eq!(live["result"], mcp::call_tool(&mut headless, "anicraft_run", &args).unwrap(), "the same dispatcher, the same answer"); + // A protocol error in headless mode is an error reply here; the connection stays usable. + let bad = send(&mut c, &json!({"id": 4, "token": TOKEN, "method": "tools.call", "params": {"name": "nope"}}).to_string()); + assert_eq!((bad["ok"].clone(), bad["error"].clone()), (json!(false), json!("unknown tool 'nope'"))); + let unknown = send(&mut c, &json!({"id": 5, "token": TOKEN, "method": "frobnicate"}).to_string()); + assert_eq!(unknown["ok"], false); + let doc = send(&mut c, &json!({"id": 6, "token": TOKEN, "method": "tools.call", "params": {"name": "anicraft_document"}}).to_string()); + // `state` numbers saved states across every session in the process, so it differs. + let described = |r: &Value| { + let mut v: Value = serde_json::from_str(r["content"][0]["text"].as_str().unwrap()).unwrap(); + v.as_object_mut().unwrap().remove("state"); + v + }; + assert_eq!(described(&doc["result"]), described(&mcp::call_tool(&mut headless, "anicraft_document", &json!({})).unwrap())); + let s = app.session(); + assert_eq!(s.visible_elements().len(), 1); + assert!(s.doc == headless.doc); +} + +#[test] +fn a_call_that_waited_past_its_deadline_does_not_run() { + let (reply, answer) = channel(); + let r = Request { name: "anicraft_run".into(), arguments: json!({"command": "draw.rect", "params": {"x": 0, "y": 0, "w": 5, "h": 5}}), deadline: Instant::now(), reply }; + assert!(r.expired() && r.changes_document()); + let mut s = Session::default(); + r.run(&mut s); + assert_eq!(answer.recv().unwrap(), Err(BUSY.to_string())); + assert!(s.visible_elements().is_empty()); +} + +fn free_port() -> u16 { + TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port() +} + +#[test] +fn the_bridge_starts_without_the_app_and_says_how_to_start_it() { + let addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, free_port())); + let dir = std::env::temp_dir().join(format!("anicraft-bridge-none-{}", std::process::id())); + let mut b = Bridge::with_token_file(addr, Some(dir.join(CONTROL_FILE))); + // The handshake and the tool list need no app. + let init = mcp::handle(&mut b, r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}"#).unwrap(); + assert!(init["result"]["instructions"].as_str().unwrap().contains("open")); + let list = mcp::handle(&mut b, r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#).unwrap(); + assert_eq!(list["result"]["tools"], mcp::tools()); + let r = mcp::handle(&mut b, r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"anicraft_document"}}"#).unwrap(); + assert_eq!(r["result"]["isError"], true); + assert!(r["result"]["content"][0]["text"].as_str().unwrap().contains("anicraft --control"), "{r}"); + // A token file but no app listening: the same advice. + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join(CONTROL_FILE), ControlFile { port: addr.port(), token: TOKEN.into(), pid: 1, version: String::new() }.to_json().to_string()).unwrap(); + assert!(matches!(b.call_tool("anicraft_document", &json!({})), Err(BridgeError::NotRunning(_)))); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_bridge_drives_the_app_and_says_when_it_has_gone() { + let dir = std::env::temp_dir().join(format!("anicraft-bridge-live-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join(CONTROL_FILE); + let app = App::start(Session::default()); + std::fs::write(&file, ControlFile { port: app.port, token: TOKEN.into(), pid: 1, version: String::new() }.to_json().to_string()).unwrap(); + let addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, app.port)); + let mut b = Bridge::with_token_file(addr, Some(file.clone())); + let r = b.call("anicraft_run", &json!({"command": "draw.rect", "params": {"x": 0, "y": 0, "w": 9, "h": 9}})).unwrap(); + assert_eq!(r["isError"], false, "{r}"); + assert_eq!(b.call("anicraft_document", &json!({})).unwrap()["isError"], false); + assert_eq!(app.session().visible_elements().len(), 1, "the edit landed in the app's session"); + // The app's frame loop is gone: the call fails (as an error the assistant reads), never + // silently. + let r = b.call("anicraft_run", &json!({"command": "draw.rect", "params": {"x": 0, "y": 0, "w": 9, "h": 9}})); + assert!(r.as_ref().map_or(true, |v| v["isError"] == true), "{r:?}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index cb9ef155..7f8c6706 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -2,6 +2,7 @@ //! server (`mcp`). Every operation goes through the engine's command registry. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod control; pub mod mcp; use anicraft_engine::{Session, commands, format}; @@ -33,6 +34,9 @@ USAGE: {\"id\":1,\"cmd\":\"draw.rect\",\"params\":{\"x\":10,\"y\":10,\"w\":50,\"h\":50}} anicraft-cli mcp [file|--sample] Model Context Protocol server on stdin/stdout, for AI assistants (see docs/mcp.md) + anicraft-cli mcp --bridge the same tools, acting live on the AniCraft window + started with `anicraft --control ` + (docs/control-protocol.md) anicraft-cli --version --plugins loads the WebAssembly plug-ins in a folder first (also the @@ -241,6 +245,16 @@ pub fn run(argv: &[String]) -> Result { Ok(String::new()) } "mcp" => { + if let Some(target) = a.flag("bridge") { + if src.is_some() || a.flag("plugins").is_some() { + return Err("mcp --bridge acts on the open AniCraft window: it takes no file or --plugins".into()); + } + let mut b = control::Bridge::new(control::parse_bridge_target(target)?); + let stdin = std::io::stdin(); + let mut stdout = std::io::stdout(); + mcp::serve(&mut b, stdin.lock(), &mut stdout).map_err(|e| e.to_string())?; + return Ok(String::new()); + } let mut s = session(&a, src)?; let stdin = std::io::stdin(); let mut stdout = std::io::stdout(); diff --git a/crates/cli/src/mcp.rs b/crates/cli/src/mcp.rs index 44e3543e..809922e0 100644 --- a/crates/cli/src/mcp.rs +++ b/crates/cli/src/mcp.rs @@ -6,6 +6,10 @@ //! frame as a picture. Everything still goes through `Session::execute`, so undo, validation //! and the confirmation tiers (ADR 0004: `"confirm": true` before irreversible loss) apply to //! an assistant exactly as to the app. +//! +//! The same tools drive the desktop app live (ADR 0070): the app runs [`call_tool`] on its own +//! session for requests from its control port, and `anicraft-cli mcp --bridge ` is this +//! server with a [`Backend`] that forwards each tool call there (`crate::control`). use anicraft_engine::{Session, commands}; use serde_json::{Value, json}; @@ -20,7 +24,8 @@ const MAX_PICTURE_EDGE: f32 = 2048.0; /// Most steps in one `anicraft_run_script` call. const MAX_STEPS: usize = 10_000; -const INSTRUCTIONS: &str = "AniCraft is a 2D animation studio. Every edit is a command: call \ +/// The headless server's instructions (an in-process document no one sees). +pub const INSTRUCTIONS: &str = "AniCraft is a 2D animation studio. Every edit is a command: call \ anicraft_commands to find one (filter by words such as 'tween' or 'export'), then anicraft_run \ with its id and params, or anicraft_run_script for several in order. Frames in params are \ 0-based. Commands act on the current scene, layer, frame and selection, which anicraft_document \ @@ -28,7 +33,8 @@ reports. Use anicraft_render to see a frame. Edits can be undone with edit.undo. would lose work or replace a file refuse until params include \"confirm\": true; ask the person \ before confirming."; -fn tools() -> Value { +/// The tools, as `tools/list` returns them. The desktop app's control port lists the same. +pub fn tools() -> Value { json!([ { "name": "anicraft_commands", @@ -95,21 +101,46 @@ fn error(id: Value, code: i64, message: impl Into) -> Value { json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message.into()}}) } -fn text_result(v: &Value, is_error: bool) -> Value { +/// A tool result holding `v` as text (pretty JSON unless it is a string). +pub fn text_result(v: &Value, is_error: bool) -> Value { let text = if let Value::String(s) = v { s.clone() } else { serde_json::to_string_pretty(v).unwrap_or_default() }; json!({"content": [{"type": "text", "text": text}], "isError": is_error}) } +/// Where tools run: a session, and how a command runs on it. The headless server uses the +/// [`Session`] itself; the desktop app runs commands through its own follow-up (the status +/// line, the view a new document resets), as for the person's own edits. +pub trait Host { + fn session(&self) -> &Session; + /// Runs one command; the error is the engine's message. + fn execute(&mut self, id: &str, params: &Value) -> Result; +} + +impl Host for Session { + fn session(&self) -> &Session { + self + } + fn execute(&mut self, id: &str, params: &Value) -> Result { + Session::execute(self, id, params).map_err(|e| e.to_string()) + } +} + +/// Whether a tool can change the document (the app holds these back while the person is in +/// the middle of a drag or typing, so the two edits never share an undo step). +pub fn tool_changes_document(name: &str) -> bool { + !matches!(name, "anicraft_commands" | "anicraft_document" | "anicraft_render") +} + /// Runs one tool. Tool failures are results with `isError` (so the assistant can read and /// correct them); only malformed calls are protocol errors. -fn call_tool(s: &mut Session, name: &str, args: &Value) -> Result { - let run = |s: &mut Session, step: &Value| -> Result { +pub fn call_tool(h: &mut H, name: &str, args: &Value) -> Result { + let run = |h: &mut H, step: &Value| -> Result { let id = step.get("command").and_then(Value::as_str).ok_or("missing \"command\"")?; let params = step.get("params").cloned().unwrap_or_else(|| json!({})); if !params.is_object() { return Err(format!("{id}: \"params\" must be an object")); } - s.execute(id, ¶ms).map_err(|e| format!("{id}: {e}")) + h.execute(id, ¶ms).map_err(|e| format!("{id}: {e}")) }; Ok(match name { "anicraft_commands" => { @@ -125,8 +156,11 @@ fn call_tool(s: &mut Session, name: &str, args: &Value) -> Result .collect(); text_result(&Value::Array(list), false) } - "anicraft_run" => match run(s, args) { - Ok(v) => text_result(&json!({"result": v, "revision": s.revision, "frame": s.frame, "scene": s.scene}), false), + "anicraft_run" => match run(h, args) { + Ok(v) => { + let s = h.session(); + text_result(&json!({"result": v, "revision": s.revision, "frame": s.frame, "scene": s.scene}), false) + } Err(e) => text_result(&Value::String(e), true), }, "anicraft_run_script" => { @@ -136,15 +170,17 @@ fn call_tool(s: &mut Session, name: &str, args: &Value) -> Result } let mut results = Vec::with_capacity(steps.len()); for (i, step) in steps.iter().enumerate() { - match run(s, step) { + match run(h, step) { Ok(v) => results.push(v), Err(e) => return Ok(text_result(&json!({"failed_step": i + 1, "error": e, "done": results}), true)), } } + let s = h.session(); text_result(&json!({"results": results, "revision": s.revision, "frame": s.frame}), false) } - "anicraft_document" => text_result(&s.info(), false), + "anicraft_document" => text_result(&h.session().info(), false), "anicraft_render" => { + let s = h.session(); let frame = match args.get("frame") { None | Some(Value::Null) => s.frame, Some(v) => v.as_u64().and_then(|f| u32::try_from(f).ok()).ok_or("\"frame\" must be a whole number from 0")?, @@ -173,8 +209,26 @@ fn call_tool(s: &mut Session, name: &str, args: &Value) -> Result }) } +/// What answers `tools/call`: the in-process session (headless), or the desktop app through +/// its control port (`--bridge`, `crate::control::Bridge`). +pub trait Backend { + /// The `instructions` the server gives the assistant at `initialize`. + fn instructions(&self) -> &'static str; + /// A `tools/call` result, or the message of a protocol error (a malformed call). + fn call(&mut self, name: &str, args: &Value) -> Result; +} + +impl Backend for Session { + fn instructions(&self) -> &'static str { + INSTRUCTIONS + } + fn call(&mut self, name: &str, args: &Value) -> Result { + call_tool(self, name, args) + } +} + /// Answers one JSON-RPC message; `None` for notifications (and responses), which get no reply. -pub fn handle(s: &mut Session, line: &str) -> Option { +pub fn handle(s: &mut B, line: &str) -> Option { let msg: Value = match serde_json::from_str(line.trim_start_matches('\u{feff}')) { Ok(v) => v, Err(e) => return Some(error(Value::Null, -32700, format!("parse error: {e}"))), @@ -198,7 +252,7 @@ pub fn handle(s: &mut Session, line: &str) -> Option { "protocolVersion": version, "capabilities": {"tools": {"listChanged": false}}, "serverInfo": {"name": "anicraft", "title": "AniCraft", "version": env!("CARGO_PKG_VERSION")}, - "instructions": INSTRUCTIONS + "instructions": s.instructions() }) } "ping" => json!({}), @@ -206,7 +260,7 @@ pub fn handle(s: &mut Session, line: &str) -> Option { "tools/call" => { let Some(name) = params.get("name").and_then(Value::as_str) else { return Some(error(id, -32602, "tools/call needs a tool \"name\"")) }; let args = params.get("arguments").cloned().unwrap_or_else(|| json!({})); - match call_tool(s, name, &args) { + match s.call(name, &args) { Ok(v) => v, Err(e) => return Some(error(id, -32602, e)), } @@ -218,7 +272,7 @@ pub fn handle(s: &mut Session, line: &str) -> Option { /// The stdio loop: one message per line in, one reply per line out, until stdin closes. /// Nothing but protocol messages is written to `out` (logs would corrupt the stream). -pub fn serve(s: &mut Session, input: R, out: &mut W) -> std::io::Result<()> { +pub fn serve(s: &mut B, input: R, out: &mut W) -> std::io::Result<()> { for line in input.lines() { let line = line?; if line.trim().is_empty() { diff --git a/docs/adr/0070-live-control-port.md b/docs/adr/0070-live-control-port.md new file mode 100644 index 00000000..44637065 --- /dev/null +++ b/docs/adr/0070-live-control-port.md @@ -0,0 +1,99 @@ +# ADR 0070: A live control port, so assistants edit the open window + +* Status: accepted (2026-11-12) +* Relates to: ADR 0004 (destructive actions), ADR 0005 (typography), ADR 0006 (platforms), + ADR 0040 (interface languages), `docs/mcp.md`, `docs/control-protocol.md` + +## Context + +`anicraft-cli mcp` gives AI assistants the engine's commands as five MCP tools, but it edits a +document inside its own process, with no window. To see the result the person saves, then opens +the file in the app. Every edit is invisible until then, and the assistant and the person can +never work on the same document at once. + +The sister apps (VectorCraft, CadCraft, FilmCraft, EffectCraft) already let an assistant drive the +open window through a TCP port on `127.0.0.1`, with a line-per-message JSON protocol and an MCP +"bridge" that forwards to it. AniCraft should behave the same way. + +One lesson from FilmCraft: its token was an environment variable, which a desktop shortcut's +process received and an MCP server started by the assistant's desktop app did not. Authentication +must not depend on an environment variable reaching two unrelated processes. + +## Decision + +1. **`anicraft --control `** (also `ANICRAFT_CONTROL_PORT`; the flag wins) opens a control + port on `127.0.0.1` only. 9878 is the convention (after EffectCraft's 9877). A bad port is an + error before any window opens. If the port can't be opened (in use), the window opens anyway + and the status bar says why. +2. **The protocol is small** (`docs/control-protocol.md`): one JSON object per line each way, + persistent connections, answered in order. Methods: `hello`, `tools.list`, `tools.call`. + Replies are `{"id", "ok": true, "result"}` or `{"id", "ok": false, "error"}`. +3. **One dispatcher for live and headless.** The app depends on the `anicraft-cli` library and + runs its `mcp::call_tool` and `mcp::tools` on the window's session. `call_tool` is generic over + a small `Host` trait (the session, and how a command runs), so the app runs commands through + its own follow-up (`App::announce`: the status line, the view a new document resets, Open + Recent), as for the person's own edits. + + *Considered:* a new crate for the dispatcher, used by both. It would have to be L4 (it needs + the engine and the renderer), and the CLI (L4) may not depend on a crate in its own layer, so + the CLI would have to move up beside the shell. The shell (L5) depending on the CLI library + (L4) fits the layering as it is, adds no crate, and the CLI library has no dependency the shell + doesn't already have (except `getrandom`, below). The CLI's library already was the MCP server; + it now also holds the control port's protocol, its listener threads and the bridge client + (`crates/cli/src/control.rs`), none of which touches the UI toolkit, so they are tested there. +4. **Threads, and the frame.** One listener thread and one thread per connection (at most 16). A + tool call goes to the UI thread through a channel with a reply sender; the connection thread + wakes the window (`request_repaint`). The frame loop runs waiting calls at the start of the + frame, before anything draws, so their edits show in the same frame (AGENTS.md "edits are + live"). The window never takes focus. An edit made behind the start screen (ADR 0059) + closes it, so the person sees the document change. +5. **The person's own gestures.** An edit from a tool must not join the person's undo step. While + the person is dragging (pointer held, a stage drag, or a plug-in dialog previewing), calls that + can change the document wait (calls that only read don't). A call that waited 60 s is refused + without running, and the client is told so. An open gesture that is only typing (a property + field still focused) is committed first, as its own undo step, as clicking elsewhere would do; + waiting for that could block an assistant indefinitely. + + *Considered:* committing the gesture mid-drag. The rest of the drag would then record one undo + step per frame, so we wait instead. +6. **Authentication: a token file, no setup.** Each run with `--control` makes a fresh 32-byte + token from the operating system's random numbers (`getrandom`, MIT OR Apache-2.0, already in + the tree) and writes `control.json` (`port`, `token`, `pid`, `version`) to the AniCraft settings + folder, owner-only on macOS and Linux (`%APPDATA%` is already private on Windows). It is + replaced at start and removed on exit if it still holds this run's token. Every request carries + the token; a missing or wrong token is refused and the connection closed before anything runs. + `ANICRAFT_CONTROL_TOKEN`, when set, is the token on both sides (CI, power users). + + The CLI can't use the shell's `platform::config_dir`, so it has its own copy of the folder rule + (`control::settings_dir`) and a shell test keeps the two equal. + + *Considered:* no authentication (VectorCraft, CadCraft, EffectCraft). Any local process, and a + web page able to reach localhost, could then edit and save files as the person. *Considered:* + an environment-variable token only (FilmCraft): see Context. +7. **Hardening, as in the sister apps.** Every line must be a JSON object with a string `method`; + anything else gets one error line and the connection closes. That also refuses a web page's + `fetch` to localhost, which starts with an HTTP request line. Lines are capped at 4 MiB. Writes + time out after 10 s so a client that stops reading can't hold a thread. +8. **Safety rules unchanged.** Calls run through `Session::execute`, so `"confirm": true` (ADR 0004) + is needed exactly as headless, unsaved-work guards and crash recovery see the edits as the + person's, and every edit undoes with Ctrl+Z. +9. **`anicraft-cli mcp --bridge `** is the MCP server with a backend that + forwards `tools/call` to the app; `initialize` and `tools/list` are answered locally (the same + tool list), so the server starts and lists its tools before AniCraft is open. It connects on + the first call and returns an error that says how to start the app when it can't. It reconnects + after a break (an app that quit is noticed before the next request is sent). An edit whose reply + was lost is never sent again (the app may have made it); a call that only reads is tried once + more. Hosts other than this computer are refused. +10. **Visible.** While the port is open the status bar says "Remote control on (port N)" (through + `tr!` and `theme::Type`), with a tooltip saying what that means. + +## Consequences + +* The shell now builds the CLI library (small; nothing new for the web build, which leaves the + control port out). +* The tool behaviour can't drift between live and headless: one function serves both, and a test + checks that a call through the port answers as `call_tool` does. +* Remote edits arrive at most once per frame batch; a long `anicraft_run_script` blocks the window + while it runs, as a long menu command would. +* Not yet: a screenshot tool that returns the window itself (the app already captures itself for + `--screenshot`). diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..65918325 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | +| 0070 | feat/live-control | Live control port | diff --git a/docs/control-protocol.md b/docs/control-protocol.md new file mode 100644 index 00000000..5e0fec7f --- /dev/null +++ b/docs/control-protocol.md @@ -0,0 +1,103 @@ +# The live control port + +`anicraft --control ` opens the AniCraft window as usual and also listens on a port on this +computer, so an assistant (or a script) can edit the open document while you watch. Every edit +appears in the window at once and undoes with Ctrl+Z, like your own. The status bar says +"Remote control on (port N)" while it is open. ADR 0070 records the design. + +Most people never speak this protocol themselves: AI assistants reach it through +`anicraft-cli mcp --bridge ` (see `docs/mcp.md`). + +```sh +anicraft --control 9878 # 9878 by convention +ANICRAFT_CONTROL_PORT=9878 anicraft # the same; --control wins over the variable +``` + +## Transport + +* TCP on `127.0.0.1` only. +* One JSON object per line (UTF-8, `\n`; a `\r` before it is ignored), each way. +* Connections stay open; requests on one connection are answered in order. + +## Authentication + +Each run makes a fresh token: 64 hex digits from the operating system's random numbers. The app +writes it to `control.json` in AniCraft's settings folder: + +| System | File | +|---|---| +| Windows | `%APPDATA%\AniCraft\control.json` | +| macOS | `~/Library/Application Support/AniCraft/control.json` | +| Linux | `$XDG_CONFIG_HOME/anicraft/control.json` (default `~/.config/anicraft/`) | + +```json +{"port": 9878, "token": "3f1c…", "pid": 12345, "version": "0.2.1"} +``` + +On macOS and Linux the file is readable only by you; on Windows the settings folder already is. +It is replaced when AniCraft starts with `--control` and removed when it closes. A program running +as you finds the token there, with nothing to copy into its settings. + +If `ANICRAFT_CONTROL_TOKEN` is set, it is the token instead (set it for both the app and the +client: CI, power users). + +Every request carries `"token"`. A missing or wrong token gets an error and the connection +closes before anything runs. + +## Requests and replies + +```json +{"id": 1, "token": "…", "method": "hello"} +{"id": 1, "ok": true, "result": {"app": "AniCraft", "version": "0.2.1", "protocol": 1}} +``` + +`id` is any JSON value and comes back as it was. A reply is `{"id", "ok": true, "result"}` or +`{"id", "ok": false, "error": "message"}`. + +| Method | Params | Result | +|---|---|---| +| `hello` | | `{app, version, protocol}` | +| `tools.list` | | the tools, exactly as MCP `tools/list` lists them (`docs/mcp.md`) | +| `tools.call` | `{name, arguments}` | exactly what MCP `tools/call` returns: `{content: […], isError}` | + +`tools.call` runs the same code as the headless MCP server. A tool that fails (a command's error) +is a result with `"isError": true`; a malformed call (an unknown tool, a missing `name`) is an +`"ok": false` reply. + +```json +{"id": 2, "token": "…", "method": "tools.call", "params": {"name": "anicraft_run", "arguments": {"command": "draw.rect", "params": {"x": 10, "y": 10, "w": 50, "h": 50}}}} +{"id": 2, "ok": true, "result": {"content": [{"type": "text", "text": "{\"frame\": 0, \"result\": {…}, \"revision\": 3, \"scene\": 0}"}], "isError": false}} +``` + +## When calls run + +The window runs calls at the start of a frame, so an edit shows in that frame. It never takes +keyboard focus and doesn't need to be the front window. An edit made while the start screen is showing closes it, so you see +the document it changed. + +While you are dragging (or a plug-in dialog is previewing), calls that could change the document +wait until you let go, so your drag and the assistant's edit stay separate undo steps. Calls that +only read run at once. If you were typing in a field, your change is kept as its own undo step +first. A call that waited 60 seconds is not run, and its reply says so. + +Commands that would lose work or replace a file still need `"confirm": true` (ADR 0004). + +## Limits + +| | | +|---|---| +| Line length | 4 MiB; a longer line gets an error and the connection closes | +| Connections | 16 at once; another gets an error line and is closed | +| Waiting | 60 s per call | +| First line | must be a JSON object with a string `"method"`, or the connection closes (this also refuses a web page's request to localhost) | + +## Trying it by hand + +With AniCraft open with `--control 9878`, in PowerShell: + +```powershell +$t = (Get-Content "$env:APPDATA\AniCraft\control.json" | ConvertFrom-Json).token +$c = New-Object Net.Sockets.TcpClient 127.0.0.1, 9878 +$w = New-Object IO.StreamWriter $c.GetStream(); $r = New-Object IO.StreamReader $c.GetStream() +$w.WriteLine("{""id"":1,""token"":""$t"",""method"":""hello""}"); $w.Flush(); $r.ReadLine() +``` diff --git a/docs/mcp.md b/docs/mcp.md index ce1a3be1..b3f8a088 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8,8 +8,22 @@ look at frames and export through the same commands the app uses. anicraft-cli mcp # a new, empty document anicraft-cli mcp scene.anicraft # open a document anicraft-cli mcp --sample # the sample animation +anicraft-cli mcp --bridge 9878 # the AniCraft window you have open (below) ``` +## Headless or live + +Without `--bridge` the server edits a document of its own, with no window: good for pipelines and +batch work. Save it (`file.save`) to keep the result. + +With `--bridge ` the same tools act on the AniCraft window you have open, started with +`anicraft --control `: every edit appears there at once, and Ctrl+Z undoes it +(`docs/control-protocol.md`, ADR 0070). The server starts even when AniCraft isn't open (an +assistant starts its servers when it starts) and connects on the first tool call; until AniCraft is +open with remote control, the tools answer with how to start it. Close and reopen AniCraft whenever +you like: the next call reconnects, with no need to restart the assistant. It finds the run's token +in `control.json` in AniCraft's settings folder, so there is nothing to copy. + The server talks MCP's stdio transport: JSON-RPC 2.0, one message per line on stdin and stdout. It speaks protocol revisions 2025-06-18, 2025-03-26 and 2024-11-05. @@ -28,6 +42,19 @@ Most clients take a server entry like this one (use the full path to `anicraft-c } ``` +For live editing, start AniCraft with `--control 9878` (a desktop shortcut is handy) and use: + +```json +{ + "mcpServers": { + "anicraft": { + "command": "C:\\path\\to\\anicraft-cli.exe", + "args": ["mcp", "--bridge", "9878"] + } + } +} +``` + ## Tools | Tool | What it does | @@ -54,3 +81,6 @@ timeline). save, import, export), as with the CLI. Only connect clients you trust with those files. * A failing command comes back as a tool result marked as an error, so the assistant can read the message and try again; it never stops the server. +* Live (`--bridge`): an edit whose answer was lost (AniCraft closed mid-call) is never sent again, + since it may have been made; the assistant is told to check with `anicraft_document`. While you + are dragging, the assistant's edits wait until you let go, so the two stay separate undo steps. diff --git a/docs/roadmap.md b/docs/roadmap.md index 6161a6c3..f352c14a 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -14,7 +14,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Not yet: width profiles in the merge. **Raw points and symbols in place** (ADR 0045): add a point on a raw edge (Pen Alt-click, Subselection double-click; every shape on the edge gets it, the curve unchanged), delete raw points (Delete; the shapes on each are joined across it so the drawing stays connected; points where three edges meet are kept), Make Smooth / Corner on raw points, smooth handle pairs (Alt breaks them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap their points within 10 screen px (Snap to Objects, Ctrl+Shift+/); a double-click on an instance (or Ctrl+E, or a double-click in the Library) opens the symbol in place, the stage dimmed around it, the edit bar showing the path back, and every tool and command works on its timeline. Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth` on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`. Not yet: rotated instances in place (they open upright). Onion skin and Edit Multiple Frames work inside a symbol since ADR 0051. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. Not yet: Paint Selection and Paint Inside. **Brush library, pressure curves and the Paint Brush (Y)** (ADR 0068, first slice): Window › Brush Library with seven built-in brushes made only of parameters (Pencil, Ink Pen, Flat Calligraphy, Round Taper, Marker, Chalk with a deterministic worn edge, Dotted stamps), each with a stroke preview drawn by the renderer; brushes of your own saved by name in your preferences, renamed, deleted (asks first) and moved between computers as a JSON brush set; a pressure curve editor (Linear, Soft, Firm, or your own points) driving size and, optionally, the stroke's opacity; tapers, dab spacing and a rough edge in Properties; Velocity (mouse speed as pressure, off by default); the Paint Brush draws a width-profiled stroke in the stroke colour that the Width tool edits. Headless: `brush.preset_list/save/rename/delete/export/import`, `preset`, `curve`, `as_stroke` and the shaping params on `draw.brush`. Not yet: pen tilt (egui doesn't report it), opacity varying along a stroke, textured or art brushes, Eraser presets and pressure. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Not yet: erasing inside symbols, erasing width-profiled shapes (gradient fills erase since ADR 0042), eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. | | Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. Not yet: exporter and easing kinds, background runs with cancel, a binary document view. | | Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. **A window of its own on the desktop** (ADR 0062): sized to the stage at 100 % (smaller to fit the screen), titled with the document, back where it was last (not on Wayland, where the desktop places windows), with the keyboard when it opens; Esc or Ctrl+W (⌘W) closes it, Ctrl+Enter restarts it in place, and the editor's Ctrl/Alt shortcuts work from it; floating inside the editor in the web build, where the system can't open windows (it says so), or by choice in Preferences › Test Movie. Not yet: full screen, zoom in the movie window, remembering its size. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. **Buttons, complete** (ADR 0057): a button open in place names its frames Up, Over, Down and Hit on the timeline and shows its Hit area translucent over the other states; Test Movie has **Show hit areas**; sounds on its frames play as its state changes. | -| Headless | CLI: info, render, render-seq, **gif**, **apng**, **webp**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. | +| Headless | CLI: info, render, render-seq, **gif**, **apng**, **webp**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. **Live control** (ADR 0070, `docs/control-protocol.md`): `anicraft --control ` and `anicraft-cli mcp --bridge ` run the same tools on the open window, with a per-run token in `control.json`. | | Sound | **Audio layers, first slice** (ADR 0020): WAV (own reader), Ogg Vorbis (`lewton`) and MP3 (`nanomp3`) import, bounded and crash-proof; sounds live in the library, stored in `.anicraft` as imported, decoded once in the background. A sound belongs to a keyframe as in Animate (Properties › Sound: name, Sync Event/Start/Stop/Stream, Repeat ×N or Loop); Import to Stage puts one on a new layer spanning its length, Import to Library only adds it, the Library previews, places and deletes sounds. The timeline draws each sound's waveform over its span. Stage playback plays the mix through `cpal` (default feature `sound-output`) and the playhead follows the audio clock; stream sounds resync after a jump and scrubbing plays one-frame snippets. Mixing is pure and sample-exact (`doc::sound::voices` + `audio::mix`, Catmull-Rom resampling between rates). Headless: `sound.place/set/remove/rename/delete`, `file.import_to_library`, **`file.export_audio`** (WAV, 16/24-bit or float, any rate), and Export Video carries the soundtrack (Opus in WebM, AAC in MP4, by the user's ffmpeg). **Second slice** (ADR 0039): each frame sound has an **Effect** (None, Left channel, Right channel, Fade left to right, Fade right to left, Fade in, Fade out, shaped over the time it is heard, or **Custom**: up to 16 volume points per channel in the **Edit Envelope** window, drawn on each channel's waveform; the timeline's waveform follows the envelope). Layers holding sounds get a **Volume** and **Mute** (Properties, and a speaker toggle in the timeline); volumes multiply down through symbols and muted layers are silent in playback and every export. **Sounds inside symbols** play: a graphic's on its own frames mapped to the parent's time (loop mode and first frame apply; streams join mid-way and follow the parent playhead), a movie clip's on a loop from when the instance appeared; in the interactive player and **Test Movie** (which now has sound, the picture keeping time with it) movie clips start theirs as their own timelines reach them. The HTML page carries envelopes, volumes and graphic sounds. Headless: `sound.set {effect, envelope}`, `layer.set_volume`, `layer.toggle_mute`. **Sounds on button frames** (ADR 0057) play in Test Movie and the HTML page as the pointer changes the button's state (Over, Down, and Up and Hit on leaving and release, as the SWF format keeps them; never in the soundtrack); `control.test_movie` lists the sounds it starts. **XFL** brings sounds whose file is in the package (WAV, Ogg, MP3) with the sounds on frames that use them, buttons' included. Not yet: sounds kept only in Animate's own data format (undocumented; reported), sound effects and in/out points from XFL, sound panning beyond the envelope, audio in Lottie, stream sounds that follow go-tos in the HTML page, lossless compression of stored WAVs, latency compensation. | | Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **animated PNG and animated WebP export** (ADR 0063: full colour and real alpha, transparent or on the stage colour; every frame exactly the renderer's; repeated frames merged into longer delays; later frames only the rectangle that changed (APNG blends opaque changes over, WebP replaces); APNG delays exact fractions of the frame rate, WebP milliseconds that never drift; loop forever, once or N times; File › Export, Publish Settings, the web build's downloads, `anicraft-cli apng`/`webp`; not yet: lossy WebP (no permissive pure-Rust VP8 encoder exists), dispose-to-background frames, palette or RGB APNG for smaller files), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Colour effects in every style (Brightness, Tint, Advanced, Alpha; ADR 0056), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). **Drops, Open Recent and the start screen** (ADR 0059): files dropped on the window open (documents) or import onto the stage at the drop point on the active layer, or into the Library folder under the pointer, in one undo step (`file.drop`), with a drop highlight; File › Open Recent (10 recent, pinned favourites, missing files greyed with Remove) kept in the preferences; a start screen at launch with New presets (1280 × 720, 1920 × 1080, 1080 × 1080, 1080 × 1920, custom), Open, the sample and recent files with thumbnails captured on save. **Templates, SVG into the Library and drops on the timeline** (ADR 0065): six built-in templates made in code (banners 728 × 90 and 300 × 250, social square 1080 × 1080 at 30 fps, storyboard 16:9 panels, character turnaround, lip-sync mouth chart) with guides on a locked guide layer, on the start screen and File › New from Template; File › Save as Template keeps the document with a picture in the settings folder by category (replacing and deleting confirm); an SVG dropped on or imported to the Library becomes one graphic symbol named after the file, in the folder under the pointer; a sound dropped on a layer's frame goes onto that keyframe, an image or SVG onto that layer in a keyframe made there if needed, one undo step, with a highlight on the cell. Not yet: exact drop positions on the desktop (eframe 0.36 and 0.37 are on winit 0.30, which gives none during a drag; a drop waits for the first pointer move, else lands mid-view), user template descriptions and renaming, several documents at once. **Publish Settings and Publish** (ADR 0060): the formats to publish, with their options and output names, saved in the document; File › Publish (Shift+F12) writes them all in the background with progress, Cancel and one report; presets in Preferences. | | Library | **Library management, first slice** (ADR 0050): nested **folders** (New Folder, rename, drag items and folders in and out, Move to; deleting a folder that holds items asks), **inline rename** (F2 or double-click the name; names unique per folder, case aside), **Duplicate Symbol** (fresh ids, same folder, “Ball copy”), **Swap Symbol** in Properties (keeps transform, colour effect, filters, looping and name), a **use count** column, **Select Unused Items** and **Delete Unused Items** (unused = not reachable from any scene; linkage classes count as used; asks first), deleting used items asks and removes their instances, fills and keyframe sounds, **sort** by name, type, use count or date added, **search** (opens the folders that lead to a match), multiple selection, a **preview** (a symbol's first frame from the oracle, a bitmap as smoothed or not, a sound's waveform with play) and **item properties** (symbol type and linkage class, bitmap **Allow Smoothing**, which the oracle, the GPU stage, SVG and HTML honour). Folders are a side table in the document (older files open flat); XFL import keeps folders and Allow Smoothing. Headless: `library.items/new_folder/rename/move/duplicate/delete/unused/delete_unused/set_smoothing`, `element.swap_symbol`. **Second slice** (ADR 0053): **drag items onto the stage** (symbols and bitmaps land at the pointer on the active layer at the playhead, sounds go onto its keyframe; several at once; one undo step; inside a symbol open for editing too), **Place on Stage** (button, right-click, or Enter) at the centre of the view, **Swap Bitmap** in Properties (a placed bitmap keeps its corner and takes the new size; a bitmap fill keeps its shape), a **Convert to Symbol** dialog with name, type and **folder** that offers the last folder and type again, and **"mixed" on every Properties row** for several elements (Scale, Rotation, Alpha, Symbol, Type, Filters, Blending, Looping, First frame, Fill, Bitmap, Stroke, Width, Style; each row compares only the elements it edits; editing a mixed row sets all, and Type sets every selected instance's symbol). Headless: `library.place {items, x, y}` (and `sound`), `element.swap_bitmap`, `kind` and `folder` on `modify.convert_to_symbol`. **9-slice scaling** (ADR 0055): Enable guides for 9-slice scaling on a symbol (Library or Properties). Scaled instances keep their corners, stretch their edges one way and the centre both ways, and strokes keep their width. Rotation and skew apply after; nested symbols, text and bitmaps scale normally. Guides are dragged as dashed lines while editing the symbol in place, or typed in Properties. The CPU, GPU, SVG and Lottie output all show it, and XFL `scaleGrid*` attributes are imported; guides switched off are kept and come back when switched on (ADR 0057). Not yet: 9-slice in HTML canvas export (scaled as a whole and reported), guides in Library previews, snapping guides. Not yet: shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, dropping files from the desktop, a picture of the item while dragging, Swap Bitmap on a Library item (every use), mixed text style rows, a Colour Effect row with tint. | diff --git a/src/app.rs b/src/app.rs index 6dccf28e..fb165c7a 100644 --- a/src/app.rs +++ b/src/app.rs @@ -285,6 +285,9 @@ pub use anicraft_engine::doc::LibraryItem; pub struct App { #[cfg(not(target_arch = "wasm32"))] pub(crate) updates: crate::updates::Updates, + /// The live control port, with `--control` (ADR 0070). + #[cfg(not(target_arch = "wasm32"))] + pub(crate) remote: Option, pub s: Session, pub tool: Tool, pub view: StageView, @@ -549,6 +552,8 @@ impl App { let mut app = App { #[cfg(not(target_arch = "wasm32"))] updates: Default::default(), + #[cfg(not(target_arch = "wasm32"))] + remote: None, s: session, tool: Tool::Select, view: StageView { zoom: 1.0, pan: egui::Vec2::ZERO, fit: true, fitted: None }, @@ -2779,6 +2784,8 @@ impl eframe::App for App { self.recovery.finish(&self.s, clean); #[cfg(not(target_arch = "wasm32"))] self.updates.finish(); + #[cfg(not(target_arch = "wasm32"))] + crate::remote::finish(self); } fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { @@ -2798,6 +2805,9 @@ impl App { } } self.handle_screenshot(&ctx); + // An assistant's edits (ADR 0070), before anything draws: they show in this frame. + #[cfg(not(target_arch = "wasm32"))] + crate::remote::poll(self, &ctx); self.poll_font_scan(&ctx); self.follow_system_contrast(&ctx); if let Some(p) = platform::picked_file() { diff --git a/src/main.rs b/src/main.rs index 594d1051..14dc0b90 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,6 +3,7 @@ //! ```text //! anicraft [file.anicraft] [--screenshot out.png] [--renderer wgpu|gl] [--open ] //! [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] +//! [--control ] //! anicraft --version //! ``` //! `--screenshot` starts normally, draws ~120 frames, saves the window as PNG and exits. @@ -55,6 +56,8 @@ mod platform; mod plugins_ui; mod prefs; mod recent; +#[cfg(not(target_arch = "wasm32"))] +mod remote; mod scale_grid; mod sound; mod shape_hints; @@ -111,7 +114,7 @@ struct Look { } #[cfg(not(target_arch = "wasm32"))] -fn run(renderer: eframe::Renderer, file: Option<&Path>, shot: Option, open: Option, look: Look) -> eframe::Result { +fn run(renderer: eframe::Renderer, file: Option<&Path>, shot: Option, open: Option, look: Look, control: Option) -> eframe::Result { let options = eframe::NativeOptions { viewport: platform::viewport(egui::ViewportBuilder::default().with_title("AniCraft").with_inner_size([1600.0, 940.0]).with_min_inner_size([960.0, 600.0])), renderer, @@ -143,6 +146,10 @@ fn run(renderer: eframe::Renderer, file: Option<&Path>, shot: Option, o start::open(&mut a); } a.preview_look(&cc.egui_ctx, look.theme, look.scale); + // `--control`: an assistant can edit this window live (ADR 0070). + if let Some(port) = control { + remote::start(&mut a, &cc.egui_ctx, port); + } a.open_panel(open.as_deref()); // An imported document says what came across, as opening it from the menu does. if let Some(r) = report { @@ -171,6 +178,8 @@ struct Args { open: Option, renderer: Option, look: Look, + /// `--control `: the live control port (ADR 0070). + control: Option, /// `--version` / `--help`: print and leave. print: Option, } @@ -191,6 +200,8 @@ fn parse_args(args: impl IntoIterator) -> Result { match a.as_str() { "--screenshot" => out.shot = Some(PathBuf::from(args.next().ok_or("--screenshot needs a file name")?)), // i18n-exempt: a console message "--open" => out.open = args.next(), + // i18n-exempt: a console message + "--control" => out.control = Some(anicraft_cli::control::parse_port(&args.next().unwrap_or_default()).map_err(|e| format!("--control: {e}"))?), "--renderer" => out.renderer = args.next(), "--shot-width" => match args.next().and_then(|s| s.parse::().ok()) { Some(w) if (64..=8192).contains(&w) => out.look.shot_width = Some(w), @@ -226,7 +237,7 @@ fn parse_args(args: impl IntoIterator) -> Result { /// `--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 ]] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|brushlibrary|brushcurve|paintbrush|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|library|librarymenu|colour|layerprops|frameview|layercolour|timelinepolish]\n\ +const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width ]] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--control ] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|brushlibrary|brushcurve|paintbrush|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|library|librarymenu|colour|layerprops|frameview|layercolour|timelinepolish]\n\ --renderer force the GPU backend (also ANICRAFT_RENDERER); default wgpu, 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\ @@ -234,6 +245,8 @@ const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--sc --theme the interface palette for this run (not saved)\n\ --scale the interface scale for this run, 75 to 200 (not saved)\n\ --lang the interface language for this run (not saved); pseudo tests the layout\n\ + --control lets an assistant edit this window live through a port on this computer\n\ + (also ANICRAFT_CONTROL_PORT; 9878 by convention; see docs/control-protocol.md)\n\ Headless use: anicraft-cli --help"; #[cfg(not(target_arch = "wasm32"))] @@ -263,7 +276,21 @@ fn main() -> eframe::Result { } None => {} } - let Args { shot, file, open, renderer, look, .. } = args; + let Args { shot, file, open, renderer, look, control, .. } = args; + // ANICRAFT_CONTROL_PORT when there is no --control; a bad port stops here, before a window. + let control = match control { + Some(p) => Some(p), + None => match std::env::var(anicraft_cli::control::PORT_ENV).ok().filter(|v| !v.trim().is_empty()) { + Some(v) => match anicraft_cli::control::parse_port(&v) { + Ok(p) => Some(p), + Err(e) => { + eprintln!("{}: {e}", anicraft_cli::control::PORT_ENV); + std::process::exit(2); + } + }, + None => None, + }, + }; // macOS hands documents over as Apple Events, the one that launched the app included: listen // from before the event loop starts until it ends (ADR 0062). let _documents = platform::listen_for_documents(); @@ -272,10 +299,10 @@ fn main() -> eframe::Result { // on some Linux setups) retry once with OpenGL, unless the user forced a backend. let forced = platform::forced_renderer(renderer.as_deref()); let first = forced.unwrap_or(eframe::Renderer::Wgpu); - match run(first, file.as_deref(), shot.clone(), open.clone(), look.clone()) { + match run(first, file.as_deref(), shot.clone(), open.clone(), look.clone(), control) { Err(e) if forced.is_none() && first == eframe::Renderer::Wgpu => { eprintln!("GPU backend (wgpu) failed to start: {e}. Retrying with OpenGL."); - run(eframe::Renderer::Glow, file.as_deref(), shot, open, look) + run(eframe::Renderer::Glow, file.as_deref(), shot, open, look, control) } other => other, } @@ -305,6 +332,11 @@ mod args_tests { assert_eq!(parse(&["--screenshot", "a.png", "--shot-width", "1200"]).look.shot_width, Some(1200)); assert!(parse_args(["--shot-width".to_string(), "9".to_string()]).is_err()); assert_eq!(parse(&["--version"]).print, Some(Print::Version)); + // `--control ` (ADR 0070): a port from 1 to 65535, or an error before any window. + assert_eq!(parse(&["--control", "9878"]).control, Some(9878)); + for bad in [&["--control"][..], &["--control", "0"], &["--control", "99999"], &["--control", "port"]] { + assert!(parse_args(bad.iter().map(|a| a.to_string())).is_err(), "{bad:?}"); + } // And the file opens: the session starts with it, not the sample. let dir = std::env::temp_dir().join(format!("anicraft-shell-args-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); diff --git a/src/panels.rs b/src/panels.rs index c7a79b2d..eef49bf0 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -208,6 +208,13 @@ pub fn status_bar(app: &mut App, ui: &mut egui::Ui) { let small = |t: String| text(Type::Data, t).color(T.text_faint); ui.label(small(tr!("undo {steps} · {size} MB", steps = app.s.history().undo_len(), size = format!("{:.1}", app.s.history().bytes() as f32 / (1024.0 * 1024.0))))); ui.add_space(12.0); + // An assistant can edit this window (ADR 0070): always in view while that is so. + #[cfg(not(target_arch = "wasm32"))] + if let Some(port) = crate::remote::port(app) { + ui.label(text(Type::Label, tr!("Remote control on (port {port})", port = port)).color(T.text_faint)) + .on_hover_text(tr!("An assistant can edit this document through a control port on this computer. Its edits appear here at once and undo like your own. Started with --control; close AniCraft to turn it off.")); + ui.add_space(12.0); + } if let Some(a) = crate::autosave::status(app, now) { ui.label(small(a)).on_hover_text(tr!("A recovery copy of your unsaved work. If AniCraft closes unexpectedly, the next start offers it back.")); ui.add_space(12.0); diff --git a/src/platform.rs b/src/platform.rs index d1ca41c5..ab45f471 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -201,6 +201,31 @@ pub fn recovery_dir() -> Option { } } +/// Writes a file only this user may read (the control port's token, ADR 0070), making its folder +/// first. On Windows the settings folder (%APPDATA%) is already private to the user; elsewhere +/// the file is made owner-only (0600). +#[cfg(not(target_arch = "wasm32"))] +pub fn write_private_file(path: &std::path::Path, contents: &[u8]) -> std::io::Result<()> { + use std::io::Write; + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let mut options = std::fs::OpenOptions::new(); + options.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; + options.mode(0o600); + // An older file keeps its mode when opened: tighten it first. + if path.exists() { + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?; + } + } + let mut f = options.open(path)?; + f.write_all(contents)?; + f.sync_all() +} + /// Whether the recovery folder was chosen explicitly (screenshot runs only touch it then). pub fn recovery_dir_overridden() -> bool { std::env::var_os("ANICRAFT_RECOVERY_DIR").is_some_and(|v| !v.is_empty()) diff --git a/src/remote.rs b/src/remote.rs new file mode 100644 index 00000000..17cc94de --- /dev/null +++ b/src/remote.rs @@ -0,0 +1,143 @@ +//! Remote control (ADR 0070, `docs/control-protocol.md`): `anicraft --control ` opens a +//! control port on this computer, and an assistant (through `anicraft-cli mcp --bridge`) edits +//! the open document live. The port, its threads and the tools are `anicraft_cli::control`'s; +//! this module runs each call on the window's session at the start of a frame, writes the +//! run's token to `control.json` in the settings folder, and removes it on exit. +//! +//! A call that edits waits while the person is dragging (or a plug-in dialog has its preview +//! open), so the two never share an undo step. Typing in a field doesn't hold it back: the +//! person's typed change is committed as its own step first, as clicking elsewhere would. + +use crate::app::{App, Drag}; +use crate::platform; +use anicraft_cli::{control, mcp}; +use anicraft_engine::Session; +use serde_json::Value; +use std::collections::VecDeque; +use std::path::PathBuf; +use std::sync::Arc; + +/// An open control port. +pub struct Remote { + server: control::Server, + /// Calls in arrival order; the first one that edits holds the rest back during a drag. + waiting: VecDeque, + token: String, + /// `control.json`, when it could be written. + file: Option, +} + +/// Opens the control port; failures go to the status bar (the window still opens). +pub fn start(app: &mut App, ctx: &egui::Context, port: u16) { + let token = match control::token_from_env().map_or_else(control::new_token, Ok) { + Ok(t) => t, + Err(e) => { + app.status_err(tr!("Remote control is off: {reason}", reason = e)); + return; + } + }; + let wake_ctx = ctx.clone(); + let server = match control::listen(port, token.clone(), Arc::new(move || wake_ctx.request_repaint())) { + Ok(s) => s, + Err(e) => { + app.status_err(tr!("Remote control is off: port {port} is in use or not allowed ({reason}). Is another AniCraft already open with remote control?", port = port, reason = e)); + return; + } + }; + let file = control::control_file(); + let written = file.as_ref().map(|path| { + let contents = control::ControlFile { port: server.port, token: token.clone(), pid: std::process::id(), version: env!("CARGO_PKG_VERSION").to_string() }; + platform::write_private_file(path, contents.to_json().to_string().as_bytes()) + }); + if let Some(Err(e)) = &written { + // The port works with ANICRAFT_CONTROL_TOKEN; without the file a bridge can't find it. + app.status_err(tr!("Remote control is on, but its token could not be saved ({reason}); set ANICRAFT_CONTROL_TOKEN for the assistant.", reason = e)); + } + let file = if matches!(written, Some(Ok(()))) { file } else { None }; + app.remote = Some(Remote { server, waiting: VecDeque::new(), token, file }); +} + +/// The port, while remote control is on (the status bar shows it). +pub fn port(app: &App) -> Option { + app.remote.as_ref().map(|r| r.server.port) +} + +/// Whether the person is in the middle of an edit a remote one must not join. +fn person_is_dragging(app: &App, ctx: &egui::Context) -> bool { + app.drag != Drag::None || app.plugin_dialog.is_some() || (app.s.in_gesture() && ctx.egui_is_using_pointer()) +} + +/// Runs the waiting calls: at the start of a frame, so their edits draw in this one. +pub fn poll(app: &mut App, ctx: &egui::Context) { + let Some(r) = app.remote.as_mut() else { return }; + while let Some(req) = r.server.try_recv() { + r.waiting.push_back(req); + } + loop { + let dragging = person_is_dragging(app, ctx); + let Some(r) = app.remote.as_mut() else { return }; + let Some(next) = r.waiting.front() else { return }; + if next.changes_document() && dragging && !next.expired() { + // Look again shortly: the drag ends without a remote wake-up. + ctx.request_repaint_after(std::time::Duration::from_millis(50)); + return; + } + let Some(req) = r.waiting.pop_front() else { return }; + // (An expired call is refused without running: it leaves the person's gesture alone.) + if req.changes_document() && !req.expired() && !dragging && app.s.in_gesture() { + // A typed property change still open: it becomes its own undo step first. + app.s.end_gesture(); + } + req.run(&mut Live(app)); + } +} + +/// On exit: calls still waiting are told so, and `control.json` goes (if it is still ours). +pub fn finish(app: &mut App) { + let Some(mut r) = app.remote.take() else { return }; + for req in r.waiting.drain(..) { + // i18n-exempt: the protocol's English, read by the assistant (as MCP) + req.refuse("AniCraft is closing"); + } + if let Some(path) = &r.file { + let ours = std::fs::read_to_string(path).ok().and_then(|t| control::ControlFile::parse(&t).ok()).is_some_and(|c| c.token == r.token); + if ours { + let _ = std::fs::remove_file(path); + } + } +} + +/// The window as the tools' host: commands run with the follow-up the person's own get (the +/// status line, the view a new document resets, Open Recent). +struct Live<'a>(&'a mut App); + +impl mcp::Host for Live<'_> { + fn session(&self) -> &Session { + &self.0.s + } + fn execute(&mut self, id: &str, params: &Value) -> Result { + let selected = self.0.s.selection.len(); + let revision = self.0.s.revision; + let v = self.0.s.execute(id, params).map_err(|e| e.to_string())?; + // An edit to the document behind the start screen: show the document, so the person + // sees it land (ADR 0059's start screen otherwise covers the workspace). + if self.0.s.revision != revision { + self.0.start = None; + } + self.0.announce(id, &v, selected); + Ok(v) + } +} + +#[cfg(test)] +mod tests { + use crate::platform; + + /// The CLI finds `control.json` with its own copy of the settings-folder rule (it can't use + /// the shell); they must agree, or the bridge looks in the wrong place. + #[test] + fn the_bridge_looks_for_the_token_in_the_settings_folder() { + assert_eq!(anicraft_cli::control::settings_dir(), platform::config_dir()); + assert_eq!(anicraft_cli::control::control_file(), platform::config_dir().map(|d| d.join("control.json"))); + } +} From 5967b274b2953ad3050a930a407855e812bef7e9 Mon Sep 17 00:00:00 2001 From: lienatanael1-beep Date: Thu, 12 Nov 2026 15:32:09 +0700 Subject: [PATCH 10/20] docs: ADR 0070 is reserved for #216 Co-Authored-By: Claude Opus 5.5 --- docs/adr/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/adr/README.md b/docs/adr/README.md index 65918325..4f01eaae 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,4 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | -| 0070 | feat/live-control | Live control port | +| 0070 | #216 | Live control port | From 74c235627613412cd3ae6855655d7e6148cd10ce Mon Sep 17 00:00:00 2001 From: Juan Larrazabal Date: Sat, 14 Nov 2026 13:28:38 -0800 Subject: [PATCH 11/20] feat(colour): fill and stroke alpha (ADR 0097) The colour picker keeps an alpha on a solid fill and on a stroke, and each gradient stop keeps its own. A brush stroke that is not fully opaque stays its own shape, and the pen-down preview is already that alpha. --- CHANGELOG.md | 8 + crates/engine/src/brush_tests.rs | 62 ++++++++ crates/engine/src/cmds_brush.rs | 31 +++- crates/engine/src/cmds_draw.rs | 4 +- crates/engine/src/cmds_paint.rs | 2 +- docs/adr/0097-fill-alpha.md | 43 ++++++ docs/adr/README.md | 1 + docs/guide/coming-from-animate.md | 2 +- docs/guide/reference/commands.md | 8 +- docs/roadmap.md | 2 +- src/brushtool.rs | 235 +++++++++++++++++++++++++++++- src/colour.rs | 29 +++- src/colour_panel.rs | 46 +++++- src/panels.rs | 59 ++++---- 14 files changed, 470 insertions(+), 62 deletions(-) create mode 100644 docs/adr/0097-fill-alpha.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 4449c7e7..6345c476 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## Unreleased +* **Fill and stroke alpha** (ADR 0097). + * The colour picker sets an alpha on a solid fill and on a stroke, from clear to opaque. + A clear fill is still a fill. No fill is the type None. + * Each stop of a linear or radial gradient keeps its own alpha, so a ramp can fade. The + stop's marker shows that alpha. + * A brush stroke that is not fully opaque stays its own shape, so the colour behind it + shows through and crossings darken. Opaque strokes still join. Group bundles the + separate strokes. The ink is drawn at that alpha while the pen is down. * **Sound output polish** (ADR 0095, M5). * The playhead follows the sound being **heard**: the device's latency is taken off and slow frames are dropped rather than drifting (within a frame over an hour of play in tests). diff --git a/crates/engine/src/brush_tests.rs b/crates/engine/src/brush_tests.rs index a75f16c1..002b65a3 100644 --- a/crates/engine/src/brush_tests.rs +++ b/crates/engine/src/brush_tests.rs @@ -142,6 +142,68 @@ fn paint_normal_covers_and_merges_with_raw_shapes() { assert_eq!(reds, 1, "brush strokes of one colour join"); } +#[test] +fn a_wash_stays_its_own_shape_and_composites() { + let mut s = blank(false); + run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 200, "h": 100, "fill": BLUE, "stroke": null})); + let r = run(&mut s, "draw.brush", json!({"points": stroke(50.0, 150.0, 350.0, 150.0), "size": 20, "color": "#ff000080"})); + assert_eq!(r["merged"], false, "a wash is not cut into the drawing"); + let blue = shapes(&s).iter().filter(|(sh, _)| fill_of(sh) == Some(Rgba::hex(0x0000ff))).count(); + assert_eq!(blue, 1, "the rectangle behind the wash is still one shape"); + let drawn = shapes(&s); + let wash = drawn.iter().find(|(sh, _)| fill_of(sh).is_some_and(|c| c.r > 0.9 && c.a < 1.0)).expect("the wash"); + let wash_a = fill_of(&wash.0).expect("solid wash").a; + assert!(!wash.0.merge && (wash_a - 128.0 / 255.0).abs() < 0.01, "{wash_a}"); + // A second wash of the same colour crosses it and stays separate, so the overlap darkens. + run(&mut s, "draw.brush", json!({"points": stroke(200.0, 60.0, 200.0, 240.0), "size": 20, "color": "#ff000080"})); + let washes = shapes(&s).iter().filter(|(sh, _)| fill_of(sh).is_some_and(|c| c.a < 1.0)).count(); + assert_eq!(washes, 2, "washes of one colour do not join"); + let px = |x, y| anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap().pixel(x, y).unwrap(); + let one = px(120, 150); + let two = px(200, 150); + let bare = px(150, 120); + assert!(bare[2] > 0.9 && bare[0] < 0.1, "blue only: {bare:?}"); + assert!(one[0] > 0.35 && one[0] < 0.65 && one[2] > 0.35 && one[2] < 0.65, "one wash over blue: {one:?}"); + assert!(two[0] > one[0] + 0.1 && two[2] < one[2] - 0.1, "two washes darken: {one:?} {two:?}"); +} + +#[test] +fn pressure_opacity_and_a_clear_gradient_stay_separate() { + let mut s = blank(false); + let pts: Vec = (0..=20).map(|i| json!([i as f32 * 10.0, 80.0, 0.25])).collect(); + let r = run(&mut s, "draw.brush", json!({"points": pts, "size": 16, "color": RED, "pressure_opacity": true, "pressure_size": false})); + assert_eq!(r["merged"], false); + let drawn = shapes(&s); + let (sh, _) = drawn.last().expect("the stroke"); + let a = fill_of(sh).expect("a solid").a; + assert!(!sh.merge && (a - 0.25).abs() < 0.02, "average pressure is the alpha: {a}"); + + let mut g = blank(false); + run(&mut g, "draw.rect", json!({"x": 40, "y": 40, "w": 80, "h": 40, "fill": BLUE, "stroke": null})); + run(&mut g, "paint.set_fill", json!({"type": "linear", "selection": false, "stops": [{"offset": 0, "color": "#ff0000ff"}, {"offset": 1, "color": "#ff000000"}]})); + let r = run(&mut g, "draw.brush", json!({"points": stroke(20.0, 60.0, 140.0, 60.0), "size": 12})); + assert_eq!(r["merged"], false); + assert_eq!(shapes(&g).iter().filter(|(sh, _)| fill_of(sh) == Some(Rgba::hex(0x0000ff))).count(), 1, "the rectangle is not cut"); + assert!(shapes(&g).iter().any(|(sh, _)| matches!(sh.fill, Some(Paint::Linear { .. })) && !sh.merge)); + + // An opaque gradient still joins the drawing. + let mut o = blank(false); + run(&mut o, "draw.rect", json!({"x": 40, "y": 40, "w": 80, "h": 40, "fill": BLUE, "stroke": null})); + run(&mut o, "paint.set_fill", json!({"type": "linear", "selection": false, "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#00ff00"}]})); + let r = run(&mut o, "draw.brush", json!({"points": stroke(20.0, 60.0, 140.0, 60.0), "size": 12})); + assert_eq!(r["merged"], true); +} + +#[test] +fn a_translucent_paint_brush_line_does_not_merge() { + let mut s = blank(false); + let r = run(&mut s, "draw.brush", json!({"points": stroke(10.0, 10.0, 80.0, 10.0), "size": 8, "as_stroke": true, "color": "#ff000080"})); + assert_ne!(r["merged"], true); + let (sh, _) = &shapes(&s)[0]; + let a = sh.stroke.as_ref().map(|st| st.color.a).unwrap_or(1.0); + assert!(!sh.merge && (a - 128.0 / 255.0).abs() < 0.01, "{a}"); +} + #[test] fn paint_behind_only_fills_empty_areas() { for object in [false, true] { diff --git a/crates/engine/src/cmds_brush.rs b/crates/engine/src/cmds_brush.rs index 0eb593e3..36c01802 100644 --- a/crates/engine/src/cmds_brush.rs +++ b/crates/engine/src/cmds_brush.rs @@ -1,6 +1,7 @@ //! The Brush tool's command (ADR 0033): a stroke of the brush paints a filled shape, the area its -//! tip sweeps, in the fill colour. Off Object Drawing it is a raw shape that merges with the -//! drawing (ADR 0031), placed by the paint mode. +//! tip sweeps, in the fill colour. Off Object Drawing an opaque stroke merges with the drawing +//! (ADR 0031), placed by the paint mode. A fill that is not fully opaque stays its own shape and +//! composites over what is behind it (ADR 0097). use crate::brush_library::{BUILTIN, BrushLibrary, BrushPreset, MAX_FILE_BYTES, MAX_USER_PRESETS, builtin, builtin_hint, clean_name}; use crate::cmds_draw::{MAX_EXTENT, add_shape, object_param}; @@ -20,7 +21,7 @@ pub fn specs() -> Vec { c( "draw.brush", "Brush Stroke", - "{points: [[x, y], [x, y, pressure 0..1 (clamped)] or [x, y, pressure, altitude, azimuth] (the pen's tilt in degrees: altitude 90 upright to 0 flat, azimuth the way it leans, clockwise from +x)], ..] (one point paints a dab), preset? (a brush from brush.preset_list, by key or name: its settings are the defaults for the rest), size? (stage units, default 10), shape?: round|square, angle? (degrees), roundness? (5..100 %, default 100), smoothing? (0..100, default 50), curve?: linear|soft|firm|[[pressure, output], ..] (how pressure maps, both 0..1), pressure_size? (default true: pressure varies the size from 10 to 100 %), pressure_opacity? (default false: the stroke's average pressure sets its opacity), taper_start?, taper_end? (0..50 % of the stroke's length), spacing? (0 continuous, or 5..1000 % of the size between dabs), jitter? (0..50 % of the size: a ragged edge), texture? (0..100 %: a paper grain of holes through the paint), scatter? (0..200 % of the size: dabs thrown either side of the line, varied in size), tilt_angle? (the pen's tilt turns the tip: its angle plus the azimuth), tilt_width? (the pen's tilt widens the tip, up to twice as wide flat; also the Paint Brush's width), as_stroke? (default false; true: the Paint Brush, a variable-width stroke in the stroke colour, editable with the Width tool), mode?: normal|fills|behind|selection|inside (Paint Normal covers fills and lines, Paint Fills leaves lines, Paint Behind paints only empty areas, Paint Selection only inside the selected fills, Paint Inside only inside the fill the stroke starts on or the empty area closed off around it; ADR 0080), color? (default: the fill colour, or the stroke colour as a stroke), unit? (stage units per screen point, default 1: smoothing and accuracy follow it), object?}", + "{points: [[x, y], [x, y, pressure 0..1 (clamped)] or [x, y, pressure, altitude, azimuth] (the pen's tilt in degrees: altitude 90 upright to 0 flat, azimuth the way it leans, clockwise from +x)], ..] (one point paints a dab), preset? (a brush from brush.preset_list, by key or name: its settings are the defaults for the rest), size? (stage units, default 10), shape?: round|square, angle? (degrees), roundness? (5..100 %, default 100), smoothing? (0..100, default 50), curve?: linear|soft|firm|[[pressure, output], ..] (how pressure maps, both 0..1), pressure_size? (default true: pressure varies the size from 10 to 100 %), pressure_opacity? (default false: the stroke's average pressure sets its opacity), taper_start?, taper_end? (0..50 % of the stroke's length), spacing? (0 continuous, or 5..1000 % of the size between dabs), jitter? (0..50 % of the size: a ragged edge), texture? (0..100 %: a paper grain of holes through the paint), scatter? (0..200 % of the size: dabs thrown either side of the line, varied in size), tilt_angle? (the pen's tilt turns the tip: its angle plus the azimuth), tilt_width? (the pen's tilt widens the tip, up to twice as wide flat; also the Paint Brush's width), as_stroke? (default false; true: the Paint Brush, a variable-width stroke in the stroke colour, editable with the Width tool), mode?: normal|fills|behind|selection|inside (Paint Normal covers fills and lines, Paint Fills leaves lines, Paint Behind paints only empty areas, Paint Selection only inside the selected fills, Paint Inside only inside the fill the stroke starts on or the empty area closed off around it; ADR 0080), color? (default: the fill colour, or the stroke colour as a stroke), unit? (stage units per screen point, default 1: smoothing and accuracy follow it), object? (default the Object Drawing setting; a fill that is not fully opaque is its own shape, so it composites over what is behind it)}", true, draw_brush as crate::RunFn, ), @@ -225,6 +226,17 @@ pub fn pressure_opacity(b: &BrushPreset, pts: &[Sample]) -> f32 { (pts.iter().map(|x| b.curve.map(x.pressure)).sum::() / pts.len() as f32).clamp(0.05, 1.0) } +/// A fill that is not fully opaque has to stay its own shape. Merge drawing replaces what the +/// new shape covers, so a wash would hide the colour behind it, and two washes of one colour +/// would join instead of darkening where they cross (ADR 0097). +fn paint_stacks(p: &Paint) -> bool { + match p { + Paint::Solid(c) => c.a < 1.0, + Paint::Linear { stops, .. } | Paint::Radial { stops, .. } => stops.iter().any(|s| s.color.a < 1.0), + Paint::Bitmap { .. } => false, + } +} + fn draw_brush(s: &mut Session, p: &Value) -> Result { let pts = bounded_samples(p)?; let b = brush_param(s, p)?; @@ -296,18 +308,20 @@ fn draw_brush(s: &mut Session, p: &Value) -> Result { Some(_) if p.get("color").is_none_or(Value::is_null) && color.a >= 1.0 => s.style.fill_paint_for(&Affine::translate(-c.x, -c.y), &local.bounds()), _ => Paint::Solid(color), }; + // Opaque ink joins the drawing. A wash stays its own shape and composites (ADR 0097). + let own = object || paint_stacks(&fill); let id = ElementId(s.doc.alloc_id()); let el = Element { id, name: String::new(), transform: Affine::translate(c.x, c.y), color: ColorEffect::default(), - kind: ElementKind::Shape(Shape { path: Arc::new(local), fill: Some(fill), stroke: None, fill_rule: FillRule::EvenOdd, merge: !object, warp: None }), + kind: ElementKind::Shape(Shape { path: Arc::new(local), fill: Some(fill), stroke: None, fill_rule: FillRule::EvenOdd, merge: !own, warp: None }), }; if s.editable_keyframe()?.elements.len() >= 100_000 { return Err(EngineError::State("too many elements on this keyframe".into())); } - if object { + if own { let kf = s.editable_keyframe()?; match order { // Behind everything on the layer. @@ -356,7 +370,8 @@ const PROFILE_TOLERANCE: f32 = 0.015; /// The Paint Brush (ADR 0068): the smoothed centre line as a stroke of the brush's size in the /// stroke colour, its width profile following the pressure and tapers, so the Width tool edits -/// it afterwards. A stroke of one width is a plain line and merges like the Pencil's. +/// it afterwards. A stroke of one width is a plain line and merges like the Pencil's. A line +/// that is not fully opaque stays its own shape (ADR 0097). fn paint_stroke(s: &mut Session, pts: &[Sample], b: &BrushPreset, smoothing: f32, tol: f32, color: Rgba, object: bool) -> Result { let (path, factors) = centre_stroke(pts, &b.shaping(), smoothing, tol * 0.25, PROFILE_SAMPLES); if !path.cmds.iter().any(|c| matches!(c, PathCmd::CubicTo(..) | PathCmd::LineTo(..))) { @@ -366,7 +381,9 @@ fn paint_stroke(s: &mut Session, pts: &[Sample], b: &BrushPreset, smoothing: f32 let profile = WidthProfile::new(kept.iter().map(|(t, f)| WidthPoint::new(*t, *f, *f)).collect()); let stroke = Stroke::new(color, b.size).with_profile(profile); let c = path.bounds().center(); - let mut v = add_shape(s, "paint_brush", path.transformed(&Affine::translate(-c.x, -c.y)), c, None, Some(stroke), object)?; + // A translucent line stays its own shape too, so it composites instead of replacing. + let own = object || color.a < 1.0; + let mut v = add_shape(s, "paint_brush", path.transformed(&Affine::translate(-c.x, -c.y)), c, None, Some(stroke), own)?; v["width_points"] = json!(kept.len()); Ok(v) } diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index 74095142..c390d954 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -27,8 +27,8 @@ pub fn specs() -> Vec { c("element.pick", "Select at Point", "", None, "{x, y, add?: bool, view?: stage|camera} the topmost element there on a visible, unlocked layer; `add` (Shift) adds it to the selection, or lets go of it, on any layer; with `view: camera` the point is on the movie's picture as the camera shows it (each layer through its depth)", false, pick), c("element.translate", "Move", "", None, "{dx, dy, snap?, from?: [x, y]} moves the selection, on every layer; with `snap` (a distance) one of its corners or ends, or its box's corners or centre (the nearest to `from`), then snaps within that distance by the snap engine's priority (ADR 0076): a point, guide, line or fill edge of the rest, the grid, a whole pixel", true, translate), c("element.set_transform", "Transform", "", None, "{x?, y?, sx?, sy?, rotation? (degrees)}", true, |s, p| s.each_layer(true, |s| set_transform(s, p))), - c("element.set_fill", "Fill Colour", "", None, "{color: \"#rrggbb\" | null}", true, |s, p| s.each_layer(false, |s| set_fill(s, p))), - c("element.set_stroke", "Stroke", "", None, "{color?: \"#rrggbb\" | null, width?, profile?: uniform|taper_both|taper_start|taper_end|bulge|pinch | [[t, left, right], ..], cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing? (as stroke.set_style)}", true, |s, p| s.each_layer(false, |s| set_stroke(s, p))), + c("element.set_fill", "Fill Colour", "", None, "{color: \"#rrggbb\" | \"#rrggbbaa\" | null} (the alpha is the fill's own; 00 is a clear fill, not the same as null)", true, |s, p| s.each_layer(false, |s| set_fill(s, p))), + c("element.set_stroke", "Stroke", "", None, "{color?: \"#rrggbb\" | \"#rrggbbaa\" | null, width?, profile?: uniform|taper_both|taper_start|taper_end|bulge|pinch | [[t, left, right], ..], cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing? (as stroke.set_style)}", true, |s, p| s.each_layer(false, |s| set_stroke(s, p))), c("element.set_alpha", "Alpha", "", None, "{alpha: 0..1} sets the alpha multiplier and keeps the rest of the colour effect (None becomes Alpha; Brightness and Tint become Advanced below 1)", true, |s, p| s.each_layer(true, |s| set_alpha(s, p))), c("element.set_color_effect", "Colour Effect", "", None, "{style?: none|brightness|tint|advanced|alpha (default: the style the values belong to, else each element's own), alpha? (%, 0..100), brightness? (%, -100..100), tint? (#rrggbb), tint_amount? (%, 0..100), red_multiplier?, green_multiplier?, blue_multiplier?, alpha_multiplier? (%, -100..100), red_offset?, green_offset?, blue_offset?, alpha_offset? (-255..255)} on every selected element (ADR 0056); values not given keep each element's own. A new style starts from the look it can keep: Advanced is exactly the effect before, Alpha keeps the opacity, Brightness and Tint start at 0 %. The camera has no opacity (no Alpha style, alpha multiplier or offset)", true, |s, p| s.each_layer(true, |s| set_color_effect(s, p))), c("element.set_blend", "Blending", "", None, "{mode: normal|layer|darken|multiply|lighten|screen|overlay|hardlight|add|subtract|difference|invert|alpha|erase} on the selected movie clip and button instances", true, |s, p| s.each_layer(false, |s| set_blend(s, p))), diff --git a/crates/engine/src/cmds_paint.rs b/crates/engine/src/cmds_paint.rs index 411447a6..1643089d 100644 --- a/crates/engine/src/cmds_paint.rs +++ b/crates/engine/src/cmds_paint.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Fill", "", None, - "{type?: solid|linear|radial|bitmap (default: the swatch's), color? (solid), stops?: [{offset: 0..1, color: \"#rrggbb\" | \"#rrggbbaa\"}, ..] (2 to 15), spread?: extend|reflect|repeat, linear_rgb?: bool, focal?: -0.98..0.98 (radial), bitmap?: id, selection?: bool (default true)} sets the fill swatch (what new shapes, the Paint Bucket and the Brush pour) and, unless `selection` is false, the fills of the selected shapes. A shape keeping its kind of fill keeps where its gradient or bitmap lies; one changing kind gets it fitted to its bounds. A new gradient starts white to black → {fill: {type, ..}, changed}", + "{type?: solid|linear|radial|bitmap (default: the swatch's), color? (solid, \"#rrggbb\" or \"#rrggbbaa\"), stops?: [{offset: 0..1, color: \"#rrggbb\" | \"#rrggbbaa\"}, ..] (2 to 15; each stop has its own alpha), spread?: extend|reflect|repeat, linear_rgb?: bool, focal?: -0.98..0.98 (radial), bitmap?: id, selection?: bool (default true)} sets the fill swatch (what new shapes, the Paint Bucket and the Brush pour) and, unless `selection` is false, the fills of the selected shapes. A shape keeping its kind of fill keeps where its gradient or bitmap lies; one changing kind gets it fitted to its bounds. A new gradient starts white to black → {fill: {type, ..}, changed}", true, set_fill, ), diff --git a/docs/adr/0097-fill-alpha.md b/docs/adr/0097-fill-alpha.md new file mode 100644 index 00000000..ba5dc5ab --- /dev/null +++ b/docs/adr/0097-fill-alpha.md @@ -0,0 +1,43 @@ +# ADR 0097: Fill alpha + +* Status: proposed +* Relates to: ADR 0074 (the fill picker and gradients), ADR 0078 (swatches) + +## Context + +In Flash, the colour you picked for a fill was not only a hue. The mixer had an alpha, and a +light wash was how people built glass, smoke, shadows and fades without a second shape. A +gradient did the same per stop: one end of a ramp could be the colour and the other end +nothing, or two stops could be the same colour at two different strengths. That is a different +thing from no fill. No fill means the shape has no interior. A clear fill is still there. You +can select it, erase it, and use it as an alpha mask. + +The document already stores that alpha on a solid colour and on every gradient stop, and the +renderer already paints it. The solid fill picker threw it away and hid the Alpha control. A +gradient stop kept its alpha in the file, and the picker could edit it, but the stop's marker +was always drawn opaque, so a fade did not show on the handles. + +## Decision + +1. **A solid fill and a stroke carry alpha.** The colour picker (Tools squares, the Colour + panel, Properties) shows a labeled Alpha row: a slider and a percent, 0% clear, 100% + opaque. Hex may be `#rrggbb` or `#rrggbbaa`. Choosing a swatch keeps the alpha you had. + None is still no fill, not a clear one. +2. **Each gradient stop keeps its own alpha.** The ramp blends them, including through + Linear RGB (the alpha is not gamma-corrected). The stop's marker is drawn at that alpha, + and its name says the percent. +3. **A brush stroke that is not fully opaque stays its own shape, and you see that alpha + while the pen is down.** Merge drawing would cut away the colour underneath, so a wash + could not show what is behind it, and two washes of one colour would join instead of + darkening where they cross. Opaque ink still joins. Modify › Group bundles the separate + strokes. The ink drawn before the pen lifts is already that alpha, as one coverage, so + lifting does not change it. Pressure that drives opacity uses the stroke's average, the + same average the finished stroke keeps. + +## Consequences + +* An older file with no alpha byte stays opaque. +* A saved solid that omitted alpha still reads as opaque. +* Alpha 0 is a fill the hit test and the eraser can still find. Removing the fill is None. +* A wash does not join the raw drawing. Group still bundles those strokes. An opaque stroke + joins as before. diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..11e2e191 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | +| 0097 | (outside contribution) | Fill alpha | diff --git a/docs/guide/coming-from-animate.md b/docs/guide/coming-from-animate.md index 0134c835..438a0edd 100644 --- a/docs/guide/coming-from-animate.md +++ b/docs/guide/coming-from-animate.md @@ -28,7 +28,7 @@ Animator and Designer, plus your own saved workspaces and Reset. | 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. | -| 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`). | +| 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, a hex field and an alpha. A solid fill's alpha is its own (0% is a clear fill, which is not the same as no fill). The fill's picker also sets its type (None, Solid, Linear, Radial, Bitmap) and a gradient's stops, each with its own alpha, 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**. | | Find and Replace | **Edit › Find and Replace** (**Ctrl+F**). | diff --git a/docs/guide/reference/commands.md b/docs/guide/reference/commands.md index 63035678..cbbfc2e3 100644 --- a/docs/guide/reference/commands.md +++ b/docs/guide/reference/commands.md @@ -496,9 +496,9 @@ These commands have no menu item: the panels, the stage and the timeline use the - **Transform** `element.set_transform` · changes the document Parameters: `{x?, y?, sx?, sy?, rotation? (degrees)}` - **Fill Colour** `element.set_fill` · changes the document - Parameters: `{color: "#rrggbb" | null}` + Parameters: `{color: "#rrggbb" | "#rrggbbaa" | null} (the alpha is the fill's own; 00 is a clear fill, not the same as null)` - **Stroke** `element.set_stroke` · changes the document - Parameters: `{color?: "#rrggbb" | null, width?, profile?: uniform|taper_both|taper_start|taper_end|bulge|pinch | [[t, left, right], ..], cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing? (as stroke.set_style)}` + Parameters: `{color?: "#rrggbb" | "#rrggbbaa" | null, width?, profile?: uniform|taper_both|taper_start|taper_end|bulge|pinch | [[t, left, right], ..], cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing? (as stroke.set_style)}` - **Alpha** `element.set_alpha` · changes the document Parameters: `{alpha: 0..1} sets the alpha multiplier and keeps the rest of the colour effect (None becomes Alpha; Brightness and Tint become Advanced below 1)` - **Colour Effect** `element.set_color_effect` · changes the document @@ -598,7 +598,7 @@ These commands have no menu item: the panels, the stage and the timeline use the - **Movie Explorer** `explorer.tree` Parameters: `{scope?: document (default) | scene, show?: {text?, symbols?, scripts?, media?, frames? (layers and keyframes)} (each default true), definitions?: bool (the Library's symbols; default true), expanded?: [row keys] (default: the top rows), all?: bool (everything open), filter?: text (rows whose names hold it, and the rows above them), offset?, limit? (default 1000, at most 10000)} → {rows: [{key, depth, kind, type?, name, extra, frame?, children, open, go: find.goto params}], total, truncated}` - **Brush Stroke** `draw.brush` · changes the document - Parameters: `{points: [[x, y], [x, y, pressure 0..1 (clamped)] or [x, y, pressure, altitude, azimuth] (the pen's tilt in degrees: altitude 90 upright to 0 flat, azimuth the way it leans, clockwise from +x)], ..] (one point paints a dab), preset? (a brush from brush.preset_list, by key or name: its settings are the defaults for the rest), size? (stage units, default 10), shape?: round|square, angle? (degrees), roundness? (5..100 %, default 100), smoothing? (0..100, default 50), curve?: linear|soft|firm|[[pressure, output], ..] (how pressure maps, both 0..1), pressure_size? (default true: pressure varies the size from 10 to 100 %), pressure_opacity? (default false: the stroke's average pressure sets its opacity), taper_start?, taper_end? (0..50 % of the stroke's length), spacing? (0 continuous, or 5..1000 % of the size between dabs), jitter? (0..50 % of the size: a ragged edge), texture? (0..100 %: a paper grain of holes through the paint), scatter? (0..200 % of the size: dabs thrown either side of the line, varied in size), tilt_angle? (the pen's tilt turns the tip: its angle plus the azimuth), tilt_width? (the pen's tilt widens the tip, up to twice as wide flat; also the Paint Brush's width), as_stroke? (default false; true: the Paint Brush, a variable-width stroke in the stroke colour, editable with the Width tool), mode?: normal|fills|behind|selection|inside (Paint Normal covers fills and lines, Paint Fills leaves lines, Paint Behind paints only empty areas, Paint Selection only inside the selected fills, Paint Inside only inside the fill the stroke starts on or the empty area closed off around it; ADR 0080), color? (default: the fill colour, or the stroke colour as a stroke), unit? (stage units per screen point, default 1: smoothing and accuracy follow it), object?}` + Parameters: `{points: [[x, y], [x, y, pressure 0..1 (clamped)] or [x, y, pressure, altitude, azimuth] (the pen's tilt in degrees: altitude 90 upright to 0 flat, azimuth the way it leans, clockwise from +x)], ..] (one point paints a dab), preset? (a brush from brush.preset_list, by key or name: its settings are the defaults for the rest), size? (stage units, default 10), shape?: round|square, angle? (degrees), roundness? (5..100 %, default 100), smoothing? (0..100, default 50), curve?: linear|soft|firm|[[pressure, output], ..] (how pressure maps, both 0..1), pressure_size? (default true: pressure varies the size from 10 to 100 %), pressure_opacity? (default false: the stroke's average pressure sets its opacity), taper_start?, taper_end? (0..50 % of the stroke's length), spacing? (0 continuous, or 5..1000 % of the size between dabs), jitter? (0..50 % of the size: a ragged edge), texture? (0..100 %: a paper grain of holes through the paint), scatter? (0..200 % of the size: dabs thrown either side of the line, varied in size), tilt_angle? (the pen's tilt turns the tip: its angle plus the azimuth), tilt_width? (the pen's tilt widens the tip, up to twice as wide flat; also the Paint Brush's width), as_stroke? (default false; true: the Paint Brush, a variable-width stroke in the stroke colour, editable with the Width tool), mode?: normal|fills|behind|selection|inside (Paint Normal covers fills and lines, Paint Fills leaves lines, Paint Behind paints only empty areas, Paint Selection only inside the selected fills, Paint Inside only inside the fill the stroke starts on or the empty area closed off around it; ADR 0080), color? (default: the fill colour, or the stroke colour as a stroke), unit? (stage units per screen point, default 1: smoothing and accuracy follow it), object? (default the Object Drawing setting; a fill that is not fully opaque is its own shape, so it composites over what is behind it)}` - **Brush Presets** `brush.preset_list` Parameters: `{} the built-in brushes and yours, with their settings` - **Save Brush** `brush.preset_save` @@ -650,7 +650,7 @@ These commands have no menu item: the panels, the stage and the timeline use the - **Apply Style** `paint.apply_style` · changes the document Parameters: `{fill?: bool, stroke?: bool} (default both) gives the selected shapes the fill swatch's paint (shapes with a fill) and the stroke settings (shapes with a line, and drawing objects without one)` - **Fill** `paint.set_fill` · changes the document - Parameters: ``{type?: solid|linear|radial|bitmap (default: the swatch's), color? (solid), stops?: [{offset: 0..1, color: "#rrggbb" | "#rrggbbaa"}, ..] (2 to 15), spread?: extend|reflect|repeat, linear_rgb?: bool, focal?: -0.98..0.98 (radial), bitmap?: id, selection?: bool (default true)} sets the fill swatch (what new shapes, the Paint Bucket and the Brush pour) and, unless `selection` is false, the fills of the selected shapes. A shape keeping its kind of fill keeps where its gradient or bitmap lies; one changing kind gets it fitted to its bounds. A new gradient starts white to black → {fill: {type, ..}, changed}`` + Parameters: ``{type?: solid|linear|radial|bitmap (default: the swatch's), color? (solid, "#rrggbb" or "#rrggbbaa"), stops?: [{offset: 0..1, color: "#rrggbb" | "#rrggbbaa"}, ..] (2 to 15; each stop has its own alpha), spread?: extend|reflect|repeat, linear_rgb?: bool, focal?: -0.98..0.98 (radial), bitmap?: id, selection?: bool (default true)} sets the fill swatch (what new shapes, the Paint Bucket and the Brush pour) and, unless `selection` is false, the fills of the selected shapes. A shape keeping its kind of fill keeps where its gradient or bitmap lies; one changing kind gets it fitted to its bounds. A new gradient starts white to black → {fill: {type, ..}, changed}`` - **Gradient Transform** `paint.transform_fill` · changes the document Parameters: `{element?: id (default: the selected shapes with a gradient or bitmap fill), frame?: [a, b, c, d, e, f] (the fill's frame in the space being edited: the box -1..1 onto a linear gradient's span, a radial gradient's ring or one copy of a bitmap), or changes made in this order: scale_x?, scale_y?, scale? (along the frame's own axes), skew_x?, skew_y? (degrees, along its axes), rotate? (degrees, about its centre), move?: [dx, dy], center?: [x, y]; focal?: -0.98..0.98 (radial)} moves, turns, scales or skews where a gradient or bitmap fill lies, as the Gradient Transform tool (F) does → {changed, frames: [[a, b, c, d, e, f], ..]}` - **Lock Fill** `paint.lock_fill` diff --git a/docs/roadmap.md b/docs/roadmap.md index 64a84a17..00cf0733 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -11,7 +11,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | 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). | | Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients (with reflect/repeat, focal points, elliptical radials and linear RGB, ADR 0074), round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Soft masks** (ADR 0070): a mask layer's mask type is Shape (coverage), Alpha (its artwork's opacity as drawn: gradients, faded shapes, strokes, bitmaps) or Luminance (brightness × opacity, SVG's coefficients), in the CPU oracle (analytic tests), the GPU stage (parity: mean 0.00006, worst 1 step of 255), SVG export (`` with `mask-type`), Lottie (alpha and luma track mattes) and the HTML canvas; Layer Properties › Mask type. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes ``. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. Filters apply in list order and may be switched off (ADR 0091): `evaluate` leaves switched-off ones out, so every renderer and export draws them as absent. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. **Second slice** (ADR 0029): on the window's wgpu device the stage tiles are drawn straight into textures egui shows (no readback; a headless device with readback when the window is on OpenGL); **masks** (nested, united artwork), **group opacity** and **all 14 blend modes** on the GPU, same parity (max 1/255, mean ≤ 0.0011/255); 4K: 1,000 shapes in 2.1–2.4 ms, 10k shapes in 10.2 ms as stage tiles, masked scenes 7× the CPU. **Third slice** (ADR 0032): **bitmap fills** (textures uploaded once per image and cached under a 256 MB budget, sampled with the oracle's own bilinear filter, colour effect and repeat rules: byte-identical) and **all seven filters** (each filtered symbol drawn into a layer of its own and filtered by compute passes that run the oracle's resolved steps: max 1/255, mean ≤ 0.007/255) on the GPU; the shaders now build with Direct3D's FXC, so DX12 windows get the GPU stage too (parity suite green on Vulkan and DX12); software adapters are refused (the CPU is faster), the start-up self-test compares with the oracle. **The GPU is the default stage renderer**: the shell's `gpu-stage` feature is on by default, Preferences › Stage › Renderer defaults to *Graphics card (GPU)*, and the CPU draws whenever there is no usable card, a tile is past the GPU's limits (more than 16 images, filters nested deeper than 4) or anything fails. 4K: the filtered sample in 3.9 ms (CPU 31.5), 200 bitmap fills in 4.4 ms (CPU 37.2). **Fourth slice** (ADR 0048): **tile binning on the GPU** for heavy frames without masks or groups (count, prefix sum, scatter and tile-list passes, no atomics, no readback; the CPU binning stays the reference and does the rest; one tile format for both: an integer backdrop per tile and steps on the tiles' left edges): on Vulkan, 10k shapes at 4K in one texture 21.7 → 4.7 ms, 50k shapes 122 → 22.5 ms, the 50k-shape 4K stage 75 → 37 ms (Direct3D 12 keeps CPU binning: slower there in stage tiles); and **hairlines** for outline mode in both renderers (coverage by distance, one edge per segment): onion outlines on the 2,000-item stress scene as fast as tinted (GPU stage 73 → 10 ms, CPU stage 34–39 → 17 ms at 1080p). **Mid-session failures** (ADR 0092): a broken GPU stage hands the stage to the CPU at once with a status-bar notice and a log line, and is retried with a bounded backoff; driver errors on the window's device are logged instead of panicking (the #255 `Surface::configure` panic), and a lost window device autosaves and reopens the window on a safer way. Not yet: sharing a filtered layer across a frame's tiles, more than 16 images per tile, GPU binning inside masks and groups, flattening and stroking on the GPU, buffer reuse and fewer dispatches across tiles, hairlines for sub-pixel strokes, GPU exports, a GPU runner in CI; the CPU stays the oracle and the export path. | | Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, icon buttons and right-click menu) act on the whole selection; with no frame selection F5 extends every layer with frames at or after the playhead, and F5/F6/F7 move the playhead on as in Animate (F6/F7 on a keyframe key the next frame; `all_layers`/`advance` headless); drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it; a motion tween's keys stretch in proportion, ADR 0083). Side dock tab strips never run under the panel menu (names shrink with an ellipsis, then the strip scrolls). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), **timeline polish** (ADR 0061): a per-layer **onion skin toggle** column (Alt-click solos; left-out layers aren't onion-skinned; Edit Multiple Frames unaffected), the colour square toggles **View as Outlines** in the layer colour **on the stage only** (exports, Test Movie and the player draw the artwork as it is), the **colour chip** opens the layer colour (swatches, hex, More…), **onion frames of the parent timeline** dimmed around a symbol edited in place, **Layer Height** 100/200/300 %, **Layer Properties** (double-click the layer icon; name, show/lock, type, outline colour, outlines, onion, height; one undo step), **Frame View** (Tiny/Small/Normal/Medium/Large, Short rows) with the frame zoom in the timeline's bottom bar (the header fits at the default window size, tested); headless `layer.set_onion/set_color/set_height/set_properties/properties`; XFL `heightMultiplier`. Not yet: folder onion toggles, onion of deeper parent timelines, multi-layer Layer Properties and layer transparency, frame thumbnails (Preview). Keyframes, blank keyframes, insert/remove frames, classic tweens with **ease presets and custom eases** (ADR 0081: Classic Ease with a strength and Quad, Cubic, Quart, Quint, Sine, Back, Circ, Bounce and Elastic In/Out/In Out; custom eases of up to 64 Bézier points in the Custom Ease window, x kept monotonic, overshoot allowed, keyboard operable, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. **Edit Multiple Frames, complete** (ADR 0051): Cut, Copy, Paste (current frame), Paste in Place (back keyframe by keyframe, or a one-frame copy onto every keyframe between the markers), Clear, Align (Ctrl+Alt+1…6, To Stage), Rotate 90° and Flip, and **Free Transform** of the selection on every keyframe about one shared pivot (one box, one undo step per drag); raw shapes moved, transformed or pasted merge again on their own keyframe; **onion skin and Edit Multiple Frames inside a symbol edited in place**, on its own timeline and markers. Headless: `frames.transform`, `frames.align`, `frames.delete`, `frames.copy`, `frames.cut`, `frames.paste`, `frames.merge`, `merge` on `frames.edit_multiple`. Not yet: Duplicate/Distribute/Arrange and recolouring across keyframes, scaling a motion tween's object on several frames, a draggable pivot. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exports play every scene in order. **Layer folders**: nestable folders (depth ≤ 16) holding layers and masks through `Layer.parent`, one invariant (`Timeline::repair_masks`: a child sits below its parent inside the parent's unbroken run; broken links fall back to the nearest valid ancestor); hiding or locking a folder hides or locks its contents (rendering, picking, drawing); folders open and close on the timeline (view state); layers move in and out with Up/Down, a folder moves with its contents; deleting a folder deletes its contents (asks first). **Motion tweens** (ADR 0016): a span's object animated property by property (x, y, scale, colour, filters, and instance filters tween; XFL custom and per-property eases import exactly; `ease.*` headless) + curve preview, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (any preset, saved ease or custom ease of several segments, ADR 0081; overshoot allowed); auto-key turns any edit of the object inside the span into property keys (every command, through the session), F6 keys every property, splits and copies keep the motion; sky-blue spans with property-key diamonds; **Motion Editor** tab beside the timeline: property list with values at the playhead, curve graph with draggable keys and Bézier handles, one undo step per drag. **Retiming** (ADR 0083): keys drag sideways in time (snapped to frames, never past a neighbour), Shift-click picks keys across properties, an All lane picks a frame's keys, Left/Right move picked keys with the curve focused; dragging a span's end stretches a motion tween's keys in proportion (Shift keeps them); a click picks a whole motion span and dragging (or a selection of whole tween spans) moves it at its length, Alt-drag copies; **Split Motion** / **Join Motion** (split then join is exact). Headless: `motion.move_keys`, `timeline.resize_span`, `timeline.move_spans`, `motion.split`, `motion.join`. Not yet: joining two independent motion paths, retiming from a span's left edge. **Motion paths** (ADR 0030): a motion tween may carry a cubic path its object travels by arc length, timed by the X/Y curves (a straight path reproduces them exactly, overshoot included); shown on the stage in the motion colour with a dot per frame when the object or span is selected; Selection drags the path to bend it and its ends to move them, Subselection drags anchors and handles; moving the object reshapes the path; Orient to path and Straighten in Properties; splits cut the path. **Path points** (ADR 0038): with Subselection, double-click the path to add a point (shape and motion unchanged), Shift-click to select several anchors, Delete to remove them (the path refits through the rest; the ends stay), right-click for smooth/corner and Straighten; the Pen's Alt-click adds a point to a motion path or a selected shape; Ctrl-drag (⌘-drag) the path or its object, or edit Properties › Path start, to move the whole path with its timing exact. **Anchors pinned to frames** (ADR 0049): moving the object at a frame pins a path point there (a new anchor where it was put; after the last position key the path carries on), and the object passes every pinned point exactly on its frame, the X/Y eases timing it between pins; pinned points are diamonds with their frame number on the stage, blue keys in the Motion Editor's X/Y (dragging one moves its point) and holed diamonds on the timeline; Subselection's right-click pins to the playhead's frame or unpins, Properties › Frame has Pin Here / Unpin, F6 pins where the object is; point edits keep pins on their anchors; files without pins evaluate exactly as before. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient/add_point/delete_points/convert_point/move_path/pin_point/unpin_point`; `motion.info` reports `pins`). Not yet: retiming a pin by dragging its key in time, two pins on one anchor, XFL motion path keyframes, a marquee over path anchors, nudging or transforming a whole path, retiming keys, rescaling keys with the span, XFL motion-tween import. **Bones and IK, first slice** (ADR 0043): the Bone tool (M) drags from one symbol instance to another to join them with a bone on an armature layer (chains join end to start: a bone from a chained instance always starts at its joint; branches allowed, up to 256 bones); bones show as wedges in the layer colour; the Selection tool drags a bone (the grabbed point follows) or a posed instance to pose by cyclic coordinate descent (joint limits, pinned bones, one undo step per drag) and the root to move it all; poses are joint angles keyed per frame and tweened with the span's easing; Properties › Bone (angle, constrain min/max, pin, remove); `bone.*` headless; every export sees the pose. **Shape armatures** (ADR 0071): the Bone tool draws bones inside a shape (it moves to an armature layer as an object, outside merge drawing); its points are bound to the nearest bones automatically (weights by distance to each bone, up to four, summing to 1) and bend by linear blend skinning (handles with their anchors, strokes keep their width, the rest pose exact); the **Bind tool** (Shift+M) shows the points (squares, triangles where shared) and binds them by click, Shift/Ctrl-click or box; the same IK, poses and tweens; `bone.add_in_shape`, `bone.bind`, `bone.info {points}`. **Painted weights and reshaping** (ADR 0090): the Bind tool's **Paint Weights** brush (Add, Subtract, Smooth; size with `[`/`]`, strength; soft falloff) paints a bone's share onto the points under it, shown live as a heat map (blue none to red all) on the outline and points; weights stay normalised per point (the other bones share the rest, a point's only bone gives way to its nearest other bones), painted points are hand-bound, one undo step per stroke (1.15 ms for 32 dabs over 20,000 points); a focused point's weights as numbers in Properties › Bone (keyboard); Subselection edits a bound shape's outline at the rest pose (move, add, delete, smooth/corner) keeping the binding: moved points keep their weights, new points blend their neighbours', deleted points drop theirs, the rest pose exact; `bone.paint_weights`, `bone.set_weight`. **Springs, joint translation and members in place** (ADR 0084): joints slide along X/Y of what they start on, freely or within pixel limits, as part of each pose (IK slides only where turning can't reach); per-bone Spring and Damping swing bones after the motion and settle, evaluated as a pure replay of up to six seconds of motion (seeking equals playing bit for bit; 0.33 ms a frame for 16 sprung bones), shown on the stage, in Test Movie and every export, switched off per armature for posing; a picked bone's instance takes colour effect, blending and filters in place on every pose; `bone.set_translation`, `bone.set_spring`, `bone.enable_springs`. Not yet: runtime armatures, XFL import, mixing instances and shapes in one armature (proposed in ADR 0084 and 0090), reshaping at a posed frame, gravity and wind. **Asset Warp** (ADR 0079): the **Asset Warp tool** (Shift+Q) pins a shape or a bitmap (the first pin covers it with a warp mesh: a grid over its bounds, 2–48 cells along the longer side, Properties › Asset Warp); dragging a pin bends the artwork around the other pins by rigid moving least squares (Schaefer et al. 2006) at the mesh's vertices, live, one undo step per drag; Delete removes a pin; pins are added to every keyframe holding the artwork and their poses tween with classic tweens and easing; shapes bend through the mesh (straight edges exactly, curves split), bitmaps are drawn through its triangles by the CPU oracle (bilinear) and the GPU stage takes the same prepared fill (parity exact); the rest pose is the drawing bit for bit; every raster export, SVG (a bent bitmap baked as an image), Lottie and HTML (a bent bitmap reported) go through `evaluate`; `warp.add`, `warp.pin_add`, `warp.pin_move`, `warp.pin_remove`, `warp.remove`, `warp.info`. Not yet: as-rigid-as-possible solving on a mesh that follows the outline, symbols and text, binding warp pins to bones, a GPU textured-triangle path, bent bitmaps in HTML and Lottie, XFL import of warped assets. eases saved in the document and offered everywhere; copy/paste of an ease; classic tweens eased per property group: position, **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tools pause there); hiding the camera layer turns it off; every export, Test Movie and the GPU stage see it. Headless: `camera.add/remove/set/info`, `layer.set_depth`. **Camera, second slice** (ADR 0082): layer depth in a pinhole perspective (deeper layers move and zoom less, draw behind nearer ones; depth 0 bit-exact), depth keyed over time (linear between keys), **Window › Layer Depth** (layers by depth, drag nearer or farther, key, attach), **Attach Layer to Camera** (timeline toggle; HUDs stay on screen), camera colour effects (Brightness, Tint, Advanced), and the Selection tool picking and moving artwork while previewing through the camera; headless `layer.set_depth {key, frame}`, `layer.remove_depth_key`, `layer.set_attached`, `layer.depths`, `element.pick {view: camera}`. Not yet: other tools while previewing, depth inside symbols, depth keys moving with inserted frames, XFL camera and layer-depth import (no public format description). **Motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | -| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, under or over the artwork, snap accuracy up to Always); Snap to Pixels; one snap engine for every drawing tool, the Selection tool's moves and Free Transform's handles (point › guide › line › grid › pixel, guides and grid per axis); stage only, never exported, on the CPU and GPU stage. Headless: `view.rulers`, `view.grid_show/grid_snap/grid_set`, `view.guides_show/guides_lock/guides_snap/guides_set`, `view.guide_add/guide_move/guide_delete/guides_clear`, `view.snap_pixels`, `view.aids`, `moving` on `draw.snap`. *Not yet:* units other than px, a movable ruler origin, a symbol's own guides, guides and grid from Animate files, Snap Align and Edit Snapping, snapping while rotating. bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Width profiles take part in the merge since ADR 0093. **Raw points and symbols in place** (ADR 0045): add a point on a raw edge (Pen Alt-click, Subselection double-click; every shape on the edge gets it, the curve unchanged), delete raw points (Delete; the shapes on each are joined across it so the drawing stays connected; points where three edges meet are kept), Make Smooth / Corner on raw points, smooth handle pairs (Alt breaks them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap their points within 10 screen px (Snap to Objects, Ctrl+Shift+/); a double-click on an instance (or Ctrl+E, or a double-click in the Library) opens the symbol in place, the stage dimmed around it, the edit bar showing the path back, and every tool and command works on its timeline. Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth` on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`. Not yet: rotated instances in place (they open upright). Onion skin and Edit Multiple Frames work inside a symbol since ADR 0051. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. **Paint Selection and Paint Inside** (ADR 0080): the paint is clipped to the selected fills' union, or to the fill (or closed-off empty area) the stroke starts in, exactly on the planar map, then merged under the lines; Paint Selection keeps the selection for the next stroke. Not yet: the live preview clipped as it paints. **Brush library, pressure curves and the Paint Brush (Y)** (ADR 0068, first slice): Window › Brush Library with seven built-in brushes made only of parameters (Pencil, Ink Pen, Flat Calligraphy, Round Taper, Marker, Chalk with a deterministic worn edge, Dotted stamps), each with a stroke preview drawn by the renderer; brushes of your own saved by name in your preferences, renamed, deleted (asks first) and moved between computers as a JSON brush set; a pressure curve editor (Linear, Soft, Firm, or your own points) driving size and, optionally, the stroke's opacity; tapers, dab spacing and a rough edge in Properties; Velocity (mouse speed as pressure, off by default); the Paint Brush draws a width-profiled stroke in the stroke colour that the Width tool edits. Headless: `brush.preset_list/save/rename/delete/export/import`, `preset`, `curve`, `as_stroke` and the shaping params on `draw.brush`. **Tilt, texture and scatter** (ADR 0093): per-sample pen tilt (Pointer Events altitude and azimuth in `draw.brush` points) turns the tip by the azimuth and widens it up to 2× as the pen leans (Brush › Tilt: Angle, Width, shown once a pen reports tilt; the Paint Brush's width too), a fixed paper grain of holes (Texture) and dabs thrown either side (Scatter), all vector fills; built-in Charcoal and Spatter (nine brushes). Not yet: reading tilt from the pen on desktop systems (winit 0.30 reports it only on iOS), opacity varying along a stroke, bitmap or art brushes, Eraser presets and pressure. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Since ADR 0093: width-profiled lines erase and merge, each piece keeping its widths; gradient pieces keep their gradient where it was; inside an open symbol or drawing object the Eraser erases its shapes, and on the stage the status bar says how. Not yet: eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. **Colour picker and drawing-tool fixes from user reports** (M1): every colour swatch (the Tools panel's fill and stroke squares too) opens one picker with Animate's web-safe swatches (216 colours, greys and primaries), the colours mixed or typed this session, a hex field and the full mixer; the Tools squares offer No Colour and recolour selected shapes; drawing tools leave nothing selected after a stroke and the Selection tool's box has no handles (they are Free Transform's); Break Apart turns drawing objects into merged drawing; Ctrl-drag on a raw edge adds a corner point; the Pencil and Line show no fill. **Swatches panel** (ADR 0078): Window › Swatches, the document's saved colours and gradients (in the `.anicraft` file; a default set for new documents and older files); click applies to the selection and the tool colour, to the stroke or fill that is active (Tools squares, Colour panel or the panel's toggle; gradients always to the fill); + adds the active colour or gradient, Duplicate, Delete, drag (or Alt+arrows) to reorder, names on hover, Clear (keeps black and white) and Load Default Swatches (ask first, undoable); import and export as a JSON swatch file, GIMP `.gpl` import; the colour picker shows the document's swatches and the fill picker its gradient swatches. Headless: `swatch.list/add/remove/move/duplicate/rename/apply/clear/reset/import/export`. Not yet: swatch folders, sorting by colour, bitmap swatches, Save as Default, XFL swatch import (no public description), Adobe `.aco`/`.ase`/`.clr` (proprietary). The layer footer is icon buttons (New Layer, Delete, New Folder, Up, Down) that fit at any size and language. **Groups and Combine Objects** (ADR 0073): Modify › Group (Ctrl+G) / Ungroup (Ctrl+Shift+G), a group element whose members are a one-layer, one-frame timeline, opened in place by a double-click like a symbol (every tool works inside; raw shapes merge only with each other); nested groups; exports, player, sounds and the Library see inside; XFL `DOMGroup` imports as groups. Combine Objects › Union, Intersect, Punch, Crop on the planar map (analytic area tests). Selection tool: Alt-drag copies, Shift constrains to 45° (Ctrl/⌘-drag corners: #257). **Drawing parity leftovers** (ADR 0080): PolyStar's Shape (Polygon or Star), sides 3–32 and star point size 0–1 in its options (`shape`, `sides`, `point_size` on `draw.star`); a double-click (or Ctrl+E) opens a drawing object in place, its raw shapes merging only with each other, and it closes as one object again (a group of the pieces when an edit leaves several); **Modify › Transform › Envelope**: a Bézier mesh of corner and tangent handles bends the selected shapes and drawing objects, one undo step per drag, baked like Animate's (no Delete Envelope needed), undo restoring the mesh; headless `modify.envelope`, `modify.envelope_move`, `modify.envelope_close`. *Not yet:* gradient and bitmap strokes (proposed in ADR 0080), envelope handles from the keyboard, an envelope on symbols, text or groups, drawing objects edited without opening them (#181), Combine across layers. **Rulers, grid and guides** (ADR 0076): View › Rulers (stage pixels, following zoom and pan, pointer marked); guides per scene saved in the document, dragged from a ruler, moved with the Selection tool, dragged back to delete, Show/Lock/Snap/Edit/Add/Clear (Edit Guides lists and adds them from the keyboard); a grid (spacing, | +| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, under or over the artwork, snap accuracy up to Always); Snap to Pixels; one snap engine for every drawing tool, the Selection tool's moves and Free Transform's handles (point › guide › line › grid › pixel, guides and grid per axis); stage only, never exported, on the CPU and GPU stage. Headless: `view.rulers`, `view.grid_show/grid_snap/grid_set`, `view.guides_show/guides_lock/guides_snap/guides_set`, `view.guide_add/guide_move/guide_delete/guides_clear`, `view.snap_pixels`, `view.aids`, `moving` on `draw.snap`. *Not yet:* units other than px, a movable ruler origin, a symbol's own guides, guides and grid from Animate files, Snap Align and Edit Snapping, snapping while rotating. bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Width profiles take part in the merge since ADR 0093. **Raw points and symbols in place** (ADR 0045): add a point on a raw edge (Pen Alt-click, Subselection double-click; every shape on the edge gets it, the curve unchanged), delete raw points (Delete; the shapes on each are joined across it so the drawing stays connected; points where three edges meet are kept), Make Smooth / Corner on raw points, smooth handle pairs (Alt breaks them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap their points within 10 screen px (Snap to Objects, Ctrl+Shift+/); a double-click on an instance (or Ctrl+E, or a double-click in the Library) opens the symbol in place, the stage dimmed around it, the edit bar showing the path back, and every tool and command works on its timeline. Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth` on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`. Not yet: rotated instances in place (they open upright). Onion skin and Edit Multiple Frames work inside a symbol since ADR 0051. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. **Paint Selection and Paint Inside** (ADR 0080): the paint is clipped to the selected fills' union, or to the fill (or closed-off empty area) the stroke starts in, exactly on the planar map, then merged under the lines; Paint Selection keeps the selection for the next stroke. Not yet: the live preview clipped as it paints. **Brush library, pressure curves and the Paint Brush (Y)** (ADR 0068, first slice): Window › Brush Library with seven built-in brushes made only of parameters (Pencil, Ink Pen, Flat Calligraphy, Round Taper, Marker, Chalk with a deterministic worn edge, Dotted stamps), each with a stroke preview drawn by the renderer; brushes of your own saved by name in your preferences, renamed, deleted (asks first) and moved between computers as a JSON brush set; a pressure curve editor (Linear, Soft, Firm, or your own points) driving size and, optionally, the stroke's opacity; tapers, dab spacing and a rough edge in Properties; Velocity (mouse speed as pressure, off by default); the Paint Brush draws a width-profiled stroke in the stroke colour that the Width tool edits. Headless: `brush.preset_list/save/rename/delete/export/import`, `preset`, `curve`, `as_stroke` and the shaping params on `draw.brush`. **Tilt, texture and scatter** (ADR 0093): per-sample pen tilt (Pointer Events altitude and azimuth in `draw.brush` points) turns the tip by the azimuth and widens it up to 2× as the pen leans (Brush › Tilt: Angle, Width, shown once a pen reports tilt; the Paint Brush's width too), a fixed paper grain of holes (Texture) and dabs thrown either side (Scatter), all vector fills; built-in Charcoal and Spatter (nine brushes). Not yet: reading tilt from the pen on desktop systems (winit 0.30 reports it only on iOS), opacity varying along a stroke, bitmap or art brushes, Eraser presets and pressure. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Since ADR 0093: width-profiled lines erase and merge, each piece keeping its widths; gradient pieces keep their gradient where it was; inside an open symbol or drawing object the Eraser erases its shapes, and on the stage the status bar says how. Not yet: eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. **Colour picker and drawing-tool fixes from user reports** (M1): every colour swatch (the Tools panel's fill and stroke squares too) opens one picker with Animate's web-safe swatches (216 colours, greys and primaries), the colours mixed or typed this session, a hex field, an alpha (a solid fill's own, and a different one on each gradient stop) and the full mixer; the Tools squares offer No Colour and recolour selected shapes; drawing tools leave nothing selected after a stroke and the Selection tool's box has no handles (they are Free Transform's); Break Apart turns drawing objects into merged drawing; Ctrl-drag on a raw edge adds a corner point; the Pencil and Line show no fill. **Swatches panel** (ADR 0078): Window › Swatches, the document's saved colours and gradients (in the `.anicraft` file; a default set for new documents and older files); click applies to the selection and the tool colour, to the stroke or fill that is active (Tools squares, Colour panel or the panel's toggle; gradients always to the fill); + adds the active colour or gradient, Duplicate, Delete, drag (or Alt+arrows) to reorder, names on hover, Clear (keeps black and white) and Load Default Swatches (ask first, undoable); import and export as a JSON swatch file, GIMP `.gpl` import; the colour picker shows the document's swatches and the fill picker its gradient swatches. Headless: `swatch.list/add/remove/move/duplicate/rename/apply/clear/reset/import/export`. Not yet: swatch folders, sorting by colour, bitmap swatches, Save as Default, XFL swatch import (no public description), Adobe `.aco`/`.ase`/`.clr` (proprietary). The layer footer is icon buttons (New Layer, Delete, New Folder, Up, Down) that fit at any size and language. **Groups and Combine Objects** (ADR 0073): Modify › Group (Ctrl+G) / Ungroup (Ctrl+Shift+G), a group element whose members are a one-layer, one-frame timeline, opened in place by a double-click like a symbol (every tool works inside; raw shapes merge only with each other); nested groups; exports, player, sounds and the Library see inside; XFL `DOMGroup` imports as groups. Combine Objects › Union, Intersect, Punch, Crop on the planar map (analytic area tests). Selection tool: Alt-drag copies, Shift constrains to 45° (Ctrl/⌘-drag corners: #257). **Drawing parity leftovers** (ADR 0080): PolyStar's Shape (Polygon or Star), sides 3–32 and star point size 0–1 in its options (`shape`, `sides`, `point_size` on `draw.star`); a double-click (or Ctrl+E) opens a drawing object in place, its raw shapes merging only with each other, and it closes as one object again (a group of the pieces when an edit leaves several); **Modify › Transform › Envelope**: a Bézier mesh of corner and tangent handles bends the selected shapes and drawing objects, one undo step per drag, baked like Animate's (no Delete Envelope needed), undo restoring the mesh; headless `modify.envelope`, `modify.envelope_move`, `modify.envelope_close`. *Not yet:* gradient and bitmap strokes (proposed in ADR 0080), envelope handles from the keyboard, an envelope on symbols, text or groups, drawing objects edited without opening them (#181), Combine across layers. **Rulers, grid and guides** (ADR 0076): View › Rulers (stage pixels, following zoom and pan, pointer marked); guides per scene saved in the document, dragged from a ruler, moved with the Selection tool, dragged back to delete, Show/Lock/Snap/Edit/Add/Clear (Edit Guides lists and adds them from the keyboard); a grid (spacing, | | Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. **Exporter and ease plug-ins** (ADR 0088): `kind: "exporter"` declares a format (name, extension, options) and gets evaluated frames (`movie`, `frame`: the flattened display list, never the document), returning the file's bytes from `ac_export` (64 MiB cap, 5·10¹⁰ instructions, 10 min); File › Export lists it with an Export window (options, frames, file, progress bar and Cancel on a worker thread); `file.export_plugin`, `file.export_formats`, `anicraft-cli export --format ` and `formats`. `kind: "ease"` declares named eases, `ac_ease(i, t)` sampled into 257 values at load (NaN, unbounded or end-missing eases refused); `Easing::Sampled` keeps the table in the document, so it plays the same without the plug-in; the ease menus list them under Plug-in eases; `{plugin, ease}` easing params. Samples: Plain Text Frames and Stepped Eases, built and run in CI. Not yet: plug-in formats in Publish, bitmaps' pixels and sounds for exporters, ease plug-ins with parameters, background runs of command plug-ins, a binary document view. | | Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. **A window of its own on the desktop** (ADR 0062): sized to the stage at 100 % (smaller to fit the screen), titled with the document, back where it was last (not on Wayland, where the desktop places windows), with the keyboard when it opens; Esc or Ctrl+W (⌘W) closes it, Ctrl+Enter restarts it in place, and the editor's Ctrl/Alt shortcuts work from it; floating inside the editor in the web build, where the system can't open windows (it says so), or by choice in Preferences › Test Movie. Not yet: full screen, zoom in the movie window, remembering its size. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; **filters and Subtract/Invert in the page** (ADR 0072: `filters.js`, a port of the renderer's filters run over the group's pixels on a layer that reaches past the canvas by the filters' reach, Subtract and Invert composited per pixel, results kept while the group is unchanged; equal to the oracle's pixels within 9.3e-4 in Boa; 3.4 ms a frame for the demo's filters at 1080p while they change); Web Audio for Event/Start/Stop/Stream sounds; bitmap tints, 9-slice scaling and plug-in frame scripts reported. Not yet: 9-slice in the page, keeping a moving filtered group's pixels, filters off the main thread. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. **Buttons, complete** (ADR 0057): a button open in place names its frames Up, Over, Down and Hit on the timeline and shows its Hit area translucent over the other states; Test Movie has **Show hit areas**; sounds on its frames play as its state changes. | | Headless | CLI: info, render, render-seq, **gif**, **apng**, **webp**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. | diff --git a/src/brushtool.rs b/src/brushtool.rs index 9a3c85dd..2a537c62 100644 --- a/src/brushtool.rs +++ b/src/brushtool.rs @@ -343,6 +343,37 @@ fn hull(mut pts: Vec) -> Vec { /// Most preview pieces drawn per frame (a long stroke skips samples in the preview only). const MAX_PREVIEW: usize = 4000; +/// Longest side of the live-alpha coverage image, in pixels. A stroke larger than this is +/// drawn softer rather than uploading a full-screen texture every move. +const MASK_MAX: usize = 2048; + +/// The alpha the finished stroke will have: the fill (or the stroke colour) times, when +/// pressure drives opacity, the average mapped pressure so far. That average is what the +/// command stores for the whole stroke (ADR 0068). +fn intended_alpha(o: &BrushOptions, paint_a: f32, samples: &[(Vec2, Option)]) -> f32 { + let paint_a = if paint_a.is_finite() { paint_a.clamp(0.0, 1.0) } else { 1.0 }; + if !o.pressure_opacity || samples.is_empty() { + return paint_a; + } + // The same stand-in `points` sends for a sample that is still waiting on a reading. + let Some(first) = samples.iter().find_map(|(_, p)| *p) else { return paint_a }; + let mut prev = first; + let mut seen = false; + let mut sum = 0.0f32; + for (_, p) in samples { + let p = if let Some(p) = *p { + seen = true; + prev = p; + p + } else if !seen { + first + } else { + prev + }; + sum += o.curve.map(p); + } + paint_a * (sum / samples.len() as f32).clamp(0.05, 1.0) +} /// The paint as it goes (each pair of samples is the hull of the tip at both, so the union is /// what the stroke covers before smoothing), and the tip under the pointer. @@ -354,9 +385,16 @@ pub fn draw_overlay(app: &App, painter: &egui::Painter, xf: Xf, hover: Option= 255.0 { + let color = to_color32(anicraft_engine::doc::Rgba { a: 1.0, ..paint }); + draw_sweep(painter, xf, &tip, &app.brush_samples, color); + } else { + draw_sweep_alpha(painter, xf, &tip, &app.brush_samples, paint, alpha); + } } if let Some(h) = hover { // The tip's size and shape at the pointer, as Animate shows it. @@ -387,6 +425,173 @@ pub fn draw_sweep(painter: &egui::Painter, xf: Xf, o: &BrushOptions, samples: &[ } } +/// The tip's outline at each step, in screen points (the union is the stroke's coverage). +fn sweep_hulls(xf: Xf, o: &BrushOptions, samples: &[(Vec2, Option)]) -> Vec> { + if samples.is_empty() { + return Vec::new(); + } + let unit = o.unit_outline(); + let screen = |at: Vec2, pressure: Option| -> Vec { + let m = o.tip_to_stage(at, o.factor(pressure)); + unit.iter().map(|u| xf.to_screen(m.apply(*u))).collect() + }; + let step = samples.len().div_ceil(MAX_PREVIEW).max(1); + let picked: Vec<&(Vec2, Option)> = samples.iter().step_by(step).chain(samples.last()).collect(); + let mut hulls = Vec::new(); + let mut push = |pts: Vec| { + let h = hull(pts); + if h.len() >= 3 { + hulls.push(h); + } + }; + if let [only] = picked.as_slice() { + push(screen(only.0, only.1)); + } + for pair in picked.windows(2) { + let &[a, b] = pair else { continue }; + let mut pts = screen(a.0, a.1); + pts.extend(screen(b.0, b.1)); + push(pts); + } + hulls +} + +/// The same sweep as one coverage image, tinted at `alpha`. Overlapping pieces keep the +/// greater coverage, so a crossing in one stroke stays one alpha. +fn draw_sweep_alpha(painter: &egui::Painter, xf: Xf, o: &BrushOptions, samples: &[(Vec2, Option)], paint: anicraft_engine::doc::Rgba, alpha: f32) { + if alpha <= 0.0 { + return; + } + let hulls = sweep_hulls(xf, o, samples); + if hulls.is_empty() { + return; + } + let mut bounds = egui::Rect::NOTHING; + for hull in &hulls { + for p in hull { + bounds.extend_with(*p); + } + } + let view = bounds.expand(1.0).intersect(painter.clip_rect()); + if !view.is_positive() || !view.width().is_finite() || !view.height().is_finite() { + return; + } + let ppp = painter.pixels_per_point(); + let mut scale = if ppp.is_finite() && ppp > 0.0 { ppp } else { 1.0 }; + let long = view.width().max(view.height()) * scale; + if long > MASK_MAX as f32 && long.is_finite() { + scale *= MASK_MAX as f32 / long; + } + let w = (view.width() * scale).round(); + let h = (view.height() * scale).round(); + if !w.is_finite() || !h.is_finite() || w < 1.0 || h < 1.0 { + return; + } + let w = (w as usize).clamp(1, MASK_MAX); + let h = (h as usize).clamp(1, MASK_MAX); + let cov = coverage(&hulls, view.min, scale, w, h); + let mut pixels = Vec::with_capacity(w.saturating_mul(h)); + for c in cov { + let a = (c.clamp(0.0, 1.0) * 255.0).round() as u8; + pixels.push(egui::Color32::from_white_alpha(a)); + } + let image = egui::ColorImage::new([w, h], pixels); + let tex = sweep_texture(painter.ctx(), image); + let tint = to_color32(anicraft_engine::doc::Rgba { a: alpha, ..paint }); + painter.image(tex.id(), view, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), tint); +} + +/// One reused texture for the live wash, so a stroke does not leak a texture every frame. +fn sweep_texture(ctx: &egui::Context, image: egui::ColorImage) -> egui::TextureHandle { + let id = egui::Id::new("anicraft.brush.sweep"); + let options = egui::TextureOptions::LINEAR; + if let Some(mut tex) = ctx.data(|d| d.get_temp::(id)) { + tex.set(image, options); + tex + } else { + let tex = ctx.load_texture("brush-sweep", image, options); + ctx.data_mut(|d| d.insert_temp(id, tex.clone())); + tex + } +} + +/// Coverage in `0..=1`, one value per pixel. A pixel covered more than once keeps the greater +/// value, so the stroke is one alpha. +fn coverage(hulls: &[Vec], origin: Pos2, scale: f32, w: usize, h: usize) -> Vec { + let mut cov = vec![0.0f32; w.saturating_mul(h)]; + let view = egui::Rect::from_min_size(origin, egui::vec2(w as f32 / scale, h as f32 / scale)); + for hull in hulls { + if hull.len() < 3 || !hull_hits(hull, view) { + continue; + } + fill_convex(&mut cov, w, h, hull, origin, scale); + } + cov +} + +fn hull_hits(poly: &[Pos2], view: egui::Rect) -> bool { + let mut b = egui::Rect::NOTHING; + for p in poly { + if p.x.is_finite() && p.y.is_finite() { + b.extend_with(*p); + } + } + b.intersects(view) +} + +/// Scan-converts one convex polygon into `cov` (pixel rows are the image, y down). +fn fill_convex(cov: &mut [f32], w: usize, h: usize, poly: &[Pos2], origin: Pos2, scale: f32) { + let pts: Vec<(f32, f32)> = poly.iter().filter(|p| p.x.is_finite() && p.y.is_finite()).map(|p| ((p.x - origin.x) * scale, (p.y - origin.y) * scale)).collect(); + if pts.len() < 3 || !scale.is_finite() || scale <= 0.0 { + return; + } + let (mut top, mut bot) = (f32::MAX, f32::MIN); + for (_, y) in &pts { + top = top.min(*y); + bot = bot.max(*y); + } + if !top.is_finite() || !bot.is_finite() { + return; + } + let iy0 = (top.floor() as i32).max(0); + let iy1 = (bot.ceil() as i32).min(h as i32); + let n = pts.len(); + for iy in iy0..iy1 { + let y = iy as f32 + 0.5; + let mut left = f32::MAX; + let mut right = f32::MIN; + for i in 0..n { + let (x0, y0) = pts[i]; + let (x1, y1) = pts[(i + 1) % n]; + // The scanline crosses the edge. A vertex on the scanline counts once. + if !((y0 <= y && y1 > y) || (y1 <= y && y0 > y)) { + continue; + } + let t = (y - y0) / (y1 - y0); + let x = x0 + (x1 - x0) * t; + if !x.is_finite() { + continue; + } + left = left.min(x); + right = right.max(x); + } + // No crossing, or a crossing thinner than a pixel. Non-finite x was skipped above. + if right <= left { + continue; + } + let ix0 = (left.floor() as i32).max(0); + let ix1 = (right.ceil() as i32).min(w as i32); + for ix in ix0..ix1 { + let x0 = ix as f32; + let span = (right.min(x0 + 1.0) - left.max(x0)).clamp(0.0, 1.0); + let Some(slot) = cov.get_mut(iy as usize * w + ix as usize) else { continue }; + if span > *slot { + *slot = span; + } + } + } +} + /// The tip's outline at stage point `at`. pub fn draw_tip(painter: &egui::Painter, xf: Xf, o: &BrushOptions, at: Vec2) { let m = o.tip_to_stage(at, 1.0); @@ -449,4 +654,28 @@ mod tests { let h = hull(vec![Pos2::new(0.0, 0.0), Pos2::new(1.0, 0.0), Pos2::new(0.5, 0.2), Pos2::new(1.0, 1.0), Pos2::new(0.0, 1.0), Pos2::new(0.0, 0.0)]); assert_eq!(h.len(), 4, "{h:?}"); } + + #[test] + fn the_preview_alpha_is_the_fill_times_the_pressure_average() { + let mut o = BrushOptions::default(); + let samples = [(Vec2::ZERO, Some(0.25)), (Vec2::new(10.0, 0.0), Some(0.25))]; + assert!((intended_alpha(&o, 0.5, &samples) - 0.5).abs() < 1e-5, "pressure off leaves the fill"); + o.pressure_opacity = true; + assert!((intended_alpha(&o, 1.0, &samples) - 0.25).abs() < 1e-3, "the average so far"); + assert!((intended_alpha(&o, 0.5, &samples) - 0.125).abs() < 1e-3, "fill alpha times that average"); + let light = [(Vec2::ZERO, Some(0.0))]; + assert!((intended_alpha(&o, 1.0, &light) - 0.05).abs() < 1e-3, "the same floor as the command"); + } + + #[test] + fn a_wash_preview_is_one_coverage_where_the_pieces_overlap() { + let square = |x: f32, y: f32| vec![Pos2::new(x, y), Pos2::new(x + 10.0, y), Pos2::new(x + 10.0, y + 10.0), Pos2::new(x, y + 10.0)]; + let cov = coverage(&[square(0.0, 0.0), square(4.0, 4.0)], Pos2::ZERO, 1.0, 16, 16); + let at = |x: usize, y: usize| cov[y * 16 + x]; + assert!(at(2, 2) > 0.99, "inside the first square"); + assert!(at(12, 2) < 0.01, "outside both"); + assert!(at(6, 6) > 0.99 && at(6, 6) <= 1.0, "the overlap stays one coverage, not two: {}", at(6, 6)); + let edge = coverage(&[vec![Pos2::new(0.5, 0.0), Pos2::new(10.0, 0.0), Pos2::new(10.0, 10.0), Pos2::new(0.5, 10.0)]], Pos2::ZERO, 1.0, 12, 12); + assert!((edge[5 * 12] - 0.5).abs() < 0.05, "the cut pixel is a partial: {}", edge[5 * 12]); + } } diff --git a/src/colour.rs b/src/colour.rs index 5f322867..287d8f9b 100644 --- a/src/colour.rs +++ b/src/colour.rs @@ -1,6 +1,7 @@ //! Colour swatches and the colour picker (#201, #246, #248), as Animate's swatch popup: a click //! on a swatch opens the web-safe palette with the colours used lately below it, a hex field, -//! and the full mixer (hue, saturation and value, alpha) one click away. +//! and, when the colour has opacity, an Alpha row (0 % clear, 100 % opaque). The mixer +//! (hue, saturation and value) is one click away. //! //! The 216 web-safe colours are the open standard cube (each channel 00, 33, 66, 99, CC or FF), //! laid out as the usual six-by-six blocks: red steps across the blocks, green down a block and @@ -230,15 +231,31 @@ pub(crate) fn picker(ui: &mut egui::Ui, popup: Id, c: &mut [u8; 4], alpha: bool, remember(ui.ctx(), popup, [h[0], h[1], h[2]]); changed = true; } - if alpha { + }); + // Its own row, with the word on it. A bare percent beside the hex does not read as opacity. + if alpha { + ui.add_space(4.0); + ui.horizontal(|ui| { + let tip = tr!("Alpha: 0 % is clear, 100 % opaque"); + ui.label(tr!("Alpha")).on_hover_text(tip); let mut pct = f32::from(c[3]) / 255.0 * 100.0; - let r = with_type(ui, Type::Data, |ui| ui.add(egui::DragValue::new(&mut pct).range(0.0..=100.0).suffix(" %").max_decimals(0))).named(tr!("Alpha")); - if r.on_hover_text(tr!("Alpha: 0 % is clear, 100 % opaque")).changed() { + ui.spacing_mut().slider_width = 148.0; + // The theme's slider rail is the popup's own colour, so the bar would vanish into it. + let name = tr!("Alpha"); + let bar = ui.scope(|ui| { + let v = ui.visuals_mut(); + v.widgets.inactive.bg_fill = T.hover; + v.selection.bg_fill = T.accent; + ui.add(egui::Slider::new(&mut pct, 0.0..=100.0).show_value(false)) + }).inner.named(name); + let num = with_type(ui, Type::Data, |ui| ui.add(egui::DragValue::new(&mut pct).range(0.0..=100.0).suffix(" %").max_decimals(0).speed(0.5))).named(name); + let r = bar.union(num); + if r.on_hover_text(tip).changed() { c[3] = (pct.clamp(0.0, 100.0) / 100.0 * 255.0).round() as u8; changed = true; } - } - }); + }); + } changed } diff --git a/src/colour_panel.rs b/src/colour_panel.rs index 1b84d5e9..3fdd60bc 100644 --- a/src/colour_panel.rs +++ b/src/colour_panel.rs @@ -26,8 +26,8 @@ const BAR_WIDTH: f32 = 270.0; /// What the fill picker asks for. #[derive(Clone, Debug, PartialEq)] pub enum FillEdit { - /// A solid colour (opaque). - Solid([u8; 3]), + /// A solid colour, unmultiplied, alpha in the last byte. 0 is a clear fill, not "no fill". + Solid([u8; 4]), /// No fill (true), or a fill again (false). None(bool), /// `paint.set_fill` params, with its undo label; `live` while a drag or typing goes on (one @@ -162,7 +162,7 @@ pub fn popup_for(ui: &egui::Ui, anchor: &Response, popup: Id, paint: Option<&Pai fn kinds() -> [(&'static str, &'static str, &'static str); 5] { [ ("none", tr!("None"), tr!("No fill")), - ("solid", tr!("Solid"), tr!("Solid colour")), + ("solid", tr!("Solid"), tr!("A solid colour, from clear to opaque")), ("linear", tr!("Linear"), tr!("Linear gradient: colours along a line")), ("radial", tr!("Radial"), tr!("Radial gradient: colours out from a centre")), ("bitmap", tr!("Bitmap"), tr!("Bitmap fill: a Library image, tiled")), @@ -200,7 +200,7 @@ pub fn fill_picker(ui: &mut egui::Ui, popup: Id, paint: Option<&Paint>, bitmaps: "solid" => match paint { // A fill again: the colour it shows. None => FillEdit::None(false), - Some(p) => FillEdit::Set { label: tr_noop!("Fill"), live: false, params: json!({"type": "solid", "color": hex(p.primary_color().with_alpha(1.0))}) }, + Some(p) => FillEdit::Set { label: tr_noop!("Fill"), live: false, params: json!({"type": "solid", "color": hex(p.primary_color())}) }, }, "bitmap" => FillEdit::Set { label: tr_noop!("Fill"), live: false, params: json!({"type": "bitmap", "bitmap": bitmaps.first().map_or(0, |b| b.0)}) }, other => FillEdit::Set { label: tr_noop!("Fill"), live: false, params: json!({"type": other}) }, @@ -213,7 +213,7 @@ pub fn fill_picker(ui: &mut egui::Ui, popup: Id, paint: Option<&Paint>, bitmaps: } Some(Paint::Solid(c)) => { let mut px = bytes(*c); - crate::colour::picker(ui, popup, &mut px, false, None).then_some(FillEdit::Solid([px[0], px[1], px[2]])) + crate::colour::picker(ui, popup, &mut px, true, None).then_some(FillEdit::Solid(px)) } Some(Paint::Linear { stops, spread, linear_rgb, .. }) => gradient(ui, popup, stops, *spread, *linear_rgb, None), Some(Paint::Radial { stops, spread, linear_rgb, focal, .. }) => gradient(ui, popup, stops, *spread, *linear_rgb, Some(*focal)), @@ -405,7 +405,8 @@ fn stop_bar(ui: &mut egui::Ui, popup: Id, stops: &mut Vec) -> Opti let hit = Rect::from_center_size(pos2(x, track.center().y), vec2(12.0, 14.0)); let r = ui.interact(hit, popup.with(("fill_stop_marker", i)), Sense::click_and_drag()); let at = format!("{:.0}", off * 100.0); - a11y::control(ui, &r, WidgetType::Button, &tr!("Colour stop {stop} of {count} at {at}%", stop = i + 1, count = count, at = at), Some(i == sel)); + let alpha = stops.get(i).map(|s| format!("{:.0}", s.color.sanitized().a * 100.0)).unwrap_or_else(|| "100".into()); + a11y::control(ui, &r, WidgetType::Button, &tr!("Colour stop {stop} of {count} at {at}%, alpha {alpha}%", stop = i + 1, count = count, at = at, alpha = alpha), Some(i == sel)); if r.clicked() || r.drag_started() || r.gained_focus() { sel = i; } @@ -445,7 +446,9 @@ fn stop_bar(ui: &mut egui::Ui, popup: Id, stops: &mut Vec) -> Opti let tip = pos2(x, track.top()); let body = [tip, pos2(x + 6.0, track.top() + 6.0), pos2(x + 6.0, track.bottom()), pos2(x - 6.0, track.bottom()), pos2(x - 6.0, track.top() + 6.0)]; let edge = if i == sel { T.accent } else if r.hovered() { T.text } else { T.control_edge }; - let fill = to_color32(st.color.with_alpha(if torn { 0.3 } else { 1.0 })); + // The marker shows that stop's own alpha, so a fade along the ramp is visible on the handles. + let shown = st.color.sanitized(); + let fill = to_color32(shown.with_alpha(shown.a * if torn { 0.35 } else { 1.0 })); ui.painter().add(egui::Shape::convex_polygon(body.to_vec(), fill, Stroke::new(if i == sel { 2.0 } else { 1.0 }, edge))); } ui.data_mut(|d| match tearing { @@ -599,7 +602,7 @@ mod tests { assert!(matches!(app.s.style.fill_paint, Some(Paint::Linear { .. }))); // Solid and None are the caller's: apply_set leaves them alone. let before = app.s.doc.clone(); - apply_set(&mut app, &FillEdit::Solid([1, 2, 3]), true); + apply_set(&mut app, &FillEdit::Solid([1, 2, 3, 255]), true); apply_set(&mut app, &FillEdit::None(true), true); assert!(app.s.doc == before); // The whole window draws with the Tools square's picker open on the selection's gradient, @@ -613,4 +616,31 @@ mod tests { assert_eq!(stops_json(&[stop(0.0, 0xff0000)])[0]["color"], "#ff0000"); assert_eq!(from_bytes(bytes(Rgba::new(1.0, 0.0, 0.0, 0.5))).a, 128.0 / 255.0); } + + /// A solid fill keeps the alpha it was given, a gradient keeps a different alpha on each + /// stop, and the open fill picker names an Alpha control for either. + #[test] + fn a_fill_keeps_its_alpha_and_the_picker_names_it() { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let mut app = App::with_context(&ctx, anicraft_engine::Session::default(), Some(PathBuf::from("unused.png"))); + app.run("draw.rect", json!({"x": 10, "y": 10, "w": 40, "h": 30, "fill": "#ff000080", "stroke": null})); + let Paint::Solid(c) = current(&app).0 else { panic!("a solid fill"); }; + assert!((c.a - 128.0 / 255.0).abs() < 1e-3, "{c:?}"); + app.run("paint.set_fill", json!({"type": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff00"}]})); + let paint = current(&app).0; + let stops = paint.stops().expect("a gradient"); + assert!((stops[0].color.a - 1.0).abs() < 1e-3 && stops[1].color.a < 1e-3, "{stops:?}"); + app.run("paint.set_fill", json!({"type": "solid", "color": "#3d8bfd80"})); + app.tool = Tool::Select; + app.open_fill_swatch = true; + let mut labels = String::new(); + for _ in 0..4 { + let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 940.0))), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| app.frame(ui)); + out.textures_delta.clear(); + labels = out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().filter_map(|(_, n)| n.label().map(str::to_string)).collect::>().join("\n")).unwrap_or_default(); + } + assert!(labels.contains("Alpha"), "the fill picker has no Alpha control:\n{labels}"); + } } diff --git a/src/panels.rs b/src/panels.rs index ea88621d..bf55766e 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -174,7 +174,7 @@ fn tool_swatches(app: &mut App, ui: &mut egui::Ui) { for (fill, resp) in [(true, fill_resp), (false, stroke_resp)] { let name = if fill { tr!("Fill colour") } else { tr!("Stroke colour") }; a11y::control(ui, &resp, WidgetType::ColorButton, name, None); - let resp = resp.on_hover_text(if fill { tr!("Fill colour: click to pick the colour shapes are filled with") } else { tr!("Stroke colour: click to pick the colour of lines and outlines") }); + let resp = resp.on_hover_text(if fill { tr!("Fill colour: click to pick the colour and how clear it is. Each stop of a gradient has its own.") } else { tr!("Stroke colour: click to pick the colour and how clear it is") }); // As in Animate, the square clicked last is the one swatches set (ADR 0078). if resp.clicked() { app.colour_target = if fill { crate::swatches_panel::ColourTarget::Fill } else { crate::swatches_panel::ColourTarget::Stroke }; @@ -193,7 +193,7 @@ fn tool_swatches(app: &mut App, ui: &mut egui::Ui) { let shown = (selected || st.use_fill).then_some(paint); match crate::colour_panel::popup_for(ui, &resp, resp.id.with("colour_popup"), shown.as_ref(), &crate::colour_panel::bitmaps(app)) { Some(crate::colour_panel::FillEdit::Solid(p)) => { - c = [p[0], p[1], p[2], 255]; + c = p; none = false; true } @@ -209,12 +209,12 @@ fn tool_swatches(app: &mut App, ui: &mut egui::Ui) { None => false, } } else { - crate::colour::popup_for(ui, &resp, resp.id.with("colour_popup"), &mut c, false, Some(&mut none)) + crate::colour::popup_for(ui, &resp, resp.id.with("colour_popup"), &mut c, true, Some(&mut none)) }; if picked { // No Colour toggled says which; a colour picked turns the colour back on. let none = none != was && none; - let pick = Rgba::new(f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, 1.0); + let pick = Rgba::new(f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, f32::from(c[3]) / 255.0); let style = &mut app.s.style; if fill { style.use_fill = !none; @@ -230,7 +230,7 @@ fn tool_swatches(app: &mut App, ui: &mut egui::Ui) { // Selected shapes take it too (one undo step for a drag in the mixer). let shapes = app.s.selected_elements().iter().any(|(_, e)| matches!(e.kind, ElementKind::Shape(_))); if shapes { - let colour = if none { Value::Null } else { json!(hex([c[0], c[1], c[2]])) }; + let colour = if none { Value::Null } else { json!(crate::colour::to_hex(c, true)) }; let (label, id, p) = if fill { (tr_noop!("Fill colour"), "element.set_fill", json!({"color": colour})) } else { (tr_noop!("Stroke colour"), "element.set_stroke", json!({"color": colour})) }; live(app, label, id, p); } @@ -249,8 +249,9 @@ fn fill_kind_label(p: Option<&Paint>) -> Option<&'static str> { } fn rgba(c: Rgba) -> [u8; 4] { - let [r, g, b] = rgb(c); - [r, g, b, 255] + let c = c.sanitized(); + let b = |v: f32| (v * 255.0).round() as u8; + [b(c.r), b(c.g), b(c.b), b(c.a)] } // ----- edit bar & status ------------------------------------------------------------------ @@ -480,25 +481,25 @@ fn row_prose(ui: &mut egui::Ui, label: &str, add: impl FnOnce(&mut egui::Ui)) { /// White as in Animate. pub(crate) fn colour_panel(app: &mut App, ui: &mut egui::Ui) { let mut st = app.s.style.clone(); - let to_rgba = |c: [u8; 3]| Rgba::new(f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, 1.0); - let (mut stroke, mut fill) = (rgb(st.stroke), rgb(st.fill)); + let to_rgba = |c: [u8; 4]| Rgba::new(f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, f32::from(c[3]) / 255.0); + let (mut stroke, mut fill) = (rgba(st.stroke), rgba(st.fill)); let (mut stroke_changed, mut fill_changed) = (false, false); let mut target = app.colour_target; row(ui, tr!("Stroke"), |ui| { - let r = crate::colour::button(ui, &mut stroke).named(tr!("Stroke colour")); + let r = crate::colour::button_alpha(ui, &mut stroke).named(tr!("Stroke colour")); if r.clicked() { target = crate::swatches_panel::ColourTarget::Stroke; } stroke_changed = r.changed(); - ui.label(text(Type::Data, hex(stroke)).color(T.text_dim)); + ui.label(text(Type::Data, crate::colour::to_hex(stroke, true)).color(T.text_dim)); }); row(ui, tr!("Fill"), |ui| { - let r = crate::colour::button(ui, &mut fill).named(tr!("Fill colour")); + let r = crate::colour::button_alpha(ui, &mut fill).named(tr!("Fill colour")); if r.clicked() { target = crate::swatches_panel::ColourTarget::Fill; } fill_changed = r.changed(); - ui.label(text(Type::Data, hex(fill)).color(T.text_dim)); + ui.label(text(Type::Data, crate::colour::to_hex(fill, true)).color(T.text_dim)); }); let mut undo = tr_noop!("Colour"); ui.horizontal_wrapped(|ui| { @@ -507,7 +508,7 @@ pub(crate) fn colour_panel(app: &mut App, ui: &mut egui::Ui) { (stroke_changed, fill_changed, undo) = (true, true, tr_noop!("Swap Colours")); } if ui.button(tr!("Black and White")).on_hover_text(tr!("A black stroke and a white fill")).clicked() { - (stroke, fill) = ([0, 0, 0], [255, 255, 255]); + (stroke, fill) = ([0, 0, 0, 255], [255, 255, 255, 255]); (stroke_changed, fill_changed, undo) = (true, true, tr_noop!("Black and White")); } }); @@ -526,10 +527,10 @@ pub(crate) fn colour_panel(app: &mut App, ui: &mut egui::Ui) { app.s.style = st; if !app.s.selection.is_empty() { if stroke_changed { - live(app, undo, "element.set_stroke", json!({"color": hex(stroke)})); + live(app, undo, "element.set_stroke", json!({"color": crate::colour::to_hex(stroke, true)})); } if fill_changed { - live(app, undo, "element.set_fill", json!({"color": hex(fill)})); + live(app, undo, "element.set_fill", json!({"color": crate::colour::to_hex(fill, true)})); } } } @@ -1022,22 +1023,22 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E let fill = sh.fill.as_ref().map(Paint::primary_color); let bitmaps = crate::colour_panel::bitmaps(app); row(ui, tr!("Fill"), |ui| { - let c = rgb(fill.unwrap_or(Rgba::WHITE)); + let c = fill.unwrap_or(Rgba::WHITE); // The one colour picker, with the fill's type (ADR 0074): a gradient shows as its // ramp here and is edited in the picker. let (r, edit) = crate::colour_panel::swatch(ui, sh.fill.as_ref(), &bitmaps); - r.named(tr!("Fill colour")).on_hover_text(tr!("Fill: click for its colour, or a gradient or bitmap fill")); + r.named(tr!("Fill colour")).on_hover_text(tr!("Fill: click for its colour and how clear it is, or a gradient or bitmap fill")); match edit { - Some(crate::colour_panel::FillEdit::Solid(p)) => live(app, tr_noop!("Fill colour"), "element.set_fill", json!({"color": hex(p)})), + Some(crate::colour_panel::FillEdit::Solid(p)) => live(app, tr_noop!("Fill colour"), "element.set_fill", json!({"color": crate::colour::to_hex(p, true)})), Some(crate::colour_panel::FillEdit::None(n)) => { - app.run("element.set_fill", if n { json!({"color": null}) } else { json!({"color": hex(c)}) }); + app.run("element.set_fill", if n { json!({"color": null}) } else { json!({"color": crate::colour::to_hex(rgba(c), true)}) }); } Some(edit) => crate::colour_panel::apply_set(app, &edit, true), None => {} } let mut on = fill.is_some(); if crate::theme::checkbox(ui, &mut on, "").named(tr!("Fill")).on_hover_text(tr!("Fill on/off")).changed() { - app.run("element.set_fill", if on { json!({"color": hex(c)}) } else { json!({"color": null}) }); + app.run("element.set_fill", if on { json!({"color": crate::colour::to_hex(rgba(c), true)}) } else { json!({"color": null}) }); } if let Some(what) = fill_kind_label(sh.fill.as_ref()) { ui.label(text(Type::Caption, what)); @@ -1047,11 +1048,11 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E if let Some(Paint::Bitmap { bitmap, .. }) = &sh.fill { bitmap_row(app, ui, *bitmap, m.bitmap); } - let mut sc = rgb(sh.stroke.as_ref().map_or(app.s.style.stroke, |s| s.color)); + let mut sc = rgba(sh.stroke.as_ref().map_or(app.s.style.stroke, |s| s.color)); let mut sw = sh.stroke.as_ref().map_or(0.0, |s| s.width); row(ui, tr!("Stroke"), |ui| { - if crate::colour::button(ui, &mut sc).named(tr!("Stroke colour")).changed() { - live(app, tr_noop!("Stroke colour"), "element.set_stroke", json!({"color": hex(sc)})); + if crate::colour::button_alpha(ui, &mut sc).named(tr!("Stroke colour")).on_hover_text(tr!("Stroke colour: click to pick the colour and how clear it is")).changed() { + live(app, tr_noop!("Stroke colour"), "element.set_stroke", json!({"color": crate::colour::to_hex(sc, true)})); } if ui.add(egui::DragValue::new(&mut sw).suffix(" px").speed(0.1).range(0.0..=200.0).max_decimals(1)).named(tr!("Stroke width")).changed() { live(app, tr_noop!("Stroke width"), "element.set_stroke", json!({"width": sw})); @@ -2567,10 +2568,10 @@ fn tool_props(app: &mut App, ui: &mut egui::Ui) { // colour picker with the fill's type (ADR 0074). let paint = st.fill_paint(); let (r, edit) = crate::colour_panel::swatch(ui, (st.use_fill || fills).then_some(&paint), &bitmaps); - r.named(tr!("Fill colour")).on_hover_text(tr!("Fill: click for its colour, or a gradient or bitmap fill")); + r.named(tr!("Fill colour")).on_hover_text(tr!("Fill: click for its colour and how clear it is, or a gradient or bitmap fill")); match edit { Some(crate::colour_panel::FillEdit::Solid(p)) => { - st.set_fill_color(Rgba::new(f32::from(p[0]) / 255.0, f32::from(p[1]) / 255.0, f32::from(p[2]) / 255.0, 1.0)); + st.set_fill_color(Rgba::new(f32::from(p[0]) / 255.0, f32::from(p[1]) / 255.0, f32::from(p[2]) / 255.0, f32::from(p[3]) / 255.0)); st.use_fill = true; } Some(crate::colour_panel::FillEdit::None(n)) => st.use_fill = !n || fills, @@ -2593,9 +2594,9 @@ fn tool_props(app: &mut App, ui: &mut egui::Ui) { } if !fills { row(ui, tr!("Stroke"), |ui| { - let mut c = rgb(st.stroke); - if crate::colour::button(ui, &mut c).named(tr!("Stroke colour")).changed() { - st.stroke = Rgba::new(c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0, 1.0); + let mut c = rgba(st.stroke); + if crate::colour::button_alpha(ui, &mut c).named(tr!("Stroke colour")).on_hover_text(tr!("Stroke colour: click to pick the colour and how clear it is")).changed() { + st.stroke = Rgba::new(f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, f32::from(c[3]) / 255.0); } if !ink { crate::theme::checkbox(ui, &mut st.use_stroke, "").named(tr!("Stroke")).on_hover_text(tr!("Stroke on/off")); From 924d571f50ac8585269129828c3fd22f134b97df Mon Sep 17 00:00:00 2001 From: Juan Larrazabal Date: Sat, 14 Nov 2026 13:29:18 -0800 Subject: [PATCH 12/20] docs: reserve ADR 0097 as pull request 354 --- docs/adr/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/adr/README.md b/docs/adr/README.md index 11e2e191..e80f8ece 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,4 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | -| 0097 | (outside contribution) | Fill alpha | +| 0097 | #354 (outside contribution) | Fill alpha | From c4a04db5ac8668c40c085d1035676a21577fdb06 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 17 Nov 2026 13:32:56 -0700 Subject: [PATCH 13/20] docs(adr): renumber the fill alpha ADR to 0102 (M8) --- crates/engine/src/cmds_brush.rs | 8 ++++---- docs/adr/0102-fill-alpha.md | 2 +- docs/adr/README.md | 1 - src/brushtool.rs | 2 +- 4 files changed, 6 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmds_brush.rs b/crates/engine/src/cmds_brush.rs index 36c01802..0dbb2ce7 100644 --- a/crates/engine/src/cmds_brush.rs +++ b/crates/engine/src/cmds_brush.rs @@ -1,7 +1,7 @@ //! The Brush tool's command (ADR 0033): a stroke of the brush paints a filled shape, the area its //! tip sweeps, in the fill colour. Off Object Drawing an opaque stroke merges with the drawing //! (ADR 0031), placed by the paint mode. A fill that is not fully opaque stays its own shape and -//! composites over what is behind it (ADR 0097). +//! composites over what is behind it (ADR 0102). use crate::brush_library::{BUILTIN, BrushLibrary, BrushPreset, MAX_FILE_BYTES, MAX_USER_PRESETS, builtin, builtin_hint, clean_name}; use crate::cmds_draw::{MAX_EXTENT, add_shape, object_param}; @@ -228,7 +228,7 @@ pub fn pressure_opacity(b: &BrushPreset, pts: &[Sample]) -> f32 { /// A fill that is not fully opaque has to stay its own shape. Merge drawing replaces what the /// new shape covers, so a wash would hide the colour behind it, and two washes of one colour -/// would join instead of darkening where they cross (ADR 0097). +/// would join instead of darkening where they cross (ADR 0102). fn paint_stacks(p: &Paint) -> bool { match p { Paint::Solid(c) => c.a < 1.0, @@ -308,7 +308,7 @@ fn draw_brush(s: &mut Session, p: &Value) -> Result { Some(_) if p.get("color").is_none_or(Value::is_null) && color.a >= 1.0 => s.style.fill_paint_for(&Affine::translate(-c.x, -c.y), &local.bounds()), _ => Paint::Solid(color), }; - // Opaque ink joins the drawing. A wash stays its own shape and composites (ADR 0097). + // Opaque ink joins the drawing. A wash stays its own shape and composites (ADR 0102). let own = object || paint_stacks(&fill); let id = ElementId(s.doc.alloc_id()); let el = Element { @@ -371,7 +371,7 @@ const PROFILE_TOLERANCE: f32 = 0.015; /// The Paint Brush (ADR 0068): the smoothed centre line as a stroke of the brush's size in the /// stroke colour, its width profile following the pressure and tapers, so the Width tool edits /// it afterwards. A stroke of one width is a plain line and merges like the Pencil's. A line -/// that is not fully opaque stays its own shape (ADR 0097). +/// that is not fully opaque stays its own shape (ADR 0102). fn paint_stroke(s: &mut Session, pts: &[Sample], b: &BrushPreset, smoothing: f32, tol: f32, color: Rgba, object: bool) -> Result { let (path, factors) = centre_stroke(pts, &b.shaping(), smoothing, tol * 0.25, PROFILE_SAMPLES); if !path.cmds.iter().any(|c| matches!(c, PathCmd::CubicTo(..) | PathCmd::LineTo(..))) { diff --git a/docs/adr/0102-fill-alpha.md b/docs/adr/0102-fill-alpha.md index ba5dc5ab..6179e43b 100644 --- a/docs/adr/0102-fill-alpha.md +++ b/docs/adr/0102-fill-alpha.md @@ -1,4 +1,4 @@ -# ADR 0097: Fill alpha +# ADR 0102: Fill alpha * Status: proposed * Relates to: ADR 0074 (the fill picker and gradients), ADR 0078 (swatches) diff --git a/docs/adr/README.md b/docs/adr/README.md index e80f8ece..8a35fed1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,4 +23,3 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | -| 0097 | #354 (outside contribution) | Fill alpha | diff --git a/src/brushtool.rs b/src/brushtool.rs index 2a537c62..8b982bb2 100644 --- a/src/brushtool.rs +++ b/src/brushtool.rs @@ -388,7 +388,7 @@ pub fn draw_overlay(app: &App, painter: &egui::Painter, xf: Xf, hover: Option= 255.0 { let color = to_color32(anicraft_engine::doc::Rgba { a: 1.0, ..paint }); draw_sweep(painter, xf, &tip, &app.brush_samples, color); From c5a406cb05da19199aecbcefa944feb039af7453 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 17 Nov 2026 13:46:03 -0700 Subject: [PATCH 14/20] fix(transform): skew doesn't snap; wire the control module after the merge (M8) --- src/main.rs | 2 ++ src/stage.rs | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index a08034b4..3386a1e2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -78,6 +78,8 @@ mod macros_ui; mod plugins_ui; mod prefs; mod recent; +#[cfg(not(target_arch = "wasm32"))] +mod remote; mod rulers; mod scale_grid; mod shape_envelope; diff --git a/src/stage.rs b/src/stage.rs index fca85a31..d11ac513 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -1362,7 +1362,8 @@ fn xf_snap(s: &mut anicraft_engine::Session, ring: &mut Option, kind: XfKi let pts = [pos2(b[0], b[1]), pos2(b[2], b[1]), pos2(b[2], b[3]), pos2(b[0], b[3]), pos2((b[0] + b[2]) * 0.5, (b[1] + b[3]) * 0.5)]; pts.into_iter().min_by(|p, q| p.distance(start).total_cmp(&q.distance(start))).unwrap_or(start) } - XfKind::Rotate => { + // Rotation and skew don't snap. + XfKind::Rotate | XfKind::Skew { .. } => { *ring = None; return c; } From 34d94154a018786eb5ddf8d05007dcab66052bb7 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 17 Nov 2026 13:46:04 -0700 Subject: [PATCH 15/20] fix(control): free the port with the window, drop silent connections, exclusive token file, portable installs (M8) --- crates/cli/src/control.rs | 57 +++++++++++++++++++++++++----- crates/cli/src/control/tests.rs | 34 ++++++++++++++++++ docs/adr/0104-live-control-port.md | 18 ++++++++++ docs/control-protocol.md | 11 ++++-- docs/guide/working-headless.md | 19 +++++++++- src/platform.rs | 17 +++++---- src/remote.rs | 4 ++- 7 files changed, 140 insertions(+), 20 deletions(-) diff --git a/crates/cli/src/control.rs b/crates/cli/src/control.rs index 8d637a1c..e2ce432e 100644 --- a/crates/cli/src/control.rs +++ b/crates/cli/src/control.rs @@ -16,7 +16,7 @@ use std::io::{BufRead, BufReader, Read, Write}; use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener, TcpStream}; use std::path::{Path, PathBuf}; use std::sync::Arc; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel}; use std::time::{Duration, Instant}; @@ -34,8 +34,14 @@ pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(60); /// Extra time the connection waits past the deadline: a call that started just before it /// still gets its real answer. const GRACE: Duration = Duration::from_secs(10); +/// How long a new connection may take to send its first request with the right token. Past it +/// the connection closes, so a program that connects and says nothing can't hold one of the +/// [`MAX_CONNECTIONS`] places. +pub const FIRST_REQUEST_TIMEOUT: Duration = Duration::from_secs(10); /// Overrides the generated token on both sides (CI, power users). pub const TOKEN_ENV: &str = "ANICRAFT_CONTROL_TOKEN"; +/// Where the bridge reads `control.json` from, when it isn't in the settings folder. +pub const FILE_ENV: &str = "ANICRAFT_CONTROL_FILE"; /// The port when `--control` isn't given. pub const PORT_ENV: &str = "ANICRAFT_CONTROL_PORT"; /// The file the app writes in the settings folder while its control port is open. @@ -55,9 +61,11 @@ pub fn settings_dir() -> Option { } } -/// Where `control.json` lives. +/// Where the bridge looks for `control.json`: `ANICRAFT_CONTROL_FILE` when set (a portable +/// install keeps the file in its own data folder, which this crate can't find), else the +/// settings folder. pub fn control_file() -> Option { - settings_dir().map(|d| d.join(CONTROL_FILE)) + std::env::var_os(FILE_ENV).filter(|v| !v.is_empty()).map(PathBuf::from).or_else(|| settings_dir().map(|d| d.join(CONTROL_FILE))) } /// `ANICRAFT_CONTROL_TOKEN`, when set and not blank. @@ -207,10 +215,20 @@ impl Request { /// Wakes the app's frame loop (`egui::Context::request_repaint`), from any thread. pub type Wake = Arc; -/// An open control port. +/// An open control port. Dropping it stops listening and frees the port (a window that opens +/// again in the same run, ADR 0092, can then listen on it again). pub struct Server { pub port: u16, rx: Receiver, + stop: Arc, +} + +impl Drop for Server { + fn drop(&mut self) { + self.stop.store(true, Ordering::SeqCst); + // `accept` only returns for a connection: make one, so the listener thread sees the flag. + let _ = TcpStream::connect_timeout(&SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, self.port)), Duration::from_secs(1)); + } } impl Server { @@ -223,17 +241,28 @@ impl Server { /// Opens the control port on `127.0.0.1:port`. Tool calls arrive through [`Server::try_recv`]; /// `wake` is called whenever one is waiting. pub fn listen(port: u16, token: String, wake: Wake) -> std::io::Result { + listen_with(port, token, wake, FIRST_REQUEST_TIMEOUT) +} + +/// [`listen`], with the time a new connection has to send its first good request. +pub fn listen_with(port: u16, token: String, wake: Wake, first_request: Duration) -> std::io::Result { let listener = TcpListener::bind(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port))?; let port = listener.local_addr()?.port(); let (tx, rx) = channel(); let token: Arc = token.into(); - std::thread::Builder::new().name("anicraft-control".into()).spawn(move || accept_loop(&listener, &token, &tx, &wake))?; - Ok(Server { port, rx }) + let stop = Arc::new(AtomicBool::new(false)); + let stopped = stop.clone(); + std::thread::Builder::new().name("anicraft-control".into()).spawn(move || accept_loop(&listener, &token, &tx, &wake, &stopped, first_request))?; + Ok(Server { port, rx, stop }) } -fn accept_loop(listener: &TcpListener, token: &Arc, tx: &Sender, wake: &Wake) { +fn accept_loop(listener: &TcpListener, token: &Arc, tx: &Sender, wake: &Wake, stop: &AtomicBool, first_request: Duration) { let active = Arc::new(AtomicUsize::new(0)); for stream in listener.incoming() { + // The server was dropped: stop, which closes the listener and frees the port. + if stop.load(Ordering::SeqCst) { + return; + } let Ok(mut stream) = stream else { continue }; let _ = stream.set_write_timeout(Some(Duration::from_secs(10))); if active.fetch_add(1, Ordering::SeqCst) >= MAX_CONNECTIONS { @@ -243,7 +272,7 @@ fn accept_loop(listener: &TcpListener, token: &Arc, tx: &Sender, w } let (token, tx, wake, active2) = (token.clone(), tx.clone(), wake.clone(), active.clone()); let spawned = std::thread::Builder::new().name("anicraft-control-conn".into()).spawn(move || { - serve_connection(stream, &token, &tx, &wake); + serve_connection(stream, &token, &tx, &wake, first_request); active2.fetch_sub(1, Ordering::SeqCst); }); if spawned.is_err() { @@ -253,8 +282,11 @@ fn accept_loop(listener: &TcpListener, token: &Arc, tx: &Sender, w } /// One connection: requests in order, until the client leaves or sends something it shouldn't. -fn serve_connection(stream: TcpStream, token: &str, tx: &Sender, wake: &Wake) { +fn serve_connection(stream: TcpStream, token: &str, tx: &Sender, wake: &Wake, first_request: Duration) { let Ok(read_half) = stream.try_clone() else { return }; + // Until the first request with the right token, reads time out (see the constant). + let _ = read_half.set_read_timeout(Some(first_request)); + let mut known = false; let mut reader = BufReader::new(read_half); let mut out = stream; loop { @@ -277,6 +309,13 @@ fn serve_connection(stream: TcpStream, token: &str, tx: &Sender, wake: if writeln!(out, "{reply}").and_then(|()| out.flush()).is_err() || !keep_open { return; } + // Only a request with the right token keeps the connection open: from here on the + // client may be idle for as long as it likes (an assistant between calls). + if !known { + known = true; + // On the reading handle itself: Windows keeps the timeout per handle, not per socket. + let _ = reader.get_ref().set_read_timeout(None); + } } } diff --git a/crates/cli/src/control/tests.rs b/crates/cli/src/control/tests.rs index 1c136fc6..1e09796d 100644 --- a/crates/cli/src/control/tests.rs +++ b/crates/cli/src/control/tests.rs @@ -251,3 +251,37 @@ fn the_bridge_drives_the_app_and_says_when_it_has_gone() { assert!(r.as_ref().map_or(true, |v| v["isError"] == true), "{r:?}"); let _ = std::fs::remove_dir_all(&dir); } + +/// A window that closes frees its port: the same run can open another window (ADR 0092) and +/// listen on it again. +#[test] +fn dropping_the_server_frees_the_port() { + let server = listen(0, TOKEN.into(), Arc::new(|| {})).unwrap(); + let port = server.port; + assert!(TcpListener::bind(("127.0.0.1", port)).is_err(), "the port is taken while the server lives"); + drop(server); + let freed = (0..200).any(|_| { + std::thread::sleep(Duration::from_millis(10)); + TcpListener::bind(("127.0.0.1", port)).is_ok() + }); + assert!(freed, "port {port} is still taken after the server was dropped"); +} + +/// A program that connects and says nothing is let go, so it can't hold a connection's place; +/// one that has sent the token may then be quiet for as long as it likes. +#[test] +fn a_silent_connection_is_closed_and_a_known_one_may_idle() { + let server = listen_with(0, TOKEN.into(), Arc::new(|| {}), Duration::from_millis(150)).unwrap(); + let connect = || { + let s = TcpStream::connect(("127.0.0.1", server.port)).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(20))).unwrap(); + (BufReader::new(s.try_clone().unwrap()), s) + }; + let mut silent = connect(); + let mut known = connect(); + let hello = format!(r#"{{"id":1,"token":"{TOKEN}","method":"hello"}}"#); + assert_eq!(send(&mut known, &hello)["ok"], true); + assert!(closed(&mut silent), "nothing sent: the app hangs up"); + std::thread::sleep(Duration::from_millis(400)); + assert_eq!(send(&mut known, &hello)["ok"], true, "a client that sent the token is not timed out"); +} diff --git a/docs/adr/0104-live-control-port.md b/docs/adr/0104-live-control-port.md index ae7f7fc3..fa334227 100644 --- a/docs/adr/0104-live-control-port.md +++ b/docs/adr/0104-live-control-port.md @@ -86,6 +86,24 @@ must not depend on an environment variable reaching two unrelated processes. more. Hosts other than this computer are refused. 10. **Visible.** While the port is open the status bar says "Remote control on (port N)" (through `tr!` and `theme::Type`), with a tooltip saying what that means. +11. **Added in review (the batch that merged this, M8).** + * *The port closes with the window.* Dropping `control::Server` stops the listener thread + and frees the port. A run can open its window again (ADR 0092, after a lost graphics + device); without this the second window found its own port "in use". + * *A silent connection is let go.* A connection has 10 s to send its first request with the + right token, then may idle. Otherwise sixteen programs that connect and say nothing would + hold every place and lock the assistant out. + * *The token file is always a new file.* An existing `control.json` (or a link under that + name) is removed and the file created exclusively, owner-only from the start, instead of + opened and tightened afterwards. + * *Portable installs* (ADR 0094) keep `control.json` in their data folder: the app writes + through `platform::config_dir`, so nothing lands outside it. The bridge can't know that + folder, so `ANICRAFT_CONTROL_FILE` names the file (or `ANICRAFT_CONTROL_TOKEN` the token). + * *What the port may do* is what the headless MCP server may: every command, files + included, with the person's permissions and the ADR 0004 confirmations. It is not a + plug-in (ADR 0017's `plugin_may_call` limits don't apply): the person turned it on, on + their own computer, for an assistant they chose. It is off unless asked for, and there is + no preference that turns it on. ## Consequences diff --git a/docs/control-protocol.md b/docs/control-protocol.md index cb30d25d..04f08975 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -35,8 +35,15 @@ writes it to `control.json` in AniCraft's settings folder: ``` On macOS and Linux the file is readable only by you; on Windows the settings folder already is. -It is replaced when AniCraft starts with `--control` and removed when it closes. A program running -as you finds the token there, with nothing to copy into its settings. +It is made new when AniCraft starts with `--control` (an older file, or a link left under its +name, is removed first and never written through) and removed when AniCraft closes. A program +running as you finds the token there, with nothing to copy into its settings. + +A portable AniCraft keeps `control.json` in its own data folder, like its other settings. Tell +the bridge where that is with `ANICRAFT_CONTROL_FILE=`. + +A connection has 10 seconds to send its first request with the right token; after that it may +stay idle. At most 16 connections are open at once. The port closes with the window. If `ANICRAFT_CONTROL_TOKEN` is set, it is the token instead (set it for both the app and the client: CI, power users). diff --git a/docs/guide/working-headless.md b/docs/guide/working-headless.md index 01e6f1e5..c4f5ef31 100644 --- a/docs/guide/working-headless.md +++ b/docs/guide/working-headless.md @@ -260,7 +260,24 @@ Things to know: * The assistant reads and writes files with your permissions, at the paths it chooses. Only connect assistants you trust with those files. * The server works on its own copy of the document, not on the window you have open. Save from - the assistant, then open the file in AniCraft. + the assistant, then open the file in AniCraft. To have the assistant work in the window + instead, see the next section. + +### An assistant in the window you have open + +Start AniCraft with `anicraft --control 9878`, and give the assistant +`anicraft-cli mcp --bridge 9878` as its server instead of `anicraft-cli mcp`. The same five +tools then act on the document in front of you: each edit shows at once and undoes with +**Ctrl+Z** like your own. While this is on, the status bar says **Remote control on (port +9878)**. + +* Only programs on this computer, running as you, can connect: the port is not open to the + network, and each run has its own secret token, kept in the settings folder until AniCraft + closes. +* An edit from the assistant waits while you are in the middle of a drag, so your undo steps + and its own never mix. +* Commands that would lose work still need `"confirm": true`, as above. +* Without `--control` nothing listens: remote control is off unless you start AniCraft this way. The full details are in [the MCP notes on GitHub](https://github.com/storytold/AniCraft/blob/main/docs/mcp.md). diff --git a/src/platform.rs b/src/platform.rs index fe7b47de..7291da73 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -414,23 +414,26 @@ pub fn recovery_dir() -> Option { /// Writes a file only this user may read (the control port's token, ADR 0104), making its folder /// first. On Windows the settings folder (%APPDATA%) is already private to the user; elsewhere -/// the file is made owner-only (0600). +/// the file is made owner-only (0600). The file is always a new one: an older file (or a link +/// someone left under its name) is removed first, never written through, and the new file is +/// made exclusively, so it has this mode from the start. #[cfg(not(target_arch = "wasm32"))] pub fn write_private_file(path: &std::path::Path, contents: &[u8]) -> std::io::Result<()> { use std::io::Write; if let Some(dir) = path.parent() { std::fs::create_dir_all(dir)?; } + match std::fs::remove_file(path) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } let mut options = std::fs::OpenOptions::new(); - options.write(true).create(true).truncate(true); + options.write(true).create_new(true); #[cfg(unix)] { - use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; + use std::os::unix::fs::OpenOptionsExt; options.mode(0o600); - // An older file keeps its mode when opened: tighten it first. - if path.exists() { - std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?; - } } let mut f = options.open(path)?; f.write_all(contents)?; diff --git a/src/remote.rs b/src/remote.rs index 9e19b3b5..b6de0506 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -44,7 +44,9 @@ pub fn start(app: &mut App, ctx: &egui::Context, port: u16) { return; } }; - let file = control::control_file(); + // In the settings folder, which a portable install keeps beside the program (ADR 0094): + // nothing is written outside it. + let file = platform::config_dir().map(|d| d.join(control::CONTROL_FILE)); let written = file.as_ref().map(|path| { let contents = control::ControlFile { port: server.port, token: token.clone(), pid: std::process::id(), version: env!("CARGO_PKG_VERSION").to_string() }; platform::write_private_file(path, contents.to_json().to_string().as_bytes()) From a8bfd987485407c30685fcf99ce3689ce5fb2d3e Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 17 Nov 2026 13:46:04 -0700 Subject: [PATCH 16/20] docs: guide and roadmap for skew and fill alpha; ADR 0102 accepted with review notes (M8) --- docs/adr/0102-fill-alpha.md | 17 ++++++++++++++++- docs/guide/coming-from-animate.md | 2 +- docs/guide/drawing.md | 22 ++++++++++++++-------- docs/roadmap.md | 2 +- 4 files changed, 32 insertions(+), 11 deletions(-) diff --git a/docs/adr/0102-fill-alpha.md b/docs/adr/0102-fill-alpha.md index 6179e43b..1856ac5b 100644 --- a/docs/adr/0102-fill-alpha.md +++ b/docs/adr/0102-fill-alpha.md @@ -1,6 +1,6 @@ # ADR 0102: Fill alpha -* Status: proposed +* Status: accepted (2026-11-17; an outside contribution by Koolskull, pull request #354, merged with the M8 batch) * Relates to: ADR 0074 (the fill picker and gradients), ADR 0078 (swatches) ## Context @@ -41,3 +41,18 @@ was always drawn opaque, so a fade did not show on the handles. * Alpha 0 is a fill the hit test and the eraser can still find. Removing the fill is None. * A wash does not join the raw drawing. Group still bundles those strokes. An opaque stroke joins as before. + +## Notes from review (the batch that merged this, M8) + +* **Where this differs from Animate.** In Animate a see-through brush stroke with Object + Drawing off still merges: it replaces the paint under it. Here it stays its own shape + (Decision 3), because a wash that cuts away what it covers can't do what a wash is for. The + cost is that such strokes don't join into one shape; Modify › Group bundles them. +* **Only the brushes do this.** A rectangle, oval or Paint Bucket fill with a see-through + colour and Object Drawing off still merges as before (it cuts what it covers, then shows the + stage through). Not yet: the same rule for the other drawing tools, if artists ask for it. +* **Nothing in the file changes.** `Rgba` always had alpha, `#rrggbbaa` was already read by the + commands, and the renderers already draw it (CPU oracle and GPU stage, SVG, HTML canvas and + Lottie exports). Older files open unchanged; no version bump. +* **Live preview.** The pen-down wash is one coverage image (at most 2048 px on its longer + side, reused as one texture), so its cost is bounded for any stroke. diff --git a/docs/guide/coming-from-animate.md b/docs/guide/coming-from-animate.md index 738eca3b..3dd37690 100644 --- a/docs/guide/coming-from-animate.md +++ b/docs/guide/coming-from-animate.md @@ -45,7 +45,7 @@ Each tool has the key you already know. |---|---|---| | Selection | **V** | Selects raw strokes and fills with the dot pattern; drag an edge to bend it. | | Subselection | **A** | Points and handles, on raw drawings and drawing objects. | -| Free Transform | **Q** | Scale, rotate and move; Shift and Alt as you'd expect. | +| Free Transform | **Q** | Scale, skew (drag the line between two handles), rotate and move; Shift and Alt as you'd expect. | | Gradient Transform | **F** | Its own button (no flyouts yet). Gradient and bitmap fills, with Lock Fill. | | Width | **U** | Variable-width strokes, with profiles in Properties. | | Bone | **M** | Joins symbol instances into an armature, or draws bones inside a shape. | diff --git a/docs/guide/drawing.md b/docs/guide/drawing.md index d53b15b0..3689e54b 100644 --- a/docs/guide/drawing.md +++ b/docs/guide/drawing.md @@ -18,7 +18,7 @@ your hand. |---|---|---| | Selection | **V** | Select, move and bend artwork | | Subselection | **A** | Edit points and curve handles | -| Free Transform | **Q** | Scale, rotate and move | +| Free Transform | **Q** | Scale, skew, rotate and move | | Gradient Transform | **F** | Move, turn and stretch a gradient or bitmap fill | | Width | **U** | Vary a line's thickness along it | | Bone | **M** | Join symbol instances into a poseable armature | @@ -215,8 +215,11 @@ width. The Pencil and the Line tool only draw lines, so they show no fill. Click any colour swatch to open the colour picker. **Swatches**, the default, shows the 216 web-safe colours with greys and primaries beside them; a shade or highlight of a colour is usually one cell away. The colours you mix or type are kept in the row below for this session. -**Mixer** sets any colour by hue, saturation and brightness (and alpha where the colour has -one). The hex field shows the colour as `#rrggbb` and takes one you type. A fill's picker +**Mixer** sets any colour by hue, saturation and brightness . Under it, the **Alpha** +row sets how clear a solid fill or a stroke is, from 0 % (clear) to 100 % (opaque). A clear +fill is still a fill: you can select it and erase it; **None** is no fill at all. Each stop of +a gradient has its own alpha, so a gradient can fade out. The hex field shows the colour as +`#rrggbb`, or `#rrggbbaa` when it isn't opaque, and takes either. A fill's picker starts with the fill's type: **None** (no fill), **Solid**, **Linear**, **Radial** or **Bitmap** (see [Gradients and bitmap fills](#gradients-and-bitmap-fills)); the stroke's picker has **No colour** instead. In the Tools panel's picker, with shapes selected, the colour you @@ -250,8 +253,10 @@ many palette sites also use); the swatches are added after yours. Adobe's `.aco` as GIMP `.gpl` from a tool that has it. To recolour existing artwork, select it and change **Fill** and **Stroke** in Properties. -For transparency, use the colour effect's **Alpha** (see -[Colour effects](#colour-effects)). +For a see-through fill or line, lower **Alpha** in its colour picker. A brush stroke painted +with a see-through colour stays a shape of its own, over what is behind it, instead of joining +the drawing. To fade a whole symbol instance, or to tween a fade, use the colour effect's +**Alpha** (see [Colour effects](#colour-effects)). ### Line styles @@ -343,9 +348,10 @@ changes everywhere it's used. ## Transforming artwork -With the **Free Transform** tool (**Q**), drag a corner or edge to **scale** (**Shift** keeps -the proportions, **Alt** scales from the centre), just outside a corner to **rotate** -(**Shift** snaps to 15°), or inside the box to **move**. You can also type exact +With the **Free Transform** tool (**Q**), drag a handle (a corner or the middle of an edge) to +**scale** (**Shift** keeps the proportions, **Alt** scales from the centre), the line between +two handles to **skew** (the opposite edge stays where it is; **Alt** skews about the centre), +just outside a corner to **rotate** (**Shift** snaps to 15°), or inside the box to **move**. You can also type exact **Position**, **Scale** and **Rotation** values in Properties. | Command | Menu | Key | diff --git a/docs/roadmap.md b/docs/roadmap.md index 5c5e9738..57c5121e 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -15,7 +15,7 @@ This integration depends on craft-libs #1962 and still requires hosted parity va | 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). | | Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients (with reflect/repeat, focal points, elliptical radials and linear RGB, ADR 0074), round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Soft masks** (ADR 0070): a mask layer's mask type is Shape (coverage), Alpha (its artwork's opacity as drawn: gradients, faded shapes, strokes, bitmaps) or Luminance (brightness × opacity, SVG's coefficients), in the CPU oracle (analytic tests), the GPU stage (parity: mean 0.00006, worst 1 step of 255), SVG export (`` with `mask-type`), Lottie (alpha and luma track mattes) and the HTML canvas; Layer Properties › Mask type. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes ``. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. Filters apply in list order and may be switched off (ADR 0091): `evaluate` leaves switched-off ones out, so every renderer and export draws them as absent. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. **Second slice** (ADR 0029): on the window's wgpu device the stage tiles are drawn straight into textures egui shows (no readback; a headless device with readback when the window is on OpenGL); **masks** (nested, united artwork), **group opacity** and **all 14 blend modes** on the GPU, same parity (max 1/255, mean ≤ 0.0011/255); 4K: 1,000 shapes in 2.1–2.4 ms, 10k shapes in 10.2 ms as stage tiles, masked scenes 7× the CPU. **Third slice** (ADR 0032): **bitmap fills** (textures uploaded once per image and cached under a 256 MB budget, sampled with the oracle's own bilinear filter, colour effect and repeat rules: byte-identical) and **all seven filters** (each filtered symbol drawn into a layer of its own and filtered by compute passes that run the oracle's resolved steps: max 1/255, mean ≤ 0.007/255) on the GPU; the shaders now build with Direct3D's FXC, so DX12 windows get the GPU stage too (parity suite green on Vulkan and DX12); software adapters are refused (the CPU is faster), the start-up self-test compares with the oracle. **The GPU is the default stage renderer**: the shell's `gpu-stage` feature is on by default, Preferences › Stage › Renderer defaults to *Graphics card (GPU)*, and the CPU draws whenever there is no usable card, a tile is past the GPU's limits (more than 16 images, filters nested deeper than 4) or anything fails. 4K: the filtered sample in 3.9 ms (CPU 31.5), 200 bitmap fills in 4.4 ms (CPU 37.2). **Fourth slice** (ADR 0048): **tile binning on the GPU** for heavy frames without masks or groups (count, prefix sum, scatter and tile-list passes, no atomics, no readback; the CPU binning stays the reference and does the rest; one tile format for both: an integer backdrop per tile and steps on the tiles' left edges): on Vulkan, 10k shapes at 4K in one texture 21.7 → 4.7 ms, 50k shapes 122 → 22.5 ms, the 50k-shape 4K stage 75 → 37 ms (Direct3D 12 keeps CPU binning: slower there in stage tiles); and **hairlines** for outline mode in both renderers (coverage by distance, one edge per segment): onion outlines on the 2,000-item stress scene as fast as tinted (GPU stage 73 → 10 ms, CPU stage 34–39 → 17 ms at 1080p). **Mid-session failures** (ADR 0092): a broken GPU stage hands the stage to the CPU at once with a status-bar notice and a log line, and is retried with a bounded backoff; driver errors on the window's device are logged instead of panicking (the #255 `Surface::configure` panic), and a lost window device autosaves and reopens the window on a safer way. Not yet: sharing a filtered layer across a frame's tiles, more than 16 images per tile, GPU binning inside masks and groups, flattening and stroking on the GPU, buffer reuse and fewer dispatches across tiles, hairlines for sub-pixel strokes, GPU exports, a GPU runner in CI; the CPU stays the oracle and the export path. | | Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, icon buttons and right-click menu) act on the whole selection; with no frame selection F5 extends every layer with frames at or after the playhead, and F5/F6/F7 move the playhead on as in Animate (F6/F7 on a keyframe key the next frame; `all_layers`/`advance` headless); drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it; a motion tween's keys stretch in proportion, ADR 0083). Side dock tab strips never run under the panel menu (names shrink with an ellipsis, then the strip scrolls). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), **timeline polish** (ADR 0061): a per-layer **onion skin toggle** column (Alt-click solos; left-out layers aren't onion-skinned; Edit Multiple Frames unaffected), the colour square toggles **View as Outlines** in the layer colour **on the stage only** (exports, Test Movie and the player draw the artwork as it is), the **colour chip** opens the layer colour (swatches, hex, More…), **onion frames of the parent timeline** dimmed around a symbol edited in place, **Layer Height** 100/200/300 %, **Layer Properties** (double-click the layer icon; name, show/lock, type, outline colour, outlines, onion, height; one undo step), **Frame View** (Tiny/Small/Normal/Medium/Large, Short rows) with the frame zoom in the timeline's bottom bar (the header fits at the default window size, tested); headless `layer.set_onion/set_color/set_height/set_properties/properties`; XFL `heightMultiplier`. Not yet: folder onion toggles, onion of deeper parent timelines, multi-layer Layer Properties and layer transparency, frame thumbnails (Preview). Keyframes, blank keyframes, insert/remove frames, classic tweens with **ease presets and custom eases** (ADR 0081: Classic Ease with a strength and Quad, Cubic, Quart, Quint, Sine, Back, Circ, Bounce and Elastic In/Out/In Out; custom eases of up to 64 Bézier points in the Custom Ease window, x kept monotonic, overshoot allowed, keyboard operable, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. **Edit Multiple Frames, complete** (ADR 0051): Cut, Copy, Paste (current frame), Paste in Place (back keyframe by keyframe, or a one-frame copy onto every keyframe between the markers), Clear, Align (Ctrl+Alt+1…6, To Stage), Rotate 90° and Flip, and **Free Transform** of the selection on every keyframe about one shared pivot (one box, one undo step per drag); raw shapes moved, transformed or pasted merge again on their own keyframe; **onion skin and Edit Multiple Frames inside a symbol edited in place**, on its own timeline and markers. Headless: `frames.transform`, `frames.align`, `frames.delete`, `frames.copy`, `frames.cut`, `frames.paste`, `frames.merge`, `merge` on `frames.edit_multiple`. Not yet: Duplicate/Distribute/Arrange and recolouring across keyframes, scaling a motion tween's object on several frames, a draggable pivot. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exports play every scene in order. **Layer folders**: nestable folders (depth ≤ 16) holding layers and masks through `Layer.parent`, one invariant (`Timeline::repair_masks`: a child sits below its parent inside the parent's unbroken run; broken links fall back to the nearest valid ancestor); hiding or locking a folder hides or locks its contents (rendering, picking, drawing); folders open and close on the timeline (view state); layers move in and out with Up/Down, a folder moves with its contents; deleting a folder deletes its contents (asks first). **Motion tweens** (ADR 0016): a span's object animated property by property (x, y, scale, colour, filters, and instance filters tween; XFL custom and per-property eases import exactly; `ease.*` headless) + curve preview, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (any preset, saved ease or custom ease of several segments, ADR 0081; overshoot allowed); auto-key turns any edit of the object inside the span into property keys (every command, through the session), F6 keys every property, splits and copies keep the motion; sky-blue spans with property-key diamonds; **Motion Editor** tab beside the timeline: property list with values at the playhead, curve graph with draggable keys and Bézier handles, one undo step per drag. **Retiming** (ADR 0083): keys drag sideways in time (snapped to frames, never past a neighbour), Shift-click picks keys across properties, an All lane picks a frame's keys, Left/Right move picked keys with the curve focused; dragging a span's end stretches a motion tween's keys in proportion (Shift keeps them); a click picks a whole motion span and dragging (or a selection of whole tween spans) moves it at its length, Alt-drag copies; **Split Motion** / **Join Motion** (split then join is exact). Headless: `motion.move_keys`, `timeline.resize_span`, `timeline.move_spans`, `motion.split`, `motion.join`. Not yet: joining two independent motion paths, retiming from a span's left edge. **Motion paths** (ADR 0030): a motion tween may carry a cubic path its object travels by arc length, timed by the X/Y curves (a straight path reproduces them exactly, overshoot included); shown on the stage in the motion colour with a dot per frame when the object or span is selected; Selection drags the path to bend it and its ends to move them, Subselection drags anchors and handles; moving the object reshapes the path; Orient to path and Straighten in Properties; splits cut the path. **Path points** (ADR 0038): with Subselection, double-click the path to add a point (shape and motion unchanged), Shift-click to select several anchors, Delete to remove them (the path refits through the rest; the ends stay), right-click for smooth/corner and Straighten; the Pen's Alt-click adds a point to a motion path or a selected shape; Ctrl-drag (⌘-drag) the path or its object, or edit Properties › Path start, to move the whole path with its timing exact. **Anchors pinned to frames** (ADR 0049): moving the object at a frame pins a path point there (a new anchor where it was put; after the last position key the path carries on), and the object passes every pinned point exactly on its frame, the X/Y eases timing it between pins; pinned points are diamonds with their frame number on the stage, blue keys in the Motion Editor's X/Y (dragging one moves its point) and holed diamonds on the timeline; Subselection's right-click pins to the playhead's frame or unpins, Properties › Frame has Pin Here / Unpin, F6 pins where the object is; point edits keep pins on their anchors; files without pins evaluate exactly as before. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient/add_point/delete_points/convert_point/move_path/pin_point/unpin_point`; `motion.info` reports `pins`). Not yet: retiming a pin by dragging its key in time, two pins on one anchor, XFL motion path keyframes, a marquee over path anchors, nudging or transforming a whole path, retiming keys, rescaling keys with the span, XFL motion-tween import. **Bones and IK, first slice** (ADR 0043): the Bone tool (M) drags from one symbol instance to another to join them with a bone on an armature layer (chains join end to start: a bone from a chained instance always starts at its joint; branches allowed, up to 256 bones); bones show as wedges in the layer colour; the Selection tool drags a bone (the grabbed point follows) or a posed instance to pose by cyclic coordinate descent (joint limits, pinned bones, one undo step per drag) and the root to move it all; poses are joint angles keyed per frame and tweened with the span's easing; Properties › Bone (angle, constrain min/max, pin, remove); `bone.*` headless; every export sees the pose. **Shape armatures** (ADR 0071): the Bone tool draws bones inside a shape (it moves to an armature layer as an object, outside merge drawing); its points are bound to the nearest bones automatically (weights by distance to each bone, up to four, summing to 1) and bend by linear blend skinning (handles with their anchors, strokes keep their width, the rest pose exact); the **Bind tool** (Shift+M) shows the points (squares, triangles where shared) and binds them by click, Shift/Ctrl-click or box; the same IK, poses and tweens; `bone.add_in_shape`, `bone.bind`, `bone.info {points}`. **Painted weights and reshaping** (ADR 0090): the Bind tool's **Paint Weights** brush (Add, Subtract, Smooth; size with `[`/`]`, strength; soft falloff) paints a bone's share onto the points under it, shown live as a heat map (blue none to red all) on the outline and points; weights stay normalised per point (the other bones share the rest, a point's only bone gives way to its nearest other bones), painted points are hand-bound, one undo step per stroke (1.15 ms for 32 dabs over 20,000 points); a focused point's weights as numbers in Properties › Bone (keyboard); Subselection edits a bound shape's outline at the rest pose (move, add, delete, smooth/corner) keeping the binding: moved points keep their weights, new points blend their neighbours', deleted points drop theirs, the rest pose exact; `bone.paint_weights`, `bone.set_weight`. **Springs, joint translation and members in place** (ADR 0084): joints slide along X/Y of what they start on, freely or within pixel limits, as part of each pose (IK slides only where turning can't reach); per-bone Spring and Damping swing bones after the motion and settle, evaluated as a pure replay of up to six seconds of motion (seeking equals playing bit for bit; 0.33 ms a frame for 16 sprung bones), shown on the stage, in Test Movie and every export, switched off per armature for posing; a picked bone's instance takes colour effect, blending and filters in place on every pose; `bone.set_translation`, `bone.set_spring`, `bone.enable_springs`. Not yet: runtime armatures, XFL import, mixing instances and shapes in one armature (proposed in ADR 0084 and 0090), reshaping at a posed frame, gravity and wind. **Asset Warp** (ADR 0079): the **Asset Warp tool** (Shift+Q) pins a shape or a bitmap (the first pin covers it with a warp mesh: a grid over its bounds, 2–48 cells along the longer side, Properties › Asset Warp); dragging a pin bends the artwork around the other pins by rigid moving least squares (Schaefer et al. 2006) at the mesh's vertices, live, one undo step per drag; Delete removes a pin; pins are added to every keyframe holding the artwork and their poses tween with classic tweens and easing; shapes bend through the mesh (straight edges exactly, curves split), bitmaps are drawn through its triangles by the CPU oracle (bilinear) and the GPU stage takes the same prepared fill (parity exact); the rest pose is the drawing bit for bit; every raster export, SVG (a bent bitmap baked as an image), Lottie and HTML (a bent bitmap reported) go through `evaluate`; `warp.add`, `warp.pin_add`, `warp.pin_move`, `warp.pin_remove`, `warp.remove`, `warp.info`. Not yet: as-rigid-as-possible solving on a mesh that follows the outline, symbols and text, binding warp pins to bones, a GPU textured-triangle path, bent bitmaps in HTML and Lottie, XFL import of warped assets. eases saved in the document and offered everywhere; copy/paste of an ease; classic tweens eased per property group: position, **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tools pause there); hiding the camera layer turns it off; every export, Test Movie and the GPU stage see it. Headless: `camera.add/remove/set/info`, `layer.set_depth`. **Camera, second slice** (ADR 0082): layer depth in a pinhole perspective (deeper layers move and zoom less, draw behind nearer ones; depth 0 bit-exact), depth keyed over time (linear between keys), **Window › Layer Depth** (layers by depth, drag nearer or farther, key, attach), **Attach Layer to Camera** (timeline toggle; HUDs stay on screen), camera colour effects (Brightness, Tint, Advanced), and the Selection tool picking and moving artwork while previewing through the camera; headless `layer.set_depth {key, frame}`, `layer.remove_depth_key`, `layer.set_attached`, `layer.depths`, `element.pick {view: camera}`. Not yet: other tools while previewing, depth inside symbols, depth keys moving with inserted frames, XFL camera and layer-depth import (no public format description). **Motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | -| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, under or over the artwork, snap accuracy up to Always); Snap to Pixels; one snap engine for every drawing tool, the Selection tool's moves and Free Transform's handles (point › guide › line › grid › pixel, guides and grid per axis); stage only, never exported, on the CPU and GPU stage. Headless: `view.rulers`, `view.grid_show/grid_snap/grid_set`, `view.guides_show/guides_lock/guides_snap/guides_set`, `view.guide_add/guide_move/guide_delete/guides_clear`, `view.snap_pixels`, `view.aids`, `moving` on `draw.snap`. *Not yet:* units other than px, a movable ruler origin, a symbol's own guides, guides and grid from Animate files, Snap Align and Edit Snapping, snapping while rotating. bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Width profiles take part in the merge since ADR 0093. **Raw points and symbols in place** (ADR 0045): add a point on a raw edge (Pen Alt-click, Subselection double-click; every shape on the edge gets it, the curve unchanged), delete raw points (Delete; the shapes on each are joined across it so the drawing stays connected; points where three edges meet are kept), Make Smooth / Corner on raw points, smooth handle pairs (Alt breaks them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap their points within 10 screen px (Snap to Objects, Ctrl+Shift+/); a double-click on an instance (or Ctrl+E, or a double-click in the Library) opens the symbol in place, the stage dimmed around it, the edit bar showing the path back, and every tool and command works on its timeline. Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth` on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`. Not yet: rotated instances in place (they open upright). Onion skin and Edit Multiple Frames work inside a symbol since ADR 0051. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. **Paint Selection and Paint Inside** (ADR 0080): the paint is clipped to the selected fills' union, or to the fill (or closed-off empty area) the stroke starts in, exactly on the planar map, then merged under the lines; Paint Selection keeps the selection for the next stroke. Not yet: the live preview clipped as it paints. **Brush library, pressure curves and the Paint Brush (Y)** (ADR 0068, first slice): Window › Brush Library with seven built-in brushes made only of parameters (Pencil, Ink Pen, Flat Calligraphy, Round Taper, Marker, Chalk with a deterministic worn edge, Dotted stamps), each with a stroke preview drawn by the renderer; brushes of your own saved by name in your preferences, renamed, deleted (asks first) and moved between computers as a JSON brush set; a pressure curve editor (Linear, Soft, Firm, or your own points) driving size and, optionally, the stroke's opacity; tapers, dab spacing and a rough edge in Properties; Velocity (mouse speed as pressure, off by default); the Paint Brush draws a width-profiled stroke in the stroke colour that the Width tool edits. Headless: `brush.preset_list/save/rename/delete/export/import`, `preset`, `curve`, `as_stroke` and the shaping params on `draw.brush`. **Tilt, texture and scatter** (ADR 0093): per-sample pen tilt (Pointer Events altitude and azimuth in `draw.brush` points) turns the tip by the azimuth and widens it up to 2× as the pen leans (Brush › Tilt: Angle, Width, shown once a pen reports tilt; the Paint Brush's width too), a fixed paper grain of holes (Texture) and dabs thrown either side (Scatter), all vector fills; built-in Charcoal and Spatter (nine brushes). Not yet: reading tilt from the pen on desktop systems (winit 0.30 reports it only on iOS), opacity varying along a stroke, bitmap or art brushes, Eraser presets and pressure. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Since ADR 0093: width-profiled lines erase and merge, each piece keeping its widths; gradient pieces keep their gradient where it was; inside an open symbol or drawing object the Eraser erases its shapes, and on the stage the status bar says how. Not yet: eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. **Colour picker and drawing-tool fixes from user reports** (M1): every colour swatch (the Tools panel's fill and stroke squares too) opens one picker with Animate's web-safe swatches (216 colours, greys and primaries), the colours mixed or typed this session, a hex field, an alpha (a solid fill's own, and a different one on each gradient stop) and the full mixer; the Tools squares offer No Colour and recolour selected shapes; drawing tools leave nothing selected after a stroke and the Selection tool's box has no handles (they are Free Transform's); Break Apart turns drawing objects into merged drawing; Ctrl-drag on a raw edge adds a corner point; the Pencil and Line show no fill. **Swatches panel** (ADR 0078): Window › Swatches, the document's saved colours and gradients (in the `.anicraft` file; a default set for new documents and older files); click applies to the selection and the tool colour, to the stroke or fill that is active (Tools squares, Colour panel or the panel's toggle; gradients always to the fill); + adds the active colour or gradient, Duplicate, Delete, drag (or Alt+arrows) to reorder, names on hover, Clear (keeps black and white) and Load Default Swatches (ask first, undoable); import and export as a JSON swatch file, GIMP `.gpl` import; the colour picker shows the document's swatches and the fill picker its gradient swatches. Headless: `swatch.list/add/remove/move/duplicate/rename/apply/clear/reset/import/export`. Not yet: swatch folders, sorting by colour, bitmap swatches, Save as Default, XFL swatch import (no public description), Adobe `.aco`/`.ase`/`.clr` (proprietary). The layer footer is icon buttons (New Layer, Delete, New Folder, Up, Down) that fit at any size and language. **Groups and Combine Objects** (ADR 0073): Modify › Group (Ctrl+G) / Ungroup (Ctrl+Shift+G), a group element whose members are a one-layer, one-frame timeline, opened in place by a double-click like a symbol (every tool works inside; raw shapes merge only with each other); nested groups; exports, player, sounds and the Library see inside; XFL `DOMGroup` imports as groups. Combine Objects › Union, Intersect, Punch, Crop on the planar map (analytic area tests). Selection tool: Alt-drag copies, Shift constrains to 45° (Ctrl/⌘-drag corners: #257). **Drawing parity leftovers** (ADR 0080): PolyStar's Shape (Polygon or Star), sides 3–32 and star point size 0–1 in its options (`shape`, `sides`, `point_size` on `draw.star`); a double-click (or Ctrl+E) opens a drawing object in place, its raw shapes merging only with each other, and it closes as one object again (a group of the pieces when an edit leaves several); **Modify › Transform › Envelope**: a Bézier mesh of corner and tangent handles bends the selected shapes and drawing objects, one undo step per drag, baked like Animate's (no Delete Envelope needed), undo restoring the mesh; headless `modify.envelope`, `modify.envelope_move`, `modify.envelope_close`. *Not yet:* gradient and bitmap strokes (proposed in ADR 0080), envelope handles from the keyboard, an envelope on symbols, text or groups, drawing objects edited without opening them (#181), Combine across layers. **Rulers, grid and guides** (ADR 0076): View › Rulers (stage pixels, following zoom and pan, pointer marked); guides per scene saved in the document, dragged from a ruler, moved with the Selection tool, dragged back to delete, Show/Lock/Snap/Edit/Add/Clear (Edit Guides lists and adds them from the keyboard); a grid (spacing, | +| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), **skew** by dragging the line between two handles (the opposite edge stays, Alt about the centre; outside PR #176), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, under or over the artwork, snap accuracy up to Always); Snap to Pixels; one snap engine for every drawing tool, the Selection tool's moves and Free Transform's handles (point › guide › line › grid › pixel, guides and grid per axis); stage only, never exported, on the CPU and GPU stage. Headless: `view.rulers`, `view.grid_show/grid_snap/grid_set`, `view.guides_show/guides_lock/guides_snap/guides_set`, `view.guide_add/guide_move/guide_delete/guides_clear`, `view.snap_pixels`, `view.aids`, `moving` on `draw.snap`. *Not yet:* units other than px, a movable ruler origin, a symbol's own guides, guides and grid from Animate files, Snap Align and Edit Snapping, snapping while rotating. bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Width profiles take part in the merge since ADR 0093. **Raw points and symbols in place** (ADR 0045): add a point on a raw edge (Pen Alt-click, Subselection double-click; every shape on the edge gets it, the curve unchanged), delete raw points (Delete; the shapes on each are joined across it so the drawing stays connected; points where three edges meet are kept), Make Smooth / Corner on raw points, smooth handle pairs (Alt breaks them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap their points within 10 screen px (Snap to Objects, Ctrl+Shift+/); a double-click on an instance (or Ctrl+E, or a double-click in the Library) opens the symbol in place, the stage dimmed around it, the edit bar showing the path back, and every tool and command works on its timeline. Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth` on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`. Not yet: rotated instances in place (they open upright). Onion skin and Edit Multiple Frames work inside a symbol since ADR 0051. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. **Paint Selection and Paint Inside** (ADR 0080): the paint is clipped to the selected fills' union, or to the fill (or closed-off empty area) the stroke starts in, exactly on the planar map, then merged under the lines; Paint Selection keeps the selection for the next stroke. Not yet: the live preview clipped as it paints. **Brush library, pressure curves and the Paint Brush (Y)** (ADR 0068, first slice): Window › Brush Library with seven built-in brushes made only of parameters (Pencil, Ink Pen, Flat Calligraphy, Round Taper, Marker, Chalk with a deterministic worn edge, Dotted stamps), each with a stroke preview drawn by the renderer; brushes of your own saved by name in your preferences, renamed, deleted (asks first) and moved between computers as a JSON brush set; a pressure curve editor (Linear, Soft, Firm, or your own points) driving size and, optionally, the stroke's opacity; tapers, dab spacing and a rough edge in Properties; Velocity (mouse speed as pressure, off by default); the Paint Brush draws a width-profiled stroke in the stroke colour that the Width tool edits. Headless: `brush.preset_list/save/rename/delete/export/import`, `preset`, `curve`, `as_stroke` and the shaping params on `draw.brush`. **Tilt, texture and scatter** (ADR 0093): per-sample pen tilt (Pointer Events altitude and azimuth in `draw.brush` points) turns the tip by the azimuth and widens it up to 2× as the pen leans (Brush › Tilt: Angle, Width, shown once a pen reports tilt; the Paint Brush's width too), a fixed paper grain of holes (Texture) and dabs thrown either side (Scatter), all vector fills; built-in Charcoal and Spatter (nine brushes). Not yet: reading tilt from the pen on desktop systems (winit 0.30 reports it only on iOS), opacity varying along a stroke, bitmap or art brushes, Eraser presets and pressure. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Since ADR 0093: width-profiled lines erase and merge, each piece keeping its widths; gradient pieces keep their gradient where it was; inside an open symbol or drawing object the Eraser erases its shapes, and on the stage the status bar says how. Not yet: eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. **Colour picker and drawing-tool fixes from user reports** (M1): every colour swatch (the Tools panel's fill and stroke squares too) opens one picker with Animate's web-safe swatches (216 colours, greys and primaries), the colours mixed or typed this session, a hex field, an alpha (a solid fill's own, and a different one on each gradient stop) and the full mixer; the Tools squares offer No Colour and recolour selected shapes; drawing tools leave nothing selected after a stroke and the Selection tool's box has no handles (they are Free Transform's); Break Apart turns drawing objects into merged drawing; Ctrl-drag on a raw edge adds a corner point; the Pencil and Line show no fill. **Swatches panel** (ADR 0078): Window › Swatches, the document's saved colours and gradients (in the `.anicraft` file; a default set for new documents and older files); click applies to the selection and the tool colour, to the stroke or fill that is active (Tools squares, Colour panel or the panel's toggle; gradients always to the fill); + adds the active colour or gradient, Duplicate, Delete, drag (or Alt+arrows) to reorder, names on hover, Clear (keeps black and white) and Load Default Swatches (ask first, undoable); import and export as a JSON swatch file, GIMP `.gpl` import; the colour picker shows the document's swatches and the fill picker its gradient swatches. Headless: `swatch.list/add/remove/move/duplicate/rename/apply/clear/reset/import/export`. Not yet: swatch folders, sorting by colour, bitmap swatches, Save as Default, XFL swatch import (no public description), Adobe `.aco`/`.ase`/`.clr` (proprietary). The layer footer is icon buttons (New Layer, Delete, New Folder, Up, Down) that fit at any size and language. **Groups and Combine Objects** (ADR 0073): Modify › Group (Ctrl+G) / Ungroup (Ctrl+Shift+G), a group element whose members are a one-layer, one-frame timeline, opened in place by a double-click like a symbol (every tool works inside; raw shapes merge only with each other); nested groups; exports, player, sounds and the Library see inside; XFL `DOMGroup` imports as groups. Combine Objects › Union, Intersect, Punch, Crop on the planar map (analytic area tests). Selection tool: Alt-drag copies, Shift constrains to 45° (Ctrl/⌘-drag corners: #257). **Drawing parity leftovers** (ADR 0080): PolyStar's Shape (Polygon or Star), sides 3–32 and star point size 0–1 in its options (`shape`, `sides`, `point_size` on `draw.star`); a double-click (or Ctrl+E) opens a drawing object in place, its raw shapes merging only with each other, and it closes as one object again (a group of the pieces when an edit leaves several); **Modify › Transform › Envelope**: a Bézier mesh of corner and tangent handles bends the selected shapes and drawing objects, one undo step per drag, baked like Animate's (no Delete Envelope needed), undo restoring the mesh; headless `modify.envelope`, `modify.envelope_move`, `modify.envelope_close`. *Not yet:* gradient and bitmap strokes (proposed in ADR 0080), envelope handles from the keyboard, an envelope on symbols, text or groups, drawing objects edited without opening them (#181), Combine across layers. **Rulers, grid and guides** (ADR 0076): View › Rulers (stage pixels, following zoom and pan, pointer marked); guides per scene saved in the document, dragged from a ruler, moved with the Selection tool, dragged back to delete, Show/Lock/Snap/Edit/Add/Clear (Edit Guides lists and adds them from the keyboard); a grid (spacing, | | Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. **Exporter and ease plug-ins** (ADR 0088): `kind: "exporter"` declares a format (name, extension, options) and gets evaluated frames (`movie`, `frame`: the flattened display list, never the document), returning the file's bytes from `ac_export` (64 MiB cap, 5·10¹⁰ instructions, 10 min); File › Export lists it with an Export window (options, frames, file, progress bar and Cancel on a worker thread); `file.export_plugin`, `file.export_formats`, `anicraft-cli export --format ` and `formats`. `kind: "ease"` declares named eases, `ac_ease(i, t)` sampled into 257 values at load (NaN, unbounded or end-missing eases refused); `Easing::Sampled` keeps the table in the document, so it plays the same without the plug-in; the ease menus list them under Plug-in eases; `{plugin, ease}` easing params. Samples: Plain Text Frames and Stepped Eases, built and run in CI. Not yet: plug-in formats in Publish, bitmaps' pixels and sounds for exporters, ease plug-ins with parameters, background runs of command plug-ins, a binary document view. | | Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. **A window of its own on the desktop** (ADR 0062): sized to the stage at 100 % (smaller to fit the screen), titled with the document, back where it was last (not on Wayland, where the desktop places windows), with the keyboard when it opens; Esc or Ctrl+W (⌘W) closes it, Ctrl+Enter restarts it in place, and the editor's Ctrl/Alt shortcuts work from it; floating inside the editor in the web build, where the system can't open windows (it says so), or by choice in Preferences › Test Movie. Not yet: full screen, zoom in the movie window, remembering its size. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; **filters and Subtract/Invert in the page** (ADR 0072: `filters.js`, a port of the renderer's filters run over the group's pixels on a layer that reaches past the canvas by the filters' reach, Subtract and Invert composited per pixel, results kept while the group is unchanged; equal to the oracle's pixels within 9.3e-4 in Boa; 3.4 ms a frame for the demo's filters at 1080p while they change); Web Audio for Event/Start/Stop/Stream sounds; bitmap tints, 9-slice scaling and plug-in frame scripts reported. Not yet: 9-slice in the page, keeping a moving filtered group's pixels, filters off the main thread. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. **Buttons, complete** (ADR 0057): a button open in place names its frames Up, Over, Down and Hit on the timeline and shows its Hit area translucent over the other states; Test Movie has **Show hit areas**; sounds on its frames play as its state changes. | | Headless | CLI: info, render, render-seq, **gif**, **apng**, **webp**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. **Live control** (ADR 0104, `docs/control-protocol.md`): `anicraft --control ` and `anicraft-cli mcp --bridge ` run the same tools on the open window, on this computer only, with a per-run token in `control.json`. | From 45a21354c64327325662590b9687dd880a4132a4 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 17 Nov 2026 13:46:04 -0700 Subject: [PATCH 17/20] docs: changelog and authors for the outside contributions (M8) --- AUTHORS.md | 4 ++++ CHANGELOG.md | 54 +++++++++++++++++++++++++++------------------------- 2 files changed, 32 insertions(+), 26 deletions(-) diff --git a/AUTHORS.md b/AUTHORS.md index edbac412..4ebb20b6 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -4,3 +4,7 @@ People who have contributed to AniCraft. The repository starts from one initial (`docs/release.md`), so the work before it is credited here. * Tanish Manku: project lead, product direction and design. +* Koolskull: fill and stroke alpha in the colour picker (#354). +* lienatanael-dev: the live control port and its MCP bridge (#216). +* mypenc: skew in Free Transform (#176). +* Davit Matchakhelidze (devius): Georgian in the interface, with Noto Sans Georgian (#160). diff --git a/CHANGELOG.md b/CHANGELOG.md index 835887b9..e4d08648 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,34 @@ ## Unreleased +* **From outside contributors** (M8; thank you). + * **Free Transform skews** (by mypenc, #176, for #174). Drag the line between two handles + of the selection box to shear the artwork along that edge, as in Animate: the opposite edge + stays put, **Alt** skews about the centre, and the cursor shows the direction. One undo + step per drag; works with Edit Multiple Frames. + * **Fill and stroke alpha** (by Koolskull, #354, ADR 0102). The colour picker has a labelled + **Alpha** row (a slider and a percent) for a solid fill and for a stroke, on the Tools + squares, the Colour panel and Properties; hex takes `#rrggbbaa`. A clear fill is still a + fill; no fill is the type None. Each stop of a gradient keeps its own alpha and its marker + shows it. A brush stroke that isn't fully opaque stays its own shape over what is behind + it, so crossings darken, and the ink is drawn at that alpha while the pen is down. Opaque + strokes join as before. + * **Remote control: an assistant edits the window you have open** (by lienatanael-dev, #216, + ADR 0104, `docs/control-protocol.md`). `anicraft --control 9878` (or + `ANICRAFT_CONTROL_PORT`) lets an assistant edit the open document through a port on this + computer only; `anicraft-cli mcp --bridge 9878` is the MCP server's five tools acting on + that window. Edits show at once and undo with Ctrl+Z; they wait while you drag, so undo + steps never mix; the status bar says "Remote control on (port 9878)". Off unless you start + AniCraft this way. Each run has a fresh token in `control.json` in the settings folder + (readable only by you; `ANICRAFT_CONTROL_TOKEN` overrides it); anything that isn't a JSON + request with that token is refused. Added in review: the port closes with the window, a + connection that sends nothing is dropped after 10 s, the token file is always created new + and owner-only, and a portable install keeps it in its own folder + (`ANICRAFT_CONTROL_FILE` tells the bridge where). + * **Georgian, ready for its translation** (by Davit Matchakhelidze, #160). Builds made with + craft-fonts embed Noto Sans Georgian as a fallback face and offer Georgian (`ka`) once its + catalog is in craft-i18n; a build without the face doesn't offer it, and a damaged font + file is never loaded. * **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 @@ -27,14 +55,6 @@ * The keyboard shortcut editor moves from F1 to **Ctrl+Alt+Shift+K**, as in Animate. * A new chapter, **Using this guide**. -* **Fill and stroke alpha** (ADR 0097). - * The colour picker sets an alpha on a solid fill and on a stroke, from clear to opaque. - A clear fill is still a fill. No fill is the type None. - * Each stop of a linear or radial gradient keeps its own alpha, so a ramp can fade. The - stop's marker shows that alpha. - * A brush stroke that is not fully opaque stays its own shape, so the colour behind it - shows through and crossings darken. Opaque strokes still join. Group bundles the - separate strokes. The ink is drawn at that alpha while the pen is down. * **Sound output polish** (ADR 0095, M5). * The playhead follows the sound being **heard**: the device's latency is taken off and slow frames are dropped rather than drifting (within a frame over an hour of play in tests). @@ -481,21 +501,6 @@ click, Shift-click, Ctrl-click or a box. **Properties › Bone** counts the bone's points and has **Rebind All**. * Headless: `bone.add_in_shape`, `bone.bind`, and `bone.info` with `points`. -* **Remote control: assistants edit the open window live** (ADR 0104). - * `anicraft --control 9878` opens AniCraft as usual and lets an assistant edit the document you - have open, through a port on this computer only. Its edits appear at once and undo with - Ctrl+Z, like yours; the status bar says "Remote control on (port 9878)" while it is open. Also - `ANICRAFT_CONTROL_PORT`. - * `anicraft-cli mcp --bridge 9878`: the MCP server's five tools, acting on that window. It starts - before AniCraft is open, connects on the first call, says how to start AniCraft when it isn't - running, and reconnects after AniCraft is reopened. - * No setup: each run makes a fresh token and writes it to `control.json` in AniCraft's settings - folder (only you can read it), where the bridge finds it. `ANICRAFT_CONTROL_TOKEN` overrides it. - * While you drag, the assistant's edits wait until you let go, so the two never share an undo step. - * The protocol (`docs/control-protocol.md`): JSON lines on `127.0.0.1`; `hello`, `tools.list`, - `tools.call`; anything that isn't a JSON request (such as a web page's request to localhost) is - refused. - * **CI on macOS and Windows** (ADR 0067, M8). Every pull request that changes code now builds, tests and lints the workspace on macOS (arm64) and Windows (x64) runners as well as Linux, so macOS-only and Windows-only code is checked before it merges. Documentation-only changes skip @@ -687,9 +692,6 @@ `prefs.recent_pin`, `prefs.recent_remove`, `prefs.recent_clear`; `file.import` takes `cx`/`cy` and `layer: "active"`. -* **Free Transform: skew and shear** (#174). Dragging the line between two handles of the - selection box shears the artwork along that edge, as in Adobe Animate: the opposite edge stays - put and Alt skews about the centre. The cursor shows the direction. * **Buttons, complete: sounds on button frames and hit-area editing** (ADR 0057, M5). * A sound on a button's **Over** or **Down** frame plays when the pointer goes over or presses the button, in Test Movie and in the HTML canvas page (Web Audio). As the SWF format From 2fb798f12cf89faad4d9f3774080cc548689c92b Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 17 Nov 2026 13:59:24 -0700 Subject: [PATCH 18/20] fix(control): leave the control port and its getrandom out of wasm32 builds (M8) --- crates/cli/Cargo.toml | 5 ++++- crates/cli/src/lib.rs | 19 ++++++++++++++----- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index eed00e1f..c67cf6bc 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -21,8 +21,11 @@ anicraft-render.workspace = true anicraft-geom.workspace = true anicraft-guide.workspace = true serde_json.workspace = true + # The live control port's per-run token (ADR 0104): the operating system's random numbers. -# MIT OR Apache-2.0, already in the tree. +# MIT OR Apache-2.0, already in the tree. Not for the web: a page has no sockets, so the control +# port (and `mcp --bridge`) is left out of wasm32 builds. +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] getrandom = "0.3" [dev-dependencies] diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index 2c7bfdd4..090ab45f 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -2,6 +2,7 @@ //! server (`mcp`). Every operation goes through the engine's command registry. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#[cfg(not(target_arch = "wasm32"))] pub mod control; pub mod mcp; @@ -300,11 +301,19 @@ pub fn run(argv: &[String]) -> Result { if src.is_some() || a.flag("plugins").is_some() { return Err("mcp --bridge acts on the open AniCraft window: it takes no file or --plugins".into()); } - let mut b = control::Bridge::new(control::parse_bridge_target(target)?); - let stdin = std::io::stdin(); - let mut stdout = std::io::stdout(); - mcp::serve(&mut b, stdin.lock(), &mut stdout).map_err(|e| e.to_string())?; - return Ok(String::new()); + #[cfg(target_arch = "wasm32")] + { + let _ = target; + return Err("mcp --bridge needs sockets, which this build doesn't have".into()); + } + #[cfg(not(target_arch = "wasm32"))] + { + let mut b = control::Bridge::new(control::parse_bridge_target(target)?); + let stdin = std::io::stdin(); + let mut stdout = std::io::stdout(); + mcp::serve(&mut b, stdin.lock(), &mut stdout).map_err(|e| e.to_string())?; + return Ok(String::new()); + } } let mut s = session(&a, src)?; let stdin = std::io::stdin(); From c8ada927783fe46f84480b5e2168e9fb52bfc376 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 17 Nov 2026 14:42:51 -0700 Subject: [PATCH 19/20] test: an edit through the control port end to end, and the see-through brush preview (M8) --- src/brushtool.rs | 44 ++++++++++++++++++++++++++++++ src/remote.rs | 70 +++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 111 insertions(+), 3 deletions(-) diff --git a/src/brushtool.rs b/src/brushtool.rs index 8b982bb2..be1a8efa 100644 --- a/src/brushtool.rs +++ b/src/brushtool.rs @@ -606,6 +606,50 @@ pub fn draw_tip(painter: &egui::Painter, xf: Xf, o: &BrushOptions, at: Vec2) { mod tests { use super::*; + /// The pen-down ink of a see-through brush: one image at the alpha the stroke will keep, + /// in one texture that every frame reuses; opaque ink makes no image at all. + #[test] + fn a_wash_is_previewed_as_one_reused_image_and_opaque_ink_is_not() { + let ctx = egui::Context::default(); + let mut app = App::with_context(&ctx, anicraft_engine::Session::default(), Some(std::path::PathBuf::from("unused.png"))); + app.tool = Tool::Brush; + app.drag = Drag::Brush; + // A stroke that crosses itself, with a dab's worth of pressure readings. + app.brush_samples = vec![(Vec2::new(40.0, 40.0), Some(0.8)), (Vec2::new(160.0, 120.0), Some(0.6)), (Vec2::new(40.0, 120.0), None), (Vec2::new(160.0, 40.0), Some(0.9))]; + let xf = Xf { origin: egui::pos2(20.0, 20.0), zoom: 1.5 }; + let sweep = egui::Id::new("anicraft.brush.sweep"); + let texture = |ctx: &egui::Context| ctx.data(|d| d.get_temp::(sweep)); + let frame = |app: &App| { + let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(800.0, 600.0))), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| draw_overlay(app, ui.painter(), xf, Some(Pos2::new(100.0, 100.0)))); + out.textures_delta.clear(); // no renderer takes them here + out.shapes.len() + }; + // Opaque: the convex sweep, no image. + app.s.style.set_fill_color(anicraft_engine::doc::Rgba::new(1.0, 0.0, 0.0, 1.0)); + let opaque_shapes = frame(&app); + assert!(opaque_shapes > 1 && texture(&ctx).is_none(), "opaque ink needs no coverage image"); + // A wash: one image for the whole stroke (plus the tip under the pointer). + app.s.style.set_fill_color(anicraft_engine::doc::Rgba::new(1.0, 0.0, 0.0, 0.5)); + let wash_shapes = frame(&app); + let first = texture(&ctx).expect("the wash is drawn from a coverage image"); + let [w, h] = first.size(); + assert!(w > 100 && h > 100 && w <= MASK_MAX && h <= MASK_MAX, "{w} x {h}"); + assert!(wash_shapes < opaque_shapes, "one image, not a piece per step: {wash_shapes} against {opaque_shapes}"); + frame(&app); + assert_eq!(texture(&ctx).map(|t| t.id()), Some(first.id()), "the next frame reuses the texture"); + // Pressure as opacity previews at the average, and a clear colour draws nothing. + options_mut(&mut app).pressure_opacity = true; + frame(&app); + app.s.style.set_fill_color(anicraft_engine::doc::Rgba::new(1.0, 0.0, 0.0, 0.0)); + options_mut(&mut app).pressure_opacity = false; + assert!(frame(&app) < wash_shapes, "a clear fill has no ink to preview"); + // A view so far in that the stroke is larger than the image may be: still bounded. + let hulls = sweep_hulls(Xf { origin: Pos2::ZERO, zoom: 400.0 }, options(&app), &app.brush_samples); + assert_eq!(hulls.len(), 4, "three steps and the tip at the end"); + assert!(coverage(&hulls, Pos2::new(-1e9, f32::NAN), 1.0, 8, 8).iter().all(|c| *c == 0.0), "off-screen and non-finite input paints nothing"); + } + #[test] fn size_steps_are_round_and_bounded() { assert_eq!(step_size(10.0, true), 15.0); diff --git a/src/remote.rs b/src/remote.rs index b6de0506..7f4e7657 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -29,6 +29,13 @@ pub struct Remote { /// Opens the control port; failures go to the status bar (the window still opens). pub fn start(app: &mut App, ctx: &egui::Context, port: u16) { + // In the settings folder, which a portable install keeps beside the program (ADR 0094): + // nothing is written outside it. + start_at(app, ctx, port, platform::config_dir().map(|d| d.join(control::CONTROL_FILE))); +} + +/// [`start`], with where `control.json` goes. +fn start_at(app: &mut App, ctx: &egui::Context, port: u16, file: Option) { let token = match control::token_from_env().map_or_else(control::new_token, Ok) { Ok(t) => t, Err(e) => { @@ -44,9 +51,6 @@ pub fn start(app: &mut App, ctx: &egui::Context, port: u16) { return; } }; - // In the settings folder, which a portable install keeps beside the program (ADR 0094): - // nothing is written outside it. - let file = platform::config_dir().map(|d| d.join(control::CONTROL_FILE)); let written = file.as_ref().map(|path| { let contents = control::ControlFile { port: server.port, token: token.clone(), pid: std::process::id(), version: env!("CARGO_PKG_VERSION").to_string() }; platform::write_private_file(path, contents.to_json().to_string().as_bytes()) @@ -134,6 +138,66 @@ impl mcp::Host for Live<'_> { #[cfg(test)] mod tests { use crate::platform; + use std::path::PathBuf; + + /// The whole path an assistant's edit takes: the port opens and writes its token file, a + /// bridge finds the token there and runs a command, the frame loop makes the edit on the + /// window's document, and closing removes the file and frees the port. + #[test] + fn an_edit_through_the_port_lands_in_the_window_and_closing_cleans_up() { + let dir = std::env::temp_dir().join(format!("anicraft-remote-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let file = dir.join("control.json"); + // A file left by a run that crashed is replaced, not written through. + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(&file, "stale").unwrap(); + let ctx = egui::Context::default(); + let mut app = crate::app::App::with_context(&ctx, anicraft_engine::Session::default(), Some(PathBuf::from("unused.png"))); + assert_eq!(super::port(&app), None); + super::start_at(&mut app, &ctx, 0, Some(file.clone())); + let port = super::port(&app).expect("the port is open"); + let written = anicraft_cli::control::ControlFile::parse(&std::fs::read_to_string(&file).unwrap()).unwrap(); + assert_eq!((written.port, written.token.len(), written.pid), (port, 64, std::process::id())); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!(std::fs::metadata(&file).unwrap().permissions().mode() & 0o777, 0o600, "only the owner reads the token"); + } + // A second window asking for the same port says so and stays without one. + let mut other = crate::app::App::with_context(&ctx, anicraft_engine::Session::default(), Some(PathBuf::from("unused.png"))); + super::start_at(&mut other, &ctx, port, None); + assert!(super::port(&other).is_none() && other.status.as_ref().is_some_and(|s| s.error)); + + let before = app.s.revision; + let token_file = file.clone(); + let client = std::thread::spawn(move || { + let addr = anicraft_cli::control::parse_bridge_target(&port.to_string()).unwrap(); + let mut bridge = anicraft_cli::control::Bridge::with_token_file(addr, Some(token_file)); + let read = bridge.call_tool("anicraft_document", &serde_json::json!({})); + let edit = bridge.call_tool("anicraft_run", &serde_json::json!({"command": "draw.rect", "params": {"x": 10, "y": 10, "w": 40, "h": 30}})); + (read.is_ok(), edit) + }); + while !client.is_finished() { + super::poll(&mut app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(2)); + } + let (read, edit) = client.join().unwrap(); + assert!(read, "a call that only reads answers"); + assert!(edit.is_ok(), "{edit:?}"); + assert!(app.s.revision > before, "the rectangle is in the window's document"); + assert!(app.s.history().undo_len() >= 1, "and it undoes like the person's own edit"); + + super::finish(&mut app); + assert!(!file.exists(), "the token file goes when the window closes"); + assert_eq!(super::port(&app), None); + // The port is free again: the same run can open another window on it (ADR 0092). + let freed = (0..200).any(|_| { + std::thread::sleep(std::time::Duration::from_millis(10)); + std::net::TcpListener::bind(("127.0.0.1", port)).is_ok() + }); + assert!(freed, "port {port} is still taken"); + let _ = std::fs::remove_dir_all(&dir); + } /// The CLI finds `control.json` with its own copy of the settings-folder rule (it can't use /// the shell); they must agree, or the bridge looks in the wrong place. From 3f214d7ccdd19d08596020b7cc5a5135baa21add Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 17 Nov 2026 17:52:50 -0700 Subject: [PATCH 20/20] fix(control): close a refused connection gracefully so the client reads the reply (M8) Closing a socket with unread input resets the connection, and on macOS the reset can discard the refusal before the client reads it (the oversized-line test failed on the macOS gate). The port now stops writing, drains what the client is still sending (bounded: 8 MiB, 2 s), then closes. --- crates/cli/src/control.rs | 35 ++++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/crates/cli/src/control.rs b/crates/cli/src/control.rs index e2ce432e..dcf85213 100644 --- a/crates/cli/src/control.rs +++ b/crates/cli/src/control.rs @@ -295,20 +295,23 @@ fn serve_connection(stream: TcpStream, token: &str, tx: &Sender, wake: Ok(None) | Err(LineError::Io(_)) => return, Err(LineError::TooLong) => { let _ = writeln!(out, "{}", fail(&Value::Null, format!("request longer than {} MiB", MAX_LINE / (1024 * 1024)))); - return; + return close_after_reply(&out, &mut reader); } Err(LineError::NotText) => { let _ = writeln!(out, "{}", fail(&Value::Null, "the request is not UTF-8 text")); - return; + return close_after_reply(&out, &mut reader); } }; if line.trim().is_empty() { continue; } let (reply, keep_open) = answer(&line, token, tx, wake); - if writeln!(out, "{reply}").and_then(|()| out.flush()).is_err() || !keep_open { + if writeln!(out, "{reply}").and_then(|()| out.flush()).is_err() { return; } + if !keep_open { + return close_after_reply(&out, &mut reader); + } // Only a request with the right token keeps the connection open: from here on the // client may be idle for as long as it likes (an assistant between calls). if !known { @@ -319,6 +322,32 @@ fn serve_connection(stream: TcpStream, token: &str, tx: &Sender, wake: } } +/// Most a refused client may still send after its reply before the connection is cut, and for +/// how long (see [`close_after_reply`]). +const DRAIN_BYTES: u64 = 2 * MAX_LINE as u64; +const DRAIN_TIME: Duration = Duration::from_secs(2); + +/// Closes a connection after a refusal so the client still reads the reply. Closing a socket +/// with unread input makes the system reset the connection, and a reset may discard the reply +/// before the client reads it (macOS does). So: no more writes, then read and drop what the +/// client is still sending, bounded in bytes and time, then close. +fn close_after_reply(out: &TcpStream, reader: &mut BufReader) { + let _ = out.shutdown(std::net::Shutdown::Write); + let _ = reader.get_ref().set_read_timeout(Some(DRAIN_TIME)); + let started = Instant::now(); + let mut buf = [0u8; 64 * 1024]; + let mut left = DRAIN_BYTES; + // Bytes already buffered count too. + let buffered = reader.buffer().len(); + reader.consume(buffered); + while left > 0 && started.elapsed() < DRAIN_TIME { + match reader.get_mut().read(&mut buf) { + Ok(0) | Err(_) => break, + Ok(n) => left = left.saturating_sub(n as u64), + } + } +} + /// The reply to one request line, and whether the connection stays open. fn answer(line: &str, token: &str, tx: &Sender, wake: &Wake) -> (Value, bool) { let req = match parse_request(line) {