chore: merge main (outside features batch: skew) into the outside UI batch (M8)

This commit is contained in:
Tanish Manku committed 2026-11-17 18:30:16 -07:00
commit 968946ea0b
38 files changed
+2235 -104

No files matched your search

+1
View File
@@ -63,6 +63,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)
+4
View File
@@ -4,6 +4,10 @@ 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).
* Mex (MMexicann): SVG path data, `Math.round` and `Math.min`/`max` signed zeros, affine inverses, documentation.
* NetterSilver (Silvertree2010): shape tweens that morph a raw shape's line with its fill, dash patterns, colour, easing and script-string parsing; an XFL nested-group regression test.
* jayzed80: flipped scales in Properties, CLI subcommand help and frame numbering; copy, cut and paste keys on the stage.
+28
View File
@@ -37,6 +37,34 @@
scene's artwork on the stage (fixes #305).
* **Camera** (Kushagra Kumar): with the camera layer hidden, Preview Through Camera no longer
blocks drawing on the stage (fixes #126).
* **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.
* **Fixes and polish from outside contributors.** Thank you all.
* **Shape tweens carry a raw shape's line with its fill** (#119, NetterSilver): when the two keyframes' lines have different numbers of pieces (a triangle into a hexagon), the pieces join into outlines that morph as the fill does, with no side left bare and no line left standing; a line on one keyframe only grows in or shrinks away, and shape hints steer the line too.
* **Flipping no longer squashes a shape to 1 %** (#116, jayzed80): the Scale fields in Properties show a mirrored scale as a negative percentage and never rewrite a value they only show.
Generated
+2
View File
@@ -234,6 +234,7 @@ name = "anicraft"
version = "0.3.0"
dependencies = [
"anicraft-audio",
"anicraft-cli",
"anicraft-doc",
"anicraft-engine",
"anicraft-geom",
@@ -284,6 +285,7 @@ dependencies = [
"anicraft-geom",
"anicraft-guide",
"anicraft-render",
"getrandom 0.3.4",
"serde_json",
"wat",
]
+3
View File
@@ -120,6 +120,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 0104): 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"] }
+4 -2
View File
@@ -3,7 +3,8 @@
//!
//! `CRAFT_FONTS_DIR=<craft-fonts checkout> 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=<craft-i18n checkout>` embeds the interface catalogs (ADR 0040); without it
@@ -12,7 +13,8 @@
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<PathBuf> {
let entries = std::fs::read_dir(dir).ok()?;
+7 -1
View File
@@ -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
@@ -22,6 +22,12 @@ 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. 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]
# Exporter plug-in fixtures written in WebAssembly text (Apache-2.0 WITH LLVM-exception).
wat = "1.228"
+561
View File
@@ -0,0 +1,561 @@
//! The live control channel (ADR 0104, `docs/control-protocol.md`): the desktop app's control
//! port, and the client `anicraft-cli mcp --bridge <port>` 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::{AtomicBool, 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);
/// 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.
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<PathBuf> {
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 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<PathBuf> {
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.
pub fn token_from_env() -> Option<String> {
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<String, String> {
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<u16, String> {
match s.trim().parse::<u16>() {
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<ControlFile, String> {
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: BufRead>(r: &mut R, limit: usize) -> Result<Option<String>, 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<String>,
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<Incoming, String> {
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<String>) -> 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<Result<Value, String>>,
}
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<H: mcp::Host + ?Sized>(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<dyn Fn() + Send + Sync>;
/// 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<Request>,
stop: Arc<AtomicBool>,
}
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 {
/// The next waiting tool call, if any.
pub fn try_recv(&self) -> Option<Request> {
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<Server> {
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<Server> {
let listener = TcpListener::bind(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port))?;
let port = listener.local_addr()?.port();
let (tx, rx) = channel();
let token: Arc<str> = token.into();
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<str>, tx: &Sender<Request>, 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 {
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, first_request);
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<Request>, 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 {
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 close_after_reply(&out, &mut reader);
}
Err(LineError::NotText) => {
let _ = writeln!(out, "{}", fail(&Value::Null, "the request is not UTF-8 text"));
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() {
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 {
known = true;
// On the reading handle itself: Windows keeps the timeout per handle, not per socket.
let _ = reader.get_ref().set_read_timeout(None);
}
}
}
/// 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<TcpStream>) {
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<Request>, 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<SocketAddr, String> {
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:<port> (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<String>, file: Option<&Path>) -> Result<String, String> {
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<u16>) -> 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<TcpStream>,
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<Conn>,
next_id: u64,
/// Where the token comes from (tests point it elsewhere).
token_file: Option<PathBuf>,
}
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<PathBuf>) -> Bridge {
Bridge { addr, conn: None, next_id: 1, token_file: file }
}
fn connect(&mut self) -> Result<String, BridgeError> {
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<Value, BridgeError> {
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<Value, BridgeError> {
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<Value, String> {
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;
+287
View File
@@ -0,0 +1,287 @@
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<AtomicBool>,
loop_thread: Option<std::thread::JoinHandle<Session>>,
}
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>, 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>, 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>, 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);
}
/// 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");
}
+23
View File
@@ -2,6 +2,8 @@
//! 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;
use anicraft_engine::{Session, commands, format};
@@ -45,6 +47,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 <port> the same tools, acting live on the AniCraft window
started with `anicraft --control <port>`
(docs/control-protocol.md)
anicraft-cli --version
--plugins <folder> loads the WebAssembly plug-ins in a folder first (also the
@@ -323,6 +328,24 @@ pub fn run(argv: &[String]) -> Result<String, String> {
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());
}
#[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();
let mut stdout = std::io::stdout();
+68 -14
View File
@@ -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 0104): the app runs [`call_tool`] on its own
//! session for requests from its control port, and `anicraft-cli mcp --bridge <port>` 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<String>) -> 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<Value, String>;
}
impl Host for Session {
fn session(&self) -> &Session {
self
}
fn execute(&mut self, id: &str, params: &Value) -> Result<Value, String> {
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<Value, String> {
let run = |s: &mut Session, step: &Value| -> Result<Value, String> {
pub fn call_tool<H: Host + ?Sized>(h: &mut H, name: &str, args: &Value) -> Result<Value, String> {
let run = |h: &mut H, step: &Value| -> Result<Value, String> {
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, &params).map_err(|e| format!("{id}: {e}"))
h.execute(id, &params).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<Value, String>
.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<Value, String>
}
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<Value, String>
})
}
/// 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<Value, String>;
}
impl Backend for Session {
fn instructions(&self) -> &'static str {
INSTRUCTIONS
}
fn call(&mut self, name: &str, args: &Value) -> Result<Value, String> {
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<Value> {
pub fn handle<B: Backend + ?Sized>(s: &mut B, line: &str) -> Option<Value> {
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<Value> {
"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<Value> {
"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<Value> {
/// 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<R: BufRead, W: Write>(s: &mut Session, input: R, out: &mut W) -> std::io::Result<()> {
pub fn serve<B: Backend + ?Sized, R: BufRead, W: Write>(s: &mut B, input: R, out: &mut W) -> std::io::Result<()> {
for line in input.lines() {
let line = line?;
if line.trim().is_empty() {
+62
View File
@@ -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<Value> = (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] {
+24 -7
View File
@@ -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 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};
@@ -20,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
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::<f32>() / 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 0102).
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<Value> {
let pts = bounded_samples(p)?;
let b = brush_param(s, p)?;
@@ -296,18 +308,20 @@ fn draw_brush(s: &mut Session, p: &Value) -> Result<Value> {
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 0102).
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 0102).
fn paint_stroke(s: &mut Session, pts: &[Sample], b: &BrushPreset, smoothing: f32, tol: f32, color: Rgba, object: bool) -> Result<Value> {
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)
}
+2 -2
View File
@@ -27,8 +27,8 @@ pub fn specs() -> Vec<CommandSpec> {
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))),
+1 -1
View File
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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,
),
+58
View File
@@ -0,0 +1,58 @@
# ADR 0102: Fill alpha
* 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
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.
## 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.
+117
View File
@@ -0,0 +1,117 @@
# ADR 0104: 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 <port>`** (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 <port | 127.0.0.1:port>`** 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.
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
* 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`).
+110
View File
@@ -0,0 +1,110 @@
# The live control port
`anicraft --control <port>` 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 0104 records the design.
Most people never speak this protocol themselves: AI assistants reach it through
`anicraft-cli mcp --bridge <port>` (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 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=<path to control.json>`.
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).
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()
```
+1 -1
View File
@@ -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.
+2 -2
View File
@@ -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. Ctrl+click steps, then Save As Command… ([saved commands](saved-commands.md)). |
| Color and Swatches | **Window › Colour** (stroke and fill, Swap, Black and White). Click the Fill or Stroke squares in the Tools panel, the Colour panel, or any colour swatch in Properties: web-safe swatches, a mixer and a hex field. The fill's picker also sets its type (None, Solid, Linear, Radial, Bitmap) and a gradient's stops, overflow and Linear RGB, like the Color panel. **Window › Swatches** keeps the document's colours and gradients (click applies to the active stroke or fill, drag to reorder, import and export swatch files and GIMP `.gpl` palettes; not Adobe `.aco`/`.ase`/`.clr`). |
| 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 › New Scene** and **Modify › Scene**. |
| Find and Replace | **Edit › Find and Replace** (**Ctrl+F**). |
@@ -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. |
+16 -10
View File
@@ -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,11 +348,12 @@ 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
**Position**, **Scale** and **Rotation** values in Properties. The lock beside **Scale** keeps
width and height in proportion.
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. The lock
beside **Scale** keeps width and height in proportion.
| Command | Menu | Key |
|---|---|---|
+4 -4
View File
@@ -500,9 +500,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
@@ -602,7 +602,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`
@@ -656,7 +656,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`
+18 -1
View File
@@ -265,7 +265,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).
+3 -2
View File
@@ -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 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. |
| Vietnamese | Not offered yet: needs a check that every fallback face has its letters. |
+30
View File
@@ -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 <port>` the same tools act on the AniCraft window you have open, started with
`anicraft --control <port>`: every edit appears there at once, and Ctrl+Z undoes it
(`docs/control-protocol.md`, ADR 0104). 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 |
@@ -59,3 +86,6 @@ unlike `anicraft_run_script` a failing step leaves the document as it was. `macr
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.
+2 -2
View File
@@ -15,10 +15,10 @@ 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 (`<mask>` 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 `<g opacity>`. **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 boLine truncated
| 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 onLine truncated
| 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 Line truncated
| 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_styLine truncated
| 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 `<settings>/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 <id>` 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`, `tLine truncated
| 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 0104, `docs/control-protocol.md`): `anicraft --control <port>` and `anicraft-cli mcp --bridge <port>` run the same tools on the open window, on this computer only, 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. **Output polish** (ADR 0095): the playhead follows the sound *heard* (the device's latency taken off, frames dropped rather than drifting; under a frame off over an hour in tests), event sounds play to their end across a loop and after the last frame (Enter stops all), a **monitor volume and mute** in the timeline header (Control › Mute Sounds; the listener's, in preferences, never in exports), **Control › Audio Scrubbing** (a slice of at least 1/20 s), a lost or missing device never crashes (silent playback, one notice, a log line, reopened on the next play; a new default device is followed), and the **web build plays sound through Web Audio**. The device sits behind an `Output` trait, so the clock and mixing paths are tested with a fake one. 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, choosing an output device other than the system's default, `stopAllSounds` as a timeline action. |
| 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** (WebP container writing delegates to shared `craft-webp`; APNG framing remains app-local; 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. One damaged bitmap, sound or library symbol is left out and reported rather than refusing the whole file (#226), and a document without a stage colour gets Animate's default white (#163). 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). Shared `craft-xfl` readers now parse filters, shape hints, tween easing, and frame-sound envelopes; AniCraft retains document-model mapping and validation. The XFL schema audit remains in progress, including per-character styles and motion-tween records; **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, tranLine truncated
| 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. |
+14 -1
View File
@@ -146,7 +146,7 @@ impl Tool {
Tool::Bind => tr_noop!("Shows the points of shapes with bones: a square follows one bone, a triangle several. Click a bone to see the points it moves (filled). Click a point, or drag a box around points, to make them follow only that bone; Shift shares the bone with the ones they follow, Ctrl takes them from it. Turn on Paint Weights in Properties to brush the bone's influence on, off or smooth, shown as a heat map."),
Tool::Warp => tr_noop!("Click a shape or a bitmap to pin it (the first pin covers it with a warp mesh). Drag a pin to bend the artwork around the other pins; with one pin it moves. Click a pin and press Delete to remove it. A pin moved at another frame keys it, and pins tween."),
Tool::GradientTransform => tr_noop!("Click a shape with a gradient or bitmap fill to show its handles. Drag the centre to move the fill, the square to change its width, the circle to change its size, the knob to rotate it (Shift: 15° steps) and, on a radial gradient, the triangle to move its focal point. A bitmap fill also has a square for its height and diamonds to skew it. Each drag is one undo step."),
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 or a polygon (Shape in the options)."),
@@ -293,6 +293,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).
@@ -350,6 +353,9 @@ impl PolyStarOptions {
pub struct App {
#[cfg(not(target_arch = "wasm32"))]
pub(crate) updates: crate::updates::Updates,
/// The live control port, with `--control` (ADR 0104).
#[cfg(not(target_arch = "wasm32"))]
pub(crate) remote: Option<crate::remote::Remote>,
pub s: Session,
pub tool: Tool,
pub view: StageView,
@@ -697,6 +703,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, clip_to_stage: false },
@@ -3948,6 +3956,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) {
@@ -3969,6 +3979,9 @@ impl App {
}
}
self.handle_screenshot(&ctx);
// An assistant's edits (ADR 0104), 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_look(&ctx);
if let Some(p) = platform::picked_file() {
+276 -3
View File
@@ -343,6 +343,37 @@ fn hull(mut pts: Vec<Pos2>) -> Vec<Pos2> {
/// 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>)]) -> 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<Po
let o = options(app);
let (paint, tip) = if app.tool == Tool::PaintBrush { (app.s.style.stroke, BrushOptions { shape: TipShape::Round, roundness: 100.0, ..*o }) } else { (app.s.style.fill, *o) };
if app.drag == Drag::Brush {
// Opaque, so overlapping pieces don't darken each other.
let color = to_color32(anicraft_engine::doc::Rgba { a: 1.0, ..paint });
draw_sweep(painter, xf, &tip, &app.brush_samples, color);
let alpha = intended_alpha(&tip, paint.a, &app.brush_samples);
// Opaque ink stays the convex sweep the Eraser shares. A wash is one coverage image
// at the alpha the stroke will keep, so the pen-down ink matches the ink after you
// lift (ADR 0102).
if (alpha * 255.0).round() >= 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<f32>)]) -> Vec<Vec<Pos2>> {
if samples.is_empty() {
return Vec::new();
}
let unit = o.unit_outline();
let screen = |at: Vec2, pressure: Option<f32>| -> Vec<Pos2> {
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<f32>)> = samples.iter().step_by(step).chain(samples.last()).collect();
let mut hulls = Vec::new();
let mut push = |pts: Vec<Pos2>| {
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<f32>)], 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::<egui::TextureHandle>(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<Pos2>], origin: Pos2, scale: f32, w: usize, h: usize) -> Vec<f32> {
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);
@@ -401,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::<egui::TextureHandle>(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);
@@ -449,4 +698,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]);
}
}
+23 -6
View File
@@ -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
}
+38 -8
View File
@@ -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<GradientStop>) -> 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<GradientStop>) -> 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::<Vec<_>>().join("\n")).unwrap_or_default();
}
assert!(labels.contains("Alpha"), "the fill picker has no Alpha control:\n{labels}");
}
}
+17 -2
View File
@@ -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<Languages> = 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)");
}
+31
View File
@@ -310,6 +310,37 @@ 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") {
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");
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");
// ... 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
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());
}
#[test]
fn lookups_fall_back_from_app_to_shared_to_base_language_to_english() {
let l = fixture();
+35 -4
View File
@@ -78,6 +78,8 @@ mod macros_ui;
mod plugins_ui;
mod prefs;
mod recent;
#[cfg(not(target_arch = "wasm32"))]
mod remote;
mod rich_edit;
mod rulers;
mod scale_grid;
@@ -154,7 +156,7 @@ struct Look {
}
#[cfg(not(target_arch = "wasm32"))]
fn run(attempt: startup::Attempt, file: Option<&Path>, shot: Option<PathBuf>, open: Option<String>, look: Look) -> eframe::Result {
fn run(attempt: startup::Attempt, file: Option<&Path>, shot: Option<PathBuf>, open: Option<String>, look: Look, control: Option<u16>) -> eframe::Result {
let options = attempt.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])),
..Default::default()
@@ -186,6 +188,10 @@ fn run(attempt: startup::Attempt, file: Option<&Path>, shot: Option<PathBuf>, op
start::open(&mut a);
}
a.preview_look(&cc.egui_ctx, look.theme, look.scale);
// `--control`: an assistant can edit this window live (ADR 0104).
if let Some(port) = control {
remote::start(&mut a, &cc.egui_ctx, port);
}
a.open_panel(open.as_deref());
match report {
// An imported document says what came across, as opening it from the menu does.
@@ -216,6 +222,8 @@ struct Args {
open: Option<String>,
renderer: Option<String>,
look: Look,
/// `--control <port>`: the live control port (ADR 0104).
control: Option<u16>,
/// `--version` / `--help`: print and leave.
print: Option<Print>,
}
@@ -236,6 +244,8 @@ fn parse_args(args: impl IntoIterator<Item = String>) -> Result<Args, String> {
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::<u32>().ok()) {
Some(w) if (64..=8192).contains(&w) => out.look.shot_width = Some(w),
@@ -272,7 +282,7 @@ fn parse_args(args: impl IntoIterator<Item = String>) -> Result<Args, String> {
/// `--help` (the console's text, in English).
#[cfg(not(target_arch = "wasm32"))]
// i18n-exempt: the --help console text
const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width <px>]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|light|high-contrast] [--scale <percent>] [--lang <code>|auto|pseudo] [--open palette|shortcuts|helpbone|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|erasemerge|tiltbrush|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|shapeweights|mixedbones|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|richtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|plugineases|pluginexport|pluginexportwindow|library|librarymenu|libraryfolders|colour|layerprops|frameview|layercolour|timelinepolish|dock|dockicons|floattabs|docknarrow|workspaces|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\
const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width <px>]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale <percent>] [--lang <code>|auto|pseudo] [--control <port>] [--open palette|shortcuts|helpbone|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|erasemerge|tiltbrush|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|shapeweights|mixedbones|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|richtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|plugineases|pluginexport|pluginexportwindow|library|librarymenu|libraryfolders|colour|layerprops|frameview|layercolour|timelinepolish|dock|dockicons|floattabs|docknarrow|workspaces|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\
--renderer the window's graphics (also ANICRAFT_RENDERER); default automatic, falling back to OpenGL\n\
--open shows a panel at start (handy with --screenshot for visual checks)\n\
--shot-width scales the screenshot down to this width (the user guide's pictures)\n\
@@ -280,6 +290,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"))]
@@ -309,7 +321,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();
@@ -328,7 +354,7 @@ fn main() -> eframe::Result {
let attempts = startup::plan(platform::forced_backend(renderer.as_deref()), prefs::Prefs::load().window_backend, &platform::window_attempts(platform::OS), &last);
for (n, attempt) in attempts.iter().enumerate() {
startup::trying(attempt, n + 1, attempts.len());
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(*attempt, file.as_deref(), shot.clone(), open.clone(), look.clone())));
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(*attempt, file.as_deref(), shot.clone(), open.clone(), look.clone(), control)));
why = match result {
Ok(Ok(())) => {
// The window's graphics device was lost mid-session (ADR 0092): it closed
@@ -395,6 +421,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 <port>` (ADR 0104): 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();
+37 -29
View File
@@ -178,7 +178,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 };
@@ -197,7 +197,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
}
@@ -213,12 +213,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;
@@ -234,7 +234,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);
}
@@ -253,8 +253,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 ------------------------------------------------------------------
@@ -447,6 +448,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 0104): 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);
@@ -569,25 +577,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| {
@@ -596,7 +604,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"));
}
});
@@ -615,10 +623,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)}));
}
}
}
@@ -1226,22 +1234,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));
@@ -1251,11 +1259,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}));
@@ -2900,10 +2908,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,
@@ -2926,9 +2934,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"));
+28
View File
@@ -412,6 +412,34 @@ pub fn recovery_dir() -> Option<PathBuf> {
}
}
/// 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 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_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.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())
+209
View File
@@ -0,0 +1,209 @@
//! Remote control (ADR 0104, `docs/control-protocol.md`): `anicraft --control <port>` 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<control::Request>,
token: String,
/// `control.json`, when it could be written.
file: Option<PathBuf>,
}
/// 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<PathBuf>) {
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 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<u16> {
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<Value, String> {
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;
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.
#[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")));
}
}
+56 -1
View File
@@ -387,6 +387,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,
@@ -1440,7 +1442,8 @@ fn xf_snap(s: &mut anicraft_engine::Session, ring: &mut Option<Vec2>, 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;
}
@@ -4135,6 +4138,8 @@ fn rt_size(te: &crate::app::TextEditing) -> 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])
@@ -4153,6 +4158,19 @@ fn xf_zone(r: Rect, p: Pos2) -> Option<XfKind> {
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);
}
@@ -4200,6 +4218,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);
@@ -4435,11 +4467,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);
+33 -1
View File
@@ -529,6 +529,31 @@ pub fn embedded_fonts() -> Vec<std::sync::Arc<[u8]>> {
[craft_fonts::UI_FONT, craft_fonts::MONO_FONT].into_iter().flatten().map(std::sync::Arc::from).collect()
}
/// 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]> {
static FACE: std::sync::OnceLock<Option<&'static [u8]>> = std::sync::OnceLock::new();
*FACE.get_or_init(|| craft_fonts::GEORGIAN_FONT.filter(|b| parses_as_font(b)))
}
/// Whether `bytes` is a font file that draws every Georgian letter (U+10D0..U+10FA).
fn parses_as_font(bytes: &[u8]) -> bool {
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)]
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.
pub fn font_summary() -> String {
match (craft_fonts::UI_FONT, craft_fonts::MONO_FONT) {
@@ -544,7 +569,8 @@ pub type UserFont = (String, Vec<u8>, 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;
@@ -555,6 +581,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) = 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}");