diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bc60765..3b3ad03 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,9 +26,10 @@ jobs: - name: Build and package every plugin run: | mkdir -p target/plugins - for dir in .generated/generated-circle examples/*; do + for dir in .generated/generated-circle examples/* community/*; do cargo fmt --manifest-path "$dir/Cargo.toml" --check cargo clippy --manifest-path "$dir/Cargo.toml" --target wasm32-wasip2 --locked -- -D warnings + cargo test --manifest-path "$dir/Cargo.toml" --workspace --locked bash "$dir/build.sh" cp "$dir"/target/*.amplugin target/plugins/ done @@ -41,3 +42,16 @@ jobs: dpkg-deb -x .host/*.deb .host/extracted python3 -m pip install Pillow python3 scripts/smoke.py .host/extracted/usr/bin/animathio-cli target/plugins + - name: Test Code Snippets on released 2.1.0 + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release download v2.1.0 --repo AniMathIO/AniMathIO --pattern '*AppImage' --dir .host/code-snippets + echo 'cce18dd8215aa9c23ba7c5756e6c0785c1931dd027aadf31a7bbbf3b92fac6ec .host/code-snippets/animathio_2.1.0_x86_64.AppImage' | sha256sum -c - + chmod +x .host/code-snippets/*.AppImage + (cd .host/code-snippets && ./animathio_2.1.0_x86_64.AppImage --appimage-extract > /dev/null) + python3 community/code-snippets/smoke.py .host/code-snippets/squashfs-root/usr/bin/animathio-cli target/plugins + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: plugins + path: target/plugins/*.amplugin diff --git a/README.md b/README.md index 995334a..44720d9 100644 --- a/README.md +++ b/README.md @@ -52,5 +52,7 @@ The host provides bounded services; plugins have no direct network or filesystem | Name | Description | Source | License | CI | ABI | | --- | --- | --- | --- | --- | --- | -No community entries yet. Submit a PR adding a row under the rules in +| [Code Snippets](community/code-snippets) | Syntax-highlighted code with reveal and token morph animations | [Source](https://github.com/AniMathIO/plugins/tree/main/community/code-snippets) | MIT; font OFL-1.1 | [Plugins CI](https://github.com/AniMathIO/plugins/actions/workflows/ci.yml) | 1.1.0 | + +Submit a PR adding a row under the rules in [CONTRIBUTING.md](CONTRIBUTING.md). A listing is not an endorsement or security audit. diff --git a/community/code-snippets/Cargo.lock b/community/code-snippets/Cargo.lock new file mode 100644 index 0000000..0201057 --- /dev/null +++ b/community/code-snippets/Cargo.lock @@ -0,0 +1,1006 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "auditable-serde" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c7bf8143dfc3c0258df908843e169b5cc5fcf76c7718bd66135ef4a9cd558c5" +dependencies = [ + "semver", + "serde", + "serde_json", + "topological-sort", +] + +[[package]] +name = "bincode" +version = "1.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" +dependencies = [ + "serde", +] + +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "code-snippets" +version = "0.1.0" +dependencies = [ + "syntect", + "ttf-parser", + "wit-bindgen", +] + +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "fancy-regex" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "998b056554fbe42e03ae0e152895cd1a7e1002aec800fdc6635d20270260c46f" +dependencies = [ + "bit-set", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "linked-hash-map" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "spdx" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3" +dependencies = [ + "smallvec", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "syntect" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "656b45c05d95a5704399aeef6bd0ddec7b2b3531b7c9e900abbf7c4d2190c925" +dependencies = [ + "bincode", + "fancy-regex", + "flate2", + "fnv", + "once_cell", + "regex-syntax", + "serde", + "serde_derive", + "thiserror", + "walkdir", + "yaml-rust", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "topological-sort" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea68304e134ecd095ac6c3574494fc62b909f416c4fca77e440530221e549d3d" + +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasm-encoder" +version = "0.227.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bb72f02e7fbf07183443b27b0f3d4144abf8c114189f2e088ed95b696a7822" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.227.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce1ef0faabbbba6674e97a56bee857ccddf942785a336c8b47b42373c922a91d" +dependencies = [ + "anyhow", + "auditable-serde", + "flate2", + "indexmap", + "serde", + "serde_derive", + "serde_json", + "spdx", + "url", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.227.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f51cad774fb3c9461ab9bccc9c62dfb7388397b5deda31bf40e8108ccd678b2" +dependencies = [ + "bitflags", + "hashbrown 0.15.5", + "indexmap", + "semver", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "wit-bindgen" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e7091ed6c9abfa4e0a2ef3b39d0539da992d841fcf32c255f64fb98764ffee5" +dependencies = [ + "wit-bindgen-rt", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "398c650cec1278cfb72e214ba26ef3440ab726e66401bd39c04f465ee3979e6b" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68faed92ae696b93ea9a7b67ba6c37bf09d72c6d9a70fa824a743c3020212f11" +dependencies = [ + "bitflags", + "futures", + "once_cell", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83903c8dcd8084a8a67ae08190122cf0e25dc37bdc239070a00f47e22d3f0aae" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 2.0.119", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7bf7f20495bcc7dc9f24c5fbcac9e919ca5ebdb7a1b1841d74447d3c8dd0c60" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.227.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "635c3adc595422cbf2341a17fb73a319669cc8d33deed3a48368a841df86b676" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.227.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddf445ed5157046e4baf56f9138c124a0824d4d1657e7204d71886ad8ce2fc11" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yaml-rust" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" +dependencies = [ + "linked-hash-map", +] + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/community/code-snippets/Cargo.toml b/community/code-snippets/Cargo.toml new file mode 100644 index 0000000..1b016f1 --- /dev/null +++ b/community/code-snippets/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "code-snippets" +version = "0.1.0" +edition = "2021" +license = "MIT" +publish = false + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +wit-bindgen = "=0.40.0" +syntect = { version = "5.3", default-features = false, features = ["parsing", "regex-fancy", "dump-load", "default-themes"] } +ttf-parser = "0.25" + +[profile.release] +opt-level = 3 +lto = true +strip = "debuginfo" + +[workspace] + +[build-dependencies] +syntect = { version = "5.3", default-features = false, features = ["parsing", "regex-fancy", "yaml-load", "dump-create"] } diff --git a/community/code-snippets/NOTICE b/community/code-snippets/NOTICE new file mode 100644 index 0000000..02e3912 --- /dev/null +++ b/community/code-snippets/NOTICE @@ -0,0 +1,31 @@ +Code Snippets for AniMathIO +Copyright (c) 2026 AniMathIO contributors. MIT (see ../../LICENSE). + +Behavioral port / inspiration: +Shiki Magic Move, Anthony Fu +https://github.com/shikijs/shiki-magic-move/tree/v1.1.0 +MIT License, copyright (c) 2022 Anthony Fu. +Studied src/core.ts (token matching) and src/renderer.ts (retained token movement, +enter/leave transitions). This plugin reimplements those ideas in Rust: bounded +lexical-token LCS plus one-to-one moved-identifier matching; position interpolation +and opacity driven by a supplied progress parameter. No TypeScript, CSS, Shiki +runtime, upstream syntax grammar or animation source code is copied. +The upstream license is retained in assets/shiki-magic-move-LICENSE. + +Embedded font: +JetBrains Mono Regular, version 2.304, unmodified +https://github.com/JetBrains/JetBrainsMono/tree/v2.304 +Copyright 2020 The JetBrains Mono Project Authors +SIL Open Font License 1.1; full license: assets/OFL.txt. + +Syntax highlighting / themes: +syntect 5.3 (MIT), Tristan Hume, Keith Hall, Google Inc and contributors +https://github.com/trishume/syntect +Full license: assets/syntect-LICENSE. Its default theme dump is embedded. +The small lexical grammars in syntaxes/ are original MIT code for this plugin. +No external grammar dump is embedded. Uses fancy-regex (MIT), not Oniguruma. + +Font outlines use ttf-parser (MIT OR Apache-2.0): +https://github.com/harfbuzz/ttf-parser +Other Rust dependencies retain their respective permissive licenses; the exact +resolved dependency set is in Cargo.lock. diff --git a/community/code-snippets/README.md b/community/code-snippets/README.md new file mode 100644 index 0000000..6b92043 --- /dev/null +++ b/community/code-snippets/README.md @@ -0,0 +1,132 @@ +# Code Snippets + +Animated, syntax-highlighted code for AniMathIO 2. ABI **1.1.0**, tested with the +released **AniMathIO 2.1.0** Linux CLI. MIT; embedded JetBrains Mono is OFL 1.1. +Plugin ID: `org.animathio.community.code-snippets`. + +A behavioral port of [Shiki Magic Move](https://github.com/shikijs/shiki-magic-move/tree/v1.1.0) +by Anthony Fu (**MIT**): retained tokens slide to their new positions while removed +and added tokens fade. Exits fade during 0–60% progress, retained tokens move with smooth ease-in-out +during 15–85%, and entries fade during 40–100%, keeping both edits visible at midpoint. +Upstream 1.1.0 defaults to a 500 ms duration, zero stagger, CSS `ease`, and +leave/move/enter delays of 0.1/0.3/0.7 times the duration; each phase runs for +the full duration, so they overlap. Our normalized windows preserve that overlap +within the host’s 0–1 progress range. We studied its token key synchronization and enter/leave/move +renderer, then implemented bounded token LCS and vector drawing in Rust. No upstream +animation code is copied. See [NOTICE](NOTICE) and its retained MIT license. + +## Build and install + +```sh +rustup target add wasm32-wasip2 +bash community/code-snippets/build.sh +# Output: community/code-snippets/target/code-snippets.amplugin +mkdir -p target/plugins +cp community/code-snippets/target/code-snippets.amplugin target/plugins/ +``` + +Build from the repository root; no AniMathIO checkout is needed. The component and +notices are packaged in the bundle. Set `ANIMATHIO_PLUGIN_DIR` to the absolute +bundle directory when starting AniMathIO. This replaces bundled discovery, so copy +any bundled plugins used by the project there too. Add **Code Snippets** from the +Library, paste code in the inspector and choose language/theme. + +For reveal, choose `mode=reveal`, set `progress=0` at the start and `progress=1` +at the end with the inspector's keyframe diamonds. Choose character or line reveal. +For morph, paste the second snippet into `code_to`, choose `mode=morph` and keyframe +`progress` from 0 to 1. Ordinary host linear/eased numeric keyframes control timing; +the plugin never reads a clock. Reverse keyframes work too. Presets that target other +parameter names (for example the Text plugin's `reveal`) do not automatically target +this plugin's `progress`. + +## Parameters + +| Parameter | Default | Meaning | +| --- | --- | --- | +| `code` | Rust hello snippet | Multiline source; strings hold between host keyframes | +| `code_to` | empty | Multiline target for morph; empty means fade all source tokens out | +| `language` | `rust` | `rust`, `python`, `javascript`, `typescript`, `c`, `cpp` / `c++`, `json`, `latex` / `tex`, `bash` | +| `theme` | `ocean` | Dark `ocean` (base16 Ocean), dark `night` (base16 Eighties), light `paper` (InspiredGitHub) | +| `font_size` | 4 | Percent of the canvas short edge, 0.5–12; JetBrains Mono Regular | +| `line_numbers` | true | Show a fixed-width gutter; morph fades extra line numbers | +| `highlight_lines` | empty | One-based comma-separated lines/ranges, e.g. `2,4-6`; unselected lines use 25% opacity. Empty selects all. Applied independently to each morph endpoint | +| `background` | true | Draw the theme-colored panel | +| `padding` | 4 | Panel padding, percent of short edge, 0–12 | +| `corner_radius` | 2 | Panel corner radius, percent of short edge, 0–12 | +| `mode` | `reveal` | `reveal` or `morph` | +| `reveal_by` | `character` | `character` (Unicode scalar values, including whitespace) or `line` | +| `progress` | 1 | Keyframable number, clamped to 0–1 | + +Every parameter uses the ordinary typed schema. Numeric parameters interpolate; +booleans, strings and choices hold. Nonfinite numeric values and malformed highlight +selections return diagnostics. The full code determines highlighting even during +reveal, so partially revealed strings retain their final syntax color. Line numbers +remain visible during reveal. The panel fits the larger of the two morph snippets +and keeps its size/position throughout; long content shrinks to fit 92% of the canvas. +The requested font size is therefore a maximum. Layout remains stable throughout +reveal. Tabs expand to four-column stops and CRLF normalizes to LF. + +## Screenshots + +Rendered headlessly by the released CLI, with no GUI or audio. Each row shows +`progress=0`, `0.25`, `0.5`, `0.75`, `1`. + +| Reveal 0% | Reveal 25% | Reveal 50% | Reveal 75% | Reveal 100% | +| --- | --- | --- | --- | --- | +| ![Reveal start](screenshots/reveal-000.png) | ![Reveal quarter](screenshots/reveal-025.png) | ![Reveal midpoint](screenshots/reveal-050.png) | ![Reveal three quarters](screenshots/reveal-075.png) | ![Reveal complete](screenshots/reveal-100.png) | + +| Morph 0% | Morph 25% | Morph 50% | Morph 75% | Morph 100% | +| --- | --- | --- | --- | --- | +| ![Recursive source](screenshots/morph-000.png) | ![Tokens departing](screenshots/morph-025.png) | ![Tokens moving](screenshots/morph-050.png) | ![Tokens arriving](screenshots/morph-075.png) | ![Iterative target](screenshots/morph-100.png) | + +## Implementation and limits + +Syntect uses its pure Rust `fancy-regex` backend, a build-time dump of nine small +original lexical grammars, and its default theme dump. No Oniguruma, C runtime, +JavaScript engine, filesystem, network, random or clock access is used. No host +imports are invoked; capabilities are empty. The vendored WIT is unchanged from the +repository template. The host only exposes DejaVu Sans through `shape-text`, so the +plugin embeds unmodified [JetBrains Mono 2.304](https://github.com/JetBrains/JetBrainsMono/tree/v2.304) +and extracts outlines with `ttf-parser`. Every glyph's contours share one fill, +preserving counters in `O`, `0`, `B`, etc. The font's OFL license is shipped in the +source and bundle. + +V1 intentionally provides lexical highlighting, not a semantic language server or +complete language grammar. It recognizes keywords, strings, comments, numbers, +function-like identifiers and punctuation. Python triple strings and C-style block +comments span lines. TypeScript has its own keyword set. Nested Rust block comments, +JS template interpolation, shell heredocs and embedded TeX languages are not parsed. +Layout uses one cell per Unicode scalar (no ligatures, grapheme shaping, bidi or +wide-character cells). Missing font glyphs use a replacement glyph. + +Each snippet is capped at 4096 UTF-8 bytes, 1024 Unicode scalar values after tab +expansion, 80 lines and 256 highlighted tokens. The `highlight_lines` string is at +most 512 bytes, with ranges in 1–80. Token LCS uses at most 257² `u16` cells; +subsequent moved-token matching is one-to-one and deterministic. Duplicate +matches resolve in source order. All output is recomputed from parameters; calls +and seek order do not affect it. These bounds protect memory/CPU; the host retains +its independent fuel, memory and epoch backstops. Pathological code can still be +rejected by the sandbox. Full editor integration, semantic parsing, arbitrary fonts, +custom themes, selection rectangles and multi-step transitions are deferred. + +## Verification + +Verified bundle size: **795,124 bytes (777 KiB)**; the uncompressed component is +2,396,212 bytes. The bundle includes the component, manifest and license notices. + +```sh +# Apply the shared machine resource limits to every cargo invocation. +CARGO_BUILD_JOBS=3 CARGO_PROFILE_DEV_DEBUG=0 CARGO_INCREMENTAL=0 nice -n 19 ionice -c3 cargo fmt --manifest-path community/code-snippets/Cargo.toml --check +CARGO_BUILD_JOBS=3 CARGO_PROFILE_DEV_DEBUG=0 CARGO_INCREMENTAL=0 nice -n 19 ionice -c3 cargo clippy --manifest-path community/code-snippets/Cargo.toml --workspace --all-targets --locked -- -D warnings +CARGO_BUILD_JOBS=3 CARGO_PROFILE_DEV_DEBUG=0 CARGO_INCREMENTAL=0 nice -n 19 ionice -c3 cargo test --manifest-path community/code-snippets/Cargo.toml --workspace --locked +python3 community/code-snippets/smoke.py /path/to/animathio-cli target/plugins --screenshots +``` + +The smoke script creates `.amio` fixtures under `target/smoke`, renders both modes +at 0/25/50/75/100%, checks exact endpoints with equal layout extents, repeatability, +all language choices, both dark themes, the light theme, line selection, no-panel +rendering and a host-sampled typed `progress` keyframe at 0.5 seconds. It checks +panel pixels to reject error placeholders and exercises a 256-token-per-side LCS +and a 1,024-character comment under the default sandbox limits. `--screenshots` refreshes README PNGs; +look at them before committing. CI also builds for `wasm32-wasip2` and runs these +checks against the released 2.1.0 CLI. No desktop window or audio device is opened. diff --git a/community/code-snippets/assets/JetBrainsMono-Regular.ttf b/community/code-snippets/assets/JetBrainsMono-Regular.ttf new file mode 100644 index 0000000..dff66cc Binary files /dev/null and b/community/code-snippets/assets/JetBrainsMono-Regular.ttf differ diff --git a/community/code-snippets/assets/OFL.txt b/community/code-snippets/assets/OFL.txt new file mode 100644 index 0000000..8bee414 --- /dev/null +++ b/community/code-snippets/assets/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/community/code-snippets/assets/shiki-magic-move-LICENSE b/community/code-snippets/assets/shiki-magic-move-LICENSE new file mode 100644 index 0000000..7d71216 --- /dev/null +++ b/community/code-snippets/assets/shiki-magic-move-LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Anthony Fu + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/community/code-snippets/assets/syntect-LICENSE b/community/code-snippets/assets/syntect-LICENSE new file mode 100644 index 0000000..7ddbcce --- /dev/null +++ b/community/code-snippets/assets/syntect-LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Tristan Hume, Keith Hall, Google Inc and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/community/code-snippets/build.rs b/community/code-snippets/build.rs new file mode 100644 index 0000000..8ae8a8a --- /dev/null +++ b/community/code-snippets/build.rs @@ -0,0 +1,14 @@ +use std::{env, path::PathBuf}; +use syntect::{dumps::dump_to_uncompressed_file, parsing::SyntaxSetBuilder}; +fn main() { + println!("cargo:rerun-if-changed=syntaxes"); + let mut builder = SyntaxSetBuilder::new(); + builder + .add_from_folder("syntaxes", true) + .expect("plugin lexical grammars"); + dump_to_uncompressed_file( + &builder.build(), + PathBuf::from(env::var_os("OUT_DIR").unwrap()).join("syntaxes.bin"), + ) + .unwrap(); +} diff --git a/community/code-snippets/build.sh b/community/code-snippets/build.sh new file mode 100755 index 0000000..f0039b8 --- /dev/null +++ b/community/code-snippets/build.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")" +export CARGO_BUILD_JOBS=3 CARGO_PROFILE_DEV_DEBUG=0 CARGO_INCREMENTAL=0 +runner=(cargo) +if [[ "$OSTYPE" == linux* ]]; then runner=(nice -n 19 ionice -c3 cargo); fi +"${runner[@]}" build --target wasm32-wasip2 --release --locked +python3 - <<'PACKAGE' +import pathlib, tomllib, zipfile +root = pathlib.Path('.') +name = tomllib.loads((root / 'Cargo.toml').read_text())['package']['name'] +out = root / 'target' / (name + '.amplugin') +with zipfile.ZipFile(out, 'w', zipfile.ZIP_DEFLATED) as z: + z.write('plugin.toml', 'plugin.toml') + z.write('NOTICE', 'NOTICE') + z.write('../../LICENSE', 'LICENSE') + for notice in ['OFL.txt', 'shiki-magic-move-LICENSE', 'syntect-LICENSE']: + z.write('assets/' + notice, 'licenses/' + notice) + z.write(f"target/wasm32-wasip2/release/{name.replace('-', '_')}.wasm", 'plugin.wasm') +print(out) +PACKAGE diff --git a/community/code-snippets/plugin.toml b/community/code-snippets/plugin.toml new file mode 100644 index 0000000..04c8d25 --- /dev/null +++ b/community/code-snippets/plugin.toml @@ -0,0 +1,7 @@ +api_version = "1.1.0" +id = "org.animathio.community.code-snippets" +name = "Code Snippets" +version = "0.1.0" +description = "Syntax-highlighted code with type-on reveal and token morph animations" +kinds = ["clip-source"] +capabilities = [] diff --git a/community/code-snippets/screenshots/morph-000.png b/community/code-snippets/screenshots/morph-000.png new file mode 100644 index 0000000..61dfdb3 Binary files /dev/null and b/community/code-snippets/screenshots/morph-000.png differ diff --git a/community/code-snippets/screenshots/morph-025.png b/community/code-snippets/screenshots/morph-025.png new file mode 100644 index 0000000..0e57577 Binary files /dev/null and b/community/code-snippets/screenshots/morph-025.png differ diff --git a/community/code-snippets/screenshots/morph-050.png b/community/code-snippets/screenshots/morph-050.png new file mode 100644 index 0000000..b4d7d16 Binary files /dev/null and b/community/code-snippets/screenshots/morph-050.png differ diff --git a/community/code-snippets/screenshots/morph-075.png b/community/code-snippets/screenshots/morph-075.png new file mode 100644 index 0000000..6815e5e Binary files /dev/null and b/community/code-snippets/screenshots/morph-075.png differ diff --git a/community/code-snippets/screenshots/morph-100.png b/community/code-snippets/screenshots/morph-100.png new file mode 100644 index 0000000..cfb2fe7 Binary files /dev/null and b/community/code-snippets/screenshots/morph-100.png differ diff --git a/community/code-snippets/screenshots/reveal-000.png b/community/code-snippets/screenshots/reveal-000.png new file mode 100644 index 0000000..58ddc26 Binary files /dev/null and b/community/code-snippets/screenshots/reveal-000.png differ diff --git a/community/code-snippets/screenshots/reveal-025.png b/community/code-snippets/screenshots/reveal-025.png new file mode 100644 index 0000000..c4f795b Binary files /dev/null and b/community/code-snippets/screenshots/reveal-025.png differ diff --git a/community/code-snippets/screenshots/reveal-050.png b/community/code-snippets/screenshots/reveal-050.png new file mode 100644 index 0000000..ec34531 Binary files /dev/null and b/community/code-snippets/screenshots/reveal-050.png differ diff --git a/community/code-snippets/screenshots/reveal-075.png b/community/code-snippets/screenshots/reveal-075.png new file mode 100644 index 0000000..b372718 Binary files /dev/null and b/community/code-snippets/screenshots/reveal-075.png differ diff --git a/community/code-snippets/screenshots/reveal-100.png b/community/code-snippets/screenshots/reveal-100.png new file mode 100644 index 0000000..61dfdb3 Binary files /dev/null and b/community/code-snippets/screenshots/reveal-100.png differ diff --git a/community/code-snippets/smoke.py b/community/code-snippets/smoke.py new file mode 100644 index 0000000..c5ddcf1 --- /dev/null +++ b/community/code-snippets/smoke.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python3 +"""Released-host integration checks. All files stay under this plugin's target/. +Usage: python3 smoke.py /path/to/animathio-cli /path/to/plugin-dir [--screenshots] +""" +import io +import json +import os +from pathlib import Path +import subprocess +import sys +import zipfile +from PIL import Image + +ROOT = Path(__file__).resolve().parent +WORK = ROOT / 'target' / 'smoke' +WORK.mkdir(parents=True, exist_ok=True) +CLI = str(Path(sys.argv[1]).resolve()) +ENV = dict(os.environ, ANIMATHIO_PLUGIN_DIR=str(Path(sys.argv[2]).resolve()), + ANIMATHIO_AUDIO='none', PIPEWIRE_REMOTE='animathio-silent-no-such-remote', + PULSE_SERVER='unix:/nonexistent/animathio-silent', SDL_AUDIODRIVER='dummy') + +def run(*args): + result = subprocess.run([CLI, *map(str, args)], env=ENV, text=True, capture_output=True) + if result.returncode or any(s in result.stderr.lower() for s in ['failed', 'trap', 'placeholder', 'not loaded']): + raise RuntimeError(result.stdout + result.stderr) + return result.stdout + +sample = WORK / 'sample.amio' +sample.unlink(missing_ok=True) +run('new-sample', '-o', sample) +with zipfile.ZipFile(sample) as z: + project = json.loads(z.read('project.json')) +project['assets'] = {} +project['width'] = 1280 +project['height'] = 720 +project['background'] = [17, 20, 28, 255] +project['tracks'] = project['tracks'][:1] +clip = project['tracks'][0]['clips']['1'] +clip['animations'] = [] +clip['effects'] = [] +CODE = '''fn fibonacci(n: u32) -> u64 { + match n { + 0 => 0, + 1 => 1, + _ => fibonacci(n - 1) + fibonacci(n - 2), + } +}''' +TARGET = '''fn fibonacci(n: u32) -> u64 { + let (mut a, mut b) = (0, 1); + for _ in 0..n { + (a, b) = (b, a + b); + } + a +}''' + +def render(name, frame=0, **params): + clip['kind'] = {'Plugin': {'plugin_id': 'org.animathio.community.code-snippets', + 'params': dict(dict(code=CODE, code_to=TARGET, font_size=4.0), **params)}} + file = WORK / (name + '.amio') + with zipfile.ZipFile(file, 'w', zipfile.ZIP_DEFLATED) as z: + z.writestr('project.json', json.dumps(project)) + png = WORK / (name + '.png') + png.unlink(missing_ok=True) + run('render', file, '--frame', frame, '-o', png) + image = Image.open(io.BytesIO(png.read_bytes())).convert('RGB') + # A placeholder or blank canvas must not pass as a successful render. + colors = dict((rgb, count) for count, rgb in image.getcolors(image.width * image.height)) + if params.get('theme', 'ocean') == 'ocean' and params.get('background', True): + assert colors.get((43, 48, 59), 0) > 1000, name + else: + assert any(max(rgb) - min(rgb) > 30 for rgb in colors), name + print('PASS', name) + return image + +frames = {} +for mode in ['reveal', 'morph']: + for p in [0, 0.25, 0.5, 0.75, 1]: + name = f'{mode}-{int(p * 100):03}' + frames[name] = render(name, mode=mode, progress=p) + assert frames[f'{mode}-000'].tobytes() != frames[f'{mode}-050'].tobytes() + assert frames[f'{mode}-050'].tobytes() != frames[f'{mode}-100'].tobytes() +assert frames['reveal-100'].tobytes() == frames['morph-000'].tobytes() +assert frames['morph-050'].tobytes() == render('repeat', mode='morph', progress=0.5).tobytes() +samples = { + 'python': 'def greet(name):\n # a comment\n return f"Hello {name}"', + 'javascript': 'const greet = (name) => "Hello " + name;', + 'typescript': 'interface User { name: string; }\nconst user: User = { name: "Ada" };', + 'c': 'int main(void) { /* comment */ return 42; }', + 'cpp': 'template T square(T x) { return x * x; }', + 'c++': 'const auto answer = 42;', + 'json': '{"name": "Ada", "active": true, "count": 42}', + 'latex': r"\frac{a}{b} + \sqrt{2} % comment", + 'tex': r"\begin{equation} e^{i\pi} + 1 = 0 \end{equation}", + 'bash': '#!/bin/bash\nfor name in Ada Bob; do\n echo "$name"\ndone', +} +for language, code in samples.items(): + render('language-' + language.replace('+', 'plus'), language=language, code=code, progress=1) +render('paper-lines', theme='paper', highlight_lines='2,4-6', reveal_by='line', progress=0.5) +render('night-transparent', theme='night', background=False, line_numbers=False) +# Verify the target endpoint against a static rendering with the same box dimensions. +original = CODE +CODE, TARGET = TARGET, CODE +assert frames['morph-100'].tobytes() == render('target-static', mode='morph', progress=0).tobytes() +CODE, TARGET = original, CODE +# Host sampling of a typed progress animation must reproduce the static midpoint. +clip['animations'] = [{'target': {'Param': 'progress'}, 'keys': { + '0': {'value': {'Number': 0.0}, 'interpolation': 'Linear'}, + '705600000': {'value': {'Number': 1.0}, 'interpolation': 'Hold'}}}] +assert frames['morph-050'].tobytes() == render('keyframed', frame=15, mode='morph', progress=0).tobytes() +clip['animations'] = [] +render('bounded-lcs', code=('x;' * 16 + '\n') * 8, code_to=('y;' * 16 + '\n') * 8, mode='morph', progress=0.5) +render('long-comment', code=('// ' + 'a' * 60 + '\n') * 16, progress=1) +if '--screenshots' in sys.argv: + out = ROOT / 'screenshots' + out.mkdir(exist_ok=True) + for mode in ['reveal','morph']: + for p in [0,25,50,75,100]: + name = f'{mode}-{p:03}' + frames[name].save(out / f'{name}.png', optimize=True) +print('All released-host checks passed') diff --git a/community/code-snippets/src/animation.rs b/community/code-snippets/src/animation.rs new file mode 100644 index 0000000..2207101 --- /dev/null +++ b/community/code-snippets/src/animation.rs @@ -0,0 +1,85 @@ +use super::Color; +#[derive(Debug, Clone)] +pub struct Token { + pub text: String, + pub column: f32, + pub line: f32, + pub offset: usize, + pub color: Color, +} + +/// Bounded token LCS, with stable tie-breaking for repeated punctuation. +/// At most 257² u16 cells (inputs are capped at 256 tokens before this call). +pub fn matches(from: &[Token], to: &[Token]) -> Vec> { + // Intern text once so the quadratic loop compares integers, not UTF-8 strings. + let mut vocabulary = std::collections::BTreeMap::new(); + let mut next_id = 0u16; + let mut ids = |tokens: &[Token]| { + tokens + .iter() + .map(|t| { + *vocabulary.entry(t.text.clone()).or_insert_with(|| { + let id = next_id; + next_id += 1; + id + }) + }) + .collect::>() + }; + let from_ids = ids(from); + let to_ids = ids(to); + let width = to.len() + 1; + let mut lengths = vec![0u16; (from.len() + 1) * width]; + for i in (0..from.len()).rev() { + for j in (0..to.len()).rev() { + lengths[i * width + j] = if from_ids[i] == to_ids[j] { + lengths[(i + 1) * width + j + 1] + 1 + } else { + lengths[(i + 1) * width + j].max(lengths[i * width + j + 1]) + }; + } + } + let mut result = vec![None; from.len()]; + let (mut i, mut j) = (0, 0); + while i < from.len() && j < to.len() { + if from_ids[i] == to_ids[j] { + result[i] = Some(j); + i += 1; + j += 1; + } else if lengths[(i + 1) * width + j] >= lengths[i * width + j + 1] { + i += 1; + } else { + j += 1; + } + } + // Preserve all moved tokens outside the LCS, one-to-one, in source order. + let mut used = vec![false; to.len()]; + for j in result.iter().flatten() { + used[*j] = true; + } + for (i, token) in from.iter().enumerate() { + if result[i].is_none() { + if let Some(j) = to + .iter() + .enumerate() + .position(|(j, t)| !used[j] && t.text == token.text) + { + result[i] = Some(j); + used[j] = true; + } + } + } + result +} + +/// Overlap exits and entries while retained tokens ease between positions. +/// Like Magic Move's duration-based delays, these are overlapping windows, +/// not three sequential slices. Progress is normalized to the whole transition. +pub fn phases(progress: f32) -> (f32, f32, f32) { + let travel = ((progress - 0.15) / 0.7).clamp(0.0, 1.0); + ( + travel * travel * (3.0 - 2.0 * travel), + (1.0 - progress / 0.6).clamp(0.0, 1.0), + ((progress - 0.4) / 0.6).clamp(0.0, 1.0), + ) +} diff --git a/community/code-snippets/src/drawing.rs b/community/code-snippets/src/drawing.rs new file mode 100644 index 0000000..498716c --- /dev/null +++ b/community/code-snippets/src/drawing.rs @@ -0,0 +1,186 @@ +use super::{Color, DrawCommand, PathVerb, Point, Size}; +use ttf_parser::{Face, OutlineBuilder}; + +pub fn color(c: syntect::highlighting::Color) -> Color { + Color { + r: c.r, + g: c.g, + b: c.b, + a: c.a, + } +} +pub fn blend(a: Color, b: Color, t: f32) -> Color { + let channel = |a: u8, b: u8| (a as f32 + (b as f32 - a as f32) * t).round() as u8; + Color { + r: channel(a.r, b.r), + g: channel(a.g, b.g), + b: channel(a.b, b.b), + a: channel(a.a, b.a), + } +} +pub struct Painter<'a> { + pub elements: Vec, + font: Face<'a>, + glyphs: std::collections::BTreeMap>, + scale: f32, + advance: f32, + line_height: f32, + x: f32, + y: f32, + panel: (f32, f32, f32, f32), +} +impl Painter<'static> { + pub fn new( + size: Size, + font_size: f32, + padding: f32, + columns: usize, + lines: usize, + gutter: usize, + ) -> Self { + let font = Face::parse(include_bytes!("../assets/JetBrainsMono-Regular.ttf"), 0) + .expect("embedded font"); + let units = font.units_per_em() as f32; + let advance = font + .glyph_hor_advance(font.glyph_index('M').unwrap()) + .unwrap() as f32 + / units; + let width = font_size * advance * columns.max(1) as f32 + padding * 2.0; + let height = font_size * 1.5 * lines as f32 + padding * 2.0; + // Fit both states as one stable box: no jump as progress changes. + let fit = (size.width as f32 * 0.92 / width) + .min(size.height as f32 * 0.92 / height) + .min(1.0); + let width = width * fit; + let height = height * fit; + let left = (size.width as f32 - width) * 0.5; + let top = (size.height as f32 - height) * 0.5; + let scale = font_size * fit / units; + let advance = advance * font_size * fit; + Self { + elements: vec![], + font, + glyphs: std::collections::BTreeMap::new(), + scale, + advance, + line_height: font_size * fit * 1.5, + x: left + padding * fit + gutter as f32 * advance, + y: top + padding * fit + font_size * fit * 1.1, + panel: (left, top, width, height), + } + } + pub fn panel(&mut self, radius: f32, color: Color) { + let (x, y, w, h) = self.panel; + let r = radius.min(w / 2.0).min(h / 2.0); + let k = 0.552_284_8; + let p = |x, y| Point { x, y }; + let path = vec![ + PathVerb::MoveTo(p(x + r, y)), + PathVerb::LineTo(p(x + w - r, y)), + PathVerb::CubicTo(( + p(x + w - r + k * r, y), + p(x + w, y + r - k * r), + p(x + w, y + r), + )), + PathVerb::LineTo(p(x + w, y + h - r)), + PathVerb::CubicTo(( + p(x + w, y + h - r + k * r), + p(x + w - r + k * r, y + h), + p(x + w - r, y + h), + )), + PathVerb::LineTo(p(x + r, y + h)), + PathVerb::CubicTo(( + p(x + r - k * r, y + h), + p(x, y + h - r + k * r), + p(x, y + h - r), + )), + PathVerb::LineTo(p(x, y + r)), + PathVerb::CubicTo((p(x, y + r - k * r), p(x + r - k * r, y), p(x + r, y))), + PathVerb::Close, + ]; + self.elements.push(DrawCommand::FillPath((path, color))); + } + pub fn text(&mut self, text: &str, column: f32, line: f32, mut color: Color, opacity: f32) { + color.a = (color.a as f32 * opacity.clamp(0.0, 1.0)).round() as u8; + if color.a == 0 { + return; + } + for (index, c) in text.chars().enumerate() { + let font = &self.font; + let scale = self.scale; + let path = self.glyphs.entry(c).or_insert_with(|| { + let glyph = font + .glyph_index(c) + .or_else(|| font.glyph_index('\u{fffd}')) + .or_else(|| font.glyph_index('?')) + .expect("embedded fallback glyph"); + let mut outline = Outline { + path: vec![], + scale, + x: 0.0, + y: 0.0, + }; + font.outline_glyph(glyph, &mut outline); + outline.path + }); + let x = self.x + (column + index as f32) * self.advance; + let y = self.y + line * self.line_height; + let point = |p: &Point| Point { + x: p.x + x, + y: p.y + y, + }; + let translated = path + .iter() + .map(|v| match v { + PathVerb::MoveTo(p) => PathVerb::MoveTo(point(p)), + PathVerb::LineTo(p) => PathVerb::LineTo(point(p)), + PathVerb::QuadTo((a, b)) => PathVerb::QuadTo((point(a), point(b))), + PathVerb::CubicTo((a, b, c)) => { + PathVerb::CubicTo((point(a), point(b), point(c))) + } + PathVerb::Close => PathVerb::Close, + }) + .collect::>(); + if !translated.is_empty() { + self.elements + .push(DrawCommand::FillPath((translated, color))); + } + } + } +} +struct Outline { + path: Vec, + scale: f32, + x: f32, + y: f32, +} +impl Outline { + fn point(&self, x: f32, y: f32) -> Point { + Point { + x: self.x + x * self.scale, + y: self.y - y * self.scale, + } + } +} +impl OutlineBuilder for Outline { + fn move_to(&mut self, x: f32, y: f32) { + self.path.push(PathVerb::MoveTo(self.point(x, y))); + } + fn line_to(&mut self, x: f32, y: f32) { + self.path.push(PathVerb::LineTo(self.point(x, y))); + } + fn quad_to(&mut self, x: f32, y: f32, x1: f32, y1: f32) { + self.path + .push(PathVerb::QuadTo((self.point(x, y), self.point(x1, y1)))); + } + fn curve_to(&mut self, x: f32, y: f32, x1: f32, y1: f32, x2: f32, y2: f32) { + self.path.push(PathVerb::CubicTo(( + self.point(x, y), + self.point(x1, y1), + self.point(x2, y2), + ))); + } + fn close(&mut self) { + self.path.push(PathVerb::Close); + } +} diff --git a/community/code-snippets/src/lib.rs b/community/code-snippets/src/lib.rs new file mode 100644 index 0000000..30b3710 --- /dev/null +++ b/community/code-snippets/src/lib.rs @@ -0,0 +1,501 @@ +//! Deterministic code animation. Behavioral inspiration: Shiki Magic Move (MIT). +//! No upstream animation implementation is copied; see NOTICE. +wit_bindgen::generate!({ path: "wit", world: "source-plugin" }); +use animathio::plugin::types::*; +use syntect::{ + easy::HighlightLines, highlighting::ThemeSet, parsing::SyntaxSet, util::LinesWithEndings, +}; + +mod animation; +mod drawing; +use animation::{matches, Token}; +use drawing::{color, Painter}; + +const CODE: &str = "fn main() {\n println!(\"Hello, AniMathIO!\");\n}"; +const MAX_BYTES: usize = 4096; +const MAX_CHARS: usize = 1024; +const MAX_TOKENS: usize = 256; +const MAX_LINES: usize = 80; +struct CodeSnippets; + +fn syntax_set() -> SyntaxSet { + syntect::dumps::from_uncompressed_data(include_bytes!(concat!( + env!("OUT_DIR"), + "/syntaxes.bin" + ))) + .expect("build-time syntax dump") +} +fn error(message: &str) -> Diagnostic { + Diagnostic { + code: "invalid-input".into(), + message: message.into(), + metadata: vec![], + } +} +fn string<'a>(params: &'a [ParamEntry], id: &str, default: &'a str) -> &'a str { + params + .iter() + .find(|p| p.id == id) + .and_then(|p| match &p.value { + ParamValue::String(s) | ParamValue::EnumChoice(s) => Some(s.as_str()), + _ => None, + }) + .unwrap_or(default) +} +fn number( + params: &[ParamEntry], + id: &str, + default: f64, + min: f64, + max: f64, +) -> Result { + let n = params + .iter() + .find(|p| p.id == id) + .and_then(|p| match p.value { + ParamValue::Number(n) => Some(n), + _ => None, + }) + .unwrap_or(default); + if !n.is_finite() { + return Err(error("Numeric parameters must be finite")); + } + Ok(n.clamp(min, max) as f32) +} +fn boolean(params: &[ParamEntry], id: &str, default: bool) -> bool { + params + .iter() + .find(|p| p.id == id) + .and_then(|p| match p.value { + ParamValue::Bool(b) => Some(b), + _ => None, + }) + .unwrap_or(default) +} +fn text_param(id: &str, label: &str, default: &str) -> ParamSpec { + ParamSpec { + id: id.into(), + label: label.into(), + kind: ParamKind::String(StringParam { + default: default.into(), + }), + } +} +fn enum_param(id: &str, label: &str, options: &[&str], default: &str) -> ParamSpec { + ParamSpec { + id: id.into(), + label: label.into(), + kind: ParamKind::EnumChoice(EnumParam { + options: options.iter().map(|s| (*s).into()).collect(), + default: default.into(), + }), + } +} +fn num_param(id: &str, label: &str, min: f64, max: f64, default: f64) -> ParamSpec { + ParamSpec { + id: id.into(), + label: label.into(), + kind: ParamKind::Number(NumberRange { + min, + max, + default, + step: 0.01, + }), + } +} +fn bool_param(id: &str, label: &str, default: bool) -> ParamSpec { + ParamSpec { + id: id.into(), + label: label.into(), + kind: ParamKind::Bool(BoolParam { default }), + } +} + +fn validate(code: &str) -> Result { + if code.len() > MAX_BYTES + || code.chars().count() > MAX_CHARS + || code.split('\n').count() > MAX_LINES + { + return Err(error( + "Code exceeds 4096 bytes, 1024 characters or 80 lines", + )); + } + // Tabs use four-column tab stops. CRLF has the same layout as LF. + let mut result = String::new(); + let mut column = 0; + for c in code.replace("\r\n", "\n").chars() { + match c { + '\n' => { + result.push(c); + column = 0; + } + '\t' => { + let count = 4 - column % 4; + result.extend(std::iter::repeat_n(' ', count)); + column += count; + } + c if c.is_control() => return Err(error("Unsupported control character in code")), + c => { + result.push(c); + column += 1; + } + } + } + if result.chars().count() > MAX_CHARS { + return Err(error("Expanded tabs exceed 1024 characters")); + } + Ok(result) +} + +/// Split highlighted spans into identifier/number runs and individual punctuation. +/// Whitespace only affects placement, never steals a diff match. +fn tokenize( + code: &str, + language: &str, + ss: &SyntaxSet, + theme: &syntect::highlighting::Theme, +) -> Result, Diagnostic> { + let ext = match language { + "rust" => "rs", + "python" => "py", + "javascript" => "js", + "typescript" => "ts", + "c" => "c", + "cpp" | "c++" => "cpp", + "json" => "json", + "latex" | "tex" => "tex", + "bash" => "sh", + _ => return Err(error("Unsupported language")), + }; + let syntax = ss + .find_syntax_by_extension(ext) + .ok_or_else(|| error("Language syntax is unavailable"))?; + let mut highlighter = HighlightLines::new(syntax, theme); + let mut tokens = Vec::new(); + let mut offset = 0; + for (line, text) in LinesWithEndings::from(code).enumerate() { + let spans = highlighter + .highlight_line(text, ss) + .map_err(|_| error("Syntax highlighting failed"))?; + let mut column = 0; + for (style, span) in spans { + let mut word = String::new(); + let mut start = column; + let mut start_offset = offset; + let flush = |word: &mut String, tokens: &mut Vec, start, start_offset| { + if !word.is_empty() { + tokens.push(Token { + text: std::mem::take(word), + column: start as f32, + line: line as f32, + offset: start_offset, + color: color(style.foreground), + }); + } + }; + for c in span.chars() { + if c.is_alphanumeric() || c == '_' { + if word.is_empty() { + start = column; + start_offset = offset; + } + word.push(c); + } else { + flush(&mut word, &mut tokens, start, start_offset); + if !c.is_whitespace() { + tokens.push(Token { + text: c.to_string(), + column: column as f32, + line: line as f32, + offset, + color: color(style.foreground), + }); + } + } + column += 1; + offset += 1; + } + flush(&mut word, &mut tokens, start, start_offset); + } + } + if tokens.len() > MAX_TOKENS { + return Err(error("Code exceeds 256 syntax tokens")); + } + Ok(tokens) +} + +fn highlighted(spec: &str, lines: usize) -> Result, Diagnostic> { + if spec.len() > 512 { + return Err(error("Highlight selection is too long")); + } + let mut selected = vec![spec.trim().is_empty(); lines]; + if spec.trim().is_empty() { + return Ok(selected); + } + for part in spec.split(',') { + let (a, b) = part + .trim() + .split_once('-') + .map_or((part.trim(), part.trim()), |(a, b)| (a.trim(), b.trim())); + let a: usize = a + .parse() + .map_err(|_| error("Use highlight lines like 2,4-6"))?; + let b: usize = b + .parse() + .map_err(|_| error("Use highlight lines like 2,4-6"))?; + if a == 0 || b < a || b > MAX_LINES { + return Err(error("Highlight lines must be within 1..80 and ordered")); + } + for line in a..=b { + if let Some(value) = selected.get_mut(line - 1) { + *value = true; + } + } + } + Ok(selected) +} +fn dimensions(code: &str) -> (usize, usize) { + ( + code.split('\n') + .map(|s| s.chars().count()) + .max() + .unwrap_or(0), + code.split('\n').count(), + ) +} + +impl Guest for CodeSnippets { + fn describe() -> Manifest { + Manifest { + name: "Code Snippets".into(), + version: "0.1.0".into(), + description: "Syntax-highlighted code with type-on reveal and token morph animations" + .into(), + kinds: vec!["clip-source".into()], + metadata: vec![ + ("param.font_size.unit".into(), "% of short edge".into()), + ("param.padding.unit".into(), "% of short edge".into()), + ("param.corner_radius.unit".into(), "% of short edge".into()), + ], + params: vec![ + text_param("code", "Code", CODE), + text_param("code_to", "Morph target", ""), + enum_param( + "language", + "Language", + &[ + "rust", + "python", + "javascript", + "typescript", + "c", + "cpp", + "c++", + "json", + "latex", + "tex", + "bash", + ], + "rust", + ), + enum_param("theme", "Theme", &["ocean", "night", "paper"], "ocean"), + num_param("font_size", "Font size (%)", 0.5, 12.0, 4.0), + bool_param("line_numbers", "Line numbers", true), + text_param("highlight_lines", "Highlight lines (2,4-6)", ""), + bool_param("background", "Background panel", true), + num_param("padding", "Panel padding (%)", 0.0, 12.0, 4.0), + num_param("corner_radius", "Panel radius (%)", 0.0, 12.0, 2.0), + enum_param("mode", "Animation", &["reveal", "morph"], "reveal"), + enum_param( + "reveal_by", + "Reveal by", + &["character", "line"], + "character", + ), + num_param("progress", "Progress", 0.0, 1.0, 1.0), + ], + } + } + fn render_clip( + params: Vec, + _time_ticks: i64, + size: Size, + ) -> Result { + render(¶ms, size) + } +} + +fn render(params: &[ParamEntry], size: Size) -> Result { + if size.width == 0 || size.height == 0 { + return Err(error("Canvas dimensions must be positive")); + } + let code = validate(string(params, "code", CODE))?; + let mode = string(params, "mode", "reveal"); + if !["reveal", "morph"].contains(&mode) { + return Err(error("Unsupported animation mode")); + } + let morph = mode == "morph"; + let code_to = if morph { + validate(string(params, "code_to", ""))? + } else { + code.clone() + }; + let progress = number(params, "progress", 1.0, 0.0, 1.0)?; + let ss = syntax_set(); + let themes = ThemeSet::load_defaults(); + let theme_name = match string(params, "theme", "ocean") { + "ocean" => "base16-ocean.dark", + "night" => "base16-eighties.dark", + "paper" => "InspiredGitHub", + _ => return Err(error("Unsupported theme")), + }; + let theme = &themes.themes[theme_name]; + let language = string(params, "language", "rust"); + let old = tokenize(&code, language, &ss, theme)?; + let new = if morph { + tokenize(&code_to, language, &ss, theme)? + } else { + Vec::new() + }; + let (cols, lines) = dimensions(&code); + let (cols_to, lines_to) = dimensions(&code_to); + let lines = lines.max(lines_to); + let selected = highlighted(string(params, "highlight_lines", ""), lines)?; + let short = size.width.min(size.height) as f32; + let font = number(params, "font_size", 4.0, 0.5, 12.0)? * short / 100.0; + let padding = number(params, "padding", 4.0, 0.0, 12.0)? * short / 100.0; + let radius = number(params, "corner_radius", 2.0, 0.0, 12.0)? * short / 100.0; + let numbers = boolean(params, "line_numbers", true); + let gutter = if numbers { + lines.to_string().len() + 2 + } else { + 0 + }; + let mut painter = Painter::new( + size, + font, + padding, + cols.max(cols_to) + gutter, + lines, + gutter, + ); + if boolean(params, "background", true) { + painter.panel( + radius, + color( + theme + .settings + .background + .unwrap_or(syntect::highlighting::Color::BLACK), + ), + ); + } + let foreground = color( + theme + .settings + .foreground + .unwrap_or(syntect::highlighting::Color::WHITE), + ); + if numbers { + for line in 0..lines { + let alpha = if morph { + if line < lines.min(dimensions(&code).1) && line < lines_to { + 0.45 + } else if line < dimensions(&code).1 { + (1.0 - progress) * 0.45 + } else { + progress * 0.45 + } + } else { + 0.45 + }; + painter.text( + &format!("{:>width$}", line + 1, width = gutter - 2), + -(gutter as f32), + line as f32, + foreground, + alpha, + ); + } + } + let dim = |line: f32| if selected[line as usize] { 1.0 } else { 0.25 }; + if morph && (progress == 0.0 || progress == 1.0) { + let endpoint = if progress == 0.0 { &old } else { &new }; + for token in endpoint { + painter.text( + &token.text, + token.column, + token.line, + token.color, + dim(token.line), + ); + } + } else if morph { + let (travel, leave, enter) = animation::phases(progress); + let pairs = matches(&old, &new); + let mut used = vec![false; new.len()]; + for (i, token) in old.iter().enumerate() { + if let Some(j) = pairs[i] { + used[j] = true; + let to = &new[j]; + painter.text( + &token.text, + token.column + (to.column - token.column) * travel, + token.line + (to.line - token.line) * travel, + drawing::blend(token.color, to.color, travel), + dim(token.line) + (dim(to.line) - dim(token.line)) * travel, + ); + } else { + painter.text( + &token.text, + token.column, + token.line, + token.color, + leave * dim(token.line), + ); + } + } + for (_, token) in new.iter().enumerate().filter(|(i, _)| !used[*i]) { + painter.text( + &token.text, + token.column, + token.line, + token.color, + enter * dim(token.line), + ); + } + } else { + let reveal_by = string(params, "reveal_by", "character"); + if !["character", "line"].contains(&reveal_by) { + return Err(error("Unsupported reveal unit")); + } + let visible = (code.chars().count() as f32 * progress).floor() as usize; + let visible_lines = (dimensions(&code).1 as f32 * progress).floor() as usize; + for token in &old { + let count = if reveal_by == "line" { + if (token.line as usize) < visible_lines { + token.text.chars().count() + } else { + 0 + } + } else { + visible.saturating_sub(token.offset) + }; + painter.text( + &token.text.chars().take(count).collect::(), + token.column, + token.line, + token.color, + dim(token.line), + ); + } + } + Ok(Scene { + coordinate_space: CoordinateSpace::Canvas, + elements: painter.elements, + }) +} +export!(CodeSnippets); + +#[cfg(test)] +mod tests; diff --git a/community/code-snippets/src/tests.rs b/community/code-snippets/src/tests.rs new file mode 100644 index 0000000..91066e6 --- /dev/null +++ b/community/code-snippets/src/tests.rs @@ -0,0 +1,248 @@ +use super::*; +fn params(values: &[(&str, ParamValue)]) -> Vec { + values + .iter() + .map(|(id, value)| ParamEntry { + id: (*id).into(), + value: value.clone(), + }) + .collect() +} +fn snapshot(p: &[ParamEntry]) -> String { + format!( + "{:?}", + render( + p, + Size { + width: 1280, + height: 720 + } + ) + .unwrap() + ) +} +#[test] +fn limits_and_unicode() { + assert!(validate(&"a".repeat(MAX_CHARS + 1)).is_err()); + assert!(validate(&"\n".repeat(MAX_LINES)).is_err()); + assert_eq!(validate("a\tβ\r\n").unwrap(), "a β\n"); + assert!(validate("\0").is_err()); + assert!(validate(&"\t".repeat(1000)).is_err()); + assert!(number( + ¶ms(&[("p", ParamValue::Number(f64::NAN))]), + "p", + 0., + 0., + 1. + ) + .is_err()); +} +#[test] +fn selection_is_strict_and_bounded() { + assert_eq!( + highlighted("2,4-6", 6).unwrap(), + vec![false, true, false, true, true, true] + ); + for bad in ["0", "5-2", "1-999999999", "x", "1,", "1-2-3"] { + assert!(highlighted(bad, 6).is_err()); + } +} +#[test] +fn all_languages_highlight_and_preserve_layout() { + let ss = syntax_set(); + let themes = ThemeSet::load_defaults(); + for language in [ + "rust", + "python", + "javascript", + "typescript", + "c", + "cpp", + "c++", + "json", + "latex", + "tex", + "bash", + ] { + let tokens = tokenize( + "fn hello() {\n hello(\"β\");\n}", + language, + &ss, + &themes.themes["base16-ocean.dark"], + ) + .unwrap(); + assert_eq!(tokens[0].text, "fn"); + assert!( + tokens.iter().any(|t| t.line == 1. && t.column == 4.), + "{language}" + ); + } + let tokens = tokenize( + "fn main() { let x = 42; }", + "rust", + &ss, + &themes.themes["base16-ocean.dark"], + ) + .unwrap(); + assert!(tokens + .iter() + .any(|t| format!("{:?}", t.color) != format!("{:?}", tokens[0].color))); +} +#[test] +fn diff_is_one_to_one_and_retains_moved_identifiers() { + let ss = syntax_set(); + let themes = ThemeSet::load_defaults(); + let token = |s| tokenize(s, "rust", &ss, &themes.themes["base16-ocean.dark"]).unwrap(); + let a = token("alpha();\nbeta();\nalpha();"); + let b = token("beta();\nalpha();\nalpha();"); + let pairs = matches(&a, &b); + let mut seen = std::collections::HashSet::new(); + for (i, j) in pairs + .iter() + .enumerate() + .filter_map(|(i, j)| j.map(|j| (i, j))) + { + assert_eq!(a[i].text, b[j].text); + assert!(seen.insert(j)); + } + for (i, t) in a + .iter() + .enumerate() + .filter(|(_, t)| t.text == "alpha" || t.text == "beta") + { + assert!(pairs[i].is_some(), "{}", t.text); + } +} +#[test] +fn reveal_and_morph_endpoints_are_exact_and_repeatable() { + let base = [ + ("code", ParamValue::String("fn old() {}".into())), + ("code_to", ParamValue::String("fn new() {}".into())), + ("line_numbers", ParamValue::Bool(false)), + ]; + let frame = |mode: &str, p: f64| { + let mut v = params(&base); + v.extend(params(&[ + ("mode", ParamValue::EnumChoice(mode.into())), + ("progress", ParamValue::Number(p)), + ])); + snapshot(&v) + }; + assert_eq!(frame("morph", 0.), frame("reveal", 1.)); + assert_ne!(frame("reveal", 0.), frame("reveal", 0.5)); + assert_ne!(frame("reveal", 0.5), frame("reveal", 1.)); + let end = params(&[ + ("code", ParamValue::String("fn new() {}".into())), + ("line_numbers", ParamValue::Bool(false)), + ]); + assert_eq!(frame("morph", 1.), snapshot(&end)); + let first = frame("morph", 0.5); + let _ = frame("morph", 0.2); + assert_eq!(first, frame("morph", 0.5)); +} +#[test] +fn line_reveal_keeps_glyph_counters_and_layout() { + let p = params(&[ + ("code", ParamValue::String("O0\nB8".into())), + ("reveal_by", ParamValue::EnumChoice("line".into())), + ("line_numbers", ParamValue::Bool(false)), + ("background", ParamValue::Bool(false)), + ("progress", ParamValue::Number(0.5)), + ]); + let scene = render( + &p, + Size { + width: 1280, + height: 720, + }, + ) + .unwrap(); + assert_eq!(scene.elements.len(), 2); + if let DrawCommand::FillPath((path, _)) = &scene.elements[0] { + assert!( + path.iter().filter(|v| matches!(v, PathVerb::Close)).count() >= 2, + "O counter must remain a subpath" + ); + } else { + panic!("expected glyph path"); + } +} + +#[test] +fn morph_phases_overlap_entering_and_leaving_tokens() { + assert_eq!(animation::phases(0.), (0., 1., 0.)); + let (travel, leave, enter) = animation::phases(0.5); + assert!((travel - 0.5).abs() < 1e-6); + assert!(leave > 0.16 && enter > 0.16); + let (travel, leave, enter) = animation::phases(1.); + assert_eq!((travel, leave, enter), (1., 0., 1.)); + let _ = snapshot(¶ms(&[( + "code", + ParamValue::String("你好 🙂 e\u{301}".into()), + )])); +} + +#[test] +fn rust_keywords_have_theme_colors() { + let ss = syntax_set(); + let themes = ThemeSet::load_defaults(); + let theme = &themes.themes["base16-ocean.dark"]; + let tokens = tokenize( + "fn fibonacci(n: u32) {\n let (mut a, mut b) = (0, 1);\n for _ in 0..n {}\n}", + "rust", + &ss, + theme, + ) + .unwrap(); + for keyword in ["fn", "let", "mut", "for", "in"] { + let token = tokens.iter().find(|t| t.text == keyword).unwrap(); + assert_ne!( + format!("{:?}", token.color), + format!("{:?}", color(theme.settings.foreground.unwrap())), + "{keyword}" + ); + } +} + +#[test] +fn typical_morph_keeps_tokens_visible_and_matches_short_tokens() { + let ss = syntax_set(); + let themes = ThemeSet::load_defaults(); + let token = |s| tokenize(s, "rust", &ss, &themes.themes["base16-ocean.dark"]).unwrap(); + let from = token("fn fibonacci(n: u32) { let a = 0; let b = 1; match n { 0 => a, _ => b } }"); + let to = token("fn fibonacci(n: u32) { for n in 0..1 { let b = n; let a = b; } }"); + let pairs = matches(&from, &to); + let mut used = vec![false; to.len()]; + for j in pairs.iter().flatten() { + used[*j] = true; + } + for text in ["fibonacci", "n", "{", "}", "0", "1", "a", "b"] { + let count = from + .iter() + .filter(|t| t.text == text) + .count() + .min(to.iter().filter(|t| t.text == text).count()); + assert!(count > 0); + assert_eq!( + pairs + .iter() + .enumerate() + .filter(|(i, j)| from[*i].text == text && j.is_some()) + .count(), + count, + "{text}" + ); + } + let (_, leave, enter) = animation::phases(0.5); + let alpha: f32 = pairs + .iter() + .map(|j| if j.is_some() { 1.0 } else { leave }) + .sum::() + + used.iter().filter(|v| !**v).count() as f32 * enter; + assert!(alpha > from.len().max(to.len()) as f32 * 0.4); + // Even a complete replacement must have both snippets visible at midpoint. + let old = token("return old_value"); + let new = token("let fresh = 42"); + assert!(matches(&old, &new).iter().all(Option::is_none)); + assert!(old.len() as f32 * leave + new.len() as f32 * enter > 0.9); +} diff --git a/community/code-snippets/syntaxes/bash.sublime-syntax b/community/code-snippets/syntaxes/bash.sublime-syntax new file mode 100644 index 0000000..420f699 --- /dev/null +++ b/community/code-snippets/syntaxes/bash.sublime-syntax @@ -0,0 +1,44 @@ +%YAML 1.2 +--- +name: bash +file_extensions: [sh] +scope: source.shell +contexts: + main: + - match: '\#.*$' + scope: comment.line + - match: '"' + push: + - meta_scope: string.quoted + - match: '\\.' + scope: constant.character.escape + - match: '"' + pop: true + - match: '''' + push: + - meta_scope: string.quoted + - match: '\\.' + scope: constant.character.escape + - match: '''' + pop: true + - match: '`' + push: + - meta_scope: string.quoted + - match: '\\.' + scope: constant.character.escape + - match: '`' + pop: true + - match: '\b(?:if|then|else|elif|fi|for|while|in|do|done|case|esac|function|select|until|time|coproc|break|continue|return|export|local|readonly|declare|typeset|let|eval|exec|exit|source|alias|unalias|set|unset|shift|trap|echo|printf|read|cd|pwd)\b' + scope: keyword.control + - match: '\b(?:0[xX][0-9a-fA-F_]+|[0-9][0-9_]*(?:\.[0-9_]+)?(?:[eE][+-]?[0-9]+)?)\b' + scope: constant.numeric + - match: '\$\{?[A-Za-z_][A-Za-z0-9_]*\}?' + scope: variable.other + - match: '\b[A-Za-z_][A-Za-z0-9_]*(?=\s*\()' + scope: entity.name.function + - match: '[+*/%=!<>&|^~?:-]+' + scope: keyword.operator + - match: '[{}\[\]();,.]' + scope: punctuation.separator + - match: '\b[A-Z][A-Za-z0-9_]*\b' + scope: entity.name.type diff --git a/community/code-snippets/syntaxes/c.sublime-syntax b/community/code-snippets/syntaxes/c.sublime-syntax new file mode 100644 index 0000000..cda25ec --- /dev/null +++ b/community/code-snippets/syntaxes/c.sublime-syntax @@ -0,0 +1,40 @@ +%YAML 1.2 +--- +name: c +file_extensions: [c] +scope: source.c +contexts: + main: + - match: '//.*$' + scope: comment.line + - match: '/\*' + push: + - meta_scope: comment.block + - match: '\*/' + pop: true + - match: '"' + push: + - meta_scope: string.quoted + - match: '\\.' + scope: constant.character.escape + - match: '"' + pop: true + - match: '''' + push: + - meta_scope: string.quoted + - match: '\\.' + scope: constant.character.escape + - match: '''' + pop: true + - match: '\b(?:auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|inline|int|long|register|restrict|return|short|signed|sizeof|static|struct|switch|typedef|union|unsigned|void|volatile|while|_Bool|_Complex|_Atomic)\b' + scope: keyword.control + - match: '\b(?:0[xX][0-9a-fA-F_]+|[0-9][0-9_]*(?:\.[0-9_]+)?(?:[eE][+-]?[0-9]+)?)\b' + scope: constant.numeric + - match: '\b[A-Za-z_][A-Za-z0-9_]*(?=\s*\()' + scope: entity.name.function + - match: '[+*/%=!<>&|^~?:-]+' + scope: keyword.operator + - match: '[{}\[\]();,.]' + scope: punctuation.separator + - match: '\b[A-Z][A-Za-z0-9_]*\b' + scope: entity.name.type diff --git a/community/code-snippets/syntaxes/cpp.sublime-syntax b/community/code-snippets/syntaxes/cpp.sublime-syntax new file mode 100644 index 0000000..5ae5c4f --- /dev/null +++ b/community/code-snippets/syntaxes/cpp.sublime-syntax @@ -0,0 +1,40 @@ +%YAML 1.2 +--- +name: cpp +file_extensions: [cpp] +scope: source.cpp +contexts: + main: + - match: '//.*$' + scope: comment.line + - match: '/\*' + push: + - meta_scope: comment.block + - match: '\*/' + pop: true + - match: '"' + push: + - meta_scope: string.quoted + - match: '\\.' + scope: constant.character.escape + - match: '"' + pop: true + - match: '''' + push: + - meta_scope: string.quoted + - match: '\\.' + scope: constant.character.escape + - match: '''' + pop: true + - match: '\b(?:alignas|alignof|asm|auto|bool|break|case|catch|char|class|concept|const|constexpr|consteval|constinit|continue|co_await|co_return|co_yield|decltype|default|delete|do|double|else|enum|explicit|export|extern|false|float|for|friend|goto|if|inline|int|long|mutable|namespace|new|noexcept|nullptr|operator|private|protected|public|register|reinterpret_cast|requires|return|short|signed|sizeof|static|static_assert|struct|switch|template|this|thread_local|throw|true|try|typedef|typename|union|unsigned|using|virtual|void|volatile|wchar_t|while)\b' + scope: keyword.control + - match: '\b(?:0[xX][0-9a-fA-F_]+|[0-9][0-9_]*(?:\.[0-9_]+)?(?:[eE][+-]?[0-9]+)?)\b' + scope: constant.numeric + - match: '\b[A-Za-z_][A-Za-z0-9_]*(?=\s*\()' + scope: entity.name.function + - match: '[+*/%=!<>&|^~?:-]+' + scope: keyword.operator + - match: '[{}\[\]();,.]' + scope: punctuation.separator + - match: '\b[A-Z][A-Za-z0-9_]*\b' + scope: entity.name.type diff --git a/community/code-snippets/syntaxes/javascript.sublime-syntax b/community/code-snippets/syntaxes/javascript.sublime-syntax new file mode 100644 index 0000000..a00a891 --- /dev/null +++ b/community/code-snippets/syntaxes/javascript.sublime-syntax @@ -0,0 +1,47 @@ +%YAML 1.2 +--- +name: javascript +file_extensions: [js] +scope: source.js +contexts: + main: + - match: '//.*$' + scope: comment.line + - match: '/\*' + push: + - meta_scope: comment.block + - match: '\*/' + pop: true + - match: '"' + push: + - meta_scope: string.quoted + - match: '\\.' + scope: constant.character.escape + - match: '"' + pop: true + - match: '''' + push: + - meta_scope: string.quoted + - match: '\\.' + scope: constant.character.escape + - match: '''' + pop: true + - match: '`' + push: + - meta_scope: string.quoted + - match: '\\.' + scope: constant.character.escape + - match: '`' + pop: true + - match: '\b(?:async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|export|extends|false|finally|for|from|function|get|if|import|in|instanceof|let|new|null|of|return|set|static|super|switch|this|throw|true|try|typeof|undefined|var|void|while|with|yield)\b' + scope: keyword.control + - match: '\b(?:0[xX][0-9a-fA-F_]+|[0-9][0-9_]*(?:\.[0-9_]+)?(?:[eE][+-]?[0-9]+)?)\b' + scope: constant.numeric + - match: '\b[A-Za-z_][A-Za-z0-9_]*(?=\s*\()' + scope: entity.name.function + - match: '[+*/%=!<>&|^~?:-]+' + scope: keyword.operator + - match: '[{}\[\]();,.]' + scope: punctuation.separator + - match: '\b[A-Z][A-Za-z0-9_]*\b' + scope: entity.name.type diff --git a/community/code-snippets/syntaxes/json.sublime-syntax b/community/code-snippets/syntaxes/json.sublime-syntax new file mode 100644 index 0000000..9f447fc --- /dev/null +++ b/community/code-snippets/syntaxes/json.sublime-syntax @@ -0,0 +1,26 @@ +%YAML 1.2 +--- +name: json +file_extensions: [json] +scope: source.json +contexts: + main: + - match: '"' + push: + - meta_scope: string.quoted + - match: '\\.' + scope: constant.character.escape + - match: '"' + pop: true + - match: '\b(?:true|false|null)\b' + scope: keyword.control + - match: '\b(?:0[xX][0-9a-fA-F_]+|[0-9][0-9_]*(?:\.[0-9_]+)?(?:[eE][+-]?[0-9]+)?)\b' + scope: constant.numeric + - match: '\b[A-Za-z_][A-Za-z0-9_]*(?=\s*\()' + scope: entity.name.function + - match: '[+*/%=!<>&|^~?:-]+' + scope: keyword.operator + - match: '[{}\[\]();,.]' + scope: punctuation.separator + - match: '\b[A-Z][A-Za-z0-9_]*\b' + scope: entity.name.type diff --git a/community/code-snippets/syntaxes/latex.sublime-syntax b/community/code-snippets/syntaxes/latex.sublime-syntax new file mode 100644 index 0000000..d21d639 --- /dev/null +++ b/community/code-snippets/syntaxes/latex.sublime-syntax @@ -0,0 +1,37 @@ +%YAML 1.2 +--- +name: latex +file_extensions: [tex] +scope: text.tex.latex +contexts: + main: + - match: '%.*$' + scope: comment.line + - match: '"' + push: + - meta_scope: string.quoted + - match: '\\.' + scope: constant.character.escape + - match: '"' + pop: true + - match: '''' + push: + - meta_scope: string.quoted + - match: '\\.' + scope: constant.character.escape + - match: '''' + pop: true + - match: '\b(?:0[xX][0-9a-fA-F_]+|[0-9][0-9_]*(?:\.[0-9_]+)?(?:[eE][+-]?[0-9]+)?)\b' + scope: constant.numeric + - match: '\\[A-Za-z]+' + scope: keyword.control + - match: '\$[^$]*\$' + scope: string.other.math + - match: '\b[A-Za-z_][A-Za-z0-9_]*(?=\s*\()' + scope: entity.name.function + - match: '[+*/%=!<>&|^~?:-]+' + scope: keyword.operator + - match: '[{}\[\]();,.]' + scope: punctuation.separator + - match: '\b[A-Z][A-Za-z0-9_]*\b' + scope: entity.name.type diff --git a/community/code-snippets/syntaxes/python.sublime-syntax b/community/code-snippets/syntaxes/python.sublime-syntax new file mode 100644 index 0000000..5d98cbf --- /dev/null +++ b/community/code-snippets/syntaxes/python.sublime-syntax @@ -0,0 +1,45 @@ +%YAML 1.2 +--- +name: python +file_extensions: [py] +scope: source.python +contexts: + main: + - match: '\#.*$' + scope: comment.line + - match: '"""' + push: + - meta_scope: string.quoted + - match: '"""' + pop: true + - match: '''''''' + push: + - meta_scope: string.quoted + - match: '''''''' + pop: true + - match: '"' + push: + - meta_scope: string.quoted + - match: '\\.' + scope: constant.character.escape + - match: '"' + pop: true + - match: '''' + push: + - meta_scope: string.quoted + - match: '\\.' + scope: constant.character.escape + - match: '''' + pop: true + - match: '\b(?:and|as|assert|async|await|break|class|continue|def|del|elif|else|except|False|finally|for|from|global|if|import|in|is|lambda|None|nonlocal|not|or|pass|raise|return|True|try|while|with|yield)\b' + scope: keyword.control + - match: '\b(?:0[xX][0-9a-fA-F_]+|[0-9][0-9_]*(?:\.[0-9_]+)?(?:[eE][+-]?[0-9]+)?)\b' + scope: constant.numeric + - match: '\b[A-Za-z_][A-Za-z0-9_]*(?=\s*\()' + scope: entity.name.function + - match: '[+*/%=!<>&|^~?:-]+' + scope: keyword.operator + - match: '[{}\[\]();,.]' + scope: punctuation.separator + - match: '\b[A-Z][A-Za-z0-9_]*\b' + scope: entity.name.type diff --git a/community/code-snippets/syntaxes/rust.sublime-syntax b/community/code-snippets/syntaxes/rust.sublime-syntax new file mode 100644 index 0000000..5eeacda --- /dev/null +++ b/community/code-snippets/syntaxes/rust.sublime-syntax @@ -0,0 +1,40 @@ +%YAML 1.2 +--- +name: rust +file_extensions: [rs] +scope: source.rust +contexts: + main: + - match: '//.*$' + scope: comment.line + - match: '/\*' + push: + - meta_scope: comment.block + - match: '\*/' + pop: true + - match: '"' + push: + - meta_scope: string.quoted + - match: '\\.' + scope: constant.character.escape + - match: '"' + pop: true + - match: '''' + push: + - meta_scope: string.quoted + - match: '\\.' + scope: constant.character.escape + - match: '''' + pop: true + - match: '\b(?:as|async|await|break|const|continue|crate|dyn|else|enum|extern|false|fn|for|if|impl|in|let|loop|match|mod|move|mut|pub|ref|return|self|Self|static|struct|super|trait|true|type|unsafe|use|where|while|union)\b' + scope: keyword.control + - match: '\b(?:0[xX][0-9a-fA-F_]+|[0-9][0-9_]*(?:\.[0-9_]+)?(?:[eE][+-]?[0-9]+)?)\b' + scope: constant.numeric + - match: '\b[A-Za-z_][A-Za-z0-9_]*(?=\s*\()' + scope: entity.name.function + - match: '[+*/%=!<>&|^~?:-]+' + scope: keyword.operator + - match: '[{}\[\]();,.]' + scope: punctuation.separator + - match: '\b[A-Z][A-Za-z0-9_]*\b' + scope: entity.name.type diff --git a/community/code-snippets/syntaxes/typescript.sublime-syntax b/community/code-snippets/syntaxes/typescript.sublime-syntax new file mode 100644 index 0000000..db05030 --- /dev/null +++ b/community/code-snippets/syntaxes/typescript.sublime-syntax @@ -0,0 +1,47 @@ +%YAML 1.2 +--- +name: typescript +file_extensions: [ts] +scope: source.ts +contexts: + main: + - match: '//.*$' + scope: comment.line + - match: '/\*' + push: + - meta_scope: comment.block + - match: '\*/' + pop: true + - match: '"' + push: + - meta_scope: string.quoted + - match: '\\.' + scope: constant.character.escape + - match: '"' + pop: true + - match: '''' + push: + - meta_scope: string.quoted + - match: '\\.' + scope: constant.character.escape + - match: '''' + pop: true + - match: '`' + push: + - meta_scope: string.quoted + - match: '\\.' + scope: constant.character.escape + - match: '`' + pop: true + - match: '\b(?:abstract|any|as|asserts|declare|enum|implements|infer|interface|is|keyof|module|namespace|never|number|override|private|protected|public|readonly|satisfies|string|symbol|type|unknown|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|export|extends|false|finally|for|from|function|get|if|import|in|instanceof|let|new|null|of|return|set|static|super|switch|this|throw|true|try|typeof|undefined|var|void|while|with|yield)\b' + scope: keyword.control + - match: '\b(?:0[xX][0-9a-fA-F_]+|[0-9][0-9_]*(?:\.[0-9_]+)?(?:[eE][+-]?[0-9]+)?)\b' + scope: constant.numeric + - match: '\b[A-Za-z_][A-Za-z0-9_]*(?=\s*\()' + scope: entity.name.function + - match: '[+*/%=!<>&|^~?:-]+' + scope: keyword.operator + - match: '[{}\[\]();,.]' + scope: punctuation.separator + - match: '\b[A-Z][A-Za-z0-9_]*\b' + scope: entity.name.type diff --git a/community/code-snippets/wit/plugin.wit b/community/code-snippets/wit/plugin.wit new file mode 100644 index 0000000..b6820d9 --- /dev/null +++ b/community/code-snippets/wit/plugin.wit @@ -0,0 +1,582 @@ +package animathio:plugin@1.1.0; + +/// Shared data types for vector graphics, parameter schemas and plugin manifests. +interface types { + /// 2D dimensions in integer pixels. + record size { + width: u32, + height: u32, + } + + /// Finite 2D coordinates: x right, y down. Scene.coordinate-space selects units. + record point { + x: f32, + y: f32, + } + + /// Straight-alpha 8-bit RGBA color. + record color { + r: u8, + g: u8, + b: u8, + a: u8, + } + + /// Path segment command. + variant path-verb { + move-to(point), + line-to(point), + quad-to(tuple), + cubic-to(tuple), + close, + } + + /// Sequence of path commands forming one or more contours. + type path = list; + + /// Line cap style at path endpoints. + enum stroke-cap { + butt, + round, + square, + } + + /// Line join style at path vertices. + enum stroke-join { + miter, + round, + bevel, + } + + /// Outline styling parameters. + record stroke-style { + width: f32, + color: color, + cap: stroke-cap, + join: stroke-join, + } + + /// Horizontal alignment in the available canvas width. + enum text-alignment { left, center, right } + + /// Text run layout element. + record text-element { + align: text-alignment, + text: string, + font-size: f32, + x: f32, + y: f32, + color: color, + } + + /// Vector drawing command. + variant draw-command { + fill-path(tuple), + stroke-path(tuple), + text-run(text-element), + } + + /// canvas: pixels on the requested render canvas. normalized: local unit square, + /// with x scaled by width and y by height. Strokes are outlined in local + /// units then transformed with the paths (nonuniform scaling is allowed). + /// Normalized text-run font-size is a fraction of canvas height; x/y are + /// offsets from the centered text block. Values outside 0..1 are allowed. + enum coordinate-space { canvas, normalized } + + /// Evaluated vector scene composed of ordered draw commands. + record scene { + coordinate-space: coordinate-space, + elements: list, + } + + /// Axis-aligned bounding box in canvas coordinates. + record bbox { + min-x: f32, + min-y: f32, + max-x: f32, + max-y: f32, + } + + /// Result of host-side math typesetting. + record typeset-result { + paths: list, + bbox: bbox, + } + + /// Input language for host-side math typesetting. + enum math-mode { + latex, + typst, + } + + /// Finite inclusive range; min <= default <= max and step > 0 (UI hint). + record number-range { + min: f64, + max: f64, + default: f64, + step: f64, + } + + /// Color parameter declaration. + record color-param { + default: color, + } + + /// Text string parameter declaration. + record string-param { + default: string, + } + + /// Multiple-choice enum parameter declaration. + record enum-param { + options: list, + default: string, + } + + /// Boolean toggle parameter declaration. + record bool-param { + default: bool, + } + + /// 2D point parameter declaration. + record point-param { + default: point, + } + + /// Asset reference parameter declaration. + record asset-ref-param { + media-type: string, + default-asset: option, + } + + /// Supported parameter types. + variant param-kind { + %number(number-range), + %color(color-param), + %string(string-param), + enum-choice(enum-param), + %bool(bool-param), + %point(point-param), + asset-ref(asset-ref-param), + } + + /// Stable id, fallback human label and typed schema. Labels are not identifiers. + /// Translation keys and units may be supplied in manifest.metadata. + record param-spec { + id: string, + label: string, + kind: param-kind, + } + + /// Concrete value assigned to a parameter at evaluation time. + variant param-value { + %number(f64), + %color(color), + %string(string), + enum-choice(string), + %bool(bool), + %point(point), + asset-ref(string), + } + + /// Key-value parameter entry. + record param-entry { + id: string, + value: param-value, + } + + /// Map of parameter values passed to plugin invocations. + type param-map = list; + + /// Open classification: clip-source, effect, audio-effect, animation-preset + /// (1.1) or importer (1.1). The legacy animation kind has no execution world. + /// Unknown strings are metadata, never permission to invoke an unknown world. + type plugin-kind = string; + + /// Optional, namespaced advisory metadata. Unknown keys must be ignored. + /// Keys are unique; values are UTF-8, never executable content. Reserved + /// conventions: label-key, description-key, param..unit, + /// param..label-key and param..option..label-key; + /// prefix with effect.. for effect descriptors. No localization service + /// is implied: plain labels/messages remain mandatory fallbacks. + type metadata = list>; + + /// Extensible error code plus fallback diagnostic text and advisory details. + /// Known codes: invalid-input, limit-exceeded, service-failed, plugin-error. + /// Unknown codes are displayed using message; callers must not parse messages. + record diagnostic { + code: string, + message: string, + metadata: metadata, + } + + /// Plugin metadata and parameter schema. + record manifest { + name: string, + version: string, + description: string, + kinds: list, + metadata: metadata, + params: list, + } +} + +/// Host-provided services imported by plugins. +interface host { + use types.{path, math-mode, typeset-result, diagnostic}; + + /// Text shaping via host font engine. Size is pixels; positive and finite. + /// Returns glyph outline paths or an explicit diagnostic. + shape-text: func(text: string, font-size: f32) -> result, diagnostic>; + + /// Typeset math via the host typesetting engine. Returns glyph and rule + /// outline paths plus a tight bounding box. + typeset-math: func(source: string, mode: math-mode, font-size: f32) -> result; + + /// Extract double-quoted d attributes from SVG path elements, or accept raw + /// SVG path data. This is not a complete SVG renderer: transforms, styles, + /// other primitives and external resources are not interpreted. Empty input + /// succeeds with no paths; unsupported/non-path input returns a diagnostic. + svg-to-paths: func(svg-xml: string) -> result, diagnostic>; + + /// Hard limits configured for this host, as unique key/value pairs. + /// Stable keys: ticks-per-second, max-memory-bytes, max-table-elements, + /// fuel-per-call, epoch-interval-ms, epoch-deadline-ticks, max-effect-pixels, + /// effect-memory-bytes, effect-fuel-per-pixel, effect-epoch-deadline-ticks, + /// max-audio-block-frames, max-audio-state-bytes, audio-memory-bytes, + /// audio-fuel-per-sample, audio-epoch-deadline-ticks, max-audio-channels, + /// max-audio-sample-rate, max-shape-text-chars, max-shape-text-verbs, + /// max-svg-input-bytes, max-svg-verbs, max-typeset-verbs, + /// max-typeset-source-bytes, max-typeset-font-size-px, typeset-timeout-ms, + /// max-log-message-bytes, max-log-entries, max-effects-per-plugin (added in 1.0.x); since 1.1 also max-import-source-bytes, + /// import-memory-bytes, import-fuel-per-byte, import-epoch-deadline-ticks, + /// max-import-output-bytes, max-import-commands, max-sibling-file-bytes, + /// max-sibling-total-bytes, max-sibling-files, max-preset-keys. + /// Keys and units are specified in docs/plugins.md; unknown keys are ignored. + /// This reports policy, not remaining fuel or memory. Budgets reset per call. + limits: func() -> list>; + + /// Host logging for diagnostic and debug output. + log: func(message: string); +} + +/// Pixel-filter effects, added in API 0.2.1. +/// +/// A frame effect receives one straight-alpha sRGB RGBA8 frame and returns a +/// frame of the same size. The host enforces size, fuel, wall-clock and memory +/// limits on every call; see `SandboxLimits` in `plugin-host`. +interface frame-effects { + use types.{size, param-map, param-spec, diagnostic}; + + /// One filter offered by an effect plugin. + record effect-descriptor { + /// Stable identifier, unique within the plugin (`[a-z0-9_-]`), stored in projects. + id: string, + /// Human-readable name for menus. + name: string, + /// One-line description for tooltips. + description: string, + /// Numeric parameters with range, default and step. Only `number` kinds are + /// supported; effect parameters are keyframeable numbers. + params: list, + } + + /// List the filters this plugin provides. + list-effects: func() -> list; + + /// Apply filter `effect` to `pixels`: `size.width * size.height * 4` bytes of + /// row-major straight-alpha sRGB RGBA8. Must return exactly the same number + /// of bytes. `time-ticks` is the clip-local source time. The call is a pure + /// function of its arguments. Returns a diagnostic on invalid input. + apply-frame: func(effect: string, pixels: list, size: size, params: param-map, time-ticks: s64) -> result, diagnostic>; +} + +/// Audio effects, added in API 0.2.2. +/// +/// An audio effect receives one block of interleaved f32 PCM and returns a block of +/// the same size. The host splits longer signals into contiguous blocks and carries an +/// opaque `state` blob from each call to the next, so filters, envelope followers and +/// other stateful processors work across block boundaries without the plugin keeping any +/// memory between calls. The host enforces block size, state size, fuel, wall-clock and +/// memory limits on every call; see `SandboxLimits` in `plugin-host`. +interface audio-effects { + use types.{param-map, param-spec, diagnostic}; + + /// One audio filter offered by an audio-effect plugin. + record audio-effect-descriptor { + /// Stable identifier, unique within the plugin (`[a-z0-9_-]`), stored in projects. + id: string, + /// Human-readable name for menus. + name: string, + /// One-line description for tooltips. + description: string, + /// Numeric parameters with range, default and step; keyframeable on clip chains. + /// Only `number` kinds are supported. + params: list, + } + + /// A block of interleaved 32-bit float PCM. + record audio-block { + /// Frames per second (1..=768000). + sample-rate: u32, + /// Interleaved channel count (1..=32). + channels: u16, + /// Time of the first frame in the chain's own timeline, in ticks: clip-local for a + /// clip chain, project time for a track chain. + start-ticks: s64, + /// `frames * channels` finite samples, frame-major interleaving. Unclipped; + /// values may exceed 1.0. Preserve channel order (stereo is left, right). + /// No channel-layout negotiation or planar format is implied. + samples: list, + } + + /// Result of processing one block. + record block-output { + /// Exactly as many samples as the input block. + samples: list, + /// State to hand back with the next contiguous block, or none for stateless filters. + state: option>, + } + + /// List the audio filters this plugin provides. + list-audio-effects: func() -> list; + + /// Process one block with filter `effect`. `state` is `none` for the first block of a + /// signal; an empty blob is equivalent to none. Otherwise it is exactly the + /// nonempty blob the previous call returned. The call is a pure + /// function of its arguments. Returns a diagnostic on invalid input. + process-block: func(effect: string, block: audio-block, params: param-map, state: option>) -> result; +} + +/// Animation presets, added in API 1.1.0. +/// +/// A preset plugin turns a preset choice into ordinary keyframe curves. The host +/// converts the curves into one `Command::Batch` of keyframe edits, so rendering never +/// calls the plugin and undo restores the previous keyframes exactly. +interface animation-presets { + use types.{param-map, param-spec, diagnostic}; + + /// Where a preset sits in a clip's lifetime. The host places the window: + /// entrance at the clip start, exit at the clip end, emphasis centred on the clip. + enum preset-role { + entrance, + exit, + emphasis, + } + + /// One preset offered by an animation-preset plugin. + record preset-descriptor { + /// Stable identifier, unique within the plugin (`[a-z0-9_-]`). + id: string, + /// Human-readable name for menus. + name: string, + /// One-line description for tooltips. + description: string, + /// Window placement. + role: preset-role, + /// Clip kinds the preset applies to; empty means every visual clip. Kind ids: + /// `video`, `image`, `vector` and `plugin:`. + applies-to: list, + /// Default window length in ticks (positive). + default-duration-ticks: s64, + /// Preset options: number, enum-choice or bool kinds only. + params: list, + } + + /// The clip a preset is generated for. + record clip-info { + /// Clip kind id, as in `applies-to`. + kind: string, + /// Visible clip length in ticks (positive). + duration-ticks: s64, + /// Length of one project frame in ticks (positive); a sampling hint. + frame-ticks: s64, + /// Current value of every animatable numeric target at the window's rest + /// point: the end of an entrance window, the start of an exit or emphasis + /// window. Keys are the curve target ids below. + rest: list>, + } + + /// Interpolation toward the next key, matching core keyframes. + enum curve-interpolation { + hold, + linear, + ease-in-out, + } + + /// One keyframe. `time-ticks` is relative to the window start, 0..=window. + record curve-key { + time-ticks: s64, + value: f64, + interpolation: curve-interpolation, + } + + /// Keyframes for one target: `opacity`, `x`, `y`, `scale-x`, `scale-y`, + /// `rotation` (radians) or `param:` for a numeric clip parameter. + record curve { + target: string, + keys: list, + } + + /// List the presets this plugin provides. + list-presets: func() -> list; + + /// Generate the curves for `preset` over a window of `window-ticks` (positive, + /// at most the clip duration). Pure in its arguments. Returns a diagnostic on + /// invalid input, e.g. a preset that does not apply to the clip kind. + generate: func(preset: string, clip: clip-info, window-ticks: s64, params: param-map) -> result, diagnostic>; +} + +/// Bounded reads of files next to an imported source, added in API 1.1.0. +/// Only importer components import this interface. +interface import-files { + use types.{diagnostic}; + + /// Read a file relative to the directory the host granted for this import. + /// `relative-path` uses `/` separators; absolute paths, `..` components and + /// paths that resolve (through symlinks) outside the directory are refused. + /// Per-file, total-byte and file-count caps apply per call; without a granted + /// directory every read fails with `invalid-input`. + read-sibling: func(relative-path: string) -> result, diagnostic>; +} + +/// Project importers, added in API 1.1.0. +/// +/// An importer turns source bytes into a versioned command document that the host +/// validates and replays onto a fresh project, plus content-addressed asset bytes. +interface importer { + use types.{param-map, param-spec, diagnostic}; + + /// One import format offered by an importer plugin. + record importer-descriptor { + /// Stable identifier, unique within the plugin (`[a-z0-9_-]`). + id: string, + /// Human-readable name for menus. + name: string, + /// One-line description for tooltips. + description: string, + /// Lower-case file extensions without the dot, e.g. `py`. + extensions: list, + /// Import options: string, number, enum-choice or bool kinds only. + params: list, + } + + /// The source being imported. + record import-source { + /// File name hint without directories (may be empty). + file-name: string, + /// Raw source bytes. + bytes: list, + } + + /// One asset referenced by the command document. + record imported-asset { + /// Lower-case hex BLAKE3 hash of `bytes`; the host recomputes it. + id: string, + /// Human-readable filename hint. + name: string, + /// Declared media type; decoders still probe the bytes. + media-type: string, + bytes: list, + } + + /// Non-fatal message severity. + enum message-severity { + info, + warning, + } + + /// One non-fatal observation; line and column are one-based, 0 when unknown. + record import-message { + severity: message-severity, + line: u32, + column: u32, + message: string, + snippet: string, + } + + /// A successful import. + record import-output { + /// UTF-8 JSON `{"version": 1, "commands": [...]}`: AniMathIO core commands + /// in their control-protocol serialization, replayed in order on an empty + /// project. Every command is validated; any failure rejects the import. + commands: string, + assets: list, + messages: list, + } + + /// List the formats this plugin imports. + list-importers: func() -> list; + + /// Import `source` with format `importer`. Pure apart from `read-sibling`. + run-import: func(importer: string, source: import-source, params: param-map) -> result; +} + +/// World for animation-preset plugins (`kinds = ["animation-preset"]`), API 1.1.0. +world animation-preset-plugin { + import host; + + use types.{manifest}; + + /// Describe the plugin and its kinds. + export describe: func() -> manifest; + + /// The presets themselves. + export animation-presets; +} + +/// World for importer plugins (`kinds = ["importer"]`), API 1.1.0. +world importer-plugin { + import host; + import import-files; + + use types.{manifest}; + + /// Describe the plugin and its kinds. + export describe: func() -> manifest; + + /// The import formats themselves. + export importer; +} + +/// World for audio-effect plugins (`kinds = ["audio-effect"]`): describe plus audio filters. +world audio-effect-plugin { + import host; + + use types.{manifest}; + + /// Describe the plugin and its kinds. + export describe: func() -> manifest; + + /// The audio filters themselves. + export audio-effects; +} + +/// World for effect plugins (`kinds = ["effect"]`): describe plus pixel filters. +/// Components for this world need no clip-source or animation exports. +world effect-plugin { + import host; + + use types.{manifest}; + + /// Describe the plugin and its kinds. + export describe: func() -> manifest; + + /// The pixel filters themselves. + export frame-effects; +} + +/// Pure vector generators. Frame and audio effects use their own worlds. +world source-plugin { + import host; + + use types.{manifest, scene, param-map, size, diagnostic}; + + /// Describe the plugin, its kinds and its parameter schema. + export describe: func() -> manifest; + + /// Render a vector scene, pure in its arguments. time-ticks is clip-local source + /// time in integer flicks (705600000 ticks/second). size is the render canvas. + /// An empty scene is valid; invalid geometry or traps fail the call. + export render-clip: func(params: param-map, time-ticks: s64, size: size) -> result; +} diff --git a/scripts/smoke.py b/scripts/smoke.py index 0934ba6..fa7390b 100644 --- a/scripts/smoke.py +++ b/scripts/smoke.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Render every source, then verify invert changes a frame and is self-inverse.""" +"""Render the circle examples, then verify invert changes a frame and is self-inverse.""" import io from PIL import Image import json @@ -36,7 +36,7 @@ def run(*args): for package in sorted(plugins.glob('*.amplugin')): with zipfile.ZipFile(package) as bundle: manifest = tomllib.loads(bundle.read('plugin.toml').decode()) - if manifest['kinds'] == ['clip-source']: + if manifest['kinds'] == ['clip-source'] and manifest['id'] in ['org.example.circle', 'org.example.generated-circle']: sources.append(manifest['id']) assert sources, 'No source plugins to test'