ProCraft for Android: An Android native painting app written in Rust
Rust
feat: initial commit & setup for procraft
Josh8992ef1096e5
diff --git a/.gitattributes b/.gitattributesnew file mode 100644index 0000000..717946f--- /dev/null+++ b/.gitattributes@@ -0,0 +1,6 @@+* text=auto eol=lf+*.bat text eol=crlf+*.jar binary+*.png binary+*.webp binary+*.ttf binarydiff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..265fb63--- /dev/null+++ b/.gitignore@@ -0,0 +1,6 @@+/target/+**/*.rs.bk++# JVM crash reports+hs_err_pid*.log+replay_pid*.logdiff --git a/Cargo.lock b/Cargo.locknew file mode 100644index 0000000..b53304e--- /dev/null+++ b/Cargo.lock@@ -0,0 +1,1827 @@+# 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 = "allocator-api2"+version = "0.2.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"++[[package]]+name = "android_log-sys"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "84521a3cf562bc62942e294181d9eef17eb38ceb8c68677bc49f144e4c3d4f8d"++[[package]]+name = "android_logger"+version = "0.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dbb4e440d04be07da1f1bf44fb4495ebd58669372fe0cffa6e48595ac5bd88a3"+dependencies = [+ "android_log-sys",+ "env_filter",+ "log",+]++[[package]]+name = "android_system_properties"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"+dependencies = [+ "libc",+]++[[package]]+name = "anstyle"+version = "1.0.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"++[[package]]+name = "anyhow"+version = "1.0.104"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"++[[package]]+name = "arrayvec"+version = "0.7.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"++[[package]]+name = "ash"+version = "0.38.0+1.3.281"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f"+dependencies = [+ "libloading",+]++[[package]]+name = "askama"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6024d73179f43f15ccd2b881bfea6fee7f3a46ec53f33b52210dea749ebebaa4"+dependencies = [+ "askama_macros",+ "itoa",+ "percent-encoding",+ "serde",+ "serde_json",+]++[[package]]+name = "askama_derive"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "071ee5ebf2138e3ad180e0aacf6940c2cab5e6d8333741d9925c7bee2b153f39"+dependencies = [+ "askama_parser",+ "basic-toml",+ "glob",+ "memchr",+ "proc-macro2",+ "quote",+ "rustc-hash 2.1.3",+ "serde",+ "serde_derive",+ "syn 3.0.9",+]++[[package]]+name = "askama_macros"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "643e1c7cbb6aec1d920332fe51a7c0d8219e273dcb8602db03f5263e4d16487b"+dependencies = [+ "askama_derive",+]++[[package]]+name = "askama_parser"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c5ae75772275d268b03ab8bdccdd12117b6169ee23256942b34e46c9f476583"+dependencies = [+ "rustc-hash 2.1.3",+ "serde",+ "serde_derive",+ "unicode-ident",+ "winnow",+]++[[package]]+name = "autocfg"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"++[[package]]+name = "basic-toml"+version = "0.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba62675e8242a4c4e806d12f11d136e626e6c8361d6b829310732241652a178a"+dependencies = [+ "serde",+]++[[package]]+name = "bit-set"+version = "0.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d"+dependencies = [+ "bit-vec",+]++[[package]]+name = "bit-vec"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"++[[package]]+name = "bitflags"+version = "2.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"++[[package]]+name = "bumpalo"+version = "3.20.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"++[[package]]+name = "bytemuck"+version = "1.25.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"+dependencies = [+ "bytemuck_derive",+]++[[package]]+name = "bytemuck_derive"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+]++[[package]]+name = "bytes"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"++[[package]]+name = "camino"+version = "1.2.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbbad30e4b4c14a39e3cc8aed085a12a327257c316619c93581e017bc52be591"+dependencies = [+ "serde_core",+]++[[package]]+name = "cargo-platform"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dd0061da739915fae12ea00e16397555ed4371a6bb285431aab930f61b0aa4ba"+dependencies = [+ "serde",+ "serde_core",+]++[[package]]+name = "cargo_metadata"+version = "0.23.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef987d17b0a113becdd19d3d0022d04d7ef41f9efe4f3fb63ac44ba61df3ade9"+dependencies = [+ "camino",+ "cargo-platform",+ "semver",+ "serde",+ "serde_json",+ "thiserror 2.0.21",+]++[[package]]+name = "cfg-if"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"++[[package]]+name = "cfg_aliases"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"++[[package]]+name = "clap"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"+dependencies = [+ "clap_builder",+ "clap_derive",+]++[[package]]+name = "clap_builder"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"+dependencies = [+ "anstyle",+ "clap_lex",+ "strsim",+]++[[package]]+name = "clap_derive"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"+dependencies = [+ "heck",+ "proc-macro2",+ "quote",+ "syn 3.0.9",+]++[[package]]+name = "clap_lex"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"++[[package]]+name = "codespan-reporting"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"+dependencies = [+ "unicode-width",+]++[[package]]+name = "crc32fast"+version = "1.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78"+dependencies = [+ "cfg-if",+]++[[package]]+name = "crunchy"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"++[[package]]+name = "dispatch2"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"+dependencies = [+ "bitflags",+ "objc2",+]++[[package]]+name = "document-features"+version = "0.2.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"+dependencies = [+ "litrs",+]++[[package]]+name = "env_filter"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1bf3c259d255ca70051b30e2e95b5446cdb8949ac4cd22c0d7fd634d89f568e2"+dependencies = [+ "log",+]++[[package]]+name = "equivalent"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"++[[package]]+name = "errno"+version = "0.3.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"+dependencies = [+ "libc",+ "windows-sys",+]++[[package]]+name = "fastrand"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"++[[package]]+name = "fdeflate"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"+dependencies = [+ "simd-adler32",+]++[[package]]+name = "flate2"+version = "1.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"+dependencies = [+ "crc32fast",+ "miniz_oxide 0.9.1",+ "zlib-rs",+]++[[package]]+name = "foldhash"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"++[[package]]+name = "fs-err"+version = "3.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b5c95b673b8f6f7235229ae11c5642d81b04c2e64c1e2fb417bc0cf73ca45f29"+dependencies = [+ "autocfg",+]++[[package]]+name = "futures-core"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"++[[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-core",+ "futures-task",+ "pin-project-lite",+ "slab",+]++[[package]]+name = "getrandom"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi",+]++[[package]]+name = "glob"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"++[[package]]+name = "goblin"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1b363a30c165f666402fe6a3024d3bec7ebc898f96a4a23bd1c99f8dbf3f4f47"+dependencies = [+ "log",+ "plain",+ "scroll",+]++[[package]]+name = "gpu-allocator"+version = "0.28.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795"+dependencies = [+ "ash",+ "hashbrown 0.16.1",+ "log",+ "presser",+ "thiserror 2.0.21",+ "windows",+]++[[package]]+name = "half"+version = "2.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"+dependencies = [+ "cfg-if",+ "crunchy",+ "num-traits",+ "zerocopy",+]++[[package]]+name = "hashbrown"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"+dependencies = [+ "allocator-api2",+ "equivalent",+ "foldhash",+]++[[package]]+name = "hashbrown"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"+dependencies = [+ "foldhash",+]++[[package]]+name = "heck"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"++[[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.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"++[[package]]+name = "jni-sys"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"+dependencies = [+ "jni-sys 0.4.1",+]++[[package]]+name = "jni-sys"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"+dependencies = [+ "jni-sys-macros",+]++[[package]]+name = "jni-sys-macros"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"+dependencies = [+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "js-sys"+version = "0.3.106"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5"+dependencies = [+ "cfg-if",+ "futures-util",+ "wasm-bindgen",+]++[[package]]+name = "libc"+version = "0.2.191"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"++[[package]]+name = "libloading"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"+dependencies = [+ "cfg-if",+ "windows-link",+]++[[package]]+name = "libm"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"++[[package]]+name = "linux-raw-sys"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"++[[package]]+name = "litrs"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70"++[[package]]+name = "lock_api"+version = "0.4.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"+dependencies = [+ "scopeguard",+]++[[package]]+name = "log"+version = "0.4.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "minimal-lexical"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"++[[package]]+name = "miniz_oxide"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"+dependencies = [+ "adler2",+ "simd-adler32",+]++[[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 = "naga"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130"+dependencies = [+ "arrayvec",+ "bit-set",+ "bitflags",+ "cfg-if",+ "cfg_aliases",+ "codespan-reporting",+ "half",+ "hashbrown 0.17.1",+ "indexmap",+ "libm",+ "log",+ "naga-types",+ "num-traits",+ "once_cell",+ "rustc-hash 1.1.0",+ "spirv",+ "thiserror 2.0.21",+ "unicode-ident",+]++[[package]]+name = "naga-types"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49"+dependencies = [+ "hashbrown 0.17.1",+ "indexmap",+ "rustc-hash 1.1.0",+ "thiserror 2.0.21",+]++[[package]]+name = "ndk"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"+dependencies = [+ "bitflags",+ "jni-sys 0.3.1",+ "log",+ "ndk-sys",+ "num_enum",+ "thiserror 1.0.69",+]++[[package]]+name = "ndk-sys"+version = "0.6.0+11769913"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873"+dependencies = [+ "jni-sys 0.3.1",+]++[[package]]+name = "nom"+version = "7.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"+dependencies = [+ "memchr",+ "minimal-lexical",+]++[[package]]+name = "num-traits"+version = "0.2.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"+dependencies = [+ "autocfg",+ "libm",+]++[[package]]+name = "num_enum"+version = "0.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26"+dependencies = [+ "num_enum_derive",+ "rustversion",+]++[[package]]+name = "num_enum_derive"+version = "0.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"+dependencies = [+ "proc-macro-crate",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "objc2"+version = "0.6.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"+dependencies = [+ "objc2-encode",+]++[[package]]+name = "objc2-core-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"+dependencies = [+ "bitflags",+ "dispatch2",+ "objc2",+]++[[package]]+name = "objc2-encode"+version = "4.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"++[[package]]+name = "objc2-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"+dependencies = [+ "bitflags",+ "objc2",+ "objc2-core-foundation",+]++[[package]]+name = "objc2-metal"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"+dependencies = [+ "bitflags",+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-quartz-core"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"+dependencies = [+ "bitflags",+ "objc2",+ "objc2-core-foundation",+ "objc2-foundation",+ "objc2-metal",+]++[[package]]+name = "once_cell"+version = "1.21.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"++[[package]]+name = "ordered-float"+version = "5.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8c7c9e0d9b23589f26070720bac724174bfec1083e82f7854cdd0267518343c0"+dependencies = [+ "num-traits",+]++[[package]]+name = "parking_lot"+version = "0.12.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"+dependencies = [+ "lock_api",+ "parking_lot_core",+]++[[package]]+name = "parking_lot_core"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"+dependencies = [+ "cfg-if",+ "libc",+ "redox_syscall",+ "smallvec",+ "windows-link",+]++[[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 = "plain"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"++[[package]]+name = "png"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"+dependencies = [+ "bitflags",+ "crc32fast",+ "fdeflate",+ "flate2",+ "miniz_oxide 0.8.9",+]++[[package]]+name = "pollster"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"++[[package]]+name = "portable-atomic"+version = "1.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"++[[package]]+name = "portable-atomic-util"+version = "0.2.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715"+dependencies = [+ "portable-atomic",+]++[[package]]+name = "presser"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"++[[package]]+name = "proc-macro-crate"+version = "3.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"+dependencies = [+ "toml_edit",+]++[[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 = "procraft-android"+version = "0.0.1"+dependencies = [+ "android_logger",+ "jni-sys 0.3.1",+ "log",+ "ndk",+ "png",+ "procraft-engine",+ "procraft-gpu",+ "raw-window-handle",+ "serde",+ "serde_json",+ "thiserror 2.0.21",+ "uniffi",+]++[[package]]+name = "procraft-android-bindgen"+version = "0.0.1"+dependencies = [+ "uniffi",+]++[[package]]+name = "procraft-engine"+version = "0.0.1"+dependencies = [+ "miniz_oxide 0.8.9",+ "serde",+ "serde_json",+]++[[package]]+name = "procraft-gpu"+version = "0.0.1"+dependencies = [+ "bytemuck",+ "log",+ "pollster",+ "procraft-engine",+ "thiserror 2.0.21",+ "wgpu",+]++[[package]]+name = "profiling"+version = "1.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5"++[[package]]+name = "quote"+version = "1.0.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "r-efi"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"++[[package]]+name = "range-alloc"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08"++[[package]]+name = "raw-window-handle"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"++[[package]]+name = "raw-window-metal"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135"+dependencies = [+ "objc2",+ "objc2-core-foundation",+ "objc2-foundation",+ "objc2-quartz-core",+]++[[package]]+name = "redox_syscall"+version = "0.5.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"+dependencies = [+ "bitflags",+]++[[package]]+name = "renderdoc-sys"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"++[[package]]+name = "rustc-hash"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"++[[package]]+name = "rustc-hash"+version = "2.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"++[[package]]+name = "rustix"+version = "1.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"+dependencies = [+ "bitflags",+ "errno",+ "libc",+ "linux-raw-sys",+ "windows-sys",+]++[[package]]+name = "rustversion"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"++[[package]]+name = "scopeguard"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"++[[package]]+name = "scroll"+version = "0.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ab8598aa408498679922eff7fa985c25d58a90771bd6be794434c5277eab1a6"+dependencies = [+ "scroll_derive",+]++[[package]]+name = "scroll_derive"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1783eabc414609e28a5ba76aee5ddd52199f7107a0b24c2e9746a1ecc34a683d"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[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.9",+]++[[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 = "serde_spanned"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c"+dependencies = [+ "serde_core",+]++[[package]]+name = "simd-adler32"+version = "0.3.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"++[[package]]+name = "siphasher"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"++[[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.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b"++[[package]]+name = "smawk"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e8e2fb0f499abb4d162f2bedad68f5ef91a1682b5a03596ddb67efd37768d100"++[[package]]+name = "spirv"+version = "0.4.0+sdk-1.4.341.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f"+dependencies = [+ "bitflags",+]++[[package]]+name = "static_assertions"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"++[[package]]+name = "strsim"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"++[[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.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "tempfile"+version = "3.27.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"+dependencies = [+ "fastrand",+ "getrandom",+ "once_cell",+ "rustix",+ "windows-sys",+]++[[package]]+name = "textwrap"+version = "0.16.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ecfad6c3abc80a577f2b91c1e412ee57e7a060d430b553c1b0c940974ebcd49"+dependencies = [+ "smawk",+ "unicode-width",+]++[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl 1.0.69",+]++[[package]]+name = "thiserror"+version = "2.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"+dependencies = [+ "thiserror-impl 2.0.21",+]++[[package]]+name = "thiserror-impl"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[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.9",+]++[[package]]+name = "tokio"+version = "1.53.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e"+dependencies = [+ "pin-project-lite",+]++[[package]]+name = "toml"+version = "1.1.8+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d"+dependencies = [+ "indexmap",+ "serde_core",+ "serde_spanned",+ "toml_datetime",+ "toml_parser",+ "toml_writer",+ "winnow",+]++[[package]]+name = "toml_datetime"+version = "1.1.2+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053"+dependencies = [+ "serde_core",+]++[[package]]+name = "toml_edit"+version = "0.25.17+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c"+dependencies = [+ "indexmap",+ "toml_datetime",+ "toml_parser",+ "winnow",+]++[[package]]+name = "toml_parser"+version = "1.1.5+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"+dependencies = [+ "winnow",+]++[[package]]+name = "toml_writer"+version = "1.1.3+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770"++[[package]]+name = "unicode-ident"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"++[[package]]+name = "unicode-width"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"++[[package]]+name = "uniffi"+version = "0.32.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76407f5f396a2c949a069eff4a9fca9ce462410eb872bffef4c2b7b89804a77a"+dependencies = [+ "anyhow",+ "camino",+ "cargo_metadata",+ "clap",+ "uniffi_bindgen",+ "uniffi_core",+ "uniffi_macros",+ "uniffi_pipeline",+]++[[package]]+name = "uniffi_bindgen"+version = "0.32.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3df3ced8f0eda3de99f6d50820e8628f443da8e4f447f477d1403ceba29dacbd"+dependencies = [+ "anyhow",+ "askama",+ "camino",+ "cargo_metadata",+ "fs-err",+ "glob",+ "goblin",+ "heck",+ "indexmap",+ "once_cell",+ "serde",+ "tempfile",+ "textwrap",+ "toml",+ "uniffi_internal_macros",+ "uniffi_meta",+ "uniffi_pipeline",+ "uniffi_udl",+]++[[package]]+name = "uniffi_core"+version = "0.32.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f7530ae8efeaaa488622865966763fe0294832779fff80508c36d69c6a874a6a"+dependencies = [+ "anyhow",+ "bytes",+ "once_cell",+ "static_assertions",+]++[[package]]+name = "uniffi_internal_macros"+version = "0.32.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0f4bad017164375d99450d70495014810d15a84ba9da6ed14b9628b1424223ba"+dependencies = [+ "anyhow",+ "indexmap",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "uniffi_macros"+version = "0.32.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5b855a58da153739ce6e863f6e296edc3716a093768c4d3d957f17f5e4317c60"+dependencies = [+ "camino",+ "fs-err",+ "once_cell",+ "proc-macro2",+ "quote",+ "serde",+ "syn 2.0.119",+ "toml",+ "uniffi_meta",+]++[[package]]+name = "uniffi_meta"+version = "0.32.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "af0c88664a9cb9559856f5a250283c9708923b303170e2e5c7db8f4ad65e9459"+dependencies = [+ "anyhow",+ "siphasher",+ "uniffi_internal_macros",+ "uniffi_pipeline",+]++[[package]]+name = "uniffi_pipeline"+version = "0.32.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d00f5c044b4a3dca0b1226c92ddaeea626f337470e22180dd182160c87a06b0b"+dependencies = [+ "anyhow",+ "heck",+ "indexmap",+ "tempfile",+ "uniffi_internal_macros",+]++[[package]]+name = "uniffi_udl"+version = "0.32.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "55dfd9c778d6b39cb5acd541d9ff63431974035d2bad83c897b766a6ee3152ac"+dependencies = [+ "anyhow",+ "textwrap",+ "uniffi_meta",+ "weedle2",+]++[[package]]+name = "wasm-bindgen"+version = "0.2.129"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409"+dependencies = [+ "cfg-if",+ "once_cell",+ "rustversion",+ "wasm-bindgen-macro",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-futures"+version = "0.4.79"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e"+dependencies = [+ "js-sys",+ "tokio",+ "wasm-bindgen",+]++[[package]]+name = "wasm-bindgen-macro"+version = "0.2.129"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535"+dependencies = [+ "quote",+ "wasm-bindgen-macro-support",+]++[[package]]+name = "wasm-bindgen-macro-support"+version = "0.2.129"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7"+dependencies = [+ "bumpalo",+ "proc-macro2",+ "quote",+ "syn 3.0.9",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-shared"+version = "0.2.129"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "web-sys"+version = "0.3.106"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "weedle2"+version = "5.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "998d2c24ec099a87daf9467808859f9d82b61f1d9c9701251aea037f514eae0e"+dependencies = [+ "nom",+]++[[package]]+name = "wgpu"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "527ccdf43dd5b2e8676eed9984ce00e2bbb0a1b85b70c1969dcb6cd2eb55ab9e"+dependencies = [+ "arrayvec",+ "bitflags",+ "bytemuck",+ "cfg-if",+ "cfg_aliases",+ "document-features",+ "hashbrown 0.17.1",+ "js-sys",+ "log",+ "parking_lot",+ "portable-atomic",+ "profiling",+ "raw-window-handle",+ "smallvec",+ "static_assertions",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+ "wgpu-core",+ "wgpu-hal",+ "wgpu-types",+]++[[package]]+name = "wgpu-core"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14"+dependencies = [+ "arrayvec",+ "bit-set",+ "bit-vec",+ "bitflags",+ "bytemuck",+ "cfg_aliases",+ "document-features",+ "hashbrown 0.17.1",+ "indexmap",+ "log",+ "naga",+ "naga-types",+ "once_cell",+ "parking_lot",+ "portable-atomic",+ "profiling",+ "raw-window-handle",+ "rustc-hash 1.1.0",+ "smallvec",+ "thiserror 2.0.21",+ "wgpu-core-deps-windows-linux-android",+ "wgpu-hal",+ "wgpu-naga-bridge",+ "wgpu-types",+]++[[package]]+name = "wgpu-core-deps-windows-linux-android"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7586165fd5f6d881cb9ce4bb71f40d6caab2c0f1837e3fc1d9788a197fb6004f"+dependencies = [+ "wgpu-hal",+]++[[package]]+name = "wgpu-hal"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6b7fb58561a792bc237628ba0792e332de418fefe145f13b5ed8201e6d52f58"+dependencies = [+ "android_system_properties",+ "arrayvec",+ "ash",+ "bit-set",+ "bitflags",+ "bytemuck",+ "cfg-if",+ "cfg_aliases",+ "gpu-allocator",+ "hashbrown 0.17.1",+ "libc",+ "libloading",+ "log",+ "naga",+ "naga-types",+ "once_cell",+ "ordered-float",+ "parking_lot",+ "portable-atomic",+ "portable-atomic-util",+ "profiling",+ "range-alloc",+ "raw-window-handle",+ "raw-window-metal",+ "renderdoc-sys",+ "smallvec",+ "static_assertions",+ "thiserror 2.0.21",+ "wgpu-naga-bridge",+ "wgpu-types",+ "windows",+ "windows-core",+]++[[package]]+name = "wgpu-naga-bridge"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2f62e73117bb7a62bfd9c5a5841438a823f6566c6442a808ee269d2d055c081"+dependencies = [+ "naga",+ "wgpu-types",+]++[[package]]+name = "wgpu-types"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "99dad6f1fbdbbdb4c278a6508b059d44688f5cebddf78d005a46a31340269286"+dependencies = [+ "bitflags",+ "bytemuck",+ "js-sys",+ "log",+ "naga-types",+ "raw-window-handle",+ "static_assertions",+ "web-sys",+]++[[package]]+name = "windows"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"+dependencies = [+ "windows-collections",+ "windows-core",+ "windows-future",+ "windows-numerics",+]++[[package]]+name = "windows-collections"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"+dependencies = [+ "windows-core",+]++[[package]]+name = "windows-core"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-link",+ "windows-result",+ "windows-strings",+]++[[package]]+name = "windows-future"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"+dependencies = [+ "windows-core",+ "windows-link",+ "windows-threading",+]++[[package]]+name = "windows-implement"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "windows-interface"+version = "0.59.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-numerics"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"+dependencies = [+ "windows-core",+ "windows-link",+]++[[package]]+name = "windows-result"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-strings"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"+dependencies = [+ "windows-link",+]++[[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 = "windows-threading"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"+dependencies = [+ "windows-link",+]++[[package]]+name = "winnow"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"+dependencies = [+ "memchr",+]++[[package]]+name = "zerocopy"+version = "0.8.63"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8"+dependencies = [+ "zerocopy-derive",+]++[[package]]+name = "zerocopy-derive"+version = "0.8.63"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[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/Cargo.toml b/Cargo.tomlnew file mode 100644index 0000000..88ef275--- /dev/null+++ b/Cargo.toml@@ -0,0 +1,49 @@+[workspace]+resolver = "3"+members = ["crates/engine", "crates/gpu", "apps/procraft-android", "apps/procraft-android/bindgen"]++[workspace.package]+version = "0.0.1"+edition = "2024"+rust-version = "1.95"+publish = false++[workspace.lints.rust]+# `deny`, not `forbid`: the one place that talks to the platform (the Android bridge's surface+# module) allows it locally.+unsafe_code = "deny"++[workspace.lints.clippy]+# Never crash on input: no unwrap/expect/panics/indexing outside tests (see clippy.toml).+unwrap_used = "deny"+expect_used = "deny"+panic = "deny"+indexing_slicing = "deny"+todo = "deny"+unimplemented = "deny"+unreachable = "deny"+dbg_macro = "warn"+too_many_arguments = "allow"++[workspace.dependencies]+procraft-engine = { path = "crates/engine" }+procraft-gpu = { path = "crates/gpu" }+wgpu = { version = "30", default-features = false, features = ["std", "parking_lot", "vulkan", "dx12", "wgsl"] }+bytemuck = { version = "1", features = ["derive"] }+pollster = "0.4"+log = "0.4"+thiserror = "2"+serde = { version = "1", features = ["derive"] }+serde_json = "1"+png = "0.18"+miniz_oxide = "0.8"++[profile.dev]+opt-level = 1++[profile.dev.package."*"]+opt-level = 2++[profile.release]+lto = "thin"+debug = falsediff --git a/README.md b/README.mdnew file mode 100644index 0000000..a71e87f--- /dev/null+++ b/README.md@@ -0,0 +1,27 @@+# ProCraft++A painting app for Android tablets, with a Rust engine and GPU renderer under a Kotlin / Jetpack+Compose interface.++**Status:** early. You can draw on the canvas with pen pressure and tapered strokes, erase, undo+and redo, and move, zoom and turn the canvas with two fingers.++## Layout++| Path | What |+|---|---|+| `crates/engine` | document, brushes, stroke geometry, canvas view (no GPU) |+| `crates/gpu` | wgpu renderer: layers, strokes, compositing, display |+| `apps/procraft-android` | the native library for Android (UniFFI bindings) |+| `apps/procraft-android/android` | the Android app (Gradle) |++## Building++```+cargo test --workspace+cd apps/procraft-android/android+./gradlew :app:assembleRelease -Pprocraft.abis=arm64-v8a+```++You need Rust with the Android targets, `cargo-ndk`, the Android SDK with NDK 29.0.14206865, and+JDK 17.diff --git a/apps/procraft-android/Cargo.toml b/apps/procraft-android/Cargo.tomlnew file mode 100644index 0000000..bd75a4f--- /dev/null+++ b/apps/procraft-android/Cargo.toml@@ -0,0 +1,33 @@+[package]+name = "procraft-android"+version.workspace = true+edition.workspace = true+rust-version.workspace = true+publish.workspace = true+description = "ProCraft on Android: the engine and renderer as a native library with Kotlin bindings (UniFFI); the app is in android/"++[lib]+name = "procraft_android"+# cdylib: the library the app loads; lib: the tests+crate-type = ["cdylib", "lib"]++[lints]+workspace = true++[dependencies]+procraft-engine = { workspace = true }+procraft-gpu = { workspace = true }+log = { workspace = true }+thiserror = { workspace = true }+serde = { workspace = true }+serde_json = { workspace = true }+png = { workspace = true }+# The exact version: the Kotlin bindings are generated by the same release (bindgen/, sharing this+# lock file) and refuse to load against another one.+uniffi = { version = "=0.32.2", default-features = false }++[target.'cfg(target_os = "android")'.dependencies]+android_logger = { version = "0.15", default-features = false }+ndk = { version = "0.9", default-features = false }+jni-sys = "0.3"+raw-window-handle = "0.6"diff --git a/apps/procraft-android/android/.gitignore b/apps/procraft-android/android/.gitignorenew file mode 100644index 0000000..2856a99--- /dev/null+++ b/apps/procraft-android/android/.gitignore@@ -0,0 +1,9 @@+.gradle/+.kotlin/+.idea/+*.iml+build/+local.properties+captures/+.externalNativeBuild/+.cxx/diff --git a/apps/procraft-android/android/app/build.gradle.kts b/apps/procraft-android/android/app/build.gradle.ktsnew file mode 100644index 0000000..92e1527--- /dev/null+++ b/apps/procraft-android/android/app/build.gradle.kts@@ -0,0 +1,160 @@+import javax.inject.Inject+import org.gradle.process.ExecOperations++plugins {+ alias(libs.plugins.android.application)+ alias(libs.plugins.kotlin.compose)+}++// The Rust half of the app: this Gradle project is the android/ folder of the `procraft-android`+// crate (apps/procraft-android), which sits in the ProCraft cargo workspace two folders up.+val cargoWorkspaceDir: File = rootDir.parentFile.parentFile.parentFile+val rustAbis: List<String> =+ providers.gradleProperty("procraft.abis").getOrElse("arm64-v8a,x86_64").split(',').map { it.trim() }.filter { it.isNotEmpty() }+val minApi = 29++/** rustup's `cargo` (Android Studio may not see rustup's PATH), else `cargo` from PATH; `CARGO` overrides. */+val cargoExecutable: String = run {+ val exe = if (System.getProperty("os.name").lowercase().startsWith("windows")) "cargo.exe" else "cargo"+ val rustup = File(System.getProperty("user.home"), ".cargo/bin/$exe")+ providers.environmentVariable("CARGO").orNull ?: if (rustup.isFile) rustup.absolutePath else exe+}++/** Builds `libprocraft_android.so` (release profile) for each ABI with cargo-ndk. */+abstract class CargoNdkBuild : DefaultTask() {+ @get:Inject abstract val execOperations: ExecOperations+ @get:Input abstract val cargo: Property<String>+ @get:Input abstract val workspaceDir: Property<String>+ @get:Input abstract val ndkDir: Property<String>+ @get:Input abstract val abis: ListProperty<String>+ @get:Input abstract val apiLevel: Property<Int>+ @get:OutputDirectory abstract val outputDir: DirectoryProperty++ @TaskAction+ fun build() {+ val targets = abis.get().flatMap { listOf("-t", it) }+ val out = outputDir.get().asFile.absolutePath+ // the library mustn't hold the paths it was built in (panic locations name source files)+ val cargoHome = System.getenv("CARGO_HOME")?.takeIf { it.isNotBlank() } ?: File(System.getProperty("user.home"), ".cargo").absolutePath+ val remap = listOf(+ "--remap-path-prefix=${File(workspaceDir.get()).absolutePath}=/procraft",+ "--remap-path-prefix=$cargoHome=/cargo",+ )+ execOperations.exec {+ workingDir(workspaceDir.get())+ environment("ANDROID_NDK_HOME", ndkDir.get())+ environment("CARGO_ENCODED_RUSTFLAGS", remap.joinToString("\u001f"))+ commandLine(+ listOf(cargo.get(), "ndk") + targets ++ listOf("--platform", apiLevel.get().toString(), "-o", out, "build", "--release", "-p", "procraft-android", "--lib"),+ )+ }+ // only the app's library ships (cargo-ndk copies any other shared library cargo left)+ File(out).walk().filter { it.isFile && it.name != "libprocraft_android.so" }.forEach { it.delete() }+ }+}++/** Generates the Kotlin bindings from the library cargo built (UniFFI library mode). */+abstract class UniffiBindgen : DefaultTask() {+ @get:Inject abstract val execOperations: ExecOperations+ @get:Input abstract val cargo: Property<String>+ @get:Input abstract val workspaceDir: Property<String>+ @get:InputFile @get:PathSensitive(PathSensitivity.NONE) abstract val library: RegularFileProperty+ @get:OutputDirectory abstract val outputDir: DirectoryProperty++ @TaskAction+ fun generate() {+ val out = outputDir.get().asFile+ out.deleteRecursively()+ out.mkdirs()+ execOperations.exec {+ workingDir(workspaceDir.get())+ commandLine(+ cargo.get(), "run", "--quiet", "-p", "procraft-android-bindgen", "--",+ "generate", library.get().asFile.absolutePath, "--language", "kotlin", "--out-dir", out.absolutePath, "--no-format",+ )+ }+ }+}++android {+ namespace = "io.github.artcraftandroid.procraft"+ compileSdk = 37+ ndkVersion = "29.0.14206865"++ defaultConfig {+ applicationId = "io.github.artcraftandroid.procraft"+ minSdk = minApi+ targetSdk = 36+ versionCode = providers.gradleProperty("procraft.versionCode").get().toInt()+ versionName = providers.gradleProperty("procraft.version").get()+ ndk { abiFilters.addAll(rustAbis) }+ }++ buildTypes {+ debug {+ applicationIdSuffix = ".debug"+ }+ release {+ isMinifyEnabled = true+ isShrinkResources = true+ proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")+ // signed with the debug key until there is a release key+ signingConfig = signingConfigs.getByName("debug")+ vcsInfo { include = false }+ }+ }+ dependenciesInfo {+ includeInApk = false+ includeInBundle = false+ }+ compileOptions {+ sourceCompatibility = JavaVersion.VERSION_17+ targetCompatibility = JavaVersion.VERSION_17+ }+ buildFeatures {+ compose = true+ }+}++androidComponents {+ onVariants { variant ->+ val name = variant.name.replaceFirstChar { it.uppercase() }+ val cargoBuild = tasks.register<CargoNdkBuild>("cargoBuild$name") {+ group = "rust"+ description = "Builds libprocraft_android.so for $rustAbis"+ cargo.set(cargoExecutable)+ workspaceDir.set(cargoWorkspaceDir.absolutePath)+ ndkDir.set(androidComponents.sdkComponents.ndkDirectory.map { it.asFile.absolutePath })+ abis.set(rustAbis)+ apiLevel.set(minApi)+ // cargo knows what changed+ outputs.upToDateWhen { false }+ }+ val bindgen = tasks.register<UniffiBindgen>("uniffiBindgen$name") {+ group = "rust"+ description = "Generates the Kotlin bindings of libprocraft_android.so"+ cargo.set(cargoExecutable)+ workspaceDir.set(cargoWorkspaceDir.absolutePath)+ library.set(cargoBuild.flatMap { it.outputDir.file("${rustAbis.first()}/libprocraft_android.so") })+ }+ variant.sources.jniLibs?.addGeneratedSourceDirectory(cargoBuild, CargoNdkBuild::outputDir)+ variant.sources.java?.addGeneratedSourceDirectory(bindgen, UniffiBindgen::outputDir)+ }+}++tasks.configureEach {+ if (name.contains("ArtProfile")) enabled = false+}++dependencies {+ implementation(libs.androidx.core.ktx)+ implementation(libs.androidx.activity.compose)+ implementation(libs.androidx.lifecycle.viewmodel.compose)+ implementation(platform(libs.androidx.compose.bom))+ implementation(libs.androidx.compose.ui)+ implementation(libs.androidx.compose.material3)+ implementation(libs.androidx.input.motionprediction)+ implementation(libs.jna) { artifact { type = "aar" } }+ testImplementation(libs.junit)+}diff --git a/apps/procraft-android/android/app/proguard-rules.pro b/apps/procraft-android/android/app/proguard-rules.pronew file mode 100644index 0000000..7e02f32--- /dev/null+++ b/apps/procraft-android/android/app/proguard-rules.pro@@ -0,0 +1,8 @@+# UniFFI's Kotlin bindings reach the Rust library through JNA, which finds the bindings' native+# functions and structures by reflection: keep both.+-keep class com.sun.jna.** { *; }+-keep class * implements com.sun.jna.** { *; }+-keep class io.github.artcraftandroid.procraft.core.** { *; }+# the JNI functions the library exports are found by these names+-keep class io.github.artcraftandroid.procraft.canvas.NativeWindows { *; }+-dontwarn java.awt.**diff --git a/apps/procraft-android/android/app/src/main/AndroidManifest.xml b/apps/procraft-android/android/app/src/main/AndroidManifest.xmlnew file mode 100644index 0000000..23a0d47--- /dev/null+++ b/apps/procraft-android/android/app/src/main/AndroidManifest.xml@@ -0,0 +1,63 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++ <application+ android:allowBackup="false"+ android:enableOnBackInvokedCallback="true"+ android:icon="@mipmap/ic_launcher"+ android:label="@string/app_name"+ android:roundIcon="@mipmap/ic_launcher"+ android:supportsRtl="true"+ android:theme="@style/Theme.ProCraft">++ <!-- configuration changes are handled in place: the canvas and its GPU state stay -->+ <activity+ android:name=".MainActivity"+ android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density"+ android:exported="true"+ android:launchMode="singleTask"+ android:windowSoftInputMode="adjustNothing">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>+ <!-- a file opened with the app, or shared to it: artworks, packages and pictures go to the gallery -->+ <intent-filter>+ <action android:name="android.intent.action.VIEW" />+ <action android:name="android.intent.action.SEND" />+ <category android:name="android.intent.category.DEFAULT" />+ <data android:mimeType="application/octet-stream" />+ <data android:mimeType="application/zip" />+ <data android:mimeType="image/*" />+ </intent-filter>+ </activity>++ <!-- the app's settings: also what Android's page for the app links to -->+ <activity+ android:name=".SettingsActivity"+ android:exported="true"+ android:label="@string/app_name">+ <intent-filter>+ <action android:name="android.intent.action.APPLICATION_PREFERENCES" />+ <category android:name="android.intent.category.DEFAULT" />+ </intent-filter>+ </activity>++ <!-- hands exported pictures to other apps -->+ <provider+ android:name="androidx.core.content.FileProvider"+ android:authorities="${applicationId}.files"+ android:exported="false"+ android:grantUriPermissions="true">+ <meta-data+ android:name="android.support.FILE_PROVIDER_PATHS"+ android:resource="@xml/shared_files" />+ </provider>+ <!-- artworks dragged out of the gallery, made when another app opens them -->+ <provider+ android:name=".gallery.DragProvider"+ android:authorities="${applicationId}.drag"+ android:exported="false"+ android:grantUriPermissions="true" />+ </application>+</manifest>diff --git a/apps/procraft-android/android/app/src/main/assets/fonts/Inter-Bold.ttf b/apps/procraft-android/android/app/src/main/assets/fonts/Inter-Bold.ttfnew file mode 100644index 0000000..9fb9b75Binary files /dev/null and b/apps/procraft-android/android/app/src/main/assets/fonts/Inter-Bold.ttf differdiff --git a/apps/procraft-android/android/app/src/main/assets/fonts/Inter-Medium.ttf b/apps/procraft-android/android/app/src/main/assets/fonts/Inter-Medium.ttfnew file mode 100644index 0000000..458cd06Binary files /dev/null and b/apps/procraft-android/android/app/src/main/assets/fonts/Inter-Medium.ttf differdiff --git a/apps/procraft-android/android/app/src/main/assets/fonts/Inter-OFL.txt b/apps/procraft-android/android/app/src/main/assets/fonts/Inter-OFL.txtnew file mode 100644index 0000000..9b2ca37--- /dev/null+++ b/apps/procraft-android/android/app/src/main/assets/fonts/Inter-OFL.txt@@ -0,0 +1,92 @@+Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)++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:+http://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 AND 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/apps/procraft-android/android/app/src/main/assets/fonts/Inter-Regular.ttf b/apps/procraft-android/android/app/src/main/assets/fonts/Inter-Regular.ttfnew file mode 100644index 0000000..b7aaca8Binary files /dev/null and b/apps/procraft-android/android/app/src/main/assets/fonts/Inter-Regular.ttf differdiff --git a/apps/procraft-android/android/app/src/main/assets/fonts/Inter-SemiBold.ttf b/apps/procraft-android/android/app/src/main/assets/fonts/Inter-SemiBold.ttfnew file mode 100644index 0000000..47f8ab1Binary files /dev/null and b/apps/procraft-android/android/app/src/main/assets/fonts/Inter-SemiBold.ttf differdiff --git a/apps/procraft-android/android/app/src/main/assets/fonts/SOURCE.md b/apps/procraft-android/android/app/src/main/assets/fonts/SOURCE.mdnew file mode 100644index 0000000..7fa3d22--- /dev/null+++ b/apps/procraft-android/android/app/src/main/assets/fonts/SOURCE.md@@ -0,0 +1,6 @@+# Fonts++`Inter-Regular.ttf`, `Inter-Medium.ttf`, `Inter-SemiBold.ttf` and `Inter-Bold.ttf` are Inter 4.1 by+The Inter Project Authors, from https://github.com/rsms/inter/releases/tag/v4.1 (`Inter-4.1.zip`,+SHA-256 `9883fdd4a49d4fb66bd8177ba6625ef9a64aa45899767dde3d36aa425756b11e`, files from+`extras/ttf/`). Licence: SIL Open Font License 1.1, in `Inter-OFL.txt`.diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/MainActivity.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/MainActivity.ktnew file mode 100644index 0000000..be7edf1--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/MainActivity.kt@@ -0,0 +1,148 @@+package io.github.artcraftandroid.procraft++import android.graphics.Color+import android.hardware.display.DisplayManager+import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.SystemBarStyle+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.viewModels+import androidx.compose.runtime.snapshotFlow+import androidx.lifecycle.lifecycleScope+import androidx.core.view.WindowCompat+import androidx.core.view.WindowInsetsCompat+import androidx.core.view.WindowInsetsControllerCompat+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import io.github.artcraftandroid.procraft.canvas.ProjectionPresentation+import kotlinx.coroutines.launch+import io.github.artcraftandroid.procraft.ui.AppRoot++/** How long a finger's touch stays where it landed with tap assistance on. */+private const val TAP_HOLD_MS = 300L++class MainActivity : ComponentActivity() {+ private val vm: CanvasViewModel by viewModels()++ // Project canvas: the presentation on a second display, and the displays coming and going+ private var projection: ProjectionPresentation? = null+ private val displays by lazy { getSystemService(DisplayManager::class.java) }+ private val displayListener = object : DisplayManager.DisplayListener {+ override fun onDisplayAdded(displayId: Int) = showProjection()+ override fun onDisplayRemoved(displayId: Int) = showProjection()+ override fun onDisplayChanged(displayId: Int) = Unit+ }++ override fun onCreate(savedInstanceState: Bundle?) {+ enableEdgeToEdge(SystemBarStyle.dark(Color.TRANSPARENT), SystemBarStyle.dark(Color.TRANSPARENT))+ super.onCreate(savedInstanceState)+ io.github.artcraftandroid.procraft.canvas.TextRenderer.assets = assets+ io.github.artcraftandroid.procraft.canvas.TextRenderer.loadImported(java.io.File(filesDir, "fonts"))+ window.isNavigationBarContrastEnforced = false+ // wide colour, so a Display P3 canvas's colours show as they are around it too+ if (resources.configuration.isScreenWideColorGamut) window.colorMode = android.content.pm.ActivityInfo.COLOR_MODE_WIDE_COLOR_GAMUT+ hideSystemBars()+ // made here, not inside the flow's read-only snapshot, where its setup can't write state+ val model = vm+ setContent { AppRoot(model) }+ lifecycleScope.launch { snapshotFlow { model.projectCanvas }.collect { showProjection() } }+ importOpened(intent)+ }++ override fun onNewIntent(intent: android.content.Intent) {+ super.onNewIntent(intent)+ importOpened(intent)+ }++ /**+ * A file opened with the app, or shared to it, is imported into the gallery (once), which+ * shows: an open artwork is saved and closed first.+ */+ private fun importOpened(intent: android.content.Intent?) {+ intent ?: return+ val uri = when (intent.action) {+ android.content.Intent.ACTION_VIEW -> intent.data+ android.content.Intent.ACTION_SEND ->+ androidx.core.content.IntentCompat.getParcelableExtra(intent, android.content.Intent.EXTRA_STREAM, android.net.Uri::class.java)+ else -> null+ } ?: return+ intent.action = null+ if (vm.screen == io.github.artcraftandroid.procraft.canvas.Screen.CANVAS) vm.closeArtwork()+ vm.importFile(uri)+ }++ override fun onStart() {+ super.onStart()+ vm.readAppSettings()+ vm.resumeTracking()+ displays.registerDisplayListener(displayListener, null)+ showProjection()+ }++ override fun onStop() {+ super.onStop()+ vm.saveNow()+ displays.unregisterDisplayListener(displayListener)+ projection?.dismiss()+ projection = null+ }++ /** Project canvas: while it is on, the canvas shows on the first second display there is. */+ private fun showProjection() {+ val display = if (vm.projectCanvas) displays.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION).firstOrNull() else null+ if (projection != null && projection?.display?.displayId == display?.displayId) return+ projection?.dismiss()+ projection = display?.let { d -> ProjectionPresentation(this, d, vm).takeIf { runCatching { it.show() }.isSuccess } }+ }++ // tap assistance: where a finger first landed, and when, while its touch is held there+ private var heldAt: android.graphics.PointF? = null+ private var heldSince = 0L++ /**+ * Tap assistance: for its first moments a finger's touch stays where it landed (its moves are+ * held back and its lift is put back there), so a tap that drifts still lands where it began.+ * More fingers, or a touch held longer, go on as they are.+ */+ override fun dispatchTouchEvent(e: android.view.MotionEvent): Boolean {+ if (!vm.tapAssistance || e.getToolType(0) != android.view.MotionEvent.TOOL_TYPE_FINGER) return super.dispatchTouchEvent(e)+ when (e.actionMasked) {+ android.view.MotionEvent.ACTION_DOWN -> {+ heldAt = android.graphics.PointF(e.x, e.y)+ heldSince = e.eventTime+ }+ android.view.MotionEvent.ACTION_POINTER_DOWN, android.view.MotionEvent.ACTION_CANCEL -> heldAt = null+ android.view.MotionEvent.ACTION_MOVE -> {+ if (heldAt != null && e.eventTime - heldSince <= TAP_HOLD_MS) return true+ heldAt = null+ }+ android.view.MotionEvent.ACTION_UP -> {+ val at = heldAt+ heldAt = null+ if (at != null) {+ val held = android.view.MotionEvent.obtain(e).apply { setLocation(at.x, at.y) }+ return super.dispatchTouchEvent(held).also { held.recycle() }+ }+ }+ }+ return super.dispatchTouchEvent(e)+ }++ /** A hardware keyboard's shortcuts on the canvas (keys no text field took). */+ override fun onKeyDown(keyCode: Int, event: android.view.KeyEvent): Boolean {+ if (event.repeatCount == 0 && vm.keyShortcut(keyCode, event.isCtrlPressed || event.isMetaPressed, event.isShiftPressed, event.isAltPressed)) return true+ return super.onKeyDown(keyCode, event)+ }++ override fun onWindowFocusChanged(hasFocus: Boolean) {+ super.onWindowFocusChanged(hasFocus)+ if (hasFocus) hideSystemBars()+ }++ /** The canvas uses the whole screen; a swipe from the edge shows the bars for a moment. */+ private fun hideSystemBars() {+ val controller = WindowCompat.getInsetsController(window, window.decorView)+ controller.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE+ controller.hide(WindowInsetsCompat.Type.systemBars())+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/SettingsActivity.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/SettingsActivity.ktnew file mode 100644index 0000000..c5c9799--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/SettingsActivity.kt@@ -0,0 +1,233 @@+package io.github.artcraftandroid.procraft++import android.content.Context+import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.compose.foundation.Canvas+import androidx.compose.foundation.background+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.gestures.drag+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.safeDrawingPadding+import androidx.compose.foundation.layout.widthIn+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.material3.DropdownMenu+import androidx.compose.material3.DropdownMenuItem+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.StrokeCap+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import io.github.artcraftandroid.procraft.ui.Switch++/**+ * The app's own settings, apart from the canvas: what Android's page for the app links to as its+ * settings, and Help's Advanced settings opens. The canvas reads them again when it comes back.+ */+class SettingsActivity : ComponentActivity() {+ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ val prefs = getSharedPreferences("interface", Context.MODE_PRIVATE)+ setContent { SettingsScreen(prefs) { finish() } }+ }+}++private val Back = Color(0xFF000000)+private val Group = Color(0xFF1C1C1E)+private val Ink = Color(0xFFFFFFFF)+private val Dim = Color(0xFF8E8E93)+private val Line = Color(0xFF38383A)+private val Blue = Color(0xFF0A84FF)++/** A row of the page. */+private sealed class Setting++/** A switch: its key in the preferences, its name, what it does, and where it starts. */+private class Toggle(val key: String, val label: String, val detail: String, val default: Boolean) : Setting()++/** A slider from [min] to [max]. */+private class Amount(val key: String, val detail: String, val min: Float, val max: Float, val default: Float) : Setting()++/** One of [options] (kept by its index). */+private class Choice(val key: String, val label: String, val options: List<String>, val default: Int) : Setting()++/** The groups of rows, each with its heading (none for "") */+private val Groups: List<Pair<String, List<Setting>>> = listOf(+ "" to listOf(+ Toggle(CanvasViewModel.ORIENTATION_MEMORY, "Canvas Orientation Memory", "An artwork opens zoomed and turned as it was left.", true),+ Toggle(CanvasViewModel.FIT_INSIDE, "Fit Canvas Inside Interface", "A fitted canvas keeps clear of the top bar and the sidebar.", false),+ ),+ "" to listOf(+ Toggle(CanvasViewModel.NO_TIME_LAPSE, "Disable Time-lapse", "New artworks don't record their time-lapse.", false),+ Toggle(CanvasViewModel.SIMPLIFIED_UNDOS, "Simplified Undos", "Strokes made in an adjustment undo together once it is left.", true),+ ),+ "Maximum Speed Distance" to listOf(+ Amount(CanvasViewModel.SPEED_DISTANCE, "How far the pen moves before a brush's speed dynamics count it as fast.", 0.25f, 1f, 1f),+ ),+ "Drag and Drop export" to listOf(+ Choice(CanvasViewModel.DRAG_FORMAT, "Preferred file format", CanvasViewModel.DRAG_FORMATS, 0),+ Choice(CanvasViewModel.DRAG_IMAGE_FORMAT, "Preferred image format", CanvasViewModel.DRAG_IMAGE_FORMATS, 0),+ ),+ "Accessibility" to listOf(+ Toggle(CanvasViewModel.SINGLE_TOUCH_COMPANION, "Single Touch Gestures Companion", "A floating bar of undo, redo, zoom, move and fit for one finger.", false),+ Toggle(CanvasViewModel.COLOR_NAMES, "Color Description Notifications", "A message names the colour once it stops changing.", false),+ Toggle(CanvasViewModel.FEEDBACK_SOUNDS, "Feedback Sounds", "Undo, redo, tools and panels click as they are used.", false),+ Toggle(+ CanvasViewModel.TAP_ASSISTANCE, "Tap Assistance - Initial Touch Location Support",+ "A tap lands where the finger first touched, even if it drifts before lifting.", false,+ ),+ ),+)++@Composable+private fun SettingsScreen(prefs: android.content.SharedPreferences, onDone: () -> Unit) {+ var licences by remember { mutableStateOf(false) }+ if (licences) return Licences { licences = false }+ Box(Modifier.fillMaxSize().background(Back).safeDrawingPadding(), contentAlignment = Alignment.TopCenter) {+ Column(Modifier.widthIn(max = 640.dp).fillMaxWidth().verticalScroll(rememberScrollState()).padding(24.dp)) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text("ProCraft", color = Ink, fontSize = 30.sp, fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f))+ Text("Done", color = Blue, fontSize = 17.sp, modifier = Modifier.clickable(onClick = onDone).padding(8.dp))+ }+ for ((heading, rows) in Groups) {+ Text(heading.uppercase(), color = Dim, fontSize = 13.sp, modifier = Modifier.padding(start = 16.dp, top = 24.dp, bottom = 6.dp))+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(12.dp)).background(Group)) {+ rows.forEachIndexed { i, s ->+ if (i > 0) Box(Modifier.padding(start = 16.dp).fillMaxWidth().height(1.dp).background(Line))+ when (s) {+ is Toggle -> ToggleRow(prefs, s)+ is Amount -> AmountRow(prefs, s)+ is Choice -> ChoiceRow(prefs, s)+ }+ }+ }+ }+ // the licences of what the app is made with+ Column(Modifier.padding(top = 24.dp).fillMaxWidth().clip(RoundedCornerShape(12.dp)).background(Group)) {+ Row(Modifier.fillMaxWidth().clickable { licences = true }.padding(horizontal = 16.dp, vertical = 14.dp), verticalAlignment = Alignment.CenterVertically) {+ Text("Licenses", color = Ink, fontSize = 17.sp, modifier = Modifier.weight(1f))+ Text("›", color = Dim, fontSize = 20.sp)+ }+ }+ }+ }+}++@Composable+private fun ToggleRow(prefs: android.content.SharedPreferences, s: Toggle) {+ var on by remember { mutableStateOf(prefs.getBoolean(s.key, s.default)) }+ Row(+ Modifier.fillMaxWidth().clickable {+ on = !on+ prefs.edit().putBoolean(s.key, on).apply()+ }.padding(horizontal = 16.dp, vertical = 10.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Column(Modifier.weight(1f)) {+ Text(s.label, color = Ink, fontSize = 17.sp)+ Text(s.detail, color = Dim, fontSize = 13.sp)+ }+ Switch(on, enabled = true)+ }+}++@Composable+private fun AmountRow(prefs: android.content.SharedPreferences, s: Amount) {+ var value by remember { mutableFloatStateOf(prefs.getFloat(s.key, s.default)) }+ Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp)) {+ // a thin track and a round knob; dragged anywhere along it+ val thumb = 14.dp+ Canvas(+ Modifier.fillMaxWidth().height(44.dp).pointerInput(s) {+ val r = thumb.toPx()+ fun at(x: Float) = s.min + ((x - r) / (size.width - 2 * r)).coerceIn(0f, 1f) * (s.max - s.min)+ awaitEachGesture {+ val down = awaitFirstDown()+ value = at(down.position.x)+ drag(down.id) {+ value = at(it.position.x)+ it.consume()+ }+ prefs.edit().putFloat(s.key, value).apply()+ }+ },+ ) {+ val r = thumb.toPx()+ val y = size.height / 2+ val x = r + (size.width - 2 * r) * (value - s.min) / (s.max - s.min)+ drawLine(Line, Offset(r, y), Offset(size.width - r, y), 4.dp.toPx(), StrokeCap.Round)+ drawLine(Blue, Offset(r, y), Offset(x, y), 4.dp.toPx(), StrokeCap.Round)+ drawCircle(Ink, r, Offset(x, y))+ }+ Text(s.detail, color = Dim, fontSize = 13.sp, modifier = Modifier.padding(bottom = 4.dp))+ }+}++@Composable+private fun ChoiceRow(prefs: android.content.SharedPreferences, s: Choice) {+ var chosen by remember { mutableStateOf(prefs.getInt(s.key, s.default).coerceIn(s.options.indices)) }+ var open by remember { mutableStateOf(false) }+ Row(Modifier.fillMaxWidth().clickable { open = true }.padding(horizontal = 16.dp, vertical = 14.dp), verticalAlignment = Alignment.CenterVertically) {+ Text(s.label, color = Ink, fontSize = 17.sp, modifier = Modifier.weight(1f))+ // the menu opens under the value+ Box {+ Text(s.options[chosen], color = Dim, fontSize = 17.sp)+ DropdownMenu(open, { open = false }, containerColor = Group) {+ s.options.forEachIndexed { i, name ->+ DropdownMenuItem(+ text = { Text(name, color = if (i == chosen) Blue else Ink, fontSize = 17.sp) },+ onClick = {+ chosen = i+ prefs.edit().putInt(s.key, i).apply()+ open = false+ },+ )+ }+ }+ }+ }+}++/** The licences of what the app is made with: the interface font's, as it ships with the app. */+@Composable+private fun Licences(onBack: () -> Unit) {+ val context = androidx.compose.ui.platform.LocalContext.current+ val text = remember {+ val inter = runCatching { context.assets.open("fonts/Inter-OFL.txt").bufferedReader().use { it.readText() } }.getOrDefault("")+ "The interface font is Inter, by The Inter Project Authors, under the SIL Open Font License 1.1.\n\n$inter"+ }+ androidx.activity.compose.BackHandler(onBack = onBack)+ Box(Modifier.fillMaxSize().background(Back).safeDrawingPadding(), contentAlignment = Alignment.TopCenter) {+ Column(Modifier.widthIn(max = 640.dp).fillMaxWidth().verticalScroll(rememberScrollState()).padding(24.dp)) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text("‹ Settings", color = Blue, fontSize = 17.sp, modifier = Modifier.clickable(onClick = onBack).padding(vertical = 8.dp))+ }+ Text("Licenses", color = Ink, fontSize = 30.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(top = 8.dp, bottom = 16.dp))+ Text(text, color = Dim, fontSize = 13.sp)+ }+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasSurfaceView.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasSurfaceView.ktnew file mode 100644index 0000000..d92f8e0--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasSurfaceView.kt@@ -0,0 +1,1001 @@+package io.github.artcraftandroid.procraft.canvas++import android.annotation.SuppressLint+import android.content.Context+import android.util.Log+import android.view.MotionEvent+import android.view.Surface+import android.view.SurfaceHolder+import android.view.SurfaceView+import androidx.compose.ui.geometry.Offset+import androidx.input.motionprediction.MotionEventPredictor+import io.github.artcraftandroid.procraft.core.CanvasSession+import io.github.artcraftandroid.procraft.core.MobileException+import io.github.artcraftandroid.procraft.core.PenSample+import io.github.artcraftandroid.procraft.core.ChromaticKind+import io.github.artcraftandroid.procraft.core.PointerKind+import io.github.artcraftandroid.procraft.core.ToolKind+import io.github.artcraftandroid.procraft.core.TransformHandle+import io.github.artcraftandroid.procraft.core.TransformKind+import kotlin.math.PI+import kotlin.math.atan2+import kotlin.math.hypot+import kotlin.math.max+import kotlin.math.pow++/**+ * The canvas: a surface the Rust renderer draws into, and the touch input that drives it.+ *+ * One pen or finger paints. A second finger turns a finger stroke into a gesture (the stroke is+ * dropped): two fingers move, zoom and turn the canvas; a quick tap with two fingers undoes, three+ * redo, four hide or show the controls. Fingers are ignored while the pen draws.+ */+@SuppressLint("ViewConstructor")+class CanvasSurfaceView(context: Context, private val vm: CanvasViewModel) : SurfaceView(context), SurfaceHolder.Callback {+ private var session: CanvasSession? = null+ private var attached = false++ // the window as last given to the session, and the display rotation it was in+ private var windowWidth = 0+ private var windowHeight = 0+ private var windowRotation = Surface.ROTATION_0++ /** Predicts where the pen is going, so the stroke can be drawn ahead of the latest input. */+ private val predictor = MotionEventPredictor.newInstance(this)++ // IDLE: a finger that doesn't paint, waiting for a hold or more fingers; HOVER: fingers+ // setting the brush while the pen hovers+ private enum class Mode { NONE, PEN, FINGER, IDLE, GESTURE, PICK, TRANSFORM, SELECT, ADJUST, PUCK, SHAPE, HOVER }++ /** The pen is hovering over the canvas. */+ private var penHovering = false++ // Hover: where the finger last was, and the two fingers' last spread+ private var hoverX = 0f+ private var hoverSpread = 0f++ /** The tool this stroke uses instead of the chosen one (Gesture controls' Erase or Smudge), if any. */+ private var toolOverride: ToolKind? = null++ /** The chosen tool back after a stroke that used another. */+ // □ + Touch / □ + Pen: the touch that came while □ was held (its pointer id), and what it does+ private var modifyPointer = -1+ private var modifyPurpose: GesturePurpose? = null++ /**+ * A touch on the canvas while □ is held does what □ + Touch (or □ + Pen) is set to; the touch+ * is followed by its pointer id alone, whether it comes as the first or as a further pointer+ * (the finger on □ may be in the same event). False if the event is not one of these.+ */+ private fun modifyTouch(e: MotionEvent, s: CanvasSession): Boolean {+ if (modifyPointer == -1) {+ val starts = e.actionMasked == MotionEvent.ACTION_DOWN || (e.actionMasked == MotionEvent.ACTION_POINTER_DOWN && mode == Mode.NONE)+ if (!starts || !vm.modifyHeld) return false+ val i = e.actionIndex+ val kind = kindOf(e, i)+ val pen = kind == PointerKind.STYLUS || kind == PointerKind.STYLUS_ERASER+ val purpose = vm.gestures.purposeOf(if (pen) Trigger.MODIFY_PEN else Trigger.MODIFY_TOUCH) ?: return false+ vm.useModify()+ vm.endQuickShape()+ modifyPointer = e.getPointerId(i)+ modifyPurpose = purpose+ val at = Offset(e.getX(i), e.getY(i))+ when (purpose) {+ GesturePurpose.EYEDROPPER -> vm.pickAt(at.x, at.y, pickSide)+ GesturePurpose.QUICKMENU -> vm.toggleQuickMenu(at)+ GesturePurpose.COPY_PASTE -> vm.copyPasteOpen = true+ GesturePurpose.LAYER_SELECT -> vm.layerSelectAt(at)+ GesturePurpose.SMUDGE, GesturePurpose.ERASE, GesturePurpose.ASSISTED -> {+ requestUnbufferedDispatch(e)+ toolOverride = when (purpose) {+ GesturePurpose.ERASE -> ToolKind.ERASE+ GesturePurpose.SMUDGE -> ToolKind.SMUDGE+ else -> null+ }+ toolOverride?.let { s.setTool(it) }+ if (purpose == GesturePurpose.ASSISTED) s.setStrokeAssist(true)+ if (vm.currentIsText()) vm.askRasterize = true+ s.strokeBegin(kind, samples(e, i))+ }+ else -> Unit+ }+ return true+ }+ val i = e.findPointerIndex(modifyPointer)+ val stroke = modifyPurpose == GesturePurpose.SMUDGE || modifyPurpose == GesturePurpose.ERASE || modifyPurpose == GesturePurpose.ASSISTED+ when (e.actionMasked) {+ MotionEvent.ACTION_MOVE -> if (i >= 0) {+ if (modifyPurpose == GesturePurpose.EYEDROPPER) vm.pickAt(e.getX(i), e.getY(i), pickSide)+ if (stroke) s.strokeAdd(samples(e, i))+ }+ MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {+ val ended = e.actionMasked == MotionEvent.ACTION_CANCEL || e.getPointerId(e.actionIndex) == modifyPointer+ if (ended) {+ if (modifyPurpose == GesturePurpose.EYEDROPPER) vm.finishPick()+ if (stroke) {+ if (e.actionMasked == MotionEvent.ACTION_CANCEL) s.strokeCancel() else s.strokeEnd(emptyList())+ s.setStrokeAssist(false)+ restoreTool(s)+ vm.strokeEnded()+ }+ modifyPointer = -1+ modifyPurpose = null+ }+ // the last finger up: the canvas waits for a new touch+ if (e.actionMasked != MotionEvent.ACTION_POINTER_UP) mode = Mode.NONE+ }+ }+ return true+ }++ private fun restoreTool(s: CanvasSession) {+ if (toolOverride != null) s.setTool(vm.tool)+ toolOverride = null+ }++ private val holdMs get() = (vm.gestures.delay(vm.gestures.purposeOf(Trigger.HOLD) ?: GesturePurpose.EYEDROPPER) * 1000).toLong()+ private val quickShapeMs get() = (vm.gestures.delay(GesturePurpose.QUICKSHAPE) * 1000).toLong()+ private val drawAndHold get() = vm.gestures.isOn(GesturePurpose.QUICKSHAPE, "DRAW_HOLD")+ private val undoTaps get() = !vm.gestures.isOn(GesturePurpose.GENERAL, "NO_UNDO")++ private var mode = Mode.NONE+ private var strokePointer = -1+ /** The liquify brush's last place (window pixels), when, and its velocity (pixels a millisecond). */+ private var liquifyAt = Offset.Zero+ private var liquifyTime = 0L+ private var liquifyVelocity = Offset.Zero++ /** Follows the liquify brush's velocity, smoothed over its moves. */+ private fun followLiquify(e: MotionEvent) {+ val dt = (e.eventTime - liquifyTime).toFloat()+ if (dt <= 0f) return+ val now = Offset(e.x, e.y)+ liquifyVelocity = liquifyVelocity * 0.5f + (now - liquifyAt) / dt * 0.5f+ liquifyAt = now+ liquifyTime = e.eventTime+ }++ /** Where the stroke last moved from (window pixels), for QuickShape's hold; the handle being dragged. */+ private var holdAt = Offset.Zero+ private var shapeHandle = -1+ private val quickShapeHold = Runnable {+ if ((mode == Mode.PEN || mode == Mode.FINGER) && drawAndHold) {+ removeCallbacks(holdToPick)+ vm.quickShapeHold()+ }+ }++ // a freehand selection drawn and held still snaps to a shape, which the lift then selects+ private var lassoHoldAt = Offset.Zero+ private var lassoSnapped = false+ private val lassoHold = Runnable {+ if (mode == Mode.SELECT && vm.selectionKind == SelectionKind.FREEHAND && selectMoved && drawAndHold) {+ lassoSnapped = vm.snapFreehand()+ }+ }++ /** A displacing drag has begun. */+ private var chromaDragging = false+ /** Where on the clone source it was taken (window pixels from its centre). */+ private var puckGrab = Offset.Zero++ // the two fingers a gesture follows (pointer ids) and where they were+ private var gestureA = -1+ private var gestureB = -1+ private var lastX = 0f+ private var lastY = 0f+ private var lastDistance = 0f+ private var lastAngle = 0f++ // whether the touches so far still make a tap+ private var tapStart = 0L+ private var tapPointers = 0+ private var tapMoved = 0f+ private val tapSlop = 24f * resources.displayMetrics.density++ // the gesture as a whole: when it began, how far it has zoomed, fingers down now+ private var gestureStart = 0L+ private var gestureScale = 1f+ private var fingers = 0++ // the three-finger scrub that clears the layer: direction changes of the fingers' centre+ private var scrubX = 0f+ private var scrubDirection = 0+ private var scrubTravel = 0f+ private var scrubTurns = 0+ private val scrubStep = 24f * resources.displayMetrics.density++ // while transforming: the handle the touch took, and whether its drag has begun (past the slop)+ private var transformHandle: TransformHandle? = null+ private var transformGrabbed = false+ private val transformSlop = TRANSFORM_SLOP_DP * resources.displayMetrics.density++ // the selection tool's touch: where it went down, and whether it has moved past the slop+ private var selectStart = Offset.Zero+ private var selectMoved = false+ private var lastSelectX = 0f+ private var lastSelectTime = 0L+ private var threshold = 0f++ // where the finger went down, for the hold that opens the eyedropper+ private var downX = 0f+ private var downY = 0f+ private val pickSide get() = (PICK_WINDOW_DP * resources.displayMetrics.density).toInt() or 1++ /** A finger held still on the canvas does what Touch and hold is set to: picks a colour, or clears the layer. */+ private val holdToPick = Runnable {+ val s = session ?: return@Runnable+ if (mode != Mode.FINGER && mode != Mode.IDLE) return@Runnable+ when (vm.gestures.purposeOf(Trigger.HOLD)) {+ GesturePurpose.EYEDROPPER -> {+ if (mode == Mode.FINGER) s.strokeCancel()+ restoreTool(s)+ mode = Mode.PICK+ vm.pickAt(downX, downY, pickSide)+ }+ GesturePurpose.CLEAR_LAYER -> {+ if (mode == Mode.FINGER) s.strokeCancel()+ restoreTool(s)+ mode = Mode.IDLE+ vm.clearCurrentLayer()+ }+ GesturePurpose.QUICKMENU -> {+ if (mode == Mode.FINGER) s.strokeCancel()+ restoreTool(s)+ mode = Mode.IDLE+ vm.toggleQuickMenu(Offset(downX, downY))+ }+ GesturePurpose.LAYER_SELECT -> {+ if (mode == Mode.FINGER) s.strokeCancel()+ restoreTool(s)+ mode = Mode.IDLE+ vm.layerSelectAt(Offset(downX, downY))+ }+ GesturePurpose.COPY_PASTE -> {+ if (mode == Mode.FINGER) s.strokeCancel()+ restoreTool(s)+ mode = Mode.IDLE+ vm.copyPasteOpen = true+ }+ else -> Unit+ }+ }++ /** Holding two fingers still undoes, then keeps undoing; three fingers redo. */+ private val rapidUndo = object : Runnable {+ override fun run() {+ if (mode != Mode.GESTURE || tapMoved > tapSlop || fingers != tapPointers || !undoTaps) return+ when (fingers) {+ 2 -> vm.undo()+ 3 -> vm.redo()+ else -> return+ }+ postDelayed(this, RAPID_REPEAT_MS)+ }+ }++ init {+ holder.addCallback(this)+ }++ override fun surfaceCreated(holder: SurfaceHolder) = Unit++ override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {+ val s = vm.session ?: return+ val rotation = display?.rotation ?: Surface.ROTATION_0+ if (attached && session === s) {+ if (rotation != windowRotation) followTurn(s, windowRotation, rotation)+ s.resizeWindow(width.toUInt(), height.toUInt())+ vm.refreshView()+ remember(width, height, rotation)+ return+ }+ val id = NativeWindows.acquire(holder.surface)+ if (id == 0L) {+ Log.e(TAG, "no native window for the surface")+ return+ }+ try {+ s.attachWindow(id.toULong(), width.toUInt(), height.toUInt())+ s.setDisplayScale(resources.displayMetrics.density)+ session = s+ attached = true+ vm.refreshView()+ remember(width, height, rotation)+ } catch (e: MobileException) {+ NativeWindows.release(id)+ Log.e(TAG, "attaching the window", e)+ }+ }++ private fun remember(width: Int, height: Int, rotation: Int) {+ vm.screenCentre = Offset(width / 2f, height / 2f)+ windowWidth = width+ windowHeight = height+ vm.windowSize = Offset(width.toFloat(), height.toFloat())+ vm.density = resources.displayMetrics.density+ windowRotation = rotation+ }++ /**+ * The display turned from rotation [from] to [to]: the view turns the other way, so the canvas+ * stays where it was on the glass while the bars turn upright.+ */+ private fun followTurn(s: CanvasSession, from: Int, to: Int) {+ // the panel's own size, in its natural orientation+ val (nw, nh) = if (from % 2 == 0) windowWidth.toFloat() to windowHeight.toFloat() else windowHeight.toFloat() to windowWidth.toFloat()+ fun toPanel(r: Int, x: Float, y: Float) = when (r) {+ Surface.ROTATION_90 -> nw - y to x+ Surface.ROTATION_180 -> nw - x to nh - y+ Surface.ROTATION_270 -> y to nh - x+ else -> x to y+ }+ fun fromPanel(r: Int, x: Float, y: Float) = when (r) {+ Surface.ROTATION_90 -> y to nw - x+ Surface.ROTATION_180 -> nw - x to nh - y+ Surface.ROTATION_270 -> nh - y to x+ else -> x to y+ }+ fun map(x: Float, y: Float) = toPanel(from, x, y).let { (px, py) -> fromPanel(to, px, py) }+ val (ox, oy) = map(0f, 0f)+ val (ux, uy) = map(1f, 0f)+ s.viewGesture(0f, 0f, ox, oy, 1f, atan2(uy - oy, ux - ox))+ }++ override fun surfaceDestroyed(holder: SurfaceHolder) {+ // returns once the render thread has stopped drawing into the surface+ session?.detachWindow()+ attached = false+ }++ /** Where the last companion drag sample was, while a one-finger zoom or move goes on. */+ private var companionAt: Offset? = null++ /**+ * With the companion's Zoom or Move on, a single finger dragged on the canvas zooms it (up+ * zooms in, about where it started) or moves it, instead of painting.+ */+ private fun companionTouch(e: MotionEvent, s: CanvasSession): Boolean {+ val mode = vm.companionMode+ if (mode == CanvasViewModel.CompanionMode.NONE && companionAt == null) return false+ when (e.actionMasked) {+ MotionEvent.ACTION_DOWN -> {+ if (mode == CanvasViewModel.CompanionMode.NONE) return false+ companionAt = Offset(e.x, e.y)+ downX = e.x+ downY = e.y+ }+ MotionEvent.ACTION_MOVE -> {+ val last = companionAt ?: return false+ val (dx, dy) = (e.x - last.x) to (e.y - last.y)+ if (mode == CanvasViewModel.CompanionMode.ZOOM) {+ val scale = kotlin.math.exp(-dy / (COMPANION_ZOOM_DP * resources.displayMetrics.density))+ s.viewGesture(downX, downY, 0f, 0f, scale, 0f)+ } else {+ s.viewGesture(e.x, e.y, dx, dy, 1f, 0f)+ }+ companionAt = Offset(e.x, e.y)+ vm.refreshView()+ }+ MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {+ companionAt ?: return false+ companionAt = null+ vm.refreshView()+ }+ else -> return companionAt != null+ }+ return true+ }++ @SuppressLint("ClickableViewAccessibility")+ override fun onTouchEvent(e: MotionEvent): Boolean {+ val s = session ?: return true+ if (penButton(e)) return true+ if (modifyTouch(e, s)) return true+ if (companionTouch(e, s)) return true+ predictor.record(e)+ when (e.actionMasked) {+ MotionEvent.ACTION_DOWN -> {+ // every sample as it arrives, not batched to the frame+ requestUnbufferedDispatch(e)+ fingers = 1+ downX = e.x+ downY = e.y+ if (vm.pickNext) {+ // the modify button was pressed: this touch picks a colour+ mode = Mode.PICK+ vm.pickAt(e.x, e.y, pickSide)+ return true+ }+ tapStart = e.eventTime+ tapPointers = 1+ tapMoved = 0f+ val a = vm.adjustment+ if (a != null) {+ vm.adjustMenuAt = null+ vm.adjustModesOpen = false+ val kind = kindOf(e, 0)+ val pen = kind == PointerKind.STYLUS || kind == PointerKind.STYLUS_ERASER+ if (a == Adjustment.CLONE && vm.onClonePuck(Offset(e.x, e.y))) {+ // the clone source is dragged+ mode = Mode.PUCK+ val puck = vm.clonePuck?.let(vm::canvasToWindow) ?: Offset(e.x, e.y)+ puckGrab = Offset(e.x, e.y) - puck+ return true+ }+ if (a == Adjustment.CLONE || (vm.adjustPencil && pen)) {+ // cloning, and the pen painting an adjustment on, paint (no eyedropper)+ strokePointer = e.getPointerId(0)+ mode = if (pen) Mode.PEN else Mode.FINGER+ if (a == Adjustment.CLONE) vm.cloneStrokeAt(Offset(e.x, e.y), start = true)+ s.strokeBegin(kind, samples(e, 0))+ return true+ }+ // otherwise one pen or finger drags the amount across the canvas (a tap opens the menu); nothing paints+ mode = Mode.ADJUST+ chromaDragging = false+ if (vm.adjustment == Adjustment.LIQUIFY) {+ vm.liquifyPopup = 0+ vm.liquifyStroke(liquifyPoints(e), start = true)+ liquifyVelocity = Offset.Zero+ liquifyAt = Offset(e.x, e.y)+ liquifyTime = e.eventTime+ }+ lastSelectX = e.x+ lastSelectTime = e.eventTime+ return true+ }+ if (vm.selecting) {+ // one pen or finger makes the selection; nothing paints+ mode = Mode.SELECT+ vm.selectionPopup = SelectionPopup.NONE+ selectStart = Offset(e.x, e.y)+ selectMoved = false+ lassoSnapped = false+ lassoHoldAt = selectStart+ lastSelectX = e.x+ lastSelectTime = e.eventTime+ threshold = vm.selectionThreshold+ return true+ }+ if (vm.transforming) {+ // one pen or finger works the box; nothing paints+ mode = Mode.TRANSFORM+ vm.transformPopup = TransformPopup.NONE+ val density = resources.displayMetrics.density+ val box = vm.transformBox+ transformHandle = when {+ box == null -> null+ vm.transformKind == TransformKind.WARP && box.mesh.isNotEmpty() ->+ meshHandleAt(box, vm.viewMatrix, Offset(e.x, e.y), density, vm.advancedMesh)+ else -> boxOnScreen(box, vm.viewMatrix, density)?.let { handleAt(it, Offset(e.x, e.y), density) }+ }+ transformGrabbed = false+ return true+ }+ // a snapped shape's handle is dragged; anything else keeps the shape and draws on+ val handle = vm.quickShapeHandleAt(Offset(e.x, e.y))+ if (handle != null) {+ mode = Mode.SHAPE+ shapeHandle = handle+ return true+ }+ vm.endQuickShape()+ val kind = kindOf(e, 0)+ val pen = kind == PointerKind.STYLUS || kind == PointerKind.STYLUS_ERASER+ // Hover: with the pen held over the canvas, a finger drags the opacity and a pinch the size+ if (!pen && penHovering && vm.gestures.isOn(GesturePurpose.HOVER, "HOVER_TOUCH")) {+ mode = Mode.HOVER+ hoverX = e.x+ return true+ }+ val gestures = vm.gestures+ // what this kind of touch is set to do in Gesture controls+ val touchDoes = gestures.purposeOf(if (pen) Trigger.PEN else Trigger.TOUCH)+ if (!pen && touchDoes == GesturePurpose.EYEDROPPER) {+ mode = Mode.PICK+ vm.pickAt(e.x, e.y, pickSide)+ return true+ }+ // a finger set to open a menu or show the interface does that instead of painting+ when (touchDoes.takeIf { !pen }) {+ GesturePurpose.QUICKMENU -> {+ mode = Mode.IDLE+ vm.toggleQuickMenu(Offset(e.x, e.y))+ return true+ }+ GesturePurpose.COPY_PASTE -> {+ mode = Mode.IDLE+ vm.copyPasteOpen = true+ return true+ }+ GesturePurpose.FULL_SCREEN -> {+ mode = Mode.IDLE+ vm.toggleBars()+ return true+ }+ GesturePurpose.LAYER_SELECT -> {+ mode = Mode.IDLE+ vm.layerSelectAt(Offset(e.x, e.y))+ return true+ }+ GesturePurpose.QUICKSHAPE -> {+ mode = Mode.IDLE+ vm.quickShapeLast()+ return true+ }+ else -> Unit+ }+ if (!pen && touchDoes == null && !gestures.isOn(GesturePurpose.GENERAL, "FINGER_PAINT")) {+ mode = Mode.IDLE+ if (gestures.purposeOf(Trigger.HOLD) != null) postDelayed(holdToPick, holdMs)+ return true+ }+ strokePointer = e.getPointerId(0)+ mode = if (pen) Mode.PEN else Mode.FINGER+ toolOverride = when (touchDoes) {+ GesturePurpose.ERASE -> ToolKind.ERASE+ GesturePurpose.SMUDGE -> ToolKind.SMUDGE+ else -> null+ }+ toolOverride?.let { s.setTool(it) }+ // a text layer takes no paint until it is rasterized+ if (vm.currentIsText()) vm.askRasterize = true+ s.strokeBegin(kind, samples(e, 0))+ vm.showCursor(Offset(e.x, e.y))+ if (mode == Mode.FINGER && gestures.purposeOf(Trigger.HOLD) != null) postDelayed(holdToPick, holdMs)+ holdAt = Offset(e.x, e.y)+ if (drawAndHold) postDelayed(quickShapeHold, quickShapeMs)+ }+ MotionEvent.ACTION_POINTER_DOWN -> {+ fingers = e.pointerCount+ if (mode == Mode.HOVER) {+ if (e.pointerCount >= 2) hoverSpread = hypot(e.getX(1) - e.getX(0), e.getY(1) - e.getY(0))+ return true+ }+ removeCallbacks(holdToPick)+ removeCallbacks(quickShapeHold)+ if (mode == Mode.PEN || mode == Mode.PICK) return true+ vm.showCursor(null)+ if (mode == Mode.FINGER) s.strokeCancel()+ restoreTool(s)+ if (mode == Mode.TRANSFORM && transformGrabbed) vm.transformMoved(s.transformCancelDrag())+ vm.transformHeld = null+ if (mode == Mode.SELECT) {+ vm.shapeDrag = null+ vm.thresholdDrag?.let { (p, t) -> vm.selectByColour(p, t, live = false) }+ }+ if (mode == Mode.FINGER || mode == Mode.IDLE || mode == Mode.TRANSFORM || mode == Mode.SELECT) {+ gestureStart = e.eventTime+ gestureScale = 1f+ }+ mode = Mode.GESTURE+ tapPointers = max(tapPointers, e.pointerCount)+ followFingers(e, exclude = -1)+ if (fingers == 3) {+ startScrub(e)+ if (!vm.gestures.isOn(GesturePurpose.CLEAR_LAYER, Trigger.SCRUB)) scrubTurns = -1+ }+ removeCallbacks(rapidUndo)+ postDelayed(rapidUndo, (vm.rapidUndoDelay * 1000).toLong())+ }+ MotionEvent.ACTION_MOVE -> when (mode) {+ Mode.PEN, Mode.FINGER -> {+ val i = e.findPointerIndex(strokePointer)+ if (i >= 0) {+ if (mode == Mode.FINGER && hypot(e.getX(i) - downX, e.getY(i) - downY) > tapSlop) removeCallbacks(holdToPick)+ if (vm.adjustment == Adjustment.CLONE) vm.cloneStrokeAt(Offset(e.getX(i), e.getY(i)), start = false)+ // moving on restarts the wait for a hold+ if (hypot(e.getX(i) - holdAt.x, e.getY(i) - holdAt.y) > CanvasViewModel.QUICKSHAPE_STILL_DP * resources.displayMetrics.density) {+ holdAt = Offset(e.getX(i), e.getY(i))+ removeCallbacks(quickShapeHold)+ if (vm.quickShape == null && drawAndHold) postDelayed(quickShapeHold, quickShapeMs)+ }+ s.strokeAdd(samples(e, i))+ vm.showCursor(Offset(e.getX(i), e.getY(i)))+ predict(s)+ }+ }+ Mode.PICK -> vm.pickAt(e.x, e.y, pickSide)+ Mode.IDLE -> if (hypot(e.x - downX, e.y - downY) > tapSlop) removeCallbacks(holdToPick)+ Mode.HOVER -> hoverAdjust(e)+ Mode.PUCK -> vm.moveClonePuck(Offset(e.x, e.y) - puckGrab)+ Mode.SHAPE -> vm.moveQuickShapeHandle(shapeHandle, Offset(e.x, e.y))+ Mode.GESTURE -> if (fingers >= 3) scrub(e) else moveGesture(e, s)+ Mode.SELECT -> select(e, done = false)+ Mode.ADJUST -> if (vm.adjustment == Adjustment.LIQUIFY) {+ vm.liquifyStroke(liquifyPoints(e), start = false)+ followLiquify(e)+ } else if (vm.adjustment == Adjustment.MOTION_BLUR) {+ // a motion blur follows the drag: along it, longer the further it goes+ vm.dragMotionBlur(e.x - downX, e.y - downY)+ } else if (vm.adjustment == Adjustment.CHROMATIC_ABERRATION && vm.chromaKind == ChromaticKind.DISPLACE) {+ // displacing, the drag moves the fringes+ vm.dragChromatic(Offset(e.x - downX, e.y - downY), start = !chromaDragging)+ chromaDragging = true+ } else if (vm.adjustment?.swiped == true) {+ // across the canvas the amount follows the drag, faster the faster it goes+ val dx = (e.x - lastSelectX) / resources.displayMetrics.density+ vm.changeAdjustAmount(dragStep(dx, e.eventTime - lastSelectTime))+ lastSelectX = e.x+ lastSelectTime = e.eventTime+ }+ Mode.TRANSFORM -> transformHandle?.let { handle ->+ if (!transformGrabbed && hypot(e.x - downX, e.y - downY) > transformSlop) {+ // the drag counts from where it was recognised, as the slop is used up+ s.transformGrab(handle, e.x, e.y)+ transformGrabbed = true+ }+ if (transformGrabbed) {+ vm.transformMoved(s.transformDrag(e.x, e.y))+ vm.transformHeld = handle to Offset(e.x, e.y)+ }+ }+ Mode.NONE -> Unit+ }+ MotionEvent.ACTION_POINTER_UP -> {+ fingers = e.pointerCount - 1+ if (mode == Mode.GESTURE) followFingers(e, exclude = e.actionIndex)+ }+ MotionEvent.ACTION_UP -> {+ vm.showCursor(null)+ when (mode) {+ Mode.PEN, Mode.FINGER -> {+ val i = e.findPointerIndex(strokePointer)+ s.strokeEnd(if (i >= 0) samples(e, i) else emptyList())+ restoreTool(s)+ vm.strokeEnded()+ }+ Mode.GESTURE -> if (e.eventTime - tapStart <= TAP_MS && tapMoved <= tapSlop) {+ when (tapPointers) {+ 2 -> if (undoTaps) vm.undo()+ 3 -> if (undoTaps) vm.redo()+ 4 -> when (vm.gestures.purposeOf(Trigger.FOUR_TAP)) {+ GesturePurpose.FULL_SCREEN -> vm.toggleBars()+ GesturePurpose.CLEAR_LAYER -> vm.clearCurrentLayer()+ // in the middle of the screen, not under the fingers+ GesturePurpose.QUICKMENU -> vm.toggleQuickMenu(vm.screenCentre)+ GesturePurpose.COPY_PASTE -> vm.copyPasteOpen = true+ GesturePurpose.QUICKSHAPE -> vm.quickShapeLast()+ else -> Unit+ }+ }+ } else if (tapPointers == 2 && e.eventTime - gestureStart <= QUICK_PINCH_MS && gestureScale < QUICK_PINCH_SCALE) {+ // a quick pinch in fits the canvas to the screen, settling into place+ vm.settleToFit()+ }+ Mode.PICK -> vm.finishPick()+ Mode.PUCK, Mode.SHAPE, Mode.IDLE, Mode.HOVER -> Unit+ Mode.SELECT -> select(e, done = true)+ Mode.ADJUST -> if (vm.adjustment == Adjustment.LIQUIFY) {+ // still moving when it lifts, liquify carries on+ if (e.eventTime - liquifyTime <= LIQUIFY_STILL_MS) vm.liquifyLifted(liquifyVelocity.x, liquifyVelocity.y)+ } else if (e.eventTime - tapStart <= TAP_MS && hypot(e.x - downX, e.y - downY) <= tapSlop) {+ vm.adjustMenuAt = Offset(e.x, e.y)+ }+ Mode.TRANSFORM -> if (transformGrabbed) {+ vm.transformMoved(s.transformRelease())+ val handle = transformHandle+ if (handle == TransformHandle.Rotate || handle == TransformHandle.TurnBox) vm.transformLetGo = handle to Offset(e.x, e.y)+ vm.transformHeld = null+ } else if (transformHandle == TransformHandle.Move && e.eventTime - tapStart <= TAP_MS) {+ // a tap off the nodes nudges the content a pixel towards it+ vm.transformMoved(s.transformNudge(e.x, e.y))+ } else if (e.eventTime - tapStart <= TAP_MS) {+ // a tap on a node types its numbers: the rotation handle its angle, the others the size+ when (transformHandle) {+ TransformHandle.Rotate -> vm.transformNumeric = CanvasViewModel.TransformNumeric(true, Offset(downX, downY))+ is TransformHandle.Corner, is TransformHandle.Edge -> vm.transformNumeric = CanvasViewModel.TransformNumeric(false, Offset(downX, downY))+ else -> Unit+ }+ }+ Mode.NONE -> Unit+ }+ mode = Mode.NONE+ transformGrabbed = false+ fingers = 0+ removeCallbacks(rapidUndo)+ removeCallbacks(holdToPick)+ removeCallbacks(quickShapeHold)+ }+ MotionEvent.ACTION_CANCEL -> {+ vm.showCursor(null)+ if (mode == Mode.PEN || mode == Mode.FINGER) s.strokeCancel()+ restoreTool(s)+ if (mode == Mode.PICK) vm.cancelPick()+ if (mode == Mode.TRANSFORM && transformGrabbed) vm.transformMoved(s.transformCancelDrag())+ vm.transformHeld = null+ transformGrabbed = false+ mode = Mode.NONE+ fingers = 0+ removeCallbacks(rapidUndo)+ removeCallbacks(holdToPick)+ }+ }+ return true+ }++ /** The pen's side buttons, hovering or touching: what Pen double-tap or squeeze is set to do. */+ private fun penButton(e: MotionEvent): Boolean {+ if (e.actionMasked != MotionEvent.ACTION_BUTTON_PRESS) return false+ when (e.actionButton) {+ MotionEvent.BUTTON_STYLUS_PRIMARY -> vm.penButton(secondary = false, Offset(e.x, e.y))+ MotionEvent.BUTTON_STYLUS_SECONDARY -> vm.penButton(secondary = true, Offset(e.x, e.y))+ else -> return false+ }+ return true+ }++ override fun onGenericMotionEvent(e: MotionEvent): Boolean = penButton(e) || super.onGenericMotionEvent(e)++ /** The pen hovering over the canvas shows the brush cursor where it would paint. */+ override fun onHoverEvent(e: MotionEvent): Boolean {+ if (penButton(e)) return true+ if (e.getToolType(0) != MotionEvent.TOOL_TYPE_STYLUS || mode != Mode.NONE) return super.onHoverEvent(e)+ when (e.actionMasked) {+ MotionEvent.ACTION_HOVER_ENTER, MotionEvent.ACTION_HOVER_MOVE -> {+ penHovering = true+ if (painting()) vm.showCursor(Offset(e.x, e.y), hovering = true)+ }+ MotionEvent.ACTION_HOVER_EXIT -> {+ penHovering = false+ vm.showCursor(null)+ }+ }+ return true+ }++ /** Hover: one finger across the screen moves the opacity; two pinching change the size. */+ private fun hoverAdjust(e: MotionEvent) {+ if (e.pointerCount >= 2) {+ val spread = hypot(e.getX(1) - e.getX(0), e.getY(1) - e.getY(0))+ if (hoverSpread > 1f && spread > 1f) vm.changeSize((vm.size * spread / hoverSpread).coerceIn(0f, 1f))+ hoverSpread = spread+ } else {+ val dx = (e.x - hoverX) / width.coerceAtLeast(1)+ vm.changeOpacity((vm.opacity + dx).coerceIn(0f, 1f))+ hoverX = e.x+ }+ }++ /** Whether a pen on the canvas now would paint (no tool of another kind open). */+ private fun painting() = vm.adjustment == null && !vm.selecting && !vm.transforming++ /**+ * A step of the selection tool's touch: a rectangle or ellipse dragged out; a freehand path drawn+ * (or tapped point by point, closed by a tap on its first point); a colour picked by a tap, its+ * threshold dragged left and right.+ */+ private fun select(e: MotionEvent, done: Boolean) {+ val start = selectStart+ val p = Offset(e.x, e.y)+ val density = resources.displayMetrics.density+ if ((p - start).getDistance() > transformSlop) selectMoved = true+ when (vm.selectionKind) {+ SelectionKind.RECTANGLE, SelectionKind.ELLIPSE -> {+ if (done) vm.selectShape(start, p) else if (selectMoved) vm.shapeDrag = start to p+ }+ SelectionKind.FREEHAND -> {+ // snapped: the shape is kept as it is, and the lift selects it+ if (lassoSnapped) {+ if (done) {+ lassoSnapped = false+ vm.closeFreehand()+ }+ return+ }+ if (done) {+ removeCallbacks(lassoHold)+ } else if (selectMoved && (p - lassoHoldAt).getDistance() > CanvasViewModel.QUICKSHAPE_STILL_DP * density) {+ // still for the QuickShape delay, it snaps+ lassoHoldAt = p+ removeCallbacks(lassoHold)+ postDelayed(lassoHold, quickShapeMs)+ }+ val last = vm.freehand.lastOrNull()?.let { vm.canvasToWindow(it) }+ if (done && !selectMoved) {+ vm.freehandPoint(p, FREEHAND_CLOSE_DP * density)+ } else if (selectMoved && (last == null || (p - last).getDistance() >= FREEHAND_STEP_DP * density)) {+ if (last == null) vm.freehandPoint(start, 0f)+ vm.freehandPoint(p, 0f)+ }+ }+ SelectionKind.AUTOMATIC -> {+ // across the screen the threshold follows the drag, faster the faster it goes+ val dx = (p.x - lastSelectX) / density+ threshold = (threshold + dragStep(dx, e.eventTime - lastSelectTime)).coerceIn(0f, 1f)+ lastSelectX = p.x+ lastSelectTime = e.eventTime+ if (done) vm.selectByColour(start, threshold, live = false)+ else if (selectMoved) vm.selectByColour(start, threshold, live = true)+ }+ }+ }++ /**+ * How much an amount dragged across the screen changes for a step of [dx] points over [ms]: more+ * for faster drags (the speed taken per 60 Hz frame), 200 points at a steady pace moving it most+ * of the way.+ */+ private fun dragStep(dx: Float, ms: Long): Float {+ val frames = (ms.coerceAtLeast(1L) / 1000f * 60f).coerceAtLeast(0.06f)+ val speed = kotlin.math.abs(dx) / frames+ return (speed / 30f).toDouble().pow(0.86).toFloat() * dx / 200f+ }++ /** The first pointer's samples in this event as (x, y, pressure), for liquify. */+ private fun liquifyPoints(e: MotionEvent): List<Float> {+ val out = ArrayList<Float>((e.historySize + 1) * 3)+ for (h in 0 until e.historySize) {+ out += e.getHistoricalX(0, h)+ out += e.getHistoricalY(0, h)+ out += if (e.getToolType(0) == MotionEvent.TOOL_TYPE_STYLUS) e.getHistoricalPressure(0, h) else 1f+ }+ out += e.getX(0)+ out += e.getY(0)+ out += if (e.getToolType(0) == MotionEvent.TOOL_TYPE_STYLUS) e.getPressure(0) else 1f+ return out+ }++ /** Draws the predicted next samples of the stroke ahead of it (replaced at the next input). */+ private fun predict(s: CanvasSession) {+ val p = predictor.predict() ?: return+ try {+ val i = p.findPointerIndex(strokePointer)+ if (i >= 0) s.strokePredict(samples(p, i))+ } finally {+ p.recycle()+ }+ }++ /** Starts following the first two fingers other than the one at [exclude]. */+ private fun startScrub(e: MotionEvent) {+ swipeStartY = centreY(e)+ swipeStartX = centreX(e)+ swiped = false+ scrubX = centreX(e)+ scrubDirection = 0+ scrubTravel = 0f+ scrubTurns = 0+ }++ /** Three fingers rubbed back and forth (three turns) clear the current layer, once per gesture. */+ private fun scrub(e: MotionEvent) {+ threeFingerSwipe(e)+ val x = centreX(e)+ val dx = x - scrubX+ scrubX = x+ tapMoved += kotlin.math.abs(dx)+ if (dx == 0f || scrubTurns < 0) return+ val direction = if (dx > 0f) 1 else -1+ if (direction != scrubDirection) {+ if (scrubDirection != 0 && scrubTravel >= scrubStep) scrubTurns+++ scrubDirection = direction+ scrubTravel = 0f+ }+ scrubTravel += kotlin.math.abs(dx)+ if (scrubTurns >= SCRUB_TURNS) {+ scrubTurns = -1+ vm.clearCurrentLayer()+ }+ }++ // three fingers swiped down: where they started, and whether it has done its thing+ private var swipeStartX = 0f+ private var swipeStartY = 0f+ private var swiped = false++ /** Three fingers swiped down (mostly straight) do what Three-finger swipe is set to, once. */+ private fun threeFingerSwipe(e: MotionEvent) {+ if (swiped || e.pointerCount != 3) return+ val dy = centreY(e) - swipeStartY+ val dx = centreX(e) - swipeStartX+ if (dy < SWIPE_DOWN_DP * resources.displayMetrics.density || kotlin.math.abs(dx) > dy / 2f) return+ swiped = true+ scrubTurns = -1+ when (vm.gestures.purposeOf(Trigger.THREE_SWIPE)) {+ GesturePurpose.COPY_PASTE -> vm.copyPasteOpen = true+ GesturePurpose.FULL_SCREEN -> vm.toggleBars()+ GesturePurpose.CLEAR_LAYER -> vm.clearCurrentLayer()+ GesturePurpose.QUICKMENU -> vm.toggleQuickMenu(Offset(centreX(e), centreY(e)))+ GesturePurpose.QUICKSHAPE -> vm.quickShapeLast()+ else -> Unit+ }+ }++ private fun centreY(e: MotionEvent): Float = (0 until e.pointerCount).sumOf { e.getY(it).toDouble() }.toFloat() / e.pointerCount++ private fun centreX(e: MotionEvent): Float = (0 until e.pointerCount).sumOf { e.getX(it).toDouble() }.toFloat() / e.pointerCount++ private fun followFingers(e: MotionEvent, exclude: Int) {+ val picked = (0 until e.pointerCount).filter { it != exclude }.take(2)+ if (picked.size < 2) {+ gestureA = -1+ gestureB = -1+ return+ }+ gestureA = e.getPointerId(picked[0])+ gestureB = e.getPointerId(picked[1])+ val (x, y, d, a) = pair(e, picked[0], picked[1])+ lastX = x+ lastY = y+ lastDistance = d+ lastAngle = a+ }++ private fun moveGesture(e: MotionEvent, s: CanvasSession) {+ val ia = e.findPointerIndex(gestureA)+ val ib = e.findPointerIndex(gestureB)+ if (ia < 0 || ib < 0) return+ val (x, y, d, a) = pair(e, ia, ib)+ val scale = if (lastDistance > 1f && d > 1f) d / lastDistance else 1f+ var turn = a - lastAngle+ if (turn > PI) turn -= (2 * PI).toFloat()+ if (turn < -PI) turn += (2 * PI).toFloat()+ if (!vm.gestures.isOn(GesturePurpose.GENERAL, "ROTATE")) turn = 0f+ tapMoved += hypot(x - lastX, y - lastY) + kotlin.math.abs(d - lastDistance)+ gestureScale *= scale+ s.viewGesture(lastX, lastY, x - lastX, y - lastY, scale, turn)+ vm.refreshView()+ lastX = x+ lastY = y+ lastDistance = d+ lastAngle = a+ }++ /** Centre, distance and angle of two fingers. */+ private fun pair(e: MotionEvent, a: Int, b: Int): FloatArray {+ val (ax, ay, bx, by) = floatArrayOf(e.getX(a), e.getY(a), e.getX(b), e.getY(b))+ return floatArrayOf((ax + bx) / 2f, (ay + by) / 2f, hypot(bx - ax, by - ay), atan2(by - ay, bx - ax))+ }++ private fun kindOf(e: MotionEvent, index: Int): PointerKind = when (e.getToolType(index)) {+ MotionEvent.TOOL_TYPE_STYLUS -> PointerKind.STYLUS+ MotionEvent.TOOL_TYPE_ERASER -> PointerKind.STYLUS_ERASER+ MotionEvent.TOOL_TYPE_MOUSE -> PointerKind.MOUSE+ else -> PointerKind.FINGER+ }++ /** The pointer's samples in this event: the batched ones since the last event, then the latest. */+ private fun samples(e: MotionEvent, i: Int): List<PenSample> {+ val out = ArrayList<PenSample>(e.historySize + 1)+ for (h in 0 until e.historySize) {+ out += PenSample(+ e.getHistoricalX(i, h),+ e.getHistoricalY(i, h),+ e.getHistoricalPressure(i, h),+ e.getHistoricalAxisValue(MotionEvent.AXIS_TILT, i, h),+ e.getHistoricalOrientation(i, h),+ e.getHistoricalEventTime(h).toDouble(),+ )+ }+ out += PenSample(e.getX(i), e.getY(i), e.getPressure(i), e.getAxisValue(MotionEvent.AXIS_TILT, i), e.getOrientation(i), e.eventTime.toDouble())+ return out+ }++ private companion object {+ /** Lifted after holding still this long (milliseconds), liquify does not carry on. */+ private const val LIQUIFY_STILL_MS = 60L+ const val TAG = "ProCraft"+ const val TAP_MS = 300L+ const val RAPID_UNDO_DELAY_MS = 650L+ const val RAPID_REPEAT_MS = 120L+ const val QUICK_PINCH_MS = 400L+ /** How far (dp) a companion zoom drag goes for the canvas to grow e times. */+ const val COMPANION_ZOOM_DP = 180f+ const val QUICK_PINCH_SCALE = 0.75f+ const val SCRUB_TURNS = 3+ /** How far three fingers go down to count as a swipe, dp. */+ const val SWIPE_DOWN_DP = 70f++ /** A tap this near a freehand path's first point closes it; points are added this far apart (dp). */+ const val FREEHAND_CLOSE_DP = 22f+ const val FREEHAND_STEP_DP = 2f++ /** How far a touch on the transform box moves before its drag begins (dp); the drag counts from there. */+ const val TRANSFORM_SLOP_DP = 15f++ /** The window the eyedropper shows (magnified twice), dp across. */+ const val PICK_WINDOW_DP = 54f+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasViewModel.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasViewModel.ktnew file mode 100644index 0000000..3e935df--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasViewModel.kt@@ -0,0 +1,4747 @@+package io.github.artcraftandroid.procraft.canvas++import io.github.artcraftandroid.procraft.ui.CanvasSpace+import android.app.Application+import android.graphics.Bitmap+import android.graphics.BitmapFactory+import android.util.Log+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableStateMapOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.graphics.asAndroidBitmap+import androidx.compose.ui.graphics.asImageBitmap+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import io.github.artcraftandroid.procraft.gallery.Artwork+import io.github.artcraftandroid.procraft.gallery.ArtworkStore+import io.github.artcraftandroid.procraft.gallery.CanvasPreset+import io.github.artcraftandroid.procraft.core.BackgroundInfo+import io.github.artcraftandroid.procraft.core.BlendModeInfo+import io.github.artcraftandroid.procraft.ui.GradientPreset+import io.github.artcraftandroid.procraft.ui.gradientColorAt+import io.github.artcraftandroid.procraft.core.BrushInfo+import io.github.artcraftandroid.procraft.core.BrushSetInfo+import io.github.artcraftandroid.procraft.core.CanvasSession+import io.github.artcraftandroid.procraft.core.ChromaticKind+import io.github.artcraftandroid.procraft.core.GlitchKind+import io.github.artcraftandroid.procraft.core.GuideInfo+import io.github.artcraftandroid.procraft.core.GuideType+import io.github.artcraftandroid.procraft.core.SymmetryType+import io.github.artcraftandroid.procraft.core.HalftoneKind+import io.github.artcraftandroid.procraft.core.NoiseKind+import io.github.artcraftandroid.procraft.core.QuickShapeInfo+import io.github.artcraftandroid.procraft.core.QuickShapeKind+import io.github.artcraftandroid.procraft.core.GuideSettings+import io.github.artcraftandroid.procraft.core.Interpolation+import io.github.artcraftandroid.procraft.core.LayerInfo+import io.github.artcraftandroid.procraft.core.TextAlignment+import io.github.artcraftandroid.procraft.core.TextInfo+import io.github.artcraftandroid.procraft.core.LayerType+import io.github.artcraftandroid.procraft.core.MobileException+import io.github.artcraftandroid.procraft.core.SelectionDisplay+import io.github.artcraftandroid.procraft.core.SelectionJoin+import io.github.artcraftandroid.procraft.core.SwipeAdjustment+import io.github.artcraftandroid.procraft.core.LiquifyBrush+import io.github.artcraftandroid.procraft.core.LiquifyKind+import io.github.artcraftandroid.procraft.core.ToolKind+import io.github.artcraftandroid.procraft.core.TransformAction+import io.github.artcraftandroid.procraft.core.TransformBox+import io.github.artcraftandroid.procraft.core.TransformHandle+import io.github.artcraftandroid.procraft.core.TransformKind+import io.github.artcraftandroid.procraft.gallery.PALETTE_SLOTS+import io.github.artcraftandroid.procraft.gallery.Palette+import io.github.artcraftandroid.procraft.gallery.PaletteStore+import io.github.artcraftandroid.procraft.gallery.StandardPresets+import io.github.artcraftandroid.procraft.core.blendModes+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlin.math.abs+import kotlin.math.roundToInt+import androidx.compose.ui.text.TextRange+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.DpSize+import androidx.compose.ui.unit.dp+import androidx.compose.ui.text.input.TextFieldValue+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import java.io.File+import java.nio.ByteBuffer++/** Which panel is open over the canvas. */+private const val TAG = "ProCraft"++enum class Panel { NONE, LAYERS, COLOR, BRUSHES, ACTIONS, ADJUSTMENTS }++/** The eyedropper while it is open: the window point (pixels), what is shown around it, the colour it would pick. */+class PickState(val x: Float, val y: Float, val image: ImageBitmap?, val rgb: Int?)++/** The colour panel's ways of choosing a colour. */+enum class ColorMode { DISC, CLASSIC, HARMONY, VALUE, PALETTES }++/** Companion colours in the harmony mode, as hue turns (degrees) from the chosen colour. */+enum class HarmonyKind(val label: String, val turns: List<Float>) {+ COMPLEMENTARY("Complementary", listOf(180f)),+ SPLIT_COMPLEMENTARY("Split Complementary", listOf(150f, 210f)),+ ANALOGOUS("Analogous", listOf(30f, -30f)),+ TRIADIC("Triadic", listOf(120f, 240f)),+ TETRADIC("Tetradic", listOf(90f, 180f, 270f)),+}++/** The gallery of artworks, or one artwork open on the canvas. */+enum class Screen { GALLERY, CANVAS }++/** A popover over the transform toolbar. */+enum class TransformPopup { NONE, SNAPPING, INTERPOLATION }++/**+ * The adjustments, in the menu's order; [ready] once made, [swiped] for those whose one amount is+ * dragged across the canvas.+ */+/**+ * An adjustment: [swiped] ones have one amount dragged across the canvas, which painting it on+ * ([paintable], Pencil) starts at [pencilAmount] (null: as it was).+ */+enum class Adjustment(val label: String, val ready: Boolean = false, val swiped: Boolean = false, val pencilAmount: Float? = null) {+ HSB("Hue, Saturation, Brightness", ready = true),+ COLOR_BALANCE("Color Balance", ready = true),+ CURVES("Curves", ready = true),+ GRADIENT_MAP("Gradient Map", ready = true, swiped = true),+ GAUSSIAN_BLUR("Gaussian Blur", ready = true, swiped = true, pencilAmount = 0.6f),+ MOTION_BLUR("Motion Blur", ready = true, swiped = true, pencilAmount = 0.6f),+ PERSPECTIVE_BLUR("Perspective Blur", ready = true, swiped = true, pencilAmount = 0.4f),+ NOISE("Noise", ready = true, swiped = true, pencilAmount = 0.69f),+ SHARPEN("Sharpen", ready = true, swiped = true, pencilAmount = 0.4f),+ BLOOM("Bloom", ready = true, swiped = true, pencilAmount = 0.5f),+ GLITCH("Glitch", ready = true, swiped = true, pencilAmount = 0.5f),+ HALFTONE("Halftone", ready = true, swiped = true, pencilAmount = 0.12f),+ CHROMATIC_ABERRATION("Chromatic Aberration", ready = true, swiped = true, pencilAmount = 1f),+ LIQUIFY("Liquify", ready = true),+ CLONE("Clone", ready = true),+ ;++ /** Can be painted on with the brush instead of changing the whole layer. */+ val paintable get() = this != LIQUIFY && this != CLONE++ companion object {+ /** The menu's groups: colour, blurs, effects, painting. */+ val groups = listOf(+ listOf(HSB, COLOR_BALANCE, CURVES, GRADIENT_MAP),+ listOf(GAUSSIAN_BLUR, MOTION_BLUR, PERSPECTIVE_BLUR),+ listOf(NOISE, SHARPEN, BLOOM, GLITCH, HALFTONE, CHROMATIC_ABERRATION),+ listOf(LIQUIFY, CLONE),+ )+ }+}++/** The selection tool's ways of making a selection. */+enum class SelectionKind(val label: String) { AUTOMATIC("Automatic"), FREEHAND("Freehand"), RECTANGLE("Rectangle"), ELLIPSE("Ellipse") }++/** A popover over the selection toolbar. */+enum class SelectionPopup { NONE, FEATHER, SAVED }++/** The gallery, the open artwork and the state of the controls around it; outlives configuration changes. */+class CanvasViewModel(app: Application) : AndroidViewModel(app) {+ var session: CanvasSession? = null+ private set++ /** Frosted panels open over the canvas, for the engine to blur what is behind them. */+ val backdrops = io.github.artcraftandroid.procraft.ui.Backdrops { session?.setBackdrops(it) }++ var screen by mutableStateOf(Screen.GALLERY)+ private set+ val store = ArtworkStore(File(app.filesDir, "artworks"))+ var artworks by mutableStateOf<List<Artwork>>(emptyList())+ private set++ /** What the gallery shows: artworks and stacks (in the stack open, only its artworks). */+ var galleryEntries by mutableStateOf<List<io.github.artcraftandroid.procraft.gallery.GalleryEntry>>(emptyList())+ private set++ /** The stack open in the gallery, if any. */+ var openStack by mutableStateOf<io.github.artcraftandroid.procraft.gallery.Stack?>(null)+ private set++ /** Bumped when artworks are saved, so thumbnails reload. */+ var galleryVersion by mutableStateOf(0)+ private set+ var opening by mutableStateOf(false)+ private set+ var message by mutableStateOf<String?>(null)+ private var artworkDir: File? = null++ var tool by mutableStateOf(ToolKind.PAINT)+ private set+ var size by mutableFloatStateOf(0f)+ private set+ var opacity by mutableFloatStateOf(1f)+ private set++ /** The paint colour as hue (0..1), saturation and brightness. */+ var hue by mutableFloatStateOf(DEFAULT_HUE)+ private set+ var saturation by mutableFloatStateOf(1f)+ private set+ var brightness by mutableFloatStateOf(1f)+ private set++ private var secondaryState by mutableStateOf(0xFFFFFF)++ /**+ * The second colour (0xRRGGBB), beside the current one in the colour panel: swapped with it,+ * and mixed in by brushes whose colour dynamics say so.+ */+ var secondaryRgb: Int+ get() = secondaryState+ private set(v) {+ secondaryState = v+ pushSecondary()+ }++ private fun pushSecondary() {+ val c = secondaryState+ session?.setSecondaryColor(((c shr 16) and 0xFF) / 255f, ((c shr 8) and 0xFF) / 255f, (c and 0xFF) / 255f)+ }++ /** Colours painted with recently (0xRRGGBB), newest first. */+ var history by mutableStateOf<List<Int>>(emptyList())+ private set++ /** Whether the size and opacity side bar shows. */+ var showSideBar by mutableStateOf(true)++ private val interfacePrefs = app.getSharedPreferences("interface", android.content.Context.MODE_PRIVATE)++ /** The colour panel's mode, kept from one session to the next. */+ private var colorModeState by mutableStateOf(ColorMode.entries.getOrElse(interfacePrefs.getInt(COLOR_MODE, ColorMode.DISC.ordinal)) { ColorMode.DISC })+ var colorMode: ColorMode+ get() = colorModeState+ set(mode) {+ colorModeState = mode+ interfacePrefs.edit().putInt(COLOR_MODE, mode.ordinal).apply()+ }++ /** The side bar on the right edge instead of the left. */+ var rightHanded by mutableStateOf(interfacePrefs.getBoolean(RIGHT_HANDED, false))+ private set++ /** How long two fingers are held before undo repeats, seconds. */+ var rapidUndoDelay by mutableStateOf(interfacePrefs.getFloat(RAPID_UNDO_DELAY, 0.65f))+ private set++ /** Brush cursor: the brush's outline where the pen paints or hovers. */+ var brushCursorOn by mutableStateOf(interfacePrefs.getBoolean(BRUSH_CURSOR, true))+ private set++ fun changeBrushCursor(on: Boolean) {+ brushCursorOn = on+ if (!on) cursorAt = null+ interfacePrefs.edit().putBoolean(BRUSH_CURSOR, on).apply()+ }++ /** Where the brush cursor is (window pixels), and its radius there; none while not shown. */+ var cursorAt by mutableStateOf<Offset?>(null)+ var cursorRadius by mutableStateOf(0f)+ private set++ /** The current brush's own outline, used when the cursor's style is per brush: 0 none, 1 contrast, 2 the colour. */+ var cursorOutline by mutableStateOf(1)+ private set++ /** When the brush cursor shows: while the pen hovers, while painting, or both. */+ enum class CursorShows { HOVERING, PAINTING, BOTH }++ /** How it is drawn: light and dark rings, in the colour painted with, or the brush's own grey ring. */+ enum class CursorStyle { CONTRAST, COLOR, BRUSH }++ var cursorShows by mutableStateOf(CursorShows.entries.getOrElse(interfacePrefs.getInt(CURSOR_SHOWS, 0)) { CursorShows.HOVERING })+ private set+ var cursorStyle by mutableStateOf(CursorStyle.entries.getOrElse(interfacePrefs.getInt(CURSOR_STYLE, 2)) { CursorStyle.BRUSH })+ private set++ fun changeCursorShows(v: CursorShows) {+ cursorShows = v+ interfacePrefs.edit().putInt(CURSOR_SHOWS, v.ordinal).apply()+ }++ fun changeCursorStyle(v: CursorStyle) {+ cursorStyle = v+ interfacePrefs.edit().putInt(CURSOR_STYLE, v.ordinal).apply()+ }++ /** The palettes show as cards (named tiles) rather than compact rows of swatches. */+ var paletteCards by mutableStateOf(interfacePrefs.getBoolean(PALETTE_CARDS, false))+ private set++ fun changePaletteCards(on: Boolean) {+ paletteCards = on+ interfacePrefs.edit().putBoolean(PALETTE_CARDS, on).apply()+ }++ /** The short colour panel shows the colour history under the picker, rather than the active palette. */+ var colorHistoryShown by mutableStateOf(interfacePrefs.getBoolean(COLOR_HISTORY_SHOWN, false))+ private set++ fun changeColorHistoryShown(on: Boolean) {+ colorHistoryShown = on+ interfacePrefs.edit().putBoolean(COLOR_HISTORY_SHOWN, on).apply()+ }++ /** Project canvas: the canvas, without the interface, on a second display when there is one. */+ var projectCanvas by mutableStateOf(interfacePrefs.getBoolean(PROJECT_CANVAS, false))+ private set++ fun changeProjectCanvas(on: Boolean) {+ projectCanvas = on+ interfacePrefs.edit().putBoolean(PROJECT_CANVAS, on).apply()+ }++ // the second display's window while it is shown, and its size+ private var projection: Triple<android.view.Surface, Int, Int>? = null++ /** The second display's window came ([surface], [width] × [height]) or went (null). */+ fun setProjectionSurface(surface: android.view.Surface?, width: Int = 0, height: Int = 0) {+ val same = surface != null && projection?.first == surface+ projection = surface?.let { Triple(it, width, height) }+ if (same) session?.resizeProjection(width.toUInt(), height.toUInt()) else attachProjection()+ }++ /** The open artwork shows on the second display, if there is one. */+ private fun attachProjection() {+ val s = session ?: return+ val (surface, w, h) = projection ?: return s.detachProjection()+ val id = NativeWindows.acquire(surface)+ if (id != 0L) runCatching { s.attachProjection(id.toULong(), w.toUInt(), h.toUInt()) }+ }++ /** Brush scaling relative to the screen (else to the canvas). */+ var brushOnScreen by mutableStateOf(interfacePrefs.getBoolean(BRUSH_ON_SCREEN, false))+ private set++ fun changeBrushScaling(onScreen: Boolean) {+ brushOnScreen = onScreen+ session?.setBrushScaling(onScreen)+ interfacePrefs.edit().putBoolean(BRUSH_ON_SCREEN, onScreen).apply()+ }++ /**+ * Shows the brush cursor at window point [p] (or hides it), sized for the current brush and+ * zoom, as long as it shows when [hovering] (or painting).+ */+ fun showCursor(p: Offset?, hovering: Boolean = false) {+ val wanted = if (hovering) cursorShows != CursorShows.PAINTING else cursorShows != CursorShows.HOVERING+ if (!brushCursorOn || p == null || !wanted) {+ cursorAt = null+ return+ }+ if (cursorAt == null) session?.let { s ->+ cursorRadius = s.info().let { it.brushDiameter * it.zoom / 2f }+ cursorOutline = s.currentBrushSetting("cursor_outline").roundToInt()+ }+ cursorAt = p+ }++ /** The light interface: light grey panels and bars with dark text. */+ var lightInterface by mutableStateOf(interfacePrefs.getBoolean(LIGHT_INTERFACE, false).also { io.github.artcraftandroid.procraft.ui.Pc.light = it })+ private set++ fun changeLightInterface(on: Boolean) {+ lightInterface = on+ io.github.artcraftandroid.procraft.ui.Pc.light = on+ interfacePrefs.edit().putBoolean(LIGHT_INTERFACE, on).apply()+ }++ fun changeRapidUndoDelay(seconds: Float) {+ rapidUndoDelay = seconds.coerceIn(RAPID_UNDO_MIN_S, RAPID_UNDO_MAX_S)+ interfacePrefs.edit().putFloat(RAPID_UNDO_DELAY, rapidUndoDelay).apply()+ }++ /** How strongly what isn't selected is banded, 0..1. */+ var selectionVisibility by mutableStateOf(interfacePrefs.getFloat(SELECTION_VISIBILITY, 0.25f))+ private set++ fun changeSelectionVisibility(v: Float) {+ selectionVisibility = v.coerceIn(0f, 1f)+ session?.setSelectionVisibility(selectionVisibility)+ interfacePrefs.edit().putFloat(SELECTION_VISIBILITY, selectionVisibility).apply()+ }++ // pressure and smoothing, for every stroke++ var inputStabilization by mutableStateOf(interfacePrefs.getFloat(INPUT_STABILIZATION, 0f))+ private set+ var inputMotionFiltering by mutableStateOf(interfacePrefs.getFloat(INPUT_MOTION, 0f))+ private set+ var inputMotionExpression by mutableStateOf(interfacePrefs.getFloat(INPUT_EXPRESSION, 0f))+ private set+ var inputPressureSmoothing by mutableStateOf(interfacePrefs.getFloat(INPUT_PRESSURE_SMOOTHING, 0f))+ private set+ var inputCurve by mutableStateOf(+ interfacePrefs.getString(INPUT_CURVE, null)?.split(',')?.mapNotNull { it.toFloatOrNull() }?.chunked(2)?.filter { it.size == 2 }+ ?.map { Offset(it[0], it[1]) }?.takeIf { it.size >= 2 } ?: listOf(Offset(0f, 0f), Offset(1f, 1f)),+ )+ private set++ fun changeInput(+ stabilization: Float = inputStabilization,+ motion: Float = inputMotionFiltering,+ expression: Float = inputMotionExpression,+ smoothing: Float = inputPressureSmoothing,+ curve: List<Offset> = inputCurve,+ ) {+ inputStabilization = stabilization+ inputMotionFiltering = motion+ inputMotionExpression = expression+ inputPressureSmoothing = smoothing+ inputCurve = curve+ interfacePrefs.edit()+ .putFloat(INPUT_STABILIZATION, stabilization).putFloat(INPUT_MOTION, motion)+ .putFloat(INPUT_EXPRESSION, expression).putFloat(INPUT_PRESSURE_SMOOTHING, smoothing)+ .putString(INPUT_CURVE, curve.joinToString(",") { "${it.x},${it.y}" })+ .apply()+ applyInput()+ }++ fun resetInput() = changeInput(0f, 0f, 0f, 0f, listOf(Offset(0f, 0f), Offset(1f, 1f)))++ private fun applyInput() {+ session?.setInputSettings(inputStabilization, inputMotionFiltering, inputMotionExpression, inputPressureSmoothing, inputCurve.flatMap { listOf(it.x, it.y) })+ }++ fun changeRightHanded(on: Boolean) {+ rightHanded = on+ interfacePrefs.edit().putBoolean(RIGHT_HANDED, on).apply()+ }++ /** The actions panel's open tab, kept from one session to the next. */+ private var actionsTabState by mutableStateOf(interfacePrefs.getInt(ACTIONS_TAB, 0))+ var actionsTab: Int+ get() = actionsTabState+ set(tab) {+ actionsTabState = tab+ interfacePrefs.edit().putInt(ACTIONS_TAB, tab).apply()+ }++ /** The eyedropper, while it is open. */+ var picking by mutableStateOf<PickState?>(null)+ private set++ /** The modify button was pressed: the next touch on the canvas picks a colour. */+ var pickNext by mutableStateOf(false)++ /** Transform is open (with a box when the layer holds anything). */+ var transforming by mutableStateOf(false)+ private set+ var transformBox by mutableStateOf<TransformBox?>(null)+ private set+ private val transformPrefs = app.getSharedPreferences("transform", android.content.Context.MODE_PRIVATE)+ /** The brush library as edited, kept between artworks and launches. */+ private val brushPrefs = app.getSharedPreferences("brushes", android.content.Context.MODE_PRIVATE)+ var transformKind by mutableStateOf(enumPref(TRANSFORM_KIND, TransformKind.FREEFORM))+ private set+ var interpolation by mutableStateOf(enumPref(INTERPOLATION, Interpolation.BILINEAR))+ private set+ var transformPopup by mutableStateOf(TransformPopup.NONE)+ /** Magnetics, snapping, and snapping's distance (1..50 points) and velocity (0..10). */+ var guides by mutableStateOf(+ GuideSettings(+ transformPrefs.getBoolean(MAGNETICS, false),+ transformPrefs.getBoolean(SNAPPING, false),+ transformPrefs.getFloat(SNAP_DISTANCE, 3f),+ transformPrefs.getFloat(SNAP_VELOCITY, 10f),+ ),+ )+ private set++ /** A warp shows and takes all 16 of its control points, not only its corners. */+ var advancedMesh by mutableStateOf(transformPrefs.getBoolean(ADVANCED_MESH, false))+ private set++ /** The selection tool is open. */+ var selecting by mutableStateOf(false)+ private set+ var selectionKind by mutableStateOf(enumPref(SELECTION_KIND, SelectionKind.FREEHAND))+ private set+ /** New shapes take away from the selection instead of adding to it. */+ var selectionRemoves by mutableStateOf(false)+ private set+ /** Each new selection is filled with the paint colour. */+ var colorFill by mutableStateOf(false)+ private set+ var hasSelection by mutableStateOf(false)+ private set+ private var selectionPopupState by mutableStateOf(SelectionPopup.NONE)+ /** The popover over the selection toolbar; closing the feather popover keeps its feathering as one undo step. */+ var selectionPopup: SelectionPopup+ get() = selectionPopupState+ set(value) {+ if (selectionPopupState == SelectionPopup.FEATHER && value != SelectionPopup.FEATHER) {+ session?.selectFeatherDone()+ refreshFlags()+ }+ selectionPopupState = value+ }+ /** The feather popover's amount, 0..1. */+ var featherAmount by mutableFloatStateOf(0f)+ private set+ var savedSelections by mutableStateOf(0)+ private set+ /** Pictures of the kept selections, by index. */+ val savedThumbnails = mutableStateMapOf<Int, ImageBitmap>()+ /** The freehand path being drawn, in canvas pixels (closed by tapping its first point). */+ var freehand by mutableStateOf<List<Offset>>(emptyList())+ private set+ /** A rectangle or ellipse being dragged out: its corners in window pixels. */+ var shapeDrag by mutableStateOf<Pair<Offset, Offset>?>(null)+ /** A colour selection's threshold being dragged: where (window pixels), and the threshold (0..1). */+ var thresholdDrag by mutableStateOf<Pair<Offset, Float>?>(null)+ /** The colour selection's threshold, kept from one selection to the next (0..1). */+ var selectionThreshold by mutableFloatStateOf(transformPrefs.getFloat(SELECTION_THRESHOLD, 0.5f))+ private set++ /** The adjustment open on the current layer, and its values. */+ var adjustment by mutableStateOf<Adjustment?>(null)+ private set+ var adjustAmount by mutableFloatStateOf(0f)+ private set+ var hue50 by mutableFloatStateOf(0.5f)+ private set+ var saturation50 by mutableFloatStateOf(0.5f)+ private set+ var brightness50 by mutableFloatStateOf(0.5f)+ private set+ /** The liquify brush: its way and sliders (0..1), and how much of it shows. */+ var liquifyKind by mutableStateOf(LiquifyKind.PUSH)+ private set+ var liquifySize by mutableFloatStateOf(0.5f)+ var liquifyPressure by mutableFloatStateOf(1f)+ var liquifyDistortion by mutableFloatStateOf(0f)+ var liquifyMomentum by mutableFloatStateOf(0.8f)+ var liquifyAmount by mutableFloatStateOf(1f)+ private set+ /** Liquify's mode list or adjust slider is open. */+ var liquifyPopup by mutableStateOf(0)+ var liquified by mutableStateOf(false)+ private set++ /** The adjustment is painted on with the brush (Pencil), and the Layer / Pencil choice is open. */+ var adjustPencil by mutableStateOf(false)+ private set+ var adjustModesOpen by mutableStateOf(false)+ /** Cloning: where the source is (canvas pixels), and how far from the brush once a stroke fixed it. */+ var clonePuck by mutableStateOf<Offset?>(null)+ private set+ private var cloneOffset: Offset? = null+ /** Where the source was before each clone stroke kept, and before each undone, for undo and redo. */+ private val puckBefore = ArrayDeque<Offset>()+ private val puckAfter = ArrayDeque<Offset>()+ /** The canvas window's size (pixels) and density, for what starts in its middle. */+ var windowSize = Offset.Zero+ var density = 2f++ /** Where the adjustment's menu is open (window pixels), after a tap on the canvas. */+ var adjustMenuAt by mutableStateOf<Offset?>(null)+ /** The layer shows as it was before the adjustment. */+ var adjustPreview by mutableStateOf(false)+ private set+ /** Colour balance: the tone shown (shadows, midtones, highlights) and its nine sliders (0..1, 0.5 none). */+ var balanceTone by mutableStateOf(1)+ private set+ var balance by mutableStateOf(List(9) { 0.5f })+ private set+ /** Curves: the channel shown (all, red, green, blue) and each channel's points (0..1). */+ var curveChannel by mutableStateOf(0)+ private set+ var curves by mutableStateOf(List(4) { listOf(Offset(0f, 0f), Offset(1f, 1f)) })+ private set+ /** The gradient mapped by. */+ var gradientIndex by mutableStateOf(0)+ private set+ private val gradientStore = io.github.artcraftandroid.procraft.gallery.GradientStore(File(app.filesDir, "gradients.json"))+ /** The gradient library: ours, and those made or changed here. */+ var gradients by mutableStateOf(gradientStore.load())+ private set+ /** The gradient being edited, by its place in [gradients]. */+ var gradientEditing by mutableStateOf<Int?>(null)+ private set+ /** Glitch: the kind shown and each kind's sliders (the last one its zoom). */+ var glitchKind by mutableStateOf(GlitchKind.ARTIFACT)+ private set+ var glitchValues by mutableStateOf(GLITCH_DEFAULTS)+ private set+ /** Noise: its kind, scale, octaves and turbulence (0..1), each channel its own, added or mixed in. */+ var noiseKind by mutableStateOf(NoiseKind.CLOUDS)+ private set+ var noiseScale by mutableFloatStateOf(0f)+ private set+ var noiseOctaves by mutableFloatStateOf(0f)+ private set+ var noiseTurbulence by mutableFloatStateOf(0.7f)+ private set+ var noiseMulti by mutableStateOf(false)+ private set+ var noiseAdded by mutableStateOf(true)+ private set+ /** Bloom: transition, size and burn (0..1). */+ var bloomTransition by mutableFloatStateOf(1f)+ private set+ var bloomSize by mutableFloatStateOf(0.3f)+ private set+ var bloomBurn by mutableFloatStateOf(0.35f)+ private set+ var halftoneKind by mutableStateOf(HalftoneKind.FULL_COLOR)+ private set+ /** Chromatic aberration: its kind and each kind's two sliders; displaced, how far (window pixels). */+ var chromaKind by mutableStateOf(ChromaticKind.PERSPECTIVE)+ private set+ var chromaValues by mutableStateOf(mapOf(ChromaticKind.PERSPECTIVE to listOf(0f, 0f), ChromaticKind.DISPLACE to listOf(0f, 0f)))+ private set+ private var chromaOffset = Offset.Zero+ private var chromaDragFrom = Offset.Zero++ /** The node held on the transform box and where the touch is (window pixels), while a drag lasts. */+ var transformHeld by mutableStateOf<Pair<TransformHandle, Offset>?>(null)+ /** The rotate or box-turning node just let go where the touch left it, springing back. */+ var transformLetGo by mutableStateOf<Pair<TransformHandle, Offset>?>(null)++ /** The view (canvas pixels to window pixels) as [a, b, c, d, e, f], read while something is drawn over the canvas. */+ var viewMatrix by mutableStateOf(listOf(1f, 0f, 0f, 1f, 0f, 0f))+ private set++ private var pickJob: Job? = null+ private var pendingPick: Pair<Float, Float>? = null++ private val paletteStore = PaletteStore(File(app.filesDir, "palettes.json"))+ var palettes by mutableStateOf<List<Palette>>(emptyList())+ private set++ /** The palette shown under the history in the other colour modes. */+ var defaultPalette by mutableStateOf(0)+ private set++ init {+ val (p, d) = paletteStore.load()+ palettes = p+ defaultPalette = d+ // colour profiles the user imported+ io.github.artcraftandroid.procraft.core.setProfileFolder(File(app.filesDir, "icc").path)+ }++ /** A CMYK canvas's inks for a colour and back, for the colour panel; null on an RGB canvas. */+ var inks by mutableStateOf<io.github.artcraftandroid.procraft.ui.Inks?>(null)+ private set++ /** How the colour panel and swatches show the canvas's colours: its space, its press. */+ private fun refreshCanvasSpace(s: CanvasSession) {+ val name = s.profile()+ val space = io.github.artcraftandroid.procraft.ui.CanvasSpace+ val p3 = io.github.artcraftandroid.procraft.gallery.CanvasPreset.P3+ when {+ s.isCmyk() -> {+ space.set(true) { s.proofColor(it.toUInt()).toInt() }+ inks = io.github.artcraftandroid.procraft.ui.Inks(+ { rgb -> s.cmykOf(rgb.toUInt()).toFloatArray().takeIf { it.size == 4 } ?: FloatArray(4) },+ { v -> s.rgbOfCmyk(v.toList()).toInt() },+ )+ return+ }+ io.github.artcraftandroid.procraft.core.profileIsBuiltIn(name) -> space.set(name == p3)+ else -> space.set(true) { io.github.artcraftandroid.procraft.core.convertColor(it.toUInt(), name, p3).toInt() }+ }+ inks = null+ }++ /** Adds the colour profile file at [uri] to those a canvas can be in; its name, or null if it isn't one. */+ suspend fun importProfile(uri: android.net.Uri): String? {+ val resolver = getApplication<Application>().contentResolver+ val name = withContext(Dispatchers.IO) {+ runCatching { resolver.openInputStream(uri)?.use { it.readBytes() }?.let { io.github.artcraftandroid.procraft.core.importProfile(it) } }.getOrNull()+ }+ if (name == null) message = "This file isn't a color profile."+ return name+ }+ var harmonyKind by mutableStateOf(HarmonyKind.COMPLEMENTARY)++ var barsHidden by mutableStateOf(false)+ private set+ var panel by mutableStateOf(Panel.NONE)+ private set++ /** The panel just closed fades away (an adjustment picked from its list) instead of going at once. */+ var panelFading by mutableStateOf(false)++ var layers by mutableStateOf<List<LayerInfo>>(emptyList())+ private set+ var background by mutableStateOf(BackgroundInfo(1f, 1f, 1f, true))+ private set+ var canUndo by mutableStateOf(false)+ private set+ var canRedo by mutableStateOf(false)+ private set+ val thumbnails = mutableStateMapOf<ULong, ImageBitmap>()++ var brushSets by mutableStateOf<List<BrushSetInfo>>(emptyList())+ private set+ var currentBrush by mutableStateOf<BrushInfo?>(null)+ private set+ var shownSet by mutableStateOf(0)+ private set+ val previews = mutableStateMapOf<String, ImageBitmap>()++ /** Previews whose stroke runs under the brush's name: the name then sits on a dark pill. */+ val shadedNames = mutableStateMapOf<String, Boolean>()++ /** The drawing guide, its editor open, and symmetry's options open. */+ var guide by mutableStateOf<GuideInfo?>(null)+ private set+ var guideEditing by mutableStateOf(false)+ private set+ var symmetryOptionsOpen by mutableStateOf(false)++ /** What was last copied or cut, for pasting (in this artwork or another). */+ private var clipboard: io.github.artcraftandroid.procraft.core.ThumbnailImage? = null+ var canPaste by mutableStateOf(false)+ private set++ /** The shape the last stroke snapped to (drawn and held), and whether its handles are shown. */+ var quickShape by mutableStateOf<QuickShapeInfo?>(null)+ private set+ var quickShapeEditing by mutableStateOf(false)++ /** The brush studio: open, the tab shown, the brush's name, its controls' values, curve and sample stroke. */+ var studioOpen by mutableStateOf(false)+ private set++ /**+ * The drawing pad's surface has drawn: until then the pad is covered, since its surface punches+ * through to the canvas's until it has a frame of its own.+ */+ var padShown by mutableStateOf(false)++ /** The brush studio's open page, whichever brush it opens on, kept from one session to the next. */+ private var studioTabState by mutableStateOf(interfacePrefs.getInt(STUDIO_TAB, 0))+ var studioTab: Int+ get() = studioTabState+ set(tab) {+ studioTabState = tab+ interfacePrefs.edit().putInt(STUDIO_TAB, tab).apply()+ }+ var studioName by mutableStateOf("")+ private set+ private val studioValues = mutableStateMapOf<String, Float>()+ var studioCurve by mutableStateOf(listOf(Offset(0f, 0f), Offset(1f, 1f)))+ private set+ var studioPreview by mutableStateOf<ImageBitmap?>(null)+ private set+ private var studioPreviewJob: Job? = null+ /** The studio's drawing pad, the colour it paints in (an index into [PAD_COLORS]), and its settings popover. */+ var pad: CanvasSession? = null+ private set+ var padColor by mutableStateOf(PAD_WHITE)+ private set+ var padMenuOpen by mutableStateOf(false)+ val blendModeList: List<BlendModeInfo> = blendModes()++ init {+ refreshGallery()+ }++ // ---- gallery ----++ /** Where new artworks go: the stack open, or the gallery. */+ private val galleryDir get() = openStack?.dir ?: store.root++ fun refreshGallery() {+ viewModelScope.launch {+ val stack = openStack+ val entries = withContext(Dispatchers.IO) { store.list(stack?.dir ?: store.root) }+ galleryEntries = entries+ artworks = entries.filterIsInstance<Artwork>()+ // an emptied stack closes+ if (stack != null && entries.isEmpty()) {+ openStack = null+ refreshGallery()+ }+ }+ }++ fun showStack(s: io.github.artcraftandroid.procraft.gallery.Stack?) {+ openStack = s+ refreshGallery()+ }++ /** The artworks put together in a new stack. */+ fun stackArtworks(list: List<Artwork>) {+ if (list.size < 2 || openStack != null) return+ viewModelScope.launch {+ withContext(Dispatchers.IO) { store.stack(list) }+ refreshGallery()+ }+ }++ fun renameStack(s: io.github.artcraftandroid.procraft.gallery.Stack, name: String) {+ viewModelScope.launch {+ withContext(Dispatchers.IO) { store.renameStack(s, name) }+ if (openStack?.dir == s.dir) openStack = s.copy(name = name.trim().ifEmpty { "Stack" })+ refreshGallery()+ }+ }++ private val presetPrefs = app.getSharedPreferences("canvas_presets", android.content.Context.MODE_PRIVATE)++ /** The New canvas list under the screen's size: the standard presets, then those made since. */+ var canvasPresets by mutableStateOf(readPresets())+ private set++ /** Custom Canvas is open, on a new preset or on [editingPreset]. */+ var customCanvasOpen by mutableStateOf(false)+ private set++ /** The preset Custom Canvas edits (its place in [canvasPresets]); null for a new one. */+ var editingPreset by mutableStateOf<Int?>(null)+ private set++ private fun readPresets(): List<CanvasPreset> {+ val saved = presetPrefs.getString(PRESETS, null) ?: return StandardPresets+ return runCatching {+ val list = org.json.JSONArray(saved)+ List(list.length()) { CanvasPreset.fromJson(list.getJSONObject(it)) }+ }.getOrDefault(StandardPresets)+ }++ private fun savePresets(list: List<CanvasPreset>) {+ canvasPresets = list+ val json = org.json.JSONArray()+ list.forEach { json.put(it.toJson()) }+ presetPrefs.edit().putString(PRESETS, json.toString()).apply()+ }++ /** Opens Custom Canvas on the preset at [index], or on a new one. */+ fun openCustomCanvas(index: Int? = null) {+ editingPreset = index?.takeIf { it in canvasPresets.indices }+ customCanvasOpen = true+ }++ fun closeCustomCanvas() {+ customCanvasOpen = false+ editingPreset = null+ }++ /**+ * Custom Canvas's Done: an edited preset is saved in its place; a new one goes at the end of+ * the list and is made into an artwork. True if an artwork was made.+ */+ fun finishCustomCanvas(p: CanvasPreset): Boolean {+ val index = editingPreset+ closeCustomCanvas()+ if (index != null && index in canvasPresets.indices) {+ savePresets(canvasPresets.toMutableList().also { it[index] = p })+ return false+ }+ savePresets(canvasPresets + p)+ newPresetArtwork(p)+ return true+ }++ fun deletePreset(index: Int) {+ if (index in canvasPresets.indices) savePresets(canvasPresets.filterIndexed { i, _ -> i != index })+ }++ /** A new artwork made as preset [p] says, opened on the canvas. */+ fun newPresetArtwork(p: CanvasPreset) {+ val rgb = listOf(((p.background shr 16) and 255) / 255f, ((p.background shr 8) and 255) / 255f, (p.background and 255) / 255f)+ val s = CanvasSession.newCustom(p.width.toUInt(), p.height.toUInt(), p.dpi, rgb, !p.backgroundHidden, "Untitled Artwork")+ s.setNewProfile(p.profile)+ start(s, store.newFolder(galleryDir))+ timeLapse?.settings = p.timeLapse+ startedNew()+ }++ /** The layers a canvas [width] × [height] holds on this device. */+ /** Says the canvas holds no more layers, and how many it holds. */+ private fun noRoom(): String {+ val (w, h) = canvasSize()+ return "This canvas holds at most ${layersFor(w, h)} layers."+ }++ fun layersFor(width: Int, height: Int): Int {+ val memory = android.app.ActivityManager.MemoryInfo()+ getApplication<Application>().getSystemService(android.app.ActivityManager::class.java)?.getMemoryInfo(memory)+ val budget = if (memory.totalMem > 0) memory.totalMem / 4 else 2L shl 30+ return (budget / (width.toLong().coerceAtLeast(1) * height.toLong().coerceAtLeast(1) * 4)).toInt().coerceAtLeast(1)+ }++ /** A new artwork of `width` × `height` pixels (the screen's size), in Display P3, opened on the canvas. */+ fun newArtwork(width: Int, height: Int) {+ val s = CanvasSession(width.coerceAtLeast(1).toUInt(), height.coerceAtLeast(1).toUInt())+ s.setNewProfile(io.github.artcraftandroid.procraft.gallery.CanvasPreset.P3)+ start(s, store.newFolder(galleryDir))+ startedNew()+ }++ // the app's own settings (the settings page beside the canvas): read when the app comes back++ /** An artwork opens as it was left. */+ var orientationMemory = interfacePrefs.getBoolean(ORIENTATION_MEMORY, true)+ private set++ /** Fitting the canvas keeps it clear of the top bar and the sidebar. */+ var fitInside = interfacePrefs.getBoolean(FIT_INSIDE, false)+ private set++ /** New artworks don't record their time-lapse. */+ var timeLapseDisabled = interfacePrefs.getBoolean(NO_TIME_LAPSE, false)+ private set++ /** Accessibility: the colour named in a message as it changes, and clicks for actions. */+ var colorNames = interfacePrefs.getBoolean(COLOR_NAMES, false)+ private set+ var feedbackSounds = interfacePrefs.getBoolean(FEEDBACK_SOUNDS, false)+ private set++ /** Accessibility: a floating bar standing in for gestures that need more than one finger. */+ var singleTouchCompanion by mutableStateOf(interfacePrefs.getBoolean(SINGLE_TOUCH_COMPANION, false))+ private set++ /** Accessibility: a tap lands where the finger first touched, even if it drifts before lifting. */+ var tapAssistance = interfacePrefs.getBoolean(TAP_ASSISTANCE, false)+ private set++ /** The companion's one-finger mode: a finger dragged on the canvas zooms it, or moves it. */+ enum class CompanionMode { NONE, ZOOM, MOVE }++ var companionMode by mutableStateOf(CompanionMode.NONE)+ private set++ fun toggleCompanionMode(m: CompanionMode) {+ feedback()+ companionMode = if (companionMode == m) CompanionMode.NONE else m+ }++ fun readAppSettings() {+ colorNames = interfacePrefs.getBoolean(COLOR_NAMES, false)+ feedbackSounds = interfacePrefs.getBoolean(FEEDBACK_SOUNDS, false)+ singleTouchCompanion = interfacePrefs.getBoolean(SINGLE_TOUCH_COMPANION, false)+ tapAssistance = interfacePrefs.getBoolean(TAP_ASSISTANCE, false)+ if (!singleTouchCompanion) companionMode = CompanionMode.NONE+ orientationMemory = interfacePrefs.getBoolean(ORIENTATION_MEMORY, true)+ fitInside = interfacePrefs.getBoolean(FIT_INSIDE, false)+ timeLapseDisabled = interfacePrefs.getBoolean(NO_TIME_LAPSE, false)+ session?.let(::applyAppSettings)+ applyFitInsets()+ }++ /** The settings the canvas itself keeps: simplified undos and the speed distance. */+ private fun applyAppSettings(s: CanvasSession) {+ s.setSimplifiedUndos(interfacePrefs.getBoolean(SIMPLIFIED_UNDOS, true))+ s.setSpeedDistance(interfacePrefs.getFloat(SPEED_DISTANCE, 1f))+ }++ /** What fitting the canvas keeps clear of: the top bar and the sidebar, with Fit Canvas Inside Interface. */+ fun applyFitInsets() {+ val s = session ?: return+ if (!fitInside) {+ s.setFitInsets(0f, 0f, 0f, 0f)+ return+ }+ val side = if (showSideBar) (io.github.artcraftandroid.procraft.ui.Pc.SideBarWidth.value + io.github.artcraftandroid.procraft.ui.Pc.PopoverGap.value) * density else 0f+ s.setFitInsets(if (rightHanded) 0f else side, io.github.artcraftandroid.procraft.ui.Pc.BarHeight.value * density, if (rightHanded) side else 0f, 0f)+ }++ /** A new artwork just started: without time-lapse if it is turned off. */+ private fun startedNew() {+ if (timeLapseDisabled) changeTimeLapseRecording(false)+ }++ /** A new artwork from a photo or picture file, its size, the picture as its one layer. */+ fun newFromPicture(uri: android.net.Uri) {+ viewModelScope.launch {+ // in Display P3 if the picture is, else in sRGB+ val p3 = withContext(Dispatchers.IO) { pictureIsP3(uri) }+ val image = withContext(Dispatchers.IO) { decodePicture(uri, p3) }+ if (image == null) {+ message = "This picture can't be opened."+ return@launch+ }+ val s = CanvasSession.fromImage(image, "Untitled Artwork")+ if (p3) s.setNewProfile(io.github.artcraftandroid.procraft.gallery.CanvasPreset.P3)+ start(s, store.newFolder(galleryDir))+ startedNew()+ }+ }++ /** A file from elsewhere into the gallery: an artwork file, or a picture as a new artwork. */+ fun importFile(uri: android.net.Uri) {+ val resolver = getApplication<Application>().contentResolver+ viewModelScope.launch {+ val head = withContext(Dispatchers.IO) { runCatching { resolver.openInputStream(uri)?.use { s -> ByteArray(4).also { s.read(it) } } }.getOrNull() }+ val name = withContext(Dispatchers.IO) { fileName(uri) }+ // another program's palette+ val foreign = head != null && io.github.artcraftandroid.procraft.gallery.ColourSwatches.isExchange(head) || name?.endsWith(".aco", ignoreCase = true) == true+ val zip = head != null && head[0] == 'P'.code.toByte() && head[1] == 'K'.code.toByte()+ // a zip of brushes+ val brushes = if (zip) withContext(Dispatchers.IO) { runCatching { resolver.openInputStream(uri)?.use { it.readBytes() } }.getOrNull() }?.takeIf(::isBrushFile) else null+ // a zip: brushes, a palette, an artwork file of ours, or a layered package+ if (brushes != null) {+ if (!addBrushes(brushes)) message = "This file has no brushes in it."+ } else if (head != null && (foreign || zip) && importSwatches(uri)) {+ message = "Palette added."+ } else if (foreign) {+ message = "This palette can't be read."+ } else if (head != null && head[0] == 'P'.code.toByte() && head[1] == 'K'.code.toByte()) {+ val ok = withContext(Dispatchers.IO) {+ val dir = store.newFolder(galleryDir)+ val ours = runCatching { resolver.openInputStream(uri)?.use { io.github.artcraftandroid.procraft.gallery.ArtworkFile.read(it, dir) } }.getOrNull() == true+ (ours || importPackage(uri, dir)).also { if (!it) dir.deleteRecursively() }+ }+ if (ok) refreshGallery() else message = "This file can't be opened."+ } else {+ newFromPicture(uri)+ }+ }+ }++ /**+ * A layered package from [uri] made into the artwork folder [dir]: its layers, settings and+ * preview (as the gallery's thumbnail until it is opened); false if it isn't one.+ */+ private fun importPackage(uri: android.net.Uri, dir: File): Boolean {+ val resolver = getApplication<Application>().contentResolver+ val temp = File(getApplication<Application>().cacheDir, "import-${System.nanoTime()}.zip")+ return try {+ resolver.openInputStream(uri)?.use { input -> temp.outputStream().use { input.copyTo(it) } } ?: return false+ val s = runCatching { CanvasSession.openPackage(temp.path) }.getOrNull() ?: return false+ s.save(dir.path)+ java.util.zip.ZipFile(temp).use { zip ->+ zip.getEntry("QuickLook/Thumbnail.png")?.let { e ->+ zip.getInputStream(e).use { input -> File(dir, "thumbnail.png").outputStream().use { input.copyTo(it) } }+ }+ }+ true+ } catch (e: Exception) {+ android.util.Log.e("ProCraft", "importing a package", e)+ false+ } finally {+ temp.delete()+ }+ }++ /** The open artwork as a layered package in the cache, to share. */+ suspend fun exportPackageFile(): File? {+ val s = session ?: return null+ return withContext(Dispatchers.IO) {+ runCatching {+ val base = s.name().filter { it.isLetterOrDigit() || it in " _-" }.trim().replace(' ', '_').ifEmpty { "Untitled_Artwork" }+ val out = File(File(getApplication<Application>().cacheDir, "exports").apply { mkdirs() }, "$base.$PACKAGE_EXTENSION")+ s.exportPackage(out.path, System.nanoTime().toULong())+ out+ }.onFailure { android.util.Log.e("ProCraft", "exporting a package", it) }.getOrNull()+ }+ }++ /** The open artwork saved and zipped into the cache as one file, to share. */+ suspend fun exportArtworkFile(): File? {+ val s = session ?: return null+ val dir = artworkDir ?: return null+ return withContext(Dispatchers.IO) {+ runCatching {+ s.save(dir.path)+ val out = File(File(getApplication<Application>().cacheDir, "exports").apply { mkdirs() },+ s.name().filter { it.isLetterOrDigit() || it in " _-" }.trim().ifEmpty { "Untitled Artwork" } + "." + io.github.artcraftandroid.procraft.gallery.ArtworkFile.EXTENSION)+ io.github.artcraftandroid.procraft.gallery.ArtworkFile.write(dir, out)+ out+ }.getOrNull()+ }+ }++ /**+ * The gallery zooming into an artwork as it opens ([opening]), or out of it as it closes: the+ * artwork's cell and where its canvas is (window pixels), and closing, a picture of the canvas.+ */+ class GalleryZoom(+ val cell: androidx.compose.ui.geometry.Rect,+ val canvas: androidx.compose.ui.geometry.Rect,+ val opening: Boolean,+ val picture: androidx.compose.ui.graphics.ImageBitmap? = null,+ )++ var galleryZoom by mutableStateOf<GalleryZoom?>(null)++ /** Where each artwork's thumbnail was last shown in the gallery (window pixels), by its folder's name. */+ val thumbAt = mutableMapOf<String, androidx.compose.ui.geometry.Rect>()++ /** The gallery's grid, kept so it is where it was when the gallery comes back. */+ val galleryGrid = androidx.compose.foundation.lazy.grid.LazyGridState()++ /** The window's size in pixels, as the gallery last saw it. */+ var windowPx = androidx.compose.ui.unit.IntSize(1, 1)++ /** Where [s]'s canvas is on screen through the view [m] (as `viewMatrix` gives it), window pixels. */+ private fun canvasRect(s: CanvasSession, m: List<Float>): androidx.compose.ui.geometry.Rect {+ val info = s.info()+ val (w, h) = info.width.toFloat() to info.height.toFloat()+ val corners = listOf(Offset(0f, 0f), Offset(w, 0f), Offset(0f, h), Offset(w, h)).map { p ->+ Offset(m[0] * p.x + m[2] * p.y + m[4], m[1] * p.x + m[3] * p.y + m[5])+ }+ return androidx.compose.ui.geometry.Rect(corners.minOf { it.x }, corners.minOf { it.y }, corners.maxOf { it.x }, corners.maxOf { it.y })+ }++ /**+ * Waits (off the main thread, as a big artwork's first frame holds the session a while) until+ * the open artwork's canvas has drawn a frame, or a few seconds have passed.+ */+ suspend fun awaitCanvasDrawn() = withContext(Dispatchers.IO) {+ val s = session ?: return@withContext+ var waited = 0L+ while (waited < CANVAS_DRAWN_LIMIT_MS && runCatching { s.info().frames }.getOrDefault(1uL) == 0uL) {+ kotlinx.coroutines.delay(CANVAS_POLL_MS)+ waited += CANVAS_POLL_MS+ }+ }++ /** Opens artwork [a], the gallery zooming into its cell; then [then]. */+ fun openArtwork(a: Artwork, then: (() -> Unit)? = null) {+ if (opening) return+ opening = true+ val cell = thumbAt[a.dir.name]+ viewModelScope.launch {+ val s = withContext(Dispatchers.IO) { runCatching { CanvasSession.open(a.dir.path) } }+ opening = false+ s.onSuccess {+ if (!orientationMemory) it.forgetSavedView()+ val m = it.openingViewMatrix(windowPx.width.toUInt(), windowPx.height.toUInt())+ galleryZoom = cell?.let { c -> GalleryZoom(c, canvasRect(it, m), opening = true) }+ start(it, a.dir)+ then?.invoke()+ }.onFailure { message = "This artwork can't be opened." }+ }+ }++ /**+ * Artworks from the gallery written as [format] (one of [SHARE_FORMATS] but the animated ones)+ * into the cache, to share; with the type they are.+ */+ suspend fun shareableFiles(list: List<Artwork>, format: String, pdfQuality: Int = 100): Pair<List<File>, String> = withContext(Dispatchers.IO) {+ val (extension, mime) = when (format) {+ "PSD" -> "psd" to "image/vnd.adobe.photoshop"+ "PDF" -> "pdf" to "application/pdf"+ "JPEG" -> "jpg" to "image/jpeg"+ "PNG" -> "png" to "image/png"+ "TIFF" -> "tif" to "image/tiff"+ else -> PACKAGE_EXTENSION to "application/octet-stream"+ }+ val dir = File(getApplication<Application>().cacheDir, "exports").apply { mkdirs() }+ val used = mutableSetOf<String>()+ list.mapNotNull { a ->+ val base = a.name.filter { it.isLetterOrDigit() || it in " _-" }.trim().ifEmpty { "Untitled Artwork" }+ var name = base+ var n = 2+ while (!used.add(name)) name = "$base ${n++}"+ File(dir, "$name.$extension").takeIf { io.github.artcraftandroid.procraft.gallery.exportArtwork(a.dir, format, it, pdfQuality) }+ } to mime+ }++ /** Opens artwork [a] to set up its animated export as [kind], going back to the gallery after. */+ fun openForAnimatedExport(a: Artwork, kind: Animated) {+ openArtwork(a) {+ exportingFromGallery = true+ animatedExport = kind+ }+ }++ fun deleteArtwork(a: Artwork) {+ viewModelScope.launch {+ withContext(Dispatchers.IO) { store.delete(a) }+ refreshGallery()+ }+ }++ fun duplicateArtwork(a: Artwork) {+ viewModelScope.launch {+ withContext(Dispatchers.IO) { store.duplicate(a) }+ refreshGallery()+ }+ }++ fun renameArtwork(a: Artwork, name: String) {+ if (name.isBlank()) return+ viewModelScope.launch {+ withContext(Dispatchers.IO) { store.rename(a, name) }+ refreshGallery()+ }+ }++ /** Saves the open artwork and goes back to the gallery. */+ fun closeArtwork() {+ endTransform(true)+ endAdjustment(true)+ val s = session ?: return+ noteTime()+ keepChoices(s)+ s.detachProjection()+ val dir = artworkDir+ autosave?.cancel()+ // the gallery zooms out of the artwork's cell, the canvas fading away over it+ val cell = dir?.let { thumbAt[it.name] }+ galleryZoom = cell?.let { c ->+ val picture = s.canvasThumbnail(CLOSING_PICTURE_SIDE.toUInt())?.let { t ->+ val bitmap = io.github.artcraftandroid.procraft.ui.CanvasSpace.tag(Bitmap.createBitmap(t.width.toInt(), t.height.toInt(), Bitmap.Config.ARGB_8888))+ bitmap.copyPixelsFromBuffer(ByteBuffer.wrap(t.rgba))+ bitmap.asImageBitmap()+ }+ GalleryZoom(c, canvasRect(s, s.viewMatrix()), opening = false, picture = picture)+ }+ session = null+ artworkDir = null+ panel = Panel.NONE+ screen = Screen.GALLERY+ viewModelScope.launch {+ withContext(Dispatchers.IO) { dir?.let { runCatching { s.save(it.path) } } }+ galleryVersion+++ refreshGallery()+ }+ }++ /** When time on the open artwork last started counting (elapsed realtime), 0 while away. */+ private var activeSince = 0L++ /** Adds the time since it last started counting to the artwork's, and stops counting. */+ private fun noteTime() {+ val s = session ?: return+ val now = android.os.SystemClock.elapsedRealtime()+ if (activeSince > 0) s.addTrackedTime((now - activeSince).coerceAtLeast(0).toULong())+ activeSince = 0+ }++ /** The app is back in front: time on the open artwork counts again. */+ fun resumeTracking() {+ if (session != null) activeSince = android.os.SystemClock.elapsedRealtime()+ }++ /** What each touch gesture does. */+ val gestures = GestureSettings(app.getSharedPreferences("gestures", android.content.Context.MODE_PRIVATE))++ /**+ * The pen's side button pressed ([secondary]: its second one), at window point [at]: what Pen+ * double-tap (or Pen squeeze) is set to do in Gesture controls.+ */+ fun penButton(secondary: Boolean, at: Offset) {+ val trigger = if (secondary) Trigger.PEN_SQUEEZE else Trigger.PEN_DOUBLE_TAP+ when (gestures.purposeOf(trigger)) {+ GesturePurpose.EYEDROPPER -> pickNext = true+ GesturePurpose.ASSISTED -> guide?.let { setGuideAssisted(!it.assisted) }+ GesturePurpose.QUICKMENU -> toggleQuickMenu(at)+ GesturePurpose.FULL_SCREEN -> toggleBars()+ GesturePurpose.CLEAR_LAYER -> clearCurrentLayer()+ GesturePurpose.COPY_PASTE -> copyPasteOpen = true+ GesturePurpose.LAYER_SELECT -> layerSelectAt(at)+ GesturePurpose.QUICKSHAPE -> quickShapeLast()+ else -> Unit+ }+ }++ /** The modify button tapped: what Tap □ is set to do (open or close the eyedropper at first). */+ fun tapModify() {+ when (gestures.purposeOf(Trigger.TAP_MODIFY)) {+ GesturePurpose.EYEDROPPER -> pickNext = !pickNext+ GesturePurpose.QUICKMENU -> toggleQuickMenu(Offset(screenCentre.x, screenCentre.y))+ GesturePurpose.COPY_PASTE -> copyPasteOpen = true+ GesturePurpose.QUICKSHAPE -> quickShapeLast()+ else -> Unit+ }+ }++ /** □ is held down: a canvas touch now does what □ + Touch (or □ + Pen) is set to. */+ var modifyHeld = false+ private set++ // when □ went down, and whether a touch has used it since+ private var modifyDownAt = 0L+ private var modifyUsed = false++ fun modifyPressed() {+ modifyHeld = true+ modifyUsed = false+ modifyDownAt = android.os.SystemClock.uptimeMillis()+ }++ /** □ let go: a short press nothing used is a tap ([cancelled] when the finger slid off). */+ fun modifyReleased(cancelled: Boolean) {+ modifyHeld = false+ if (!cancelled && !modifyUsed && android.os.SystemClock.uptimeMillis() - modifyDownAt < MODIFY_TAP_MS) tapModify()+ }++ fun useModify() {+ modifyUsed = true+ }++ /** The middle of the screen (window pixels), for menus a button opens. */+ var screenCentre = Offset(800f, 1280f)++ /** Gesture controls is open. */+ var gestureControlsOpen by mutableStateOf(false)++ /** Canvas information is open. */+ var canvasInfoOpen by mutableStateOf(false)++ /** The artwork's facts, its time counted up to now. */+ fun artworkInfo(): io.github.artcraftandroid.procraft.core.ArtworkInfo? {+ val s = session ?: return null+ if (activeSince > 0) {+ noteTime()+ resumeTracking()+ }+ return s.artworkInfo()+ }++ /** The artwork's folder (for its size and when it was saved). */+ fun artworkFolder(): File? = artworkDir++ fun timeLapseInfo(): Pair<Int, Long> = timeLapse?.let { it.count to it.bytes() } ?: (0 to 0L)++ /** Renames the artwork and sets its author, from Canvas information. */+ fun changeArtworkInfo(name: String, author: String) {+ val s = session ?: return+ if (name.isNotBlank() && name.trim() != s.name()) s.setName(name.trim())+ s.setAuthor(author)+ }++ /** Puts the canvas in colour profile [name], its colours and the current colour turned into it. */+ fun changeProfile(name: String) {+ val s = session ?: return+ val from = s.profile()+ val rgb = colorRgb()+ if (!s.changeProfile(name)) return+ refresh()+ setRgb(io.github.artcraftandroid.procraft.core.convertColor(rgb.toUInt(), from, name).toInt())+ }++ /** Saves the open artwork where it is (the app going into the background). */+ fun saveNow() {+ val s = session ?: return+ val dir = artworkDir ?: return+ noteTime()+ keepChoices(s)+ viewModelScope.launch(Dispatchers.IO) { runCatching { s.save(dir.path) } }+ }++ private fun start(s: CanvasSession, dir: File) {+ // the canvas's colours are P3 or sRGB numbers: the colour panel and swatches follow+ refreshCanvasSpace(s)+ // layers may take a quarter of the device's memory: every layer stays on the GPU+ val memory = android.app.ActivityManager.MemoryInfo()+ getApplication<Application>().getSystemService(android.app.ActivityManager::class.java)?.getMemoryInfo(memory)+ if (memory.totalMem > 0) io.github.artcraftandroid.procraft.core.setLayerBudget((memory.totalMem / 4).toULong())+ s.setSelectionVisibility(selectionVisibility)+ s.setBrushScaling(brushOnScreen)+ // as it was left, or fitted+ if (!orientationMemory) s.forgetSavedView()+ s.setInputSettings(inputStabilization, inputMotionFiltering, inputMotionExpression, inputPressureSmoothing, inputCurve.flatMap { listOf(it.x, it.y) })+ applyAppSettings(s)+ timeLapse = TimeLapse(dir).also { timeLapseRecording = it.recording }+ // the library as kept, else edits kept by earlier versions+ val kept = brushPrefs.getString(BRUSH_LIBRARY, null)+ val loaded = kept != null && s.loadBrushLibrary(kept)+ if (!loaded) brushPrefs.getString(BRUSH_CHANGES, null)?.let { s.applyBrushChanges(it) }+ // brushes and sets shipped since the library was kept join it, once+ val seen = brushPrefs.getString(BRUSHES_SEEN, null)?.split(',')?.mapNotNull { it.toUIntOrNull() } ?: FIRST_SHIPPED+ val shipped = if (loaded) s.addShippedBrushes(seen) else s.shippedBrushCounts()+ if (shipped != seen || !brushPrefs.contains(BRUSHES_SEEN)) {+ brushPrefs.edit().apply {+ // kept with them, or the next start would load the library without them+ if (loaded) putString(BRUSH_LIBRARY, s.savedBrushLibrary())+ putString(BRUSHES_SEEN, shipped.joinToString(","))+ }.apply()+ }+ // the brushes in use as they were left (they go by place in the kept library)+ if (loaded) brushPrefs.getString(BRUSH_CHOICES, null)?.let { s.loadBrushChoices(it) }+ session = s+ // brush files that came while no canvas was open+ addPendingBrushes(s)+ pushSecondary()+ artworkDir = dir+ applyFitInsets()+ attachProjection()+ activeSince = android.os.SystemClock.elapsedRealtime()+ thumbnails.clear()+ previews.clear()+ shadedNames.clear()+ panel = Panel.NONE+ barsHidden = false+ transforming = false+ transformBox = null+ adjustment = null+ selecting = false+ hasSelection = false+ freehand = emptyList()+ tool = ToolKind.PAINT+ applyColor()+ readSliders()+ refresh()+ brushSets = s.brushLibrary()+ readSetChoices()+ currentBrush = s.currentBrush()+ screen = Screen.CANVAS+ // a new artwork exists in the gallery from the start+ viewModelScope.launch(Dispatchers.IO) { runCatching { s.save(dir.path) } }+ startAutosave(s, dir)+ }++ private var autosave: kotlinx.coroutines.Job? = null++ /**+ * Keeps [s] saved into [dir] while it is open: a few seconds after it changes, once nothing is+ * under way that saving would cut short (only the layers that changed are written).+ */+ private fun startAutosave(s: CanvasSession, dir: File) {+ autosave?.cancel()+ autosave = viewModelScope.launch(Dispatchers.IO) {+ var saved = s.edits()+ while (session === s) {+ kotlinx.coroutines.delay(AUTOSAVE_MS)+ val now = s.edits()+ if (now != saved && session === s && runCatching { s.saveIfIdle(dir.path) }.getOrDefault(false)) saved = now+ }+ }+ }++ fun select(tool: ToolKind) {+ feedback()+ session?.setTool(tool)+ this.tool = tool+ readSliders()+ currentBrush = session?.currentBrush()+ }++ /** A tool button: the first tap picks the tool, the next opens its brush library. */+ // the drawing guide++ fun setGuideOn(on: Boolean) {+ guide = session?.setGuideOn(on)+ }++ /** Opens the guide editor (turning the guide on), the canvas fitted between its bars. */+ fun openGuideEditor() {+ val s = session ?: return+ endQuickShape()+ closePanels()+ if (guide?.on != true) s.setGuideOn(true)+ val d = density+ guide = s.guideEditBegin(GUIDE_FIT_SIDE_DP * d, GUIDE_FIT_TOP_DP * d, windowSize.x - GUIDE_FIT_SIDE_DP * d, windowSize.y - GUIDE_FIT_BOTTOM_DP * d)+ guideEditing = true+ refreshView()+ }++ fun closeGuideEditor(keep: Boolean) {+ guide = session?.guideEditEnd(keep)+ guideEditing = false+ symmetryOptionsOpen = false+ refreshView()+ }++ fun chooseGuideKind(kind: GuideType) {+ guide = session?.setGuideKind(kind)+ symmetryOptionsOpen = false+ }++ /** The shown kind's look, each left as it is when not given. */+ fun setGuideLook(opacity: Float? = null, thickness: Float? = null, size: Float? = null, hue: Float? = null) {+ val g = guide ?: return+ guide = session?.setGuideLook(opacity ?: g.opacity, thickness ?: g.thickness, size ?: g.size, hue ?: g.hue)+ }++ fun setGuideSymmetry(kind: SymmetryType, rotational: Boolean) {+ guide = session?.setGuideSymmetry(kind, rotational)+ }++ fun setGuideAssisted(on: Boolean) {+ guide = session?.setGuideAssisted(on)+ }++ /** What a touch at [p] in the guide editor takes: the turn handle (-2), the centre (-1), or a vanishing point (its index); a tap elsewhere in perspective adds one. */+ fun guideGrab(p: Offset): Int? {+ val g = guide ?: return null+ val reach = QUICKSHAPE_REACH_DP * density+ symmetryOptionsOpen = false+ if (g.kind == GuideType.PERSPECTIVE) {+ val index = session?.touchVanishingPoint(p.x, p.y)?.toInt()+ guide = session?.guide()+ return index+ }+ return when {+ (Offset(g.handle[0], g.handle[1]) - p).getDistance() <= reach -> -2+ (Offset(g.centre[0], g.centre[1]) - p).getDistance() <= reach -> -1+ else -> null+ }+ }++ fun guideDrag(grab: Int?, p: Offset) {+ val s = session ?: return+ guide = when (grab) {+ null -> return+ -2 -> s.turnGuide(p.x, p.y)+ -1 -> s.moveGuideCentre(p.x, p.y)+ else -> s.moveVanishingPoint(grab.toUInt(), p.x, p.y)+ }+ }++ // copy and paste, flipping, pictures++ fun copyLayer() {+ val copied = session?.copyLayer()+ clipboard = copied ?: clipboard+ canPaste = clipboard != null+ closePanels()+ if (copied != null) showNotice("Layer copied")+ }++ fun copyCanvas() {+ val copied = session?.copyCanvas()+ clipboard = copied ?: clipboard+ canPaste = clipboard != null+ closePanels()+ if (copied != null) showNotice("Canvas copied")+ }++ fun cutLayer() {+ if (!currentTakesChanges()) {+ closePanels()+ return+ }+ val cut = session?.cutLayer()+ clipboard = cut ?: clipboard+ canPaste = clipboard != null+ closePanels()+ refresh()+ if (cut != null) showNotice("Layer cut")+ }++ fun paste() {+ val image = clipboard ?: return+ if (session?.paste(image) == null) message = noRoom()+ closePanels()+ refresh()+ if (panel == Panel.LAYERS) refreshThumbnails()+ }++ /** Layer Select: the layers drawn under a point (top first), listed there to choose from. */+ var layerChoice by mutableStateOf<Pair<Offset, List<ULong>>?>(null)++ /** Layer Select at window point [at]: the top layer drawn there becomes current, the others listed. */+ fun layerSelectAt(at: Offset) {+ val ids = session?.layersAt(at.x, at.y).orEmpty()+ if (ids.isEmpty()) {+ message = "Nothing is drawn there."+ return+ }+ selectLayer(ids.first())+ layerChoice = if (ids.size > 1) at to ids else null+ }++ /** The QuickMenu, open around this window point. */+ var quickMenuAt by mutableStateOf<Offset?>(null)++ /** The QuickMenu's actions, in order round from the top. */+ /** The QuickMenu's buttons, clockwise from the top: each set to an action (a hold changes it). */+ var quickMenuSlots by mutableStateOf(+ interfacePrefs.getString(QUICK_MENU, null)?.split(',')?.map { n -> QuickAction.entries.firstOrNull { it.name == n } ?: QuickAction.NONE }+ ?.takeIf { it.size == QuickAction.DEFAULTS.size } ?: QuickAction.DEFAULTS,+ )+ private set++ fun setQuickSlot(i: Int, a: QuickAction) {+ if (i !in quickMenuSlots.indices) return+ quickMenuSlots = quickMenuSlots.toMutableList().also { it[i] = a }+ interfacePrefs.edit().putString(QUICK_MENU, quickMenuSlots.joinToString(",") { it.name }).apply()+ }++ /**+ * A key of a hardware keyboard on the canvas ([ctrl] the command key): true if it is a+ * shortcut, done. Typing in a text field never comes here.+ */+ fun keyShortcut(keyCode: Int, ctrl: Boolean, shift: Boolean, alt: Boolean): Boolean {+ if (screen != Screen.CANVAS || session == null) return false+ when {+ ctrl && keyCode == android.view.KeyEvent.KEYCODE_Z -> if (shift) redo() else undo()+ ctrl && keyCode == android.view.KeyEvent.KEYCODE_C -> copyLayer()+ ctrl && keyCode == android.view.KeyEvent.KEYCODE_X -> cutLayer()+ ctrl && keyCode == android.view.KeyEvent.KEYCODE_V -> paste()+ ctrl -> return false+ keyCode == android.view.KeyEvent.KEYCODE_B -> select(ToolKind.PAINT)+ keyCode == android.view.KeyEvent.KEYCODE_E -> select(ToolKind.ERASE)+ keyCode == android.view.KeyEvent.KEYCODE_M -> pickNext = !pickNext+ keyCode == android.view.KeyEvent.KEYCODE_S -> toggleSelecting()+ keyCode == android.view.KeyEvent.KEYCODE_V -> toggleTransform()+ keyCode == android.view.KeyEvent.KEYCODE_U -> startAdjustment(Adjustment.HSB)+ keyCode == android.view.KeyEvent.KEYCODE_C -> toggle(Panel.COLOR)+ keyCode == android.view.KeyEvent.KEYCODE_X -> swapColors()+ keyCode == android.view.KeyEvent.KEYCODE_D -> clearSelection()+ keyCode == android.view.KeyEvent.KEYCODE_J -> duplicateCurrent()+ keyCode == android.view.KeyEvent.KEYCODE_K -> toggle(Panel.ACTIONS)+ keyCode == android.view.KeyEvent.KEYCODE_L -> toggle(Panel.LAYERS)+ keyCode == android.view.KeyEvent.KEYCODE_0 -> toggleBars()+ keyCode == android.view.KeyEvent.KEYCODE_DEL || keyCode == android.view.KeyEvent.KEYCODE_FORWARD_DEL -> clearCurrentLayer()+ // the brush a step smaller or bigger: 1%, with shift 5%, with alt 10%+ keyCode == android.view.KeyEvent.KEYCODE_LEFT_BRACKET || keyCode == android.view.KeyEvent.KEYCODE_RIGHT_BRACKET -> {+ val step = if (alt) 0.10f else if (shift) 0.05f else 0.01f+ val sign = if (keyCode == android.view.KeyEvent.KEYCODE_LEFT_BRACKET) -1f else 1f+ changeSize((size + sign * step).coerceIn(0f, 1f))+ }+ // arrows nudge what is being transformed a pixel at a time+ transforming && keyCode in listOf(+ android.view.KeyEvent.KEYCODE_DPAD_LEFT,+ android.view.KeyEvent.KEYCODE_DPAD_RIGHT,+ android.view.KeyEvent.KEYCODE_DPAD_UP,+ android.view.KeyEvent.KEYCODE_DPAD_DOWN,+ ) -> {+ val box = transformBox?.corners ?: return true+ if (box.size < 8) return true+ val cx = (0 until 4).map { box[it * 2] }.average().toFloat()+ val cy = (0 until 4).map { box[it * 2 + 1] }.average().toFloat()+ val far = 100_000f+ val (dx, dy) = when (keyCode) {+ android.view.KeyEvent.KEYCODE_DPAD_LEFT -> -far to 0f+ android.view.KeyEvent.KEYCODE_DPAD_RIGHT -> far to 0f+ android.view.KeyEvent.KEYCODE_DPAD_UP -> 0f to -far+ else -> 0f to far+ }+ session?.transformNudge(cx + dx, cy + dy)?.let { transformMoved(it) }+ }+ else -> return false+ }+ return true+ }++ /** Does [a], a QuickMenu button opened at window point [at]. */+ fun runQuickAction(a: QuickAction, at: Offset) {+ val current = layers.firstOrNull { it.current }+ when (a) {+ QuickAction.NONE -> Unit+ QuickAction.NEW_LAYER -> addLayer()+ QuickAction.DUPLICATE_LAYER -> current?.let(::duplicate)+ QuickAction.DELETE_LAYER -> current?.let(::delete)+ QuickAction.MERGE_DOWN -> current?.let(::mergeDown)+ QuickAction.CLEAR_LAYER -> clearCurrentLayer()+ QuickAction.FILL_LAYER -> current?.let(::fillLayer)+ QuickAction.SELECT_LAYER -> current?.let(::selectLayerContents)+ QuickAction.ALPHA_LOCK -> current?.let(::toggleAlphaLock)+ QuickAction.LAYER_VISIBILITY -> current?.let(::toggleVisible)+ QuickAction.COPY -> copyLayer()+ QuickAction.CUT -> cutLayer()+ QuickAction.PASTE -> paste()+ QuickAction.COPY_PASTE_MENU -> copyPasteOpen = true+ QuickAction.FLIP_HORIZONTAL -> flipCanvas(horizontal = true)+ QuickAction.FLIP_VERTICAL -> flipCanvas(horizontal = false)+ QuickAction.UNDO -> undo()+ QuickAction.REDO -> redo()+ QuickAction.PAINT -> select(ToolKind.PAINT)+ QuickAction.SMUDGE -> select(ToolKind.SMUDGE)+ QuickAction.ERASE -> select(ToolKind.ERASE)+ QuickAction.EYEDROPPER -> pickNext = true+ QuickAction.SWAP_COLORS -> swapColors()+ QuickAction.SELECTION -> toggleSelecting()+ QuickAction.INVERT_SELECTION -> invertSelection()+ QuickAction.TRANSFORM -> toggleTransform()+ QuickAction.ADJUSTMENTS -> adjustmentsPressed()+ QuickAction.COLORS -> toggle(Panel.COLOR)+ QuickAction.LAYERS -> toggle(Panel.LAYERS)+ QuickAction.BRUSHES -> toggle(Panel.BRUSHES)+ QuickAction.ACTIONS -> toggle(Panel.ACTIONS)+ QuickAction.INTERFACE -> toggleBars()+ QuickAction.FIT_CANVAS -> settleToFit()+ QuickAction.ADD_TEXT -> addText()+ QuickAction.QUICKSHAPE -> quickShapeLast()+ QuickAction.LAYER_SELECT -> layerSelectAt(at)+ QuickAction.DRAWING_GUIDE -> setGuideOn(guide?.on != true)+ }+ }++ /** Does what a gesture set to the QuickMenu does: opens it at [at], or closes it if open. */+ fun toggleQuickMenu(at: Offset) {+ quickMenuAt = if (quickMenuAt == null) at else null+ }++ /** The Copy & Paste panel (three fingers swiped down) is open. */+ var copyPasteOpen by mutableStateOf(false)++ /** Cut & Paste: what is selected (or the layer) cut out and put back as a new layer. */+ fun cutAndPaste() {+ cutLayer()+ paste()+ }++ /** Duplicate: the selection copied to a new layer, or without one the current layer. */+ fun duplicateCurrent() {+ if (hasSelection) {+ copyLayer()+ paste()+ } else {+ layers.firstOrNull { it.current }?.let(::duplicate)+ }+ }++ fun flipCanvas(horizontal: Boolean) {+ endQuickShape()+ session?.flipCanvas(horizontal)+ refresh()+ }++ /** A photo or picture file comes in as a new layer, fitted to the canvas, ready to transform. */+ fun insertPicture(uri: android.net.Uri) {+ val s = session ?: return+ closePanels()+ viewModelScope.launch {+ val image = withContext(Dispatchers.IO) { decodePicture(uri, io.github.artcraftandroid.procraft.ui.CanvasSpace.p3) }+ if (image == null) {+ message = "This picture can't be opened."+ return@launch+ }+ if (s.insertImage(image) != null) {+ refresh()+ toggleTransform()+ } else {+ message = noRoom()+ }+ }+ }++ /** Whether the picture at [uri] is in Display P3. */+ private fun pictureIsP3(uri: android.net.Uri): Boolean = runCatching {+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }+ getApplication<Application>().contentResolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, bounds) }+ bounds.outColorSpace == android.graphics.ColorSpace.get(android.graphics.ColorSpace.Named.DISPLAY_P3)+ }.getOrDefault(false)++ /**+ * A picture's straight RGBA pixels, at most [MAX_PICTURE] pixels on a side, its colours turned+ * into Display P3 ([p3]) or sRGB.+ */+ private fun decodePicture(uri: android.net.Uri, p3: Boolean): io.github.artcraftandroid.procraft.core.ThumbnailImage? = runCatching {+ val resolver = getApplication<Application>().contentResolver+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }+ resolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, bounds) }+ var sample = 1+ while (maxOf(bounds.outWidth, bounds.outHeight) / sample > MAX_PICTURE) sample *= 2+ val options = BitmapFactory.Options().apply {+ inSampleSize = sample+ inPremultiplied = false+ inPreferredConfig = Bitmap.Config.ARGB_8888+ inPreferredColorSpace = android.graphics.ColorSpace.get(if (p3) android.graphics.ColorSpace.Named.DISPLAY_P3 else android.graphics.ColorSpace.Named.SRGB)+ }+ val bitmap = resolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, options) } ?: return null+ val buffer = ByteBuffer.allocate(bitmap.width * bitmap.height * 4)+ bitmap.copyPixelsToBuffer(buffer)+ io.github.artcraftandroid.procraft.core.ThumbnailImage(bitmap.width.toUInt(), bitmap.height.toUInt(), buffer.array())+ }.getOrNull()++ // QuickShape++ /** The stroke being drawn was held still: it snaps to a shape if it looks like one. */+ fun quickShapeHold() {+ val info = session?.quickshapeHold() ?: return+ quickShape = info+ quickShapeEditing = false+ showNotice(snappedTo(info.kind))+ }++ /** What a stroke snapped to, for the band under the top bar. */+ private fun snappedTo(kind: QuickShapeKind): String = "Snapped to " + when (kind) {+ QuickShapeKind.LINE -> "a line"+ QuickShapeKind.POLYLINE -> "a polyline"+ QuickShapeKind.ARC -> "an arc"+ QuickShapeKind.ELLIPSE -> "an ellipse"+ QuickShapeKind.CIRCLE -> "a circle"+ QuickShapeKind.TRIANGLE -> "a triangle"+ QuickShapeKind.EQUILATERAL_TRIANGLE -> "an equilateral triangle"+ QuickShapeKind.QUADRILATERAL -> "a quadrilateral"+ QuickShapeKind.RECTANGLE -> "a rectangle"+ QuickShapeKind.SQUARE -> "a square"+ }++ /** The last stroke snaps to the shape it looks like, if nothing has been done since (a QuickShape trigger). */+ fun quickShapeLast() {+ val info = session?.quickshapeLast() ?: return+ quickShape = info+ quickShapeEditing = false+ showNotice(snappedTo(info.kind))+ refreshFlags()+ }++ fun chooseQuickShape(kind: QuickShapeKind) {+ quickShape = session?.quickshapeChoose(kind) ?: quickShape+ }++ fun moveQuickShapeHandle(index: Int, at: Offset) {+ quickShape = session?.quickshapeMoveHandle(index.toUInt(), at.x, at.y) ?: quickShape+ }++ /** The handle of the snapped shape under window point [p], while its handles show. */+ fun quickShapeHandleAt(p: Offset): Int? {+ val h = quickShape?.handles ?: return null+ if (!quickShapeEditing) return null+ return (0 until h.size / 2).minByOrNull { (Offset(h[it * 2], h[it * 2 + 1]) - p).getDistance() }+ ?.takeIf { (Offset(h[it * 2], h[it * 2 + 1]) - p).getDistance() <= QUICKSHAPE_REACH_DP * density }+ }++ /** Keeps the snapped shape as drawn. */+ fun endQuickShape() {+ if (quickShape == null) return+ session?.quickshapeDone()+ quickShape = null+ quickShapeEditing = false+ refreshFlags()+ }++ fun toolPressed(tool: ToolKind) {+ endQuickShape()+ if (transforming || selecting || adjustment != null) {+ // leaving transform, selection or an adjustment for a tool keeps what they made, and only picks the tool+ endTransform(true)+ closeSelecting()+ endAdjustment(true)+ select(tool)+ return+ }+ if (this.tool == tool) {+ currentBrush?.let { shownSet = it.set.toInt() }+ toggle(Panel.BRUSHES)+ } else {+ select(tool)+ if (panel == Panel.BRUSHES) panel = Panel.NONE+ }+ }++ /**+ * A tool button held: that tool takes the brush the current one has (erasing with the painting+ * brush, say), and becomes the tool.+ */+ fun toolHeld(target: ToolKind) {+ val s = session ?: return+ val brush = currentBrush ?: return+ if (transforming || selecting || adjustment != null || target == tool) return+ endQuickShape()+ select(target)+ if (s.selectBrush(brush.set, brush.index)) {+ currentBrush = s.currentBrush()+ readSliders()+ brushSets = s.brushLibrary()+ readSetChoices()+ keepChoices(s)+ }+ if (panel == Panel.BRUSHES) panel = Panel.NONE+ showNotice(+ when (target) {+ ToolKind.PAINT -> "Painting"+ ToolKind.SMUDGE -> "Smudging"+ ToolKind.ERASE -> "Erasing"+ } + " with the current brush",+ )+ }++ fun showSet(index: Int) {+ shownSet = index+ // the set's last chosen brush becomes the current one, as choosing it again would+ val choice = setChoice[index] ?: return+ brushSets.getOrNull(index)?.brushes?.getOrNull(choice)?.let { chooseBrush(it) }+ }++ // ---- time-lapse ----++ private var timeLapse: TimeLapse? = null+ var timeLapseRecording by mutableStateOf(true)+ private set++ /** The replay shows over everything. */+ var timeLapseReplaying by mutableStateOf(false)++ /** Frames recorded, for the replay. */+ fun timeLapseFrames() = timeLapse?.count ?: 0++ fun timeLapseFrame(i: Int): Bitmap? = timeLapse?.frame(i)++ fun changeTimeLapseRecording(on: Boolean) {+ timeLapse?.recording = on+ timeLapseRecording = on+ }++ private var frameJob: Job? = null+ private var frameStale = false++ /** Records the canvas as a time-lapse frame, one at a time while changes come. */+ private fun recordFrame() {+ val t = timeLapse ?: return+ if (!t.recording) return+ if (frameJob?.isActive == true) {+ frameStale = true+ return+ }+ val s = session ?: return+ frameJob = viewModelScope.launch {+ do {+ frameStale = false+ withContext(Dispatchers.Default) {+ // frames as large as the video they make+ val shot = s.canvasThumbnail((timeLapse?.settings?.side ?: TimeLapse.FRAME_SIDE).toUInt()) ?: return@withContext+ t.record(shot.rgba, shot.width.toInt(), shot.height.toInt())+ }+ } while (frameStale)+ }+ }++ /** The time-lapse as a video in the cache, to share: all of it, or [seconds] long. */+ suspend fun exportTimeLapse(seconds: Int?): File? {+ val t = timeLapse ?: return null+ val s = session ?: return null+ return withContext(Dispatchers.IO) {+ val dir = File(getApplication<Application>().cacheDir, "exports").apply { mkdirs() }+ val base = s.name().filter { it.isLetterOrDigit() || it in " _-" }.trim().ifEmpty { "Untitled Artwork" }+ val out = File(dir, "$base.mp4")+ out.delete()+ if (t.export(out, seconds)) out else null+ }+ }++ // ---- crop and resize ----++ /** The rectangle being kept (canvas pixels: left, top, width, height), or null outside crop. */+ var cropRect by mutableStateOf<androidx.compose.ui.geometry.Rect?>(null)+ private set+ var cropAngle by mutableStateOf(0f)+ private set+ var cropResample by mutableStateOf(false)+ private set+ /** With resampling, the size what is kept becomes. */+ var cropSize by mutableStateOf(0 to 0)+ private set+ var cropAspectLocked by mutableStateOf(false)+ var cropSettingsOpen by mutableStateOf(false)+ var cropSnapping by mutableStateOf(false)+ /** The canvas's dots per inch, as the crop's settings have it. */+ var cropDpi by mutableStateOf(132f)+ private set++ fun changeCropDpi(dpi: Float) {+ if (dpi.isFinite() && dpi >= 1f) cropDpi = dpi.coerceAtMost(9999f)+ }++ /** The canvas's size, pixels. */+ fun canvasSize(): Pair<Int, Int> = session?.info()?.let { it.width.toInt() to it.height.toInt() } ?: (0 to 0)++ fun beginCrop() {+ closePanels()+ val (w, h) = canvasSize()+ if (w == 0) return+ // the canvas fitted to the screen and shrunk, in the middle, so the frame's handles are clear+ session?.fitCanvasScaled(CROP_SCALE)+ cropDpi = session?.info()?.dpi ?: 132f+ refreshView()+ followView()+ cropRect = androidx.compose.ui.geometry.Rect(0f, 0f, w.toFloat(), h.toFloat())+ cropAngle = 0f+ cropResample = false+ cropSize = w to h+ cropSettingsOpen = false+ }++ fun resetCrop() = beginCrop()++ fun changeCropRect(r: androidx.compose.ui.geometry.Rect) {+ val w = r.width.coerceAtLeast(1f)+ val h = r.height.coerceAtLeast(1f)+ cropRect = androidx.compose.ui.geometry.Rect(r.left, r.top, r.left + w, r.top + h)+ if (!cropResample) cropSize = w.roundToInt() to h.roundToInt()+ }++ fun changeCropAngle(radians: Float) {+ cropAngle = radians+ }++ fun changeCropResample(on: Boolean) {+ cropResample = on+ cropRect?.let { cropSize = it.width.roundToInt() to it.height.roundToInt() }+ }++ /** A width or height typed in: resampling, it is the new size; otherwise the kept rectangle's. */+ fun changeCropSize(width: Int?, height: Int?) {+ val r = cropRect ?: return+ val (w0, h0) = cropSize+ var w = (width ?: w0).coerceIn(1, MAX_CANVAS_EDGE)+ var h = (height ?: h0).coerceIn(1, MAX_CANVAS_EDGE)+ if (cropAspectLocked && w0 > 0 && h0 > 0) {+ if (width != null) h = (w * h0.toFloat() / w0).roundToInt().coerceIn(1, MAX_CANVAS_EDGE)+ else if (height != null) w = (h * w0.toFloat() / h0).roundToInt().coerceIn(1, MAX_CANVAS_EDGE)+ }+ cropSize = w to h+ if (!cropResample) cropRect = androidx.compose.ui.geometry.Rect(r.left, r.top, r.left + w, r.top + h)+ }++ /** How many layers a canvas of the size kept can hold. */+ fun cropLayerCount(): Int {+ val (w, h) = cropSize+ val bytes = w.toLong() * h.toLong() * 4+ return if (bytes <= 0) 0 else (LAYER_BUDGET / bytes).toInt().coerceAtMost(999)+ }++ fun endCrop(keep: Boolean) {+ val r = cropRect ?: return+ val s = session+ cropRect = null+ cropSettingsOpen = false+ // either way the canvas is fitted to the screen again: cancelled, growing back into place+ if (!keep || s == null) {+ s?.easeToFit()+ refreshView()+ followView()+ return+ }+ s.fitView()+ val (w, h) = cropSize+ if (abs(cropDpi - (s.info().dpi)) > 0.01f) s.setDpi(cropDpi)+ // nothing to crop: the whole canvas, unturned, at its size+ val (cw, ch) = canvasSize()+ val same = r.left == 0f && r.top == 0f && r.width.roundToInt() == cw && r.height.roundToInt() == ch && cropAngle == 0f && w == cw && h == ch+ if (same) {+ refresh()+ refreshView()+ return+ }+ if (s.cropCanvas(r.left, r.top, r.width, r.height, cropAngle, cropResample, w.toUInt(), h.toUInt())) {+ thumbnails.clear()+ refresh()+ refreshView()+ if (panel == Panel.LAYERS) refreshThumbnails()+ }+ }++ // ---- the reference window ----++ enum class ReferenceMode { CANVAS, IMAGE, FACE }++ var referenceOn by mutableStateOf(false)+ private set+ var referenceMode by mutableStateOf(ReferenceMode.CANVAS)+ private set++ /** The whole canvas as it is, kept up to date while the window shows it. */+ var referenceCanvas by mutableStateOf<ImageBitmap?>(null)+ private set+ var referenceImage by mutableStateOf<ImageBitmap?>(null)+ private set++ /** Where the window is (window pixels), and the size of its picture. */+ var referenceOffset by mutableStateOf(Offset.Unspecified)+ private set+ var referenceSize by mutableStateOf(DpSize(REFERENCE_WIDTH_DP.dp, REFERENCE_HEIGHT_DP.dp))+ private set++ private var referenceJob: Job? = null+ private var referenceStale = false++ fun changeReferenceOn(on: Boolean) {+ referenceOn = on+ if (on) refreshReference()+ }++ fun changeReferenceMode(mode: ReferenceMode) {+ referenceMode = mode+ refreshReference()+ }++ /** The window's first place on a screen [width] × [height] (pixels), [tall] (pixels) tall in all: in the middle, near the bottom. */+ fun placeReference(width: Float, height: Float, tall: Float) {+ if (referenceOffset != Offset.Unspecified) return+ val w = referenceSize.width.value * density+ referenceOffset = Offset((width - w) / 2f, (height - REFERENCE_BOTTOM_DP * density - tall).coerceAtLeast(0f))+ }++ fun moveReference(by: Offset) {+ referenceOffset += by+ }++ /** A drag on a size handle; from the left one the window's left edge moves. */+ fun resizeReference(dx: Dp, dy: Dp, fromLeft: Boolean) {+ val old = referenceSize+ val w = (old.width + if (fromLeft) -dx else dx).coerceIn(REFERENCE_MIN_DP.dp, REFERENCE_MAX_DP.dp)+ val h = (old.height + dy).coerceIn(REFERENCE_MIN_DP.dp, REFERENCE_MAX_DP.dp)+ if (fromLeft) referenceOffset = referenceOffset.copy(x = referenceOffset.x + (old.width - w).value * density)+ referenceSize = DpSize(w, h)+ }++ fun importReference(uri: android.net.Uri) {+ viewModelScope.launch {+ val image = withContext(Dispatchers.IO) {+ runCatching {+ val resolver = getApplication<Application>().contentResolver+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }+ resolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, bounds) }+ var sample = 1+ while (maxOf(bounds.outWidth, bounds.outHeight) / sample > MAX_PICTURE) sample *= 2+ resolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, BitmapFactory.Options().apply { inSampleSize = sample }) }+ }.getOrNull()+ }+ if (image != null) referenceImage = image.asImageBitmap() else message = "This picture can't be opened."+ }+ }++ fun clearReference() {+ referenceImage = null+ }++ /** Reads the canvas again for the window, at most every so often while changes come. */+ fun refreshReference() {+ if (!referenceOn || referenceMode != ReferenceMode.CANVAS) return+ if (referenceJob?.isActive == true) {+ referenceStale = true+ return+ }+ val s = session ?: return+ referenceJob = viewModelScope.launch {+ do {+ referenceStale = false+ val image = withContext(Dispatchers.Default) {+ val t = s.canvasThumbnail(REFERENCE_PIXELS.toUInt()) ?: return@withContext null+ val bitmap = io.github.artcraftandroid.procraft.ui.CanvasSpace.tag(Bitmap.createBitmap(t.width.toInt(), t.height.toInt(), Bitmap.Config.ARGB_8888))+ bitmap.copyPixelsFromBuffer(ByteBuffer.wrap(t.rgba))+ bitmap.asImageBitmap()+ }+ if (image != null) referenceCanvas = image+ kotlinx.coroutines.delay(REFERENCE_INTERVAL_MS)+ } while (referenceStale)+ }+ }++ // ---- text ----++ /** The text being edited, as it stands; null when no text is being edited. */+ var textInfo by mutableStateOf<TextInfo?>(null)+ private set++ /** What the hidden text field holds: the text with its caret and selection. */+ var textField by mutableStateOf(TextFieldValue(""))+ private set++ /** The style sheet (fonts, styles, design, attributes) is open over the keyboard. */+ var textStyleOpen by mutableStateOf(false)++ /** The text as it was when the style sheet opened, for its Cancel. */+ private var textBeforeStyle: TextInfo? = null++ /** The canvas's dots per inch. */+ fun canvasDpi(): Float = session?.info()?.dpi?.coerceAtLeast(1f) ?: 132f++ fun openTextStyle() {+ textBeforeStyle = textInfo+ textStyleOpen = true+ }++ /** The style sheet's Cancel: its changes go back (the text stays), and the keyboard returns. */+ fun cancelTextStyle() {+ textBeforeStyle?.let { before -> changeText { before.copy(text = it.text) } }+ textStyleOpen = false+ }++ private val systemClipboard get() = getApplication<Application>().getSystemService(android.content.ClipboardManager::class.java)++ /** Copies the selected text (all of it if none is), and with [cut] takes it out. */+ fun copyText(cut: Boolean) {+ val v = textField+ val sel = if (v.selection.collapsed) TextRange(0, v.text.length) else v.selection+ val part = v.text.substring(sel.min, sel.max)+ if (part.isEmpty()) return+ systemClipboard?.setPrimaryClip(android.content.ClipData.newPlainText("Text", part))+ if (cut) changeTextField(TextFieldValue(v.text.removeRange(sel.min, sel.max), TextRange(sel.min)))+ }++ /** Puts the copied text in place of the selection. */+ fun pasteText() {+ val add = systemClipboard?.primaryClip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.coerceToText(getApplication())?.toString() ?: return+ val v = textField+ val text = v.text.replaceRange(v.selection.min, v.selection.max, add)+ changeTextField(TextFieldValue(text, TextRange(v.selection.min + add.length)))+ }++ private val fontDir get() = File(getApplication<Application>().filesDir, "fonts")++ /** Copies a font file into the app and offers it; the text being edited takes it. */+ fun importFont(uri: android.net.Uri) {+ viewModelScope.launch {+ val family = withContext(Dispatchers.IO) {+ runCatching {+ val resolver = getApplication<Application>().contentResolver+ val name = resolver.query(uri, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->+ if (c.moveToFirst()) c.getString(0) else null+ } ?: "Font.ttf"+ val safe = name.filter { it.isLetterOrDigit() || it in " ._-" }.ifEmpty { "Font.ttf" }+ val file = File(fontDir.apply { mkdirs() }, if (safe.substringAfterLast('.', "").lowercase() in listOf("ttf", "otf")) safe else "$safe.ttf")+ resolver.openInputStream(uri)?.use { input -> file.outputStream().use { input.copyTo(it) } }+ // a file that isn't a font is dropped+ if (android.graphics.Typeface.createFromFile(file) == android.graphics.Typeface.DEFAULT && file.length() == 0L) file.delete()+ TextRenderer.FILE + file.path+ }.getOrNull()+ }+ TextRenderer.loadImported(fontDir)+ if (family != null && TextRenderer.families.any { it.family == family }) {+ changeText { it.copy(font = family) }+ showNotice("Font imported")+ }+ }+ }++ /** A stroke landed on a text layer: offer to rasterize it. */+ var askRasterize by mutableStateOf(false)++ private var textJob: Job? = null+ private var textGeneration = 0++ /** New text in the middle of the canvas, all of it selected for typing over. */+ fun addText() {+ val s = session ?: return+ closePanels()+ val c = s.info()+ val rgb = colorRgb()+ // a medium sans about an eighth of the canvas's width, in a box as wide as the canvas,+ // centred where the canvas shows above the keyboard (about a quarter of the way down)+ val w = c.width.toFloat()+ var info = TextInfo(+ text = "Text", font = "sans-serif", style = "Medium",+ size = w * TEXT_SIZE_OF_WIDTH,+ kerning = 0f, tracking = 0f, leading = 0f, baseline = 0f, opacity = 1f,+ align = TextAlignment.CENTER, underline = false, outline = false, vertical = false, allCaps = false,+ r = ((rgb shr 16) and 255) / 255f, g = ((rgb shr 8) and 255) / 255f, b = (rgb and 255) / 255f,+ x = w * (1f - TEXT_BOX_OF_WIDTH) / 2f, y = 0f, width = w * TEXT_BOX_OF_WIDTH,+ )+ val box = TextRenderer.bounds(info)+ val h = c.height.toFloat()+ val middle = windowToCanvas(Offset(windowSize.x / 2f, windowSize.y * TEXT_SCREEN_Y))?.y ?: (h / 4f)+ info = info.copy(y = (middle - box.height() / 2f).coerceIn(0f, (h - box.height()).coerceAtLeast(0f)))+ if (s.textBegin(null, info) == null) {+ message = noRoom()+ return+ }+ startText(info)+ }++ /** Edits a text layer's text again. */+ fun editText(l: LayerInfo) {+ val s = session ?: return+ val info = s.layerText(l.id) ?: return+ closePanels()+ s.textBegin(l.id, info) ?: return+ startText(info)+ }++ private fun startText(info: TextInfo) {+ textInfo = info+ textField = TextFieldValue(info.text, TextRange(0, info.text.length))+ textStyleOpen = false+ renderText()+ refresh()+ }++ fun changeTextField(v: TextFieldValue) {+ textField = v+ if (v.text != textInfo?.text) changeText { it.copy(text = v.text) }+ }++ fun changeText(f: (TextInfo) -> TextInfo) {+ val info = textInfo?.let(f) ?: return+ textInfo = info+ session?.setText(info)+ renderText()+ }++ /** Draws the text into its layer off the main thread; only the latest drawing lands. */+ private fun renderText() {+ val s = session ?: return+ val info = textInfo ?: return+ val c = s.info()+ val generation = ++textGeneration+ textJob?.cancel()+ textJob = viewModelScope.launch {+ val pixels = withContext(Dispatchers.Default) { TextRenderer.render(info, c.width.toInt(), c.height.toInt()) }+ if (generation == textGeneration) s.putTextPixels(pixels)+ }+ }++ /** Ends editing text: [keep] makes it one undo step, otherwise it goes back. */+ fun endText(keep: Boolean) {+ val s = session ?: return+ if (textInfo == null) return+ val job = textJob+ textInfo = null+ textStyleOpen = false+ viewModelScope.launch {+ // the last drawing lands first+ job?.join()+ s.textEnd(keep)+ refresh()+ if (panel == Panel.LAYERS) refreshThumbnails()+ }+ }++ /** Moves the text being edited by a drag from window point [from] to [to]. */+ fun moveText(from: Offset, to: Offset) {+ val a = windowToCanvas(from) ?: return+ val b = windowToCanvas(to) ?: return+ changeText { it.copy(x = it.x + b.x - a.x, y = it.y + b.y - a.y) }+ }++ /** Whether the current layer holds editable text. */+ fun currentIsText() = layers.firstOrNull { it.current }?.text == true++ /** Why the current layer turned a change away. */+ enum class Blocked { LOCKED, HIDDEN, EMPTY_GROUP }++ /** The current layer turned a change away, and why: a dialog offers to unlock or show it, or open Layers. */+ var blocked by mutableStateOf<Pair<Blocked, LayerInfo>?>(null)+ private set++ /**+ * Whether the current layer takes a change (a stroke, a transform, an adjustment, clearing,+ * cutting); if not (locked, hidden, or an empty group), a dialog says why. What was tried is+ * not done afterwards.+ */+ fun currentTakesChanges(): Boolean {+ val l = layers.firstOrNull { it.current } ?: return true+ val why = when {+ l.locked -> Blocked.LOCKED+ !l.visible -> Blocked.HIDDEN+ l.kind == LayerType.GROUP && layers.none { it.parent == l.id } -> Blocked.EMPTY_GROUP+ else -> return true+ }+ blocked = why to l+ return false+ }++ /** The dialog's answer: unlock or show the layer ([fix]), open Layers ([openLayers]), or neither. */+ fun answerBlocked(fix: Boolean, openLayers: Boolean) {+ val (why, l) = blocked ?: return+ blocked = null+ if (fix) {+ when (why) {+ Blocked.LOCKED -> toggleLocked(l)+ Blocked.HIDDEN -> toggleVisible(l)+ Blocked.EMPTY_GROUP -> Unit+ }+ }+ if (openLayers) panel = Panel.LAYERS+ }++ fun rasterize(l: LayerInfo) {+ layerChange { it.rasterizeLayer(l.id) }+ showNotice("Text rasterized", warning = true)+ }++ // editing the library++ /** The set whose name is being edited in place. */+ var renamingSet by mutableStateOf<Int?>(null)++ /** The studio is open on a brush just made: cancelling throws it away. */+ private var studioNew = false++ /** After a change to the library: read it again, keep it, and draw previews again (they go by place). */+ private fun libraryChanged() {+ val s = session ?: return+ brushSets = s.brushLibrary()+ currentBrush = s.currentBrush()+ readSetChoices()+ shownSet = shownSet.coerceIn(0, (brushSets.size - 1).coerceAtLeast(0))+ readSliders()+ previews.clear()+ shadedNames.clear()+ brushPrefs.edit().putString(BRUSH_LIBRARY, s.savedBrushLibrary()).putString(BRUSH_CHOICES, s.savedBrushChoices()).apply()+ }++ fun duplicateBrush(b: BrushInfo) {+ session?.duplicateBrush(b.set, b.index) ?: return+ libraryChanged()+ }++ fun deleteBrush(b: BrushInfo) {+ if (session?.deleteBrush(b.set, b.index) == true) libraryChanged()+ }++ /** Moves [b] to place [index] of set [set] (a brush dragged onto a set, or along its own). */+ fun moveBrush(b: BrushInfo, set: Int, index: Int) {+ if (set == b.set.toInt() && index == b.index.toInt()) return+ if (session?.moveBrush(b.set, b.index, set.toUInt(), index.toUInt()) == true) libraryChanged()+ }++ /** A new brush at the top of the shown set, opened in the studio. */+ fun newBrush() {+ val s = session ?: return+ s.newBrush(shownSet.toUInt()) ?: return+ libraryChanged()+ studioNew = true+ openStudio()+ }++ /** A new set at the top of the library, shown, with its name ready to edit. */+ fun newBrushSet() {+ val s = session ?: return+ shownSet = s.newBrushSet().toInt()+ libraryChanged()+ renamingSet = shownSet+ }++ fun renameBrushSet(i: Int, name: String) {+ renamingSet = null+ if (session?.renameBrushSet(i.toUInt(), name) == true) libraryChanged()+ }++ fun changeBrushSetIcon(i: Int, icon: Int) {+ if (session?.setBrushSetIcon(i.toUInt(), icon.toUInt()) == true) libraryChanged()+ }++ fun duplicateBrushSet(i: Int) {+ shownSet = session?.duplicateBrushSet(i.toUInt())?.toInt() ?: return+ libraryChanged()+ }++ fun deleteBrushSet(i: Int) {+ if (session?.deleteBrushSet(i.toUInt()) != true) return+ if (shownSet >= i) shownSet = (shownSet - 1).coerceAtLeast(0)+ libraryChanged()+ }++ /** A brush, or (no brush) the shown set, written to a brush or set file to share. */+ suspend fun brushFileToShare(b: BrushInfo?): File? = withContext(Dispatchers.IO) {+ val s = session ?: return@withContext null+ val (name, bytes) = if (b != null) {+ b.name to (s.brushAsFile(b.set, b.index) ?: return@withContext null)+ } else {+ val set = brushSets.getOrNull(shownSet) ?: return@withContext null+ set.name to (s.brushSetAsFile(shownSet.toUInt()) ?: return@withContext null)+ }+ runCatching {+ val dir = File(getApplication<Application>().cacheDir, "exports").apply { mkdirs() }+ val safe = name.replace(Regex("[^A-Za-z0-9 _-]"), "_").ifBlank { "Brush" }+ File(dir, safe + if (b != null) ".$BRUSH_EXTENSION" else ".$BRUSH_SET_EXTENSION").apply { writeBytes(bytes) }+ }.getOrNull()+ }++ /** A brush or set file from elsewhere: it joins the library and its set is shown. */+ fun importBrushes(uri: android.net.Uri) {+ viewModelScope.launch {+ val bytes = withContext(Dispatchers.IO) {+ runCatching { getApplication<Application>().contentResolver.openInputStream(uri)?.use { it.readBytes() } }.getOrNull()+ } ?: return@launch+ if (!addBrushes(bytes)) message = "This file has no brushes in it."+ }+ }++ /**+ * Brushes from a brush or set file [bytes] into the library (shown), or, with no canvas open,+ * kept until one opens; false if the file has none.+ */+ private suspend fun addBrushes(bytes: ByteArray): Boolean {+ val s = session+ if (s == null) {+ if (!isBrushFile(bytes)) return false+ withContext(Dispatchers.IO) {+ pendingBrushDir.mkdirs()+ File(pendingBrushDir, "${System.nanoTime()}.$BRUSH_EXTENSION").writeBytes(bytes)+ }+ message = "Brushes will be added to the library when a canvas opens."+ return true+ }+ val set = s.importBrushes(bytes)+ // files of ours, from before+ ?: runCatching { s.importBrushFile(shownSet.toUInt(), bytes.decodeToString()) }.getOrNull()+ ?: return false+ shownSet = set.toInt()+ libraryChanged()+ return true+ }++ /** Brush files kept while no canvas was open, added now. */+ private fun addPendingBrushes(s: CanvasSession) {+ val files = pendingBrushDir.listFiles()?.sortedBy { it.name } ?: return+ var any = false+ for (f in files) {+ runCatching { s.importBrushes(f.readBytes()) }.getOrNull()?.let {+ shownSet = it.toInt()+ any = true+ }+ f.delete()+ }+ if (any) {+ libraryChanged()+ message = "Brushes added to the library."+ }+ }++ private val pendingBrushDir get() = File(getApplication<Application>().filesDir, "pending-brushes")++ /** Whether [bytes] is a zip holding a brush or a set of them. */+ private fun isBrushFile(bytes: ByteArray): Boolean = runCatching {+ java.util.zip.ZipInputStream(bytes.inputStream()).use { zip ->+ generateSequence { zip.nextEntry }.any { it.name == "Brush.archive" || it.name == "brushset.plist" || it.name.endsWith("/Brush.archive") }+ }+ }.getOrDefault(false)++ fun chooseBrush(b: BrushInfo) {+ val s = session ?: return+ val before = currentBrush+ if (s.selectBrush(b.set, b.index)) {+ // the set left behind keeps showing the brush it had+ before?.let { setChoice[it.set.toInt()] = it.index.toInt() }+ currentBrush = s.currentBrush()+ setChoice[b.set.toInt()] = b.index.toInt()+ readSliders()+ keepChoices(s)+ }+ }++ /** Each set's last chosen brush, which it shows highlighted (by place in the set). */+ val setChoice = mutableStateMapOf<Int, Int>()++ /** Each set's last choice, as the library read last has it. */+ private fun readSetChoices() {+ setChoice.clear()+ brushSets.forEachIndexed { i, set -> set.chosen?.let { setChoice[i] = it.toInt() } }+ }++ /** Keeps the tools' brushes, the sets' choices and each brush's sliders for the next session. */+ private fun keepChoices(s: CanvasSession) {+ brushPrefs.edit().putString(BRUSH_CHOICES, s.savedBrushChoices()).apply()+ }++ /** Whether [b] shows highlighted: the current brush, or its set's last choice. */+ fun highlighted(b: BrushInfo): Boolean {+ val c = currentBrush+ if (c != null && c.set == b.set) return c.index == b.index+ return setChoice[b.set.toInt()] == b.index.toInt()+ }++ // the brush studio++ fun studio(key: String): Float = studioValues[key] ?: 0f++ /** Opens the studio on the current tool's brush. */+ fun openStudio() {+ val s = session ?: return+ // the brush library stays open under it, so Cancel and Done go back to it+ if (panel != Panel.BRUSHES) closePanels()+ studioName = s.studioBegin()+ readStudio()+ studioOpen = true+ }++ private fun readStudio() {+ val s = session ?: return+ val keys = io.github.artcraftandroid.procraft.ui.STUDIO_KEYS+ s.studioSettings(keys).forEachIndexed { i, v -> studioValues[keys[i]] = v }+ studioCurve = s.studioCurve().chunked(2).filter { it.size == 2 }.map { Offset(it[0], it[1]) }+ readStudioSources()+ readStudioAbout()+ refreshStudioPreview()+ }++ /** Who made the studio's brush, and when its reset point was made: its About page. */+ class BrushAbout(val author: String, val picture: ImageBitmap?, val signature: ImageBitmap?, val resetMade: Long?)++ var studioAbout by mutableStateOf<BrushAbout?>(null)+ private set++ private fun readStudioAbout() {+ val a = session?.studioAbout() ?: return+ val picture = { png: ByteArray? -> png?.let { android.graphics.BitmapFactory.decodeByteArray(it, 0, it.size)?.asImageBitmap() } }+ studioAbout = BrushAbout(a.author, picture(a.picture), picture(a.signature), a.resetMade)+ }++ /** Sets the studio's brush aside as it is now, for resetting it to go back to. */+ fun newResetPoint() {+ session?.studioNewResetPoint()+ readStudioAbout()+ }++ fun setStudio(key: String, value: Float) {+ studioValues[key] = value+ session?.setStudioSetting(key, value)+ // the spacing sets how big the brush may be, so where the size controls sit+ if (key == "spacing") session?.let { s ->+ val keys = listOf("max_size", "min_size", "most_size")+ s.studioSettings(keys).forEachIndexed { i, v -> studioValues[keys[i]] = v }+ }+ refreshStudioPreview()+ syncPad()+ }++ // the studio brush's shape and grain images++ /** The images the studio brush's shape and grain use (white on black), for their rows and editors. */+ var studioShapeSource by mutableStateOf<ImageBitmap?>(null)+ private set+ var studioGrainSource by mutableStateOf<ImageBitmap?>(null)+ private set++ /** The shape (false) or grain (true) editor is open. */+ var sourceEditing by mutableStateOf<Boolean?>(null)++ /** The shipped shape and grain images, by name, for the source library. */+ val shapeLibrary by lazy { io.github.artcraftandroid.procraft.core.sourceLibrary(false).map { it.name to grayBitmap(it.pixels) } }+ val grainLibrary by lazy { io.github.artcraftandroid.procraft.core.sourceLibrary(true).map { it.name to grayBitmap(it.pixels) } }++ private fun readStudioSources() {+ val s = session ?: return+ val shape = sourceBitmap(s.studioSource(false), shape = true)+ val grain = sourceBitmap(s.studioSource(true), shape = false)+ studioShapeSource = shape?.let { small(it, SOURCE_ROW_PX) }+ studioGrainSource = grain?.let { small(it, SOURCE_ROW_PX) }+ studioShapeSourceBig = shape?.let { small(it, SOURCE_BOX_PX) }+ studioGrainSourceBig = grain?.let { small(it, SOURCE_BOX_PX) }+ }++ /** The same images as big as the landscape studio's square shows them. */+ var studioShapeSourceBig by mutableStateOf<ImageBitmap?>(null)+ private set+ var studioGrainSourceBig by mutableStateOf<ImageBitmap?>(null)+ private set++ /** [image] shrunk by halves to about [side] pixels across, each step averaging, so fine detail evens out. */+ private fun small(image: ImageBitmap, side: Int): ImageBitmap {+ var b = image.asAndroidBitmap()+ while (b.width >= side * 2) b = Bitmap.createScaledBitmap(b, b.width / 2, b.height / 2, true)+ return b.asImageBitmap()+ }++ /** A square greyscale image (white = paint) as a bitmap, white on black; none if it is empty. */+ private fun grayBitmap(pixels: ByteArray): ImageBitmap? {+ val n = kotlin.math.sqrt(pixels.size.toDouble()).toInt()+ if (n <= 0 || n * n != pixels.size) return null+ val argb = IntArray(n * n) { i -> (pixels[i].toInt() and 0xFF).let { v -> (0xFF shl 24) or (v shl 16) or (v shl 8) or v } }+ return Bitmap.createBitmap(argb, n, n, Bitmap.Config.ARGB_8888).asImageBitmap()+ }++ /** The image the studio brush's shape (or [grain]) uses now: square greyscale, white = paint; empty for the round tip. */+ fun studioSourcePixels(grain: Boolean): ByteArray = session?.studioSource(grain) ?: ByteArray(0)++ /** [pixels] made to repeat without seams (the grain editor's Auto repeat). */+ fun repeatSource(pixels: ByteArray, scale: Float, rotation: Float, overlap: Float, hardness: Float, mirror: Boolean, pyramid: Boolean): ByteArray =+ io.github.artcraftandroid.procraft.core.repeatableSource(pixels, scale, rotation, overlap, hardness, mirror, pyramid)++ /** A square greyscale image as the editors show it: a [shape] white over what is behind, a grain as its greys. */+ fun sourceBitmap(pixels: ByteArray, shape: Boolean): ImageBitmap? {+ val n = kotlin.math.sqrt(pixels.size.toDouble()).toInt()+ if (n <= 0 || n * n != pixels.size) return null+ val argb = IntArray(n * n) { i ->+ val v = pixels[i].toInt() and 0xFF+ if (shape) (v shl 24) or 0xFFFFFF else (0xFF shl 24) or (v shl 16) or (v shl 8) or v+ }+ return Bitmap.createBitmap(argb, n, n, Bitmap.Config.ARGB_8888).asImageBitmap()+ }++ /** Shipped image [index] of the source library. */+ fun librarySource(grain: Boolean, index: Int): ByteArray =+ io.github.artcraftandroid.procraft.core.sourceLibrary(grain).getOrNull(index)?.pixels ?: ByteArray(0)++ /** [bitmap] fitted into the square on black, by its lightness. */+ private fun sourceFrom(bitmap: Bitmap): ByteArray {+ val n = io.github.artcraftandroid.procraft.core.sourceSize().toInt()+ val square = Bitmap.createBitmap(n, n, Bitmap.Config.ARGB_8888)+ val canvas = android.graphics.Canvas(square)+ canvas.drawColor(android.graphics.Color.BLACK)+ val scale = minOf(n / bitmap.width.toFloat(), n / bitmap.height.toFloat())+ val (w, h) = bitmap.width * scale to bitmap.height * scale+ canvas.drawBitmap(bitmap, null, android.graphics.RectF((n - w) / 2f, (n - h) / 2f, (n + w) / 2f, (n + h) / 2f), android.graphics.Paint(android.graphics.Paint.FILTER_BITMAP_FLAG))+ val argb = IntArray(n * n)+ square.getPixels(argb, 0, n, 0, 0, n, n)+ return ByteArray(n * n) { i ->+ val c = argb[i]+ ((((c shr 16) and 255) * 54 + ((c shr 8) and 255) * 183 + (c and 255) * 19) shr 8).toByte()+ }+ }++ /** A picture from elsewhere as a source image; none if it can't be read. */+ suspend fun decodeSource(uri: android.net.Uri): ByteArray? {+ val bitmap = withContext(Dispatchers.IO) {+ runCatching {+ val resolver = getApplication<Application>().contentResolver+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }+ resolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, bounds) }+ var sample = 1+ while (maxOf(bounds.outWidth, bounds.outHeight) / sample > 2048) sample *= 2+ resolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, BitmapFactory.Options().apply { inSampleSize = sample }) }+ }.getOrNull()+ }+ if (bitmap == null) {+ message = "This picture can't be opened."+ return null+ }+ return sourceFrom(bitmap)+ }++ /** A picture on the clipboard as a source image; none if there isn't one. */+ suspend fun pastedSource(): ByteArray? {+ val uri = systemClipboard?.primaryClip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.uri+ if (uri == null) {+ message = "There's no picture to paste."+ return null+ }+ return decodeSource(uri)+ }++ /** The editor's tick: the studio brush's shape (or [grain]) becomes [pixels], or shipped image [shipped]. */+ fun keepStudioSource(grain: Boolean, pixels: ByteArray, shipped: Int?) {+ val s = session ?: return+ val changed = when {+ shipped != null -> s.setStudioShippedSource(grain, shipped.toUInt())+ pixels.isNotEmpty() -> s.setStudioSource(grain, pixels)+ else -> false+ }+ sourceEditing = null+ if (changed) sourceChanged()+ }++ private fun sourceChanged() {+ readStudioSources()+ refreshStudioPreview()+ syncPad()+ }++ /** The drawing pad's canvas is made: dark, painting with the brush being edited, keeping its strokes. */+ fun startPad(p: CanvasSession) {+ pad = p+ p.setBackgroundColor(PAD_BACK, PAD_BACK, PAD_BACK, true)+ p.keepStrokes()+ syncPad()+ }++ /** The pad has drawn its first frame: it shows the brush's sample scribble. */+ fun padReady(p: CanvasSession) {+ if (pad === p) p.drawSampleScribble()+ }++ /** The pad paints with the brush as it is now, and what is on it is drawn again that way. */+ private fun syncPad() {+ val p = pad ?: return+ val s = session ?: return+ val c = PAD_COLORS.getOrElse(padColor) { 0xFFFFFF }+ p.paintLike(s, ((c shr 16) and 0xFF) / 255f, ((c shr 8) and 0xFF) / 255f, (c and 0xFF) / 255f)+ p.replayStrokes()+ }++ fun choosePadColor(i: Int) {+ padColor = i+ syncPad()+ }++ fun clearPad() {+ pad?.forgetStrokes()+ pad?.clearLayer()+ padMenuOpen = false+ }++ fun changeStudioCurve(points: List<Offset>) {+ studioCurve = points+ session?.setStudioCurve(points.flatMap { listOf(it.x, it.y) })+ refreshStudioPreview()+ syncPad()+ }++ /** Every control back to how the brush ships. */+ fun resetStudio() {+ session?.studioReset()+ readStudio()+ syncPad()+ padMenuOpen = false+ }++ /** Closes the studio: [keep] keeps the edits, otherwise the brush goes back to how it opened. */+ fun closeStudio(keep: Boolean) {+ session?.studioEnd(keep)+ // a new brush cancelled is thrown away+ if (!keep && studioNew) currentBrush?.let { session?.deleteBrush(it.set, it.index) }+ studioNew = false+ studioOpen = false+ padShown = false+ padMenuOpen = false+ // the pad's canvas goes with the studio+ val p = pad+ pad = null+ p?.detachWindow()+ p?.destroy()+ studioPreview = null+ libraryChanged()+ readSliders()+ }++ /** Draws the brush's sample stroke again, a moment after the last change. */+ private fun refreshStudioPreview() {+ val s = session ?: return+ val b = currentBrush ?: return+ studioPreviewJob?.cancel()+ studioPreviewJob = viewModelScope.launch {+ kotlinx.coroutines.delay(STUDIO_PREVIEW_DELAY_MS)+ val image = withContext(Dispatchers.Default) {+ val t = s.brushPreview(b.set, b.index, 1060u, 324u) ?: return@withContext null+ val bitmap = io.github.artcraftandroid.procraft.ui.CanvasSpace.tag(Bitmap.createBitmap(t.width.toInt(), t.height.toInt(), Bitmap.Config.ARGB_8888))+ bitmap.copyPixelsFromBuffer(ByteBuffer.wrap(t.rgba))+ bitmap.asImageBitmap()+ }+ if (image != null && studioOpen) studioPreview = image+ }+ }++ /** Renders the brush's sample stroke once, off the main thread. */+ fun loadPreview(b: BrushInfo) {+ val key = "${b.set}-${b.index}"+ if (previews.containsKey(key)) return+ val s = session ?: return+ viewModelScope.launch {+ val made = withContext(Dispatchers.Default) {+ // half the sample stroke's own canvas: the cell shows it across its width+ val t = s.brushPreview(b.set, b.index, 530u, 162u) ?: return@withContext null+ // whether the stroke runs under the name: the name's box (19.5 in, 14 to 26 down, about+ // 7.7 a letter wide, in a cell the picture fills 80 high and 261.7 wide) covered more+ // than 2/255 on average+ val k = 162f / 80f+ val x0 = ((19.5f + 6.85f) * k).toInt()+ val x1 = ((19.5f + 6.85f + 7.7f * b.name.length) * k).toInt().coerceAtMost(530)+ val y0 = (14f * k).toInt()+ val y1 = (26f * k).toInt()+ var cover = 0L+ for (y in y0 until y1) for (x in x0 until x1) cover += t.rgba[(y * 530 + x) * 4 + 3].toInt() and 0xFF+ val under = x1 > x0 && cover > 2L * (x1 - x0) * (y1 - y0)+ val bitmap = io.github.artcraftandroid.procraft.ui.CanvasSpace.tag(Bitmap.createBitmap(t.width.toInt(), t.height.toInt(), Bitmap.Config.ARGB_8888))+ bitmap.copyPixelsFromBuffer(ByteBuffer.wrap(t.rgba))+ bitmap.asImageBitmap() to under+ }+ if (made != null) {+ shadedNames[key] = made.second+ previews[key] = made.first+ }+ }+ }++ fun changeSize(value: Float) {+ size = value+ session?.setBrushSize(value)+ }++ /** The current brush's saved sizes and opacities: the side sliders' notches (0..1). */+ var sizeNotches by mutableStateOf<List<Float>>(emptyList())+ private set+ var opacityNotches by mutableStateOf<List<Float>>(emptyList())+ private set++ /** The notch [value] is on, of the size or opacity slider's ([size]), if any. */+ fun notchAt(size: Boolean, value: Float): Float? =+ (if (size) sizeNotches else opacityNotches)+ .filter { kotlin.math.abs(it - value) < NOTCH_NEAR }+ .minByOrNull { kotlin.math.abs(it - value) }++ /** Whether the slider's panel offers to save its value: not when it is on a notch or the slider is full. */+ fun canSaveNotch(size: Boolean): Boolean =+ notchAt(size, if (size) this.size else opacity) == null && (if (size) sizeNotches else opacityNotches).size < NOTCH_MOST++ /** The slider panel's button: saves the value as a notch, or takes away the notch it is on. */+ fun toggleNotch(size: Boolean) {+ val s = session ?: return+ val value = if (size) this.size else opacity+ if (notchAt(size, value) != null) s.removeSliderNotch(size, value) else s.addSliderNotch(size, value)+ readNotches()+ brushPrefs.edit().putString(BRUSH_LIBRARY, s.savedBrushLibrary()).apply()+ }++ private fun readNotches() {+ val s = session ?: return+ sizeNotches = s.sliderNotches(true)+ opacityNotches = s.sliderNotches(false)+ }++ /** Which slider's panel shows beside it: the size's or the opacity's. */+ enum class SliderPanel { SIZE, OPACITY }++ /** The panel beside a slider: shown while it is dragged, and kept up after it is held still. */+ var sliderPanel by mutableStateOf<SliderPanel?>(null)++ /** The panel stays up (the slider was held still) until the next touch elsewhere. */+ var sliderPanelKept by mutableStateOf(false)++ /** The brush's diameter on the screen now, window pixels. */+ fun brushScreenDiameter(): Float = session?.info()?.let { it.brushDiameter * it.zoom } ?: 0f++ fun changeOpacity(value: Float) {+ opacity = value+ session?.setBrushOpacity(value)+ }++ fun setColor(h: Float, s: Float, v: Float) {+ hue = h.coerceIn(0f, 1f)+ saturation = s.coerceIn(0f, 1f)+ brightness = v.coerceIn(0f, 1f)+ applyColor()+ }++ /** The colour as 0xRRGGBB. */+ fun colorRgb(): Int = hsvToRgb(hue, saturation, brightness)++ fun setRgb(rgb: Int) {+ val hsv = FloatArray(3)+ android.graphics.Color.RGBToHSV((rgb shr 16) and 0xFF, (rgb shr 8) and 0xFF, rgb and 0xFF, hsv)+ // a grey keeps the hue it had, so the hue slider does not jump+ setColor(if (hsv[1] > 0f) hsv[0] / 360f else hue, hsv[1], hsv[2])+ }++ /**+ * Moves the eyedropper to window point ([x], [y]) and reads what is shown there. The reading+ * happens off the main thread; points that arrive meanwhile replace each other.+ */+ fun pickAt(x: Float, y: Float, side: Int) {+ pendingPick = x to y+ if (picking == null) picking = PickState(x, y, null, null)+ if (pickJob?.isActive == true) return+ pickJob = viewModelScope.launch {+ while (true) {+ val (px, py) = pendingPick ?: break+ pendingPick = null+ val s = session ?: break+ val seen = withContext(Dispatchers.Default) {+ s.pick(px, py, side.toUInt())?.let { p ->+ val n = p.side.toInt()+ val bytes = p.pixels+ val argb = IntArray(n * n) { i ->+ (0xFF shl 24) or ((bytes[i * 4].toInt() and 0xFF) shl 16) or ((bytes[i * 4 + 1].toInt() and 0xFF) shl 8) or (bytes[i * 4 + 2].toInt() and 0xFF)+ }+ Bitmap.createBitmap(argb, n, n, Bitmap.Config.ARGB_8888).asImageBitmap() to p.rgb?.toInt()+ }+ }+ val now = picking ?: break+ picking = PickState(px, py, seen?.first ?: now.image, seen?.second ?: now.rgb)+ }+ }+ }++ /** The eyedropper lets go: its colour becomes the current one. */+ fun finishPick() {+ pickNext = false+ // a quick tap ends before the colour under it has been read: it is taken once it has+ val job = pickJob+ if (job?.isActive == true) {+ viewModelScope.launch {+ job.join()+ endPick()+ }+ } else {+ endPick()+ }+ }++ private fun endPick() {+ pendingPick = null+ picking?.rgb?.let { setRgb(it) }+ picking = null+ }++ fun cancelPick() {+ pendingPick = null+ picking = null+ }++ /** The colour button held: back to the colour painted with before this one, if there was one. */+ fun previousColor() {+ val now = colorRgb()+ val before = history.firstOrNull { it != now } ?: return+ setRgb(before)+ showNotice("Previous colour")+ }++ /** The current and second colours trade places. */+ fun swapColors() {+ val current = colorRgb()+ setRgb(secondaryRgb)+ secondaryRgb = current+ }++ fun clearHistory() {+ history = emptyList()+ }++ /**+ * The flattened picture as a PNG (or a JPEG on white) in the cache's exports folder, for+ * sharing; null when it could not be made.+ */+ /** What Share can write besides JPEG and PNG. */+ enum class Export(val extension: String, val mime: String) {+ PSD("psd", "image/vnd.adobe.photoshop"),+ PDF("pdf", "application/pdf"),+ TIFF("tif", "image/tiff"),+ LAYERS_PDF("pdf", "application/pdf"),+ LAYER_PNGS("png", "image/png"),+ }++ /** The artwork written as [kind] into the cache, to share: one file, or a PNG per layer. */+ suspend fun export(kind: Export, pdfQuality: Int = 100): List<File> {+ val s = session ?: return emptyList()+ return withContext(Dispatchers.IO) {+ val dir = File(getApplication<Application>().cacheDir, "exports").apply { mkdirs() }+ val base = s.name().filter { it.isLetterOrDigit() || it in " _-" }.trim().ifEmpty { "Untitled Artwork" }+ val file = File(dir, "$base.${kind.extension}")+ try {+ when (kind) {+ Export.PSD -> s.exportPsd(file.path)+ Export.PDF -> s.exportPdf(file.path, false, pdfQuality.toUByte())+ Export.TIFF -> s.exportTiff(file.path)+ Export.LAYERS_PDF -> s.exportPdf(file.path, true, pdfQuality.toUByte())+ Export.LAYER_PNGS -> {+ val folder = File(dir, base).apply { deleteRecursively(); mkdirs() }+ return@withContext s.exportLayerPngs(folder.path).map { File(it) }+ }+ }+ listOf(file)+ } catch (e: MobileException) {+ Log.e(TAG, "exporting", e)+ emptyList()+ }+ }+ }++ /** The layers as an animation, a frame each: the formats, by name, extension and type. */+ enum class Animated(val title: String, val extension: String, val mime: String) {+ GIF("Animated GIF", "gif", "image/gif"),+ PNG("Animated PNG", "png", "image/png"),+ MP4("Animated MP4", "mp4", "video/mp4"),+ HEVC("Animated HEVC", "mp4", "video/mp4"),+ }++ /** The animated export being set up, if any. */+ var animatedExport by mutableStateOf<Animated?>(null)++ /** The artwork was opened from the gallery's Share only for [animatedExport]: closing it goes back. */+ private var exportingFromGallery = false++ /** Ends the animated export; an artwork opened for it from the gallery is closed again. */+ fun endAnimatedExport() {+ animatedExport = null+ if (exportingFromGallery) {+ exportingFromGallery = false+ closeArtwork()+ }+ }++ fun animationFrameCount(): Int = session?.animationFrameCount()?.toInt() ?: 0++ /** Frame [index] fitted to [side] pixels, without the background if [transparent]. */+ fun animationFrame(index: Int, side: Int, transparent: Boolean): Bitmap? {+ val t = session?.animationFrame(index.toUInt(), transparent, side.coerceAtLeast(1).toUInt()) ?: return null+ val w = t.width.toInt()+ val h = t.height.toInt()+ val argb = IntArray(w * h) { i ->+ val o = i * 4+ ((t.rgba[o + 3].toInt() and 255) shl 24) or ((t.rgba[o].toInt() and 255) shl 16) or ((t.rgba[o + 1].toInt() and 255) shl 8) or (t.rgba[o + 2].toInt() and 255)+ }+ return Bitmap.createBitmap(argb, w, h, Bitmap.Config.ARGB_8888)+ }++ /**+ * The animation written as [format] into the cache, to share: Web Ready fits 480 pixels, else+ * the canvas size (a video as large as the encoder takes, up to 4096).+ */+ suspend fun exportAnimation(format: Animated, webReady: Boolean, dither: Boolean, transparent: Boolean): File? {+ val s = session ?: return null+ return withContext(Dispatchers.IO) {+ val dir = File(getApplication<Application>().cacheDir, "exports").apply { mkdirs() }+ val base = s.name().filter { it.isLetterOrDigit() || it in " _-" }.trim().ifEmpty { "Untitled Artwork" }+ val file = File(dir, "$base.${format.extension}")+ val side = if (webReady) WEB_READY_SIDE else 0+ // Animation Assist's own frame rate, when it is on+ val fps = s.animationSettings()?.fps?.toInt() ?: ANIMATION_FPS+ try {+ when (format) {+ Animated.GIF -> s.exportGif(file.path, side.toUInt(), fps.toFloat(), dither, transparent)+ Animated.PNG -> s.exportApng(file.path, side.toUInt(), fps.toFloat(), transparent)+ Animated.MP4, Animated.HEVC -> {+ val mime = if (format == Animated.HEVC) android.media.MediaFormat.MIMETYPE_VIDEO_HEVC else android.media.MediaFormat.MIMETYPE_VIDEO_AVC+ val (cw, ch) = canvasSize()+ val (w, h) = VideoWriter.fit(cw, ch, if (webReady) WEB_READY_SIDE else MAX_VIDEO_SIDE, mime) ?: return@withContext null+ val frame = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)+ val paint = android.graphics.Paint(android.graphics.Paint.FILTER_BITMAP_FLAG)+ val ok = try {+ val order = s.animationSequence()+ VideoWriter.write(file, w, h, fps, order.size, mime) { i, pixels ->+ val picture = animationFrame(order[i].toInt(), maxOf(w, h), false) ?: return@write false+ android.graphics.Canvas(frame).drawBitmap(picture, null, android.graphics.Rect(0, 0, w, h), paint)+ picture.recycle()+ frame.getPixels(pixels, 0, w, 0, 0, w, h)+ true+ }+ } finally {+ frame.recycle()+ }+ if (!ok) return@withContext null+ }+ }+ file+ } catch (e: MobileException) {+ Log.e(TAG, "exporting an animation", e)+ null+ }+ }+ }++ suspend fun exportImage(jpeg: Boolean): File? {+ val s = session ?: return null+ return withContext(Dispatchers.IO) {+ val dir = File(getApplication<Application>().cacheDir, "exports").apply { mkdirs() }+ val base = s.name().filter { it.isLetterOrDigit() || it in " _-" }.trim().ifEmpty { "Untitled Artwork" }+ val png = File(dir, "$base.png")+ try {+ s.exportPng(png.path)+ } catch (e: MobileException) {+ Log.e(TAG, "exporting", e)+ return@withContext null+ }+ if (!jpeg) return@withContext png+ val jpg = File(dir, "$base.jpg")+ val ok = io.github.artcraftandroid.procraft.gallery.pngToJpeg(png, jpg)+ png.delete()+ jpg.takeIf { ok }+ }+ }++ // ---- palettes ----++ fun addPalette() = changePalettes(palettes + Palette("Untitled Palette", List(PALETTE_SLOTS) { null }))++ /** Our example palettes back, those missing added at the end. */+ fun restoreExamplePalettes() {+ val missing = io.github.artcraftandroid.procraft.gallery.PaletteStore.starters().filter { s -> palettes.none { it.name == s.name } }+ if (missing.isNotEmpty()) changePalettes(palettes + missing)+ }++ /** A palette of the main colours in the picture at [uri], light to dark, added at the end. */+ fun paletteFromImage(uri: android.net.Uri) {+ val resolver = getApplication<Application>().contentResolver+ viewModelScope.launch {+ val colours = withContext(Dispatchers.IO) {+ runCatching {+ val bounds = android.graphics.BitmapFactory.Options().apply { inJustDecodeBounds = true }+ resolver.openInputStream(uri)?.use { android.graphics.BitmapFactory.decodeStream(it, null, bounds) }+ // read small: a few hundred pixels across is plenty to find its colours+ var sample = 1+ while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= 256) sample *= 2+ val bitmap = resolver.openInputStream(uri)?.use {+ android.graphics.BitmapFactory.decodeStream(it, null, android.graphics.BitmapFactory.Options().apply { inSampleSize = sample })+ } ?: return@runCatching null+ val pixels = IntArray(bitmap.width * bitmap.height).also { bitmap.getPixels(it, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height) }+ mainColours(pixels.filter { (it ushr 24) > 128 }.map { it and 0xFFFFFF }, PALETTE_SLOTS)+ }.getOrNull()+ }+ if (colours.isNullOrEmpty()) {+ message = "This picture can't be read."+ return@launch+ }+ changePalettes(palettes + Palette("Palette from image", List(PALETTE_SLOTS) { colours.getOrNull(it) }))+ }+ }++ /**+ * Reads a palette file at [uri] (ours, or another program's colour swatch or swatch exchange+ * file) into a new palette at the end; false if it isn't one.+ */+ suspend fun importSwatches(uri: android.net.Uri): Boolean {+ val resolver = getApplication<Application>().contentResolver+ val p = withContext(Dispatchers.IO) {+ runCatching {+ val head = resolver.openInputStream(uri)?.use { s -> ByteArray(4).also { s.read(it) } } ?: return@runCatching null+ val name = fileName(uri)+ when {+ head[0] == 'P'.code.toByte() && head[1] == 'K'.code.toByte() ->+ resolver.openInputStream(uri)?.use { io.github.artcraftandroid.procraft.gallery.Swatches.read(it) }+ io.github.artcraftandroid.procraft.gallery.ColourSwatches.isExchange(head) || name?.endsWith(".aco", ignoreCase = true) == true ->+ resolver.openInputStream(uri)?.use { io.github.artcraftandroid.procraft.gallery.ColourSwatches.read(it.readBytes(), name) }+ else -> null+ }+ }.getOrNull()+ } ?: return false+ changePalettes(palettes + p)+ return true+ }++ /** The name of the file at [uri], if its provider says. */+ private fun fileName(uri: android.net.Uri): String? = runCatching {+ getApplication<Application>().contentResolver.query(uri, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->+ if (c.moveToFirst()) c.getString(0) else null+ }+ }.getOrNull()++ /** Palette [i] as a swatches file in the cache, to share. */+ suspend fun paletteFile(i: Int): File? {+ val p = palettes.getOrNull(i) ?: return null+ return withContext(Dispatchers.IO) {+ runCatching {+ val base = p.name.filter { it.isLetterOrDigit() || it in " _-" }.trim().ifEmpty { "Palette" }+ File(File(getApplication<Application>().cacheDir, "exports").apply { mkdirs() }, "$base.${io.github.artcraftandroid.procraft.gallery.Swatches.EXTENSION}")+ .also { io.github.artcraftandroid.procraft.gallery.Swatches.write(p, it) }+ }.onFailure { Log.e(TAG, "sharing a palette", it) }.getOrNull()+ }+ }++ fun renamePalette(i: Int, name: String) = editPalette(i) { it.copy(name = name.trim().ifEmpty { it.name }) }++ fun duplicatePalette(i: Int) {+ val p = palettes.getOrNull(i) ?: return+ changePalettes(palettes.take(i + 1) + p.copy(name = p.name + " copy") + palettes.drop(i + 1))+ }++ fun deletePalette(i: Int) {+ if (palettes.size <= 1 || i !in palettes.indices) return+ val d = when {+ defaultPalette == i -> 0+ defaultPalette > i -> defaultPalette - 1+ else -> defaultPalette+ }+ changePalettes(palettes.filterIndexed { j, _ -> j != i }, d)+ }++ fun chooseDefaultPalette(i: Int) {+ if (i in palettes.indices) changePalettes(palettes, i)+ }++ /** Puts [rgb] in a palette's [slot], or empties it when null. */+ fun setSwatch(i: Int, slot: Int, rgb: Int?) = editPalette(i) { p ->+ if (slot !in 0 until PALETTE_SLOTS) p else p.copy(colors = p.colors.toMutableList().also { it[slot] = rgb })+ }++ private fun editPalette(i: Int, f: (Palette) -> Palette) {+ val p = palettes.getOrNull(i) ?: return+ changePalettes(palettes.toMutableList().also { it[i] = f(p) })+ }++ private fun changePalettes(next: List<Palette>, default: Int = defaultPalette) {+ palettes = next+ defaultPalette = default.coerceIn(0, (next.size - 1).coerceAtLeast(0))+ val snapshot = palettes to defaultPalette+ viewModelScope.launch(Dispatchers.IO) { paletteStore.save(snapshot.first, snapshot.second) }+ }++ private fun applyColor() {+ val c = colorRgb()+ session?.setColor(((c shr 16) and 0xFF) / 255f, ((c shr 8) and 0xFF) / 255f, (c and 0xFF) / 255f)+ if (colorNames) nameColorSoon()+ }++ private var naming: kotlinx.coroutines.Job? = null+ private var namedAt = 0L++ /**+ * Names the colour in a message as it changes (Color Description Notifications): at once, or,+ * while it keeps changing, the latest colour at most every [COLOR_NAME_GAP_MS].+ */+ private fun nameColorSoon() {+ naming?.cancel()+ val wait = (namedAt + COLOR_NAME_GAP_MS - android.os.SystemClock.uptimeMillis()).coerceAtLeast(0L)+ naming = viewModelScope.launch {+ kotlinx.coroutines.delay(wait)+ namedAt = android.os.SystemClock.uptimeMillis()+ message = io.github.artcraftandroid.procraft.ui.colourName(colorRgb())+ }+ }++ /** A click for an action done, with Feedback Sounds on. */+ fun feedback() {+ if (!feedbackSounds) return+ getApplication<Application>().getSystemService(android.media.AudioManager::class.java)+ ?.playSoundEffect(android.media.AudioManager.FX_KEY_CLICK)+ }++ fun toggle(p: Panel) {+ feedback()+ endQuickShape()+ if (transforming) endTransform(true)+ endAdjustment(true)+ closeSelecting()+ panel = if (panel == p) Panel.NONE else p+ if (panel == Panel.LAYERS) refreshThumbnails()+ }++ fun closePanels() {+ panel = Panel.NONE+ }++ /** Closes the open panel by fading it away, as picking something that takes the screen does. */+ fun fadePanels() {+ if (panel != Panel.NONE) panelFading = true+ panel = Panel.NONE+ }++ fun undo() {+ feedback()+ // undoing while editing text undoes the whole edit+ if (textInfo != null) {+ textInfo = null+ textStyleOpen = false+ }+ if (transforming) {+ transformBox = session?.transformApply(TransformAction.UNDO) ?: transformBox+ return+ }+ // cloning, the source goes back to where it was before the stroke+ if (adjustment == Adjustment.CLONE) {+ puckBefore.removeLastOrNull()?.let { before -> clonePuck?.let { puckAfter.addLast(it) }; clonePuck = before }+ }+ val could = canUndo+ val name = session?.undo()+ if (could) showNotice("Undo" + name?.let { " $it" }.orEmpty())+ refresh()+ }++ /**+ * A passing message under the top bar (what undo and redo did, and the like); [id] tells+ * repeats apart; a [warning] stays longer.+ */+ data class Notice(val text: String, val id: Long, val warning: Boolean = false)++ var notice by mutableStateOf<Notice?>(null)+ private set++ private var notices = 0L++ /** Shows [text] in the band under the top bar, in place of any message there; a [warning] stays longer. */+ fun showNotice(text: String, warning: Boolean = false) {+ notice = Notice(text, ++notices, warning)+ }++ /** The message under the top bar has gone. */+ fun noticeGone(n: Notice) {+ if (notice == n) notice = null+ }++ fun redo() {+ feedback()+ if (transforming) return+ if (adjustment == Adjustment.CLONE) {+ puckAfter.removeLastOrNull()?.let { after -> clonePuck?.let { puckBefore.addLast(it) }; clonePuck = after }+ }+ val could = canRedo+ val name = session?.redo()+ if (could) showNotice("Redo" + name?.let { " $it" }.orEmpty())+ refresh()+ }++ // ---- adjustments ----++ /** Opens adjustment [a] on the current layer (keeping one already open). */+ fun startAdjustment(a: Adjustment) {+ val s = session ?: return+ if (!currentTakesChanges()) return+ endAdjustment(true)+ endTransform(true)+ closeSelecting()+ // the list fades away rather than going at once+ if (panel == Panel.ADJUSTMENTS) panelFading = true+ panel = Panel.NONE+ val begun = when (a) {+ Adjustment.LIQUIFY -> s.liquifyBegin()+ Adjustment.CLONE -> s.cloneBegin()+ else -> s.adjustBegin()+ }+ if (!begun) return+ adjustment = a+ chromaOffset = Offset.Zero+ adjustPencil = a == Adjustment.CLONE+ adjustModesOpen = false+ cloneOffset = null+ puckBefore.clear()+ puckAfter.clear()+ clonePuck = null+ if (a == Adjustment.CLONE) {+ // the source starts in the middle of the window+ moveClonePuck(windowSize / 2f)+ readSliders()+ }+ liquified = false+ liquifyAmount = 1f+ liquifyPopup = 0+ adjustAmount = if (a == Adjustment.GRADIENT_MAP) 1f else 0f+ hue50 = 0.5f+ saturation50 = 0.5f+ brightness50 = 0.5f+ balance = List(9) { 0.5f }+ curves = List(4) { listOf(Offset(0f, 0f), Offset(1f, 1f)) }+ if (a == Adjustment.GRADIENT_MAP) applyGradient()+ if (a == Adjustment.GLITCH) applyGlitch()+ }++ /** Ends the adjustment: [commit] keeps it as one undo step, otherwise the layer goes back. */+ fun endAdjustment(commit: Boolean) {+ if (adjustment == null) return+ // a gradient being edited is kept as it is+ if (gradientEditing != null) endGradientEdit()+ adjustMenuAt = null+ adjustPreview = false+ session?.adjustEnd(commit)+ if (commit) showNotice("Adjustment applied")+ adjustment = null+ val painted = adjustPencil+ adjustPencil = false+ adjustModesOpen = false+ clonePuck = null+ if (painted) readSliders()+ refresh()+ if (panel == Panel.LAYERS) refreshThumbnails()+ }++ /**+ * Layer or Pencil: painting the adjustment on starts it at its own amount, and only where the+ * brush goes shows it; back to the layer starts it again.+ */+ fun chooseAdjustMode(pencil: Boolean) {+ val a = adjustment ?: return+ adjustModesOpen = false+ if (pencil == adjustPencil || !a.paintable) return+ if (!pencil) {+ resetAdjustment()+ return+ }+ session?.adjustPencil()+ adjustPencil = true+ readSliders()+ val amount = a.pencilAmount ?: return+ if (a == Adjustment.BLOOM) {+ // painted on, bloom starts smaller and burns more+ bloomSize = PENCIL_BLOOM_SIZE+ bloomBurn = PENCIL_BLOOM_BURN+ }+ if (a == Adjustment.MOTION_BLUR) {+ // along the canvas, as long as a drag of that much+ dragMotionBlur(amount * MOTION_DRAG_PT * density, 0f)+ } else {+ changeAdjustAmount(amount - adjustAmount)+ }+ }++ /** The clone source moved to window point [p]: the next stroke fixes how far from it the brush is. */+ fun moveClonePuck(p: Offset) {+ val at = windowToCanvas(p) ?: return+ clonePuck = at+ cloneOffset = null+ session?.cloneSource(p.x, p.y)+ }++ /** A clone stroke reached window point [p] ([start]: it begins there); the source follows the brush. */+ fun cloneStrokeAt(p: Offset, start: Boolean) {+ val puck = clonePuck ?: return+ val at = windowToCanvas(p) ?: return+ if (start) {+ puckBefore.addLast(puck)+ puckAfter.clear()+ }+ val offset = cloneOffset ?: (puck - at).also { cloneOffset = it }+ clonePuck = at + offset+ }++ /** Whether window point [p] is on the clone source. */+ fun onClonePuck(p: Offset): Boolean {+ val puck = clonePuck ?: return false+ return (canvasToWindow(puck) - p).getDistance() <= (CLONE_PUCK_RADIUS_DP + CLONE_PUCK_SLOP_DP) * density+ }++ /** The amount dragged across the canvas changed by [step] (0..1 of the whole). */+ fun changeAdjustAmount(step: Float) {+ val a = adjustment ?: return+ adjustAmount = (adjustAmount + step).coerceIn(0f, 1f)+ val kind = when (a) {+ Adjustment.GAUSSIAN_BLUR -> SwipeAdjustment.GAUSSIAN_BLUR+ Adjustment.SHARPEN -> SwipeAdjustment.SHARPEN+ Adjustment.PERSPECTIVE_BLUR -> SwipeAdjustment.PERSPECTIVE_BLUR+ Adjustment.GRADIENT_MAP -> {+ applyGradient()+ return+ }+ Adjustment.GLITCH -> {+ applyGlitch()+ return+ }+ Adjustment.NOISE -> {+ applyNoise()+ return+ }+ Adjustment.BLOOM -> {+ applyBloom()+ return+ }+ Adjustment.HALFTONE -> {+ applyHalftone()+ return+ }+ Adjustment.CHROMATIC_ABERRATION -> {+ applyChroma()+ return+ }+ else -> return+ }+ session?.adjustSwipe(kind, adjustAmount)+ }++ /** A motion blur's drag reached ([dx], [dy]) window pixels from where it started. */+ fun dragMotionBlur(dx: Float, dy: Float) {+ adjustAmount = session?.adjustMotion(dx, dy) ?: adjustAmount+ }++ fun chooseBalanceTone(tone: Int) {+ balanceTone = tone.coerceIn(0, 2)+ }++ /** Slider [k] (red, green, blue) of the tone shown moved to [value] (0..1). */+ fun setBalance(k: Int, value: Float) {+ balance = balance.toMutableList().also { it[balanceTone * 3 + k] = value }+ val v = balance.map { (it - 0.5f) * 2f }+ session?.adjustColorBalance(v.subList(0, 3), v.subList(3, 6), v.subList(6, 9))+ }++ fun chooseCurveChannel(channel: Int) {+ curveChannel = channel.coerceIn(0, 3)+ }++ /** Adds a point to the channel shown; returns its index. */+ fun addCurvePoint(p: Offset): Int {+ val pts = (curves[curveChannel] + p).sortedBy { it.x }+ setCurve(pts)+ return pts.indexOf(p)+ }++ /** Moves point [index] of the channel shown to [p], kept between its neighbours; returns its index. */+ fun moveCurvePoint(index: Int, p: Offset): Int {+ val pts = curves[curveChannel].toMutableList()+ if (index !in pts.indices) return index+ val lo = pts.getOrNull(index - 1)?.x?.plus(0.01f) ?: 0f+ val hi = pts.getOrNull(index + 1)?.x?.minus(0.01f) ?: 1f+ pts[index] = Offset(p.x.coerceIn(lo, maxOf(lo, hi)), p.y)+ setCurve(pts)+ return index+ }++ private fun setCurve(points: List<Offset>) {+ curves = curves.toMutableList().also { it[curveChannel] = points }+ val flat = curves.map { c -> c.flatMap { listOf(it.x, it.y) } }+ session?.adjustCurves(flat[0], flat[1], flat[2], flat[3])+ }++ /** The curve of [channel] as points to draw (x, height). */+ fun curveShape(channel: Int): List<Offset> {+ val heights = session?.curveShape(curves[channel].flatMap { listOf(it.x, it.y) }) ?: return emptyList()+ return heights.mapIndexed { i, h -> Offset(i / 255f, h) }+ }++ fun chooseGradient(i: Int) {+ gradientIndex = i.coerceIn(0, gradients.size - 1)+ applyGradient()+ }++ /** A new gradient, black to white, just after the chosen one: chosen and opened to edit. */+ fun newGradient() {+ val at = (gradientIndex + 1).coerceIn(0, gradients.size)+ gradients = gradients.toMutableList().apply { add(at, GradientPreset("Gradient", listOf(0f to 0xFF000000, 1f to 0xFFFFFFFF))) }+ gradientIndex = at+ gradientEditing = at+ gradientStore.save(gradients)+ applyGradient()+ }++ /** Opens gradient [i] (chosen) to edit. */+ fun editGradient(i: Int) {+ chooseGradient(i)+ gradientEditing = gradientIndex+ }++ /** Done editing: the library is saved. */+ fun endGradientEdit() {+ gradientEditing = null+ gradientStore.save(gradients)+ }++ fun deleteGradient(i: Int) {+ if (gradients.size <= 1 || i !in gradients.indices) return+ gradients = gradients.toMutableList().apply { removeAt(i) }+ if (gradientIndex > i || gradientIndex >= gradients.size) gradientIndex = (gradientIndex - 1).coerceAtLeast(0)+ gradientStore.save(gradients)+ applyGradient()+ }++ /** A copy of gradient [i] just after it, chosen. */+ fun duplicateGradient(i: Int) {+ val g = gradients.getOrNull(i) ?: return+ gradients = gradients.toMutableList().apply { add(i + 1, g) }+ gradientIndex = i + 1+ gradientStore.save(gradients)+ applyGradient()+ }++ private fun changeEdited(f: (GradientPreset) -> GradientPreset) {+ val i = gradientEditing ?: return+ val g = gradients.getOrNull(i) ?: return+ gradients = gradients.toMutableList().apply { set(i, f(g)) }+ applyGradient()+ }++ fun renameGradient(name: String) = changeEdited { if (name.isBlank()) it else it.copy(name = name.trim()) }++ /** A stop at [position] (0..1), coloured as the gradient was there; returns its index. */+ fun addGradientStop(position: Float): Int {+ val g = gradientEditing?.let { gradients.getOrNull(it) } ?: return -1+ val p = position.coerceIn(0f, 1f)+ changeEdited { it.copy(stops = it.stops + (p to gradientColorAt(it, p))) }+ return g.stops.size+ }++ fun moveGradientStop(i: Int, position: Float) = changeEdited { g ->+ g.copy(stops = g.stops.mapIndexed { k, s -> if (k == i) position.coerceIn(0f, 1f) to s.second else s })+ }++ fun setGradientStopColor(i: Int, rgb: Int) = changeEdited { g ->+ g.copy(stops = g.stops.mapIndexed { k, s -> if (k == i) s.first to (0xFF000000 or (rgb.toLong() and 0xFFFFFF)) else s })+ }++ /** Takes a stop out; a gradient keeps two. */+ fun deleteGradientStop(i: Int) = changeEdited { g -> if (g.stops.size <= 2) g else g.copy(stops = g.stops.filterIndexed { k, _ -> k != i }) }++ // noise, bloom, halftone and chromatic aberration's toolbars++ fun chooseNoiseKind(kind: NoiseKind) {+ noiseKind = kind+ applyNoise()+ }++ /** Noise's slider [index] (scale, octaves, turbulence) moved to [value]. */+ fun setNoiseValue(index: Int, value: Float) {+ when (index) {+ 0 -> noiseScale = value+ 1 -> noiseOctaves = value+ else -> noiseTurbulence = value+ }+ applyNoise()+ }++ fun chooseNoiseMulti(multi: Boolean) {+ noiseMulti = multi+ applyNoise()+ }++ fun toggleNoiseAdded() {+ noiseAdded = !noiseAdded+ applyNoise()+ }++ private fun applyNoise() {+ session?.adjustNoise(noiseKind, adjustAmount, noiseScale, noiseOctaves, noiseTurbulence, noiseMulti, noiseAdded)+ }++ /** Bloom's slider [index] (transition, size, burn) moved to [value]. */+ fun setBloomValue(index: Int, value: Float) {+ when (index) {+ 0 -> bloomTransition = value+ 1 -> bloomSize = value+ else -> bloomBurn = value+ }+ applyBloom()+ }++ private fun applyBloom() {+ session?.adjustBloom(adjustAmount, bloomTransition, bloomSize, bloomBurn)+ }++ fun chooseHalftoneKind(kind: HalftoneKind) {+ halftoneKind = kind+ applyHalftone()+ }++ private fun applyHalftone() {+ session?.adjustHalftone(halftoneKind, adjustAmount)+ }++ fun chooseChromaKind(kind: ChromaticKind) {+ chromaKind = kind+ applyChroma()+ }++ /** Chromatic aberration's slider [index] of the kind shown moved to [value]. */+ fun setChromaValue(index: Int, value: Float) {+ val values = chromaValues[chromaKind] ?: return+ if (index !in values.indices) return+ chromaValues = chromaValues + (chromaKind to values.toMutableList().also { it[index] = value })+ applyChroma()+ }++ /** Displacing: a drag [d] window pixels from where it began ([start] at its beginning) moves the fringes on. */+ fun dragChromatic(d: Offset, start: Boolean) {+ if (start) chromaDragFrom = chromaOffset+ chromaOffset = chromaDragFrom + d+ // how far, shown as the amount: a quarter of the window's short side is all of it+ val whole = minOf(windowSize.x, windowSize.y) / 4f+ adjustAmount = if (whole > 0f) (chromaOffset.getDistance() / whole).coerceIn(0f, 1f) else 0f+ applyChroma()+ }++ private fun applyChroma() {+ val v = chromaValues[chromaKind] ?: return+ val offset = if (chromaKind == ChromaticKind.DISPLACE) chromaOffset else Offset.Zero+ session?.adjustChromatic(chromaKind, adjustAmount, offset.x, offset.y, v[0], v[1])+ }++ fun chooseGlitchKind(kind: GlitchKind) {+ glitchKind = kind+ applyGlitch()+ }++ /** Slider [index] of the glitch kind shown moved to [value] (0..1, or −1..1 for diverge's shifts). */+ fun setGlitchValue(index: Int, value: Float) {+ val values = glitchValues[glitchKind] ?: return+ if (index !in values.indices) return+ glitchValues = glitchValues + (glitchKind to values.toMutableList().also { it[index] = value })+ applyGlitch()+ }++ private fun applyGlitch() {+ val v = glitchValues[glitchKind] ?: return+ session?.adjustGlitch(glitchKind, adjustAmount, v.dropLast(1), v.last())+ }++ private fun applyGradient() {+ val g = gradients.getOrNull(gradientIndex) ?: return+ val stops = g.stops.sortedBy { it.first }.flatMap { (p, c) ->+ listOf(p, ((c shr 16) and 0xFF) / 255f, ((c shr 8) and 0xFF) / 255f, (c and 0xFF) / 255f)+ }+ session?.adjustGradientMap(stops, adjustAmount)+ }++ // the menu a tap on the canvas opens during an adjustment++ /** Keeps what the adjustment did as one undo step and starts it again from there. */+ fun applyAdjustment() {+ val a = adjustment ?: return+ endAdjustment(true)+ startAdjustment(a)+ }++ /** Takes back the adjustment's changes, or with none, the last one kept. */+ fun undoAdjustment() {+ val a = adjustment ?: return+ if (adjustChanged()) {+ resetAdjustment()+ return+ }+ endAdjustment(false)+ session?.undo()+ startAdjustment(a)+ }++ fun togglePreview() {+ adjustPreview = !adjustPreview+ session?.adjustPreview(adjustPreview)+ adjustMenuAt = null+ }++ fun cancelAdjustment() = endAdjustment(false)++ /** Every value back to where the adjustment started. */+ fun resetAdjustment() {+ val a = adjustment ?: return+ endAdjustment(false)+ startAdjustment(a)+ }++ private fun adjustChanged(): Boolean = when (adjustment) {+ Adjustment.HSB -> listOf(hue50, saturation50, brightness50).any { it != 0.5f }+ Adjustment.COLOR_BALANCE -> balance.any { it != 0.5f }+ Adjustment.CURVES -> curves.any { it.size != 2 || it[0] != Offset(0f, 0f) || it[1] != Offset(1f, 1f) }+ Adjustment.GRADIENT_MAP -> true+ else -> adjustAmount > 0f+ }++ /** A liquify stroke's window points (x, y, pressure each); [start] begins it. */+ /** The liquify brush lifted moving at ([vx], [vy]) window pixels a millisecond: it carries on with its momentum. */+ fun liquifyLifted(vx: Float, vy: Float) {+ session?.liquifyCoast(vx, vy, liquifyMomentum, LiquifyBrush(liquifyKind, liquifySize, liquifyPressure, liquifyDistortion))+ }++ fun liquifyStroke(points: List<Float>, start: Boolean) {+ val s = session ?: return+ s.liquifyStroke(points, start, LiquifyBrush(liquifyKind, liquifySize, liquifyPressure, liquifyDistortion))+ liquified = true+ }++ fun chooseLiquifyKind(kind: LiquifyKind) {+ liquifyKind = kind+ liquifyPopup = 0+ }++ fun changeLiquifyAmount(amount: Float) {+ liquifyAmount = amount+ session?.liquifyAmount(amount)+ }++ fun resetLiquify() {+ session?.liquifyReset()+ liquified = false+ liquifyAmount = 1f+ liquifyPopup = 0+ }++ fun setHsb(h: Float, s: Float, b: Float) {+ hue50 = h+ saturation50 = s+ brightness50 = b+ session?.adjustHsb(h, s, b)+ }++ /** The adjustments button: closes an open adjustment (keeping it), or opens the menu. */+ fun adjustmentsPressed() {+ endQuickShape()+ if (adjustment != null) endAdjustment(true) else toggle(Panel.ADJUSTMENTS)+ }++ // ---- selection ----++ /** The selection button: opens or closes the selection tool (a selection made stays). */+ fun toggleSelecting() {+ endQuickShape()+ if (selecting) {+ closeSelecting()+ return+ }+ endTransform(true)+ endAdjustment(true)+ panel = Panel.NONE+ pickNext = false+ // each time the tool opens, shapes add to the selection+ selectionRemoves = false+ selecting = true+ refreshView()+ showSelectionLook()+ }++ fun closeSelecting() {+ if (!selecting) return+ closeFreehand()+ selecting = false+ selectionPopup = SelectionPopup.NONE+ showSelectionLook()+ }++ fun chooseSelectionKind(kind: SelectionKind) {+ closeFreehand()+ selectionKind = kind+ transformPrefs.edit().putString(SELECTION_KIND, kind.name).apply()+ showSelectionLook()+ }++ fun chooseSelectionRemoves(removes: Boolean) {+ selectionRemoves = removes+ }++ private val join get() = if (selectionRemoves) SelectionJoin.REMOVE else SelectionJoin.ADD++ /** A rectangle or ellipse dragged out between window points [a] and [b]. */+ fun selectShape(a: Offset, b: Offset) {+ val s = session ?: return+ shapeDrag = null+ if ((b - a).getDistance() < 1f) return+ s.selectShape(selectionKind == SelectionKind.ELLIPSE, a.x, a.y, b.x, b.y, join)+ selectionChanged()+ }++ /** Adds window point [p] to the freehand path; a point near its first one closes it. */+ fun freehandPoint(p: Offset, closeReach: Float) {+ val canvas = windowToCanvas(p) ?: return+ val first = freehand.firstOrNull()+ if (first != null && freehand.size > 2 && closeReach > 0f && (canvasToWindow(first) - p).getDistance() <= closeReach) {+ closeFreehand()+ return+ }+ freehand = freehand + canvas+ }++ /** The freehand path, held still, snaps to the shape it looks like; true if it did. */+ fun snapFreehand(): Boolean {+ val outline = io.github.artcraftandroid.procraft.core.quickshapeOutline(freehand.flatMap { listOf(it.x, it.y) }) ?: return false+ if (outline.size < 6) return false+ freehand = outline.chunked(2).map { (x, y) -> Offset(x, y) }+ return true+ }++ /** Closes the freehand path into a selection (a path of fewer than three points is dropped). */+ fun closeFreehand() {+ val s = session ?: return+ val path = freehand+ freehand = emptyList()+ if (path.size < 3) return+ s.selectPolygon(path.flatMap { canvasToWindow(it).let { w -> listOf(w.x, w.y) } }, join)+ selectionChanged()+ }++ /** Selects by colour at window point [p] with [threshold]; [live] while the threshold is dragged. */+ fun selectByColour(p: Offset, threshold: Float, live: Boolean) {+ val s = session ?: return+ thresholdDrag = if (live) p to threshold else null+ s.setSelectionDisplay(if (live) SelectionDisplay.FILL else SelectionDisplay.TINT)+ s.selectByColour(p.x, p.y, threshold, join, live)+ if (!live) {+ selectionThreshold = threshold+ transformPrefs.edit().putFloat(SELECTION_THRESHOLD, threshold).apply()+ }+ selectionChanged(fill = !live)+ }++ fun invertSelection() {+ session?.selectInvert()+ selectionChanged(fill = false)+ }++ fun copySelectionToLayer() {+ val s = session ?: return+ s.copySelectionToLayer() ?: return+ s.selectNone()+ selectionChanged(fill = false)+ refresh()+ if (panel == Panel.LAYERS) refreshThumbnails()+ }++ /** The feather popover's amount (0..1): the selection's edges softened from how they were before. */+ fun featherTo(amount: Float) {+ featherAmount = amount+ session?.selectFeather(amount)+ }++ fun openSelectionPopup(p: SelectionPopup) {+ selectionPopup = if (selectionPopup == p) SelectionPopup.NONE else p+ if (selectionPopup == SelectionPopup.FEATHER) featherAmount = 0f+ session?.let { savedSelections = it.savedSelectionCount().toInt() }+ if (selectionPopup == SelectionPopup.SAVED) loadSavedThumbnails()+ }++ fun saveSelection() {+ savedSelections = session?.saveSelection()?.toInt() ?: savedSelections+ loadSavedThumbnails()+ }++ private fun loadSavedThumbnails() {+ val s = session ?: return+ savedThumbnails.clear()+ for (i in 0 until savedSelections) {+ val t = s.savedSelectionThumbnail(i.toUInt(), 128u, 92u) ?: continue+ val bitmap = io.github.artcraftandroid.procraft.ui.CanvasSpace.tag(Bitmap.createBitmap(t.width.toInt(), t.height.toInt(), Bitmap.Config.ARGB_8888))+ bitmap.copyPixelsFromBuffer(ByteBuffer.wrap(t.rgba))+ savedThumbnails[i] = bitmap.asImageBitmap()+ }+ }++ fun loadSelection(i: Int) {+ session?.loadSelection(i.toUInt())+ selectionChanged(fill = false)+ }++ fun deleteSavedSelection(i: Int) {+ val s = session ?: return+ s.deleteSavedSelection(i.toUInt())+ savedSelections = s.savedSelectionCount().toInt()+ loadSavedThumbnails()+ }++ fun toggleColorFill() {+ colorFill = !colorFill+ if (colorFill && hasSelection) {+ session?.fillSelection()+ refresh()+ }+ }++ fun clearSelection() {+ closeFreehand()+ session?.selectNone()+ selectionChanged(fill = false)+ }++ private fun selectionChanged(fill: Boolean = true) {+ val s = session ?: return+ hasSelection = s.hasSelection()+ if (fill && colorFill && hasSelection) {+ s.fillSelection()+ refresh()+ }+ showSelectionLook()+ }++ /** Bands over what is not selected, except while selecting by colour, which tints what is. */+ private fun showSelectionLook() {+ val tint = selecting && selectionKind == SelectionKind.AUTOMATIC+ session?.setSelectionDisplay(if (tint) SelectionDisplay.TINT else SelectionDisplay.STRIPES)+ }++ /** Window pixels to canvas pixels through the view, or none when it cannot be inverted. */+ fun windowToCanvas(p: Offset): Offset? {+ val (a, b, c, d) = viewMatrix+ val e = viewMatrix[4]+ val f = viewMatrix[5]+ val det = a * d - b * c+ if (kotlin.math.abs(det) < 1e-9f) return null+ val x = p.x - e+ val y = p.y - f+ return Offset((d * x - c * y) / det, (a * y - b * x) / det)+ }++ fun canvasToWindow(p: Offset): Offset {+ val m = viewMatrix+ return Offset(m[0] * p.x + m[2] * p.y + m[4], m[1] * p.x + m[3] * p.y + m[5])+ }++ // ---- transform ----++ /** The transform button: opens transform on the current layer, or keeps it and closes. */+ fun toggleTransform() {+ endQuickShape()+ if (transforming) {+ endTransform(true)+ return+ }+ val s = session ?: return+ if (!currentTakesChanges()) return+ closeSelecting()+ endAdjustment(true)+ panel = Panel.NONE+ pickNext = false+ s.transformSetInterpolation(interpolation)+ s.transformSetGuides(guides)+ transformBox = s.transformBegin()+ // nothing there to move: it says so and stays out of transform+ if (transformBox == null) {+ showNotice(+ when {+ currentIsText() -> "Rasterize the text to transform it"+ hasSelection -> "Nothing is selected on this layer"+ else -> "This layer is empty"+ },+ )+ return+ }+ // a warp lays its mesh over what began+ transformBox = s.transformSetKind(transformKind) ?: transformBox+ transformPopup = TransformPopup.NONE+ refreshView()+ transforming = true+ }++ /** Ends transform: [commit] keeps the change as one undo step, otherwise the layer goes back. */+ fun endTransform(commit: Boolean) {+ if (!transforming) return+ session?.transformEnd(commit)+ transforming = false+ transformBox = null+ transformPopup = TransformPopup.NONE+ transformNumeric = null+ refresh()+ if (panel == Panel.LAYERS) refreshThumbnails()+ }++ fun chooseTransformKind(kind: TransformKind) {+ transformKind = kind+ session?.transformSetKind(kind)?.let { transformBox = it }+ transformPrefs.edit().putString(TRANSFORM_KIND, kind.name).apply()+ }++ fun chooseInterpolation(i: Interpolation) {+ interpolation = i+ session?.transformSetInterpolation(i)+ transformPrefs.edit().putString(INTERPOLATION, i.name).apply()+ }++ fun toggleAdvancedMesh() {+ advancedMesh = !advancedMesh+ transformPrefs.edit().putBoolean(ADVANCED_MESH, advancedMesh).apply()+ showNotice("Advanced mesh " + if (advancedMesh) "on" else "off")+ }++ fun changeGuides(g: GuideSettings) {+ if (g.snapping != guides.snapping) showNotice("Snapping " + if (g.snapping) "on" else "off")+ else if (g.magnetics != guides.magnetics) showNotice("Magnetics " + if (g.magnetics) "on" else "off")+ guides = g+ session?.transformSetGuides(g)+ transformPrefs.edit()+ .putBoolean(MAGNETICS, g.magnetics)+ .putBoolean(SNAPPING, g.snapping)+ .putFloat(SNAP_DISTANCE, g.distance)+ .putFloat(SNAP_VELOCITY, g.velocity)+ .apply()+ }++ private inline fun <reified E : Enum<E>> enumPref(key: String, default: E): E =+ transformPrefs.getString(key, null)?.let { name -> enumValues<E>().firstOrNull { it.name == name } } ?: default++ fun transformAction(action: TransformAction) {+ transformPopup = TransformPopup.NONE+ transformBox = session?.transformApply(action) ?: transformBox+ }++ /** The box after a drag step on the canvas. */+ fun transformMoved(box: TransformBox?) {+ if (box != null) transformBox = box+ }++ /** Numeric entry open beside window point [at]: for the box's angle (the rotation handle) or its size. */+ data class TransformNumeric(val angle: Boolean, val at: Offset)++ var transformNumeric by mutableStateOf<TransformNumeric?>(null)++ fun transformSetSize(width: Float, height: Float) = transformMoved(session?.transformSetSize(width, height))++ fun transformSetAngle(degrees: Float) = transformMoved(session?.transformSetAngle(degrees))++ /** Re-reads the view, after a gesture moved it, while something is drawn over the canvas. */+ /** Fits the canvas to the screen, settling into place; what is drawn over it follows each frame. */+ fun settleToFit() {+ session?.settleToFit()+ followView()+ }++ /** What is drawn over the canvas follows the view each frame while it moves into place. */+ private fun followView() {+ val s = session ?: return+ settling?.cancel()+ settling = viewModelScope.launch {+ val until = System.nanoTime() + (s.viewSettleSeconds() * 1e9).toLong() + SETTLE_MARGIN_NS+ while (System.nanoTime() < until && s.viewMoving()) {+ refreshView()+ kotlinx.coroutines.delay(FRAME_MS)+ }+ refreshView()+ }+ }++ private var settling: kotlinx.coroutines.Job? = null++ fun refreshView() {+ session?.let {+ viewMatrix = it.viewMatrix()+ // the guide's lines follow the canvas+ guide = it.guide()+ }+ // the shape's handles follow the canvas+ if (quickShape != null) quickShape = session?.quickshapeInfo()+ }++ fun toggleBars() {+ if (transforming) return+ barsHidden = !barsHidden+ if (barsHidden) panel = Panel.NONE+ }++ /** A stroke finished: its layer's thumbnail and the undo state changed. */+ fun strokeEnded() {+ // a stroke on a locked or hidden layer drew nothing: say why (text layers ask to rasterize instead)+ if (adjustment == null && !currentIsText()) currentTakesChanges()+ refreshFlags()+ if (animation != null) refreshFrameThumbnails()+ refreshReference()+ recordFrame()+ // painting an adjustment on uses no colour+ if (tool == ToolKind.PAINT && adjustment == null) {+ val c = colorRgb()+ history = (listOf(c) + history.filter { it != c }).take(HISTORY_SIZE)+ }+ if (panel == Panel.LAYERS) layers.firstOrNull { it.current }?.let { loadThumbnail(it.id) }+ }++ // ---- Animation Assist ----++ /** Animation Assist's settings while it is on. */+ var animation by mutableStateOf<io.github.artcraftandroid.procraft.core.AnimationSettings?>(null)+ private set++ /** The frames' layers, bottom first, and which one is current. */+ var animationFrames by mutableStateOf<List<ULong>>(emptyList())+ private set+ var currentFrame by mutableStateOf<Int?>(null)+ private set++ /** Each frame's picture for the timeline. */+ val frameThumbnails = mutableStateMapOf<ULong, ImageBitmap>()++ /** Playing: the frame shown. */+ var playingFrame by mutableStateOf<Int?>(null)+ private set+ private var playJob: Job? = null++ var animationSettingsOpen by mutableStateOf(false)+ var frameOptionsOpen by mutableStateOf(false)++ fun changeAnimationAssist(on: Boolean) {+ stopPlaying()+ session?.setAnimationAssist(on)+ refresh()+ }++ fun changePageAssist(on: Boolean) {+ stopPlaying()+ session?.setPageAssist(on)+ refresh()+ }++ /** Re-reads Animation Assist from the session (after any change to the layers). */+ private fun refreshAnimation() {+ val s = session ?: return+ val settings = s.animationSettings()+ animation = settings+ if (settings == null) {+ animationFrames = emptyList()+ currentFrame = null+ animationSettingsOpen = false+ frameOptionsOpen = false+ return+ }+ animationFrames = s.animationFrames()+ currentFrame = s.currentFrame()?.toInt()+ refreshFrameThumbnails()+ }++ private var frameThumbJob: Job? = null++ private fun refreshFrameThumbnails() {+ val s = session ?: return+ val ids = animationFrames+ frameThumbJob?.cancel()+ frameThumbJob = viewModelScope.launch {+ for (id in ids) {+ val image = withContext(Dispatchers.Default) {+ val t = s.frameThumbnail(id, FRAME_THUMB_SIDE.toUInt()) ?: return@withContext null+ val bitmap = io.github.artcraftandroid.procraft.ui.CanvasSpace.tag(Bitmap.createBitmap(t.width.toInt(), t.height.toInt(), Bitmap.Config.ARGB_8888))+ bitmap.copyPixelsFromBuffer(ByteBuffer.wrap(t.rgba))+ bitmap.asImageBitmap()+ }+ if (image != null) frameThumbnails[id] = image else frameThumbnails.remove(id)+ }+ }+ }++ fun changeAnimation(f: (io.github.artcraftandroid.procraft.core.AnimationSettings) -> io.github.artcraftandroid.procraft.core.AnimationSettings) {+ val s = session ?: return+ val a = animation ?: return+ s.setAnimationSettings(f(a))+ animation = s.animationSettings()+ }++ /** Frame [i] becomes the one drawn on (a tap on the current one opens its options). */+ fun tapFrame(i: Int) {+ if (playingFrame != null) stopPlaying()+ if (i == currentFrame) {+ frameOptionsOpen = !frameOptionsOpen+ animationSettingsOpen = false+ return+ }+ frameOptionsOpen = false+ animationFrames.getOrNull(i)?.let { selectLayer(it) }+ }++ fun addFrame() {+ stopPlaying()+ frameOptionsOpen = false+ addLayer()+ }++ private fun currentFrameLayer(): LayerInfo? = currentFrame?.let { animationFrames.getOrNull(it) }?.let { id -> layers.firstOrNull { it.id == id } }++ fun duplicateFrame() {+ frameOptionsOpen = false+ currentFrameLayer()?.let(::duplicate)+ }++ fun deleteFrame() {+ frameOptionsOpen = false+ currentFrameLayer()?.let(::delete)+ }++ fun frameHold(): Int = currentFrame?.let { animationFrames.getOrNull(it) }?.let { session?.frameHold(it)?.toInt() } ?: 0++ var holdVersion by mutableStateOf(0)+ private set++ fun changeFrameHold(frames: Int) {+ val id = currentFrame?.let { animationFrames.getOrNull(it) } ?: return+ session?.setFrameHold(id, frames.coerceIn(0, MAX_HOLD).toUInt())+ holdVersion+++ }++ /** The frames in playing order, each as often as it is held. */+ private fun playOrder(): List<Int> {+ val s = session ?: return emptyList()+ return animationFrames.flatMapIndexed { i, id -> List(1 + s.frameHold(id).toInt()) { i } }+ }++ fun togglePlaying() = if (playingFrame != null) stopPlaying() else play()++ private fun play() {+ val s = session ?: return+ val a = animation ?: return+ val order = playOrder()+ if (order.isEmpty()) return+ animationSettingsOpen = false+ frameOptionsOpen = false+ playJob?.cancel()+ playJob = viewModelScope.launch {+ var at = 0+ var step = 1+ while (true) {+ val frame = order[at]+ playingFrame = frame+ s.setPlayFrame(frame.toUInt())+ kotlinx.coroutines.delay(1000L / (animation?.fps ?: a.fps).toInt().coerceAtLeast(1))+ val next = at + step+ when {+ next in order.indices -> at = next+ a.playback == io.github.artcraftandroid.procraft.core.AnimationPlayback.LOOP -> at = 0+ a.playback == io.github.artcraftandroid.procraft.core.AnimationPlayback.PING_PONG && order.size > 1 -> {+ step = -step+ at += step+ }+ else -> break+ }+ }+ // a single pass ends on its last frame, still shown+ }+ }++ fun stopPlaying() {+ playJob?.cancel()+ playJob = null+ if (playingFrame != null) {+ playingFrame = null+ session?.setPlayFrame(null)+ }+ }++ // ---- layers ----++ fun addLayer() = layerChange { if (it.addLayer() == 0uL) message = noRoom() }++ fun selectLayer(id: ULong) = layerChange { it.selectLayer(id) }++ fun toggleVisible(l: LayerInfo) = layerChange { it.setLayerVisible(l.id, !l.visible) }++ fun setLayerOpacity(l: LayerInfo, value: Float, done: Boolean) = layerChange(thumbs = false) { it.setLayerOpacity(l.id, value, done) }++ fun setBlend(l: LayerInfo, blend: UInt) = layerChange(thumbs = false) { it.setLayerBlend(l.id, blend) }++ fun toggleAlphaLock(l: LayerInfo) = layerChange(thumbs = false) { it.setLayerAlphaLock(l.id, !l.alphaLock) }++ /** A mask's layer; anything else itself. */+ fun ownerOf(l: LayerInfo): LayerInfo = if (l.kind == LayerType.MASK) layers.firstOrNull { it.id == l.parent } ?: l else l++ /** Whether [l] is somewhere inside group [group]. */+ fun isInside(l: LayerInfo, group: ULong): Boolean {+ var at = ownerOf(l).parent+ repeat(layers.size) {+ val id = at ?: return false+ if (id == group) return true+ at = layers.firstOrNull { it.id == id }?.parent+ }+ return false+ }++ /** Whether a closed group hides [l]'s row. */+ fun hidden(l: LayerInfo) = layers.any { it.kind == LayerType.GROUP && it.collapsed && isInside(l, it.id) }++ fun hasMask(l: LayerInfo) = layers.any { it.kind == LayerType.MASK && it.parent == l.id }++ /** The rows that go with [l]: it with its mask, or a group with everything in it. */+ fun unitOf(l: LayerInfo): Set<ULong> = layers+ .filter { it.id == l.id || (it.kind == LayerType.MASK && it.parent == l.id) || (l.kind == LayerType.GROUP && isInside(it, l.id)) }+ .map { it.id }+ .toSet()++ /**+ * Moves [l] (with what goes with it) just above or below [target]'s row; a chosen layer with+ * others picked takes them along, in their order.+ */+ fun moveNextTo(l: LayerInfo, target: LayerInfo, above: Boolean) = layerChange(thumbs = false) {+ val together = anyPicked && (l.current || l.picked)+ val unit = if (together) {+ // a picked mask moves with its layer+ layers.filter { it.current || it.picked }+ .mapNotNull { c -> if (c.kind == LayerType.MASK) layers.firstOrNull { it.id == c.parent } else c }+ .flatMap { unitOf(it) }.toSet()+ } else {+ unitOf(l)+ }+ if (target.id in unit) return@layerChange null+ val rest = layers.filter { it.id !in unit }.asReversed()+ val at = rest.indexOfFirst { it.id == target.id }+ if (at < 0) return@layerChange null+ val to = (if (above) at + 1 else at).toUInt()+ if (together) it.moveChosen(to) else it.moveLayer(l.id, to)+ }++ fun addMask(l: LayerInfo) = layerChange { if (it.addMask(l.id) == null && !hasMask(l)) message = noRoom() }++ fun combineDown(l: LayerInfo) = layerChange { it.combineDown(l.id) }++ fun ungroup(l: LayerInfo) = layerChange { it.ungroup(l.id) }++ fun flattenGroup(l: LayerInfo) = layerChange { it.flattenGroup(l.id) }++ fun toggleCollapsed(l: LayerInfo) = layerChange(thumbs = false) { it.setGroupCollapsed(l.id, !l.collapsed) }++ fun selectLayerContents(l: LayerInfo) {+ session?.selectLayerContents(l.id)+ refreshFlags()+ }++ fun copyLayerContents(l: LayerInfo) {+ clipboard = session?.copyLayerContents(l.id) ?: clipboard+ canPaste = clipboard != null+ }++ fun fillLayer(l: LayerInfo) = layerChange { it.fillLayer(l.id) }++ fun invertLayer(l: LayerInfo) = layerChange { it.invertLayer(l.id) }++ fun toggleReference(l: LayerInfo) = layerChange(thumbs = false) { it.setLayerReference(l.id, !l.reference) }++ fun toggleClipped(l: LayerInfo) = layerChange(thumbs = false) { it.setLayerClipped(l.id, !l.clipped) }++ fun toggleLocked(l: LayerInfo) = layerChange(thumbs = false) { it.setLayerLocked(l.id, !l.locked) }++ fun duplicate(l: LayerInfo) = layerChange { if (it.duplicateLayer(l.id) == null) message = noRoom() }++ fun delete(l: LayerInfo) = layerChange { it.deleteLayer(l.id) }++ fun mergeDown(l: LayerInfo) = layerChange { it.mergeDown(l.id) }++ /** Whether layers are picked to act on with the current one. */+ val anyPicked: Boolean get() = layers.any { it.picked }++ /** Picks layer [l] to act on with the current one, or unpicks it. */+ fun pickLayer(l: LayerInfo) = layerChange(thumbs = false) { it.pickLayer(l.id) }++ fun pickAllLayers() = layerChange(thumbs = false) { it.pickAllLayers() }++ fun groupPicked() = layerChange { it.groupPicked() }++ fun mergePicked() = layerChange { it.mergePicked() }++ fun duplicatePicked() = layerChange { if (!it.duplicatePicked()) message = noRoom() }++ fun deletePicked() = layerChange { it.deletePicked() }++ /** The current and picked layers each as a PNG in the cache, to share. */+ suspend fun chosenLayerFiles(): List<File> {+ val s = session ?: return emptyList()+ return withContext(Dispatchers.IO) {+ runCatching {+ val folder = File(File(getApplication<Application>().cacheDir, "exports"), "layers").apply {+ deleteRecursively()+ mkdirs()+ }+ s.exportChosenPngs(folder.path).map { File(it) }+ }.onFailure { Log.e(TAG, "exporting layers", it) }.getOrDefault(emptyList())+ }+ }++ fun clearCurrentLayer() {+ refresh()+ layers.firstOrNull { it.current }?.let {+ if (currentTakesChanges()) {+ clear(it)+ showNotice("Layer cleared")+ }+ }+ }++ fun clear(l: LayerInfo) = layerChange {+ it.selectLayer(l.id)+ it.clearLayer()+ }++ fun rename(l: LayerInfo, name: String) = layerChange(thumbs = false) { it.renameLayer(l.id, name) }++ /** Moves a layer to `index` in the panel's top-first order. */+ fun moveTo(l: LayerInfo, index: Int) = layerChange(thumbs = false) {+ val fromBottom = (layers.size - 1 - index).coerceAtLeast(0)+ it.moveLayer(l.id, fromBottom.toUInt())+ }++ fun toggleBackground() = layerChange(thumbs = false) { it.setBackgroundVisible(!background.visible) }++ /** The Layers panel shows the colour panel, picking the background's colour. */+ var backgroundPicking by mutableStateOf(false)+ private set++ fun pickBackground() {+ backgroundPicking = true+ }++ /** The background's colour as 0xRRGGBB. */+ fun backgroundRgb(): Int {+ fun c(v: Float) = (v.coerceIn(0f, 1f) * 255f).roundToInt()+ return (c(background.r) shl 16) or (c(background.g) shl 8) or c(background.b)+ }++ /** Sets the background's colour, live while a picker moves; [done] makes the change one undo step. */+ fun setBackgroundRgb(rgb: Int, done: Boolean) {+ val s = session ?: return+ s.setBackgroundColor(((rgb shr 16) and 0xFF) / 255f, ((rgb shr 8) and 0xFF) / 255f, (rgb and 0xFF) / 255f, done)+ if (done) refresh() else background = s.background()+ }++ /** The background picker closes (its tick, or the panel going away): the colour is kept as one undo step. */+ fun endBackgroundPick() {+ if (!backgroundPicking) return+ backgroundPicking = false+ setBackgroundRgb(backgroundRgb(), done = true)+ }++ private fun layerChange(thumbs: Boolean = true, f: (CanvasSession) -> Any?) {+ val s = session ?: return+ f(s)+ refresh()+ if (thumbs && panel == Panel.LAYERS) refreshThumbnails()+ }++ /** Re-reads the layers and undo state from the session. */+ fun refresh() {+ val s = session ?: return+ refreshReference()+ recordFrame()+ // undo and redo keep a snapped shape as drawn first+ if (quickShape != null && s.quickshapeInfo() == null) {+ quickShape = null+ quickShapeEditing = false+ }+ layers = s.layers()+ background = s.background()+ // undoing may put the canvas back in another profile+ refreshCanvasSpace(s)+ refreshFlags()+ refreshAnimation()+ }++ private fun refreshFlags() {+ val info = session?.info() ?: return+ canUndo = info.canUndo+ canRedo = info.canRedo+ hasSelection = session?.hasSelection() ?: false+ }++ private fun refreshThumbnails() {+ for (l in layers) loadThumbnail(l.id)+ }++ private fun loadThumbnail(id: ULong) {+ val s = session ?: return+ viewModelScope.launch {+ val image = withContext(Dispatchers.Default) {+ val t = s.layerThumbnail(id, THUMB_SIDE.toUInt()) ?: return@withContext null+ val bitmap = io.github.artcraftandroid.procraft.ui.CanvasSpace.tag(Bitmap.createBitmap(t.width.toInt(), t.height.toInt(), Bitmap.Config.ARGB_8888))+ bitmap.copyPixelsFromBuffer(ByteBuffer.wrap(t.rgba))+ bitmap.asImageBitmap()+ }+ if (image != null) thumbnails[id] = image+ }+ }++ private fun readSliders() {+ val info = session?.info() ?: return+ size = info.size+ opacity = info.opacity+ readNotches()+ }++ override fun onCleared() {+ saveNow()+ session = null+ }++ companion object {+ /** While the view settles, what is drawn over the canvas is moved this often (ms), and a little past its end (ns). */+ const val FRAME_MS = 16L+ const val SETTLE_MARGIN_NS = 50_000_000L++ /** The clone source's ring (points from its centre), and how far off it a touch still takes it. */+ const val CLONE_PUCK_RADIUS_DP = 30f+ const val CLONE_PUCK_SLOP_DP = 8f+ /** Each glitch kind's sliders as they start: its own two (diverge three), then the zoom. */+ val GLITCH_DEFAULTS = mapOf(+ GlitchKind.ARTIFACT to listOf(1f, 0.09f, 1f),+ GlitchKind.WAVE to listOf(0.2f, 0.3f, 1f),+ GlitchKind.SIGNAL to listOf(0.8f, 0.19f, 1f),+ GlitchKind.DIVERGE to listOf(0.98f, -0.5f, 0.85f, 0.5f),+ )+ const val BRUSH_CHANGES = "changes"+ const val BRUSH_LIBRARY = "library"+ /** How big the studio's Shape and Grain Source rows show their image (pixels across). */+ const val SOURCE_ROW_PX = 88+ /** And the landscape studio's square of it. */+ const val SOURCE_BOX_PX = 566+ /** The brushes in use, each set's last choice and each brush's sliders. */+ const val BRUSH_CHOICES = "choices"++ /** How many brushes of each shipped set the kept library has had the chance to hold. */+ const val BRUSHES_SEEN = "brushes_seen"++ /** What shipped before brushes and sets were added to kept libraries. */+ val FIRST_SHIPPED = listOf(3u, 3u, 3u, 2u, 2u, 2u)+ /** Said when a layer can't be added: the canvas holds no more at its size. */+ /** The memory layers may take, which sets how many a canvas can hold. */+ const val LAYER_BUDGET = 2L * 1024 * 1024 * 1024+ const val MAX_CANVAS_EDGE = 16384+ /** How much smaller than fitted to the screen the canvas is while cropping. */+ const val CROP_SCALE = 0.597f+ /** The reference window: its first place and picture size, its limits, and how sharp and how often its canvas is read. */+ /** The reference window's picture at first, and its gap to the screen's bottom. */+ const val REFERENCE_WIDTH_DP = 350f+ const val REFERENCE_HEIGHT_DP = 423f+ const val REFERENCE_BOTTOM_DP = 50f+ const val REFERENCE_MIN_DP = 150f+ const val REFERENCE_MAX_DP = 700f+ const val REFERENCE_PIXELS = 700+ const val REFERENCE_INTERVAL_MS = 300L+ /** New text's size: the canvas's shorter side over this. */+ /** New text's size and its box's width, as fractions of the canvas width. */+ const val TEXT_SIZE_OF_WIDTH = 0.13f+ const val TEXT_SCREEN_Y = 0.24f+ const val TEXT_BOX_OF_WIDTH = 1f+ const val RIGHT_HANDED = "right_handed"+ const val COLOR_MODE = "color_mode"+ const val ACTIONS_TAB = "actions_tab"+ const val STUDIO_TAB = "studio_tab"+ const val RAPID_UNDO_DELAY = "rapid_undo_delay"+ const val LIGHT_INTERFACE = "light_interface"+ const val BRUSH_CURSOR = "brush_cursor"+ const val CURSOR_SHOWS = "cursor_shows"+ const val CURSOR_STYLE = "cursor_style"+ const val BRUSH_ON_SCREEN = "brush_on_screen"+ const val PROJECT_CANVAS = "project_canvas"+ const val PALETTE_CARDS = "palette_cards"+ const val COLOR_HISTORY_SHOWN = "color_history_shown"+ const val ORIENTATION_MEMORY = "orientation_memory"+ const val FIT_INSIDE = "fit_inside"+ const val NO_TIME_LAPSE = "no_time_lapse"+ const val SIMPLIFIED_UNDOS = "simplified_undos"++ /** The picture of the canvas the gallery zooms out of, at most this many pixels on a side. */+ const val CLOSING_PICTURE_SIDE = 768+ const val COLOR_NAMES = "color_names"+ const val FEEDBACK_SOUNDS = "feedback_sounds"+ const val SINGLE_TOUCH_COMPANION = "single_touch_companion"+ const val TAP_ASSISTANCE = "tap_assistance"++ /** The layered package's file extension, and its name in the Share lists. */+ const val PACKAGE_EXTENSION = "procreate"++ /** Brush and brush set files, as other painting apps share them. */+ const val BRUSH_EXTENSION = "brush"+ const val BRUSH_SET_EXTENSION = "brushset"+ val PACKAGE_LABEL = PACKAGE_EXTENSION.replaceFirstChar(Char::titlecase)++ /** What the gallery's Share offers, in order: still pictures, then animations. */+ val SHARE_FORMATS = listOf(PACKAGE_LABEL, "PSD", "PDF", "JPEG", "PNG", "TIFF") + Animated.entries.map { it.title }++ /** How often, and for how long at most, opening waits for the canvas's first frame, milliseconds. */+ const val CANVAS_POLL_MS = 32L+ const val CANVAS_DRAWN_LIMIT_MS = 15_000L++ /** How near a slider value is on a notch (and is pulled onto it), and the most a slider takes. */+ const val NOTCH_NEAR = 0.04f+ const val NOTCH_MOST = 4++ /** The least time between two colour names while the colour keeps changing, milliseconds. */+ const val COLOR_NAME_GAP_MS = 150L++ /** How often an open artwork is saved when it has changed, milliseconds. */+ const val AUTOSAVE_MS = 3000L+ const val SPEED_DISTANCE = "speed_distance"++ /** What an artwork dragged out of the gallery becomes (an index into [DRAG_FORMATS]), and a picture's format when one is wanted. */+ const val DRAG_FORMAT = "drag_format"+ const val DRAG_IMAGE_FORMAT = "drag_image_format"+ val DRAG_FORMATS = listOf("ProCraft", "PSD", "JPEG", "PNG", "TIFF")+ val DRAG_IMAGE_FORMATS = listOf("JPEG", "PNG", "TIFF")+ const val QUICK_MENU = "quick_menu"+ /** A press of □ this short, used by nothing, is a tap. */+ const val MODIFY_TAP_MS = 500L+ const val PRESETS = "presets"+ const val INPUT_STABILIZATION = "input_stabilization"+ const val INPUT_MOTION = "input_motion_filtering"+ const val INPUT_EXPRESSION = "input_motion_expression"+ const val INPUT_PRESSURE_SMOOTHING = "input_pressure_smoothing"+ const val INPUT_CURVE = "input_pressure_curve"+ /** Frames a second an animation plays at (Animation Assist's own when it is on). */+ const val ANIMATION_FPS = 15+ /** The timeline's frame pictures' longest side, pixels; a frame's longest hold. */+ const val FRAME_THUMB_SIDE = 96+ const val MAX_HOLD = 60+ /** A Web Ready animation's longest side, pixels. */+ const val WEB_READY_SIDE = 480+ /** An animated video's longest side at most, pixels. */+ const val MAX_VIDEO_SIDE = 4096+ const val RAPID_UNDO_MIN_S = 0.1f+ const val RAPID_UNDO_MAX_S = 1.5f+ const val SELECTION_VISIBILITY = "selection_visibility"+ /** The guide editor fits the canvas this far in from the window's sides, top and bottom (points). */+ const val GUIDE_FIT_SIDE_DP = 40f+ const val GUIDE_FIT_TOP_DP = 226f+ const val GUIDE_FIT_BOTTOM_DP = 228f+ /** The largest side a picture brought in is decoded at (pixels). */+ const val MAX_PICTURE = 4096+ /** How long a stroke is held still to snap (milliseconds), how still (points), and how near a handle a touch takes it. */+ const val QUICKSHAPE_MS = 650L+ const val QUICKSHAPE_STILL_DP = 6f+ const val QUICKSHAPE_REACH_DP = 30f+ /** The drawing pad's colours (0xRRGGBB), the white one, and its background's grey. */+ val PAD_COLORS = listOf(0xF83045, 0xFCBD03, 0x85D921, 0x2BB5E6, 0x4956A5, 0xDA3D92, 0xFFFFFF, 0x000000)+ const val PAD_WHITE = 6+ const val PAD_BACK = 31f / 255f+ /** How long after a studio control stops moving its sample stroke is drawn again (milliseconds). */+ const val STUDIO_PREVIEW_DELAY_MS = 60L+ /** Bloom's size and burn sliders when painted on. */+ const val PENCIL_BLOOM_SIZE = 0.335f+ const val PENCIL_BLOOM_BURN = 0.57f+ /** How far a motion blur's drag goes for its whole amount (points). */+ const val MOTION_DRAG_PT = 500f+ /** The first colour: a saturated blue. */+ const val DEFAULT_HUE = 0.59f+ /** Layer thumbnails are read at about the size they show (93 dp at 2 px a dp). */+ const val THUMB_SIDE = 192+ const val HISTORY_SIZE = 10+ private const val TRANSFORM_KIND = "kind"+ private const val INTERPOLATION = "interpolation"+ private const val MAGNETICS = "magnetics"+ private const val SNAPPING = "snapping"+ private const val SNAP_DISTANCE = "snapDistance"+ private const val SNAP_VELOCITY = "snapVelocity"+ private const val ADVANCED_MESH = "advancedMesh"+ private const val SELECTION_KIND = "selectionKind"+ private const val SELECTION_THRESHOLD = "selectionThreshold"++ fun hsvToRgb(h: Float, s: Float, v: Float): Int {+ val hsv = floatArrayOf((h * 360f) % 360f, s, v)+ return android.graphics.Color.HSVToColor(hsv) and 0xFFFFFF+ }+ }+}++/**+ * Up to [count] colours standing for [pixels] (0xRRGGBB): the colours split again and again at the+ * middle of their widest channel, each part's mean kept; lightest first.+ */+internal fun mainColours(pixels: List<Int>, count: Int): List<Int> {+ if (pixels.isEmpty()) return emptyList()+ fun ch(c: Int, k: Int) = (c shr (16 - 8 * k)) and 0xFF+ fun spread(box: List<Int>) = (0 until 3).maxOf { k -> box.maxOf { ch(it, k) } - box.minOf { ch(it, k) } }+ val boxes = mutableListOf(pixels)+ while (boxes.size < count) {+ val widest = boxes.filter { it.size > 1 }.maxByOrNull { spread(it) } ?: break+ if (spread(widest) == 0) break+ val k = (0 until 3).maxBy { k -> widest.maxOf { ch(it, k) } - widest.minOf { ch(it, k) } }+ val sorted = widest.sortedBy { ch(it, k) }+ boxes.remove(widest)+ boxes.add(sorted.subList(0, sorted.size / 2))+ boxes.add(sorted.subList(sorted.size / 2, sorted.size))+ }+ val means = boxes.map { box -> (0 until 3).map { k -> box.sumOf { ch(it, k) } / box.size }.let { (r, g, b) -> (r shl 16) or (g shl 8) or b } }+ return means.distinct().sortedByDescending { 0.299 * ch(it, 0) + 0.587 * ch(it, 1) + 0.114 * ch(it, 2) }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/Gestures.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/Gestures.ktnew file mode 100644index 0000000..f68278f--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/Gestures.kt@@ -0,0 +1,218 @@+package io.github.artcraftandroid.procraft.canvas++import android.content.SharedPreferences+import androidx.compose.runtime.mutableStateMapOf++/** What a gesture can do: the pages of Gesture controls. */+enum class GesturePurpose(val title: String, val heading: String) {+ SMUDGE("Smudge", "Customize smudge"),+ ERASE("Erase", "Customize erase"),+ ASSISTED("Assisted Drawing", "Customize assisted drawing"),+ EYEDROPPER("Eyedropper", "Customize eyedropper"),+ QUICKSHAPE("QuickShape", "Customize QuickShape"),+ QUICKMENU("QuickMenu", "Customize QuickMenu"),+ FULL_SCREEN("Full Screen", "Customize full screen"),+ CLEAR_LAYER("Clear Layer", "Customize clear layer"),+ COPY_PASTE("Copy & Paste", "Customize copy & paste"),+ LAYER_SELECT("Layer Select", "Customize layer select"),+ HOVER("Hover", "Customize hover"),+ GENERAL("General", "General"),+}++/** A way of touching: each one does one thing at most (General's settings aside). */+enum class Trigger(val label: String) {+ TAP_MODIFY("Tap □"),+ TOUCH("Touch"),+ PEN("Pen"),+ MODIFY_TOUCH("□ + Touch"),+ MODIFY_PEN("□ + Pen"),+ THREE_SWIPE("Three-finger swipe"),+ FOUR_TAP("Four-finger tap"),+ // the pen's side buttons+ PEN_DOUBLE_TAP("Pen button"),+ PEN_SQUEEZE("Pen second button"),+ HOLD("Touch and hold"),+ SCRUB("Scrub"),+}++/**+ * One switch on a page: a trigger (or, for General and Hover, a setting of its own [key]), its+ * name, what it does, whether it starts on, and whether it has a delay slider under it.+ */+class GestureOption(+ val key: String,+ val label: String,+ val detail: String,+ val default: Boolean = false,+ val trigger: Trigger? = null,+ val delayed: Boolean = false,+)++private fun opt(t: Trigger, detail: String, default: Boolean = false) =+ GestureOption(t.name, t.label, detail, default, t, delayed = t == Trigger.HOLD)++/** Every page's switches, in order. */+val GestureOptions: Map<GesturePurpose, List<GestureOption>> = mapOf(+ GesturePurpose.SMUDGE to listOf(+ opt(Trigger.TOUCH, "Finger strokes smudge"),+ opt(Trigger.PEN, "Pen strokes smudge"),+ opt(Trigger.MODIFY_TOUCH, "Finger strokes smudge while □ is held down"),+ opt(Trigger.MODIFY_PEN, "Pen strokes smudge while □ is held down"),+ ),+ GesturePurpose.ERASE to listOf(+ opt(Trigger.TOUCH, "Finger strokes erase"),+ opt(Trigger.PEN, "Pen strokes erase"),+ opt(Trigger.MODIFY_TOUCH, "Finger strokes erase while □ is held down"),+ opt(Trigger.MODIFY_PEN, "Pen strokes erase while □ is held down"),+ ),+ GesturePurpose.ASSISTED to listOf(+ opt(Trigger.TAP_MODIFY, "Turns drawing assist on or off for this layer"),+ opt(Trigger.TOUCH, "Finger strokes follow the drawing guide"),+ opt(Trigger.PEN, "Pen strokes follow the drawing guide"),+ opt(Trigger.MODIFY_TOUCH, "Finger strokes follow the guide while □ is held down"),+ opt(Trigger.MODIFY_PEN, "Pen strokes follow the guide while □ is held down"),+ opt(Trigger.PEN_DOUBLE_TAP, "Turns drawing assist on or off for this layer"),+ ),+ GesturePurpose.EYEDROPPER to listOf(+ opt(Trigger.TAP_MODIFY, "Opens or closes the eyedropper", default = true),+ opt(Trigger.TOUCH, "A finger on the canvas picks a colour"),+ opt(Trigger.MODIFY_TOUCH, "A finger picks a colour while □ is held down", default = true),+ opt(Trigger.MODIFY_PEN, "The pen picks a colour while □ is held down", default = true),+ opt(Trigger.PEN_DOUBLE_TAP, "Opens the eyedropper"),+ opt(Trigger.PEN_SQUEEZE, "Opens the eyedropper"),+ opt(Trigger.HOLD, "A finger kept still on the canvas picks a colour", default = true),+ ),+ GesturePurpose.QUICKSHAPE to listOf(+ opt(Trigger.TAP_MODIFY, "Turns the last stroke into a shape"),+ opt(Trigger.TOUCH, "A finger touch turns the last stroke into a shape"),+ opt(Trigger.THREE_SWIPE, "Three fingers swiped down turn the last stroke into a shape"),+ opt(Trigger.FOUR_TAP, "Four fingers tapped turn the last stroke into a shape"),+ opt(Trigger.PEN_DOUBLE_TAP, "Turns the last stroke into a shape"),+ opt(Trigger.PEN_SQUEEZE, "Turns the last stroke into a shape"),+ GestureOption("DRAW_HOLD", "Draw and hold", "Pausing at the end of a stroke turns it into a shape", default = true, delayed = true),+ ),+ GesturePurpose.QUICKMENU to listOf(+ opt(Trigger.TAP_MODIFY, "Opens or closes the quick menu"),+ opt(Trigger.TOUCH, "A finger touch opens the quick menu"),+ opt(Trigger.MODIFY_TOUCH, "A finger opens the quick menu while □ is held down"),+ opt(Trigger.MODIFY_PEN, "The pen opens the quick menu while □ is held down"),+ opt(Trigger.THREE_SWIPE, "Three fingers swiped down open the quick menu"),+ opt(Trigger.FOUR_TAP, "Four fingers tapped open or close the quick menu"),+ opt(Trigger.PEN_DOUBLE_TAP, "Opens the quick menu"),+ opt(Trigger.PEN_SQUEEZE, "Opens the quick menu"),+ opt(Trigger.HOLD, "A finger kept still on the canvas opens the quick menu"),+ ),+ GesturePurpose.FULL_SCREEN to listOf(+ opt(Trigger.TOUCH, "A finger touch shows or hides the interface"),+ opt(Trigger.THREE_SWIPE, "Three fingers swiped down show or hide the interface"),+ opt(Trigger.FOUR_TAP, "Four fingers tapped show or hide the interface", default = true),+ opt(Trigger.PEN_DOUBLE_TAP, "Shows or hides the interface"),+ GestureOption("AUTO", "Automatic Full Screen", "The interface steps aside while you paint", delayed = true),+ ),+ GesturePurpose.CLEAR_LAYER to listOf(+ opt(Trigger.SCRUB, "Rubbing three fingers back and forth clears the layer", default = true),+ opt(Trigger.THREE_SWIPE, "Three fingers swiped down clear the layer"),+ opt(Trigger.FOUR_TAP, "Four fingers tapped clear the layer"),+ opt(Trigger.PEN_DOUBLE_TAP, "Clears the layer"),+ opt(Trigger.HOLD, "A finger kept still on the canvas clears the layer"),+ ),+ GesturePurpose.COPY_PASTE to listOf(+ opt(Trigger.TAP_MODIFY, "Opens the copy and paste menu"),+ opt(Trigger.TOUCH, "A finger touch opens the copy and paste menu"),+ opt(Trigger.MODIFY_TOUCH, "A finger opens the copy and paste menu while □ is held down"),+ opt(Trigger.MODIFY_PEN, "The pen opens the copy and paste menu while □ is held down"),+ opt(Trigger.THREE_SWIPE, "Three fingers swiped down open the copy and paste menu", default = true),+ opt(Trigger.FOUR_TAP, "Four fingers tapped open the copy and paste menu"),+ opt(Trigger.PEN_DOUBLE_TAP, "Opens the copy and paste menu"),+ opt(Trigger.HOLD, "A finger kept still on the canvas opens the copy and paste menu"),+ ),+ GesturePurpose.LAYER_SELECT to listOf(+ opt(Trigger.TOUCH, "A finger touch picks the layer drawn there"),+ opt(Trigger.MODIFY_TOUCH, "A finger picks the layer drawn there while □ is held down"),+ opt(Trigger.MODIFY_PEN, "The pen picks the layer drawn there while □ is held down"),+ opt(Trigger.PEN_SQUEEZE, "Picks the layer drawn under the pen"),+ opt(Trigger.HOLD, "A finger kept still picks the layer drawn there"),+ ),+ GesturePurpose.HOVER to listOf(+ GestureOption("HOVER_TOUCH", "Touch", "While the pen hovers, drag a finger for opacity and pinch for size"),+ ),+ GesturePurpose.GENERAL to listOf(+ GestureOption("FINGER_PAINT", "Painting with a finger", "One finger paints as the pen does", default = true),+ GestureOption("NO_UNDO", "Disable undo and redo gestures", "Two- and three-finger taps leave the history alone"),+ GestureOption("ROTATE", "Rotate with pinch zoom", "Two fingers turn the canvas as they zoom it", default = true),+ ),+)++/** The delays at first, seconds: holds 0.40 s, QuickShape 0.65 s, automatic full screen 0.66 s. */+private fun defaultDelay(p: GesturePurpose) = when (p) {+ GesturePurpose.QUICKSHAPE -> 0.65f+ GesturePurpose.FULL_SCREEN -> 0.66f+ else -> 0.40f+}++/** The gesture settings, kept in [prefs]: a trigger switched on for one page goes off on the others. */+class GestureSettings(private val prefs: SharedPreferences) {+ private val on = mutableStateMapOf<String, Boolean>()+ private val delays = mutableStateMapOf<GesturePurpose, Float>()++ init {+ for ((p, options) in GestureOptions) {+ for (o in options) on[name(p, o.key)] = prefs.getBoolean(name(p, o.key), o.default)+ delays[p] = prefs.getFloat("${p.name}.delay", defaultDelay(p))+ }+ }++ private fun name(p: GesturePurpose, key: String) = "${p.name}.$key"++ fun isOn(p: GesturePurpose, key: String): Boolean = on[name(p, key)] == true++ fun isOn(p: GesturePurpose, t: Trigger): Boolean = isOn(p, t.name)++ /** Turns a switch on or off; on, its trigger goes off everywhere else. */+ fun set(p: GesturePurpose, key: String, value: Boolean) {+ val edit = prefs.edit()+ val trigger = GestureOptions[p]?.firstOrNull { it.key == key }?.trigger+ if (value && trigger != null) {+ for ((other, options) in GestureOptions) {+ if (other == p) continue+ for (o in options) if (o.trigger == trigger && isOn(other, o.key)) {+ on[name(other, o.key)] = false+ edit.putBoolean(name(other, o.key), false)+ }+ }+ }+ on[name(p, key)] = value+ edit.putBoolean(name(p, key), value).apply()+ }++ /** What [t] does, if anything. */+ fun purposeOf(t: Trigger): GesturePurpose? = GestureOptions.entries.firstOrNull { (p, options) -> options.any { it.trigger == t && isOn(p, it.key) } }?.key++ /** A page's delay, seconds. */+ fun delay(p: GesturePurpose): Float = delays[p] ?: defaultDelay(p)++ fun setDelay(p: GesturePurpose, seconds: Float) {+ val s = seconds.coerceIn(MIN_DELAY_S, MAX_DELAY_S)+ delays[p] = s+ prefs.edit().putFloat("${p.name}.delay", s).apply()+ }++ /** Every switch and delay as the app ships them. */+ fun resetAll() {+ val edit = prefs.edit()+ for ((p, options) in GestureOptions) {+ for (o in options) {+ on[name(p, o.key)] = o.default+ edit.remove(name(p, o.key))+ }+ delays[p] = defaultDelay(p)+ edit.remove("${p.name}.delay")+ }+ edit.apply()+ }++ companion object {+ const val MIN_DELAY_S = 0.1f+ const val MAX_DELAY_S = 1.5f+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/NativeWindows.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/NativeWindows.ktnew file mode 100644index 0000000..00cc473--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/NativeWindows.kt@@ -0,0 +1,17 @@+package io.github.artcraftandroid.procraft.canvas++import android.view.Surface++/** Hands a [Surface]'s native window to the Rust library (`window.rs`), which draws into it. */+object NativeWindows {+ init {+ // JNA loads the library for the UniFFI bindings; the JVM needs it loaded too, for these+ System.loadLibrary("procraft_android")+ }++ /** Registers [surface]'s window and returns its id for `CanvasSession.attachWindow`, or 0. */+ @JvmStatic external fun acquire(surface: Surface): Long++ /** Lets go of a window that was never attached. */+ @JvmStatic external fun release(id: Long)+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/PadSurfaceView.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/PadSurfaceView.ktnew file mode 100644index 0000000..d17fab5--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/PadSurfaceView.kt@@ -0,0 +1,123 @@+package io.github.artcraftandroid.procraft.canvas++import android.annotation.SuppressLint+import android.content.Context+import android.util.Log+import android.view.MotionEvent+import android.view.SurfaceHolder+import android.view.SurfaceView+import io.github.artcraftandroid.procraft.core.CanvasSession+import io.github.artcraftandroid.procraft.core.MobileException+import io.github.artcraftandroid.procraft.core.PenSample+import io.github.artcraftandroid.procraft.core.PointerKind++/**+ * The brush studio's drawing pad: a small canvas of its own, as big as the view, painted with the+ * brush being edited. Pen and finger both paint; there are no gestures.+ */+/** How often (ms) the pad is asked whether it has drawn yet, and for how long at most. */+private const val PAD_POLL_MS = 32L+private const val PAD_POLL_LIMIT_MS = 4000L++class PadSurfaceView(context: Context, private val vm: CanvasViewModel) : SurfaceView(context), SurfaceHolder.Callback {+ private var attached = false+ private var strokePointer = -1++ init {+ // over the canvas's own surface, under the studio's controls+ setZOrderMediaOverlay(true)+ holder.addCallback(this)+ }++ override fun surfaceCreated(holder: SurfaceHolder) = Unit++ override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {+ val pad = vm.pad ?: CanvasSession(width.toUInt(), height.toUInt()).also { vm.startPad(it) }+ if (attached) {+ pad.resizeWindow(width.toUInt(), height.toUInt())+ return+ }+ val id = NativeWindows.acquire(holder.surface)+ if (id == 0L) return+ try {+ pad.attachWindow(id.toULong(), width.toUInt(), height.toUInt())+ pad.setDisplayScale(resources.displayMetrics.density)+ attached = true+ // uncovered once it has drawn a frame of its own+ uncoverWhenDrawn(pad)+ } catch (e: MobileException) {+ NativeWindows.release(id)+ Log.e("ProCraft", "attaching the pad", e)+ }+ }++ /**+ * Once the pad has presented a frame (or after a while regardless), draws its sample scribble,+ * and uncovers it (see [CanvasViewModel.padShown]) a poll later, the scribble drawn.+ */+ private fun uncoverWhenDrawn(pad: CanvasSession, waited: Long = 0L, scribbled: Boolean = false) {+ if (vm.pad !== pad) return+ if (scribbled) {+ vm.padShown = true+ return+ }+ if (waited >= PAD_POLL_LIMIT_MS || runCatching { pad.info().frames > 0uL }.getOrDefault(true)) {+ vm.padReady(pad)+ postDelayed({ uncoverWhenDrawn(pad, waited, scribbled = true) }, PAD_POLL_MS)+ return+ }+ postDelayed({ uncoverWhenDrawn(pad, waited + PAD_POLL_MS) }, PAD_POLL_MS)+ }++ override fun surfaceDestroyed(holder: SurfaceHolder) {+ vm.pad?.detachWindow()+ attached = false+ }++ @SuppressLint("ClickableViewAccessibility")+ override fun onTouchEvent(e: MotionEvent): Boolean {+ val pad = vm.pad ?: return true+ when (e.actionMasked) {+ MotionEvent.ACTION_DOWN -> {+ requestUnbufferedDispatch(e)+ vm.padMenuOpen = false+ strokePointer = e.getPointerId(0)+ // the first stroke of one's own takes the sample scribble's place+ pad.beginOwnStroke()+ pad.strokeBegin(kindOf(e), samples(e, 0))+ }+ MotionEvent.ACTION_MOVE -> {+ val i = e.findPointerIndex(strokePointer)+ if (i >= 0) pad.strokeAdd(samples(e, i))+ }+ MotionEvent.ACTION_UP -> {+ val i = e.findPointerIndex(strokePointer)+ pad.strokeEnd(if (i >= 0) samples(e, i) else emptyList())+ }+ MotionEvent.ACTION_CANCEL -> pad.strokeCancel()+ }+ return true+ }++ private fun kindOf(e: MotionEvent): PointerKind = when (e.getToolType(0)) {+ MotionEvent.TOOL_TYPE_STYLUS -> PointerKind.STYLUS+ MotionEvent.TOOL_TYPE_ERASER -> PointerKind.STYLUS_ERASER+ else -> PointerKind.FINGER+ }++ private fun samples(e: MotionEvent, i: Int): List<PenSample> {+ val out = ArrayList<PenSample>(e.historySize + 1)+ for (h in 0 until e.historySize) {+ out += PenSample(+ e.getHistoricalX(i, h),+ e.getHistoricalY(i, h),+ e.getHistoricalPressure(i, h),+ e.getHistoricalAxisValue(MotionEvent.AXIS_TILT, i, h),+ e.getHistoricalOrientation(i, h),+ e.getHistoricalEventTime(h).toDouble(),+ )+ }+ out += PenSample(e.getX(i), e.getY(i), e.getPressure(i), e.getAxisValue(MotionEvent.AXIS_TILT, i), e.getOrientation(i), e.eventTime.toDouble())+ return out+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/Projection.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/Projection.ktnew file mode 100644index 0000000..7789fd4--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/Projection.kt@@ -0,0 +1,31 @@+package io.github.artcraftandroid.procraft.canvas++import android.app.Presentation+import android.content.Context+import android.graphics.Color+import android.graphics.drawable.ColorDrawable+import android.os.Bundle+import android.view.Display+import android.view.SurfaceHolder+import android.view.SurfaceView++/** Project canvas on [display]: one full-screen surface the session draws the canvas into. */+class ProjectionPresentation(context: Context, display: Display, private val vm: CanvasViewModel) : Presentation(context, display) {+ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ window?.setBackgroundDrawable(ColorDrawable(Color.BLACK))+ val view = SurfaceView(context)+ view.holder.addCallback(object : SurfaceHolder.Callback {+ override fun surfaceCreated(holder: SurfaceHolder) = Unit++ override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {+ vm.setProjectionSurface(holder.surface, width, height)+ }++ override fun surfaceDestroyed(holder: SurfaceHolder) {+ vm.setProjectionSurface(null)+ }+ })+ setContentView(view)+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/QuickActions.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/QuickActions.ktnew file mode 100644index 0000000..12bd802--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/QuickActions.kt@@ -0,0 +1,56 @@+package io.github.artcraftandroid.procraft.canvas++/** What a QuickMenu button can be set to do. */+enum class QuickAction(val label: String) {+ NONE("No Action"),+ NEW_LAYER("New Layer"),+ DUPLICATE_LAYER("Duplicate Layer"),+ DELETE_LAYER("Delete Layer"),+ MERGE_DOWN("Merge Down"),+ CLEAR_LAYER("Clear Layer"),+ FILL_LAYER("Fill Layer"),+ SELECT_LAYER("Select Layer"),+ ALPHA_LOCK("Alpha Lock"),+ LAYER_VISIBILITY("Layer Visibility"),+ COPY("Copy"),+ CUT("Cut"),+ PASTE("Paste"),+ COPY_PASTE_MENU("Copy & Paste Menu"),+ FLIP_HORIZONTAL("Flip Horizontal"),+ FLIP_VERTICAL("Flip Vertical"),+ UNDO("Undo"),+ REDO("Redo"),+ PAINT("Paint"),+ SMUDGE("Smudge"),+ ERASE("Erase"),+ EYEDROPPER("Eyedropper"),+ SWAP_COLORS("Swap Colors"),+ SELECTION("Selection"),+ INVERT_SELECTION("Invert Selection"),+ TRANSFORM("Transform"),+ ADJUSTMENTS("Adjustments"),+ COLORS("Colors"),+ LAYERS("Layers"),+ BRUSHES("Brushes"),+ ACTIONS("Actions"),+ INTERFACE("Interface"),+ FIT_CANVAS("Fit Canvas"),+ ADD_TEXT("Add Text"),+ QUICKSHAPE("QuickShape"),+ LAYER_SELECT("Layer Select"),+ DRAWING_GUIDE("Drawing Guide"),+ ;++ /** What its button in the menu says: the name in sentence case, the flips as verbs. */+ val button: String+ get() = when (this) {+ FLIP_HORIZONTAL -> "Flip horizontally"+ FLIP_VERTICAL -> "Flip vertically"+ else -> label.take(1) + label.drop(1).lowercase()+ }++ companion object {+ /** The buttons a QuickMenu starts with, clockwise from the top. */+ val DEFAULTS = listOf(NEW_LAYER, FLIP_HORIZONTAL, COPY, MERGE_DOWN, CLEAR_LAYER, FLIP_VERTICAL)+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/TextRenderer.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/TextRenderer.ktnew file mode 100644index 0000000..78aab2b--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/TextRenderer.kt@@ -0,0 +1,147 @@+package io.github.artcraftandroid.procraft.canvas++import android.content.res.AssetManager+import android.graphics.Bitmap+import android.graphics.Canvas+import android.graphics.Paint+import android.graphics.RectF+import android.graphics.Typeface+import android.text.Layout+import android.text.StaticLayout+import android.text.TextPaint+import io.github.artcraftandroid.procraft.core.TextAlignment+import io.github.artcraftandroid.procraft.core.TextInfo+import java.nio.ByteBuffer+import kotlin.math.ceil+import kotlin.math.roundToInt++/**+ * Lays text layers out and draws them, with the platform's typefaces (and the bundled Inter):+ * the layer's pixels come from here whenever its text or look changes.+ */+object TextRenderer {+ /** A typeface the text tool offers: the name shown, and the family it is made from. */+ class Family(val name: String, val family: String)++ private val builtIn = listOf(+ Family("Sans Serif", "sans-serif"),+ Family("Sans Serif Condensed", "sans-serif-condensed"),+ Family("Serif", "serif"),+ Family("Monospace", "monospace"),+ Family("Serif Monospace", "serif-monospace"),+ Family("Casual", "casual"),+ Family("Cursive", "cursive"),+ Family("Small Caps", "sans-serif-smallcaps"),+ Family("Inter", INTER),+ )++ /** Fonts imported into the app, kept in its files. */+ val imported = androidx.compose.runtime.mutableStateListOf<Family>()++ /** Every typeface on offer: the system's, Inter and those imported. */+ val families: List<Family> get() = builtIn + imported++ /** Reads the imported fonts kept in [dir]. */+ fun loadImported(dir: java.io.File) {+ imported.clear()+ dir.listFiles { f -> f.extension.lowercase() in listOf("ttf", "otf") }?.sortedBy { it.name.lowercase() }?.forEach {+ imported.add(Family(it.nameWithoutExtension, FILE + it.path))+ }+ }++ /** The styles a family offers: a name, its weight and whether it slants. */+ class Style(val name: String, val weight: Int, val italic: Boolean)++ val styles = listOf(+ Style("Thin", 100, false), Style("Thin Italic", 100, true),+ Style("Light", 300, false), Style("Light Italic", 300, true),+ Style("Regular", 400, false), Style("Italic", 400, true),+ Style("Medium", 500, false), Style("Medium Italic", 500, true),+ Style("Bold", 700, false), Style("Bold Italic", 700, true),+ Style("Black", 900, false), Style("Black Italic", 900, true),+ )++ /** Where the bundled Inter comes from (set once the app starts). */+ var assets: AssetManager? = null++ fun typeface(font: String, style: String): Typeface {+ val s = styles.firstOrNull { it.name == style } ?: styles.first { it.name == "Regular" }+ val base = if (font == INTER) {+ val file = when {+ s.weight >= 700 -> "fonts/Inter-Bold.ttf"+ s.weight >= 600 -> "fonts/Inter-SemiBold.ttf"+ s.weight >= 500 -> "fonts/Inter-Medium.ttf"+ else -> "fonts/Inter-Regular.ttf"+ }+ assets?.let { runCatching { Typeface.createFromAsset(it, file) }.getOrNull() } ?: Typeface.SANS_SERIF+ } else if (font.startsWith(FILE)) {+ runCatching { Typeface.createFromFile(font.removePrefix(FILE)) }.getOrNull() ?: Typeface.SANS_SERIF+ } else {+ Typeface.create(font.ifEmpty { "sans-serif" }, Typeface.NORMAL)+ }+ return Typeface.create(base, s.weight, s.italic)+ }++ private fun paint(t: TextInfo): TextPaint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply {+ typeface = typeface(t.font, t.style)+ textSize = t.size+ val a = (t.opacity.coerceIn(0f, 1f) * 255).roundToInt()+ color = android.graphics.Color.argb(a, (t.r * 255).roundToInt(), (t.g * 255).roundToInt(), (t.b * 255).roundToInt())+ // spacing between letters, in sizes+ letterSpacing = t.tracking + t.kerning+ isUnderlineText = t.underline+ if (t.outline) {+ style = Paint.Style.STROKE+ strokeWidth = (t.size * OUTLINE).coerceAtLeast(1f)+ }+ }++ /** What is drawn: upper case if asked, one letter a line when vertical. */+ private fun shown(t: TextInfo): String {+ val text = if (t.allCaps) t.text.uppercase() else t.text+ return if (t.vertical) text.lines().joinToString("\n\n") { line -> line.toList().joinToString("\n") } else text+ }++ fun layout(t: TextInfo): StaticLayout {+ val p = paint(t)+ val text = shown(t)+ val natural = text.lines().maxOfOrNull { ceil(StaticLayout.getDesiredWidth(it, p)).toInt() } ?: 0+ val width = if (t.width > 0f) t.width.roundToInt() else natural.coerceAtLeast(1)+ val align = when (t.align) {+ TextAlignment.CENTER -> Layout.Alignment.ALIGN_CENTER+ TextAlignment.RIGHT -> Layout.Alignment.ALIGN_OPPOSITE+ else -> Layout.Alignment.ALIGN_NORMAL+ }+ return StaticLayout.Builder.obtain(text, 0, text.length, p, width.coerceAtLeast(1))+ .setAlignment(align)+ .setLineSpacing(t.leading * t.size, 1f)+ .setIncludePad(false)+ .setJustificationMode(if (t.align == TextAlignment.JUSTIFY) Layout.JUSTIFICATION_MODE_INTER_WORD else Layout.JUSTIFICATION_MODE_NONE)+ .build()+ }++ /** The text's box on the canvas, pixels. */+ fun bounds(t: TextInfo): RectF {+ val l = layout(t)+ val top = t.y - t.baseline * t.size+ return RectF(t.x, top, t.x + l.width, top + l.height)+ }++ /** The text drawn over transparency on a picture the canvas's size: premultiplied RGBA8. */+ fun render(t: TextInfo, width: Int, height: Int): ByteArray {+ val bitmap = Bitmap.createBitmap(width.coerceAtLeast(1), height.coerceAtLeast(1), Bitmap.Config.ARGB_8888)+ val canvas = Canvas(bitmap)+ canvas.translate(t.x, t.y - t.baseline * t.size)+ layout(t).draw(canvas)+ val buffer = ByteBuffer.allocate(bitmap.byteCount)+ bitmap.copyPixelsToBuffer(buffer)+ bitmap.recycle()+ return buffer.array()+ }++ const val INTER = "inter"+ /** An imported font's family: this, then the file's path. */+ const val FILE = "file:"+ /** An outline's width, as a fraction of the size. */+ private const val OUTLINE = 0.04f+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/TimeLapse.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/TimeLapse.ktnew file mode 100644index 0000000..64c8911--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/TimeLapse.kt@@ -0,0 +1,128 @@+package io.github.artcraftandroid.procraft.canvas++import android.graphics.Bitmap+import android.graphics.BitmapFactory+import android.graphics.Canvas+import android.graphics.Color+import android.graphics.Paint+import android.graphics.Rect+import java.io.File+import java.nio.ByteBuffer++/**+ * An artwork's time-lapse: a picture of the whole canvas after each change, kept as numbered JPEG+ * frames in the artwork's folder, replayed or made into a video at [FPS] frames a second.+ */+/**+ * A time-lapse's video: 1080p, 2K or 4K ([resolution] 0 to 2), Low, Good, Studio quality or+ * Lossless ([quality] 0 to 3), and HEVC or H.264.+ */+data class TimeLapseSettings(val resolution: Int = 0, val quality: Int = 1, val hevc: Boolean = false) {+ /** The frames' longest side, pixels. */+ val side: Int get() = listOf(1920, 2732, 3840).getOrElse(resolution) { 1920 }+ val bitsPerPixel: Int get() = listOf(2, 4, 8, 16).getOrElse(quality) { 4 }+}++class TimeLapse(artwork: File) {+ private val dir = File(artwork, "timelapse")+ private val off = File(dir, "off")+ private val settingsFile = File(dir, "settings.json")++ /** The video's size, quality and codec, kept with the artwork. */+ var settings: TimeLapseSettings = runCatching {+ val j = org.json.JSONObject(settingsFile.readText())+ TimeLapseSettings(j.optInt("resolution", 0), j.optInt("quality", 1), j.optBoolean("hevc", false))+ }.getOrDefault(TimeLapseSettings())+ set(v) {+ field = v+ dir.mkdirs()+ runCatching {+ settingsFile.writeText(org.json.JSONObject().put("resolution", v.resolution).put("quality", v.quality).put("hevc", v.hevc).toString())+ }+ }++ /** Frames recorded so far. */+ var count: Int = dir.listFiles { f -> f.name.startsWith("frame-") }?.size ?: 0+ private set++ /** Whether changes are recorded (on unless turned off for this artwork). */+ var recording: Boolean+ get() = !off.exists()+ set(on) {+ dir.mkdirs()+ if (on) off.delete() else off.createNewFile()+ }++ private var last: Int? = null++ private fun file(i: Int) = File(dir, "frame-%06d.jpg".format(i))++ /** Keeps a frame (premultiplied RGBA, [width] × [height]) unless it is the same as the last. */+ fun record(rgba: ByteArray, width: Int, height: Int) {+ if (!recording || width <= 0 || height <= 0) return+ val hash = rgba.contentHashCode()+ if (hash == last) return+ last = hash+ val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)+ bitmap.copyPixelsFromBuffer(ByteBuffer.wrap(rgba))+ // on white, as the canvas shows a hidden background+ val flat = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)+ Canvas(flat).apply {+ drawColor(Color.WHITE)+ drawBitmap(bitmap, 0f, 0f, null)+ }+ dir.mkdirs()+ runCatching { file(count).outputStream().use { flat.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, it) } }.onSuccess { count++ }+ bitmap.recycle()+ flat.recycle()+ }++ /** What the recorded frames take on disk, bytes. */+ fun bytes(): Long = dir.listFiles { f -> f.name.startsWith("frame-") }?.sumOf { it.length() } ?: 0L++ fun frame(i: Int): Bitmap? = runCatching { BitmapFactory.decodeFile(file(i).path) }.getOrNull()++ /**+ * The frames as an H.264 MP4 at [out]: all of them, or (with [seconds]) spread evenly over+ * that long. False if there are none or the encoder fails.+ */+ fun export(out: File, seconds: Int?): Boolean {+ if (count == 0) return false+ val picks = if (seconds != null && count > seconds * FPS) {+ val n = seconds * FPS+ List(n) { (it.toLong() * (count - 1) / (n - 1).coerceAtLeast(1)).toInt() }+ } else List(count) { it }+ val first = frame(picks.first()) ?: return false+ val video = settings+ val mime = if (video.hevc) android.media.MediaFormat.MIMETYPE_VIDEO_HEVC else android.media.MediaFormat.MIMETYPE_VIDEO_AVC+ val (w, h) = VideoWriter.fit(first.width, first.height, video.side, mime) ?: return false+ first.recycle()+ val frameBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)+ val paint = Paint(Paint.FILTER_BITMAP_FLAG)+ try {+ return VideoWriter.write(out, w, h, FPS, picks.size, mime, video.bitsPerPixel) { n, pixels ->+ val source = frame(picks[n]) ?: return@write false+ // fitted on white+ Canvas(frameBitmap).apply {+ drawColor(Color.WHITE)+ val s = minOf(w / source.width.toFloat(), h / source.height.toFloat())+ val dw = (source.width * s).toInt()+ val dh = (source.height * s).toInt()+ drawBitmap(source, null, Rect((w - dw) / 2, (h - dh) / 2, (w + dw) / 2, (h + dh) / 2), paint)+ }+ source.recycle()+ frameBitmap.getPixels(pixels, 0, w, 0, 0, w, h)+ true+ }+ } finally {+ frameBitmap.recycle()+ }+ }++ companion object {+ const val FPS = 30+ /** A frame's longest side, pixels. */+ const val FRAME_SIDE = 1280+ private const val JPEG_QUALITY = 85+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/TransformHandles.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/TransformHandles.ktnew file mode 100644index 0000000..225ea92--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/TransformHandles.kt@@ -0,0 +1,68 @@+package io.github.artcraftandroid.procraft.canvas++import androidx.compose.ui.geometry.Offset+import io.github.artcraftandroid.procraft.core.TransformBox+import io.github.artcraftandroid.procraft.core.TransformHandle++/** How far the rotate node sits above the box's top edge, and the box-turning node below its bottom (dp). */+const val ROTATE_LIFT_DP = 34.5f+const val TURN_DROP_DP = 35.5f++/** How near a node a touch must land to take it (dp). */+private const val GRAB_RADIUS_DP = 37.5f++/** How near a warp's control point a touch must land to take it rather than the surface (dp). */+private const val MESH_GRAB_RADIUS_DP = 15f++/** The warp's control points a touch can take: the corners, or all 16 with the advanced mesh. */+fun shownMeshPoints(advanced: Boolean): List<Int> = if (advanced) (0 until 16).toList() else listOf(0, 3, 12, 15)++/** Canvas point ([x], [y]) through the view [m] (`[a, b, c, d, e, f]`), in window pixels. */+fun toScreen(x: Float, y: Float, m: List<Float>): Offset = Offset(m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5])++/**+ * The transform box on screen, in window pixels: its corners (top left, top right, bottom right,+ * bottom left), the middles of its edges (top, right, bottom, left), the rotate node above it, the+ * node below it that turns the box alone, and the box's up direction.+ */+class BoxOnScreen(val corners: List<Offset>, val edges: List<Offset>, val rotate: Offset, val turn: Offset, val up: Offset)++/** Where [box] (canvas pixels) shows through the view [m] (`[a, b, c, d, e, f]`); [density] is pixels per dp. */+fun boxOnScreen(box: TransformBox, m: List<Float>, density: Float): BoxOnScreen? {+ val c = box.corners+ if (c.size < 8 || m.size < 6) return null+ val corners = List(4) { i -> toScreen(c[2 * i], c[2 * i + 1], m) }+ val edges = List(4) { (corners[it] + corners[(it + 1) % 4]) / 2f }+ val upward = edges[0] - edges[2]+ val length = upward.getDistance()+ val up = if (length > 1e-3f) upward / length else Offset(0f, -1f)+ // the box's right, a quarter turn clockwise from up+ val right = Offset(-up.y, up.x)+ val rotate = edges[0] + up * (ROTATE_LIFT_DP * density)+ val turn = edges[2] - up * (TURN_DROP_DP * density) + right * density+ return BoxOnScreen(corners, edges, rotate, turn, up)+}++/** In a warp: the control point a touch at window point [p] takes, otherwise the surface under it (a move). */+fun meshHandleAt(box: TransformBox, m: List<Float>, p: Offset, density: Float, advanced: Boolean): TransformHandle {+ val mesh = box.mesh+ if (mesh.size < 32 || m.size < 6) return TransformHandle.Move+ val reach = MESH_GRAB_RADIUS_DP * density+ val nearest = shownMeshPoints(advanced).minByOrNull { (toScreen(mesh[2 * it], mesh[2 * it + 1], m) - p).getDistance() }+ ?: return TransformHandle.Move+ val at = toScreen(mesh[2 * nearest], mesh[2 * nearest + 1], m)+ return if ((at - p).getDistance() <= reach) TransformHandle.Mesh(nearest.toUByte()) else TransformHandle.Move+}++/** The handle a touch at window point [p] takes: the nearest node within reach, otherwise a move. */+fun handleAt(box: BoxOnScreen, p: Offset, density: Float): TransformHandle {+ val reach = GRAB_RADIUS_DP * density+ val nodes = buildList {+ add(TransformHandle.Rotate to box.rotate)+ add(TransformHandle.TurnBox to box.turn)+ box.corners.forEachIndexed { i, c -> add(TransformHandle.Corner(i.toUByte()) to c) }+ box.edges.forEachIndexed { i, c -> add(TransformHandle.Edge(i.toUByte()) to c) }+ }+ val nearest = nodes.minByOrNull { (_, at) -> (at - p).getDistance() } ?: return TransformHandle.Move+ return if ((nearest.second - p).getDistance() <= reach) nearest.first else TransformHandle.Move+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/VideoWriter.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/VideoWriter.ktnew file mode 100644index 0000000..3cbbee3--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/VideoWriter.kt@@ -0,0 +1,131 @@+package io.github.artcraftandroid.procraft.canvas++import android.media.MediaCodec+import android.media.MediaCodecInfo+import android.media.MediaCodecList+import android.media.MediaFormat+import android.media.MediaMuxer+import java.io.File++/** Video files made a frame at a time with the device's encoder. */+object VideoWriter {+ private const val BITS_PER_PIXEL = 4+ private const val TIMEOUT_US = 10_000L++ /**+ * The largest size no bigger than [width] × [height] (same shape, even sides, longest side at+ * most [maxSide]) the encoder for [mime] takes; null if there is no such encoder.+ */+ fun fit(width: Int, height: Int, maxSide: Int, mime: String = MediaFormat.MIMETYPE_VIDEO_AVC): Pair<Int, Int>? {+ val caps = MediaCodecList(MediaCodecList.REGULAR_CODECS).codecInfos+ .filter { it.isEncoder && it.supportedTypes.any { t -> t.equals(mime, ignoreCase = true) } }+ .mapNotNull { runCatching { it.getCapabilitiesForType(mime).videoCapabilities }.getOrNull() }+ if (caps.isEmpty()) return null+ var scale = minOf(1f, maxSide / maxOf(width, height).toFloat())+ repeat(40) {+ val w = ((width * scale).toInt() / 2 * 2).coerceAtLeast(2)+ val h = ((height * scale).toInt() / 2 * 2).coerceAtLeast(2)+ if (caps.any { it.isSizeSupported(w, h) }) return w to h+ scale *= 0.9f+ }+ return null+ }++ /**+ * [count] frames, [width] × [height] (even), [fps] a second, as an MP4 at [out] encoded with+ * [mime]. [frame] fills a frame's ARGB pixels (rows top to bottom) and says whether it has one.+ * False if the encoder fails.+ */+ fun write(+ out: File, width: Int, height: Int, fps: Int, count: Int, mime: String = MediaFormat.MIMETYPE_VIDEO_AVC,+ bitsPerPixel: Int = BITS_PER_PIXEL, frame: (Int, IntArray) -> Boolean,+ ): Boolean {+ val format = MediaFormat.createVideoFormat(mime, width, height).apply {+ setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible)+ setInteger(MediaFormat.KEY_BIT_RATE, (width * height * bitsPerPixel).coerceAtLeast(1_000_000))+ setInteger(MediaFormat.KEY_FRAME_RATE, fps)+ setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1)+ }+ val codec = runCatching { MediaCodec.createEncoderByType(mime) }.getOrNull() ?: return false+ val muxer = MediaMuxer(out.path, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)+ var track = -1+ val info = MediaCodec.BufferInfo()+ val pixels = IntArray(width * height)+ try {+ codec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)+ codec.start()+ fun drain(end: Boolean) {+ while (true) {+ val index = codec.dequeueOutputBuffer(info, if (end) TIMEOUT_US else 0)+ when {+ index == MediaCodec.INFO_TRY_AGAIN_LATER -> if (!end) return+ index == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED -> {+ track = muxer.addTrack(codec.outputFormat)+ muxer.start()+ }+ index >= 0 -> {+ val buffer = codec.getOutputBuffer(index)+ if (buffer != null && info.size > 0 && track >= 0 && info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG == 0) {+ muxer.writeSampleData(track, buffer, info)+ }+ codec.releaseOutputBuffer(index, false)+ if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) return+ }+ }+ }+ }+ fun nextInput(): Int {+ var input: Int+ do {+ input = codec.dequeueInputBuffer(TIMEOUT_US)+ if (input < 0) drain(false)+ } while (input < 0)+ return input+ }+ var n = 0+ for (i in 0 until count) {+ if (!frame(i, pixels)) continue+ val input = nextInput()+ val image = codec.getInputImage(input) ?: continue+ writeYuv(image, pixels, width, height)+ codec.queueInputBuffer(input, 0, width * height * 3 / 2, n * 1_000_000L / fps, 0)+ n+++ drain(false)+ }+ codec.queueInputBuffer(nextInput(), 0, 0, n * 1_000_000L / fps, MediaCodec.BUFFER_FLAG_END_OF_STREAM)+ drain(true)+ return track >= 0+ } catch (e: Exception) {+ android.util.Log.e("ProCraft", "video", e)+ return false+ } finally {+ runCatching { codec.stop() }+ codec.release()+ runCatching { if (track >= 0) muxer.stop() }+ muxer.release()+ }+ }++ /** ARGB pixels into the encoder's YUV 4:2:0 planes (BT.601, video range). */+ private fun writeYuv(image: android.media.Image, argb: IntArray, w: Int, h: Int) {+ val planes = image.planes+ val y = planes[0]+ val u = planes[1]+ val v = planes[2]+ for (row in 0 until h) {+ for (col in 0 until w) {+ val c = argb[row * w + col]+ val r = (c shr 16) and 255+ val g = (c shr 8) and 255+ val b = c and 255+ y.buffer.put(row * y.rowStride + col * y.pixelStride, (((66 * r + 129 * g + 25 * b + 128) shr 8) + 16).toByte())+ if (row % 2 == 0 && col % 2 == 0) {+ val cu = ((-38 * r - 74 * g + 112 * b + 128) shr 8) + 128+ val cv = ((112 * r - 94 * g - 18 * b + 128) shr 8) + 128+ u.buffer.put((row / 2) * u.rowStride + (col / 2) * u.pixelStride, cu.toByte())+ v.buffer.put((row / 2) * v.rowStride + (col / 2) * v.pixelStride, cv.toByte())+ }+ }+ }+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/ArtworkFile.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/ArtworkFile.ktnew file mode 100644index 0000000..a340570--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/ArtworkFile.kt@@ -0,0 +1,53 @@+package io.github.artcraftandroid.procraft.gallery++import java.io.File+import java.io.InputStream+import java.util.zip.ZipEntry+import java.util.zip.ZipInputStream+import java.util.zip.ZipOutputStream++/**+ * An artwork as one file to share or keep elsewhere: its folder (the document, every layer, the+ * thumbnail and the time-lapse) in a zip.+ */+object ArtworkFile {+ const val EXTENSION = "procraft"++ /** Zips the artwork folder [dir] into [out]. */+ fun write(dir: File, out: File) {+ ZipOutputStream(out.outputStream().buffered()).use { zip ->+ dir.walkTopDown().filter { it.isFile && !it.name.endsWith(".tmp") }.forEach { f ->+ zip.putNextEntry(ZipEntry(f.relativeTo(dir).invariantSeparatorsPath))+ f.inputStream().use { it.copyTo(zip) }+ zip.closeEntry()+ }+ }+ }++ /**+ * Unzips an artwork file into the empty folder [dir]; false (and nothing kept) if it isn't+ * one. Only the files an artwork has are taken, and none outside the folder.+ */+ fun read(input: InputStream, dir: File): Boolean {+ val root = dir.canonicalFile+ var found = false+ ZipInputStream(input.buffered()).use { zip ->+ while (true) {+ val entry = zip.nextEntry ?: break+ val name = entry.name+ val allowed = name == "artwork.json" || name == "thumbnail.png" ||+ (name.startsWith("layers/") && name.endsWith(".png")) ||+ (name.startsWith("timelapse/") && (name.endsWith(".jpg") || name == "timelapse/off")) ||+ name == "about/photo.jpg" || name == "about/signature.json"+ if (entry.isDirectory || !allowed || name.contains("..")) continue+ val target = File(root, name).canonicalFile+ if (!target.path.startsWith(root.path + File.separator)) continue+ target.parentFile?.mkdirs()+ target.outputStream().use { zip.copyTo(it) }+ if (name == "artwork.json") found = true+ }+ }+ if (!found) dir.deleteRecursively()+ return found+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/ArtworkStore.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/ArtworkStore.ktnew file mode 100644index 0000000..6925243--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/ArtworkStore.kt@@ -0,0 +1,179 @@+package io.github.artcraftandroid.procraft.gallery++import io.github.artcraftandroid.procraft.canvas.TimeLapseSettings+import org.json.JSONObject+import java.io.File+import java.util.Locale+import java.util.UUID+import kotlin.math.roundToInt++/** Something the gallery shows: an artwork, or a stack of them. */+sealed interface GalleryEntry {+ val dir: File+ val name: String+ val modified: Long+}++/** A saved artwork: its folder (see the native library's `project.rs` for what is inside). */+data class Artwork(override val dir: File, override val name: String, val width: Int, val height: Int, override val modified: Long) : GalleryEntry {+ val thumbnail: File get() = File(dir, "thumbnail.png")+}++/** Artworks kept together: a folder holding their folders, newest first. */+data class Stack(override val dir: File, override val name: String, val artworks: List<Artwork>) : GalleryEntry {+ override val modified: Long get() = artworks.maxOfOrNull { it.modified } ?: dir.lastModified()+}++/** The artworks in the app's private storage, one folder each, some in stacks (a folder of them). */+class ArtworkStore(val root: File) {+ init {+ root.mkdirs()+ }++ /** What is in [at] (the gallery, or a stack's folder), newest first; empty stacks go away. */+ fun list(at: File = root): List<GalleryEntry> = at.listFiles { f -> f.isDirectory }.orEmpty().mapNotNull { dir ->+ read(dir) ?: if (at == root) readStack(dir) else null+ }.sortedByDescending { it.modified }++ fun newFolder(at: File = root): File = File(at, UUID.randomUUID().toString()).also { it.mkdirs() }++ fun delete(a: Artwork) {+ a.dir.deleteRecursively()+ }++ /** A copy beside the original, named "<name> copy" (the copy's title is set by the caller when opened). */+ fun duplicate(a: Artwork): File {+ val copy = newFolder(a.dir.parentFile ?: root)+ a.dir.copyRecursively(copy, overwrite = true)+ File(copy, "artwork.json").let { f ->+ runCatching {+ val json = JSONObject(f.readText())+ json.put("name", "${a.name} copy")+ f.writeText(json.toString())+ }+ }+ copy.setLastModified(System.currentTimeMillis())+ return copy+ }++ fun rename(a: Artwork, name: String) {+ val f = File(a.dir, "artwork.json")+ runCatching {+ val json = JSONObject(f.readText())+ json.put("name", name.trim())+ f.writeText(json.toString())+ }+ }++ /** A new stack in the gallery holding [artworks] (moved into it). */+ fun stack(artworks: List<Artwork>): File {+ val dir = newFolder(root)+ File(dir, STACK_FILE).writeText(JSONObject().put("name", "Stack").toString())+ for (a in artworks) a.dir.renameTo(File(dir, a.dir.name))+ return dir+ }++ fun renameStack(s: Stack, name: String) {+ runCatching { File(s.dir, STACK_FILE).writeText(JSONObject().put("name", name.trim().ifEmpty { "Stack" }).toString()) }+ }++ private fun read(dir: File): Artwork? {+ val f = File(dir, "artwork.json")+ if (!f.isFile) return null+ return runCatching {+ val json = JSONObject(f.readText())+ val doc = json.getJSONObject("document")+ Artwork(dir, json.optString("name", "Untitled Artwork"), doc.optInt("width"), doc.optInt("height"), f.lastModified())+ }.getOrNull()+ }++ private fun readStack(dir: File): Stack? {+ val f = File(dir, STACK_FILE)+ if (!f.isFile) return null+ val artworks = list(dir).filterIsInstance<Artwork>()+ if (artworks.isEmpty()) {+ dir.deleteRecursively()+ return null+ }+ val name = runCatching { JSONObject(f.readText()).optString("name", "Stack") }.getOrDefault("Stack")+ return Stack(dir, name, artworks)+ }++ private companion object {+ const val STACK_FILE = "stack.json"+ }+}++/**+ * A canvas to start from, in the New canvas list: its name, its size in [unit] ("px", "mm", "cm"+ * or "in"), DPI, background (and whether it is hidden) and time-lapse video.+ */+data class CanvasPreset(+ val name: String,+ val unit: String,+ val sizeWidth: Float,+ val sizeHeight: Float,+ val dpi: Float,+ val background: Int = 0xFFFFFF,+ val backgroundHidden: Boolean = false,+ val timeLapse: TimeLapseSettings = TimeLapseSettings(),+ /** The colour profile, by name. */+ val profile: String = SRGB,+) {+ val width: Int get() = pixels(sizeWidth)+ val height: Int get() = pixels(sizeHeight)++ /** The size as the list shows it, in its unit. */+ val label: String+ get() = if (unit == "in") "${number(sizeWidth)}″ × ${number(sizeHeight)}″" else "${number(sizeWidth)} × ${number(sizeHeight)}$unit"++ private fun pixels(v: Float): Int = (perInch(unit)?.let { v / it * dpi } ?: v).roundToInt().coerceIn(1, MAX_SIDE)++ fun toJson(): JSONObject = JSONObject().put("name", name).put("unit", unit).put("width", sizeWidth.toDouble()).put("height", sizeHeight.toDouble())+ .put("dpi", dpi.toDouble()).put("background", background).put("hidden", backgroundHidden)+ .put("resolution", timeLapse.resolution).put("quality", timeLapse.quality).put("hevc", timeLapse.hevc).put("profile", profile)++ companion object {+ /** The longest side a canvas can have, pixels. */+ const val MAX_SIDE = 16384++ const val SRGB = "sRGB IEC61966-2.1"+ const val P3 = "Display P3"++ /** A profile as a list's chip shows it. */+ fun chip(profile: String): String = when {+ profile == P3 -> "P3"+ io.github.artcraftandroid.procraft.core.isCmykProfile(profile) -> "CMYK"+ else -> "sRGB"+ }++ /** How many of [unit] make an inch; null for pixels. */+ fun perInch(unit: String): Float? = when (unit) {+ "mm" -> 25.4f+ "cm" -> 2.54f+ "in" -> 1f+ else -> null+ }++ /** [v] with at most two decimals and no trailing zeros. */+ fun number(v: Float): String = "%.2f".format(Locale.ROOT, v).trimEnd('0').trimEnd('.')++ fun fromJson(j: JSONObject) = CanvasPreset(+ j.optString("name", "Untitled Canvas"), j.optString("unit", "px"), j.optDouble("width", 1080.0).toFloat(), j.optDouble("height", 1080.0).toFloat(),+ j.optDouble("dpi", 300.0).toFloat(), j.optInt("background", 0xFFFFFF), j.optBoolean("hidden", false),+ TimeLapseSettings(j.optInt("resolution", 0), j.optInt("quality", 1), j.optBoolean("hevc", false)),+ j.optString("profile", SRGB),+ )+ }+}++/** The presets a new gallery starts with, under the screen's size. */+val StandardPresets = listOf(+ CanvasPreset("Square", "px", 2048f, 2048f, 132f),+ CanvasPreset("4K", "px", 4096f, 1714f, 132f),+ CanvasPreset("A4", "mm", 210f, 297f, 300f),+ CanvasPreset("4 × 6 Photo", "in", 6f, 4f, 300f),+ CanvasPreset("Paper", "in", 11f, 8.5f, 300f),+ // printed: CMYK+ CanvasPreset("Comic", "in", 6f, 9.5f, 400f, profile = io.github.artcraftandroid.procraft.core.cmykProfiles().first()),+)diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/ColourSwatches.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/ColourSwatches.ktnew file mode 100644index 0000000..2cd7d95--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/ColourSwatches.kt@@ -0,0 +1,145 @@+package io.github.artcraftandroid.procraft.gallery++import java.nio.ByteBuffer+import kotlin.math.cbrt+import kotlin.math.pow+import kotlin.math.roundToInt++/**+ * Palettes from other painting and design programs' swatch files: colour swatch (`.aco`) and+ * swatch exchange (`.ase`) files. Their colours (RGB, HSB, CMYK, Lab or grey) come in as sRGB,+ * the first [PALETTE_SLOTS] of them.+ */+object ColourSwatches {+ /** Whether [head] (a file's first bytes) starts a swatch exchange file. */+ fun isExchange(head: ByteArray) = head.size >= 4 && String(head, 0, 4, Charsets.US_ASCII) == "ASEF"++ /**+ * The palette in [bytes], a swatch exchange file or (when [fileName] ends in `.aco`) a colour+ * swatch file, named by its first group or else the file; null if it is neither.+ */+ fun read(bytes: ByteArray, fileName: String?): Palette? {+ val base = fileName?.substringAfterLast('/')?.substringBeforeLast('.')?.trim().orEmpty()+ return runCatching {+ when {+ isExchange(bytes) -> exchange(bytes, base)+ fileName?.endsWith(".aco", ignoreCase = true) == true -> colourSwatch(bytes, base)+ else -> null+ }+ }.getOrNull()+ }++ /** A colour swatch file: a list of colours, then (in version 2) the same again with names. */+ private fun colourSwatch(bytes: ByteArray, name: String): Palette? {+ val b = ByteBuffer.wrap(bytes)+ val version = b.short.toInt()+ if (version !in 1..2) return null+ val count = b.short.toInt() and 0xFFFF+ val colours = (0 until count).mapNotNull {+ val space = b.short.toInt() and 0xFFFF+ val v = IntArray(4) { b.short.toInt() and 0xFFFF }+ // version 2 names each colour: its length in UTF-16 units, then the units+ if (version == 2) b.position(b.position() + 2 * b.int)+ acoColour(space, v)+ }+ if (colours.isEmpty()) return null+ return Palette(name.ifEmpty { "Imported Palette" }, List(PALETTE_SLOTS) { colours.getOrNull(it) })+ }++ /** A colour swatch file's colour in colour space [space] from its four numbers. */+ private fun acoColour(space: Int, v: IntArray): Int? = when (space) {+ 0 -> rgb(v[0] / 65535.0, v[1] / 65535.0, v[2] / 65535.0)+ 1 -> hsb(v[0] / 65535.0, v[1] / 65535.0, v[2] / 65535.0)+ // 0 is full ink+ 2 -> cmyk(1 - v[0] / 65535.0, 1 - v[1] / 65535.0, 1 - v[2] / 65535.0, 1 - v[3] / 65535.0)+ 7 -> lab(v[0] / 100.0, v[1].toShort() / 100.0, v[2].toShort() / 100.0)+ // 0 is white+ 8 -> (1 - v[0] / 10000.0).let { rgb(it, it, it) }+ 9 -> cmyk(v[0] / 10000.0, v[1] / 10000.0, v[2] / 10000.0, v[3] / 10000.0)+ else -> null+ }++ /** A swatch exchange file: blocks of groups and colours, each colour named and in a model. */+ private fun exchange(bytes: ByteArray, fallback: String): Palette? {+ val b = ByteBuffer.wrap(bytes)+ b.position(8)+ val blocks = b.int+ val colours = mutableListOf<Int>()+ var group: String? = null+ repeat(blocks) {+ val type = b.short.toInt() and 0xFFFF+ val length = b.int+ val end = b.position() + length+ when (type) {+ // a group starts: the palette takes the first one's name+ 0xC001 -> if (length >= 2) utf16(b).let { if (group == null && it.isNotBlank()) group = it }+ 0x0001 -> {+ utf16(b)+ val model = String(ByteArray(4).also { b.get(it) }, Charsets.US_ASCII)+ val c = when (model) {+ "RGB " -> rgb(b.float.toDouble(), b.float.toDouble(), b.float.toDouble())+ "CMYK" -> cmyk(b.float.toDouble(), b.float.toDouble(), b.float.toDouble(), b.float.toDouble())+ "LAB " -> lab(b.float * 100.0, b.float.toDouble(), b.float.toDouble())+ "Gray" -> b.float.toDouble().let { rgb(it, it, it) }+ else -> null+ }+ c?.let(colours::add)+ }+ }+ b.position(end)+ }+ if (colours.isEmpty()) return null+ val name = group?.trim()?.ifEmpty { null } ?: fallback.ifEmpty { "Imported Palette" }+ return Palette(name, List(PALETTE_SLOTS) { colours.getOrNull(it) })+ }++ /** A name: its length in UTF-16 units (with the closing zero), then the units. */+ private fun utf16(b: ByteBuffer): String {+ val units = b.short.toInt() and 0xFFFF+ val chars = CharArray(units) { b.char }+ return String(chars).trimEnd('\u0000')+ }++ private fun rgb(r: Double, g: Double, b: Double): Int {+ fun byte(v: Double) = (v.coerceIn(0.0, 1.0) * 255).roundToInt()+ return (byte(r) shl 16) or (byte(g) shl 8) or byte(b)+ }++ private fun hsb(h: Double, s: Double, v: Double): Int {+ val k = { n: Double -> (n + h * 6) % 6 }+ val f = { n: Double -> v - v * s * minOf(k(n), 4 - k(n), 1.0).coerceAtLeast(0.0) }+ return rgb(f(5.0), f(3.0), f(1.0))+ }++ /** Ink amounts (0..1) to RGB, simply: no press profile. */+ private fun cmyk(c: Double, m: Double, y: Double, k: Double) = rgb((1 - c) * (1 - k), (1 - m) * (1 - k), (1 - y) * (1 - k))++ /** CIE Lab (D50, as print programs keep it) to sRGB. */+ private fun lab(l: Double, a: Double, bb: Double): Int {+ val fy = (l + 16) / 116+ val fx = fy + a / 500+ val fz = fy - bb / 200+ fun inv(t: Double) = if (t > 6.0 / 29) t * t * t else 3 * (6.0 / 29).pow(2) * (t - 4.0 / 29)+ val (x, y, z) = Triple(0.96422 * inv(fx), inv(fy), 0.82521 * inv(fz))+ // D50 XYZ to linear sRGB (Bradford-adapted to D65)+ val r = 3.1338561 * x - 1.6168667 * y - 0.4906146 * z+ val g = -0.9787684 * x + 1.9161415 * y + 0.0334540 * z+ val b = 0.0719453 * x - 0.2289914 * y + 1.4052427 * z+ fun encode(c: Double) = if (c <= 0.0031308) 12.92 * c else 1.055 * c.coerceAtLeast(0.0).pow(1 / 2.4) - 0.055+ return rgb(encode(r), encode(g), encode(b))+ }++ /** For tests: sRGB [rgb] as D50 Lab, the inverse of [lab]. */+ internal fun labOf(rgb: Int): DoubleArray {+ fun decode(c: Double) = if (c <= 0.04045) c / 12.92 else ((c + 0.055) / 1.055).pow(2.4)+ val (r, g, b) = listOf(16, 8, 0).map { decode(((rgb shr it) and 0xFF) / 255.0) }+ val x = 0.4360747 * r + 0.3850649 * g + 0.1430804 * b+ val y = 0.2225045 * r + 0.7168786 * g + 0.0606169 * b+ val z = 0.0139322 * r + 0.0971045 * g + 0.7141733 * b+ fun f(t: Double) = if (t > (6.0 / 29).pow(3)) cbrt(t) else t / (3 * (6.0 / 29).pow(2)) + 4.0 / 29+ val (fx, fy, fz) = Triple(f(x / 0.96422), f(y), f(z / 0.82521))+ return doubleArrayOf(116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz))+ }++ internal fun labToRgb(l: Double, a: Double, b: Double) = lab(l, a, b)+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/DragOut.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/DragOut.ktnew file mode 100644index 0000000..661f66f--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/DragOut.kt@@ -0,0 +1,162 @@+package io.github.artcraftandroid.procraft.gallery++import android.content.ClipData+import android.content.ClipDescription+import android.content.ContentProvider+import android.content.ContentValues+import android.content.Context+import android.database.Cursor+import android.database.MatrixCursor+import android.graphics.Bitmap+import android.graphics.BitmapFactory+import android.graphics.Point+import android.net.Uri+import android.os.ParcelFileDescriptor+import android.provider.OpenableColumns+import android.view.View+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import io.github.artcraftandroid.procraft.core.CanvasSession+import java.io.File++/**+ * Artworks dragged out of the gallery into other apps. Each is offered in the formats the+ * settings prefer, as a file made only when the other app opens it.+ *+ * Its addresses are `content://<package>.drag/<format>/<the artwork's folder under the gallery>/<file name>`.+ */+class DragProvider : ContentProvider() {+ override fun onCreate() = true++ override fun getType(uri: Uri): String? = uri.pathSegments.firstOrNull()?.let(::mime)++ override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor {+ val name = uri.lastPathSegment?.let { File(it).name } ?: ""+ val made = context?.let { made(it, uri) }?.takeIf { it.exists() }+ return MatrixCursor(arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE)).apply { addRow(arrayOf<Any?>(name, made?.length())) }+ }++ override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? {+ val ctx = context ?: return null+ val segments = uri.pathSegments+ if (segments.size != 3 || mode != "r") return null+ val root = File(ctx.filesDir, "artworks").canonicalFile+ val dir = File(root, segments[1]).canonicalFile+ if (!dir.path.startsWith(root.path + File.separator) || !File(dir, "artwork.json").exists()) return null+ val out = made(ctx, uri) ?: return null+ // made again only if the artwork changed since+ if (out.lastModified() < File(dir, "artwork.json").lastModified() || !out.exists()) {+ if (!exportArtwork(dir, segments[0], out)) return null+ }+ return ParcelFileDescriptor.open(out, ParcelFileDescriptor.MODE_READ_ONLY)+ }++ override fun insert(uri: Uri, values: ContentValues?): Uri? = null++ override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?) = 0++ override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?) = 0++ companion object {+ private val Extensions = mapOf("ProCraft" to ArtworkFile.EXTENSION, "PSD" to "psd", "JPEG" to "jpg", "PNG" to "png", "TIFF" to "tif")++ fun mime(format: String): String = when (format) {+ "PSD" -> "image/vnd.adobe.photoshop"+ "JPEG" -> "image/jpeg"+ "PNG" -> "image/png"+ "TIFF" -> "image/tiff"+ else -> "application/octet-stream"+ }++ /** Where the file for [uri] is made: one folder per format and artwork. */+ private fun made(ctx: Context, uri: Uri): File? {+ val segments = uri.pathSegments+ if (segments.size != 3) return null+ val folder = (segments[0] + "-" + segments[1]).map { if (it.isLetterOrDigit()) it else '_' }.joinToString("")+ return File(File(ctx.cacheDir, "drags/$folder").apply { mkdirs() }, File(segments[2]).name)+ }++ /** The address of artwork [a] (in the gallery at [root]) as [format]. */+ fun uri(ctx: Context, format: String, a: Artwork, root: File): Uri {+ val base = a.name.filter { it.isLetterOrDigit() || it in " _-" }.trim().ifEmpty { "Untitled Artwork" }+ return Uri.Builder().scheme("content").authority(ctx.packageName + ".drag")+ .appendPath(format).appendPath(a.dir.relativeTo(root).path).appendPath("$base.${Extensions[format] ?: "bin"}").build()+ }+ }+}++/**+ * Writes the artwork saved in [dir] to [out] as [format] (one of [CanvasViewModel.DRAG_FORMATS], or+ * of the gallery's still [CanvasViewModel.SHARE_FORMATS]).+ */+fun exportArtwork(dir: File, format: String, out: File, pdfQuality: Int = 100): Boolean = runCatching {+ if (format == "ProCraft") {+ ArtworkFile.write(dir, out)+ return@runCatching true+ }+ CanvasSession.open(dir.path).use { s ->+ if (!s.prepareOffscreen()) return@runCatching false+ when (format) {+ CanvasViewModel.PACKAGE_LABEL -> s.exportPackage(out.path, System.nanoTime().toULong())+ "PDF" -> s.exportPdf(out.path, false, pdfQuality.toUByte())+ "PSD" -> s.exportPsd(out.path)+ "TIFF" -> s.exportTiff(out.path)+ "PNG" -> s.exportPng(out.path)+ "JPEG" -> {+ val png = File(out.path + ".png")+ s.exportPng(png.path)+ val ok = pngToJpeg(png, out)+ png.delete()+ return@runCatching ok+ }+ else -> return@runCatching false+ }+ }+ true+}.getOrDefault(false)++/** The picture in [png] flattened onto white as a JPEG in [jpg], keeping its colour space. */+fun pngToJpeg(png: File, jpg: File): Boolean {+ val picture = BitmapFactory.decodeFile(png.path) ?: return false+ val space = picture.colorSpace ?: android.graphics.ColorSpace.get(android.graphics.ColorSpace.Named.SRGB)+ val flat = Bitmap.createBitmap(picture.width, picture.height, Bitmap.Config.ARGB_8888, true, space)+ android.graphics.Canvas(flat).apply {+ drawColor(android.graphics.Color.WHITE)+ drawBitmap(picture, 0f, 0f, null)+ }+ jpg.outputStream().use { flat.compress(Bitmap.CompressFormat.JPEG, 92, it) }+ return true+}++/**+ * Starts dragging artwork [a] (in the gallery at [root]) from [view] out to other apps: the+ * preferred file format, and the preferred picture format too when that file isn't a picture.+ */+fun startArtworkDrag(view: View, a: Artwork, root: File): Boolean {+ val ctx = view.context+ val prefs = ctx.getSharedPreferences("interface", Context.MODE_PRIVATE)+ val file = CanvasViewModel.DRAG_FORMATS.getOrElse(prefs.getInt(CanvasViewModel.DRAG_FORMAT, 0)) { "ProCraft" }+ val image = CanvasViewModel.DRAG_IMAGE_FORMATS.getOrElse(prefs.getInt(CanvasViewModel.DRAG_IMAGE_FORMAT, 0)) { "JPEG" }+ val formats = if (file in CanvasViewModel.DRAG_IMAGE_FORMATS) listOf(file) else listOf(file, image)+ val clip = ClipData(ClipDescription(a.name, formats.map(DragProvider::mime).toTypedArray()), ClipData.Item(DragProvider.uri(ctx, formats[0], a, root)))+ formats.drop(1).forEach { clip.addItem(ClipData.Item(DragProvider.uri(ctx, it, a, root))) }+ val thumb = BitmapFactory.decodeFile(a.thumbnail.path)+ val shadow = object : View.DragShadowBuilder(view) {+ // the thumbnail, 160 dp on its long side, held at its middle+ private val side = 160f * ctx.resources.displayMetrics.density+ private val scale = thumb?.let { side / maxOf(it.width, it.height) } ?: 1f++ override fun onProvideShadowMetrics(size: Point, touch: Point) {+ val w = ((thumb?.width ?: 1) * scale).toInt().coerceAtLeast(1)+ val h = ((thumb?.height ?: 1) * scale).toInt().coerceAtLeast(1)+ size.set(w, h)+ touch.set(w / 2, h / 2)+ }++ override fun onDrawShadow(canvas: android.graphics.Canvas) {+ val t = thumb ?: return+ canvas.scale(scale, scale)+ canvas.drawBitmap(t, 0f, 0f, null)+ }+ }+ return view.startDragAndDrop(clip, shadow, null, View.DRAG_FLAG_GLOBAL or View.DRAG_FLAG_GLOBAL_URI_READ)+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/GradientStore.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/GradientStore.ktnew file mode 100644index 0000000..df8924f--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/GradientStore.kt@@ -0,0 +1,45 @@+package io.github.artcraftandroid.procraft.gallery++import io.github.artcraftandroid.procraft.ui.GRADIENTS+import io.github.artcraftandroid.procraft.ui.GradientPreset+import org.json.JSONArray+import org.json.JSONObject+import java.io.File++/**+ * The gradient library (Gradient Map's gradients), kept as JSON in [file]: each gradient's name and+ * stops (position, 0xAARRGGBB). With nothing saved yet it holds ours.+ */+class GradientStore(private val file: File) {++ fun load(): List<GradientPreset> {+ val read = runCatching {+ val list = JSONObject(file.readText()).getJSONArray("gradients")+ (0 until list.length()).map { i ->+ val g = list.getJSONObject(i)+ val stops = g.getJSONArray("stops")+ GradientPreset(+ g.getString("name"),+ (0 until stops.length()).map { j ->+ val s = stops.getJSONArray(j)+ s.getDouble(0).toFloat().coerceIn(0f, 1f) to (s.getLong(1) or 0xFF000000)+ },+ )+ }.filter { it.stops.size >= 2 }+ }.getOrNull()+ return if (read.isNullOrEmpty()) GRADIENTS else read+ }++ fun save(gradients: List<GradientPreset>) {+ val root = JSONObject().put(+ "gradients",+ JSONArray(gradients.map { g -> JSONObject().put("name", g.name).put("stops", JSONArray(g.stops.map { (p, c) -> JSONArray().put(p.toDouble()).put(c) })) }),+ )+ val tmp = File(file.parentFile, file.name + ".tmp")+ tmp.writeText(root.toString())+ if (!tmp.renameTo(file)) {+ file.delete()+ tmp.renameTo(file)+ }+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/PaletteStore.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/PaletteStore.ktnew file mode 100644index 0000000..82733d5--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/PaletteStore.kt@@ -0,0 +1,70 @@+package io.github.artcraftandroid.procraft.gallery++import org.json.JSONArray+import org.json.JSONObject+import java.io.File++/** Thirty swatches a palette holds: ten across, three down. */+const val PALETTE_SLOTS = 30++/** A named set of swatches (0xRRGGBB, or null for an empty slot). */+data class Palette(val name: String, val colors: List<Int?>) {+ init {+ require(colors.size == PALETTE_SLOTS)+ }+}++/** The palettes and which one is the default, kept in a JSON file. */+class PaletteStore(private val file: File) {++ fun load(): Pair<List<Palette>, Int> {+ val read = runCatching {+ val root = JSONObject(file.readText())+ val list = root.getJSONArray("palettes")+ val palettes = (0 until list.length()).map { i ->+ val p = list.getJSONObject(i)+ val colors = p.getJSONArray("colors")+ Palette(p.getString("name"), List(PALETTE_SLOTS) { j -> if (j < colors.length() && !colors.isNull(j)) colors.getInt(j) and 0xFFFFFF else null })+ }+ palettes to root.optInt("default", 0)+ }.getOrNull()+ return if (read == null || read.first.isEmpty()) starters() to 0 else read.first to read.second.coerceIn(0, read.first.size - 1)+ }++ fun save(palettes: List<Palette>, default: Int) {+ val root = JSONObject()+ root.put("default", default)+ root.put(+ "palettes",+ JSONArray(palettes.map { p -> JSONObject().put("name", p.name).put("colors", JSONArray(p.colors.map { it ?: JSONObject.NULL })) }),+ )+ val tmp = File(file.parentFile, file.name + ".tmp")+ tmp.writeText(root.toString())+ if (!tmp.renameTo(file)) {+ file.delete()+ tmp.renameTo(file)+ }+ }++ companion object {+ /** The palettes a new install starts with. */+ fun starters(): List<Palette> = listOf(+ Palette(+ "Basics",+ listOf(+ 0xFFFFFF, 0xE3E3E3, 0xC6C6C6, 0xA9A9A9, 0x8C8C8C, 0x707070, 0x545454, 0x393939, 0x1F1F1F, 0x000000,+ 0xD7263D, 0xF46036, 0xF5B700, 0x7CB518, 0x1B998B, 0x2E86AB, 0x2E4A9E, 0x6A3FA0, 0xC2377D, 0x7A4B2A,+ 0xF2A7B1, 0xF9B99A, 0xFBE38E, 0xC5E39A, 0x9AD9CF, 0xA4CCE3, 0xA3B1DD, 0xC5ADE0, 0xE7A9C8, 0xC9A88C,+ ),+ ),+ Palette(+ "Earth",+ listOf(+ 0xF6E7CF, 0xE9CFA5, 0xD8B07A, 0xC28F55, 0xA8703B, 0x8A552B, 0x6C3F20, 0x4F2D17, 0x34200F, 0x1E1309,+ 0x9FB28A, 0x7E9A6A, 0x60804F, 0x46663A, 0x324E2A, 0xB9C4C9, 0x8FA3AD, 0x66808E, 0x46606F, 0x2D4250,+ 0xE8C1A0, 0xD9A37F, 0xC4845F, 0xA86846, 0x8A5135, 0x6B3E2A, null, null, null, null,+ ),+ ),+ )+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/Swatches.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/Swatches.ktnew file mode 100644index 0000000..0facfe0--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/gallery/Swatches.kt@@ -0,0 +1,74 @@+package io.github.artcraftandroid.procraft.gallery++import android.graphics.Color+import org.json.JSONArray+import org.json.JSONObject+import java.io.File+import java.io.InputStream+import java.util.zip.ZipEntry+import java.util.zip.ZipInputStream+import java.util.zip.ZipOutputStream++/**+ * Palettes as swatches files: a zip holding `Swatches.json`, the palette's name and its swatches+ * as hue, saturation and brightness (0..1), alpha and a colour space number; empty slots null.+ */+object Swatches {+ const val EXTENSION = "swatches"+ private const val ENTRY = "Swatches.json"++ /**+ * Writes palette [p] to [out]: all thirty slots, empty ones null, each colour in sRGB with the+ * profile it is in kept once beside them (named by its SHA-256 in base64).+ */+ fun write(p: Palette, out: File) {+ val icc = io.github.artcraftandroid.procraft.core.srgbProfile()+ val hash = java.util.Base64.getEncoder().encodeToString(java.security.MessageDigest.getInstance("SHA-256").digest(icc))+ val swatches = JSONArray()+ for (rgb in p.colors) {+ if (rgb == null) {+ swatches.put(JSONObject.NULL)+ continue+ }+ val hsv = FloatArray(3)+ Color.RGBToHSV((rgb shr 16) and 0xFF, (rgb shr 8) and 0xFF, rgb and 0xFF, hsv)+ val (h, sat, b) = Triple(hsv[0] / 360.0, hsv[1].toDouble(), hsv[2].toDouble())+ swatches.put(+ JSONObject().put("alpha", 1).put("origin", 1).put("colorSpace", 0).put("colorModel", 0).put("brightness", b)+ .put("components", JSONArray().put(h).put(sat).put(b)).put("version", "5.0").put("colorProfile", hash)+ .put("saturation", sat).put("hue", h),+ )+ }+ val profile = JSONObject().put("colorSpace", 0).put("hash", hash)+ .put("iccData", java.util.Base64.getEncoder().encodeToString(icc)).put("iccName", "sRGB IEC61966-2.1")+ val json = JSONObject().put("name", p.name).put("swatches", swatches).put("colorProfiles", JSONArray().put(profile)).toString()+ ZipOutputStream(out.outputStream()).use { zip ->+ zip.putNextEntry(ZipEntry(ENTRY))+ zip.write(json.toByteArray())+ zip.closeEntry()+ }+ }++ /** The palette in a swatches file, or null if [input] isn't one. */+ fun read(input: InputStream): Palette? = runCatching {+ ZipInputStream(input).use { zip ->+ generateSequence { zip.nextEntry }.firstOrNull { it.name.substringAfterLast('/') == ENTRY }+ ?.let { parse(zip.readBytes().decodeToString()) }+ }+ }.getOrNull()++ /** A palette from its JSON; tolerant of trailing commas. */+ private fun parse(text: String): Palette? {+ val clean = text.replace(Regex(",\\s*([}\\]])"), "$1")+ val root = clean.trim().let { if (it.startsWith("[")) JSONArray(it).optJSONObject(0) else JSONObject(it) } ?: return null+ val list = root.optJSONArray("swatches") ?: return null+ val colors = List(PALETTE_SLOTS) { i ->+ val s = if (i < list.length()) list.optJSONObject(i) else null+ s?.let {+ val hsv = floatArrayOf(it.optDouble("hue", 0.0).toFloat() * 360f, it.optDouble("saturation", 0.0).toFloat(), it.optDouble("brightness", 0.0).toFloat())+ Color.HSVToColor(hsv) and 0xFFFFFF+ }+ }+ return Palette(root.optString("name").trim().ifEmpty { "Untitled Palette" }, colors)+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ActionsPanel.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ActionsPanel.ktnew file mode 100644index 0000000..333b4ce--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ActionsPanel.kt@@ -0,0 +1,593 @@+package io.github.artcraftandroid.procraft.ui++import android.content.Context+import android.content.Intent+import androidx.activity.compose.BackHandler+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.detectHorizontalDragGestures+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.material3.AlertDialog+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.foundation.border+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.drawBehind+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.core.content.FileProvider+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import kotlinx.coroutines.launch+import kotlin.math.roundToInt+import java.io.File++private val ActionsWidth = 390.dp++/** One row of the actions panel. Rows whose features are still to come show dimmed. */+private sealed interface ActionRow++private class Act(val label: String, val value: String? = null, val onClick: (() -> Unit)? = null) : ActionRow++/** A switch row; [fixed] is a setting shown as it is, its name not dimmed. */+private class Toggle(val label: String, val checked: Boolean, val fixed: Boolean = false, val onChange: ((Boolean) -> Unit)? = null) : ActionRow++private class Heading(val label: String) : ActionRow++/** A setting with its value on the right and a slider under its name, always shown. */+private class Slide(val label: String, val value: String, val fraction: Float, val tall: Dp = 63.dp, val onChange: (Float) -> Unit) : ActionRow++/** The pages the panel shows: its tabs, or a page of settings reached from one of them. */+private enum class ActionsPage { TABS, PRESSURE, CURSOR }++private val CurveFill = Color(0xFF262626)+private val CurveEdge = Color(0xFF666666)+private val CurveGrid = Color(0xFF353535)++/** A fraction shown as the panel's sliders show it: "None" at nothing, else a percentage. */+private fun percent(v: Float) = if (v <= 0f) "None" else "%.1f%%".format(v * 100f)++private class Tab(val label: String, val icon: ImageVector)++private val Tabs = listOf(+ Tab("Add", PcIcons.TabAdd),+ Tab("Canvas", PcIcons.TabCanvas),+ Tab("Share", PcIcons.TabShare),+ Tab("Video", PcIcons.TabVideo),+ Tab("Prefs", PcIcons.TabPrefs),+ Tab("Help", PcIcons.TabHelp),+)++/** The actions panel: six tabs of grouped rows (adding, the canvas, sharing, video, preferences, help). */+@Composable+fun ActionsPanel(vm: CanvasViewModel, arrowX: Dp, modifier: Modifier = Modifier) {+ val context = LocalContext.current+ val scope = rememberCoroutineScope()+ var dialog by remember { mutableStateOf<Pair<String, String>?>(null) }+ var exportingVideo by remember { mutableStateOf(false) }+ fun shareVideo(seconds: Int?) {+ exportingVideo = false+ scope.launch {+ val file = vm.exportTimeLapse(seconds)+ if (file != null) shareFile(context, file, "video/mp4") else dialog = "Time-lapse" to "There is no time-lapse to export yet."+ }+ }+ var page by remember { mutableStateOf(ActionsPage.TABS) }+ // the tab whose rows are shown: changing tabs, the old rows fade out, then the new ones fade in+ var shownTab by remember { mutableStateOf(vm.actionsTab) }+ val rowsShown = remember { androidx.compose.animation.core.Animatable(1f) }+ LaunchedEffect(vm.actionsTab) {+ if (shownTab == vm.actionsTab) return@LaunchedEffect+ rowsShown.animateTo(0f, Motion.actionsTabOut())+ shownTab = vm.actionsTab+ rowsShown.animateTo(1f, Motion.actionsTabIn())+ }+ // Brush scaling's menu is open+ var scalingMenu by remember { mutableStateOf(false) }+ // a PDF waiting on its quality+ var pdfAsking by remember { mutableStateOf<CanvasViewModel.Export?>(null) }+ fun share(kind: CanvasViewModel.Export, pdfQuality: Int = 100) {+ scope.launch {+ val files = vm.export(kind, pdfQuality)+ if (files.isNotEmpty()) shareFiles(context, files, kind.mime) else dialog = "Share" to "The artwork could not be exported."+ }+ }+ fun share(jpeg: Boolean) {+ scope.launch {+ val file = vm.exportImage(jpeg)+ if (file != null) shareFile(context, file, if (jpeg) "image/jpeg" else "image/png") else dialog = "Share" to "The picture could not be exported."+ }+ }+ val pickPhoto = androidx.activity.compose.rememberLauncherForActivityResult(androidx.activity.result.contract.ActivityResultContracts.PickVisualMedia()) { uri ->+ uri?.let { vm.insertPicture(it) }+ }+ val pickFile = androidx.activity.compose.rememberLauncherForActivityResult(androidx.activity.result.contract.ActivityResultContracts.OpenDocument()) { uri ->+ uri?.let { vm.insertPicture(it) }+ }+ // the camera writes its picture to a file of ours, which goes in like a photo+ val photo = remember {+ val dir = File(context.cacheDir, "exports").apply { mkdirs() }+ FileProvider.getUriForFile(context, context.packageName + ".files", File(dir, "camera.jpg"))+ }+ val takePhoto = androidx.activity.compose.rememberLauncherForActivityResult(androidx.activity.result.contract.ActivityResultContracts.TakePicture()) { taken ->+ if (taken) vm.insertPicture(photo)+ }+ val groups: List<List<ActionRow>> = when (shownTab) {+ 0 -> listOf(+ listOf(+ Act("Insert a file") { pickFile.launch(arrayOf("image/*")) },+ Act("Insert a photo") {+ pickPhoto.launch(androidx.activity.result.PickVisualMediaRequest(androidx.activity.result.contract.ActivityResultContracts.PickVisualMedia.ImageOnly))+ },+ Act("Take a photo") { runCatching { takePhoto.launch(photo) }.onFailure { dialog = "Take a photo" to "No camera app is available." } },+ Act("Add text") { vm.addText() },+ ),+ // Paste is grey until something has been cut or copied+ listOf(Act("Cut") { vm.cutLayer() }, Act("Copy") { vm.copyLayer() }, Act("Copy canvas") { vm.copyCanvas() }, Act("Paste", onClick = if (vm.canPaste) ({ vm.paste() }) else null)),+ )+ 1 -> listOf(+ listOf(Act("Crop & Resize") { vm.beginCrop() }),+ listOf(+ Toggle("Animation Assist", vm.animation?.pages == false) { vm.changeAnimationAssist(it) },+ Toggle("Page Assist", vm.animation?.pages == true) { vm.changePageAssist(it) },+ Toggle("Drawing Guide", vm.guide?.on == true) { vm.setGuideOn(it) },+ // only with the guide on+ Act("Edit Drawing Guide", onClick = if (vm.guide?.on == true) ({ vm.openGuideEditor() }) else null),+ ),+ listOf(Toggle("Reference", vm.referenceOn) { vm.changeReferenceOn(it) }),+ listOf(Act("Flip horizontal") { vm.flipCanvas(horizontal = true) }, Act("Flip vertical") { vm.flipCanvas(horizontal = false) }),+ listOf(Act("Canvas information") { vm.canvasInfoOpen = true }),+ )+ 2 -> listOf(+ listOf(+ Heading("Share Image"),+ Act(CanvasViewModel.PACKAGE_LABEL) {+ scope.launch {+ val file = vm.exportPackageFile()+ if (file != null) shareFile(context, file, "application/octet-stream") else dialog = "Share" to "The artwork could not be exported."+ }+ },+ Act("PSD") { share(CanvasViewModel.Export.PSD) },+ Act("PDF") { pdfAsking = CanvasViewModel.Export.PDF },+ Act("JPEG") { share(jpeg = true) },+ Act("PNG") { share(jpeg = false) },+ Act("TIFF") { share(CanvasViewModel.Export.TIFF) },+ ),+ listOf(+ Heading("Share Layers"),+ Act("PDF") { pdfAsking = CanvasViewModel.Export.LAYERS_PDF },+ Act("PNG Files") { share(CanvasViewModel.Export.LAYER_PNGS) },+ Act("Animated GIF") { vm.animatedExport = CanvasViewModel.Animated.GIF },+ Act("Animated PNG") { vm.animatedExport = CanvasViewModel.Animated.PNG },+ Act("Animated MP4") { vm.animatedExport = CanvasViewModel.Animated.MP4 },+ Act("Animated HEVC") { vm.animatedExport = CanvasViewModel.Animated.HEVC },+ ),+ )+ 3 -> listOf(+ listOf(+ Act("Time-lapse Replay") {+ // the panel fades away as the replay takes the screen+ vm.fadePanels()+ vm.timeLapseReplaying = true+ },+ Toggle("Time-lapse Recording", vm.timeLapseRecording) { vm.changeTimeLapseRecording(it) },+ ),+ listOf(Act("Export time-lapse video") { exportingVideo = true }),+ )+ 4 -> listOf(+ listOf(+ Toggle("Light interface", vm.lightInterface) { vm.changeLightInterface(it) },+ Toggle("Right-hand interface", vm.rightHanded) { vm.changeRightHanded(it) },+ Act("Brush scaling", value = if (vm.brushOnScreen) "Screen" else "Canvas") { scalingMenu = true },+ Toggle("Project canvas", vm.projectCanvas) { vm.changeProjectCanvas(it) },+ Toggle("Brush cursor", vm.brushCursorOn) { vm.changeBrushCursor(it) },+ Act("Advanced cursor settings") { page = ActionsPage.CURSOR },+ ),+ listOf(+ Act("Pressure and Smoothing") { page = ActionsPage.PRESSURE },+ Act("Gesture controls") { vm.gestureControlsOpen = true },+ ),+ listOf(+ Slide(+ "Rapid undo delay",+ "%.2fs".format(vm.rapidUndoDelay),+ (vm.rapidUndoDelay - CanvasViewModel.RAPID_UNDO_MIN_S) / (CanvasViewModel.RAPID_UNDO_MAX_S - CanvasViewModel.RAPID_UNDO_MIN_S),+ ) { vm.changeRapidUndoDelay(CanvasViewModel.RAPID_UNDO_MIN_S + it * (CanvasViewModel.RAPID_UNDO_MAX_S - CanvasViewModel.RAPID_UNDO_MIN_S)) },+ Slide("Selection mask visibility", "%.1f%%".format(vm.selectionVisibility * 100f), vm.selectionVisibility, onChange = vm::changeSelectionVisibility),+ ),+ listOf(Toggle("Size & Opacity sidebar", vm.showSideBar) { vm.showSideBar = it }),+ )+ else -> listOf(+ listOf(+ Act("About ProCraft") { dialog = "ProCraft" to "Version ${versionName(context)}" },+ Act("Licences") { dialog = "Licences" to licences(context) },+ ),+ listOf(+ Act("Advanced settings") {+ // the app's own settings page, apart from the canvas+ runCatching { context.startActivity(Intent(context, io.github.artcraftandroid.procraft.SettingsActivity::class.java)) }+ },+ ),+ )+ }+ Popover(ActionsWidth, arrowX, modifier) {+ androidx.compose.animation.AnimatedContent(+ page,+ transitionSpec = { Motion.panelPage(forward = targetState != ActionsPage.TABS) },+ label = "page",+ ) { shown ->+ Column {+ if (shown == ActionsPage.PRESSURE) {+ PressurePage(vm) { page = ActionsPage.TABS }+ return@Column+ }+ if (shown == ActionsPage.CURSOR) {+ CursorPage(vm) { page = ActionsPage.TABS }+ return@Column+ }+ Text(+ "Actions",+ color = Pc.PanelTitle,+ fontSize = 24.sp,+ fontWeight = FontWeight.Bold,+ modifier = Modifier.padding(start = 24.dp, top = 22.dp).height(34.dp),+ )+ Row(Modifier.padding(start = 10.dp).height(60.dp)) {+ Tabs.forEachIndexed { i, tab ->+ // a tab lights up as soon as it is touched; the old one goes out when it is let go+ val touch = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }+ val held = heldOf(touch)+ val lit = i == vm.actionsTab || held+ Box(Modifier.width(54.dp).fillMaxSize().clickable(touch, indication = null) { vm.actionsTab = i }) {+ Icon(+ tab.icon,+ contentDescription = null,+ tint = if (lit) Pc.Accent else Pc.TabIdle,+ // a 50 frame centred 24 down+ modifier = Modifier.align(Alignment.TopCenter).offset(y = (-1).dp).requiredSize(50.dp),+ )+ Text(+ tab.label,+ color = if (lit) Pc.Text else Pc.TabIdle,+ fontSize = 12.sp,+ fontWeight = FontWeight.Medium,+ modifier = Modifier.align(Alignment.TopCenter).padding(top = 41.dp),+ )+ }+ if (i < Tabs.size - 1) Spacer(Modifier.width(10.dp))+ }+ }+ Column(+ Modifier.heightIn(max = 760.dp).verticalScroll(rememberScrollState()).padding(start = 12.dp, end = 12.dp, top = 20.dp, bottom = 11.dp)+ .graphicsLayer { alpha = rowsShown.value },+ ) {+ groups.forEachIndexed { g, all ->+ if (g > 0) Spacer(Modifier.height(20.dp))+ // a group led by a heading shows it above the group, not as a row of it+ val heading = all.firstOrNull() as? Heading+ if (heading != null) {+ Box(Modifier.fillMaxWidth().height(45.dp)) {+ Text(heading.label, color = Pc.PanelTitle, fontSize = 14.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 13.dp, top = 7.dp))+ }+ }+ val rows = if (heading != null) all.drop(1) else all+ Box {+ Group(rows)+ // beside Brush scaling, the third row+ if (rows.any { it is Act && it.label == "Brush scaling" }) MenuPresence(scalingMenu, androidx.compose.ui.graphics.TransformOrigin(0f, 0f)) { look ->+ ChoiceMenu(+ look,+ listOf("Relative to canvas", "Relative to screen"), if (vm.brushOnScreen) 1 else 0, offsetY = 89.dp,+ onPick = {+ vm.changeBrushScaling(it == 1)+ scalingMenu = false+ },+ onDismiss = { scalingMenu = false },+ )+ }+ }+ }+ }+ }+ }+ }+ // the time-lapse in full or cut to 30 seconds (a tap outside: neither)+ Alert(+ if (exportingVideo) Unit else null,+ title = { "Video length" },+ message = { "" },+ action = "30 Seconds",+ onCancel = { exportingVideo = false },+ onAction = { shareVideo(30) },+ icon = PcIcons.Clock,+ destructive = false,+ cancel = "Full length",+ first = { shareVideo(null) },+ )+ PdfQualityAlert(pdfAsking != null, onCancel = { pdfAsking = null }) { quality ->+ pdfAsking?.let { share(it, quality.jpeg) }+ pdfAsking = null+ }+ dialog?.let { (title, text) ->+ AlertDialog(+ onDismissRequest = { dialog = null },+ title = { Text(title) },+ text = { Text(text, modifier = Modifier.heightIn(max = 420.dp).verticalScroll(rememberScrollState())) },+ confirmButton = { TextButton(onClick = { dialog = null }) { Text("Done") } },+ )+ }+}++/** A small menu beside a row: its choices, the chosen one marked with a blue dot. */+@Composable+private fun ChoiceMenu(look: Modifier, choices: List<String>, chosen: Int, offsetY: Dp, onPick: (Int) -> Unit, onDismiss: () -> Unit) {+ val density = androidx.compose.ui.platform.LocalDensity.current+ androidx.compose.ui.window.Popup(+ alignment = Alignment.TopEnd,+ offset = with(density) { androidx.compose.ui.unit.IntOffset(130.dp.roundToPx(), offsetY.roundToPx()) },+ onDismissRequest = onDismiss,+ properties = androidx.compose.ui.window.PopupProperties(focusable = true),+ ) {+ Column(look.width(250.dp).clip(RoundedCornerShape(16.dp)).background(Pc.MenuFill).padding(vertical = 6.dp)) {+ choices.forEachIndexed { i, label ->+ Row(Modifier.fillMaxWidth().height(40.dp).clickable { onPick(i) }.padding(horizontal = 18.dp), verticalAlignment = Alignment.CenterVertically) {+ Text(label, color = Pc.Text, fontSize = 15.sp, modifier = Modifier.weight(1f))+ if (i == chosen) Box(Modifier.size(8.dp).clip(CircleShape).background(Pc.Accent))+ }+ }+ }+ }+}++/**+ * Advanced cursor settings, a page of the panel: when the brush cursor shows, and how it is drawn.+ */+@Composable+private fun CursorPage(vm: CanvasViewModel, onBack: () -> Unit) {+ BackHandler(onBack = onBack)+ Row(Modifier.padding(start = 8.dp, top = 12.dp).height(44.dp), verticalAlignment = Alignment.CenterVertically) {+ Box(Modifier.size(44.dp, 34.dp).clickable(onClick = onBack), contentAlignment = Alignment.Center) {+ Icon(PcIcons.ChevronLeft, contentDescription = "Back", tint = Pc.PanelTitle, modifier = Modifier.size(22.dp))+ }+ Text("Advanced cursor", color = Pc.PanelTitle, fontSize = 22.sp, fontWeight = FontWeight.Bold, maxLines = 1)+ }+ Column(Modifier.padding(start = 12.dp, end = 12.dp, top = 8.dp, bottom = 13.dp)) {+ Text("Brush cursor visibility", color = Pc.TabIdle, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, modifier = Modifier.padding(start = 14.dp, top = 6.dp, bottom = 8.dp))+ ChoiceGroup(listOf("Show while hovering", "Show while painting", "Show both"), vm.cursorShows.ordinal) {+ vm.changeCursorShows(CanvasViewModel.CursorShows.entries[it])+ }+ Text("Brush outline style", color = Pc.TabIdle, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, modifier = Modifier.padding(start = 14.dp, top = 18.dp, bottom = 8.dp))+ ChoiceGroup(listOf("High contrast", "Active color", "Per brush"), vm.cursorStyle.ordinal) {+ vm.changeCursorStyle(CanvasViewModel.CursorStyle.entries[it])+ }+ }+}++/** Choices as rows of a rounded group, the chosen one a full blue row. */+@Composable+private fun ChoiceGroup(choices: List<String>, chosen: Int, onPick: (Int) -> Unit) {+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(18.dp)).background(Pc.ActionsGroup)) {+ choices.forEachIndexed { i, label ->+ if (i > 0 && i != chosen && i - 1 != chosen) Box(Modifier.fillMaxWidth().height(1.dp).background(Pc.ActionsSeparator))+ Box(+ Modifier.fillMaxWidth().height(42.dp).background(if (i == chosen) Pc.Accent else Color.Transparent).clickable { onPick(i) }.padding(start = 16.dp),+ contentAlignment = Alignment.CenterStart,+ ) {+ Text(label, color = if (i == chosen) Color.White else Pc.PanelTitle, fontSize = 17.sp, maxLines = 1)+ }+ }+ }+}++/** Rows in a rounded group, a line between them (not between sliders). */+@Composable+private fun Group(rows: List<ActionRow>) {+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(22.dp)).background(Pc.ActionsGroup)) {+ rows.forEachIndexed { i, row ->+ if (i > 0 && !(row is Slide && rows[i - 1] is Slide)) Box(Modifier.fillMaxWidth().height(1.dp).background(Pc.ActionsSeparator))+ if (row is Slide) SlideRow(row) else ActionRowView(row)+ }+ }+}++/**+ * Pressure and Smoothing, a page of the panel: the app's stabilization, motion filtering and its+ * expression, Tip Attachment, the pressure curve every stroke goes through, and Reset all.+ */+@Composable+private fun PressurePage(vm: CanvasViewModel, onBack: () -> Unit) {+ BackHandler(onBack = onBack)+ Row(Modifier.padding(start = 8.dp, top = 12.dp).height(44.dp), verticalAlignment = Alignment.CenterVertically) {+ Box(Modifier.size(44.dp, 34.dp).clickable(onClick = onBack), contentAlignment = Alignment.Center) {+ Icon(PcIcons.ChevronLeft, contentDescription = "Back", tint = Pc.PanelTitle, modifier = Modifier.size(22.dp))+ }+ Text("Pressure & Smoothing", color = Pc.PanelTitle, fontSize = 22.sp, fontWeight = FontWeight.Bold, maxLines = 1)+ }+ Column(Modifier.heightIn(max = 760.dp).verticalScroll(rememberScrollState()).padding(start = 12.dp, end = 12.dp, top = 20.dp, bottom = 13.dp)) {+ Group(+ listOf(+ Slide("Stabilization", percent(vm.inputStabilization), vm.inputStabilization, 64.dp) { vm.changeInput(stabilization = it) },+ Slide("Motion Filtering", percent(vm.inputMotionFiltering), vm.inputMotionFiltering, 64.dp) { vm.changeInput(motion = it) },+ Slide("Motion Filtering Expression", percent(vm.inputMotionExpression), vm.inputMotionExpression, 64.dp) { vm.changeInput(expression = it) },+ ),+ )+ Spacer(Modifier.height(16.dp))+ // the stroke always starts at the pen's tip here+ Group(listOf(Toggle("Tip Attachment", true, fixed = true)))+ Spacer(Modifier.height(24.dp))+ Text("App Pressure Sensitivity", color = Pc.SlideLabel, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, modifier = Modifier.padding(start = 13.dp).height(19.dp))+ Box(Modifier.padding(horizontal = 7.dp).fillMaxWidth().aspectRatio(1f).background(CurveFill)) {+ PressureCurve(vm.inputCurve, Modifier.fillMaxSize(), grid = CurveGrid, edge = CurveEdge) { vm.changeInput(curve = it) }+ }+ Spacer(Modifier.height(27.dp))+ Group(listOf(Act("Reset all") { vm.resetInput() }))+ }+}++/** A slider row: the name and value on top, the bar under them; drag or tap along it. */+@Composable+private fun SlideRow(row: Slide) {+ val change by rememberUpdatedState(row.onChange)+ Box(+ Modifier.fillMaxWidth().height(row.tall)+ .pointerInput(Unit) {+ val inset = 16.dp.toPx()+ fun at(x: Float) = ((x - inset) / (size.width - 2f * inset)).coerceIn(0f, 1f)+ detectTapGestures { change(at(it.x)) }+ }+ .pointerInput(Unit) {+ val inset = 16.dp.toPx()+ fun at(x: Float) = ((x - inset) / (size.width - 2f * inset)).coerceIn(0f, 1f)+ detectHorizontalDragGestures(onDragStart = { change(at(it.x)) }) { c, _ ->+ c.consume()+ change(at(c.position.x))+ }+ }+ .drawBehind {+ val inset = 16.dp.toPx()+ val y = size.height - 17.5.dp.toPx()+ val h = 3.dp.toPx()+ val x = inset + row.fraction.coerceIn(0f, 1f) * (size.width - 2f * inset)+ drawRect(Pc.SlideTrack, Offset(inset, y - h / 2f), Size(size.width - 2f * inset, h))+ drawRect(Pc.Accent, Offset(inset, y - h / 2f), Size(x - inset, h))+ val knob = Size(16.dp.toPx(), 10.dp.toPx())+ drawRoundRect(Color.White, Offset(x - knob.width / 2f, y - knob.height / 2f), knob, CornerRadius(knob.height / 2f))+ },+ ) {+ Text(row.label, color = Pc.SlideLabel, fontSize = 17.sp, maxLines = 1, modifier = Modifier.padding(start = 16.dp, top = 9.dp))+ Text(row.value, color = Pc.SlideValue, fontSize = 17.sp, maxLines = 1, modifier = Modifier.align(Alignment.TopEnd).padding(end = 19.dp, top = 9.dp))+ }+}++@Composable+private fun ActionRowView(row: ActionRow) {+ val enabled = when (row) {+ is Act -> row.onClick != null+ is Toggle -> row.onChange != null+ is Heading, is Slide -> true+ }+ // a button row turns blue while it is held, its text white+ val touch = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }+ val lit = animateHighlight(heldOf(touch))+ val ink = androidx.compose.ui.graphics.lerp(if (enabled || (row is Toggle && row.fixed)) Pc.ActionsRow else Pc.ActionsDisabled, Color.White, lit)+ Row(+ Modifier.fillMaxWidth().height(44.dp)+ .then(if (lit > 0f) Modifier.background(Pc.Accent.copy(alpha = lit)) else Modifier)+ .then(if (row is Act && row.onClick != null) Modifier.clickable(touch, indication = null, onClick = row.onClick) else Modifier)+ .then(if (row is Toggle && row.onChange != null) Modifier.clickable { row.onChange.invoke(!row.checked) } else Modifier)+ .padding(start = 16.dp, end = 8.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ when (row) {+ is Heading -> Text(row.label, color = Pc.PanelTitle, fontSize = 17.sp, fontWeight = FontWeight.SemiBold, modifier = Modifier.weight(1f))+ is Act -> {+ Text(row.label, color = ink, fontSize = 17.sp, maxLines = 1, modifier = Modifier.weight(1f))+ row.value?.let { Text(it, color = androidx.compose.ui.graphics.lerp(Pc.TabIdle, Color.White, lit), fontSize = 15.sp, modifier = Modifier.padding(end = 8.dp)) }+ }+ is Toggle -> {+ Text(row.label, color = ink, fontSize = 17.sp, maxLines = 1, modifier = Modifier.weight(1f))+ Switch(row.checked, enabled)+ }+ is Slide -> SlideRow(row)+ }+ }+}++/**+ * A 63 × 28 switch: a blue track when on, grey when off, with a white knob. Flipped, the knob swells+ * into a clear lens as it slides across, the track's colour fading under it, then settles white.+ */+@Composable+internal fun Switch(checked: Boolean, enabled: Boolean, fixedTrack: Color = Pc.SwitchFixed, fixedKnob: Color = Pc.SwitchFixedKnob) {+ val on = androidx.compose.animation.core.animateFloatAsState(if (checked) 1f else 0f, Motion.switchKnob(), label = "knob").value+ val lens = remember { androidx.compose.animation.core.Animatable(0f) }+ var flipped by remember { mutableStateOf(false) }+ LaunchedEffect(checked) {+ // not when it is first shown+ if (!flipped) {+ flipped = true+ return@LaunchedEffect+ }+ lens.animateTo(1f, Motion.switchSwell())+ kotlinx.coroutines.delay(Motion.SWITCH_HOLD_MS)+ lens.animateTo(0f, Motion.switchSettle())+ }+ val g = lens.value+ val track = if (!enabled) fixedTrack else androidx.compose.ui.graphics.lerp(Pc.SwitchOff, Pc.Accent, on)+ // not clipped to the track: the swollen knob spills over it+ Box(Modifier.size(63.dp, 28.dp)) {+ Box(Modifier.matchParentSize().clip(CircleShape).background(track))+ Box(+ Modifier.offset(x = 2.dp + 22.dp * on, y = 2.dp).size(37.dp, 24.dp)+ .graphicsLayer {+ scaleX = 1f + Motion.SWITCH_SWELL_X * g+ scaleY = 1f + Motion.SWITCH_SWELL_Y * g+ }+ .clip(CircleShape)+ .background((if (enabled) Color.White else fixedKnob).copy(alpha = 1f - 0.7f * g))+ .border(1.dp, Color.White.copy(alpha = 0.55f * g), CircleShape),+ )+ }+}+++private fun versionName(context: Context): String =+ runCatching { context.packageManager.getPackageInfo(context.packageName, 0).versionName }.getOrNull() ?: "?"++private fun licences(context: Context): String {+ val inter = runCatching { context.assets.open("fonts/Inter-OFL.txt").bufferedReader().use { it.readText() } }.getOrDefault("")+ return "The interface font is Inter, by The Inter Project Authors.\n\n$inter"+}++/** Offers [files] to other apps through the share sheet. */+internal fun shareFiles(context: Context, files: List<File>, mime: String) {+ if (files.size == 1) return shareFile(context, files[0], mime)+ val uris = ArrayList(files.map { FileProvider.getUriForFile(context, context.packageName + ".files", it) })+ val send = Intent(Intent.ACTION_SEND_MULTIPLE).setType(mime).putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)+ context.startActivity(Intent.createChooser(send, null))+}++/** Offers [file] to other apps through the share sheet. */+internal fun shareFile(context: Context, file: File, mime: String) {+ val uri = FileProvider.getUriForFile(context, context.packageName + ".files", file)+ val send = Intent(Intent.ACTION_SEND).setType(mime).putExtra(Intent.EXTRA_STREAM, uri).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)+ context.startActivity(Intent.createChooser(send, null))+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AdjustmentsUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AdjustmentsUi.ktnew file mode 100644index 0000000..1696d68--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AdjustmentsUi.kt@@ -0,0 +1,1034 @@+package io.github.artcraftandroid.procraft.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.horizontalScroll+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.setValue+import androidx.compose.foundation.gestures.detectDragGestures+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.drawBehind+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.StrokeCap+import androidx.compose.ui.graphics.lerp+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.positionInWindow+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.procraft.canvas.Adjustment+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import io.github.artcraftandroid.procraft.core.ChromaticKind+import io.github.artcraftandroid.procraft.core.GlitchKind+import io.github.artcraftandroid.procraft.core.HalftoneKind+import io.github.artcraftandroid.procraft.core.NoiseKind+import io.github.artcraftandroid.procraft.core.QuickShapeKind+import io.github.artcraftandroid.procraft.core.LiquifyKind+import kotlin.math.roundToInt++private val ModeBar = Color(0xFF5A5A5A)+private val ModeText = Color(0xFFC5C5C5)+private val HsbPanelFill = Color(0xF71E1E1E)+private val HsbLabel = Color(0xFF808080)+private val HsbValue = Color(0xFFEDEDED)++/** The adjustments menu hanging from its button, in groups: colour, blurs, effects, painting. */+@Composable+fun AdjustmentsPanel(vm: CanvasViewModel, arrowX: Dp, modifier: Modifier = Modifier) {+ Popover(330.dp, arrowX, modifier) {+ // a 52 header, the title's capitals from 28.5 below the panel's top; the groups 8 into the+ // list under it+ Box(Modifier.fillMaxWidth().height(52.dp).padding(start = 24.dp, top = 22.5.dp)) {+ Text("Adjustments", color = Pc.PanelTitle, fontSize = 24.sp, fontWeight = FontWeight.Bold, maxLines = 1)+ }+ Column(+ Modifier.verticalScroll(rememberScrollState()).padding(start = 10.dp, top = 8.dp, end = 10.dp, bottom = 10.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp),+ ) {+ for (group in Adjustment.groups) {+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(13.dp)).background(Pc.ActionsGroup)) {+ group.forEachIndexed { i, a ->+ if (i > 0) Box(Modifier.fillMaxWidth().height(1.dp).background(Pc.ActionsSeparator))+ Box(+ Modifier.fillMaxWidth().height(44.dp).then(if (a.ready) Modifier.tap { vm.startAdjustment(a) } else Modifier)+ .padding(start = 15.dp),+ contentAlignment = Alignment.CenterStart,+ ) {+ Text(a.label, color = if (a.ready) MenuText else Pc.ActionsDisabled, fontSize = 17.sp, maxLines = 1)+ }+ }+ }+ }+ }+ }+}++/**+ * The bar under the top bar while an adjustment is open: its icon and name, its amount when it has+ * one, and the triangle that opens its options; and under it the amount as a thin blue bar.+ */+@Composable+fun AdjustmentBar(vm: CanvasViewModel, modifier: Modifier = Modifier) {+ val a = vm.adjustment ?: return+ Column(modifier.fillMaxWidth()) {+ Row(Modifier.fillMaxWidth().height(32.dp).background(ModeBar), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically) {+ Box(Modifier.size(33.dp, 32.dp), contentAlignment = Alignment.Center) {+ // drawn in a 32 frame, shown as it is+ Icon(a.icon(), contentDescription = null, tint = ModeText, modifier = Modifier.requiredSize(32.dp))+ }+ Text(a.label, color = ModeText, fontSize = 17.sp, fontWeight = FontWeight.Bold, maxLines = 1)+ if (a.swiped) {+ Spacer(Modifier.width(3.dp))+ Text("${(vm.adjustAmount * 100).roundToInt()}%", color = ModeText, fontSize = 14.sp, maxLines = 1)+ }+ // Layer or Pencil, for the adjustments that can be painted on+ if (a.paintable) {+ Box(Modifier.size(33.dp, 32.dp).tap { vm.adjustModesOpen = !vm.adjustModesOpen }, contentAlignment = Alignment.Center) {+ Icon(PcIcons.Disclose, contentDescription = null, tint = ModeText, modifier = Modifier.requiredSize(32.dp))+ }+ }+ }+ if (a.swiped) {+ Box(Modifier.fillMaxWidth(vm.adjustAmount.coerceIn(0f, 1f)).height(4.dp).background(Pc.Accent))+ }+ }+}++private fun Adjustment.icon() = when (this) {+ Adjustment.HSB -> PcIcons.AdjustHsb+ Adjustment.COLOR_BALANCE -> PcIcons.AdjustBalance+ Adjustment.CURVES -> PcIcons.AdjustCurves+ Adjustment.GRADIENT_MAP -> PcIcons.AdjustGradient+ Adjustment.GAUSSIAN_BLUR -> PcIcons.AdjustBlur+ Adjustment.MOTION_BLUR -> PcIcons.AdjustMotion+ Adjustment.PERSPECTIVE_BLUR -> PcIcons.AdjustPerspective+ Adjustment.NOISE -> PcIcons.AdjustNoise+ Adjustment.SHARPEN -> PcIcons.AdjustSharpen+ Adjustment.BLOOM -> PcIcons.AdjustBloom+ Adjustment.GLITCH -> PcIcons.AdjustGlitch+ Adjustment.HALFTONE -> PcIcons.AdjustHalftone+ Adjustment.CHROMATIC_ABERRATION -> PcIcons.AdjustChromatic+ Adjustment.LIQUIFY -> PcIcons.AdjustLiquify+ Adjustment.CLONE -> PcIcons.AdjustClone+}++/** The floating panel of hue, saturation and brightness, each 0..100% with 50% leaving the layer as it was. */+@Composable+fun HsbPanel(vm: CanvasViewModel, modifier: Modifier = Modifier) {+ Column(+ modifier.offset(y = (-25).dp).size(532.dp, 220.dp).clip(RoundedCornerShape(33.dp)).background(HsbPanelFill).padding(horizontal = 26.dp, vertical = 16.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ val (h, s, b) = Triple(vm.hue50, vm.saturation50, vm.brightness50)+ HsbRow("Hue", h, Brush.horizontalGradient(HUE_STOPS.map { Color(it) }), { Color.hsv((it * 360f) % 360f, 1f, 1f) }) { vm.setHsb(it, s, b) }+ HsbRow("Saturation", s, Brush.horizontalGradient(listOf(Color(0xFF808080), Color(0xFFFF0000))), { lerp(Color(0xFF808080), Color.Red, it) }) { vm.setHsb(h, it, b) }+ HsbRow("Brightness", b, Brush.horizontalGradient(listOf(Color.Black, Color.White)), { lerp(Color.Black, Color.White, it) }) { vm.setHsb(h, s, it) }+ }+}++private val HUE_STOPS = listOf(0xFFFF0000, 0xFFFFFF00, 0xFF00FF00, 0xFF00FFFF, 0xFF0000FF, 0xFFFF00FF, 0xFFFF0000)++/** A labelled slider over a coloured track, its knob taking the track's colour where it sits. */+@Composable+private fun HsbRow(label: String, value: Float, track: Brush, knobColor: (Float) -> Color, onChange: (Float) -> Unit) {+ val change by rememberUpdatedState(onChange)+ Column(Modifier.fillMaxWidth().height(55.dp)) {+ Row(Modifier.fillMaxWidth().padding(top = 6.dp)) {+ Text(label, color = HsbLabel, fontSize = 16.sp, maxLines = 1, modifier = Modifier.weight(1f))+ Text("${(value * 100).roundToInt()}%", color = HsbValue, fontSize = 16.sp, maxLines = 1)+ }+ Box(+ Modifier.fillMaxWidth().height(24.dp).pointerInput(Unit) {+ awaitEachGesture {+ val down = awaitFirstDown()+ down.consume()+ change((down.position.x / size.width).coerceIn(0f, 1f))+ while (true) {+ val c = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break+ if (!c.pressed) break+ change((c.position.x / size.width).coerceIn(0f, 1f))+ c.consume()+ }+ }+ }.drawBehind {+ val y = size.height / 2f+ drawLine(track, Offset(0f, y), Offset(size.width, y), 3.dp.toPx(), cap = StrokeCap.Round)+ val knob = Size(24.dp.toPx(), 14.dp.toPx())+ val x = (size.width * value).coerceIn(knob.width / 2, size.width - knob.width / 2)+ drawRoundRect(Color(0x55000000), Offset(x - knob.width / 2, y - knob.height / 2 + 0.5.dp.toPx()), knob, CornerRadius(knob.height / 2))+ drawRoundRect(knobColor(value), Offset(x - knob.width / 2, y - knob.height / 2), knob, CornerRadius(knob.height / 2))+ },+ )+ }+}++private val PanelButton = Color(0xFF303030)+private val PanelButtonText = Color(0xFFA6A6A6)+private val GridLine = Color(0xFF8A8A8A)++/** The colour balance panel: three sliders between opposite colours, for the tone chosen below them. */+@Composable+fun ColorBalancePanel(vm: CanvasViewModel, modifier: Modifier = Modifier) {+ Column(+ modifier.offset(y = (-25).dp).size(532.dp, 272.dp).clip(RoundedCornerShape(33.dp)).background(HsbPanelFill).padding(horizontal = 26.dp, vertical = 16.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ val tone = vm.balanceTone+ val pairs = listOf(+ Triple("Cyan", "Red", listOf(Color(0xFF00FFFF), Color(0xFF808080), Color(0xFFFF0000))),+ Triple("Magenta", "Green", listOf(Color(0xFFFF00FF), Color(0xFF808080), Color(0xFF00FF00))),+ Triple("Yellow", "Blue", listOf(Color(0xFFFFFF00), Color(0xFF808080), Color(0xFF0000FF))),+ )+ pairs.forEachIndexed { k, (left, right, colours) ->+ val value = vm.balance[tone * 3 + k]+ BalanceRow(left, right, value, Brush.horizontalGradient(colours)) { vm.setBalance(k, it) }+ }+ Row(Modifier.fillMaxWidth().padding(top = 4.dp), horizontalArrangement = Arrangement.spacedBy(7.dp)) {+ listOf("Shadows", "Midtones", "Highlights").forEachIndexed { i, name ->+ val chosen = tone == i+ Box(+ Modifier.weight(1f).height(40.dp).clip(RoundedCornerShape(20.dp)).background(if (chosen) Pc.Accent else PanelButton).tap { vm.chooseBalanceTone(i) },+ contentAlignment = Alignment.Center,+ ) {+ Text(name, color = if (chosen) Color.White else PanelButtonText, fontSize = 15.sp, maxLines = 1)+ }+ }+ }+ }+}++/** A slider between two named colours, its middle leaving the colour as it was. */+@Composable+private fun BalanceRow(left: String, right: String, value: Float, track: Brush, onChange: (Float) -> Unit) {+ val change by rememberUpdatedState(onChange)+ Column(Modifier.fillMaxWidth().height(55.dp)) {+ Row(Modifier.fillMaxWidth().padding(top = 6.dp)) {+ Text(left, color = MenuText, fontSize = 16.sp, maxLines = 1, modifier = Modifier.weight(1f))+ Text(right, color = HsbValue, fontSize = 16.sp, maxLines = 1)+ }+ Box(+ Modifier.fillMaxWidth().height(24.dp).pointerInput(Unit) {+ awaitEachGesture {+ val down = awaitFirstDown()+ down.consume()+ change((down.position.x / size.width).coerceIn(0f, 1f))+ while (true) {+ val c = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break+ if (!c.pressed) break+ change((c.position.x / size.width).coerceIn(0f, 1f))+ c.consume()+ }+ }+ }.drawBehind {+ val y = size.height / 2f+ drawLine(track, Offset(0f, y), Offset(size.width, y), 3.dp.toPx(), cap = StrokeCap.Round)+ val knob = Size(24.dp.toPx(), 14.dp.toPx())+ val x = (size.width * value).coerceIn(knob.width / 2, size.width - knob.width / 2)+ drawRoundRect(Color(0x55000000), Offset(x - knob.width / 2, y - knob.height / 2 + 0.5.dp.toPx()), knob, CornerRadius(knob.height / 2))+ drawRoundRect(Color(0xFF7A7A7A), Offset(x - knob.width / 2, y - knob.height / 2), knob, CornerRadius(knob.height / 2))+ },+ )+ }+}++/** The curves panel: the chosen channel's curve over a grid (drag its points; touch elsewhere to add one), and the channels. */+@Composable+fun CurvesPanel(vm: CanvasViewModel, modifier: Modifier = Modifier) {+ Row(+ modifier.offset(y = (-25).dp).size(584.dp, 183.dp).clip(RoundedCornerShape(33.dp)).background(HsbPanelFill).padding(16.dp),+ horizontalArrangement = Arrangement.spacedBy(16.dp),+ ) {+ val points = vm.curves[vm.curveChannel]+ Box(+ Modifier.weight(1f).fillMaxHeight().padding(8.dp).pointerInput(vm.curveChannel) {+ awaitEachGesture {+ val down = awaitFirstDown()+ down.consume()+ val w = size.width.toFloat()+ val h = size.height.toFloat()+ fun toCurve(p: Offset) = Offset((p.x / w).coerceIn(0f, 1f), (1f - p.y / h).coerceIn(0f, 1f))+ val reach = 22.dp.toPx()+ val current = vm.curves[vm.curveChannel]+ var index = current.indexOfFirst { (Offset(it.x * w, (1f - it.y) * h) - down.position).getDistance() <= reach }+ if (index < 0) index = vm.addCurvePoint(toCurve(down.position))+ while (true) {+ val c = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break+ if (!c.pressed) break+ index = vm.moveCurvePoint(index, toCurve(c.position))+ c.consume()+ }+ }+ }.drawBehind {+ val w = size.width+ val h = size.height+ for (k in 0..4) {+ drawLine(GridLine, Offset(w * k / 4f, 0f), Offset(w * k / 4f, h), 1.dp.toPx())+ drawLine(GridLine, Offset(0f, h * k / 4f), Offset(w, h * k / 4f), 1.dp.toPx())+ }+ val curve = vm.curveShape(vm.curveChannel)+ for (i in 1 until curve.size) {+ drawLine(Color.White, Offset(curve[i - 1].x * w, (1f - curve[i - 1].y) * h), Offset(curve[i].x * w, (1f - curve[i].y) * h), 1.5.dp.toPx())+ }+ for (p in points) node(Offset(p.x * w, (1f - p.y) * h), CurveNode, 1f)+ },+ )+ Column(Modifier.width(111.dp).fillMaxHeight().clip(RoundedCornerShape(13.dp)), verticalArrangement = Arrangement.spacedBy(1.dp)) {+ listOf("Gamma", "Red", "Green", "Blue").forEachIndexed { i, name ->+ val chosen = vm.curveChannel == i+ Box(Modifier.fillMaxWidth().weight(1f).background(if (chosen) Pc.Accent else PanelButton).tap { vm.chooseCurveChannel(i) }, contentAlignment = Alignment.Center) {+ Text(name, color = if (chosen) Color.White else PanelButtonText, fontSize = 16.sp, maxLines = 1)+ }+ }+ }+ }+}++private val CurveNode = Color(0xFF0171EA)++/**+ * The gradient map panel: the gradient library (a tap chooses one, a tap on the chosen one edits+ * it, a hold offers Delete and Duplicate, "+" makes a new one), or the gradient being edited.+ */+@Composable+fun GradientMapPanel(vm: CanvasViewModel, modifier: Modifier = Modifier) {+ val editing = vm.gradientEditing+ Column(modifier.offset(y = (-25).dp).size(544.dp, 159.dp).clip(RoundedCornerShape(33.dp)).background(HsbPanelFill).padding(horizontal = 14.dp, vertical = 12.dp)) {+ Row(Modifier.fillMaxWidth().height(40.dp), verticalAlignment = Alignment.CenterVertically) {+ Text(if (editing != null) "Gradient Map" else "Gradient Library", color = MenuText, fontSize = 20.sp, fontWeight = FontWeight.Bold, maxLines = 1, modifier = Modifier.weight(1f).padding(start = 14.dp))+ if (editing != null) {+ Box(Modifier.size(40.dp).clip(androidx.compose.foundation.shape.CircleShape).background(GradientDone).tap { vm.endGradientEdit() }, contentAlignment = Alignment.Center) {+ Icon(PcIcons.DoneTick, contentDescription = "Done", tint = Color.White, modifier = Modifier.requiredSize(36.dp))+ }+ } else {+ val disc = androidx.compose.foundation.shape.CircleShape+ Box(Modifier.size(40.dp).clip(disc).background(PlusDisc).border(1.dp, PlusRim, disc).tap { vm.newGradient() }, contentAlignment = Alignment.Center) {+ Icon(PcIcons.Add, contentDescription = "New gradient", tint = PlusGlyph, modifier = Modifier.requiredSize(34.dp))+ }+ }+ }+ if (editing != null) GradientEditor(vm, editing) else GradientCards(vm)+ }+}++/** The library's cards on a grey band: each dark, its name over a strip of it; the chosen one stands taller. */+@Composable+private fun GradientCards(vm: CanvasViewModel) {+ var held by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf<Int?>(null) }+ Row(+ Modifier.fillMaxWidth().padding(top = 11.dp).height(81.dp).clip(RoundedCornerShape(12.dp)).background(GradientBand)+ .horizontalScroll(rememberScrollState()).padding(horizontal = 6.dp),+ horizontalArrangement = Arrangement.spacedBy(6.dp),+ verticalAlignment = Alignment.Bottom,+ ) {+ vm.gradients.forEachIndexed { i, g ->+ val chosen = vm.gradientIndex == i+ Column(+ Modifier.padding(bottom = 5.5.dp).size(108.dp, if (chosen) 69.dp else 65.dp).clip(RoundedCornerShape(9.dp)).background(GradientCard)+ .pointerInput(i, chosen) {+ detectTapGestures(+ onTap = { if (chosen) vm.editGradient(i) else vm.chooseGradient(i) },+ onLongPress = { held = i },+ )+ },+ ) {+ // a hold: Delete and Duplicate above the card+ LibraryMenu(held == i, androidx.compose.ui.graphics.TransformOrigin(0.5f, 1f), MenuPlace { a, size -> androidx.compose.ui.unit.IntOffset(a.center.x - size.width / 2, a.top - size.height) }, onDismiss = { held = null }, overPanel = true) {+ MenuItem(PcIcons.MenuTrash, "Delete", Pc.MenuDanger) {+ held = null+ vm.deleteGradient(i)+ }+ MenuItem(PcIcons.MenuDuplicate, "Duplicate") {+ held = null+ vm.duplicateGradient(i)+ }+ }+ Spacer(Modifier.weight(1f))+ Text(g.name, color = if (chosen) Color.White else GradientName, fontSize = 12.sp, maxLines = 1, modifier = Modifier.padding(start = 11.dp, bottom = 10.dp))+ Box(Modifier.fillMaxWidth().height(13.dp).background(gradientBrush(g)))+ }+ }+ }+}++/** A gradient's colours left to right, over [from]..[to] of the width (0..1). */+private fun gradientBrush(g: GradientPreset, from: Float = 0f, to: Float = 1f): Brush {+ val stops = g.stops.sortedBy { it.first }.map { (p, c) -> (from + p * (to - from)) to Color(c) }+ return if (stops.size >= 2) Brush.horizontalGradient(*stops.toTypedArray()) else androidx.compose.ui.graphics.SolidColor(stops.firstOrNull()?.second ?: Color.Black)+}++private val StopSize = 42.dp+/** Room round a popover shown in a popup of its own, for its shadow. */+private val PopupShadowRoom = 56.dp++/**+ * The gradient being edited: its name to rename, over its bar, with a disc for each stop. A tap on+ * the bar adds a stop; on a stop, its colours open above it. A stop drags along the bar; a hold+ * offers Delete.+ */+@Composable+private fun GradientEditor(vm: CanvasViewModel, index: Int) {+ val g = vm.gradients.getOrNull(index) ?: return+ val stops by rememberUpdatedState(g.stops)+ val density = androidx.compose.ui.platform.LocalDensity.current+ var colouring by androidx.compose.runtime.remember(index) { androidx.compose.runtime.mutableStateOf<Int?>(null) }+ var holding by androidx.compose.runtime.remember(index) { androidx.compose.runtime.mutableStateOf<Int?>(null) }+ var barWidth by androidx.compose.runtime.remember { androidx.compose.runtime.mutableFloatStateOf(1f) }+ // where the bar is in the window, for what opens over a stop+ var barAt by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf(Offset.Zero) }+ val r = with(density) { StopSize.toPx() / 2f }+ // a stop's centre along the bar, and the stop under a point+ fun xOf(p: Float) = r + p * (barWidth - 2f * r)+ fun positionAt(x: Float) = ((x - r) / (barWidth - 2f * r).coerceAtLeast(1f)).coerceIn(0f, 1f)+ fun stopAt(at: Offset): Int? = stops.indices.filter { kotlin.math.abs(xOf(stops[it].first) - at.x) <= r }.minByOrNull { kotlin.math.abs(xOf(stops[it].first) - at.x) }+ Column(Modifier.padding(top = 11.dp).fillMaxWidth().height(81.dp).clip(RoundedCornerShape(12.dp)).background(EditorCard)) {+ var name by androidx.compose.runtime.remember(index) { androidx.compose.runtime.mutableStateOf(g.name) }+ androidx.compose.foundation.text.BasicTextField(+ name,+ { name = it.take(64); vm.renameGradient(name) },+ singleLine = true,+ textStyle = androidx.compose.ui.text.TextStyle(color = EditorName, fontSize = 14.sp),+ cursorBrush = androidx.compose.ui.graphics.SolidColor(Pc.Accent),+ modifier = Modifier.padding(start = 14.dp, top = 8.dp, end = 14.dp).fillMaxWidth().height(28.dp),+ )+ Spacer(Modifier.weight(1f))+ Box(+ Modifier.fillMaxWidth().height(44.dp)+ .then(+ Modifier.onGloballyPositioned {+ barWidth = it.size.width.toFloat()+ barAt = it.positionInWindow()+ },+ )+ .drawBehind { drawRect(gradientBrush(g, r / size.width, 1f - r / size.width)) }+ .pointerInput(index) {+ detectTapGestures(+ onTap = { at ->+ val hit = stopAt(at)+ if (hit != null) colouring = hit else vm.addGradientStop(positionAt(at.x))+ },+ onLongPress = { at -> holding = stopAt(at) },+ )+ }+ .pointerInput(index) {+ var dragged: Int? = null+ detectDragGestures(+ onDragStart = { at -> dragged = stopAt(at) },+ onDrag = { change, _ ->+ dragged?.let {+ change.consume()+ vm.moveGradientStop(it, positionAt(change.position.x))+ }+ },+ onDragEnd = { dragged = null },+ onDragCancel = { dragged = null },+ )+ },+ ) {+ androidx.compose.foundation.Canvas(Modifier.fillMaxSize()) {+ val ring = 2.dp.toPx()+ for ((p, c) in stops) {+ val centre = Offset(xOf(p), size.height / 2f)+ val fill = Color(c)+ // the ring stands out from what it rings: white round a dark colour, black round a light one+ val light = 0.299f * fill.red + 0.587f * fill.green + 0.114f * fill.blue > 0.45f+ drawCircle(if (light) Color.Black else Color.White, r, centre)+ drawCircle(fill, r - ring, centre)+ }+ }+ colouring?.let { i ->+ val rgb = (stops.getOrNull(i)?.second ?: 0xFF000000).toInt() and 0xFFFFFF+ val held = androidx.compose.runtime.remember(i) { HeldColor(rgb) { vm.setGradientStopColor(i, it) } }+ // over the stop, its arrow at the stop's top, kept inside the window+ val window = androidx.compose.ui.platform.LocalWindowInfo.current.containerSize+ val width = with(density) { CompactColorsWidth.toPx() }+ val centre = barAt.x + xOf(stops.getOrNull(i)?.first ?: 0f)+ val left = (centre - width / 2f).coerceIn(0f, (window.width - width).coerceAtLeast(0f))+ val tip = barAt.y + with(density) { (22.dp - StopSize / 2).toPx() }+ // room round it for its shadow to fade out in+ val room = with(density) { PopupShadowRoom.toPx() }+ androidx.compose.ui.window.Popup(+ popupPositionProvider = object : androidx.compose.ui.window.PopupPositionProvider {+ override fun calculatePosition(+ anchorBounds: androidx.compose.ui.unit.IntRect,+ windowSize: androidx.compose.ui.unit.IntSize,+ layoutDirection: androidx.compose.ui.unit.LayoutDirection,+ popupContentSize: androidx.compose.ui.unit.IntSize,+ ) = androidx.compose.ui.unit.IntOffset((left - room).roundToInt(), (tip + room - popupContentSize.height).roundToInt())+ },+ onDismissRequest = { colouring = null },+ properties = androidx.compose.ui.window.PopupProperties(focusable = true, clippingEnabled = false),+ ) {+ CompactColors(vm, held, arrowX = with(density) { (centre - left).toDp() }, modifier = Modifier.padding(PopupShadowRoom), side = ArrowSide.BOTTOM)+ }+ }+ holding?.let { i ->+ val stopX = xOf(stops.getOrNull(i)?.first ?: 0f)+ LibraryMenu(+ true,+ androidx.compose.ui.graphics.TransformOrigin(0.5f, 1f),+ MenuPlace { a, size -> androidx.compose.ui.unit.IntOffset(a.left + stopX.roundToInt() - size.width / 2, a.top + with(density) { (22.dp - StopSize / 2).roundToPx() } - size.height) },+ onDismiss = { holding = null },+ overPanel = true,+ ) {+ MenuItem(PcIcons.MenuTrash, "Delete", Pc.MenuDanger) {+ holding = null+ vm.deleteGradientStop(i)+ }+ }+ }+ }+ }+}++private val GradientBand = Color(0xFF535353)+private val GradientDone = Color(0xFF0190FF)+private val PlusDisc = Color(0xFF1B1B1B)+private val PlusRim = Color(0xFF373737)+private val PlusGlyph = Color(0xFFAAAAAA)+private val EditorCard = Color(0xFF383838)+private val EditorName = Color(0xFFC5C5C5)+private val GradientCard = Color(0xFF282828)+private val GradientName = Color(0xFFC1C1C1)++/** A gradient to map by: its name and colour stops (position, 0xAARRGGBB), in any order. */+data class GradientPreset(val name: String, val stops: List<Pair<Float, Long>>)++/** The colour gradient [g] has at [p] (0..1): its stops' colours mixed between them. */+fun gradientColorAt(g: GradientPreset, p: Float): Long {+ val stops = g.stops.sortedBy { it.first }+ val first = stops.firstOrNull() ?: return 0xFF000000+ if (p <= first.first) return first.second+ for ((a, b) in stops.zipWithNext()) {+ if (p <= b.first) {+ val t = if (b.first > a.first) (p - a.first) / (b.first - a.first) else 1f+ fun ch(c: Long, shift: Int) = ((c shr shift) and 0xFF).toFloat()+ fun mix(shift: Int) = (ch(a.second, shift) + (ch(b.second, shift) - ch(a.second, shift)) * t).toInt().coerceIn(0, 255).toLong() shl shift+ return 0xFF000000 or mix(16) or mix(8) or mix(0)+ }+ }+ return stops.last().second+}++/** ProCraft's own gradients. */+val GRADIENTS = listOf(+ GradientPreset("Ember", listOf(0f to 0xFF140A1E, 0.45f to 0xFF9C2A1F, 0.8f to 0xFFF29B38, 1f to 0xFFFFF4D6)),+ GradientPreset("Glacier", listOf(0f to 0xFF0B1A33, 0.5f to 0xFF3F7FB5, 1f to 0xFFE8F6FF)),+ GradientPreset("Moss", listOf(0f to 0xFF101A0C, 0.5f to 0xFF5C7A34, 1f to 0xFFE9F0C8)),+ GradientPreset("Citrus", listOf(0f to 0xFF2B1640, 0.5f to 0xFFE0466A, 1f to 0xFFFFE15C)),+ GradientPreset("Graphite", listOf(0f to 0xFF000000, 1f to 0xFFFFFFFF)),+ GradientPreset("Lagoon", listOf(0f to 0xFF06202A, 0.55f to 0xFF1B9A8E, 1f to 0xFFF4F1D0)),+)++private val MenuButton = Color(0xFF3B3B3B)+private val MenuButtonText = Color(0xFFD8D8D8)++/**+ * The menu a tap on the canvas opens during an adjustment: apply above, undo to the left, preview+ * in the middle, cancel to the right and reset below, around the tap.+ */+@Composable+fun AdjustmentMenu(vm: CanvasViewModel) {+ val at = vm.adjustMenuAt ?: return+ val density = androidx.compose.ui.platform.LocalDensity.current+ val centre = with(density) { androidx.compose.ui.unit.DpOffset(at.x.toDp(), at.y.toDp()) }+ val step = 88.dp+ val items = listOf(+ Triple(PcIcons.Apply, "Apply", Offset(0f, -1f)) to { vm.applyAdjustment() },+ Triple(PcIcons.PieUndo, "Undo", Offset(-1f, 0f)) to { vm.undoAdjustment() },+ Triple(PcIcons.Preview, "Preview", Offset(0f, 0f)) to { vm.togglePreview() },+ Triple(PcIcons.CancelAdjust, "Cancel", Offset(1f, 0f)) to { vm.cancelAdjustment() },+ Triple(PcIcons.PieReset, "Reset", Offset(0f, 1f)) to { vm.resetAdjustment() },+ )+ for ((item, action) in items) {+ val (icon, label, place) = item+ Box(+ Modifier.offset(centre.x - 40.dp + step * place.x, centre.y - 40.dp + step * place.y).size(80.dp)+ .clip(RoundedCornerShape(22.dp)).background(MenuButton).tap {+ vm.adjustMenuAt = null+ action()+ },+ ) {+ // the icon (a 50 frame) 30 across, centred 33 down; the name from 45 down+ Icon(icon, contentDescription = null, tint = MenuButtonText, modifier = Modifier.align(Alignment.TopCenter).padding(top = 18.dp).requiredSize(30.dp))+ Text(label, color = MenuButtonText, fontSize = 13.5.sp, maxLines = 1, modifier = Modifier.align(Alignment.TopCenter).padding(top = 44.dp))+ }+ }+}++private val LIQUIFY_NAMES = listOf(+ LiquifyKind.PUSH to "Push",+ LiquifyKind.TWIRL_RIGHT to "Twirl Right",+ LiquifyKind.TWIRL_LEFT to "Twirl Left",+ LiquifyKind.PINCH to "Pinch",+ LiquifyKind.EXPAND to "Expand",+ LiquifyKind.CRYSTALS to "Crystals",+ LiquifyKind.EDGE to "Edge",+ LiquifyKind.RECONSTRUCT to "Reconstruct",+)++/** The liquify panel: the brush's size, pressure, distortion and momentum; its way, adjust and reset. */+@Composable+fun LiquifyPanel(vm: CanvasViewModel, screenWidth: Dp, screenHeight: Dp, modifier: Modifier = Modifier) {+ Column(+ modifier.offset(y = (-25).dp).size(654.dp, 200.dp).clip(RoundedCornerShape(33.dp)).background(HsbPanelFill).padding(16.dp),+ verticalArrangement = Arrangement.SpaceBetween,+ ) {+ val percent = { v: Float, none: String? -> if (v >= 1f) "Max" else if (v <= 0f && none != null) none else "${(v * 100).roundToInt()}%" }+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(20.dp)) {+ Box(Modifier.weight(1f)) { SliderRow("Size", vm.liquifySize, percent(vm.liquifySize, null)) { vm.liquifySize = it } }+ Box(Modifier.weight(1f)) { SliderRow("Pressure", vm.liquifyPressure, percent(vm.liquifyPressure, null)) { vm.liquifyPressure = it } }+ }+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(20.dp)) {+ Box(Modifier.weight(1f)) { SliderRow("Distortion", vm.liquifyDistortion, percent(vm.liquifyDistortion, "None")) { vm.liquifyDistortion = it } }+ Box(Modifier.weight(1f)) { SliderRow("Momentum", vm.liquifyMomentum, percent(vm.liquifyMomentum, "None")) { vm.liquifyMomentum = it } }+ }+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ val name = LIQUIFY_NAMES.firstOrNull { it.first == vm.liquifyKind }?.second ?: ""+ Box(Modifier.weight(1f).height(40.dp).clip(RoundedCornerShape(20.dp)).background(PanelButton).tap { vm.liquifyPopup = if (vm.liquifyPopup == 1) 0 else 1 }, contentAlignment = Alignment.Center) {+ Text(name, color = MenuText, fontSize = 15.sp, maxLines = 1)+ }+ val canAdjust = vm.liquified+ Row(+ Modifier.weight(1f).height(40.dp).clip(RoundedCornerShape(20.dp)).background(PanelButton.copy(alpha = if (canAdjust) 1f else 0.5f))+ .then(if (canAdjust) Modifier.tap { vm.liquifyPopup = if (vm.liquifyPopup == 2) 0 else 2 } else Modifier),+ horizontalArrangement = Arrangement.Center,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ val tint = if (canAdjust) MenuText else Color(0xFF575757)+ // a 50 frame shown 39.5 across, the name 2 after+ Icon(PcIcons.AdjustKnob, contentDescription = null, tint = tint, modifier = Modifier.requiredSize(39.5.dp))+ Spacer(Modifier.width(2.dp))+ Text("Adjust", color = tint, fontSize = 15.sp, maxLines = 1)+ }+ Row(+ Modifier.weight(1f).height(40.dp).clip(RoundedCornerShape(20.dp)).background(PanelButton.copy(alpha = if (canAdjust) 1f else 0.5f))+ .then(if (canAdjust) Modifier.tap { vm.resetLiquify() } else Modifier),+ horizontalArrangement = Arrangement.Center,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ val tint = if (canAdjust) MenuText else Color(0xFF575757)+ // the pie's reset, 23 across here, the name 2.5 after+ Icon(PcIcons.PieReset, contentDescription = null, tint = tint, modifier = Modifier.requiredSize(23.dp))+ Spacer(Modifier.width(2.5.dp))+ Text("Reset", color = tint, fontSize = 15.sp, maxLines = 1)+ }+ }+ }+ // the way's list and the adjust slider open over the panel's buttons+ val panelLeft = (screenWidth - 654.dp) / 2+ val buttonsTop = screenHeight - 25.dp - 16.dp - 40.dp+ when (vm.liquifyPopup) {+ 1 -> {+ val centre = panelLeft + 16.dp + (654.dp - 32.dp - 16.dp) / 6+ val left = (centre - 130.dp).coerceIn(0.dp, screenWidth - 260.dp)+ MenuPopover(centre - left, left, buttonsTop) {+ MenuTitle("Liquify Mode")+ Spacer(Modifier.height(10.dp))+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(13.dp)).background(MenuGroup)) {+ LIQUIFY_NAMES.forEachIndexed { i, (kind, label) ->+ if (i > 0) Box(Modifier.fillMaxWidth().height(1.dp).background(MenuLine))+ val chosen = vm.liquifyKind == kind+ Row(+ Modifier.fillMaxWidth().height(44.dp).background(if (chosen) Pc.Accent else Color.Transparent).tap { vm.chooseLiquifyKind(kind) }.padding(start = 16.dp, end = 14.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ MenuLabel(label, if (chosen) Color.White else MenuText, Modifier.weight(1f))+ if (chosen) Icon(PcIcons.MenuTick, contentDescription = null, tint = Color.White, modifier = Modifier.size(29.dp))+ }+ }+ }+ }+ }+ 2 -> {+ val centre = screenWidth / 2+ MenuPopover(130.dp, centre - 130.dp, buttonsTop) {+ MenuTitle("Adjust")+ Spacer(Modifier.height(4.dp))+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(13.dp)).background(MenuGroup).padding(vertical = 8.dp)) {+ SliderRow("Amount", vm.liquifyAmount, "${(vm.liquifyAmount * 100).roundToInt()}%") { vm.changeLiquifyAmount(it) }+ }+ }+ }+ }+}++private val ModesFill = Color(0xFF7B7B7B)++/** The Layer / Pencil choice under the mode bar: the adjustment changes the layer, or is painted on. */+@Composable+fun AdjustModes(vm: CanvasViewModel, modifier: Modifier = Modifier) {+ if (!vm.adjustModesOpen) return+ Row(+ modifier.size(225.dp, 36.dp).clip(RoundedCornerShape(18.dp)).background(ModesFill).padding(2.dp),+ horizontalArrangement = Arrangement.spacedBy(1.dp),+ ) {+ for ((pencil, item) in listOf(false to (PcIcons.ModeLayer to "Layer"), true to (PcIcons.ModePencil to "Pencil"))) {+ val (icon, label) = item+ val chosen = vm.adjustPencil == pencil+ Row(+ Modifier.size(110.dp, 32.dp).clip(RoundedCornerShape(16.dp)).background(if (chosen) Pc.Accent else Color.Transparent)+ .tap { vm.chooseAdjustMode(pencil) }.padding(start = 24.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ // drawn in 27 x 32 (the pencil 24 x 32) frames, shown as they are+ Icon(icon, contentDescription = null, tint = Color.White, modifier = Modifier.requiredSize(if (pencil) 24.dp else 27.dp, 32.dp))+ Spacer(Modifier.width(1.5.dp))+ Text(label, color = Color.White, fontSize = 14.sp, maxLines = 1)+ }+ }+ }+}++/** The clone source: a dark ring with a light edge, so it shows on any colour. */+@Composable+fun ClonePuck(vm: CanvasViewModel) {+ val puck = vm.clonePuck ?: return+ val at = vm.canvasToWindow(puck)+ androidx.compose.foundation.Canvas(Modifier.fillMaxSize()) {+ val r = CanvasViewModel.CLONE_PUCK_RADIUS_DP.dp.toPx()+ drawCircle(Color.White, r, at, style = androidx.compose.ui.graphics.drawscope.Stroke(4.dp.toPx()))+ drawCircle(Color.Black, r, at, style = androidx.compose.ui.graphics.drawscope.Stroke(2.dp.toPx()))+ }+}++private val KindsFill = Color(0xFF535353)+private val KindsEdge = Color(0xFF747474)+private val GlitchTrack = Color(0xFF2E2E2E)+private val GlitchTick = Color(0xFF4A4A4A)++private val GLITCH_KINDS = listOf(+ Triple(GlitchKind.ARTIFACT, "Artifact", 111.dp),+ Triple(GlitchKind.WAVE, "Wave", 99.dp),+ Triple(GlitchKind.SIGNAL, "Signal", 104.dp),+ Triple(GlitchKind.DIVERGE, "Diverge", 113.dp),+)++/** The glitch toolbar: its four kinds above the kind's sliders, two to a row. */+@Composable+fun GlitchPanel(vm: CanvasViewModel, modifier: Modifier = Modifier) {+ Column(+ modifier.offset(y = (-25).dp).size(640.dp, 167.dp).clip(RoundedCornerShape(33.dp)).background(HsbPanelFill).padding(top = 8.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ KindsSwitch(466.dp, GLITCH_KINDS.map { (kind, label, width) -> Kind(kind.icon(), label, width) }, GLITCH_KINDS.indexOfFirst { it.first == vm.glitchKind }) {+ vm.chooseGlitchKind(GLITCH_KINDS[it].first)+ }+ val names = when (vm.glitchKind) {+ GlitchKind.ARTIFACT, GlitchKind.SIGNAL -> listOf("Amount", "Block Size", "Zoom")+ GlitchKind.WAVE -> listOf("Amplitude", "Frequency", "Zoom")+ GlitchKind.DIVERGE -> listOf("Red shift", "Green shift", "Blue shift", "Zoom")+ }+ val values = vm.glitchValues[vm.glitchKind].orEmpty()+ Spacer(Modifier.height(12.dp))+ for (row in names.indices.chunked(2)) {+ Row(Modifier.width(608.dp).height(54.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ for (k in row) {+ // diverge's shifts go both ways from the middle+ val both = vm.glitchKind == GlitchKind.DIVERGE && k < 3+ val v = values.getOrElse(k) { 0f }+ OptionSlider(names[k], v, "${(v * 100).roundToInt()}%", 300.dp, both) { vm.setGlitchValue(k, it) }+ }+ }+ }+ }+}++/** One choice in a [KindsSwitch]: its icon, label and width. */+internal class Kind(val icon: androidx.compose.ui.graphics.vector.ImageVector, val label: String, val width: Dp)++/** A toolbar's row of kinds, [width] wide, the [chosen] one blue. */+@Composable+internal fun KindsSwitch(width: Dp, kinds: List<Kind>, chosen: Int, onChoose: (Int) -> Unit) {+ Row(+ Modifier.size(width, 34.dp).clip(RoundedCornerShape(17.dp)).background(KindsFill).border(1.dp, KindsEdge, RoundedCornerShape(17.dp)).padding(2.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ ) {+ kinds.forEachIndexed { i, kind ->+ val on = i == chosen+ Row(+ Modifier.size(kind.width, 30.dp).clip(RoundedCornerShape(15.dp)).background(if (on) Pc.Accent else Color.Transparent).tap { onChoose(i) },+ horizontalArrangement = Arrangement.Center,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ // drawn in a 50 frame, shown 30 across, the name 2 after+ Icon(kind.icon, contentDescription = null, tint = if (on) Color.White else ModesText, modifier = Modifier.requiredSize(30.dp))+ Spacer(Modifier.width(2.dp))+ Text(kind.label, color = if (on) Color.White else ModesText, fontSize = 14.sp, maxLines = 1)+ }+ }+ }+}++/** A toolbar's floating panel, [width] × [height], 25 above the bottom. */+@Composable+internal fun OptionsPanel(width: Dp, height: Dp, modifier: Modifier, top: Dp, content: @Composable androidx.compose.foundation.layout.ColumnScope.() -> Unit) {+ Column(+ modifier.offset(y = (-25).dp).size(width, height).clip(RoundedCornerShape(33.dp)).background(HsbPanelFill).padding(top = top),+ horizontalAlignment = Alignment.CenterHorizontally,+ content = content,+ )+}++/** A slider's value as shown: None at nothing, Max at all ([max]), else a percentage. */+internal fun shown(v: Float, max: Boolean = false) = when {+ v <= 0f -> "None"+ max && v >= 1f -> "Max"+ else -> "${(v * 100).roundToInt()}%"+}++/** A labelled toolbar slider [width] wide: [both] ways runs −1..1 with its fill from the middle, else 0..1. */+@Composable+internal fun OptionSlider(label: String, value: Float, shown: String, width: Dp, both: Boolean = false, labelColor: Color = HsbLabel, onChange: (Float) -> Unit) {+ val change by rememberUpdatedState(onChange)+ Column(Modifier.width(width).height(54.dp)) {+ Row(Modifier.fillMaxWidth().padding(start = 10.dp, end = 15.dp, top = 6.dp)) {+ Text(label, color = labelColor, fontSize = 16.sp, maxLines = 1, modifier = Modifier.weight(1f))+ Text(shown, color = HsbValue, fontSize = 16.sp, maxLines = 1)+ }+ Box(+ Modifier.fillMaxWidth().height(24.dp).padding(start = 10.dp, end = 11.dp).pointerInput(both) {+ fun at(x: Float): Float {+ val t = (x / size.width).coerceIn(0f, 1f)+ return if (both) t * 2f - 1f else t+ }+ awaitEachGesture {+ val down = awaitFirstDown()+ down.consume()+ while (true) {+ val c = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break+ if (!c.pressed) break+ change(at(c.position.x))+ c.consume()+ }+ }+ }.drawBehind {+ val y = size.height / 2f+ val t = if (both) (value + 1f) / 2f else value+ val x = size.width * t.coerceIn(0f, 1f)+ val from = if (both) size.width / 2f else 0f+ val line = 2.dp.toPx()+ drawLine(GlitchTrack, Offset(0f, y), Offset(size.width, y), line, cap = StrokeCap.Round)+ drawLine(Pc.Accent, Offset(from, y), Offset(x, y), line, cap = StrokeCap.Round)+ if (both) drawLine(GlitchTick, Offset(from, y - 6.dp.toPx()), Offset(from, y + 6.dp.toPx()), 1.dp.toPx())+ val knob = Size(17.dp.toPx(), 11.dp.toPx())+ val kx = x.coerceIn(knob.width / 2, size.width - knob.width / 2)+ drawRoundRect(Color(0x33000000), Offset(kx - knob.width / 2, y - knob.height / 2 + 0.5.dp.toPx()), knob, CornerRadius(knob.height / 2))+ drawRoundRect(Color.White, Offset(kx - knob.width / 2, y - knob.height / 2), knob, CornerRadius(knob.height / 2))+ },+ )+ }+}++private val ModesText = Color(0xFFD0D0D0)++private fun GlitchKind.icon() = when (this) {+ GlitchKind.ARTIFACT -> PcIcons.GlitchArtifact+ GlitchKind.WAVE -> PcIcons.GlitchWave+ GlitchKind.SIGNAL -> PcIcons.GlitchSignal+ GlitchKind.DIVERGE -> PcIcons.GlitchDiverge+}++/** The noise toolbar: its three kinds, scale, octaves and turbulence, single or multi channel, added or not. */+@Composable+fun NoisePanel(vm: CanvasViewModel, modifier: Modifier = Modifier) {+ OptionsPanel(532.dp, 292.dp, modifier, 10.dp) {+ val kinds = listOf(NoiseKind.CLOUDS, NoiseKind.BILLOWS, NoiseKind.RIDGES)+ KindsSwitch(472.dp, listOf(Kind(PcIcons.NoiseClouds, "Clouds", 149.dp), Kind(PcIcons.NoiseBillows, "Billows", 149.dp), Kind(PcIcons.NoiseRidges, "Ridges", 148.dp)), kinds.indexOf(vm.noiseKind)) {+ vm.chooseNoiseKind(kinds[it])+ }+ Spacer(Modifier.height(8.dp))+ Column(Modifier.width(500.dp), verticalArrangement = Arrangement.spacedBy(8.5.dp)) {+ OptionSlider("Scale", vm.noiseScale, shown(vm.noiseScale), 500.dp, labelColor = ModesText) { vm.setNoiseValue(0, it) }+ OptionSlider("Octaves", vm.noiseOctaves, shown(vm.noiseOctaves), 500.dp, labelColor = ModesText) { vm.setNoiseValue(1, it) }+ OptionSlider("Turbulence", vm.noiseTurbulence, shown(vm.noiseTurbulence), 500.dp, labelColor = ModesText) { vm.setNoiseValue(2, it) }+ }+ Spacer(Modifier.height(12.dp))+ Row(Modifier.width(492.dp).height(40.dp), verticalAlignment = Alignment.CenterVertically) {+ for ((multi, label) in listOf(false to "Single", true to "Multi")) {+ val on = vm.noiseMulti == multi+ Box(+ Modifier.size(160.dp, 40.dp).clip(RoundedCornerShape(20.dp)).background(if (on) Pc.Accent else NoiseButton).tap { vm.chooseNoiseMulti(multi) },+ contentAlignment = Alignment.Center,+ ) {+ Text(label, color = if (on) Color.White else ModesText, fontSize = 15.sp, maxLines = 1)+ }+ Spacer(Modifier.width(7.dp))+ }+ Box(Modifier.weight(1f), contentAlignment = Alignment.Center) {+ Text("Additive", color = ModesText, fontSize = 16.sp, maxLines = 1)+ }+ Box(Modifier.tap { vm.toggleNoiseAdded() }) { Switch(vm.noiseAdded, enabled = true) }+ }+ }+}++private val NoiseButton = Color(0xFF1E1E1E)++/** The bloom toolbar: transition, size and burn. */+@Composable+fun BloomPanel(vm: CanvasViewModel, modifier: Modifier = Modifier) {+ OptionsPanel(532.dp, 220.dp, modifier, 24.dp) {+ Column(Modifier.width(500.dp), verticalArrangement = Arrangement.spacedBy(8.5.dp)) {+ OptionSlider("Transition", vm.bloomTransition, shown(vm.bloomTransition, max = true), 500.dp) { vm.setBloomValue(0, it) }+ OptionSlider("Size", vm.bloomSize, shown(vm.bloomSize, max = true), 500.dp) { vm.setBloomValue(1, it) }+ OptionSlider("Burn", vm.bloomBurn, shown(vm.bloomBurn, max = true), 500.dp) { vm.setBloomValue(2, it) }+ }+ }+}++/** The halftone toolbar: full colour, screen print or newspaper. */+@Composable+fun HalftonePanel(vm: CanvasViewModel, modifier: Modifier = Modifier) {+ OptionsPanel(507.dp, 66.dp, modifier, 16.dp) {+ val kinds = listOf(HalftoneKind.FULL_COLOR, HalftoneKind.SCREEN_PRINT, HalftoneKind.NEWSPAPER)+ KindsSwitch(475.dp, listOf(Kind(PcIcons.HalftoneFull, "Full Color", 140.dp), Kind(PcIcons.HalftoneScreen, "Screen Print", 157.dp), Kind(PcIcons.HalftoneNews, "Newspaper", 151.dp)), kinds.indexOf(vm.halftoneKind)) {+ vm.chooseHalftoneKind(kinds[it])+ }+ }+}++/** The chromatic aberration toolbar: perspective or displace, with the kind's two sliders. */+@Composable+fun ChromaticPanel(vm: CanvasViewModel, modifier: Modifier = Modifier) {+ OptionsPanel(668.dp, 120.dp, modifier, 8.dp) {+ val kinds = listOf(ChromaticKind.PERSPECTIVE, ChromaticKind.DISPLACE)+ KindsSwitch(428.dp, listOf(Kind(PcIcons.ChromaPerspective, "Perspective", 204.dp), Kind(PcIcons.ChromaDisplace, "Displace", 204.dp)), kinds.indexOf(vm.chromaKind)) {+ vm.chooseChromaKind(kinds[it])+ }+ Spacer(Modifier.height(12.dp))+ val names = if (vm.chromaKind == ChromaticKind.PERSPECTIVE) listOf("Transition", "Fall off") else listOf("Blur", "Transparency")+ val values = vm.chromaValues[vm.chromaKind].orEmpty()+ Row(Modifier.width(620.dp), horizontalArrangement = Arrangement.spacedBy(20.dp)) {+ names.forEachIndexed { k, name ->+ val v = values.getOrElse(k) { 0f }+ OptionSlider(name, v, shown(v, max = true), 300.dp) { vm.setChromaValue(k, it) }+ }+ }+ }+}++private fun QuickShapeKind.label() = when (this) {+ QuickShapeKind.LINE -> "Line"+ QuickShapeKind.POLYLINE -> "Polyline"+ QuickShapeKind.ARC -> "Arc"+ QuickShapeKind.ELLIPSE -> "Ellipse"+ QuickShapeKind.CIRCLE -> "Circle"+ QuickShapeKind.TRIANGLE -> "Triangle"+ QuickShapeKind.EQUILATERAL_TRIANGLE -> "Equilateral"+ QuickShapeKind.QUADRILATERAL -> "Quadrilateral"+ QuickShapeKind.RECTANGLE -> "Rectangle"+ QuickShapeKind.SQUARE -> "Square"+}++private fun QuickShapeKind.icon() = when (this) {+ QuickShapeKind.LINE -> PcIcons.ShapeLine+ QuickShapeKind.POLYLINE -> PcIcons.ShapePolyline+ QuickShapeKind.ARC -> PcIcons.ShapeArc+ QuickShapeKind.ELLIPSE -> PcIcons.ShapeEllipse+ QuickShapeKind.CIRCLE -> PcIcons.ShapeCircle+ QuickShapeKind.TRIANGLE -> PcIcons.ShapeTriangle+ QuickShapeKind.EQUILATERAL_TRIANGLE -> PcIcons.ShapeEquilateral+ QuickShapeKind.QUADRILATERAL -> PcIcons.ShapeQuad+ QuickShapeKind.RECTANGLE -> PcIcons.ShapeRect+ QuickShapeKind.SQUARE -> PcIcons.ShapeSquare+}++/**+ * The bar a snapped stroke shows: the shape's name (and, while its handles show, "Editing" and+ * the kind in grey); a tap shows the handles, and the kinds it can be shown as below.+ */+@Composable+fun QuickShapeBar(vm: CanvasViewModel, modifier: Modifier = Modifier) {+ val info = vm.quickShape ?: return+ Column(modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {+ Row(+ Modifier.fillMaxWidth().height(32.dp).background(ModeBar).tap { vm.quickShapeEditing = true },+ horizontalArrangement = Arrangement.Center,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Box(Modifier.size(29.dp, 28.dp), contentAlignment = Alignment.Center) {+ // drawn in a 28 frame, shown as it is+ Icon(info.kind.icon(), contentDescription = null, tint = ModeText, modifier = Modifier.requiredSize(28.dp))+ }+ Text(if (vm.quickShapeEditing) "Editing" else info.kind.label(), color = ModeText, fontSize = 17.sp, fontWeight = FontWeight.Bold, maxLines = 1)+ if (vm.quickShapeEditing && info.choices.size > 1) {+ Spacer(Modifier.width(3.dp))+ Text(info.kind.label(), color = Color(0xFF9A9A9A), fontSize = 15.sp, maxLines = 1)+ }+ if (info.choices.size > 1) {+ Box(Modifier.size(33.dp, 32.dp), contentAlignment = Alignment.Center) {+ Icon(PcIcons.Disclose, contentDescription = null, tint = ModeText, modifier = Modifier.requiredSize(32.dp))+ }+ }+ }+ if (vm.quickShapeEditing && info.choices.size > 1) {+ val each = if (info.choices.size > 2) 154.dp else 116.dp+ Spacer(Modifier.height(20.dp))+ Row(+ Modifier.height(32.dp).clip(RoundedCornerShape(16.dp)).background(ModesFill).padding(2.dp),+ horizontalArrangement = Arrangement.spacedBy(2.dp),+ ) {+ for (kind in info.choices) {+ val chosen = kind == info.kind+ Row(+ Modifier.size(each, 28.dp).clip(RoundedCornerShape(14.dp)).background(if (chosen) Pc.Accent else Color.Transparent).tap { vm.chooseQuickShape(kind) },+ horizontalArrangement = Arrangement.Center,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Icon(kind.icon(), contentDescription = null, tint = Color.White, modifier = Modifier.requiredSize(28.dp))+ Spacer(Modifier.width(6.dp))+ Text(kind.label(), color = Color.White, fontSize = 14.sp, maxLines = 1)+ }+ }+ }+ }+ }+}++/** The snapped shape's handles, while they show: blue dots ringed in white. */+@Composable+fun QuickShapeHandles(vm: CanvasViewModel) {+ val info = vm.quickShape ?: return+ if (!vm.quickShapeEditing) return+ androidx.compose.foundation.Canvas(Modifier.fillMaxSize()) {+ val h = info.handles+ for (i in 0 until h.size / 2) {+ val at = Offset(h[i * 2], h[i * 2 + 1])+ drawCircle(Color.White, 6.5.dp.toPx(), at)+ drawCircle(Pc.Accent, 5.dp.toPx(), at)+ }+ }+}+diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AlertUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AlertUi.ktnew file mode 100644index 0000000..feeae07--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AlertUi.kt@@ -0,0 +1,159 @@+package io.github.artcraftandroid.procraft.ui++import androidx.compose.animation.core.CubicBezierEasing+import androidx.compose.animation.core.animateFloatAsState+import androidx.compose.animation.core.tween+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.compose.ui.window.Popup+import androidx.compose.ui.window.PopupProperties++// buttons keep their width and the panel grows with them: 428 across for two, 632 for three+private val AlertButtonWidth = 192.dp+private val AlertButtonGap = 12.dp+private val AlertSide = 16.dp+// dark glass, or light with the light interface+private val AlertFill get() = if (Pc.light) Color(0xF2E3E3E3) else Color(0xF21E1E1E)+private val AlertInk get() = if (Pc.light) Color(0xFF222222) else Color(0xFFC5C5C5)+private val AlertCancelFill get() = if (Pc.light) Color(0xFFD9D9D9) else Color(0xFF2D2D2D)+private val AlertCancelInk get() = if (Pc.light) Color.Black else Color.White+private val AlertDestroyFill get() = if (Pc.light) Color(0xFFFD0100) else Color(0xFFFE2D2E)+private const val ALERT_DIM = 0.7f+private const val ALERT_START_SCALE = 1.1f++/**+ * An alert over everything while [value] is not null: the screen dims to 70% black as a dark glass+ * panel fades in, settling from a little larger (0.3 s); in it a title (after an [icon]), a+ * message, and [cancel] beside the action, red when it [destructive]ly destroys; an [extra] choice+ * (blue, as the action) can sit between them, the panel widening for it. It goes over 0.35 s.+ */+@Composable+fun <T : Any> Alert(+ value: T?,+ title: (T) -> String,+ message: (T) -> String,+ action: String,+ onCancel: () -> Unit,+ onAction: (T) -> Unit,+ icon: ImageVector? = null,+ destructive: Boolean = true,+ cancel: String = "Cancel",+ extra: String? = null,+ onExtra: (T) -> Unit = {},+ first: ((T) -> Unit)? = null,+) {+ val last = remember { arrayOfNulls<Any>(1) }+ if (value != null) last[0] = value+ val shown by animateFloatAsState(+ if (value != null) 1f else 0f,+ if (value != null) tween(300, easing = Motion.EaseInOut) else tween(350, easing = CubicBezierEasing(0f, 0f, 0.58f, 1f)),+ label = "alert",+ )+ @Suppress("UNCHECKED_CAST")+ val kept = last[0] as T? ?: return+ if (shown <= 0f) return+ Popup(+ alignment = Alignment.Center,+ onDismissRequest = { if (value != null) onCancel() },+ properties = PopupProperties(focusable = value != null, clippingEnabled = false),+ ) {+ Box(+ Modifier.fillMaxSize().background(Color.Black.copy(alpha = ALERT_DIM * shown))+ // nothing under it is touched while it is up+ .pointerInput(Unit) { awaitEachGesture { awaitFirstDown().consume() } },+ contentAlignment = Alignment.Center,+ ) {+ val buttons = if (extra != null) 3 else 2+ Column(+ Modifier.width(AlertButtonWidth * buttons + AlertButtonGap * (buttons - 1) + AlertSide * 2).graphicsLayer {+ alpha = shown+ val k = ALERT_START_SCALE + (1f - ALERT_START_SCALE) * shown+ scaleX = k+ scaleY = k+ }.clip(RoundedCornerShape(24.dp)).background(AlertFill).padding(start = AlertSide, end = AlertSide, top = 21.dp, bottom = 15.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ Row(Modifier.height(29.dp), verticalAlignment = Alignment.CenterVertically) {+ icon?.let {+ Icon(it, contentDescription = null, tint = Pc.Accent, modifier = Modifier.size(24.dp))+ Spacer(Modifier.width(8.dp))+ }+ Text(title(kept), color = AlertInk, fontSize = 22.sp, fontWeight = FontWeight.Bold, maxLines = 1)+ }+ Spacer(Modifier.height(13.dp))+ message(kept).takeIf { it.isNotEmpty() }?.let { Text(it, color = AlertInk, fontSize = 16.sp, lineHeight = 20.sp, textAlign = TextAlign.Center) }+ Spacer(Modifier.height(27.dp))+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(AlertButtonGap)) {+ // a first choice of three, blue too (a tap outside still cancels), or Cancel+ if (first != null) {+ AlertButton(cancel, Pc.Accent, Color.White, Modifier.weight(1f)) { if (value != null) first(kept) }+ } else {+ AlertButton(cancel, AlertCancelFill, AlertCancelInk, Modifier.weight(1f)) { if (value != null) onCancel() }+ }+ extra?.let { AlertButton(it, Pc.Accent, Color.White, Modifier.weight(1f)) { if (value != null) onExtra(kept) } }+ AlertButton(action, if (destructive) AlertDestroyFill else Pc.Accent, Color.White, Modifier.weight(1f)) { if (value != null) onAction(kept) }+ }+ }+ }+ }+}++@Composable+private fun AlertButton(label: String, fill: Color, ink: Color, modifier: Modifier, onClick: () -> Unit) {+ Box(modifier.height(48.dp).clip(CircleShape).background(fill).clickable(onClick = onClick), contentAlignment = Alignment.Center) {+ Text(label, color = ink, fontSize = 17.sp, fontWeight = FontWeight.Medium, maxLines = 1)+ }+}++/** How well a PDF keeps its pictures: JPEG at these qualities, or exactly. */+enum class PdfQuality(val label: String, val jpeg: Int) { GOOD("Good", 60), BETTER("Better", 85), BEST("Best", 100) }++/** Asks how well a PDF keeps its pictures while [open]: Good, Better or Best. */+@Composable+fun PdfQualityAlert(open: Boolean, onCancel: () -> Unit, onPick: (PdfQuality) -> Unit) {+ Alert(+ if (open) Unit else null,+ title = { "PDF quality" },+ message = { "" },+ action = PdfQuality.BEST.label,+ onCancel = onCancel,+ onAction = { onPick(PdfQuality.BEST) },+ icon = PcIcons.Page,+ destructive = false,+ cancel = PdfQuality.GOOD.label,+ extra = PdfQuality.BETTER.label,+ onExtra = { onPick(PdfQuality.BETTER) },+ first = { onPick(PdfQuality.GOOD) },+ )+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AnimatedExportUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AnimatedExportUi.ktnew file mode 100644index 0000000..27037b4--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AnimatedExportUi.kt@@ -0,0 +1,178 @@+package io.github.artcraftandroid.procraft.ui++import android.graphics.Bitmap+import androidx.activity.compose.BackHandler+import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++private val ScreenFill = Color(0xFF1F1F1F)+private val TitleInk = Color(0xFFAAAAAA)+private val RowInk = Color(0xFFC1C1C1)+private val PanelFill = Color(0xFF262626)+private val PanelEdge = Color(0xFF363636)+private val SegmentTrack = Color(0xFF3C3C3C)+private val CapsuleFill = Color(0xFF1A1A1A)+private val CapsuleEdge = Color(0xFF373737)+private val DoneBlue = Color(0xFF0190FF)++/**+ * Sharing the layers as an animation: the frames playing in a square, Export Settings (the size,+ * and per format dithering and a transparent background) in a panel on the left, Cancel, and+ * the round Done that exports and shares.+ */+@Composable+fun AnimatedExport(vm: CanvasViewModel, format: CanvasViewModel.Animated) {+ val context = LocalContext.current+ val scope = rememberCoroutineScope()+ var settingsOpen by remember { mutableStateOf(false) }+ var webReady by remember { mutableStateOf(false) }+ var dither by remember { mutableStateOf(true) }+ var transparent by remember { mutableStateOf(false) }+ var exporting by remember { mutableStateOf(false) }+ fun cancel() {+ if (settingsOpen) settingsOpen = false else vm.endAnimatedExport()+ }+ BackHandler { cancel() }+ BoxWithConstraints(Modifier.fillMaxSize().background(ScreenFill).pointerInput(Unit) { detectTapGestures { } }) {+ val box = maxWidth - 48.dp+ val side = with(LocalDensity.current) { box.roundToPx() }+ // the frames, fitted to the square, played over and over+ var frames by remember { mutableStateOf<List<Bitmap>>(emptyList()) }+ var shown by remember { mutableIntStateOf(0) }+ val canTransparent = format == CanvasViewModel.Animated.GIF || format == CanvasViewModel.Animated.PNG+ LaunchedEffect(transparent && canTransparent, side) {+ val loaded = withContext(Dispatchers.IO) { List(vm.animationFrameCount()) { vm.animationFrame(it, side, transparent && canTransparent) }.filterNotNull() }+ frames = loaded+ shown = 0+ }+ LaunchedEffect(frames) {+ while (frames.size > 1) {+ delay(1000L / CanvasViewModel.ANIMATION_FPS)+ shown = (shown + 1) % frames.size+ }+ }+ Box(Modifier.offset(x = 24.dp, y = 96.dp).size(box), contentAlignment = Alignment.Center) {+ frames.getOrNull(shown)?.let { Image(it.asImageBitmap(), contentDescription = "Preview", contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize()) }+ }+ // the header: Export Settings on the left, Cancel and Done on the right+ Row(Modifier.offset(x = 14.dp, y = 20.dp).height(44.dp).clickable { settingsOpen = !settingsOpen }.padding(end = 12.dp), verticalAlignment = Alignment.CenterVertically) {+ Box(Modifier.width(60.dp), contentAlignment = Alignment.Center) {+ Icon(PcIcons.ChevronLeft, contentDescription = null, tint = TitleInk, modifier = Modifier.size(28.dp))+ }+ Text("Export Settings", color = TitleInk, fontSize = 24.sp, fontWeight = FontWeight.Bold, maxLines = 1)+ }+ Row(Modifier.align(Alignment.TopEnd).padding(top = 16.dp, end = 16.dp), verticalAlignment = Alignment.CenterVertically) {+ Box(+ Modifier.height(43.dp).clip(CircleShape).background(CapsuleFill).border(1.dp, CapsuleEdge, CircleShape).clickable { cancel() }.padding(horizontal = 13.dp),+ contentAlignment = Alignment.Center,+ ) {+ Text("Cancel", color = Color(0xFFA5A5A5), fontSize = 17.sp)+ }+ Spacer(Modifier.width(13.dp))+ Box(+ Modifier.size(44.dp, 45.dp).clip(CircleShape).background(DoneBlue).clickable(enabled = !exporting) {+ exporting = true+ scope.launch {+ val file = vm.exportAnimation(format, webReady, dither, transparent)+ exporting = false+ if (file != null) {+ vm.endAnimatedExport()+ shareFile(context, file, format.mime)+ } else {+ vm.message = "The animation could not be exported."+ }+ }+ },+ contentAlignment = Alignment.Center,+ ) {+ if (exporting) CircularProgressIndicator(color = Color.White, strokeWidth = 2.dp, modifier = Modifier.size(24.dp))+ else Icon(PcIcons.DoneTick, contentDescription = "Export", tint = Color.White, modifier = Modifier.requiredSize(40.dp))+ }+ }+ if (settingsOpen) {+ // a tap outside the panel closes it+ Box(Modifier.fillMaxSize().pointerInput(Unit) { detectTapGestures { settingsOpen = false } })+ Column(+ Modifier.padding(10.dp).width(400.dp).fillMaxHeight().clip(RoundedCornerShape(20.dp)).background(PanelFill).border(1.dp, PanelEdge, RoundedCornerShape(20.dp))+ .pointerInput(Unit) { detectTapGestures { } },+ ) {+ Text(format.title, color = TitleInk, fontSize = 24.sp, fontWeight = FontWeight.Bold, maxLines = 1, modifier = Modifier.padding(start = 24.dp, top = 15.dp).height(36.dp))+ Spacer(Modifier.height(8.dp))+ Segments(listOf("Max Resolution", "Web Ready"), if (webReady) 1 else 0) { webReady = it == 1 }+ Spacer(Modifier.height(15.dp))+ if (format == CanvasViewModel.Animated.GIF) SettingRow("Dithering", dither) { dither = it }+ if (canTransparent) SettingRow("Transparent background", transparent) { transparent = it }+ }+ }+ }+}++/** Two or more choices side by side in a grey track, the chosen one blue. */+@Composable+private fun Segments(labels: List<String>, chosen: Int, onChoose: (Int) -> Unit) {+ Row(Modifier.padding(start = 9.dp).width(382.dp).height(33.dp).clip(CircleShape).background(SegmentTrack).padding(1.5.dp)) {+ labels.forEachIndexed { i, label ->+ Box(+ Modifier.weight(1f).fillMaxHeight().clip(CircleShape).background(if (i == chosen) Pc.Accent else Color.Transparent).clickable { onChoose(i) },+ contentAlignment = Alignment.Center,+ ) {+ Text(label, color = if (i == chosen) Color.White else RowInk, fontSize = 15.sp, maxLines = 1)+ }+ }+ }+}++/** A setting's name and its switch, 52 tall. */+@Composable+private fun SettingRow(label: String, on: Boolean, onChange: (Boolean) -> Unit) {+ Row(Modifier.height(52.dp).clickable { onChange(!on) }.padding(start = 16.dp, end = 4.dp), verticalAlignment = Alignment.CenterVertically) {+ Text(label, color = RowInk, fontSize = 17.sp, maxLines = 1, modifier = Modifier.width(307.dp))+ Switch(on, enabled = true)+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AnimationUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AnimationUi.ktnew file mode 100644index 0000000..c5845b0--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AnimationUi.kt@@ -0,0 +1,272 @@+package io.github.artcraftandroid.procraft.ui++import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.detectHorizontalDragGestures+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxScope+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ColumnScope+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.drawBehind+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.RoundRect+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.layout.positionInParent+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import io.github.artcraftandroid.procraft.core.AnimationPlayback+import kotlin.math.roundToInt++private val BarWidth = 446.dp+private val BarHeight = 96.dp+private val BarGap = 25.dp+private val FrameWidth = 27.dp+private val FramePitch = 28.dp+private val BarFill get() = if (Pc.light) Color(0xFFE4E4E4) else Color(0xFF2A2A2A)+private val TrackFill get() = if (Pc.light) Color(0xFFD0D0D0) else Color(0xFF474747)+private val TrackEdge get() = if (Pc.light) Color(0xFFBDBDBD) else Color(0xFF5C5C5C)+private val BarInk get() = if (Pc.light) Color(0xFF393939) else Color(0xFFC5C5C5)+private const val MAX_ONION = 12++/**+ * Animation Assist's bar at the bottom: Play, Settings and Add Frame over the timeline of frames,+ * the current one in the middle; with its settings or the current frame's options above it.+ */+@Composable+fun BoxScope.AnimationBar(vm: CanvasViewModel) {+ if (vm.animation == null) return+ Box(Modifier.align(Alignment.BottomCenter).fillMaxWidth()) {+ // where Settings' middle is along the bar, for the arrow of its popover+ var settingsAt by remember { mutableStateOf(281.5.dp) }+ val density = LocalDensity.current+ Column(Modifier.align(Alignment.BottomCenter)) {+ if (vm.animationSettingsOpen) {+ DownPopover(290.dp, 145.dp, Modifier.offset(x = (settingsAt - 145.dp).coerceIn(0.dp, BarWidth - 290.dp))) { AnimationSettingsPage(vm) }+ } else if (vm.frameOptionsOpen) {+ DownPopover(268.dp, 134.dp, Modifier.offset(x = BarWidth / 2 - 134.dp)) { FrameOptionsPage(vm) }+ }+ Box(Modifier.padding(bottom = BarGap).size(BarWidth, BarHeight).clip(RoundedCornerShape(30.dp)).background(BarFill)) {+ val pages = vm.animation?.pages == true+ Row(Modifier.fillMaxWidth().padding(start = 26.dp, end = 26.dp, top = 8.dp).height(30.dp), verticalAlignment = Alignment.CenterVertically) {+ Text(+ if (pages) "Page Assist" else if (vm.playingFrame != null) "Pause" else "Play", color = BarInk, fontSize = 17.sp, fontWeight = FontWeight.Bold,+ modifier = if (pages) Modifier else Modifier.clickable { vm.togglePlaying() },+ )+ Spacer(Modifier.weight(1f))+ if (!pages) BarText(+ "Settings",+ Modifier.onGloballyPositioned { c -> settingsAt = with(density) { (c.positionInParent().x + c.size.width / 2f).toDp() } },+ ) {+ vm.animationSettingsOpen = !vm.animationSettingsOpen+ vm.frameOptionsOpen = false+ }+ Spacer(Modifier.width(23.dp))+ BarText(if (pages) "New Page" else "Add Frame", Modifier) { vm.addFrame() }+ }+ Timeline(vm, Modifier.offset(x = 12.dp, y = 42.dp))+ }+ }+ }+}++@Composable+private fun BarText(label: String, modifier: Modifier, onClick: () -> Unit) {+ Box(modifier.height(30.dp).clickable(onClick = onClick), contentAlignment = Alignment.Center) {+ Text(label, color = BarInk, fontSize = 17.sp, maxLines = 1)+ }+}++/** The frames in a rounded track, the current (or played) one in the middle with a blue line under it. */+@Composable+private fun Timeline(vm: CanvasViewModel, modifier: Modifier) {+ val frames = vm.animationFrames+ val focus = vm.playingFrame ?: vm.currentFrame ?: 0+ val width = 422.dp+ Box(modifier.size(width, 44.dp).clip(RoundedCornerShape(18.dp)).background(TrackFill).border(1.dp, TrackEdge, RoundedCornerShape(18.dp))) {+ frames.forEachIndexed { i, id ->+ val x = width / 2 - FrameWidth / 2 + FramePitch * (i - focus)+ if (x > -FrameWidth && x < width) {+ Box(+ Modifier.offset(x = x, y = 2.dp).size(FrameWidth, 40.dp).clip(RoundedCornerShape(6.dp)).background(Color.White)+ .border(1.dp, Color(0xFF9A9A9A), RoundedCornerShape(6.dp)).clickable { vm.tapFrame(i) },+ ) {+ vm.frameThumbnails[id]?.let { Image(it, contentDescription = "Frame ${i + 1}", contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize().padding(2.dp)) }+ }+ }+ }+ }+ Box(Modifier.offset(x = 12.dp + width / 2 - 12.dp, y = 42.dp + 44.dp + 3.dp).size(24.dp, 3.dp).clip(RoundedCornerShape(1.5.dp)).background(Pc.Accent))+}++/** A panel standing on the bar, its arrow pointing down at [arrowX] from its left edge. */+@Composable+private fun DownPopover(width: Dp, arrowX: Dp, modifier: Modifier, content: @Composable ColumnScope.() -> Unit) {+ val fill = Pc.PopoverFill+ Box(+ modifier.width(width).padding(bottom = 2.dp).drawBehind {+ val arrowH = Pc.ArrowHeight.toPx()+ val tipX = arrowX.toPx()+ val outline = Path().apply {+ addRoundRect(RoundRect(0f, 0f, size.width, size.height - arrowH, CornerRadius(24.dp.toPx())))+ moveTo(tipX - arrowH, size.height - arrowH - 0.5f)+ lineTo(tipX, size.height)+ lineTo(tipX + arrowH, size.height - arrowH - 0.5f)+ close()+ }+ drawPath(outline, fill)+ }.pointerInput(Unit) { detectTapGestures { } },+ ) {+ Column(Modifier.padding(start = 8.dp, end = 8.dp, top = 8.dp, bottom = Pc.ArrowHeight + 8.dp), content = content)+ }+}++/** Animation Assist's settings: playback, frames a second, onion skins, the primary frame. */+@Composable+private fun ColumnScope.AnimationSettingsPage(vm: CanvasViewModel) {+ val a = vm.animation ?: return+ Text("Settings", color = Pc.PanelTitle, fontSize = 22.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 14.dp, top = 2.dp, bottom = 12.dp))+ Group {+ for ((mode, label) in listOf(AnimationPlayback.LOOP to "Loop", AnimationPlayback.PING_PONG to "Ping-Pong", AnimationPlayback.ONE_SHOT to "One Shot")) {+ val chosen = a.playback == mode+ Row(+ Modifier.fillMaxWidth().height(40.dp).background(if (chosen) Pc.Accent else Color.Transparent).clickable { vm.changeAnimation { it.copy(playback = mode) } }.padding(horizontal = 16.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(label, color = if (chosen) Color.White else Pc.PanelTitle, fontSize = 17.sp, modifier = Modifier.weight(1f))+ if (chosen) Icon(PcIcons.MenuTick, contentDescription = null, tint = Color.White, modifier = Modifier.size(22.dp))+ }+ }+ }+ Spacer(Modifier.height(10.dp))+ Group {+ ValueSlider("Frames Per Second", "${a.fps}", (a.fps.toFloat() - 1f) / 59f) { v -> vm.changeAnimation { it.copy(fps = (1 + (v * 59f).roundToInt()).toUInt()) } }+ val onion = a.onionFrames.toInt()+ ValueSlider("Onion skin frames", when (onion) { 0 -> "None"; MAX_ONION -> "Max"; else -> "$onion" }, onion / MAX_ONION.toFloat()) { v ->+ vm.changeAnimation { it.copy(onionFrames = (v * MAX_ONION).roundToInt().toUInt()) }+ }+ ValueSlider("Onion skin opacity", "${(a.onionOpacity * 100).roundToInt()} %", a.onionOpacity) { v -> vm.changeAnimation { it.copy(onionOpacity = v) } }+ }+ Spacer(Modifier.height(10.dp))+ Group {+ Row(Modifier.fillMaxWidth().height(45.dp).clickable { vm.changeAnimation { it.copy(blendPrimary = !it.blendPrimary) } }.padding(start = 16.dp, end = 6.dp), verticalAlignment = Alignment.CenterVertically) {+ Text("Blend primary frame", color = Pc.PanelTitle, fontSize = 17.sp, modifier = Modifier.weight(1f))+ Switch(a.blendPrimary, enabled = true)+ }+ Box(Modifier.fillMaxWidth().height(1.dp).background(Pc.ActionsSeparator))+ Box(Modifier.fillMaxWidth().height(45.dp).padding(start = 16.dp), contentAlignment = Alignment.CenterStart) {+ Text("Onion skin colors", color = Pc.ActionsDisabled, fontSize = 17.sp)+ }+ }+}++/** The current frame's options: how long it is held, Duplicate, Delete, and Background or Foreground. */+@Composable+private fun ColumnScope.FrameOptionsPage(vm: CanvasViewModel) {+ val a = vm.animation ?: return+ val index = vm.currentFrame ?: return+ val last = vm.animationFrames.size - 1+ // re-read when the hold changes+ val hold = vm.holdVersion.let { vm.frameHold() }+ Text(if (a.pages) "Page options" else "Frame options", color = Pc.PanelTitle, fontSize = 22.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 14.dp, top = 2.dp, bottom = 12.dp))+ if (!a.pages) {+ Group {+ ValueSlider("Hold duration", if (hold == 0) "None" else "$hold", hold / CanvasViewModel.MAX_HOLD.toFloat()) { v ->+ vm.changeFrameHold((v * CanvasViewModel.MAX_HOLD).roundToInt())+ }+ }+ Spacer(Modifier.height(10.dp))+ }+ Group {+ Row(Modifier.fillMaxWidth().height(45.dp).clickable { vm.duplicateFrame() }.padding(start = 16.dp), verticalAlignment = Alignment.CenterVertically) {+ Text("Duplicate", color = Pc.PanelTitle, fontSize = 17.sp)+ }+ Box(Modifier.fillMaxWidth().height(1.dp).background(Pc.ActionsSeparator))+ Row(Modifier.fillMaxWidth().height(45.dp).clickable { vm.deleteFrame() }.padding(start = 16.dp), verticalAlignment = Alignment.CenterVertically) {+ Text("Delete", color = Pc.PanelTitle, fontSize = 17.sp)+ }+ }+ if (!a.pages && (index == 0 || (index == last && last > 0))) {+ Spacer(Modifier.height(10.dp))+ val background = index == 0+ val on = if (background) a.background else a.foreground+ Group {+ Row(+ Modifier.fillMaxWidth().height(45.dp).clickable { vm.changeAnimation { if (background) it.copy(background = !on) else it.copy(foreground = !on) } }.padding(start = 16.dp, end = 6.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(if (background) "Background" else "Foreground", color = Pc.PanelTitle, fontSize = 17.sp, modifier = Modifier.weight(1f))+ Switch(on, enabled = true)+ }+ }+ }+}++@Composable+private fun Group(content: @Composable ColumnScope.() -> Unit) {+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(18.dp)).background(Pc.ActionsGroup), content = content)+}++/** A setting's name and value over a bar dragged or tapped along. */+@Composable+private fun ValueSlider(label: String, value: String, fraction: Float, onChange: (Float) -> Unit) {+ val change by rememberUpdatedState(onChange)+ Column(Modifier.fillMaxWidth().height(62.dp).padding(horizontal = 16.dp)) {+ Row(Modifier.fillMaxWidth().padding(top = 12.dp)) {+ Text(label, color = Pc.SlideLabel, fontSize = 17.sp, modifier = Modifier.weight(1f), maxLines = 1)+ Text(value, color = Pc.SlideValue, fontSize = 17.sp, maxLines = 1)+ }+ Box(+ Modifier.fillMaxWidth().height(22.dp)+ .pointerInput(Unit) { detectTapGestures { change((it.x / size.width).coerceIn(0f, 1f)) } }+ .pointerInput(Unit) {+ detectHorizontalDragGestures(onDragStart = { change((it.x / size.width).coerceIn(0f, 1f)) }) { c, _ ->+ c.consume()+ change((c.position.x / size.width).coerceIn(0f, 1f))+ }+ }+ .drawBehind {+ val y = size.height / 2f+ val h = 3.dp.toPx()+ val x = fraction.coerceIn(0f, 1f) * size.width+ drawRect(Pc.SlideTrack, Offset(0f, y - h / 2f), Size(size.width, h))+ drawRect(Pc.Accent, Offset(0f, y - h / 2f), Size(x, h))+ val knob = Size(16.dp.toPx(), 10.dp.toPx())+ drawRoundRect(Color.White, Offset((x - knob.width / 2f).coerceIn(0f, size.width - knob.width), y - knob.height / 2f), knob, CornerRadius(knob.height / 2f))+ },+ )+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AppRoot.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AppRoot.ktnew file mode 100644index 0000000..40863f4--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AppRoot.kt@@ -0,0 +1,356 @@+package io.github.artcraftandroid.procraft.ui++import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.activity.compose.BackHandler+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.Text+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.clipToBounds+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.getValue+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.ui.viewinterop.AndroidView+import io.github.artcraftandroid.procraft.canvas.Adjustment+import io.github.artcraftandroid.procraft.canvas.CanvasSurfaceView+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import io.github.artcraftandroid.procraft.canvas.Panel+import io.github.artcraftandroid.procraft.canvas.Screen+import io.github.artcraftandroid.procraft.canvas.SelectionPopup+import io.github.artcraftandroid.procraft.canvas.TransformPopup+import io.github.artcraftandroid.procraft.core.LayerInfo+import io.github.artcraftandroid.procraft.core.ToolKind++/** The canvas screen: the canvas, the bars over it, and the panel that is open. */+@Composable+fun AppRoot(vm: CanvasViewModel) {+ ProCraftTheme {+ if (vm.screen == Screen.GALLERY) {+ ZoomingGallery(vm, overlay = false)+ return@ProCraftTheme+ }+ // back closes an open panel first, then leaves the artwork for the gallery+ BackHandler {+ when {+ vm.guideEditing -> vm.closeGuideEditor(keep = false)+ vm.studioOpen -> vm.closeStudio(keep = false)+ vm.transformPopup != TransformPopup.NONE -> vm.transformPopup = TransformPopup.NONE+ vm.selectionPopup != SelectionPopup.NONE -> vm.selectionPopup = SelectionPopup.NONE+ vm.selecting -> vm.closeSelecting()+ vm.adjustment != null -> vm.endAdjustment(true)+ vm.transforming -> vm.endTransform(true)+ vm.panel != Panel.NONE -> vm.closePanels()+ else -> vm.closeArtwork()+ }+ }+ // panels over the canvas are frosted+ CompositionLocalProvider(LocalBackdrops provides vm.backdrops) {+ BoxWithConstraints(Modifier.fillMaxSize().background(Pc.Surround)) {+ AndroidView(factory = { CanvasSurfaceView(it, vm) }, modifier = Modifier.fillMaxSize())+ if (vm.transforming) TransformOverlay(vm)+ if (vm.selecting) SelectionOverlay(vm, Pc.BarHeight)+ if (vm.panel != Panel.NONE) {+ // a tap outside an open panel closes it (and does not paint)+ Box(Modifier.fillMaxSize().pointerInput(Unit) { detectTapGestures { vm.closePanels() } })+ }+ vm.picking?.let { pick ->+ Loupe(pick, CanvasSpace.color(vm.colorRgb()))+ if (!vm.barsHidden) PickingBar(Modifier.offset(y = Pc.BarHeight))+ }+ // the bars fade out as the interface hides, and back+ val barsShown = androidx.compose.animation.core.animateFloatAsState(if (vm.barsHidden) 0f else 1f, Motion.bars(), label = "bars").value+ // with the interface hidden, a button in the top left brings it back+ if (barsShown < 1f) {+ Box(+ Modifier.offset(x = 20.dp).size(44.dp).graphicsLayer { alpha = 1f - barsShown }+ .pointerInput(Unit) { detectTapGestures { if (vm.barsHidden) vm.toggleBars() } },+ contentAlignment = Alignment.Center,+ ) {+ // its glyph is drawn wider than it is tall: 50 units shown 36.7 by 32+ androidx.compose.foundation.Image(+ androidx.compose.ui.graphics.vector.rememberVectorPainter(PcIcons.FullScreen),+ contentDescription = "Show the interface",+ contentScale = androidx.compose.ui.layout.ContentScale.FillBounds,+ colorFilter = androidx.compose.ui.graphics.ColorFilter.tint(Pc.SideGlyph),+ modifier = Modifier.offset(y = 0.3.dp).requiredSize(36.7.dp, 32.dp),+ )+ }+ }+ // a slider's panel kept up goes with the next touch anywhere else+ if (vm.sliderPanelKept && vm.sliderPanel != null) {+ Box(+ Modifier.fillMaxSize().pointerInput(Unit) {+ awaitEachGesture {+ awaitFirstDown().consume()+ vm.sliderPanel = null+ vm.sliderPanelKept = false+ }+ },+ )+ }+ if (barsShown > 0f) {+ // the top bar slides up off the screen and the side bar out to its side as they fade+ val fade = Modifier.graphicsLayer { alpha = barsShown }+ val up = Modifier.graphicsLayer { translationY = -size.height * (1f - barsShown) }+ val aside = Modifier.graphicsLayer { translationX = size.width * (1f - barsShown) * if (vm.rightHanded) 1f else -1f }+ TopBar(vm, Modifier.align(Alignment.TopCenter).then(up).then(fade))+ // a mode taking the screen slides it off its edge, and back when it ends+ androidx.compose.animation.AnimatedVisibility(+ vm.showSideBar && !vm.transforming && !vm.selecting && !vm.guideEditing && vm.cropRect == null && (vm.adjustment == null || vm.adjustPencil),+ Modifier.align(if (vm.rightHanded) Alignment.TopEnd else Alignment.TopStart).offset(y = maxHeight * Pc.SIDE_BAR_CENTRE - Pc.SideBarHeight / 2),+ enter = Motion.sideBarIn(vm.rightHanded),+ exit = Motion.sideBarOut(vm.rightHanded),+ ) {+ SideBar(vm, aside.then(fade), right = vm.rightHanded)+ }+ }+ NoticeBand(vm)+ // each panel hangs from its button: colour, layers, then the tool that opened the library;+ // it grows out of its arrow as it opens and fades as it closes+ PanelPresence(vm.panel, Panel.NONE, fading = vm.panelFading, onFaded = { vm.panelFading = false }) { shown, alpha, scale, origin ->+ val (width, button) = when (shown) {+ Panel.LAYERS -> (if (vm.backgroundPicking) 376.dp else 384.dp) to 1+ Panel.COLOR -> 376.dp to 0+ Panel.BRUSHES -> 440.dp to when (vm.tool) {+ ToolKind.ERASE -> 2+ ToolKind.SMUDGE -> 3+ else -> 4+ }+ Panel.ACTIONS -> 390.dp to 0+ Panel.ADJUSTMENTS -> 330.dp to 1+ Panel.NONE -> 0.dp to 0+ }+ val fromLeft = shown == Panel.ACTIONS || shown == Panel.ADJUSTMENTS+ val buttonX = if (fromLeft) Pc.actionCentre(button, maxWidth) else maxWidth - Pc.toolCentreFromRight(button, maxWidth)+ // panels keep clear of the side bar, on whichever side it is+ val clear = if (vm.showSideBar) Pc.SideBarWidth + Pc.PopoverGap else Pc.PopoverGap+ val place = if (vm.rightHanded) popoverPlace(width, buttonX, maxWidth, minRight = clear) else popoverPlace(width, buttonX, maxWidth, clear)+ val pivot = with(androidx.compose.ui.platform.LocalDensity.current) {+ origin + androidx.compose.ui.geometry.Offset((place.left + place.arrowX).toPx(), Pc.BarHeight.toPx())+ }+ val at = Modifier.offset(x = place.left, y = Pc.BarHeight).graphicsLayer {+ this.alpha = alpha+ scaleX = scale+ scaleY = scale+ transformOrigin = androidx.compose.ui.graphics.TransformOrigin(place.arrowX / width, 0f)+ }+ ProvidePanelLook(PanelLook(alpha, scale, pivot)) {+ when (shown) {+ Panel.LAYERS -> if (vm.backgroundPicking) {+ ColorPanel(vm, place.arrowX, maxHeight, at, background = true)+ // closed any way at all, the colour is kept+ androidx.compose.runtime.DisposableEffect(Unit) { onDispose { vm.endBackgroundPick() } }+ } else {+ LayersPanel(vm, place.arrowX, at.heightIn(max = maxHeight - Pc.BarHeight - Pc.PopoverGap))+ }+ Panel.COLOR -> ColorPanel(vm, place.arrowX, maxHeight, at)+ Panel.BRUSHES -> BrushLibrary(vm, place.arrowX, at.height(maxHeight - Pc.BarHeight - 25.dp))+ Panel.ACTIONS -> ActionsPanel(vm, place.arrowX, at)+ Panel.ADJUSTMENTS -> AdjustmentsPanel(vm, place.arrowX, at.heightIn(max = maxHeight - Pc.BarHeight - Pc.PopoverGap))+ Panel.NONE -> Unit+ }+ }+ }+ // the bottom toolbars rise from below the screen, and drop away+ androidx.compose.animation.AnimatedVisibility(+ vm.transforming && !vm.barsHidden,+ Modifier.align(Alignment.BottomCenter),+ enter = Motion.toolbarIn(),+ exit = Motion.toolbarOut(),+ ) { TransformToolbar(vm, maxWidth) }+ if (vm.transforming && !vm.barsHidden) {+ TransformPopover(vm, maxWidth, maxHeight)+ TransformNumeric(vm)+ }+ BrushCursor(vm)+ ReferenceWindow(vm)+ TouchCompanion(vm)+ CropOverlay(vm)+ if (vm.textInfo != null) TextEditor(vm)+ RasterizePrompt(vm)+ vm.animatedExport?.let { AnimatedExport(vm, it) }+ // full-screen pages slide up over everything, and back down+ androidx.compose.animation.AnimatedVisibility(+ vm.canvasInfoOpen,+ enter = androidx.compose.animation.slideInVertically(Motion.studioIn()) { it },+ exit = androidx.compose.animation.slideOutVertically(Motion.studioOut()) { it },+ ) { Box(Modifier.fillMaxSize()) { CanvasInfo(vm) } }+ androidx.compose.animation.AnimatedVisibility(+ vm.gestureControlsOpen,+ enter = androidx.compose.animation.slideInVertically(Motion.studioIn()) { it },+ exit = androidx.compose.animation.slideOutVertically(Motion.studioOut()) { it },+ ) { Box(Modifier.fillMaxSize()) { GestureControls(vm) } }+ BlockedDialog(vm)+ // a passing message goes in the band under the top bar, as what undo and redo did+ vm.message?.let { text ->+ androidx.compose.runtime.LaunchedEffect(text) {+ vm.showNotice(text)+ vm.message = null+ }+ }+ androidx.compose.animation.AnimatedVisibility(+ vm.timeLapseReplaying,+ Modifier.matchParentSize(),+ enter = androidx.compose.animation.fadeIn(Motion.replayFade()),+ exit = androidx.compose.animation.fadeOut(Motion.replayFade()),+ ) { TimeLapseReplay(vm) }+ // the gallery zooming into the artwork as it opens, over everything+ ZoomingGallery(vm, overlay = true)+ GuideOverlay(vm)+ if (vm.adjustment == Adjustment.CLONE) ClonePuck(vm)+ QuickShapeHandles(vm)+ if (!vm.barsHidden) AnimationBar(vm)+ CopyPastePanel(vm)+ QuickMenu(vm)+ LayerChoice(vm)+ if (!vm.barsHidden) QuickShapeBar(vm, Modifier.offset(y = Pc.BarHeight))+ if (vm.adjustment != null && !vm.barsHidden) {+ AdjustmentBar(vm, Modifier.offset(y = Pc.BarHeight))+ AdjustModes(vm, Modifier.align(Alignment.TopCenter).offset(y = Pc.BarHeight + 52.dp))+ AdjustmentMenu(vm)+ }+ // the adjustment's own panel rises from below the screen, and drops away+ val bottomPanel = vm.adjustment?.takeIf { !vm.barsHidden && it in BottomPanels }+ val shownPanel = androidx.compose.runtime.remember { arrayOfNulls<Adjustment>(1) }+ if (bottomPanel != null) shownPanel[0] = bottomPanel+ androidx.compose.animation.AnimatedVisibility(+ bottomPanel != null,+ Modifier.align(Alignment.BottomCenter),+ enter = Motion.toolbarIn(),+ exit = Motion.toolbarOut(),+ ) {+ shownPanel[0]?.let {+ when (it) {+ Adjustment.HSB -> HsbPanel(vm, Modifier)+ Adjustment.COLOR_BALANCE -> ColorBalancePanel(vm, Modifier)+ Adjustment.CURVES -> CurvesPanel(vm, Modifier)+ Adjustment.GRADIENT_MAP -> GradientMapPanel(vm, Modifier)+ Adjustment.GLITCH -> GlitchPanel(vm, Modifier)+ Adjustment.NOISE -> NoisePanel(vm, Modifier)+ Adjustment.BLOOM -> BloomPanel(vm, Modifier)+ Adjustment.HALFTONE -> HalftonePanel(vm, Modifier)+ Adjustment.CHROMATIC_ABERRATION -> ChromaticPanel(vm, Modifier)+ Adjustment.LIQUIFY -> LiquifyPanel(vm, maxWidth, maxHeight, Modifier)+ else -> Unit+ }+ }+ }+ androidx.compose.animation.AnimatedVisibility(+ vm.selecting && !vm.barsHidden,+ Modifier.align(Alignment.BottomCenter),+ enter = Motion.toolbarIn(),+ exit = Motion.toolbarOut(),+ ) { SelectionToolbar(vm, maxWidth) }+ if (vm.selecting && !vm.barsHidden) {+ SelectionPopover(vm, maxWidth, maxHeight)+ }+ GuideEditor(vm)+ BrushStudio(vm)+ PadMenu(vm)+ }+ }+ }+}++/**+ * The current layer turned a change away (locked, hidden, or an empty group): Cancel, unlock or+ * show it, or open Layers. What was tried is not done afterwards.+ */+@Composable+private fun BlockedDialog(vm: CanvasViewModel) {+ val last = androidx.compose.runtime.remember { arrayOfNulls<Pair<CanvasViewModel.Blocked, LayerInfo>>(1) }+ vm.blocked?.let { last[0] = it }+ val why = last[0]?.first+ Alert(+ vm.blocked,+ title = { (w, _) ->+ when (w) {+ CanvasViewModel.Blocked.LOCKED -> "Layer is locked"+ CanvasViewModel.Blocked.HIDDEN -> "Layer is hidden"+ CanvasViewModel.Blocked.EMPTY_GROUP -> "Group is empty"+ }+ },+ message = { (w, l) ->+ when (w) {+ CanvasViewModel.Blocked.LOCKED -> "“${l.name}” can't be changed while it is locked."+ CanvasViewModel.Blocked.HIDDEN -> "“${l.name}” can't be changed while it is hidden."+ CanvasViewModel.Blocked.EMPTY_GROUP -> "“${l.name}” holds no layers to change."+ }+ },+ action = "Open Layers",+ onCancel = { vm.answerBlocked(fix = false, openLayers = false) },+ onAction = { vm.answerBlocked(fix = false, openLayers = true) },+ icon = when (why) {+ CanvasViewModel.Blocked.LOCKED -> PcIcons.PageLocked+ CanvasViewModel.Blocked.HIDDEN -> PcIcons.EyeStruck+ else -> PcIcons.Folder+ },+ destructive = false,+ extra = when (why) {+ CanvasViewModel.Blocked.LOCKED -> "Unlock"+ CanvasViewModel.Blocked.HIDDEN -> "Show"+ else -> null+ },+ onExtra = { vm.answerBlocked(fix = true, openLayers = false) },+ )+}++/** The adjustments whose controls are a panel at the bottom of the screen. */+private val BottomPanels = setOf(+ Adjustment.HSB, Adjustment.COLOR_BALANCE, Adjustment.CURVES, Adjustment.GRADIENT_MAP, Adjustment.GLITCH, Adjustment.NOISE,+ Adjustment.BLOOM, Adjustment.HALFTONE, Adjustment.CHROMATIC_ABERRATION, Adjustment.LIQUIFY,+)++/**+ * What undo or redo did (and other passing messages), in a band across the screen just under the+ * top bar: it slides down from behind the bar, stays a moment and slides back up. A new message+ * takes the place of the one there: down, its text changes in place; moving, the band goes on+ * down from where it is. Either way it stays its full time from the new message.+ */+@Composable+private fun NoticeBand(vm: CanvasViewModel) {+ val shown = androidx.compose.runtime.remember { androidx.compose.animation.core.Animatable(0f) }+ var text by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf("") }+ val n = vm.notice+ androidx.compose.runtime.LaunchedEffect(n) {+ if (n == null) return@LaunchedEffect+ text = n.text+ val start = System.nanoTime()+ if (shown.value < 1f) shown.animateTo(1f, Motion.noticeIn())+ val shownFor = if (n.warning) Motion.NOTICE_WARNING_SHOWN_MS else Motion.NOTICE_SHOWN_MS+ kotlinx.coroutines.delay((shownFor - (System.nanoTime() - start) / 1_000_000).coerceAtLeast(0L))+ shown.animateTo(0f, Motion.noticeOut())+ vm.noticeGone(n)+ }+ if (shown.value <= 0f && n == null) return+ Box(Modifier.offset(y = Pc.BarHeight).fillMaxWidth().height(24.dp).clipToBounds()) {+ Box(+ Modifier.fillMaxSize().graphicsLayer { translationY = -(1f - shown.value) * size.height }.background(NoticeFill),+ contentAlignment = Alignment.Center,+ ) {+ Text(text, color = NoticeInk, fontSize = 13.sp, maxLines = 1)+ }+ }+}++private val NoticeFill = Color(0xC2424242)+private val NoticeInk = Color(0xFFD7D7D7)diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/BrushLibrary.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/BrushLibrary.ktnew file mode 100644index 0000000..afc7d6e--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/BrushLibrary.kt@@ -0,0 +1,647 @@+package io.github.artcraftandroid.procraft.ui++import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.lazy.grid.GridCells+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid+import androidx.compose.foundation.lazy.grid.items+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.animation.core.Animatable+import androidx.compose.foundation.Canvas+import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress+import androidx.compose.foundation.gestures.detectHorizontalDragGestures+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ColumnScope+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.WindowInsets+import androidx.compose.foundation.layout.isImeVisible+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.itemsIndexed+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.AlertDialog+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateMapOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.alpha+import androidx.compose.ui.draw.clipToBounds+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.focus.onFocusChanged+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.input.nestedscroll.NestedScrollConnection+import androidx.compose.ui.input.nestedscroll.NestedScrollSource+import androidx.compose.ui.input.nestedscroll.nestedScroll+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.layout.layout+import androidx.compose.ui.layout.boundsInWindow+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.layout.onSizeChanged+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.IntRect+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.LayoutDirection+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.compose.ui.window.Popup+import androidx.compose.ui.window.PopupPositionProvider+import androidx.compose.ui.window.PopupProperties+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import io.github.artcraftandroid.procraft.core.BrushInfo+import io.github.artcraftandroid.procraft.core.ToolKind+import kotlinx.coroutines.launch+import kotlin.math.roundToInt++private val LibraryWidth = 440.dp+private val SetsWidth = 168.dp+private val BrushHeight = 80.dp+private val BrushGap = 8.dp+/** The library's menus: dark glass with a light edge, rows 40 high. */+private val LibraryMenuWidth = 253.dp+private val MenuFill = Color(0xFA303335)+private val MenuEdge = Color(0xFF5A5D5F)+private val MenuRule = Color(0xFF3F4347)+private val MenuRed = Color(0xFFFF453A)+/** Menus stay below the top bar. */+private val MenuTop = 57.dp+/** A brush swiped left shows three buttons filling its place, this far apart. */+private val SwipeGap = 5.5.dp+private val SwipeFill = Color(0xFF3F3F3F)+private val SwipeInk = Color(0xFFC5C5C5)+private val SwipeDelete = Color(0xFFFF3A46)++/** A brush's name on its cell: on a dark pill where its sample stroke runs under it. */+@Composable+private fun BrushName(name: String, selected: Boolean, shaded: Boolean, modifier: Modifier) {+ Text(+ name,+ color = if (selected) Color.White else Pc.PanelTitle,+ fontSize = 14.sp,+ fontWeight = FontWeight.SemiBold,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = modifier.offset(x = (-6).dp, y = (-2).dp)+ .then(if (shaded) Modifier.clip(RoundedCornerShape(50)).background(NamePill) else Modifier)+ .padding(horizontal = 6.dp, vertical = 2.dp),+ )+}++private val NamePill = Color(0x80000000)+/** The search field with the space above and below it, which scrolls away with the lists. */+private val SearchBlock = 60.dp+private val SearchFill = Color(0x1F767680)+private val SearchHint = Color(0x4DEBEBF5)+private val ResultFill = Color(0x14FFFFFF)++/**+ * The search field under the library's header: a magnifier, the text and, once typed, a clear+ * button. Putting the keyboard away leaves the field.+ */+@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)+@Composable+private fun LibrarySearch(query: String, onQuery: (String) -> Unit, onFocus: (Boolean) -> Unit) {+ val focus = androidx.compose.ui.platform.LocalFocusManager.current+ val keyboard = WindowInsets.isImeVisible+ var hadKeyboard by remember { mutableStateOf(false) }+ LaunchedEffect(keyboard) {+ if (keyboard) hadKeyboard = true else if (hadKeyboard) {+ hadKeyboard = false+ focus.clearFocus()+ }+ }+ Row(+ Modifier.padding(start = 12.dp, end = 12.dp, top = 10.dp, bottom = 10.dp).fillMaxWidth().height(40.dp)+ .clip(RoundedCornerShape(10.dp)).background(SearchFill),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Canvas(Modifier.size(41.dp, 40.dp)) {+ // a magnifier: a ring and its handle+ val c = Offset(size.width * 0.47f, size.height * 0.46f)+ val r = 7.dp.toPx()+ drawCircle(SearchHint, r, c, style = androidx.compose.ui.graphics.drawscope.Stroke(2.dp.toPx()))+ val d = r * 0.7071f+ drawLine(SearchHint, c + Offset(d, d), c + Offset(d + 5.dp.toPx(), d + 5.dp.toPx()), 2.4.dp.toPx(), cap = androidx.compose.ui.graphics.StrokeCap.Round)+ }+ Box(Modifier.weight(1f), contentAlignment = Alignment.CenterStart) {+ if (query.isEmpty()) Text("Search", color = SearchHint, fontSize = 17.sp, maxLines = 1)+ androidx.compose.foundation.text.BasicTextField(+ query,+ onValueChange = onQuery,+ singleLine = true,+ textStyle = androidx.compose.ui.text.TextStyle(color = Color.White, fontSize = 17.sp),+ cursorBrush = androidx.compose.ui.graphics.SolidColor(Pc.Accent),+ keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(imeAction = androidx.compose.ui.text.input.ImeAction.Search),+ keyboardActions = androidx.compose.foundation.text.KeyboardActions(onSearch = { focus.clearFocus() }),+ modifier = Modifier.fillMaxWidth().onFocusChanged { onFocus(it.isFocused) },+ )+ }+ if (query.isNotEmpty()) {+ // a filled circle with a cross cut out of it+ Canvas(Modifier.padding(end = 5.dp).size(19.dp, 18.dp).clip(CircleShape).clickable { onQuery("") }) {+ val c = center+ drawCircle(SearchHint, size.minDimension / 2f, c)+ val k = 3.5.dp.toPx()+ for (s in listOf(1f, -1f)) {+ drawLine(Color.Black, c + Offset(-k, -k * s), c + Offset(k, k * s), 1.8.dp.toPx(), cap = androidx.compose.ui.graphics.StrokeCap.Round, blendMode = androidx.compose.ui.graphics.BlendMode.Clear)+ }+ }+ }+ }+}++/** The brushes of every set whose name holds the search, two to a row; tapping one chooses it. */+@Composable+private fun SearchResults(vm: CanvasViewModel, query: String) {+ val found = if (query.isBlank()) emptyList() else vm.brushSets.flatMap { it.brushes }.filter { it.name.contains(query.trim(), ignoreCase = true) }+ if (found.isEmpty()) {+ Box(Modifier.fillMaxSize().padding(top = 24.dp), contentAlignment = Alignment.TopCenter) {+ Text("No results", color = Pc.PanelTitle, fontSize = 15.sp, fontWeight = FontWeight.Medium)+ }+ return+ }+ LazyVerticalGrid(+ columns = GridCells.Fixed(2),+ modifier = Modifier.fillMaxSize(),+ contentPadding = PaddingValues(start = 12.dp, top = 11.dp, end = 12.dp, bottom = 12.dp),+ horizontalArrangement = Arrangement.spacedBy(6.dp),+ verticalArrangement = Arrangement.spacedBy(6.dp),+ ) {+ items(found, key = { "${it.set}-${it.index}" }) { b ->+ val key = "${b.set}-${b.index}"+ val preview = vm.previews[key]+ LaunchedEffect(key, preview == null) { if (preview == null) vm.loadPreview(b) }+ val selected = vm.highlighted(b)+ Box(+ Modifier.fillMaxWidth().height(81.dp).clip(RoundedCornerShape(12.dp))+ .background(if (selected) Pc.RowSelected else ResultFill)+ .clickable { vm.chooseBrush(b) },+ ) {+ preview?.let { Image(it, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize()) }+ BrushName(b.name, selected, vm.shadedNames[key] == true, Modifier.padding(start = 14.dp, top = 11.dp, end = 10.dp))+ }+ }+ }+}++/**+ * The brush library: sets on the left, the set's brushes with a sample stroke on the right. Tap+ * the chosen set for its menu, swipe a brush left to share, duplicate or delete it, hold and drag+ * it onto a set or to another place in its own, and add brushes and sets with the plus.+ */+@Composable+fun BrushLibrary(vm: CanvasViewModel, arrowX: Dp, modifier: Modifier = Modifier) {+ val sets = vm.brushSets+ val shown = sets.getOrNull(vm.shownSet) ?: return+ val context = LocalContext.current+ val scope = rememberCoroutineScope()+ val density = LocalDensity.current+ var adding by remember { mutableStateOf(false) }+ var setMenu by remember { mutableStateOf<Int?>(null) }+ // the set menu's icon grid is open+ var iconPicker by remember { mutableStateOf(false) }+ var swiped by remember { mutableStateOf<String?>(null) }+ // the search: what is typed, and whether the field is in use+ var query by remember { mutableStateOf("") }+ var searching by remember { mutableStateOf(false) }+ var deleting by remember { mutableStateOf<Pair<String, () -> Unit>?>(null) }+ val pick = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> uri?.let { vm.importBrushes(it) } }+ // a brush held and dragged: which, where the finger is and where on the brush it took hold+ // (window pixels); and where the sets, the brushes and the lists are on the screen+ var dragged by remember { mutableStateOf<BrushInfo?>(null) }+ var dragAt by remember { mutableStateOf(Offset.Zero) }+ var grab by remember { mutableStateOf(Offset.Zero) }+ val setBounds = remember { mutableStateMapOf<Int, Rect>() }+ val brushBounds = remember { mutableStateMapOf<String, Rect>() }+ var listBounds by remember { mutableStateOf(Rect.Zero) }+ // the set the dragged brush is over, if any+ val overSet = dragged?.let { setBounds.entries.firstOrNull { it.value.contains(dragAt) }?.key }+ fun drop() {+ val b = dragged ?: return+ dragged = null+ // onto a set: to its top; onto a brush of this set: to its place+ val set = setBounds.entries.firstOrNull { it.value.contains(dragAt) }?.key+ if (set != null) {+ if (set != b.set.toInt()) vm.moveBrush(b, set, 0)+ return+ }+ val target = shown.brushes.firstOrNull { brushBounds["${it.set}-${it.index}"]?.contains(dragAt) == true } ?: return+ vm.moveBrush(b, target.set.toInt(), target.index.toInt())+ }+ fun share(b: BrushInfo?) {+ scope.launch { vm.brushFileToShare(b)?.let { shareFile(context, it, "application/octet-stream") } }+ }+ // how far the search field (and the lists under it) has scrolled up out of sight: all of it+ // when the library opens+ val searchBlock = with(density) { SearchBlock.toPx() }+ var searchAway by remember { mutableFloatStateOf(searchBlock) }+ val searchScroll = remember(searchBlock) {+ object : NestedScrollConnection {+ override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {+ // scrolling up, the field goes first+ if (available.y >= 0f || searchAway >= searchBlock) return Offset.Zero+ val taken = maxOf(available.y, searchAway - searchBlock)+ searchAway -= taken+ return Offset(0f, taken)+ }++ override fun onPostScroll(consumed: Offset, available: Offset, source: NestedScrollSource): Offset {+ // pulled down past a list's top (not flung), the field comes back+ if (available.y <= 0f || searchAway <= 0f || source != NestedScrollSource.UserInput) return Offset.Zero+ val taken = minOf(available.y, searchAway)+ searchAway -= taken+ return Offset(0f, taken)+ }+ }+ }++ Popover(LibraryWidth, arrowX, modifier) {+ PanelHeader(+ when (vm.tool) {+ ToolKind.ERASE -> "Erase library"+ ToolKind.SMUDGE -> "Smudge library"+ else -> "Brush library"+ },+ start = 20.dp,+ end = 12.dp,+ height = 52.dp,+ ) {+ Box(Modifier.padding(top = 12.dp).size(41.dp, 40.dp).clickable { adding = true }, contentAlignment = Alignment.Center) {+ Icon(PcIcons.PlusMedium, contentDescription = "Add", tint = Pc.PanelGlyph, modifier = Modifier.requiredSize(41.dp))+ // hangs below the plus, their right edges in line+ LibraryMenu(adding, androidx.compose.ui.graphics.TransformOrigin(1f, 0f), MenuPlace { a, size -> IntOffset(a.right - size.width, a.bottom) }, onDismiss = { adding = false }, overPanel = true) {+ MenuItem(PcIcons.MenuNewBrush, "Create new brush") {+ adding = false+ vm.newBrush()+ }+ MenuItem(PcIcons.MenuNewSet, "Create new set") {+ adding = false+ vm.newBrushSet()+ }+ MenuDivider(11.dp)+ MenuItem(PcIcons.MenuFolder, "Import from Files") {+ adding = false+ pick.launch(arrayOf("*/*"))+ }+ }+ }+ }+ // the search field scrolls away with the lists: out of sight at first, it comes down as a+ // list is pulled down past its top, and goes again as the lists scroll up+ Box(Modifier.weight(1f).clipToBounds().nestedScroll(searchScroll)) {+ Column(+ Modifier.layout { measurable, constraints ->+ val away = if (searching || query.isNotEmpty()) 0 else searchAway.roundToInt()+ val tall = constraints.maxHeight + away+ val placeable = measurable.measure(constraints.copy(minHeight = tall, maxHeight = tall))+ layout(constraints.maxWidth, constraints.maxHeight) { placeable.place(0, -away) }+ },+ ) {+ LibrarySearch(query, onQuery = { query = it }, onFocus = { searching = it })+ Box(Modifier.weight(1f).onGloballyPositioned { listBounds = it.boundsInWindow() }) {+ if (searching || query.isNotEmpty()) {+ SearchResults(vm, query)+ } else {+ Row(Modifier.fillMaxSize()) {+ LazyColumn(+ Modifier.width(SetsWidth).fillMaxHeight().background(Pc.SetColumn),+ contentPadding = PaddingValues(12.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp),+ ) {+ itemsIndexed(sets) { i, set ->+ val selected = i == vm.shownSet+ Box {+ Row(+ Modifier.fillMaxWidth().height(50.dp).onGloballyPositioned { setBounds[i] = it.boundsInWindow() }.clip(RoundedCornerShape(12.dp))+ .background(if (overSet == i) Pc.Accent else if (selected) Pc.RowSelected else Pc.SetCell)+ .clickable { if (selected) setMenu = i else vm.showSet(i) },+ verticalAlignment = Alignment.CenterVertically,+ ) {+ val ink = if (selected) Color.White else Pc.PanelTitle+ // a 40 frame centred 24 in+ Icon(PcIcons.SetIcons.getOrElse(set.icon.toInt()) { PcIcons.BrushSet }, contentDescription = null, tint = ink, modifier = Modifier.padding(start = 4.dp).requiredSize(40.dp))+ val nameModifier = Modifier.padding(start = 1.dp, end = 8.dp)+ if (vm.renamingSet == i) {+ InlineName(set.name, ink, 14.sp, nameModifier) { vm.renameBrushSet(i, it) }+ } else {+ Text(+ set.name,+ color = ink,+ fontSize = 14.sp,+ fontWeight = FontWeight.SemiBold,+ lineHeight = 16.sp,+ maxLines = 2,+ overflow = TextOverflow.Ellipsis,+ modifier = nameModifier,+ )+ }+ }+ // centred on the set, a little left of it+ val left = with(density) { 6.dp.roundToPx() }+ val below = with(density) { MenuTop.roundToPx() }+ // the icons to choose from, beside the menu on its left+ MenuPresence(setMenu == i && iconPicker, androidx.compose.ui.graphics.TransformOrigin(1f, 0.5f)) { look ->+ Popup(+ popupPositionProvider = MenuPlace(below) { a, size -> IntOffset(a.left - left - size.width + with(density) { 6.dp.roundToPx() }, a.center.y - size.height / 2 + with(density) { 40.dp.roundToPx() }) },+ onDismissRequest = { iconPicker = false },+ ) {+ val shape = RoundedCornerShape(16.dp)+ LazyVerticalGrid(+ columns = GridCells.Fixed(5),+ modifier = look.size(252.dp, 327.dp).clip(shape).background(MenuFill).border(1.dp, MenuEdge, shape).padding(4.dp),+ ) {+ items(PcIcons.PICKED_SET_ICONS) { k ->+ val chosen = k == set.icon.toInt()+ Box(+ Modifier.size(48.dp).clip(CircleShape).background(if (chosen) Pc.Accent else Color.Transparent).clickable {+ vm.changeBrushSetIcon(i, k)+ iconPicker = false+ setMenu = null+ },+ contentAlignment = Alignment.Center,+ ) {+ Icon(PcIcons.SetIcons[k], contentDescription = PcIcons.SetIconNames[k], tint = Color.White, modifier = Modifier.requiredSize(40.dp))+ }+ }+ }+ }+ }+ // left of the set, 6 clear of it, centred on it+ LibraryMenu(setMenu == i, androidx.compose.ui.graphics.TransformOrigin(1f, 0.5f), MenuPlace(below) { a, size -> IntOffset(a.left - size.width - left, a.center.y - size.height / 2) }, onDismiss = { setMenu = null }) {+ MenuItem(PcIcons.MenuRename, "Rename") {+ setMenu = null+ vm.renamingSet = i+ }+ MenuItem(PcIcons.MenuDuplicate, "Duplicate") {+ setMenu = null+ vm.duplicateBrushSet(i)+ }+ MenuItem(PcIcons.SetIcons.getOrElse(set.icon.toInt()) { PcIcons.BrushSet }, "Customize icon", trailing = PcIcons.MenuChevron) {+ iconPicker = !iconPicker+ }+ MenuDivider()+ MenuItem(PcIcons.MenuShare, "Share") {+ setMenu = null+ share(null)+ }+ if (sets.size > 1) {+ MenuDivider()+ MenuItem(PcIcons.MenuTrash, "Delete", Pc.MenuDanger) {+ setMenu = null+ deleting = "Delete this set and its brushes?" to { vm.deleteBrushSet(i) }+ }+ }+ }+ }+ }+ }+ // another set's brushes replace these at once (rows fade only as brushes come and go)+ androidx.compose.runtime.key(vm.shownSet) {+ LazyColumn(+ Modifier.weight(1f).fillMaxHeight().background(Pc.BrushColumn),+ contentPadding = PaddingValues(start = 12.dp, top = 9.75.dp, end = 12.dp, bottom = 12.dp),+ verticalArrangement = Arrangement.spacedBy(BrushGap),+ ) {+ items(shown.brushes, key = { "${it.set}-${it.index}" }) { b ->+ val key = "${b.set}-${b.index}"+ // the current brush, or the brush last chosen in this set+ val selected = vm.highlighted(b)+ // previews go by place, and are dropped when the library changes+ val preview = vm.previews[key]+ LaunchedEffect(key, preview == null) { if (preview == null) vm.loadPreview(b) }+ Box(Modifier.animateItem(Motion.rowFade(), Motion.rowMove(), Motion.rowFade())) {+ SwipeBrush(+ open = swiped == key,+ onOpen = { swiped = if (it) key else null },+ onShare = { share(b) },+ onDuplicate = { vm.duplicateBrush(b) },+ onDelete = { deleting = "Delete this brush?" to { vm.deleteBrush(b) } },+ ) {+ Box(+ Modifier.fillMaxWidth().height(BrushHeight).onGloballyPositioned { brushBounds[key] = it.boundsInWindow() }+ .alpha(if (dragged?.let { d -> d.set == b.set && d.index == b.index } == true) 0.3f else 1f)+ .pointerInput(key) {+ detectDragGesturesAfterLongPress(+ onDragStart = { at ->+ swiped = null+ val top = brushBounds[key]?.topLeft ?: Offset.Zero+ grab = at+ dragAt = top + at+ dragged = b+ },+ onDrag = { change, by ->+ change.consume()+ dragAt += by+ },+ onDragEnd = { drop() },+ onDragCancel = { dragged = null },+ )+ }+ .clip(RoundedCornerShape(12.dp))+ .background(if (selected) Pc.RowSelected else Color.Transparent)+ .clickable {+ swiped = null+ // a highlighted brush opens in the studio+ vm.chooseBrush(b)+ if (selected) vm.openStudio()+ },+ ) {+ // the sample stroke filling the cell's height (its ends past the cell's sides),+ // under the name+ preview?.let {+ // the samples are drawn white: dark on the light interface's cells+ Image(+ it, contentDescription = null, contentScale = ContentScale.Crop,+ colorFilter = if (Pc.light && !selected) androidx.compose.ui.graphics.ColorFilter.tint(Color.Black, androidx.compose.ui.graphics.BlendMode.SrcIn) else null,+ modifier = Modifier.fillMaxSize(),+ )+ }+ BrushName(b.name, selected, vm.shadedNames[key] == true, Modifier.padding(start = 18.dp, top = 11.75.dp))+ }+ }+ }+ }+ }+ }+ }+ }+ // the dragged brush follows the finger+ dragged?.let { d ->+ val size = brushBounds["${d.set}-${d.index}"]?.size+ val at = dragAt - grab - listBounds.topLeft+ Box(+ Modifier.offset { IntOffset(at.x.roundToInt(), at.y.roundToInt()) }+ .size(with(density) { (size?.width ?: 0f).toDp() }, BrushHeight)+ .clip(RoundedCornerShape(12.dp)).background(Pc.RowSelected.copy(alpha = 0.9f)),+ ) {+ vm.previews["${d.set}-${d.index}"]?.let {+ Image(it, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())+ }+ Text(d.name, color = Color.White, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, modifier = Modifier.padding(start = 18.dp, top = 11.dp))+ }+ }+ }+ }+ }+ }++ Alert(+ deleting,+ title = { (title, _) -> title },+ message = { "It can't be brought back." },+ action = "Delete",+ icon = PcIcons.Trash,+ onCancel = { deleting = null },+ onAction = { (_, action) ->+ deleting = null+ action()+ },+ )+}++/** A brush that slides away to the left, showing Share, Duplicate and Delete in its place. */+@Composable+private fun SwipeBrush(+ open: Boolean,+ onOpen: (Boolean) -> Unit,+ onShare: () -> Unit,+ onDuplicate: () -> Unit,+ onDelete: () -> Unit,+ content: @Composable () -> Unit,+) {+ var width by remember { mutableIntStateOf(0) }+ val offset = remember { Animatable(0f) }+ val scope = rememberCoroutineScope()+ LaunchedEffect(open, width) { offset.animateTo(if (open) -width.toFloat() else 0f, Motion.swipeSettle()) }+ Box(Modifier.fillMaxWidth().onSizeChanged { width = it.width }.clipToBounds()) {+ if (offset.value < 0f) {+ Row(Modifier.matchParentSize(), horizontalArrangement = Arrangement.spacedBy(SwipeGap)) {+ SwipeButton(PcIcons.ShareOut, "Share", SwipeFill, SwipeInk, Modifier.weight(1f)) {+ onOpen(false)+ onShare()+ }+ SwipeButton(PcIcons.Duplicate, "Duplicate", SwipeFill, SwipeInk, Modifier.weight(1f)) {+ onOpen(false)+ onDuplicate()+ }+ SwipeButton(PcIcons.Trash, "Delete", SwipeDelete, Color.White, Modifier.weight(1f)) {+ onOpen(false)+ onDelete()+ }+ }+ }+ Box(+ Modifier.offset { IntOffset(offset.value.roundToInt(), 0) }.pointerInput(open, width) {+ detectHorizontalDragGestures(+ onHorizontalDrag = { change, amount ->+ change.consume()+ scope.launch { offset.snapTo((offset.value + amount).coerceIn(-width.toFloat(), 0f)) }+ },+ onDragEnd = {+ val opened = offset.value < -width / 3f+ if (opened == open) scope.launch { offset.animateTo(if (open) -width.toFloat() else 0f, Motion.swipeSettle()) } else onOpen(opened)+ },+ onDragCancel = { scope.launch { offset.animateTo(if (open) -width.toFloat() else 0f, Motion.swipeSettle()) } },+ )+ },+ ) { content() }+ }+}++@Composable+private fun SwipeButton(icon: ImageVector, label: String, fill: Color, ink: Color, modifier: Modifier, onClick: () -> Unit) {+ Column(+ modifier.fillMaxHeight().clip(RoundedCornerShape(16.dp)).background(fill).clickable(onClick = onClick).padding(top = 5.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.Center,+ ) {+ Icon(icon, contentDescription = null, tint = ink, modifier = Modifier.size(16.dp))+ Spacer(Modifier.height(5.dp))+ Text(label, color = ink, fontSize = 14.sp, fontWeight = FontWeight.Medium, maxLines = 1)+ }+}++/** A menu of the library (and the layers panel's title), placed by [place]. */+@Composable+internal fun LibraryMenu(+ open: Boolean,+ origin: androidx.compose.ui.graphics.TransformOrigin,+ place: PopupPositionProvider,+ onDismiss: () -> Unit,+ overPanel: Boolean = false,+ content: @Composable ColumnScope.() -> Unit,+) {+ MenuPresence(open, origin) { look ->+ Popup(popupPositionProvider = place, onDismissRequest = onDismiss, properties = PopupProperties(focusable = true)) {+ val shape = RoundedCornerShape(16.dp)+ // frosted over the canvas; over the library itself, nearly solid+ val glass = if (overPanel) Modifier.background(Pc.GlassMenuOverPanel) else rememberFrost(16.dp).background(Pc.GlassMenu)+ Column(look.width(LibraryMenuWidth).clip(shape).then(glass).border(1.dp, MenuEdge, shape).padding(vertical = 7.dp), content = content)+ }+ }+}++/** A menu row: its icon (a 40 frame) centred 29.5 in, the label from 52, a chevron 27.5 from the right. */+@Composable+internal fun MenuItem(icon: ImageVector, label: String, ink: Color = Color.White, trailing: ImageVector? = null, iconSize: Dp = 40.dp, onClick: () -> Unit) {+ Row(Modifier.fillMaxWidth().height(40.dp).clickable(onClick = onClick), verticalAlignment = Alignment.CenterVertically) {+ Box(Modifier.padding(start = 9.5.dp).size(40.dp), contentAlignment = Alignment.Center) {+ Icon(icon, contentDescription = null, tint = ink, modifier = Modifier.requiredSize(iconSize))+ }+ // the menus' 17 pt system text is as wide as 18 here+ Text(label, color = ink, fontSize = 18.sp, maxLines = 1, modifier = Modifier.padding(start = 2.5.dp).weight(1f))+ if (trailing != null) Icon(trailing, contentDescription = null, tint = ink, modifier = Modifier.padding(end = 7.5.dp).requiredSize(40.dp))+ }+}++@Composable+internal fun MenuDivider(gap: Dp = 10.dp) {+ Box(Modifier.padding(horizontal = 15.5.dp, vertical = gap).fillMaxWidth().height(1.dp).background(MenuRule))+}++/** Places a menu from its anchor's bounds and its own size, kept in the window below [top]. */+internal class MenuPlace(private val top: Int = 0, private val place: (IntRect, IntSize) -> IntOffset) : PopupPositionProvider {+ override fun calculatePosition(anchorBounds: IntRect, windowSize: IntSize, layoutDirection: LayoutDirection, popupContentSize: IntSize): IntOffset {+ val p = place(anchorBounds, popupContentSize)+ return IntOffset(+ p.x.coerceIn(0, (windowSize.width - popupContentSize.width).coerceAtLeast(0)),+ p.y.coerceIn(top, (windowSize.height - popupContentSize.height).coerceAtLeast(top)),+ )+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/BrushStudio.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/BrushStudio.ktnew file mode 100644index 0000000..73f7d5a--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/BrushStudio.kt@@ -0,0 +1,1230 @@+package io.github.artcraftandroid.procraft.ui++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.layout.widthIn+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.drawBehind+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.ColorFilter+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.StrokeCap+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.graphics.drawscope.clipRect+import androidx.compose.ui.graphics.drawscope.withTransform+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.text.font.FontWeight+import android.content.res.Configuration+import androidx.compose.ui.platform.LocalConfiguration+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import io.github.artcraftandroid.procraft.canvas.PadSurfaceView+import io.github.artcraftandroid.procraft.core.curveSamples+import kotlin.math.pow+import kotlin.math.roundToInt+import androidx.compose.ui.unit.IntRect+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.LayoutDirection+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.layout.boundsInWindow+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.draw.shadow+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.ui.platform.LocalDensity++private val StudioTabs = Color(0xFF272727)+private val StudioBack = Color(0xFF1F1F1F)+private val StudioLine = Color(0xFF303030)+private val StudioHeader = Color(0xFF9C9C9C)+private val StudioLabel = Color(0xFFEDEDED)+private val StudioDim = Color(0xFF8E8E8E)+// a control that can't be used now+private val StudioOff = Color(0xFF505050)+/** Landscape: the pages' card's edge and title, the pages' names, and the settings column's width. */+private val StudioCardEdge = Color(0xFF373737)+private val StudioCardTitle = Color(0xFFC1C1C1)+private val StudioPageInk = Color(0xFF797979)+private val SettingsWidth = 323.dp+/** A switch that can't be changed here: the usual one, faded. */+private val StudioSwitchFixed = Color(0xFF515153)+private val StudioSwitchFixedKnob = Color(0xFF9B9B9B)+/** A slider that can't be changed here: its value and knob faded into the panel. */+private val StudioPillOff = Color(0xFF222222)+private val StudioValueOff = Color(0xFF646464)+private val StudioKnobOff = Color(0xFF353535)+private val StudioList = Color(0xFF242424)+private val StudioListLine = Color(0xFF202020)+private val StudioSegments = Color(0xFF3C3C3C)+private val StudioMaterial = Color(0xFF232323)+private val StudioMaterialInk = Color(0xFFB1B1B1)+private val StudioPill = Color(0xFF292929)+private val StudioTrack = Color(0xFF333333)+private val StudioTabIcon = Color(0xFFAAAAAA)+private val StudioButton = Color(0xFF1C1C1C)+private val StudioButtonEdge = Color(0xFF383838)+// the pad's buttons' text and icon: grey, not the labels' white+private val StudioButtonInk = Color(0xFFAAAAAA)+private val StudioGroup = Color(0xFF262626)+private val StudioCard = Color(0xFF313131)+private val PreviewCardFill = Color(0xFF2A2A2A)+private val PreviewCardEdge = Color(0xFF4A4A4A)+private val PreviewCardName = Color(0xFFC5C5C5)+private val StudioDone = Color(0xFF0190FF)++/** Where the settings start below the drawing pad (points from the top). */+private val PadHeight = 510.dp+private val TabsWidth = 81.dp++/**+ * How a slider reads; [SIZE] reads the size the control sets (the brush's most size × place^2.2) as a+ * percent (Max at the control's end), [BOTH] goes both ways from 0% in its middle, -100% to Max (and+ * [FOLLOW] and [GRADE] to a name of their own), [DOUBLE] reads 100% at its middle.+ */+enum class Shown { PERCENT, BOTH, COUNT, TIP, MOVEMENT, ZOOM, CHARGE, ZERO, SIZE, FOLLOW, GRADE, DOUBLE, TWICE }++/** One control in the brush studio. */+sealed class StudioControl {+ /** A slider; with [enabledBy] (a control's key and the choice it must be on), greyed out otherwise. */+ class Slider(val key: String, val label: String, val shown: Shown = Shown.PERCENT, val enabledBy: Pair<String, Int>? = null) : StudioControl()+ /** A switch; with [enabledBy] (a control's key and the choice it must be on), greyed out otherwise. */+ class Toggle(val key: String, val label: String, val enabledBy: Pair<String, Int>? = null) : StudioControl()+ class Choice(val key: String, val options: List<String>) : StudioControl()+ class Kinds(val key: String, val options: List<Pair<ImageVector, String>>) : StudioControl()+ /** The taper's two ends on a bar, with the switch linking their sizes under it. */+ class TaperBar(val start: String, val end: String, val link: String) : StudioControl()+ data object PressureCurve : StudioControl()+ /** The tilt angle on its quarter-circle graph. */+ data object TiltAngle : StudioControl()+ /** The shape's roundness and angle on an ellipse with handles. */+ data object Roundness : StudioControl()+ class Source(val label: String) : StudioControl()+ /** A blend mode, kept by the engine's number for it, picked from a list. */+ class Picker(val key: String, val label: String) : StudioControl()+ class Disclosure(val label: String) : StudioControl()+ data object PreviewCard : StudioControl()+ data object About : StudioControl()+}++class StudioSection(val title: String?, val controls: List<StudioControl>)++/** A page of the studio: its name, its icon (shown [iconSize] across) and its sections. */+class StudioTab(val name: String, val icon: ImageVector, val iconSize: Dp, val sections: List<StudioSection>)++private fun slider(key: String, label: String, shown: Shown = Shown.PERCENT, enabledBy: Pair<String, Int>? = null) =+ StudioControl.Slider(key, label, shown, enabledBy)+private fun toggle(key: String, label: String, enabledBy: Pair<String, Int>? = null) = StudioControl.Toggle(key, label, enabledBy)+private val FILTERING = listOf("No filtering", "Classic filtering", "Improved filtering")+private fun colorJitter(prefix: String, both: Boolean, brightness: String) = listOf(+ slider("${prefix}_hue", "Hue", if (both) Shown.BOTH else Shown.PERCENT),+ slider("${prefix}_saturation", "Saturation", if (both) Shown.BOTH else Shown.PERCENT),+ slider("${prefix}_brightness", brightness, if (both) Shown.BOTH else Shown.PERCENT),+)++/** The studio's tabs, in order, with what each shows. */+val STUDIO_TABS: List<StudioTab> by lazy {+ listOf(+ StudioTab("Stroke path", PcIcons.StudioStroke, 33.dp, listOf(+ StudioSection("Stroke properties", listOf(+ slider("spacing", "Spacing"), slider("spacing_jitter", "Spacing Jitter"), slider("jitter_lateral", "Jitter Lateral"),+ slider("jitter_linear", "Jitter Linear"), slider("falloff", "Fall off"),+ )),+ )),+ StudioTab("Stabilization", PcIcons.StudioStabilize, 45.dp, listOf(+ StudioSection("StreamLine", listOf(slider("streamline", "Amount"), slider("streamline_pressure", "Pressure"))),+ StudioSection("Stabilization", listOf(slider("stabilization", "Amount"))),+ StudioSection("Motion filtering", listOf(slider("motion_filtering", "Amount"), slider("motion_expression", "Expression"))),+ )),+ StudioTab("Taper", PcIcons.StudioTaper, 41.dp, listOf(+ StudioSection("Pressure taper", listOf(+ StudioControl.TaperBar("pen_taper_start", "pen_taper_end", "pen_taper_link"),+ slider("pen_taper_size", "Size"), slider("pen_taper_opacity", "Opacity"), slider("pen_taper_pressure", "Pressure"),+ slider("pen_taper_tip", "Tip", Shown.TIP), toggle("pen_tip_animation", "Tip animation"),+ )),+ StudioSection("Touch taper", listOf(+ StudioControl.TaperBar("touch_taper_start", "touch_taper_end", "touch_taper_link"),+ slider("touch_taper_size", "Size"), slider("touch_taper_opacity", "Opacity"), slider("touch_taper_tip", "Tip", Shown.TIP),+ )),+ StudioSection("Taper properties", listOf(toggle("classic_taper", "Classic taper"))),+ )),+ StudioTab("Shape", PcIcons.StudioShape, 45.dp, listOf(+ StudioSection(null, listOf(StudioControl.Source("Shape Source"))),+ StudioSection("Input style", listOf(+ StudioControl.Choice("input_style", listOf("Touch only", "Azimuth", "Azimuth and barrel roll")),+ // only with the barrel roll to follow+ toggle("relative_to_stroke", "Relative to stroke", enabledBy = "input_style" to 2),+ )),+ StudioSection("Touch properties", listOf(slider("shape_rotation", "Rotation", Shown.FOLLOW))),+ StudioSection("Shape properties", listOf(+ slider("scatter", "Scatter", Shown.TWICE), slider("count", "Count", Shown.COUNT), slider("count_jitter", "Count jitter"),+ toggle("randomized", "Randomized"), toggle("flip_x", "Flip X"), toggle("flip_y", "Flip Y"),+ StudioControl.Roundness, slider("pressure_roundness", "Pressure Roundness", Shown.BOTH),+ slider("tilt_roundness", "Tilt roundness", Shown.BOTH), slider("roundness_jitter_y", "Roundness Vertical Jitter"),+ slider("roundness_jitter_x", "Roundness Horizontal Jitter"),+ )),+ StudioSection("Shape filtering", listOf(StudioControl.Choice("shape_filtering", FILTERING))),+ )),+ StudioTab("Grain", PcIcons.StudioGrain, 45.dp, listOf(+ StudioSection(null, listOf(StudioControl.Source("Grain Source"))),+ StudioSection("Grain behavior", listOf(+ StudioControl.Kinds("grain_behavior", listOf(PcIcons.GrainMoving to "Moving", PcIcons.GrainTexturized to "Texturized")),+ slider("grain_movement", "Movement", Shown.MOVEMENT), slider("grain_scale", "Scale"), slider("grain_zoom", "Zoom", Shown.ZOOM),+ slider("grain_rotation", "Rotation", Shown.FOLLOW), slider("grain_depth", "Depth"), slider("grain_depth_min", "Depth minimum"),+ slider("grain_depth_jitter", "Depth jitter"), toggle("grain_offset_jitter", "Offset jitter"),+ StudioControl.Picker("grain_blend", "Blend mode"), slider("grain_brightness", "Brightness", Shown.BOTH),+ slider("grain_contrast", "Contrast", Shown.BOTH),+ )),+ StudioSection("Grain filtering", listOf(StudioControl.Choice("grain_filtering", FILTERING))),+ StudioSection("3D grain behaviour", listOf(toggle("grain_follows_camera", "Grain follows camera"))),+ )),+ StudioTab("Rendering", PcIcons.StudioRendering, 37.dp, listOf(+ StudioSection("Rendering mode", listOf(+ StudioControl.Choice("rendering_mode", listOf("Light Glaze", "Uniformed Glaze", "Intense Glaze", "Heavy Glaze", "Uniform Blending", "Intense Blending")),+ )),+ StudioSection("Blending", listOf(+ slider("flow", "Flow"), slider("wet_edges", "Wet edges"), slider("burnt_edges", "Burnt edges"),+ StudioControl.Picker("burnt_blend", "Burnt edges mode"), StudioControl.Picker("blend_mode", "Blend mode"),+ toggle("luminance_blending", "Luminance blending"), toggle("alpha_threshold", "Alpha Threshold"),+ slider("alpha_threshold_amount", "Threshold Amount", enabledBy = "alpha_threshold" to 1),+ // only for a brush paired with another, which none are yet+ toggle("classic_combine", "Classic Normal Combine mode", enabledBy = "dual_brush" to 1),+ )),+ )),+ StudioTab("Wet Mix", PcIcons.StudioWet, 45.dp, listOf(+ StudioSection("Wet mix", listOf(+ slider("wet_dilution", "Dilution"), slider("wet_charge", "Charge", Shown.CHARGE), slider("wet_attack", "Attack"),+ slider("wet_pull", "Pull"), slider("wet_grade", "Grade", Shown.GRADE), slider("wet_blur", "Blur"),+ slider("wet_blur_jitter", "Blur jitter"), slider("wet_jitter", "Wetness jitter"),+ )),+ )),+ StudioTab("Color dynamics", PcIcons.StudioColor, 41.dp, listOf(+ StudioSection("Stamp color jitter", listOf(+ slider("stamp_hue", "Hue"), slider("stamp_saturation", "Saturation"), slider("stamp_lightness", "Lightness"),+ slider("stamp_darkness", "Darkness"), slider("stamp_secondary", "Secondary color"),+ )),+ StudioSection("Stroke color jitter", listOf(+ slider("stroke_hue", "Hue"), slider("stroke_saturation", "Saturation"), slider("stroke_lightness", "Lightness"),+ slider("stroke_darkness", "Darkness"), slider("stroke_secondary", "Secondary color"),+ )),+ StudioSection("Color pressure", colorJitter("pressure", true, "Brightness") + slider("pressure_secondary", "Secondary Color")),+ StudioSection("Color tilt", colorJitter("tilt", true, "Brightness") + slider("tilt_secondary", "Secondary Color")),+ StudioSection("Color barrel roll", colorJitter("roll", false, "Brightness") + slider("roll_secondary", "Secondary Color")),+ )),+ StudioTab("Dynamics", PcIcons.StudioDynamics, 37.dp, listOf(+ StudioSection("Speed", listOf(slider("speed_size", "Size", Shown.BOTH), slider("speed_opacity", "Opacity", Shown.BOTH), slider("speed_spacing", "Spacing"))),+ StudioSection("Jitter", listOf(slider("jitter_size", "Size"), slider("jitter_opacity", "Opacity"))),+ )),+ StudioTab("Stylus", PcIcons.StudioStylus, 43.dp, listOf(+ StudioSection("Pressure", listOf(+ StudioControl.PressureCurve, slider("pressure_size", "Size", Shown.BOTH), slider("pressure_flow", "Opacity"),+ slider("pressure_opacity", "Flow", Shown.BOTH), slider("pressure_bleed", "Bleed"),+ )),+ StudioSection("Tilt", listOf(+ StudioControl.TiltAngle, slider("tilt_opacity", "Opacity"), slider("tilt_gradation", "Gradation"),+ slider("tilt_bleed", "Bleed"), slider("tilt_size", "Size"), toggle("tilt_size_compression", "Size compression"),+ )),+ StudioSection("Barrel roll", listOf(slider("roll_size", "Size", Shown.BOTH), slider("roll_opacity", "Opacity"), slider("roll_bleed", "Bleed"))),+ StudioSection("Cursor outline", listOf(StudioControl.Choice("cursor_outline", listOf("None", "Contrast", "Active color")))),+ StudioSection("Hover", listOf(slider("hover_pressure", "Estimated pressure"))),+ StudioSection("Hover fill", listOf(StudioControl.Choice("hover_fill", listOf("None", "Shape", "All")))),+ )),+ StudioTab("Properties", PcIcons.StudioProperties, 49.dp, listOf(+ StudioSection("Brush properties", listOf(toggle("orient_to_screen", "Orient to screen"), slider("smudge_pull", "Smudge Pull"))),+ StudioSection("Brush behavior", listOf(+ slider("max_size", "Maximum size", Shown.SIZE), slider("min_size", "Minimum size", Shown.SIZE),+ slider("max_opacity", "Maximum opacity"), slider("min_opacity", "Minimum opacity"),+ )),+ )),+ StudioTab("Materials", PcIcons.StudioMaterials, 29.dp, listOf(+ StudioSection("3D Materials", listOf(StudioControl.Disclosure("Metallic"), StudioControl.Disclosure("Roughness"))),+ )),+ StudioTab("Preview", PcIcons.StudioPreview, 45.dp, listOf(+ StudioSection("Preview render", listOf(StudioControl.PreviewCard)),+ StudioSection("Preview properties", listOf(+ toggle("preview_stamp", "Use stamp preview"), slider("preview_size", "Size"), slider("preview_pressure_min", "Pressure Minimum"),+ slider("preview_pressure_scale", "Pressure Scale", Shown.DOUBLE), toggle("preview_wet_mix", "Wet Mix"),+ slider("preview_tilt_offset", "Tilt angle", Shown.BOTH),+ )),+ )),+ StudioTab("About this brush", PcIcons.StudioAbout, 45.dp, listOf(StudioSection(null, listOf(StudioControl.About)))),+ )+}++/** Every key the studio's controls read. */+val STUDIO_KEYS: List<String> by lazy {+ STUDIO_TABS.flatMap { t -> t.sections.flatMap { s -> s.controls } }.flatMap { c ->+ when (c) {+ is StudioControl.Slider -> listOf(c.key)+ is StudioControl.Toggle -> listOf(c.key)+ is StudioControl.Choice -> listOf(c.key)+ is StudioControl.Kinds -> listOf(c.key)+ is StudioControl.Picker -> listOf(c.key)+ is StudioControl.TaperBar -> listOf(c.start, c.end, c.link)+ StudioControl.TiltAngle -> listOf("tilt_angle")+ StudioControl.Roundness -> listOf("roundness", "shape_angle")+ else -> emptyList()+ }+ }.plus("most_size").distinct()+}++/** The space above a control: after the section's title (when [titled]) or the control before it. */+/** What a space in the studio's column can follow or come before, besides a control. */+private enum class Edge { TOP, TITLE }++/**+ * The space between [above] (a control, a section's title or the column's top) and [below] (a+ * control or a title), as the reference spaces them. Titles here are 23 tall (24 there), slider rows+ * 55, switch and picker rows 47, list rows 44 with a line between.+ */+private fun gap(above: Any, below: Any): Dp {+ // switch and picker rows+ fun line(c: Any) = c is StudioControl.Toggle || c is StudioControl.Picker+ return when {+ above == Edge.TOP -> 8.dp+ above == Edge.TITLE -> when {+ line(below) -> 7.5.dp+ below == StudioControl.PressureCurve -> 29.dp+ below == StudioControl.TiltAngle -> 28.dp+ below == StudioControl.About -> 29.dp+ below is StudioControl.Disclosure -> 41.dp+ else -> 23.dp+ }+ below == Edge.TITLE -> when {+ line(above) -> 50.5.dp+ above is StudioControl.Slider -> 46.5.dp+ above == StudioControl.PreviewCard -> 48.dp+ else -> 47.dp+ }+ line(above) -> if (line(below)) 4.dp else 19.5.dp+ above is StudioControl.Slider || above is StudioControl.Choice -> if (line(below)) 0.dp else 15.5.dp+ above is StudioControl.Kinds -> 16.dp+ above is StudioControl.TaperBar -> 23.5.dp+ above == StudioControl.PressureCurve -> 24.5.dp+ above == StudioControl.TiltAngle -> 21.5.dp+ above == StudioControl.Roundness -> 16.5.dp+ above is StudioControl.Disclosure -> 29.dp+ else -> 15.5.dp+ }+}++/** A blend mode setting: its mode's name, in blue, opens the modes as a list over it. */+@Composable+private fun BlendPicker(vm: CanvasViewModel, c: StudioControl.Picker) {+ var open by remember { mutableStateOf(false) }+ var at by remember { mutableFloatStateOf(0f) }+ val current = vm.studio(c.key).roundToInt()+ Row(+ Modifier.offset(y = 2.dp).fillMaxWidth().height(47.dp).padding(start = 8.dp, end = 8.dp).onGloballyPositioned { at = it.boundsInWindow().center.y },+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(c.label, color = StudioDim, fontSize = 17.sp, maxLines = 1, modifier = Modifier.weight(1f))+ val name = vm.blendModeList.firstOrNull { it.id.toInt() == current }?.name ?: "Normal"+ Text(name, color = Pc.Accent, fontSize = 17.sp, maxLines = 1, modifier = Modifier.tap { open = true })+ }+ if (open) {+ BlendModeList(vm.blendModeList, current, at) { picked ->+ open = false+ picked?.let { vm.setStudio(c.key, it.toFloat()) }+ }+ }+}++private val ModeRow = 38.dp+private val ModeListWidth = 250.dp+/** At most this many rows show at once; the rest scroll. */+private const val MODE_ROWS_SHOWN = 11++/**+ * The blend modes in the layer panel's order, as a light list 10 from the window's right with the+ * current one ([current], an engine number) over the window height [centreY]; a tap picks one,+ * a tap outside it closes it ([onDone] with null).+ */+@Composable+private fun BlendModeList(modes: List<io.github.artcraftandroid.procraft.core.BlendModeInfo>, current: Int, centreY: Float, onDone: (Int?) -> Unit) {+ val density = LocalDensity.current+ val chosen = modes.indexOfFirst { it.id.toInt() == current }.coerceAtLeast(0)+ val shown = minOf(MODE_ROWS_SHOWN, modes.size)+ val first = (chosen - shown / 2).coerceIn(0, (modes.size - shown).coerceAtLeast(0))+ val pitch = with(density) { (ModeRow + 1.dp).toPx() }+ val height = ModeRow * shown + 1.dp * (shown - 1)+ val list = rememberLazyListState(first)+ val place = remember(centreY, chosen, first) {+ object : androidx.compose.ui.window.PopupPositionProvider {+ override fun calculatePosition(anchorBounds: IntRect, windowSize: IntSize, layoutDirection: LayoutDirection, popupContentSize: IntSize): IntOffset {+ val margin = with(density) { 10.dp.roundToPx() }+ val top = (centreY - (chosen - first + 0.5f) * pitch).roundToInt()+ return IntOffset(+ windowSize.width - margin - popupContentSize.width,+ top.coerceIn(margin, (windowSize.height - margin - popupContentSize.height).coerceAtLeast(margin)),+ )+ }+ }+ }+ androidx.compose.ui.window.Popup(popupPositionProvider = place, onDismissRequest = { onDone(null) }, properties = androidx.compose.ui.window.PopupProperties(focusable = true)) {+ androidx.compose.foundation.lazy.LazyColumn(+ Modifier.size(ModeListWidth, height).shadow(24.dp, RoundedCornerShape(13.dp)).clip(RoundedCornerShape(13.dp)).background(ModeListFill),+ state = list,+ ) {+ items(modes.size) { i ->+ val m = modes[i]+ val picked = i == chosen+ if (i > 0) Box(Modifier.fillMaxWidth().height(1.dp).background(ModeListLine))+ Row(+ Modifier.fillMaxWidth().height(ModeRow).background(if (picked) Pc.RowSelected else Color.Transparent).tap { onDone(m.id.toInt()) }+ .padding(start = 13.5.dp, end = 20.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(m.name, color = if (picked) Color.White else ModeListInk, fontSize = 17.sp, maxLines = 1, modifier = Modifier.weight(1f))+ PcIcons.BlendGlyphs[m.name]?.let { Icon(it, contentDescription = null, tint = if (picked) Color.White else ModeListGlyph, modifier = Modifier.size(22.dp)) }+ }+ }+ }+ }+}++private val ModeListFill = Color(0xFFE1E1E1)+private val ModeListLine = Color(0xFFCDCDCD)+private val ModeListInk = Color(0xFF393939)+private val ModeListGlyph = Color(0xFF7F7F7F)++/** A slider's value as it reads. */+private fun shownValue(v: Float, shown: Shown, most: Float = 16f): String {+ val percent = "${(v * 100).roundToInt()}%"+ // between ends that read by name, a value never rounds onto an end (0.996 reads 99%)+ val between = "${(v * 100).roundToInt().coerceIn(1, 99)}%"+ val belowTop = "${(v * 100).roundToInt().coerceAtMost(99)}%"+ return when (shown) {+ Shown.PERCENT -> when {+ v <= 0f -> "None"+ v >= 1f -> "Max"+ else -> between+ }+ Shown.ZERO -> percent+ Shown.BOTH -> if (v >= 1f) "Max" else belowTop+ // smoothing all the way+ Shown.GRADE -> if (v >= 1f) "Smooth" else belowTop+ // the control's middle reads as 100%+ Shown.DOUBLE -> "${(v * 200).roundToInt()}%"+ // as a percent, with the control's middle at 100%+ Shown.TWICE -> when {+ v <= 0f -> "None"+ v >= 1f -> "Max"+ else -> "${(v * 200).roundToInt().coerceIn(1, 199)}%"+ }+ // turning with the stroke: all the way reads as following it+ Shown.FOLLOW -> if (v >= 1f) "Follow stroke" else belowTop+ Shown.COUNT -> "${1 + (v * 15).roundToInt()}"+ Shown.TIP -> if (v <= 0f) "Sharp" else if (v >= 1f) "Blunt" else between+ Shown.MOVEMENT -> if (v <= 0f) "Stamp" else if (v >= 1f) "Rolling" else between+ Shown.ZOOM -> if (v <= 0f) "Follow size" else if (v >= 1f) "Cropped" else between+ Shown.CHARGE -> if (v <= 0f) "Disabled" else if (v >= 1f) "Max" else between+ Shown.SIZE -> {+ val size = most * v.coerceIn(0f, 1f).toDouble().pow(2.2).toFloat()+ // Max only at the control's end: a size of more than a unit reads as its percent+ if (v >= 1f) "Max" else if (size <= 0f) "None" else "${(size * 100).roundToInt()}%"+ }+ }+}++private val PadBehind = Color(0xFF1F1F1F)++/**+ * The brush studio: tabs down the left, the drawing pad above, the tab's settings below. It slides up+ * from the bottom of the screen, and back down when it closes.+ */+@Composable+fun BrushStudio(vm: CanvasViewModel) {+ androidx.compose.animation.AnimatedVisibility(+ vm.studioOpen,+ enter = androidx.compose.animation.slideInVertically(Motion.studioIn()) { it },+ exit = androidx.compose.animation.slideOutVertically(Motion.studioOut()) { it },+ ) { Studio(vm) }+}++@Composable+private fun Studio(vm: CanvasViewModel) {+ val landscape = LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE+ Box(Modifier.fillMaxSize().background(StudioBack).pointerInput(Unit) { awaitEachGesture { awaitFirstDown().consume() } }) {+ if (landscape) {+ // the pages listed by name on a card, the settings beside them, the pad on the right+ Row(Modifier.fillMaxSize()) {+ StudioPagesCard(vm)+ StudioSettings(vm, Modifier.width(SettingsWidth).fillMaxHeight())+ Box(Modifier.width(1.dp).fillMaxHeight().background(StudioLine))+ StudioPad(vm, Modifier.fillMaxSize())+ }+ } else {+ Row(Modifier.fillMaxSize()) {+ StudioRail(vm)+ Column(Modifier.fillMaxSize()) {+ StudioPad(vm, Modifier.fillMaxWidth().height(PadHeight))+ Box(Modifier.fillMaxWidth().height(1.dp).background(StudioLine))+ StudioSettings(vm, Modifier.fillMaxSize())+ }+ }+ }+ }+ SourceEditor(vm)+}++/** Portrait: the pages as icons down the left. */+@Composable+private fun StudioRail(vm: CanvasViewModel) {+ Column(Modifier.width(TabsWidth).fillMaxHeight().background(StudioTabs).padding(top = 46.dp)) {+ STUDIO_TABS.forEachIndexed { i, tab ->+ val on = vm.studioTab == i+ Box(+ Modifier.padding(start = 8.dp, bottom = 3.dp).size(65.dp, 45.dp).clip(RoundedCornerShape(22.5.dp))+ .background(if (on) Pc.Accent else Color.Transparent).tap { vm.studioTab = i },+ contentAlignment = Alignment.Center,+ ) {+ // drawn in a 50 frame, fitted to the tab's own size+ Icon(tab.icon, contentDescription = tab.name, tint = if (on) Color.White else StudioTabIcon, modifier = Modifier.requiredSize(tab.iconSize))+ }+ }+ }+}++/** Landscape: the pages by icon and name on a card headed "Brush Studio", the list scrolling under the title. */+@Composable+private fun StudioPagesCard(vm: CanvasViewModel) {+ val shape = RoundedCornerShape(20.dp)+ Column(+ Modifier.padding(start = 10.dp, top = 10.dp, bottom = 10.dp).width(320.dp).fillMaxHeight().clip(shape).background(StudioTabs)+ .border(1.dp, StudioCardEdge, shape),+ ) {+ Text("Brush Studio", color = StudioCardTitle, fontSize = 24.sp, fontWeight = FontWeight.Bold, maxLines = 1, modifier = Modifier.padding(start = 24.dp, top = 19.dp))+ Column(+ Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(start = 8.dp, end = 8.dp, top = 17.dp, bottom = 8.dp),+ verticalArrangement = Arrangement.spacedBy(4.dp),+ ) {+ STUDIO_TABS.forEachIndexed { i, tab ->+ val on = vm.studioTab == i+ Row(+ Modifier.fillMaxWidth().height(44.dp).clip(RoundedCornerShape(22.dp)).background(if (on) Pc.Accent else Color.Transparent).tap { vm.studioTab = i },+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Box(Modifier.width(52.dp), contentAlignment = Alignment.Center) {+ Icon(tab.icon, contentDescription = null, tint = if (on) Color.White else StudioTabIcon, modifier = Modifier.requiredSize(tab.iconSize))+ }+ Text(tab.name, color = if (on) Color.White else StudioPageInk, fontSize = 17.sp, maxLines = 1)+ }+ }+ }+ }+}++/** The drawing pad with its buttons: Drawing Pad (its menu), Cancel and Done. */+@Composable+private fun StudioPad(vm: CanvasViewModel, modifier: Modifier) {+ // the pad's own colour behind its surface, so the canvas doesn't show through before the+ // pad's first frame (as the studio slides up)+ Box(modifier.background(PadBehind)) {+ androidx.compose.ui.viewinterop.AndroidView(factory = { PadSurfaceView(it, vm) }, modifier = Modifier.fillMaxSize())+ // drawn over the surface's hole until the pad has a frame of its own+ if (!vm.padShown) Box(Modifier.fillMaxSize().background(PadBehind))+ Row(Modifier.offset(21.dp, 21.dp).height(43.dp).clip(CircleShape).background(StudioButton).border(1.dp, StudioButtonEdge, CircleShape)+ .tap { vm.padMenuOpen = !vm.padMenuOpen }.padding(start = 9.dp, end = 13.dp),+ verticalAlignment = Alignment.CenterVertically) {+ Icon(PcIcons.StudioPad, contentDescription = null, tint = StudioButtonInk, modifier = Modifier.size(26.dp))+ Spacer(Modifier.width(6.dp))+ Text("Drawing Pad", color = StudioButtonInk, fontSize = 16.sp, fontWeight = FontWeight.SemiBold, maxLines = 1)+ }+ Row(Modifier.align(Alignment.TopEnd).padding(top = 20.dp, end = 20.dp), verticalAlignment = Alignment.CenterVertically) {+ Box(Modifier.size(73.dp, 43.dp).clip(CircleShape).background(StudioButton).border(1.dp, StudioButtonEdge, CircleShape).tap { vm.closeStudio(keep = false) },+ contentAlignment = Alignment.Center) {+ Text("Cancel", color = StudioButtonInk, fontSize = 17.sp, maxLines = 1)+ }+ Spacer(Modifier.width(13.dp))+ Box(Modifier.size(44.dp).clip(CircleShape).background(StudioDone).tap { vm.closeStudio(keep = true) }, contentAlignment = Alignment.Center) {+ Icon(PcIcons.DoneTick, contentDescription = "Done", tint = Color.White, modifier = Modifier.requiredSize(40.dp))+ }+ }+ }+}++/** The open page's settings, in sections, spaced as the reference spaces them. */+@Composable+private fun StudioSettings(vm: CanvasViewModel, modifier: Modifier) {+ val tab = STUDIO_TABS.getOrNull(vm.studioTab) ?: return+ // each section opens at its top+ Column(modifier.verticalScroll(remember(vm.studioTab) { androidx.compose.foundation.ScrollState(0) }).padding(start = 20.dp, end = 20.dp, bottom = 77.dp)) {+ // what the space above each thing follows: a control, a title, or the top+ var above: Any = Edge.TOP+ tab.sections.forEachIndexed { k, section ->+ // the About page is headed by the brush's name+ val title = section.title ?: vm.studioName.takeIf { section.controls.firstOrNull() == StudioControl.About }+ title?.let {+ Spacer(Modifier.height(if (k == 0) 25.dp else gap(above, Edge.TITLE)))+ Text(it, color = StudioHeader, fontSize = 19.sp, fontWeight = FontWeight.Bold, maxLines = 1, modifier = Modifier.padding(start = 8.dp))+ above = Edge.TITLE+ }+ for (control in section.controls) {+ Spacer(Modifier.height(gap(above, control)))+ StudioControlView(vm, control)+ above = control+ }+ }+ }+}++@Composable+private fun StudioControlView(vm: CanvasViewModel, c: StudioControl) {+ when (c) {+ is StudioControl.Slider -> {+ val enabled = c.enabledBy?.let { (key, choice) -> vm.studio(key).roundToInt() == choice } ?: true+ StudioSlider(c.label, vm.studio(c.key), c.shown, most = if (c.shown == Shown.SIZE) vm.studio("most_size") else 16f, enabled = enabled) { vm.setStudio(c.key, it) }+ }+ // a long name runs on under the switch, which is drawn over it+ is StudioControl.Toggle -> Box(Modifier.fillMaxWidth().height(47.dp).padding(start = 8.dp)) {+ val enabled = c.enabledBy?.let { (key, choice) -> vm.studio(key).roundToInt() == choice } ?: true+ Text(c.label, color = if (enabled) StudioDim else StudioOff, fontSize = 17.sp, maxLines = 1, softWrap = false, modifier = Modifier.align(Alignment.CenterStart))+ val on = vm.studio(c.key) >= 0.5f+ Box(Modifier.align(Alignment.CenterEnd).padding(end = 6.dp).then(if (enabled) Modifier.tap { vm.setStudio(c.key, if (on) 0f else 1f) } else Modifier)) {+ Switch(on, enabled = enabled, fixedTrack = StudioSwitchFixed, fixedKnob = StudioSwitchFixedKnob)+ }+ }+ is StudioControl.Choice -> Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(22.dp)).background(StudioList)) {+ val chosen = vm.studio(c.key).roundToInt()+ c.options.forEachIndexed { i, label ->+ if (i > 0) Box(Modifier.fillMaxWidth().height(1.dp).background(StudioListLine))+ Row(+ Modifier.fillMaxWidth().height(44.dp).background(if (i == chosen) Pc.Accent else Color.Transparent).tap { vm.setStudio(c.key, i.toFloat()) }+ .padding(start = 16.dp, end = 14.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(label, color = if (i == chosen) Color.White else StudioDim, fontSize = 17.sp, maxLines = 1, modifier = Modifier.weight(1f))+ if (i == chosen) Icon(PcIcons.MenuTick, contentDescription = null, tint = Color.White, modifier = Modifier.requiredSize(34.dp))+ }+ }+ }+ is StudioControl.Kinds -> {+ val chosen = vm.studio(c.key).roundToInt()+ Row(+ Modifier.padding(start = 8.dp, end = 8.dp).fillMaxWidth().height(34.dp).clip(RoundedCornerShape(17.dp)).background(StudioSegments).padding(2.dp),+ horizontalArrangement = Arrangement.spacedBy(11.dp),+ ) {+ c.options.forEachIndexed { i, (icon, label) ->+ Row(+ Modifier.weight(1f).fillMaxHeight().clip(RoundedCornerShape(15.dp)).background(if (i == chosen) Pc.Accent else Color.Transparent).tap { vm.setStudio(c.key, i.toFloat()) },+ horizontalArrangement = Arrangement.Center,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ // drawn in a 50 frame, shown 30 across, the name 2 after+ Icon(icon, contentDescription = null, tint = if (i == chosen) Color.White else StudioDim, modifier = Modifier.requiredSize(30.dp))+ Spacer(Modifier.width(2.dp))+ Text(label, color = if (i == chosen) Color.White else StudioDim, fontSize = 13.sp, maxLines = 1)+ }+ }+ }+ }+ is StudioControl.TaperBar -> Column {+ // linked, the two ends move together+ val linked = vm.studio(c.link) >= 0.5f+ TaperBar(+ vm.studio(c.start), vm.studio(c.end),+ { vm.setStudio(c.start, it); if (linked) vm.setStudio(c.end, it) },+ ) { vm.setStudio(c.end, it); if (linked) vm.setStudio(c.start, it) }+ Spacer(Modifier.height(4.5.dp))+ StudioControlView(vm, StudioControl.Toggle(c.link, "Link tip sizes"))+ }+ StudioControl.PressureCurve -> PressureCurve(+ vm.studioCurve, edge = StudioCurveEdge, fill = StudioCurveFill, corner = 8.dp, line = StudioCurveLine, lineWidth = 1.dp, handle = 5.5.dp to 3.5.dp,+ onChange = vm::changeStudioCurve,+ )+ StudioControl.TiltAngle -> TiltAngle(vm.studio("tilt_angle")) { vm.setStudio("tilt_angle", it) }+ StudioControl.Roundness -> RoundnessGraph(vm.studio("roundness"), vm.studio("shape_angle"), onRoundness = { vm.setStudio("roundness", it) }, onAngle = { vm.setStudio("shape_angle", it) })+ is StudioControl.Source -> if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE) SourceBox(vm, c) else Row(+ Modifier.fillMaxWidth().height(60.dp).clip(RoundedCornerShape(12.dp)).background(StudioCard)+ .tap { vm.sourceEditing = c.label.startsWith("Grain") }.padding(start = 16.dp, end = 8.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(c.label, color = StudioHeader, fontSize = 19.sp, fontWeight = FontWeight.Bold, maxLines = 1, modifier = Modifier.weight(1f))+ // the image it uses: the shape white on the row (the round tip a white disc), the grain as its greys+ val image = if (c.label.startsWith("Grain")) vm.studioGrainSource else vm.studioShapeSource+ Box(Modifier.size(44.dp).clip(RoundedCornerShape(10.dp)).then(if (image == null) Modifier.clip(CircleShape).background(Color.White) else Modifier)) {+ image?.let { Image(it, contentDescription = null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize()) }+ }+ }+ is StudioControl.Picker -> BlendPicker(vm, c)+ is StudioControl.Disclosure -> Row(+ Modifier.fillMaxWidth().height(60.dp).clip(RoundedCornerShape(20.dp)).background(StudioMaterial).padding(start = 16.dp, end = 16.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(c.label, color = StudioMaterialInk, fontSize = 17.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, modifier = Modifier.weight(1f))+ Box(Modifier.size(30.dp).clip(CircleShape).background(StudioBack), contentAlignment = Alignment.Center) {+ Icon(PcIcons.ChevronRight, contentDescription = null, tint = Color.White, modifier = Modifier.size(16.dp))+ }+ }+ // the brush's stroke filling the card's height, its name over it on a patch of the card's own colour+ StudioControl.PreviewCard -> Box(+ Modifier.fillMaxWidth()+ .aspectRatio(if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT) 623f / 200f else 278.5f / 91.5f)+ .clip(RoundedCornerShape(12.dp))+ .background(PreviewCardFill).border(1.dp, PreviewCardEdge, RoundedCornerShape(12.dp)),+ ) {+ vm.studioPreview?.let {+ Image(it, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())+ }+ Box(+ Modifier.padding(start = 15.5.dp, top = 14.5.dp).height(37.dp).clip(RoundedCornerShape(10.dp)).background(PreviewCardFill)+ .padding(horizontal = 17.dp),+ contentAlignment = Alignment.CenterStart,+ ) {+ Text(vm.studioName, color = PreviewCardName, fontSize = 20.sp, fontWeight = FontWeight.Bold, maxLines = 1, softWrap = false)+ }+ }+ StudioControl.About -> AboutBrush(vm)+ }+}++/**+ * A brush's About page: a card with its maker's picture, name and signature (ProCraft's own for+ * ours), then making a new reset point and resetting to it, with when it was made.+ */+@Composable+private fun AboutBrush(vm: CanvasViewModel) {+ val about = vm.studioAbout+ Column(Modifier.fillMaxWidth()) {+ Column(Modifier.fillMaxWidth().height(295.dp).clip(RoundedCornerShape(20.dp)).background(AboutCard), horizontalAlignment = Alignment.CenterHorizontally) {+ Spacer(Modifier.height(30.dp))+ Box(Modifier.size(96.dp).clip(CircleShape).background(AboutFace), contentAlignment = Alignment.Center) {+ val picture = about?.picture+ if (picture != null) {+ Image(picture, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())+ } else {+ Icon(PcIcons.Brush, contentDescription = null, tint = StudioDim, modifier = Modifier.size(56.dp))+ }+ }+ Spacer(Modifier.height(21.dp))+ Text("Made by ${about?.author?.takeIf { it.isNotBlank() } ?: "ProCraft"}", color = AboutName, fontSize = 20.sp, maxLines = 1)+ Spacer(Modifier.height(25.dp))+ // the signature in grey, whatever its own colour+ about?.signature?.let {+ Image(it, contentDescription = null, contentScale = ContentScale.Fit, colorFilter = ColorFilter.tint(AboutSignature), modifier = Modifier.size(300.dp, 64.dp))+ }+ }+ Spacer(Modifier.height(25.dp))+ Box(+ Modifier.fillMaxWidth().height(44.dp).clip(RoundedCornerShape(22.dp)).background(AboutCard).tap { vm.newResetPoint() }.padding(start = 15.dp),+ contentAlignment = Alignment.CenterStart,+ ) {+ Text("Create new reset point", color = AboutRowInk, fontSize = 17.sp, maxLines = 1)+ }+ Spacer(Modifier.height(11.dp))+ val made = about?.resetMade+ Column(+ Modifier.fillMaxWidth().height(if (made != null) 69.dp else 44.dp).clip(RoundedCornerShape(22.dp)).background(AboutCard).tap { vm.resetStudio() }+ .padding(start = 15.dp),+ verticalArrangement = Arrangement.Center,+ ) {+ Text("Reset brush", color = AboutRowInk, fontSize = 17.sp, maxLines = 1)+ if (made != null) {+ Spacer(Modifier.height(4.dp))+ Row(verticalAlignment = Alignment.CenterVertically) {+ Box(Modifier.size(17.dp).clip(CircleShape).background(Pc.Accent), contentAlignment = Alignment.Center) {+ Icon(PcIcons.MenuTick, contentDescription = null, tint = Color.White, modifier = Modifier.requiredSize(20.dp))+ }+ Spacer(Modifier.width(6.dp))+ // the short date and time with a comma between, as the reference writes them+ val day = java.util.Date(made * 1000)+ val at = java.text.DateFormat.getDateInstance(java.text.DateFormat.SHORT).format(day) + ", " ++ java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT).format(day)+ Text("Last reset point: $at", color = AboutRowInk, fontSize = 13.sp, maxLines = 1)+ }+ }+ }+ }+}++/**+ * Landscape: a source as a title with an Edit button, over a square of its image as wide as the+ * rows (the shape white on dark, the grain as its greys).+ */+@Composable+private fun SourceBox(vm: CanvasViewModel, c: StudioControl.Source) {+ val grain = c.label.startsWith("Grain")+ val open = { vm.sourceEditing = grain }+ Column(Modifier.fillMaxWidth()) {+ Box(Modifier.fillMaxWidth().padding(top = 8.5.dp).height(45.dp)) {+ // where a section's title sits+ Text(c.label, color = StudioHeader, fontSize = 19.sp, fontWeight = FontWeight.Bold, maxLines = 1,+ modifier = Modifier.align(Alignment.TopStart).padding(start = 8.dp, top = 9.5.dp))+ Box(Modifier.align(Alignment.CenterEnd).offset(x = 4.dp).size(54.dp, 45.dp).clip(CircleShape).background(StudioButton).tap { open() },+ contentAlignment = Alignment.Center) {+ Text("Edit", color = StudioButtonInk, fontSize = 17.sp, maxLines = 1)+ }+ }+ Spacer(Modifier.height(12.5.dp))+ val image = if (grain) vm.studioGrainSourceBig else vm.studioShapeSourceBig+ Box(Modifier.fillMaxWidth().aspectRatio(1f).clip(RoundedCornerShape(22.dp)).background(StudioButton).tap { open() }) {+ image?.let { Image(it, contentDescription = null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize()) }+ // the round tip: a white disc+ ?: Box(Modifier.fillMaxSize(0.7f).align(Alignment.Center).clip(CircleShape).background(Color.White))+ }+ }+}++private val AboutCard = Color(0xFF252525)+private val AboutFace = Color(0xFF3A3A3A)+private val AboutName = Color(0xFFE0E0E0)+private val AboutRowInk = Color(0xFFBBBBBB)+private val AboutSignature = Color(0xFF595959)++private val PadMenuFill = Color(0xFFC1C1C1)+private val PadMenuGroup = Color(0xFFD3D3D3)+private val PadMenuText = Color(0xFF393939)+private val PadMenuLine = Color(0xFFBDBDBD)++/** The drawing pad's settings: preview size, the pad's colour, and clearing or resetting. */+@Composable+fun PadMenu(vm: CanvasViewModel) {+ if (!vm.studioOpen || !vm.padMenuOpen) return+ Column(+ Modifier.offset(14.dp, 79.dp).width(320.dp).clip(RoundedCornerShape(26.dp)).background(PadMenuFill).padding(start = 10.dp, end = 10.dp, top = 17.dp, bottom = 10.dp),+ ) {+ Text("Settings", color = PadMenuText, fontSize = 22.sp, fontWeight = FontWeight.Bold, maxLines = 1, modifier = Modifier.padding(start = 12.dp))+ Spacer(Modifier.height(18.dp))+ Row(Modifier.fillMaxWidth().padding(horizontal = 10.dp)) {+ Text("Preview size", color = PadMenuText, fontSize = 16.sp, maxLines = 1, modifier = Modifier.weight(1f))+ Text("${(vm.studio("preview_size") * 100).roundToInt()}%", color = PadMenuText, fontSize = 16.sp, maxLines = 1)+ }+ PadSizeSlider(vm.studio("preview_size")) { vm.setStudio("preview_size", it) }+ Spacer(Modifier.height(18.dp))+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {+ CanvasViewModel.PAD_COLORS.forEachIndexed { i, c ->+ val chosen = vm.padColor == i+ Box(Modifier.size(37.dp).clip(CircleShape).background(if (chosen) Color(0xFFEBEBEB) else Color.Transparent).tap { vm.choosePadColor(i) }, contentAlignment = Alignment.Center) {+ Box(Modifier.size(19.dp).clip(CircleShape).background(CanvasSpace.color(c)))+ }+ }+ }+ Spacer(Modifier.height(18.dp))+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(16.dp)).background(PadMenuGroup)) {+ Box(Modifier.fillMaxWidth().height(45.dp).padding(start = 16.dp), contentAlignment = Alignment.CenterStart) {+ Text("Stylus", color = PadMenuText, fontSize = 17.sp, maxLines = 1)+ }+ Box(Modifier.fillMaxWidth().height(1.dp).background(PadMenuLine))+ Row(Modifier.fillMaxWidth().height(45.dp).padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {+ Text("3D preview", color = PadMenuText, fontSize = 17.sp, maxLines = 1, modifier = Modifier.weight(1f))+ Switch(false, enabled = true)+ }+ }+ Spacer(Modifier.height(10.dp))+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(16.dp)).background(PadMenuGroup)) {+ Box(Modifier.fillMaxWidth().height(41.dp).tap { vm.clearPad() }.padding(start = 16.dp), contentAlignment = Alignment.CenterStart) {+ Text("Clear drawing pad", color = PadMenuText, fontSize = 17.sp, maxLines = 1)+ }+ Box(Modifier.fillMaxWidth().height(1.dp).background(PadMenuLine))+ Box(Modifier.fillMaxWidth().height(41.dp).tap { vm.resetStudio() }.padding(start = 16.dp), contentAlignment = Alignment.CenterStart) {+ Text("Reset all brush settings", color = PadMenuText, fontSize = 17.sp, maxLines = 1)+ }+ }+ }+}++/** The pad menu's thin slider: blue up to a white knob, jumping to the touch. */+@Composable+private fun PadSizeSlider(value: Float, onChange: (Float) -> Unit) {+ val change by rememberUpdatedState(onChange)+ Box(+ Modifier.fillMaxWidth().height(28.dp).padding(horizontal = 10.dp).pointerInput(Unit) {+ awaitEachGesture {+ val down = awaitFirstDown()+ down.consume()+ change((down.position.x / size.width).coerceIn(0f, 1f))+ while (true) {+ val ev = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break+ if (!ev.pressed) break+ change((ev.position.x / size.width).coerceIn(0f, 1f))+ ev.consume()+ }+ }+ }.drawBehind {+ val y = size.height / 2f+ val x = size.width * value.coerceIn(0f, 1f)+ drawLine(Color(0xFFA9A9A9), Offset(0f, y), Offset(size.width, y), 3.dp.toPx(), cap = StrokeCap.Round)+ drawLine(Pc.Accent, Offset(0f, y), Offset(x, y), 3.dp.toPx(), cap = StrokeCap.Round)+ val knob = Size(28.dp.toPx(), 17.dp.toPx())+ val kx = x.coerceIn(knob.width / 2, size.width - knob.width / 2)+ drawRoundRect(Color(0x33000000), Offset(kx - knob.width / 2, y - knob.height / 2 + 1.dp.toPx()), knob, CornerRadius(knob.height / 2))+ drawRoundRect(Color.White, Offset(kx - knob.width / 2, y - knob.height / 2), knob, CornerRadius(knob.height / 2))+ },+ )+}++/** A labelled slider with its value in a pill: blue up to the knob, or out from the middle both ways. */+@Composable+internal fun StudioSlider(label: String, value: Float, shown: Shown, most: Float = 16f, enabled: Boolean = true, onChange: (Float) -> Unit) {+ val change by rememberUpdatedState(onChange)+ val current by rememberUpdatedState(value)+ val both = shown == Shown.BOTH || shown == Shown.FOLLOW || shown == Shown.GRADE+ Column(Modifier.fillMaxWidth().height(55.dp)) {+ // the name and value 2 below the top half's middle+ Row(Modifier.offset(y = 2.dp).fillMaxWidth().height(28.dp).padding(start = 10.dp, end = 3.5.dp), verticalAlignment = Alignment.CenterVertically) {+ FittedLabel(label, Modifier.weight(1f).padding(end = 12.dp))+ // as wide as its words need, 13 either side, and never narrower than 73+ Box(Modifier.height(28.dp).widthIn(min = 73.dp).clip(RoundedCornerShape(14.dp)).background(if (enabled) StudioPill else StudioPillOff).padding(horizontal = 13.dp),+ contentAlignment = Alignment.Center) {+ Text(shownValue(value, shown, most), color = if (enabled) StudioLabel else StudioValueOff, fontSize = 16.sp, maxLines = 1, softWrap = false)+ }+ }+ Box(+ Modifier.fillMaxWidth().height(20.dp).padding(start = 10.dp, end = 10.5.dp).pointerInput(both, enabled) {+ if (!enabled) return@pointerInput+ awaitEachGesture {+ val down = awaitFirstDown()+ down.consume()+ var last = down.position.x+ var v = current+ while (true) {+ val ev = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break+ if (!ev.pressed) break+ // relative: the knob follows the drag, as far as it travels+ val span = if (both) 2f else 1f+ val travel = (size.width - 2 * KNOB_INSET.toPx()).coerceAtLeast(1f)+ v = (v + (ev.position.x - last) / travel * span).coerceIn(if (both) -1f else 0f, 1f)+ last = ev.position.x+ change(v)+ ev.consume()+ }+ }+ }.drawBehind {+ val y = size.height / 2f+ val t = (if (both) (value + 1f) / 2f else value).coerceIn(0f, 1f)+ // the knob's middle travels from 5 in at either end, so it overhangs the track by 3+ val inset = KNOB_INSET.toPx()+ val x = inset + (size.width - 2 * inset) * t+ val line = 3.dp.toPx()+ // a two-way slider's middle: a tick across the track+ if (both) drawLine(StudioTrack, Offset(size.width / 2f, y - 10.dp.toPx()), Offset(size.width / 2f, y + 10.dp.toPx()), 1.dp.toPx())+ drawLine(StudioTrack, Offset(0f, y), Offset(size.width, y), line)+ if (enabled) drawLine(Pc.Accent, Offset(if (both) size.width / 2f else 0f, y), Offset(x, y), line)+ val knob = Size(16.dp.toPx(), 10.dp.toPx())+ drawRoundRect(if (enabled) Color.White else StudioKnobOff, Offset(x - knob.width / 2, y - knob.height / 2), knob, CornerRadius(knob.height / 2))+ },+ )+ }+}++/** A slider's name, 17 sp, made smaller (to 60%) when it would not fit beside the value. */+@Composable+private fun FittedLabel(label: String, modifier: Modifier) {+ val measurer = androidx.compose.ui.text.rememberTextMeasurer()+ androidx.compose.foundation.layout.BoxWithConstraints(modifier) {+ val room = constraints.maxWidth+ val size = remember(label, room) {+ fun wide(sp: Float) = measurer.measure(label, androidx.compose.ui.text.TextStyle(fontSize = sp.sp), maxLines = 1, softWrap = false).size.width+ var sp = 17f+ while (sp > 17f * 0.6f && wide(sp) > room) sp -= 0.5f+ sp+ }+ Text(label, color = StudioLabel, fontSize = size.sp, maxLines = 1, softWrap = false)+ }+}++/** How far in from the track's ends a studio slider's knob stops. */+private val KNOB_INSET = 5.dp++/**+ * The taper bar: a box inset as far as the sliders' knobs travel, the bar across it thinning to+ * points at its ends as the start and end handles (on lines across the box) move in, each up to+ * half way.+ */+@Composable+private fun TaperBar(start: Float, end: Float, onStart: (Float) -> Unit, onEnd: (Float) -> Unit) {+ val s by rememberUpdatedState(start)+ val e by rememberUpdatedState(end)+ val setStart by rememberUpdatedState(onStart)+ val setEnd by rememberUpdatedState(onEnd)+ Canvas(+ Modifier.fillMaxWidth().height(72.dp).pointerInput(Unit) {+ awaitEachGesture {+ val down = awaitFirstDown()+ down.consume()+ val from = TAPER_TRAVEL.toPx()+ val half = (size.width - 2 * from) / 2f+ // the nearer handle+ val startX = from + s * half+ val endX = size.width - from - e * half+ val grabStart = kotlin.math.abs(down.position.x - startX) <= kotlin.math.abs(down.position.x - endX)+ while (true) {+ val ev = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break+ if (!ev.pressed) break+ if (grabStart) setStart(((ev.position.x - from) / half).coerceIn(0f, 1f)) else setEnd(((size.width - from - ev.position.x) / half).coerceIn(0f, 1f))+ ev.consume()+ }+ }+ },+ ) {+ val left = TAPER_TRAVEL.toPx() - 1.dp.toPx()+ val right = size.width - left+ drawRoundRect(TaperBox, Offset(left, 0f), Size(right - left, size.height), CornerRadius(5.dp.toPx()))+ val y = size.height / 2f+ val half = (size.width - 2 * TAPER_TRAVEL.toPx()) / 2f+ val startX = TAPER_TRAVEL.toPx() + start * half+ val endX = size.width - TAPER_TRAVEL.toPx() - end * half+ val thick = 7.dp.toPx()+ val bar = Path().apply {+ moveTo(left, y)+ lineTo(startX, y - thick)+ lineTo(endX, y - thick)+ lineTo(right, y)+ lineTo(endX, y + thick)+ lineTo(startX, y + thick)+ close()+ }+ drawPath(bar, TaperBarFill)+ for (x in listOf(startX, endX)) {+ drawLine(Color.White, Offset(x, 0f), Offset(x, size.height), 2.dp.toPx())+ drawCircle(Color.White, 6.5.dp.toPx(), Offset(x, y))+ drawCircle(Pc.Accent, 4.dp.toPx(), Offset(x, y))+ }+ }+}++/** How far in from the row's ends the taper handles stop: where the sliders' knobs do. */+private val TAPER_TRAVEL = 15.dp+private val TaperBox = Color(0xFF212121)+/** The studio's pressure curve: a darker box with a light edge, a grey curve, small handles. */+private val StudioCurveFill = Color(0xFF1B1B1B)+private val StudioCurveEdge = Color(0xFF353535)+private val StudioCurveLine = Color(0xFFD5D5D5)+private val TaperBarFill = Color(0xFF363636)++/**+ * The pressure curve: a grid in quarters, the curve through its points as strokes apply it; drag a+ * point, or tap to add one.+ */+@Composable+internal fun TiltAngle(value: Float, onChange: (Float) -> Unit) {+ val change by rememberUpdatedState(onChange)+ val degrees = (value.coerceIn(0f, 1f) * 90f).roundToInt()+ Box(+ // not clipped: the handle sits on the box's edge, whole+ Modifier.padding(horizontal = 5.dp).fillMaxWidth().aspectRatio(271.5f / 221f).background(TiltBox, RoundedCornerShape(6.dp)),+ ) {+ Canvas(+ Modifier.fillMaxSize().pointerInput(Unit) {+ // the angle of the touch from the bottom-left corner, a quarter turn at most+ fun angleAt(p: Offset) = (kotlin.math.atan2((size.height - p.y).toDouble(), p.x.toDouble()) / (Math.PI / 2)).toFloat().coerceIn(0f, 1f)+ awaitEachGesture {+ val down = awaitFirstDown()+ down.consume()+ change(angleAt(down.position))+ while (true) {+ val ev = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break+ if (!ev.pressed) break+ change(angleAt(ev.position))+ ev.consume()+ }+ }+ },+ ) {+ val corner = Offset(0f, size.height)+ val r = size.height+ clipRect {+ drawCircle(TiltQuarter, r, corner)+ drawCircle(TiltArc, r, corner, style = Stroke(1.dp.toPx()))+ }+ val a = value.coerceIn(0f, 1f) * (Math.PI / 2)+ val dir = Offset(kotlin.math.cos(a).toFloat(), -kotlin.math.sin(a).toFloat())+ // the line runs on to the box's edge; the handle sits on the arc+ val reach = minOf(if (dir.x > 1e-4f) size.width / dir.x else Float.MAX_VALUE, if (dir.y < -1e-4f) size.height / -dir.y else Float.MAX_VALUE)+ drawLine(TiltLine, corner, corner + dir * reach, 1.dp.toPx())+ drawCircle(Color.White, 5.5.dp.toPx(), corner + dir * r)+ drawCircle(Pc.Accent, 3.5.dp.toPx(), corner + dir * r)+ }+ Text("$degrees°", color = TiltLabel, fontSize = 17.sp, modifier = Modifier.align(Alignment.TopEnd).padding(top = 7.dp, end = 9.dp))+ }+}++/**+ * The shape's roundness and angle: an ellipse on crossed lines, its blue handles (the ends of its+ * short axis) dragged in and out for the roundness, its green handle (the end of its long axis)+ * dragged round for the angle, shown in degrees.+ */+@Composable+internal fun RoundnessGraph(roundness: Float, angle: Float, onRoundness: (Float) -> Unit, onAngle: (Float) -> Unit) {+ val setRound by rememberUpdatedState(onRoundness)+ val setAngle by rememberUpdatedState(onAngle)+ val round by rememberUpdatedState(roundness.coerceIn(0.05f, 1f))+ val turn by rememberUpdatedState(angle)+ val degrees = ((angle.coerceIn(0f, 1f) * 360f).roundToInt()) % 360+ Box(+ Modifier.fillMaxWidth().aspectRatio(283f / 231.5f)+ .clip(RoundedCornerShape(6.dp)).background(TiltBox),+ ) {+ Canvas(+ Modifier.fillMaxSize().pointerInput(Unit) {+ awaitEachGesture {+ val down = awaitFirstDown()+ down.consume()+ val c = Offset(size.width / 2f, size.height / 2f)+ val r = size.height * 78f / 231.5f+ val a = turn * 2f * Math.PI.toFloat()+ val long = Offset(kotlin.math.cos(a), -kotlin.math.sin(a))+ val short = Offset(-long.y, long.x)+ // the green handle turns it; anything else squashes it+ val turning = (down.position - (c + long * r)).getDistance() < 28.dp.toPx()+ while (true) {+ val ev = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break+ if (!ev.pressed) break+ val d = ev.position - c+ if (turning) {+ val t = (kotlin.math.atan2(-d.y, d.x) / (2 * Math.PI)).toFloat()+ setAngle(if (t < 0f) t + 1f else t)+ } else {+ val along = kotlin.math.abs(d.x * short.x + d.y * short.y)+ setRound((along / r).coerceIn(0.05f, 1f))+ }+ ev.consume()+ }+ }+ },+ ) {+ val c = Offset(size.width / 2f, size.height / 2f)+ val r = size.height * 78f / 231.5f+ // the crossed lines show dimly through the ellipse's fill+ drawLine(RoundnessCross, Offset(0f, c.y), Offset(size.width, c.y), 1.dp.toPx())+ drawLine(RoundnessCross, Offset(c.x, 0f), Offset(c.x, size.height), 1.dp.toPx())+ val a = turn.coerceIn(0f, 1f) * 360f+ withTransform({ rotate(-a, c) }) {+ val oval = androidx.compose.ui.geometry.Size(2 * r, 2 * r * round)+ val at = Offset(c.x - r, c.y - r * round)+ drawOval(RoundnessFill, at, oval)+ drawOval(RoundnessEdge, at, oval, style = Stroke(1.dp.toPx()))+ }+ val rad = Math.toRadians(a.toDouble())+ val long = Offset(kotlin.math.cos(rad).toFloat(), -kotlin.math.sin(rad).toFloat())+ val short = Offset(-long.y, long.x)+ for (end in listOf(c + short * (r * round), c - short * (r * round))) {+ drawCircle(Color.White, 5.6.dp.toPx(), end)+ drawCircle(Pc.Accent, 3.7.dp.toPx(), end)+ }+ drawCircle(Color.White, 5.6.dp.toPx(), c + long * r)+ drawCircle(RoundnessGreen, 3.7.dp.toPx(), c + long * r)+ }+ Text("$degrees°", color = TiltLabel, fontSize = 17.sp, modifier = Modifier.align(Alignment.TopEnd).padding(top = 12.dp, end = 14.dp))+ }+}++private val RoundnessGreen = Color(0xFF42E347)+private val RoundnessCross = Color(0xFF4C4C4C)+private val RoundnessFill = Color(0xD6232323)+private val RoundnessEdge = Color(0xFF565656)+private val TiltBox = Color(0xFF1B1B1B)+private val TiltQuarter = Color(0xFF262626)+private val TiltArc = Color(0xFF4A4A4A)+private val TiltLine = Color(0xFF6E6E6E)+private val TiltLabel = Color(0xFF8E8E8E)++@Composable+internal fun PressureCurve(+ points: List<Offset>,+ modifier: Modifier = Modifier.padding(horizontal = 8.dp).fillMaxWidth().aspectRatio(1f),+ grid: Color = Color(0xFF3A3A3A),+ edge: Color = grid,+ /** The box's own fill and corners, the curve's colour and width, and its handles' radii (ring, middle). */+ fill: Color = Color.Transparent,+ corner: Dp = 0.dp,+ line: Color = Color.White,+ lineWidth: Dp = 1.5.dp,+ handle: Pair<Dp, Dp> = 7.dp to 5.dp,+ onChange: (List<Offset>) -> Unit,+) {+ val pts by rememberUpdatedState(points)+ val change by rememberUpdatedState(onChange)+ val samples = remember(points) { curveSamples(points.flatMap { listOf(it.x, it.y) }, 129u) }+ Canvas(+ modifier.pointerInput(Unit) {+ awaitEachGesture {+ val down = awaitFirstDown()+ down.consume()+ fun toCurve(p: Offset) = Offset((p.x / size.width).coerceIn(0f, 1f), (1f - p.y / size.height).coerceIn(0f, 1f))+ val at = toCurve(down.position)+ var list = pts.toMutableList()+ var index = list.indexOfFirst { (it - at).getDistance() < 0.05f }+ if (index < 0) {+ list.add(at)+ list.sortBy { it.x }+ index = list.indexOf(at)+ change(list.toList())+ }+ while (true) {+ val ev = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break+ if (!ev.pressed) break+ val p = toCurve(ev.position)+ val lo = list.getOrNull(index - 1)?.x ?: 0f+ val hi = list.getOrNull(index + 1)?.x ?: 1f+ list = list.toMutableList().also { it[index] = Offset(p.x.coerceIn(lo, hi), p.y) }+ change(list.toList())+ ev.consume()+ }+ }+ },+ ) {+ val w = size.width+ val h = size.height+ val round = CornerRadius(corner.toPx())+ drawRoundRect(fill, cornerRadius = round)+ for (k in 1..3) {+ drawLine(grid, Offset(w * k / 4f, 0f), Offset(w * k / 4f, h), 1.dp.toPx())+ drawLine(grid, Offset(0f, h * k / 4f), Offset(w, h * k / 4f), 1.dp.toPx())+ }+ drawRoundRect(edge, cornerRadius = round, style = Stroke(1.dp.toPx()))+ val sorted = points.sortedBy { it.x }+ val path = Path()+ val last = (samples.size - 1).coerceAtLeast(1)+ samples.forEachIndexed { i, v ->+ val x = w * i / last+ val y = (1f - v) * h+ if (i == 0) path.moveTo(x, y) else path.lineTo(x, y)+ }+ drawPath(path, line, style = Stroke(lineWidth.toPx(), cap = StrokeCap.Round))+ for (p in sorted) {+ drawCircle(Color.White, handle.first.toPx(), Offset(p.x * w, (1f - p.y) * h))+ drawCircle(Pc.Accent, handle.second.toPx(), Offset(p.x * w, (1f - p.y) * h))+ }+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/CanvasInfoUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/CanvasInfoUi.ktnew file mode 100644index 0000000..cf69655--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/CanvasInfoUi.kt@@ -0,0 +1,389 @@+package io.github.artcraftandroid.procraft.ui++import android.graphics.BitmapFactory+import androidx.activity.compose.BackHandler+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.PickVisualMediaRequest+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.Canvas+import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.foundation.verticalScroll+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.PathEffect+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.graphics.StrokeCap+import androidx.compose.ui.graphics.StrokeJoin+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import io.github.artcraftandroid.procraft.canvas.TimeLapse+import org.json.JSONArray+import java.io.File+import java.text.DateFormat+import java.util.Date+import kotlin.math.roundToInt+import kotlinx.coroutines.launch++private val ScreenFill = Color(0xFF1F1F1F)+private val RailFill = Color(0xFF272727)+private val CardFill = Color(0xFF252525)+private val Ink = Color(0xFFC1C1C1)+private val RailIdle = Color(0xFFAAAAAA)+private val PhotoFill = Color(0xFF303030)+private val PhotoGlyph = Color(0xFF4E4E4E)+private val Placeholder = Color(0xFF605F63)+private val SignLine = Color(0xFF494949)+private val CapsuleFill = Color(0xFF1A1A1A)+private val CapsuleEdge = Color(0xFF373737)+private val DoneBlue = Color(0xFF0190FF)+private val CardCorner = 25.dp++/** A page of the rail: its name, and its icon shown [size] across (each its own). */+private class InfoTab(val label: String, val icon: ImageVector, val size: Dp)++private val InfoTabs = listOf(+ InfoTab("About this artwork", PcIcons.InfoAbout, 39.dp),+ InfoTab("Dimensions", PcIcons.InfoDimensions, 51.dp),+ InfoTab("Layers", PcIcons.InfoLayers, 35.dp),+ InfoTab("Color profile", PcIcons.InfoProfile, 33.dp),+ InfoTab("Video settings", PcIcons.InfoVideo, 55.dp),+ InfoTab("Statistics", PcIcons.InfoStatistics, 35.dp),+)++/**+ * Canvas information, full screen: a rail of pages (about the artwork, its dimensions, layers,+ * colour profile, video and statistics), the artwork's name to edit as the title, Cancel and+ * Done.+ */+@Composable+fun CanvasInfo(vm: CanvasViewModel) {+ val session = vm.session ?: return+ val dir = vm.artworkFolder()+ val about = remember(dir) { dir?.let { File(it, "about") } }+ val info = remember { vm.artworkInfo() }+ var page by remember { mutableIntStateOf(0) }+ var name by remember { mutableStateOf(session.name()) }+ var author by remember { mutableStateOf(info?.author ?: "") }+ var photo by remember { mutableStateOf<ImageBitmap?>(about?.let { File(it, "photo.jpg") }?.takeIf { it.exists() }?.let { BitmapFactory.decodeFile(it.path)?.asImageBitmap() }) }+ var newPhoto by remember { mutableStateOf<android.net.Uri?>(null) }+ // the profile picked on its page, set on Done+ var profile by remember { mutableStateOf(session.profile()) }+ var askProfile by remember { mutableStateOf(false) }+ val signature = remember { mutableStateListOf<List<Offset>>().apply { addAll(readSignature(about)) } }+ val context = LocalContext.current+ val scope = androidx.compose.runtime.rememberCoroutineScope()+ val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->+ uri?.let {+ scope.launch {+ // a profile of the canvas's kind is picked to change to+ vm.importProfile(it)?.takeIf { name -> io.github.artcraftandroid.procraft.core.isCmykProfile(name) == session.isCmyk() }?.let { name -> profile = name }+ }+ }+ }+ val pick = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->+ if (uri != null) {+ newPhoto = uri+ photo = runCatching { context.contentResolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it) }?.asImageBitmap() }.getOrNull()+ }+ }+ fun close() {+ vm.canvasInfoOpen = false+ }+ fun done(asked: Boolean = false) {+ // a time-lapse recorded so far is in the old profile: asked first+ if (!asked && profile != session.profile() && vm.timeLapseInfo().first > 0) {+ askProfile = true+ return+ }+ vm.changeArtworkInfo(name, author)+ about?.let { folder ->+ folder.mkdirs()+ newPhoto?.let { uri -> runCatching { context.contentResolver.openInputStream(uri)?.use { input -> File(folder, "photo.jpg").outputStream().use { input.copyTo(it) } } } }+ writeSignature(folder, signature)+ }+ if (profile != session.profile()) vm.changeProfile(profile)+ close()+ }+ BackHandler { close() }+ Box(Modifier.fillMaxSize().background(ScreenFill).pointerInput(Unit) { detectTapGestures { } }) {+ // the rail of pages+ Column(Modifier.width(81.dp).fillMaxHeight().background(RailFill).padding(start = 8.dp, top = 46.dp)) {+ InfoTabs.forEachIndexed { i, tab ->+ val chosen = i == page+ Box(+ Modifier.size(65.dp, 53.dp).clip(CircleShape).background(if (chosen) Pc.Accent else Color.Transparent).clickable { page = i },+ contentAlignment = Alignment.Center,+ ) {+ Icon(tab.icon, contentDescription = tab.label, tint = if (chosen) Color.White else RailIdle, modifier = Modifier.requiredSize(tab.size))+ }+ Spacer(Modifier.height(3.dp))+ }+ }+ // the name, Cancel and Done+ BasicTextField(+ name,+ { name = it.take(256) },+ singleLine = true,+ textStyle = TextStyle(color = Ink, fontSize = 18.sp, fontWeight = FontWeight.Bold),+ cursorBrush = SolidColor(Color.White),+ modifier = Modifier.offset(x = 101.dp, y = 30.dp).width(400.dp),+ )+ Row(Modifier.align(Alignment.TopEnd).padding(top = 20.dp, end = 20.dp), verticalAlignment = Alignment.CenterVertically) {+ // Cancel, with Import before it on the colour profile page+ Row(Modifier.height(43.dp).clip(CircleShape).background(CapsuleFill).border(1.dp, CapsuleEdge, CircleShape), verticalAlignment = Alignment.CenterVertically) {+ if (page == 3) CapsuleText("Import") { importer.launch(arrayOf("*/*")) }+ CapsuleText("Cancel") { close() }+ }+ Spacer(Modifier.width(13.dp))+ Box(Modifier.size(44.dp, 45.dp).clip(CircleShape).background(DoneBlue).clickable { done() }, contentAlignment = Alignment.Center) {+ Icon(PcIcons.DoneTick, contentDescription = "Done", tint = Color.White, modifier = Modifier.requiredSize(40.dp))+ }+ }+ Column(Modifier.padding(start = 105.dp, end = 24.dp, top = 100.dp).verticalScroll(rememberScrollState())) {+ when (page) {+ 0 -> {+ AboutCard(photo, author, { author = it.take(256) }, { pick.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) }, signature)+ Spacer(Modifier.height(21.dp))+ val created = info?.createdMs?.toLong()?.takeIf { it > 0 } ?: dir?.let { File(it, "artwork.json").lastModified() }?.takeIf { it > 0 }+ val modified = dir?.let { File(it, "artwork.json").lastModified() }?.takeIf { it > 0 } ?: created+ Rows(listOf("Date created" to (created?.let(::dateText) ?: "—"), "Date modified" to (modified?.let(::dateText) ?: "—")))+ }+ 1 -> {+ val c = session.info()+ val dpi = c.dpi.coerceAtLeast(1f)+ val mm = { px: UInt -> "${(px.toFloat() / dpi * 25.4f).roundToInt()}mm" }+ Rows(listOf("Pixel width" to "${c.width}px", "Pixel height" to "${c.height}px"))+ Spacer(Modifier.height(21.dp))+ Rows(listOf("Physical width" to mm(c.width), "Physical height" to mm(c.height)))+ Spacer(Modifier.height(21.dp))+ Rows(listOf("DPI" to if (dpi % 1f == 0f) "${dpi.toInt()}" else "%.1f".format(dpi)))+ }+ 2 -> {+ val l = session.layerStats()+ Rows(listOf("Maximum layers" to "${l.maximum}"))+ Spacer(Modifier.height(21.dp))+ Rows(listOf("Layers used" to "${l.used}", "Layers available" to "${(l.maximum.toInt() - l.used.toInt()).coerceAtLeast(0)}"))+ Spacer(Modifier.height(21.dp))+ Rows(listOf("Assisted layers" to "0", "Clipping layers" to "${l.clipping}", "Layer masks" to "${l.masks}", "Layer groups" to "${l.groups}"))+ }+ 3 -> {+ Rows(listOf("Current color profile" to session.profile()), tall = 44)+ Text("Available color profiles", color = Ink, fontSize = 17.sp, modifier = Modifier.padding(start = 16.dp, top = 32.dp, bottom = 11.dp))+ // the profiles of the canvas's kind: RGB, or CMYK+ val names = if (session.isCmyk()) io.github.artcraftandroid.procraft.core.cmykProfiles() else io.github.artcraftandroid.procraft.core.colorProfiles()+ ProfileRows(names, profile.takeIf { it != session.profile() }) { profile = it }+ }+ 4 -> {+ val (frames, bytes) = vm.timeLapseInfo()+ val seconds = frames / TimeLapse.FPS+ Rows(+ listOf(+ "Video length" to "%02d:%02d:%02d".format(seconds / 3600, seconds / 60 % 60, seconds % 60),+ "Video quality" to "Good",+ "Video resolution" to "720p",+ "Video file size" to megabytes(bytes),+ "Video codec" to "H.264",+ ),+ )+ }+ else -> {+ val minutes = (info?.trackedMs?.toLong() ?: 0L) / 60_000L+ Rows(+ listOf(+ "Total strokes made" to "${info?.strokes ?: 0u}",+ "Tracked time" to "${minutes / 60}h ${minutes % 60}m",+ "Total file size" to megabytes(dir?.walkTopDown()?.filter { it.isFile }?.sumOf { it.length() } ?: 0L),+ ),+ )+ }+ }+ Spacer(Modifier.height(40.dp))+ }+ Alert(+ if (askProfile) Unit else null,+ title = { "Change color profile?" },+ message = { "The time-lapse recorded so far was made in the old profile's colours." },+ action = "Change",+ destructive = false,+ cancel = "Don't change",+ onCancel = {+ askProfile = false+ profile = session.profile()+ done(asked = true)+ },+ onAction = {+ askProfile = false+ done(asked = true)+ },+ )+ }+}++/** One of the header capsule's words, a button. */+@Composable+private fun CapsuleText(label: String, onClick: () -> Unit) {+ Box(Modifier.fillMaxHeight().clickable(onClick = onClick).padding(horizontal = 13.dp), contentAlignment = Alignment.Center) {+ Text(label, color = Color(0xFFA5A5A5), fontSize = 17.sp)+ }+}++/** The profiles to pick from in a rounded card, a line between, [picked] ticked. */+@Composable+private fun ProfileRows(names: List<String>, picked: String?, onPick: (String) -> Unit) {+ // the profile picked to change to fills its row blue; the current one is not marked+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(CardCorner)).background(CardFill)) {+ names.forEachIndexed { i, name ->+ if (i > 0) Box(Modifier.fillMaxWidth().height(2.dp).background(ScreenFill))+ val on = name == picked+ Row(+ Modifier.fillMaxWidth().height(47.dp).background(if (on) Pc.Accent else Color.Transparent).clickable { onPick(name) }.padding(horizontal = 13.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(name, color = if (on) Color.White else Ink, fontSize = 14.sp, maxLines = 1, modifier = Modifier.weight(1f))+ }+ }+ }+}++/** Rows of a name and its value in a rounded card, a line between. */+@Composable+private fun Rows(rows: List<Pair<String, String>>, tall: Int = 50) {+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(CardCorner)).background(CardFill)) {+ rows.forEachIndexed { i, (label, value) ->+ if (i > 0) Box(Modifier.fillMaxWidth().height(1.dp).background(ScreenFill))+ Row(Modifier.fillMaxWidth().height(tall.dp).padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {+ Text(label, color = Ink, fontSize = 17.sp, maxLines = 1, modifier = Modifier.weight(1f))+ Text(value, color = Ink, fontSize = 17.sp, maxLines = 1)+ }+ }+ }+}++/** The author: a photo (tap for another), "Made by" and the name, and a signature drawn on a line. */+@Composable+private fun AboutCard(photo: ImageBitmap?, author: String, onAuthor: (String) -> Unit, onPhoto: () -> Unit, signature: MutableList<List<Offset>>) {+ Box(Modifier.fillMaxWidth().height(300.dp).clip(RoundedCornerShape(CardCorner)).background(CardFill)) {+ Box(+ Modifier.align(Alignment.TopCenter).padding(top = 30.dp).size(97.dp).clip(CircleShape).background(PhotoFill).clickable(onClick = onPhoto),+ contentAlignment = Alignment.Center,+ ) {+ if (photo != null) Image(photo, contentDescription = "Author photo", contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())+ else Icon(PcIcons.Person, contentDescription = "Add a photo", tint = PhotoGlyph, modifier = Modifier.size(48.dp))+ }+ Row(Modifier.align(Alignment.TopCenter).padding(top = 146.dp), verticalAlignment = Alignment.Bottom) {+ Text("Made by ", color = Ink, fontSize = 21.sp)+ Box {+ if (author.isEmpty()) Text("Name", color = Placeholder, fontSize = 21.sp)+ BasicTextField(+ author,+ onAuthor,+ singleLine = true,+ textStyle = TextStyle(color = Ink, fontSize = 21.sp),+ cursorBrush = SolidColor(Color.White),+ modifier = Modifier.width(if (author.isEmpty()) 60.dp else (author.length * 12 + 16).coerceAtMost(260).dp),+ )+ }+ }+ // the signature: drawn with a finger or pen over the dashed line+ Box(Modifier.align(Alignment.TopCenter).padding(top = 180.dp).size(401.dp, 121.dp)) {+ Canvas(+ Modifier.fillMaxSize().pointerInput(Unit) {+ awaitEachGesture {+ val down = awaitFirstDown()+ down.consume()+ val line = mutableListOf(Offset(down.position.x / size.width, down.position.y / size.height))+ signature.add(line.toList())+ while (true) {+ val c = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break+ if (!c.pressed) break+ line.add(Offset(c.position.x / size.width, c.position.y / size.height))+ signature[signature.size - 1] = line.toList()+ c.consume()+ }+ }+ },+ ) {+ val lineY = 82.dp.toPx()+ val from = (size.width - 305.dp.toPx()) / 2f+ drawLine(SignLine, Offset(from, lineY), Offset(from + 305.dp.toPx(), lineY), 1.5.dp.toPx(), pathEffect = PathEffect.dashPathEffect(floatArrayOf(3.dp.toPx(), 4.dp.toPx())))+ for (stroke in signature) {+ val path = Path()+ stroke.forEachIndexed { i, p -> if (i == 0) path.moveTo(p.x * size.width, p.y * size.height) else path.lineTo(p.x * size.width, p.y * size.height) }+ drawPath(path, Ink, style = Stroke(2.dp.toPx(), cap = StrokeCap.Round, join = StrokeJoin.Round))+ }+ }+ Text("Sign here", color = PhotoGlyph, fontSize = 11.sp, modifier = Modifier.offset(x = 50.dp, y = 90.dp))+ // always there, at the line's end+ Box(Modifier.offset(x = 330.dp, y = 58.dp).size(22.dp).clip(CircleShape).background(PhotoGlyph).clickable { signature.clear() }, contentAlignment = Alignment.Center) {+ Icon(PcIcons.Cross, contentDescription = "Clear the signature", tint = CardFill, modifier = Modifier.size(14.dp))+ }+ }+ }+}++private fun dateText(ms: Long): String =+ DateFormat.getDateInstance(DateFormat.LONG).format(Date(ms)) + " at " + DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(ms))++private fun megabytes(bytes: Long) = "%.2f MB".format(bytes / 1_000_000.0)++/** The signature kept in an artwork's about folder: strokes of points across its box, 0..1. */+private fun readSignature(about: File?): List<List<Offset>> = runCatching {+ val strokes = JSONArray(File(about, "signature.json").readText())+ List(strokes.length()) { i ->+ val pts = strokes.getJSONArray(i)+ List(pts.length() / 2) { j -> Offset(pts.getDouble(j * 2).toFloat(), pts.getDouble(j * 2 + 1).toFloat()) }+ }+}.getOrDefault(emptyList())++private fun writeSignature(about: File, strokes: List<List<Offset>>) {+ val out = JSONArray()+ for (s in strokes) out.put(JSONArray().apply { s.forEach { put(it.x.toDouble()); put(it.y.toDouble()) } })+ runCatching { File(about, "signature.json").writeText(out.toString()) }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Chrome.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Chrome.ktnew file mode 100644index 0000000..fc55309--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Chrome.kt@@ -0,0 +1,422 @@+package io.github.artcraftandroid.procraft.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.wrapContentSize+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.ui.input.pointer.AwaitPointerEventScope+import androidx.compose.foundation.layout.wrapContentHeight+import kotlinx.coroutines.withTimeoutOrNull+import kotlin.math.roundToInt+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.gestures.waitForUpOrCancellation+import androidx.compose.foundation.interaction.MutableInteractionSource+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.composed+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.drawBehind+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.RoundRect+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.lerp+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.PathFillType+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import io.github.artcraftandroid.procraft.canvas.Panel+import io.github.artcraftandroid.procraft.core.ToolKind++private val SliderLeft = 5.dp+private val SizeTrackTop = 6.dp+private val OpacityTrackTop = 248.dp++/** A tap target without a ripple: the bars show their state through colour alone. */+private fun Modifier.tap(enabled: Boolean = true, onClick: () -> Unit): Modifier = composed {+ clickable(remember { MutableInteractionSource() }, indication = null, enabled = enabled, onClick = onClick)+}++/** The bar across the top of the canvas: artwork actions on the left, painting tools on the right. */+@Composable+fun TopBar(vm: CanvasViewModel, modifier: Modifier = Modifier) {+ BoxWithConstraints(modifier.fillMaxWidth().height(Pc.BarHeight).background(Pc.Bar)) {+ val (toolGap, actionGap) = Pc.barGaps(maxWidth)+ Row(+ Modifier.align(Alignment.CenterStart).padding(start = Pc.BarMargin),+ horizontalArrangement = Arrangement.spacedBy(actionGap),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Box(Modifier.size(Pc.GalleryWidth, Pc.BarButtonHeight).tap { vm.closeArtwork() }, contentAlignment = Alignment.CenterStart) {+ Text("Gallery", color = Pc.BarText, fontSize = 18.sp, fontWeight = FontWeight.Medium, maxLines = 1, softWrap = false, modifier = Modifier.offset(y = (-1).dp))+ }+ ActionButton(PcIcons.Actions, "Actions", selected = vm.panel == Panel.ACTIONS) { vm.toggle(Panel.ACTIONS) }+ ActionButton(PcIcons.Adjustments, "Adjustments", selected = vm.panel == Panel.ADJUSTMENTS || vm.adjustment != null) { vm.adjustmentsPressed() }+ ActionButton(PcIcons.Selection, "Selection", selected = vm.selecting, glyph = 33.dp) { vm.toggleSelecting() }+ ActionButton(PcIcons.Transform, "Transform", selected = vm.transforming, glyph = 44.dp) { vm.toggleTransform() }+ }+ // the layers and colour panels take the highlight from the current tool while open+ val panelOpen = vm.panel == Panel.LAYERS || vm.panel == Panel.COLOR || vm.transforming || vm.selecting || vm.adjustment != null+ Row(+ Modifier.align(Alignment.CenterEnd).padding(end = Pc.BarMargin),+ horizontalArrangement = Arrangement.spacedBy(toolGap),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ // painting an adjustment on (or cloning), the brush shows it+ ToolButton(+ if (vm.adjustPencil) PcIcons.BrushPaintedOn else PcIcons.Brush,+ "Paint",+ selected = vm.adjustPencil || (!panelOpen && vm.tool == ToolKind.PAINT),+ onHold = { vm.toolHeld(ToolKind.PAINT) },+ ) {+ vm.toolPressed(ToolKind.PAINT)+ }+ ToolButton(PcIcons.Smudge, "Smudge", selected = !panelOpen && vm.tool == ToolKind.SMUDGE, onHold = { vm.toolHeld(ToolKind.SMUDGE) }) {+ vm.toolPressed(ToolKind.SMUDGE)+ }+ ToolButton(PcIcons.Erase, "Erase", selected = !panelOpen && vm.tool == ToolKind.ERASE, onHold = { vm.toolHeld(ToolKind.ERASE) }) {+ vm.toolPressed(ToolKind.ERASE)+ }+ ToolButton(PcIcons.Layers, "Layers", selected = vm.panel == Panel.LAYERS) { vm.toggle(Panel.LAYERS) }+ ColorButton(vm)+ }+ }+}++/** An action button: its glyph on a dark disc, which turns blue while its panel is open. */+@Composable+private fun ActionButton(icon: ImageVector, label: String, selected: Boolean = false, glyph: Dp = 36.dp, onClick: () -> Unit = {}) {+ val lit = animateHighlight(selected)+ Box(Modifier.size(Pc.BarButtonWidth, Pc.BarButtonHeight).tap(onClick = onClick), contentAlignment = Alignment.Center) {+ Box(Modifier.size(Pc.ActionDiscSize).clip(CircleShape).background(lerp(Pc.ActionDisc, Pc.BarGlyphSelected, lit)))+ // the glyphs are drawn in a 44 frame, shown [glyph] across (most 36)+ Icon(icon, contentDescription = label, tint = lerp(Pc.ActionGlyph, Color.White, lit), modifier = Modifier.requiredSize(glyph))+ }+}++/** A tap target that also does [onHold] when held instead. */+private fun Modifier.tapOrHold(onClick: () -> Unit, onHold: () -> Unit): Modifier = composed {+ val tap by rememberUpdatedState(onClick)+ val hold by rememberUpdatedState(onHold)+ pointerInput(Unit) { detectTapGestures(onLongPress = { hold() }, onTap = { tap() }) }+}++/** A tool button: tapped, the tool (or its brushes); held ([onHold]), it takes the current brush. */+@Composable+private fun ToolButton(icon: ImageVector, label: String, selected: Boolean, onHold: (() -> Unit)? = null, onClick: () -> Unit) {+ val touch = if (onHold != null) Modifier.tapOrHold(onClick, onHold) else Modifier.tap(onClick = onClick)+ Box(Modifier.size(Pc.BarButtonWidth, Pc.BarButtonHeight).then(touch), contentAlignment = Alignment.Center) {+ // a 44 frame shown as it is, over the 38 tall button+ Icon(icon, contentDescription = label, tint = lerp(Pc.BarGlyph, Pc.BarGlyphSelected, animateHighlight(selected)), modifier = Modifier.requiredSize(44.dp))+ }+}++@Composable+private fun ColorButton(vm: CanvasViewModel) {+ val rgb = vm.colorRgb()+ // ringed only where the colour would fade into the bar: dark ones on the dark bar, light ones+ // on the light bar+ val ringed = if (Pc.light) vm.brightness > LIGHT_RING_ABOVE else vm.brightness < DARK_RING_BELOW+ // held, the colour painted with before+ Box(Modifier.size(Pc.BarButtonWidth, Pc.BarButtonHeight).tapOrHold({ vm.toggle(Panel.COLOR) }, { vm.previousColor() }), contentAlignment = Alignment.Center) {+ val dot = Modifier.size(Pc.ColorDot).clip(CircleShape).background(CanvasSpace.color(rgb))+ Box(if (ringed) dot.border(1.dp, Pc.ColorRing, CircleShape) else dot)+ }+}++/** The colour button's brightness (HSB) under which it is ringed on the dark bar. */+private const val DARK_RING_BELOW = 0.35f++/** The colour button's brightness over which it is ringed on the light bar. */+private const val LIGHT_RING_ABOVE = 0.85f++/**+ * The side bar against the left edge (the right one, [right]-handed): brush size, the modify+ * button, opacity, undo and redo. On the right everything is mirrored but the glyphs.+ */+@Composable+fun SideBar(vm: CanvasViewModel, modifier: Modifier = Modifier, right: Boolean = false) {+ // a control's left edge, mirrored on the right+ fun x(left: Dp, width: Dp) = if (right) Pc.SideBarWidth - left - width else left+ Box(+ modifier.size(Pc.SideBarWidth, Pc.SideBarHeight)+ .drawBehind {+ // translucent, with windows where the slider tracks are: they show what is behind+ val r = Pc.SideBarCorner.toPx()+ val track = Size(Pc.SliderWidth.toPx(), Pc.SliderHeight.toPx())+ val trackR = CornerRadius(Pc.SliderCorner.toPx())+ val body = Path().apply {+ fillType = PathFillType.EvenOdd+ val (inner, outer) = CornerRadius.Zero to CornerRadius(r)+ addRoundRect(+ if (right) RoundRect(0f, 0f, size.width, size.height, outer, inner, inner, outer)+ else RoundRect(0f, 0f, size.width, size.height, inner, outer, outer, inner),+ )+ for (top in listOf(SizeTrackTop, OpacityTrackTop)) {+ val o = Offset(x(SliderLeft, Pc.SliderWidth).toPx(), top.toPx())+ addRoundRect(RoundRect(o.x, o.y, o.x + track.width, o.y + track.height, trackR))+ }+ }+ drawPath(body, Pc.SideBar)+ },+ ) {+ BrushSlider(vm.size, vm::changeSize, Modifier.offset(x(SliderLeft, Pc.SliderWidth), SizeTrackTop), panel(vm, CanvasViewModel.SliderPanel.SIZE), vm.sizeNotches)+ // the modify button: the next touch on the canvas picks a colour+ Box(+ Modifier.offset(x(5.dp, 40.dp), 191.dp).size(40.dp, 41.dp).pointerInput(Unit) {+ // held, it changes what a canvas touch does; tapped, it does what Tap □ is set to+ awaitEachGesture {+ awaitFirstDown().consume()+ vm.modifyPressed()+ val up = waitForUpOrCancellation()+ up?.consume()+ vm.modifyReleased(cancelled = up == null)+ }+ },+ contentAlignment = Alignment.Center,+ ) {+ Box(+ Modifier.size(Pc.ModifySize).drawBehind {+ val w = Pc.ModifyStroke.toPx()+ drawRoundRect(+ if (vm.pickNext) Pc.Accent else Pc.SideGlyph,+ topLeft = Offset(w / 2f, w / 2f),+ size = Size(size.width - w, size.height - w),+ cornerRadius = CornerRadius(Pc.ModifyCorner.toPx() - w / 2f),+ style = Stroke(w),+ )+ },+ )+ }+ BrushSlider(vm.opacity, vm::changeOpacity, Modifier.offset(x(SliderLeft, Pc.SliderWidth), OpacityTrackTop), panel(vm, CanvasViewModel.SliderPanel.OPACITY), vm.opacityNotches)+ // beside the slider it belongs to, a little above it, outside the bar+ vm.sliderPanel?.let { which ->+ val top = if (which == CanvasViewModel.SliderPanel.SIZE) SizeTrackTop else OpacityTrackTop+ SliderPanel(vm, which, Modifier.offset(x(SliderLeft + Pc.SliderWidth + SliderPanelGap, SliderPanelSide), top - SliderPanelRise))+ }+ SideButton(PcIcons.Undo, "Undo", vm.canUndo, Modifier.offset(x(5.dp, 40.dp), 430.5.dp)) { vm.undo() }+ SideButton(PcIcons.Redo, "Redo", vm.canRedo, Modifier.offset(x(5.dp, 40.dp), 472.5.dp)) { vm.redo() }+ }+}++@Composable+private fun SideButton(icon: ImageVector, label: String, enabled: Boolean, modifier: Modifier, onClick: () -> Unit) {+ Box(modifier.size(40.dp, 41.dp).tap(enabled, onClick), contentAlignment = Alignment.Center) {+ // a 50 frame shown 36 across+ Icon(icon, contentDescription = label, tint = if (enabled) Pc.SideGlyph else Pc.SideGlyphDisabled, modifier = Modifier.requiredSize(36.dp))+ }+}++/** What a slider's panel does: shown while it is dragged ([held] false), kept up when it is held still. */+class SliderPanelHooks(val show: (held: Boolean) -> Unit, val hide: () -> Unit)++private fun panel(vm: CanvasViewModel, which: CanvasViewModel.SliderPanel) = SliderPanelHooks(+ show = { held ->+ vm.sliderPanel = which+ vm.sliderPanelKept = held+ },+ hide = { if (!vm.sliderPanelKept) vm.sliderPanel = null },+)++private val SliderPanelSide = 190.dp+private val SliderPanelGap = 8.dp+private val SliderPanelRise = 10.dp+// dark glass over the canvas (what is behind it blurred), or light+private val SliderPanelFill get() = if (Pc.light) Color(0xFFE7E7E7) else Color(0xC93E3E3E)+private val SliderPanelInk get() = if (Pc.light) Color(0xFF393939) else Color(0xFFF0F0F0)+// the dot is drawn in the interface's ink, not the brush's colour+private val SliderPanelDot get() = if (Pc.light) Color.Black else Color.White++/**+ * A slider's panel: its name and value ("Size 8%"), a button saving the value as a notch on the+ * slider ("+"; "-" takes away the notch it is on), and in the middle a dot of the brush as it+ * would paint now, its size on the screen (and at its opacity).+ */+@Composable+private fun SliderPanel(vm: CanvasViewModel, which: CanvasViewModel.SliderPanel, modifier: Modifier) {+ val size = which == CanvasViewModel.SliderPanel.SIZE+ val value = if (size) vm.size else vm.opacity+ val diameter = androidx.compose.runtime.remember(vm.size) { vm.brushScreenDiameter() }+ // its own size, past the bar's edge (the bar's width would otherwise squeeze it)+ Box(+ modifier.wrapContentSize(Alignment.TopStart, unbounded = true).size(SliderPanelSide)+ .then(if (Pc.light) Modifier else rememberFrost(22.dp))+ .clip(RoundedCornerShape(22.dp)).background(SliderPanelFill),+ ) {+ Text(+ androidx.compose.ui.text.buildAnnotatedString {+ pushStyle(androidx.compose.ui.text.SpanStyle(fontWeight = FontWeight.Bold))+ append(if (size) "Size" else "Opacity")+ pop()+ append(" ${(value * 100f).roundToInt()}%")+ },+ color = SliderPanelInk,+ fontSize = 19.sp,+ maxLines = 1,+ modifier = Modifier.offset(16.dp, 6.dp).height(32.dp).wrapContentHeight(Alignment.CenterVertically),+ )+ val onNotch = vm.notchAt(size, value) != null+ if (onNotch || vm.canSaveNotch(size)) {+ Box(Modifier.offset(150.dp, 6.dp).size(32.dp).tap { vm.toggleNotch(size) }, contentAlignment = Alignment.Center) {+ Icon(+ if (onNotch) PcIcons.NotchRemove else PcIcons.NotchAdd,+ contentDescription = if (onNotch) "Remove" else "Save",+ tint = SliderPanelInk,+ modifier = Modifier.size(24.dp),+ )+ }+ }+ androidx.compose.foundation.Canvas(Modifier.fillMaxSize()) {+ val r = (diameter / 2f).coerceIn(1.5f, this.size.minDimension / 2f - 8.dp.toPx())+ drawCircle(SliderPanelDot.copy(alpha = if (size) 1f else value.coerceIn(0.02f, 1f)), r, center)+ }+ }+}++/**+ * An upright slider moved by dragging anywhere on it: the thumb follows the finger (relative,+ * not jump-to-touch), 1 at the top. Moved, its [panel] shows while it moves; held still, it stays up.+ * Its [notches] (saved values) show as marks on the track; a value dragged near one is pulled onto+ * it, and a tap on one goes there. On a notch, the thumb shows a blue bar.+ */+@Composable+fun BrushSlider(value: Float, onChange: (Float) -> Unit, modifier: Modifier = Modifier, panel: SliderPanelHooks? = null, notches: List<Float> = emptyList()) {+ val current by rememberUpdatedState(value)+ val change by rememberUpdatedState(onChange)+ val hooks by rememberUpdatedState(panel)+ val marks by rememberUpdatedState(notches)+ fun near(v: Float, reach: Float = CanvasViewModel.NOTCH_NEAR) =+ marks.filter { kotlin.math.abs(it - v) < reach }.minByOrNull { kotlin.math.abs(it - v) }+ Box(+ modifier.size(Pc.SliderWidth, Pc.SliderHeight)+ .pointerInput(Unit) {+ val travel = (Pc.SliderHeight - Pc.ThumbHeight - Pc.ThumbInset * 2).toPx()+ awaitEachGesture {+ val down = awaitFirstDown()+ down.consume()+ var last = down.position.y+ var moved = false+ var lifted = false+ // where the finger has taken it, before a notch pulls it in+ var raw = current+ // follows the finger; false once it is lifted+ suspend fun AwaitPointerEventScope.follow(): Boolean {+ val c = awaitPointerEvent().changes.firstOrNull { it.id == down.id }+ if (c == null || !c.pressed) return false+ val dy = c.position.y - last+ if (dy != 0f) {+ if (!moved) hooks?.show(false)+ moved = true+ last = c.position.y+ raw = (raw - dy / travel).coerceIn(0f, 1f)+ change(near(raw) ?: raw)+ }+ c.consume()+ return true+ }+ withTimeoutOrNull(viewConfiguration.longPressTimeoutMillis) {+ while (!lifted && !moved) lifted = !follow()+ }+ if (!lifted && !moved) hooks?.show(true)+ // a tap on a notch's mark goes to it+ if (lifted && !moved) {+ val inset = Pc.ThumbInset.toPx()+ val at = 1f - (down.position.y - inset - Pc.ThumbHeight.toPx() / 2f) / travel+ near(at, Pc.ThumbHeight.toPx() / 2f / travel)?.let { change(it) }+ }+ while (!lifted) lifted = !follow()+ if (moved) hooks?.hide()+ }+ }+ .drawBehind {+ val inset = Pc.ThumbInset.toPx()+ val thumb = Size(Pc.ThumbWidth.toPx(), Pc.ThumbHeight.toPx())+ val at = Offset((size.width - thumb.width) / 2f, inset + (size.height - thumb.height - inset * 2) * (1f - value))+ val knob = RoundRect(at.x, at.y, at.x + thumb.width, at.y + thumb.height, CornerRadius(thumb.height / 2f))+ // the track has a window where the thumb is, so the thumb shows over the bar alone+ val track = Path().apply {+ fillType = PathFillType.EvenOdd+ addRoundRect(RoundRect(0f, 0f, size.width, size.height, CornerRadius(Pc.SliderCorner.toPx())))+ addRoundRect(knob)+ }+ drawPath(track, Pc.SliderTrack)+ // the notches: short bars across the track; on one, the thumb shows a blue bar+ val bar = Size(NotchWidth.toPx(), NotchHeight.toPx())+ val travel = size.height - thumb.height - inset * 2+ for (n in notches) {+ val y = inset + thumb.height / 2f + travel * (1f - n)+ drawRoundRect(NotchMark, Offset((size.width - bar.width) / 2f, y - bar.height / 2f), bar, CornerRadius(bar.height / 2f))+ }+ drawPath(Path().apply { addRoundRect(knob) }, Pc.SliderThumb)+ if (notches.any { kotlin.math.abs(it - value) < 1e-4f }) {+ drawRoundRect(Pc.Accent, Offset((size.width - bar.width) / 2f, at.y + (thumb.height - bar.height) / 2f), bar, CornerRadius(bar.height / 2f))+ }+ },+ )+}++private val NotchWidth = 20.dp+private val NotchHeight = 4.dp+private val NotchMark = Color(0x1AFFFFFF)++/** The brush's outline where the pen paints or hovers: a thin grey ring with a light edge. */+@Composable+fun BrushCursor(vm: CanvasViewModel) {+ val at = vm.cursorAt ?: return+ val r = vm.cursorRadius+ if (r < 2f) return+ val style = vm.cursorStyle+ val paint = CanvasSpace.color(vm.colorRgb())+ androidx.compose.foundation.Canvas(Modifier.fillMaxSize()) {+ when (style) {+ CanvasViewModel.CursorStyle.CONTRAST -> {+ drawCircle(Color.White, r, at, style = Stroke(3.dp.toPx()))+ drawCircle(Color.Black, r, at, style = Stroke(1.dp.toPx()))+ }+ CanvasViewModel.CursorStyle.COLOR -> {+ drawCircle(Color(0x99FFFFFF), r, at, style = Stroke(3.dp.toPx()))+ drawCircle(paint, r, at, style = Stroke(1.5.dp.toPx()))+ }+ // as the brush says: none, contrasting rings, or the colour+ CanvasViewModel.CursorStyle.BRUSH -> when (vm.cursorOutline) {+ 0 -> Unit+ 2 -> {+ drawCircle(Color(0x99FFFFFF), r, at, style = Stroke(3.dp.toPx()))+ drawCircle(paint, r, at, style = Stroke(1.5.dp.toPx()))+ }+ else -> {+ drawCircle(Color.White, r, at, style = Stroke(3.dp.toPx()))+ drawCircle(Color.Black, r, at, style = Stroke(1.dp.toPx()))+ }+ }+ }+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ColorPanel.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ColorPanel.ktnew file mode 100644index 0000000..2ab4bd1--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ColorPanel.kt@@ -0,0 +1,1302 @@+package io.github.artcraftandroid.procraft.ui++import android.graphics.BlurMaskFilter+import androidx.compose.foundation.ExperimentalFoundationApi+import androidx.compose.foundation.background+import androidx.compose.foundation.combinedClickable+import androidx.compose.foundation.border+import androidx.compose.foundation.interaction.collectIsPressedAsState+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.itemsIndexed+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.drawBehind+import androidx.compose.ui.draw.drawWithContent+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.graphics.Paint+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.graphics.drawscope.drawIntoCanvas+import androidx.compose.ui.graphics.lerp+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.input.pointer.PointerInputScope+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.window.Popup+import androidx.compose.ui.window.PopupProperties+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.IntOffset+import kotlinx.coroutines.launch+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import io.github.artcraftandroid.procraft.canvas.ColorMode+import io.github.artcraftandroid.procraft.canvas.HarmonyKind+import io.github.artcraftandroid.procraft.gallery.Palette+import kotlin.math.PI+import kotlin.math.atan2+import kotlin.math.cos+import kotlin.math.max+import kotlin.math.pow+import kotlin.math.roundToInt+import kotlin.math.sin+import kotlin.math.sqrt++private val PanelWidth = 376.dp++/** Screens shorter than this (landscape) get the short colour panel: no history, the rest tighter. */+private val ShortScreen = 900.dp++/**+ * Short, the classic square takes the height left over: the screen less the bar and arrow (56),+ * the header (64), the sliders (108), the palette (142), the tabs (70) and a 25 margin.+ */+private val ShortClassicRest = 465.dp+private val RingOuter = 182.dp+private val RingInner = 124.dp+private val DiscRadius = 105.dp+private val HarmonyRadius = 149.dp++/**+ * The hue controls are not linear in hue. These are the hues (degrees) at evenly spaced points+ * along each, measured; positions between them interpolate. The classic slider has 25, the+ * disc's ring 49 (every 7.5 degrees, anticlockwise from the right).+ */+private val SliderHues = floatArrayOf(+ 0f, 0.2f, 8f, 17.7f, 27.3f, 36.4f, 44.2f, 52.7f, 80.4f, 112.8f, 120.5f, 120.5f, 133.3f,+ 154.3f, 178.2f, 196.1f, 211.1f, 226.1f, 241.1f, 259.7f, 275.1f, 291.7f, 310f, 340.2f, 360f,+)+private val RingHues = floatArrayOf(+ 0f, 0.2f, 0.2f, 0.2f, 4.5f, 13.2f, 18.9f, 23.7f, 27.9f, 32.4f, 36.4f, 40.9f, 44.6f, 49.1f,+ 53.1f, 57.2f, 61.4f, 74.2f, 88.6f, 114.8f, 120.5f, 120.5f, 120.5f, 120.5f, 134.8f, 149.9f,+ 162.2f, 173.4f, 180f, 186.9f, 195.4f, 203.4f, 211.4f, 219.4f, 227.5f, 235.3f, 242.1f, 251.1f,+ 258.5f, 268f, 276.5f, 285.3f, 293.6f, 300.2f, 303.3f, 318.2f, 333.7f, 351.2f, 360f,+)++/** The hue (0..1) at [position] (0..1) along a control whose hues are [stops]. */+private fun hueAt(stops: FloatArray, position: Float): Float {+ val p = position.coerceIn(0f, 1f) * (stops.size - 1)+ val i = p.toInt().coerceAtMost(stops.size - 2)+ return (stops[i] + (stops[i + 1] - stops[i]) * (p - i)) / 360f+}++/** Where [hue] (0..1) sits (0..1) along a control whose hues are [stops]. */+private fun huePosition(stops: FloatArray, hue: Float): Float {+ val h = hue.coerceIn(0f, 1f) * 360f+ for (i in 0 until stops.size - 1) {+ val a = stops[i]+ val b = stops[i + 1]+ if (h <= b && b > a) return (i + ((h - a) / (b - a)).coerceIn(0f, 1f)) / (stops.size - 1)+ }+ return 1f+}++private fun rgbColor(rgb: Int) = CanvasSpace.color(rgb)++/**+ * [colours] all in one colour space (the first that isn't sRGB, if any): a gradient's colours+ * must share one, and canvas colours may be Display P3 beside the panel's own sRGB greys.+ */+private fun oneSpace(colours: List<Color>): List<Color> {+ val space = colours.firstOrNull { it.colorSpace != androidx.compose.ui.graphics.colorspace.ColorSpaces.Srgb }?.colorSpace ?: return colours+ return colours.map { it.convert(space) }+}++private fun hsvColor(h: Float, s: Float, v: Float) = rgbColor(CanvasViewModel.hsvToRgb(h, s, v))++/** A colour the pickers show and change: the one painted with, or one of its own (a background). */+interface ColorPick {+ val hue: Float+ val saturation: Float+ val brightness: Float+ fun rgb(): Int+ fun setHsv(h: Float, s: Float, v: Float)+ fun setRgb(rgb: Int)+}++/** The colour painted with. */+private class BrushColor(private val vm: CanvasViewModel) : ColorPick {+ override val hue get() = vm.hue+ override val saturation get() = vm.saturation+ override val brightness get() = vm.brightness+ override fun rgb() = vm.colorRgb()+ override fun setHsv(h: Float, s: Float, v: Float) = vm.setColor(h, s, v)+ override fun setRgb(rgb: Int) = vm.setRgb(rgb)+}++/** A colour of its own, starting at [rgb]; [onChange] hears every change. Greys keep their hue. */+class HeldColor(rgb: Int, private val onChange: (Int) -> Unit) : ColorPick {+ override var hue by mutableFloatStateOf(0f)+ private set+ override var saturation by mutableFloatStateOf(0f)+ private set+ override var brightness by mutableFloatStateOf(0f)+ private set++ init {+ take(rgb)+ }++ private fun take(rgb: Int) {+ val hsv = FloatArray(3)+ android.graphics.Color.RGBToHSV((rgb shr 16) and 0xFF, (rgb shr 8) and 0xFF, rgb and 0xFF, hsv)+ if (hsv[1] > 0f) hue = hsv[0] / 360f+ saturation = hsv[1]+ brightness = hsv[2]+ }++ override fun rgb() = CanvasViewModel.hsvToRgb(hue, saturation, brightness)++ override fun setHsv(h: Float, s: Float, v: Float) {+ hue = h.coerceIn(0f, 1f)+ saturation = s.coerceIn(0f, 1f)+ brightness = v.coerceIn(0f, 1f)+ onChange(rgb())+ }++ override fun setRgb(rgb: Int) {+ take(rgb)+ onChange(rgb)+ }+}++/**+ * The colour panel: the current and second colours, a picker per mode, the history and the mode+ * tabs. With [background] it sets the canvas's background colour instead, titled so, with a tick+ * that closes it. On a screen less than [ShortScreen] tall it leaves the history out and tightens+ * the pickers to fit.+ */+@Composable+fun ColorPanel(vm: CanvasViewModel, arrowX: Dp, screenHeight: Dp, modifier: Modifier = Modifier, background: Boolean = false) {+ val short = screenHeight < ShortScreen+ // short, the disc reaches up into the header's last 7+ val headerHeight = if (short && vm.colorMode == ColorMode.DISC) 57.dp else 64.dp+ val c: ColorPick = if (background) {+ remember { HeldColor(vm.backgroundRgb()) { vm.setBackgroundRgb(it, done = false) } }+ } else {+ remember(vm) { BrushColor(vm) }+ }+ Popover(PanelWidth, arrowX, modifier) {+ Box {+ if (background) {+ PanelHeader("Background", start = 20.dp, end = 12.dp, height = headerHeight, chevron = false) {+ Box(+ Modifier.padding(top = 19.dp).size(44.dp).clip(CircleShape).background(Pc.Accent).clickable { vm.endBackgroundPick() },+ contentAlignment = Alignment.Center,+ ) {+ Icon(PcIcons.DoneTick, contentDescription = "Done", tint = Color.White, modifier = Modifier.requiredSize(40.dp))+ }+ }+ } else if (vm.colorMode == ColorMode.PALETTES) {+ PanelHeader("Palettes", start = 20.dp, end = 17.dp, chevron = false) { NewPaletteButton(vm) }+ } else PanelHeader("Colors", start = 20.dp, end = 20.dp, height = headerHeight, chevron = false) {+ Row(Modifier.padding(top = 21.5.dp), horizontalArrangement = Arrangement.spacedBy(7.dp)) {+ val swatch = Modifier.size(43.dp, 25.dp).clip(RoundedCornerShape(6.dp))+ Box(swatch.background(rgbColor(vm.colorRgb())).border(1.dp, Pc.SwatchEdge, RoundedCornerShape(6.dp)))+ Box(swatch.background(rgbColor(vm.secondaryRgb)).clickable { vm.swapColors() })+ }+ }+ Box(Modifier.align(Alignment.TopCenter).padding(top = 4.dp).size(40.dp, 4.dp).clip(CircleShape).background(Pc.Grabber))+ if (vm.colorMode == ColorMode.HARMONY) HarmonyKindButton(vm)+ }+ // the other modes come one by one; until then they show the classic picker+ when (vm.colorMode) {+ ColorMode.DISC -> Disc(c, short = short)+ ColorMode.VALUE -> Value(c, short = short, inks = vm.inks)+ ColorMode.HARMONY -> Harmony(vm, c, short = short)+ ColorMode.PALETTES -> Palettes(vm, c, short)+ else -> Classic(c, square = if (short) (screenHeight - ShortClassicRest).coerceIn(150.dp, 344.dp) else 344.dp)+ }+ if (vm.colorMode != ColorMode.PALETTES && short) {+ ShortBottom(vm, c)+ } else if (vm.colorMode != ColorMode.PALETTES) {+ History(vm, c)+ vm.palettes.getOrNull(vm.defaultPalette)?.let { p ->+ Box(Modifier.fillMaxWidth().height(if (short) 34.dp else 44.dp)) {+ Text(p.name, color = Pc.PanelTitle, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, modifier = Modifier.padding(start = 21.dp, top = if (short) 8.dp else 13.dp))+ }+ SwatchGrid(vm, c, vm.defaultPalette, p, Modifier.padding(horizontal = 8.dp))+ }+ }+ ModeTabs(vm)+ }+}++private val CompactWidth = 260.dp+/** How wide the compact colour picker is, for placing it. */+internal val CompactColorsWidth get() = CompactWidth+private val CompactFill = Color(0xFF1E1E1E)+private val CompactGroup = Color(0xFF292929)+private val CompactHexField = Color(0xFF343434)++/**+ * The compact colour picker other screens open (Custom Canvas's background): "Colors", a picker+ * per mode and the mode tabs as icons, 260 wide; no swatches, history or palette.+ */+@Composable+fun CompactColors(vm: CanvasViewModel, c: ColorPick, arrowX: Dp, modifier: Modifier = Modifier, side: ArrowSide = ArrowSide.TOP) {+ var mode by remember { mutableStateOf(ColorMode.DISC) }+ Popover(CompactWidth, arrowX, modifier, fill = CompactFill, side = side) {+ Text("Colors", color = Pc.PanelTitle, fontSize = 24.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 18.dp, top = 9.dp, bottom = 5.dp))+ when (mode) {+ ColorMode.DISC -> Disc(c, compact = true)+ ColorMode.VALUE -> Value(c, compact = true)+ ColorMode.HARMONY -> Harmony(vm, c, compact = true)+ ColorMode.PALETTES -> CompactPalettes(vm, c)+ else -> Classic(c, compact = true)+ }+ Row(Modifier.fillMaxWidth().height(52.dp)) {+ for ((m, icon, label) in Modes) {+ Box(Modifier.weight(1f).fillMaxSize().clickable { mode = m }, contentAlignment = Alignment.Center) {+ // the tabs' 36-unit glyphs, a little smaller here+ Icon(icon, contentDescription = label, tint = if (m == mode) Pc.Accent else Pc.PanelTitle, modifier = Modifier.requiredSize(33.dp))+ }+ }+ }+ }+}++/** The palettes' swatches, one grid after another, a tap taking a colour. */+@Composable+private fun CompactPalettes(vm: CanvasViewModel, c: ColorPick) {+ LazyColumn(+ Modifier.fillMaxWidth().height(240.dp),+ contentPadding = PaddingValues(horizontal = 10.dp, vertical = 4.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp),+ ) {+ itemsIndexed(vm.palettes) { _, p ->+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))) {+ for (row in 0 until 3) {+ Row {+ for (col in 0 until 10) {+ val rgb = p.colors[row * 10 + col]+ Box(+ Modifier.weight(1f).height(24.dp).background(if (rgb != null) rgbColor(rgb) else Pc.EmptySlot)+ .then(if (rgb != null) Modifier.clickable { c.setRgb(rgb) } else Modifier),+ )+ }+ }+ }+ }+ }+ }+}++@Composable+private fun Classic(c: ColorPick, compact: Boolean = false, square: Dp = 344.dp) {+ SaturationBrightness(c, compact, square)+ if (compact) {+ // the hue only, 240 wide under the 248 square+ Box(Modifier.padding(start = 10.dp, end = 10.dp).height(40.dp)) {+ SliderRow(huePosition(SliderHues, c.hue), SliderHues.map { hsvColor(it / 360f, 1f, 1f) }) { c.setHsv(hueAt(SliderHues, it), c.saturation, c.brightness) }+ }+ return+ }+ Column(Modifier.padding(horizontal = 20.dp)) {+ val pure = hsvColor(c.hue, 1f, 1f)+ SliderRow(huePosition(SliderHues, c.hue), SliderHues.map { hsvColor(it / 360f, 1f, 1f) }) { c.setHsv(hueAt(SliderHues, it), c.saturation, c.brightness) }+ SliderRow(c.saturation, listOf(Pc.SaturationGrey, pure)) { c.setHsv(c.hue, it, c.brightness) }+ SliderRow(c.brightness, listOf(Color.Black, hsvColor(c.hue, c.saturation, 1f))) { c.setHsv(c.hue, c.saturation, it) }+ }+}++/** Square (saturation across, brightness up, both -1..1 with y down) to disc, by the elliptical grid map. */+private fun squareToDisc(x: Float, y: Float): Offset = Offset(x * sqrt(1f - y * y / 2f), y * sqrt(1f - x * x / 2f))++/** The inverse of [squareToDisc]. */+private fun discToSquare(u: Float, v: Float): Offset {+ val r2 = 2f * sqrt(2f)+ fun half(a: Float, b: Float, s: Float) = 0.5f * sqrt(max(0f, 2f + a * a - b * b + r2 * s)) - 0.5f * sqrt(max(0f, 2f + a * a - b * b - r2 * s))+ return Offset(half(u, v, u).coerceIn(-1f, 1f), half(v, u, v).coerceIn(-1f, 1f))+}++/** The saturation/brightness disc for [hue], [side] pixels square, with a soft edge. */+private fun discImage(hue: Float, side: Int): ImageBitmap {+ val pixels = IntArray(side * side)+ val hsv = floatArrayOf(hue * 360f, 0f, 0f)+ val half = side / 2f+ for (j in 0 until side) {+ for (i in 0 until side) {+ val u = (i + 0.5f) / half - 1f+ val v = (j + 0.5f) / half - 1f+ val edge = ((1f - sqrt(u * u + v * v)) * half + 0.5f).coerceIn(0f, 1f)+ if (edge <= 0f) continue+ val sq = discToSquare(u, v)+ hsv[1] = (sq.x + 1f) / 2f+ hsv[2] = (1f - sq.y) / 2f+ val rgb = android.graphics.Color.HSVToColor(hsv) and 0xFFFFFF+ pixels[j * side + i] = ((edge * 255f).toInt() shl 24) or rgb+ }+ }+ return CanvasSpace.tag(android.graphics.Bitmap.createBitmap(pixels, side, side, android.graphics.Bitmap.Config.ARGB_8888)).asImageBitmap()+}++/**+ * The disc picker, 364 square: a hue ring (radii 124 to 182, the hue scale running anticlockwise+ * from the right) around the saturation/brightness disc (radius 105).+ */+@Composable+private fun Disc(c: ColorPick, compact: Boolean = false, short: Boolean = false) {+ val hue by rememberUpdatedState(c.hue)+ val sat by rememberUpdatedState(c.saturation)+ val bri by rememberUpdatedState(c.brightness)+ val density = LocalDensity.current+ // compact, the whole picker is 240 across instead of 364+ val k = if (compact) 240f / 364f else 1f+ val discRadius = DiscRadius * k+ val ringInner = RingInner * k+ val ringOuter = RingOuter * k+ val disc = remember(c.hue, k) { discImage(c.hue, with(density) { (discRadius * 2).roundToPx() }) }+ val ring = remember {+ val stops = Array(RingHues.size) { i -> (1f - i / (RingHues.size - 1f)) to hsvColor(RingHues[i] / 360f, 1f, 1f) }+ Brush.sweepGradient(*stops.reversedArray())+ }+ Box(+ Modifier.then(+ when {+ compact -> Modifier.padding(start = 10.dp, top = 4.dp, bottom = 6.dp)+ short -> Modifier.padding(start = 6.dp, bottom = 3.dp)+ else -> Modifier.padding(start = 6.dp, top = 8.dp, bottom = 17.dp)+ },+ ).size(364.dp * k)+ .pointerInput(Unit) {+ awaitEachGesture {+ val down = awaitFirstDown()+ down.consume()+ val centre = Offset(size.width / 2f, size.height / 2f)+ val onRing = (down.position - centre).getDistance() > ((discRadius + ringInner) / 2).toPx()+ fun send(p: Offset) {+ val d = p - centre+ if (onRing) {+ val turn = (atan2(-d.y, d.x) / (2f * PI.toFloat()) + 1f) % 1f+ c.setHsv(hueAt(RingHues, turn), sat, bri)+ } else {+ val r = discRadius.toPx()+ var uv = Offset(d.x / r, d.y / r)+ val len = uv.getDistance()+ if (len > 1f) uv = Offset(uv.x / len, uv.y / len)+ val sq = discToSquare(uv.x, uv.y)+ c.setHsv(hue, (sq.x + 1f) / 2f, (1f - sq.y) / 2f)+ }+ }+ send(down.position)+ while (true) {+ val event = awaitPointerEvent()+ val ch = event.changes.firstOrNull { it.id == down.id } ?: break+ if (!ch.pressed) break+ send(ch.position)+ ch.consume()+ }+ }+ }+ .drawBehind {+ val o = center+ val inner = ringInner.toPx()+ val outer = ringOuter.toPx()+ drawCircle(ring, (inner + outer) / 2f, o, style = Stroke(outer - inner))+ val r = discRadius.toPx()+ drawImage(disc, topLeft = Offset(o.x - r, o.y - r))+ // the ring knob sits on the middle of the ring, where the hue is+ val turn = huePosition(RingHues, c.hue) * 2f * PI.toFloat()+ val mid = (inner + outer) / 2f+ knob(o + Offset(cos(turn) * mid, -sin(turn) * mid), 26.2.dp.toPx() * k, hsvColor(c.hue, 1f, 1f))+ val p = squareToDisc(c.saturation * 2f - 1f, 1f - c.brightness * 2f)+ knob(o + Offset(p.x * r, p.y * r), 10.75.dp.toPx(), rgbColor(c.rgb()))+ },+ )+}++/** A colour knob: [fill] inside a thin white ring, over a soft shadow. */+private fun DrawScope.knob(c: Offset, r: Float, fill: Color) {+ drawIntoCanvas { canvas ->+ val shadow = Paint().apply {+ color = Color(0x59000000)+ asFrameworkPaint().maskFilter = BlurMaskFilter(4.dp.toPx(), BlurMaskFilter.Blur.NORMAL)+ }+ canvas.drawCircle(c + Offset(0f, 2.dp.toPx()), r, shadow)+ }+ drawCircle(fill, r, c)+ drawCircle(Color.White, r - 0.6.dp.toPx(), c, style = Stroke(1.2.dp.toPx()))+}++@Composable+private fun SaturationBrightness(c: ColorPick, compact: Boolean, height: Dp = 344.dp) {+ val hue by rememberUpdatedState(c.hue)+ val pure = hsvColor(c.hue, 1f, 1f)+ val current = rgbColor(c.rgb())+ Box(+ Modifier.padding(horizontal = if (compact) 6.dp else 16.dp).size(if (compact) 248.dp else 344.dp, if (compact) 248.dp else height).drawWithContent {+ drawContent()+ // the knob may hang over the square's edge+ knob(Offset(c.saturation * size.width, (1f - c.brightness) * size.height), 10.75.dp.toPx(), current)+ },+ ) {+ Box(+ Modifier.fillMaxSize().clip(RoundedCornerShape(10.dp))+ .pointerInput(Unit) { track { x, y -> c.setHsv(hue, x, 1f - y) } }+ .drawBehind {+ drawRect(Brush.horizontalGradient(oneSpace(listOf(Color.White, pure))))+ drawRect(Brush.verticalGradient(listOf(Color.Transparent, Color.Black)))+ },+ )+ }+}++/**+ * A 36-tall slider row: a 4-dp track through [colours] and a pill showing the colour under it.+ * Touching anywhere on the row moves the pill there.+ */+@Composable+private fun SliderRow(value: Float, colours: List<Color>, onChange: (Float) -> Unit) {+ val change by rememberUpdatedState(onChange)+ Box(+ Modifier.fillMaxWidth().height(36.dp)+ .pointerInput(Unit) { track { x, _ -> change(x) } }+ .drawBehind {+ val trackH = 4.dp.toPx()+ val y = size.height / 2f+ drawRoundRect(Brush.horizontalGradient(oneSpace(colours)), Offset(0f, y - trackH / 2f), Size(size.width, trackH), CornerRadius(trackH / 2f))+ val pill = Size(16.dp.toPx(), 10.dp.toPx())+ val x = (value * size.width).coerceIn(pill.width / 2f, size.width - pill.width / 2f)+ drawRoundRect(colourAlong(colours, value), Offset(x - pill.width / 2f, y - pill.height / 2f), pill, CornerRadius(pill.height / 2f))+ },+ )+}++// The harmony disc is a hue/saturation wheel in Display P3: on an sRGB canvas its colours are+// turned into sRGB (clipped), on a P3 one they are taken as they are (both spaces use the sRGB+// transfer curve).+private fun toLinear(c: Float) = if (c <= 0.04045f) c / 12.92f else ((c + 0.055f) / 1.055f).pow(2.4f)++private fun toEncoded(c: Float) = if (c <= 0.0031308f) c * 12.92f else 1.055f * c.pow(1f / 2.4f) - 0.055f++/** P3 hue (0..1), saturation and value to a canvas colour (0xRRGGBB), clipped to sRGB on an sRGB canvas. */+private fun p3HsvToRgb(h: Float, s: Float, v: Float): Int {+ val p = CanvasViewModel.hsvToRgb(h, s, v)+ if (CanvasSpace.p3) return p+ val r = toLinear(((p shr 16) and 0xFF) / 255f)+ val g = toLinear(((p shr 8) and 0xFF) / 255f)+ val b = toLinear((p and 0xFF) / 255f)+ fun out(x: Float) = (toEncoded(x.coerceIn(0f, 1f)) * 255f).roundToInt()+ return (out(1.2249f * r - 0.2247f * g) shl 16) or (out(-0.0420f * r + 1.0419f * g) shl 8) or out(-0.0197f * r - 0.0786f * g + 1.0979f * b)+}++/** A canvas colour (0xRRGGBB) as P3 hue (0..1), saturation and value. */+private fun rgbToP3Hsv(rgb: Int): FloatArray {+ if (CanvasSpace.p3) {+ val hsv = FloatArray(3)+ android.graphics.Color.RGBToHSV((rgb shr 16) and 0xFF, (rgb shr 8) and 0xFF, rgb and 0xFF, hsv)+ return floatArrayOf(hsv[0] / 360f, hsv[1], hsv[2])+ }+ val r = toLinear(((rgb shr 16) and 0xFF) / 255f)+ val g = toLinear(((rgb shr 8) and 0xFF) / 255f)+ val b = toLinear((rgb and 0xFF) / 255f)+ fun enc(x: Float) = (toEncoded(x.coerceIn(0f, 1f)) * 255f).roundToInt()+ val hsv = FloatArray(3)+ android.graphics.Color.RGBToHSV(enc(0.8225f * r + 0.1774f * g), enc(0.0332f * r + 0.9669f * g), enc(0.0171f * r + 0.0724f * g + 0.9108f * b), hsv)+ return floatArrayOf(hsv[0] / 360f, hsv[1], hsv[2])+}++/** The harmony wheel at value [v], [side] pixels square: hue anticlockwise from the right, saturation outwards. */+private fun harmonyImage(v: Float, side: Int): ImageBitmap {+ val pixels = IntArray(side * side)+ val half = side / 2f+ for (j in 0 until side) {+ for (i in 0 until side) {+ val u = (i + 0.5f) / half - 1f+ val w = (j + 0.5f) / half - 1f+ val d = sqrt(u * u + w * w)+ val edge = ((1f - d) * half + 0.5f).coerceIn(0f, 1f)+ if (edge <= 0f) continue+ val h = (atan2(-w, u) / (2f * PI.toFloat()) + 1f) % 1f+ pixels[j * side + i] = ((edge * 255f).toInt() shl 24) or p3HsvToRgb(h, d.coerceAtMost(1f), v)+ }+ }+ return CanvasSpace.tag(android.graphics.Bitmap.createBitmap(pixels, side, side, android.graphics.Bitmap.Config.ARGB_8888)).asImageBitmap()+}++/** The harmony kind under the title; tapping it lists the kinds. */+@Composable+private fun HarmonyKindButton(vm: CanvasViewModel) {+ var open by remember { mutableStateOf(false) }+ Box(Modifier.padding(start = 20.dp, top = 50.dp).height(28.dp).clickable { open = true }, contentAlignment = Alignment.CenterStart) {+ Text(vm.harmonyKind.label, color = Pc.PanelTitle, fontSize = 17.sp)+ MenuPresence(open, androidx.compose.ui.graphics.TransformOrigin(1f, 0f)) { look ->+ // the menu opens to the left of the panel, its top level with the wheel+ Popup(offset = with(LocalDensity.current) { IntOffset((-204).dp.roundToPx(), 36.dp.roundToPx()) }, properties = PopupProperties(focusable = true), onDismissRequest = { open = false }) {+ Column(look.width(195.dp).clip(RoundedCornerShape(24.dp)).background(Pc.MenuFill).padding(vertical = 9.dp)) {+ for (kind in HarmonyKind.entries) {+ Row(+ Modifier.fillMaxWidth().height(38.dp).clickable {+ vm.harmonyKind = kind+ open = false+ }.padding(start = 20.dp, end = 18.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(kind.label, color = Color.White, fontSize = 17.sp, maxLines = 1, modifier = Modifier.weight(1f))+ if (kind == vm.harmonyKind) Icon(PcIcons.Tick, contentDescription = null, tint = Color.White, modifier = Modifier.size(18.dp))+ }+ }+ }+ }+ }+ }+}++/**+ * The harmony picker: a 298 dp wheel (hue around, saturation out, in Display P3) with a knob for+ * the colour and one for each companion of the harmony kind, and a brightness slider below.+ */+@Composable+private fun Harmony(vm: CanvasViewModel, c: ColorPick, compact: Boolean = false, short: Boolean = false) {+ val rgb = c.rgb()+ val hsv = remember(rgb) { rgbToP3Hsv(rgb) }+ val state by rememberUpdatedState(hsv)+ val density = LocalDensity.current+ // compact, the wheel is 200 across instead of 298; short, 296+ val radius = if (compact) 100.dp else if (short) HarmonyRadius - 1.dp else HarmonyRadius+ val wheel = remember(hsv[2], radius) { harmonyImage(hsv[2], with(density) { radius.roundToPx() }) }+ // the header is 78 tall here, with the kind under the title; the wheel starts 88 down (short, 82)+ Column(Modifier.padding(top = if (short) 4.dp else 10.dp)) {+ Box(+ Modifier.padding(start = if (compact) 30.dp else PanelWidth / 2 - radius).size(radius * 2)+ .pointerInput(Unit) {+ track { x, y ->+ val u = x * 2f - 1f+ val w = y * 2f - 1f+ val h = (atan2(-w, u) / (2f * PI.toFloat()) + 1f) % 1f+ c.setRgb(p3HsvToRgb(h, sqrt(u * u + w * w).coerceAtMost(1f), state[2]))+ }+ }+ .drawBehind {+ drawImage(wheel, dstSize = IntSize(size.width.roundToInt(), size.height.roundToInt()))+ val r = size.width / 2f+ fun at(turn: Float) = center + Offset(cos(turn) * hsv[1] * r, -sin(turn) * hsv[1] * r)+ for (t in vm.harmonyKind.turns) {+ val h = ((hsv[0] + t / 360f) % 1f + 1f) % 1f+ knob(at(h * 2f * PI.toFloat()), 10.75.dp.toPx(), rgbColor(p3HsvToRgb(h, hsv[1], hsv[2])))+ }+ knob(at(hsv[0] * 2f * PI.toFloat()), 14.5.dp.toPx(), rgbColor(rgb))+ },+ )+ Box(Modifier.padding(start = if (compact) 10.dp else 20.dp, end = if (compact) 10.dp else 20.dp, top = if (compact) 8.dp else if (short) 10.dp else 31.dp)) {+ SliderRow(hsv[2], listOf(Color.Black, rgbColor(p3HsvToRgb(hsv[0], hsv[1], 1f)))) { c.setRgb(p3HsvToRgb(state[0], state[1], it)) }+ }+ }+}++/** All palettes as compact cards: the default one ticked, each with its menu and its swatches. */+@Composable+private fun Palettes(vm: CanvasViewModel, c: ColorPick, short: Boolean) {+ var renaming by remember { mutableStateOf<Int?>(null) }+ val cards = vm.paletteCards+ Row(Modifier.padding(horizontal = 8.5.dp).fillMaxWidth().height(36.dp).clip(RoundedCornerShape(9.dp)).background(Pc.SetCell).padding(2.dp)) {+ for ((on, icon, label) in listOf(Triple(!cards, PcIcons.CardCompact, "Compact"), Triple(cards, PcIcons.CardStack, "Cards"))) {+ Row(+ Modifier.weight(1f).fillMaxSize().clip(RoundedCornerShape(7.dp)).background(if (on) Pc.Accent else Color.Transparent)+ .clickable { vm.changePaletteCards(label == "Cards") },+ horizontalArrangement = Arrangement.Center,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ // drawn in a 21 x 32 frame, shown as it is+ Icon(icon, contentDescription = null, tint = if (on) Color.White else Pc.PanelTitle, modifier = Modifier.requiredSize(21.dp, 32.dp))+ Text(label, color = if (on) Color.White else Pc.PanelTitle, fontSize = 15.sp, fontWeight = if (on) FontWeight.SemiBold else FontWeight.Normal, modifier = Modifier.padding(start = 6.dp))+ }+ }+ }+ LazyColumn(+ Modifier.padding(top = 8.dp).fillMaxWidth().height(if (short) 458.dp else 577.dp),+ // cards: three 120 tiles across+ contentPadding = if (cards) PaddingValues(start = 8.dp, end = 8.dp, bottom = 8.dp) else PaddingValues(start = 8.5.dp, end = 8.5.dp, bottom = 8.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ itemsIndexed(vm.palettes) { i, p ->+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(12.dp)).background(Pc.SetCell)) {+ Row(Modifier.fillMaxWidth().height(44.dp), verticalAlignment = Alignment.CenterVertically) {+ if (i == vm.defaultPalette) {+ Box(Modifier.padding(start = 11.5.dp).size(20.dp).clip(CircleShape).background(Pc.Accent), contentAlignment = Alignment.Center) {+ Icon(PcIcons.Tick, contentDescription = "Default", tint = Color.White, modifier = Modifier.size(14.dp))+ }+ }+ // a tap on the name renames it in place+ Box(Modifier.weight(1f).padding(start = if (i == vm.defaultPalette) 4.dp else 12.dp)) {+ if (renaming == i) {+ InlineName(p.name, Pc.PanelTitle, 14.sp, Modifier.fillMaxWidth()) {+ vm.renamePalette(i, it)+ renaming = null+ }+ } else {+ Text(p.name, color = Pc.PanelTitle, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, modifier = Modifier.clickable { renaming = i })+ }+ }+ PaletteMenu(vm, i)+ }+ if (cards) PaletteTiles(vm, c, i, p) else SwatchGrid(vm, c, i, p, Modifier)+ }+ }+ }+}++/** The ... button of a palette card and its menu: Set as active, Duplicate, Share; Delete. */+@Composable+private fun PaletteMenu(vm: CanvasViewModel, i: Int) {+ var open by remember { mutableStateOf(false) }+ val context = androidx.compose.ui.platform.LocalContext.current+ val scope = androidx.compose.runtime.rememberCoroutineScope()+ Box(Modifier.padding(end = 8.5.dp).size(30.dp, 44.dp).clickable { open = true }, contentAlignment = Alignment.Center) {+ Icon(PcIcons.More, contentDescription = "More", tint = Pc.PanelTitle, modifier = Modifier.size(20.dp))+ // under the button, its right edge near the button's+ LibraryMenu(open, androidx.compose.ui.graphics.TransformOrigin(1f, 0f), MenuPlace { a, size -> IntOffset(a.right - size.width, a.bottom) }, onDismiss = { open = false }, overPanel = true) {+ MenuItem(PcIcons.MenuCheckCircle, "Set as active") {+ open = false+ vm.chooseDefaultPalette(i)+ }+ MenuItem(PcIcons.MenuDuplicate, "Duplicate") {+ open = false+ vm.duplicatePalette(i)+ }+ MenuItem(PcIcons.MenuShare, "Share") {+ open = false+ scope.launch { vm.paletteFile(i)?.let { shareFile(context, it, "application/octet-stream") } }+ }+ if (vm.palettes.size > 1) {+ MenuDivider()+ MenuItem(PcIcons.MenuTrash, "Delete", Pc.MenuDanger) {+ open = false+ vm.deletePalette(i)+ }+ }+ }+ }+}++/**+ * The palettes' "+" and its menu: a new palette, empty or from a photo taken, a file or a picture,+ * and our example palettes back.+ */+@Composable+private fun NewPaletteButton(vm: CanvasViewModel) {+ var open by remember { mutableStateOf(false) }+ val context = androidx.compose.ui.platform.LocalContext.current+ val scope = androidx.compose.runtime.rememberCoroutineScope()+ val photo = remember {+ val dir = java.io.File(context.cacheDir, "exports").apply { mkdirs() }+ androidx.core.content.FileProvider.getUriForFile(context, context.packageName + ".files", java.io.File(dir, "palette-camera.jpg"))+ }+ val camera = androidx.activity.compose.rememberLauncherForActivityResult(androidx.activity.result.contract.ActivityResultContracts.TakePicture()) { taken ->+ if (taken) vm.paletteFromImage(photo)+ }+ // a file: a palette's, or a picture to take colours from+ val file = androidx.activity.compose.rememberLauncherForActivityResult(androidx.activity.result.contract.ActivityResultContracts.OpenDocument()) { uri ->+ uri?.let { scope.launch { if (!vm.importSwatches(it)) vm.paletteFromImage(it) } }+ }+ val photos = androidx.activity.compose.rememberLauncherForActivityResult(androidx.activity.result.contract.ActivityResultContracts.PickVisualMedia()) { uri ->+ uri?.let(vm::paletteFromImage)+ }+ Box(Modifier.padding(top = 12.dp).size(40.dp, 41.dp).clickable { open = true }, contentAlignment = Alignment.Center) {+ Icon(PcIcons.PlusMedium, contentDescription = "New palette", tint = Pc.PanelGlyph, modifier = Modifier.requiredSize(41.dp))+ LibraryMenu(open, androidx.compose.ui.graphics.TransformOrigin(1f, 0f), MenuPlace { a, size -> IntOffset(a.left - size.width, a.bottom) }, onDismiss = { open = false }, overPanel = true) {+ MenuItem(PcIcons.MenuGrid, "Create new palette") {+ open = false+ vm.addPalette()+ }+ MenuItem(PcIcons.MenuCamera, "New from camera") {+ open = false+ runCatching { camera.launch(photo) }.onFailure { vm.message = "No camera app is available." }+ }+ MenuItem(PcIcons.MenuFolder, "New from file") {+ open = false+ file.launch(arrayOf("*/*"))+ }+ MenuItem(PcIcons.MenuPhoto, "New from photos") {+ open = false+ photos.launch(androidx.activity.result.PickVisualMediaRequest(androidx.activity.result.contract.ActivityResultContracts.PickVisualMedia.ImageOnly))+ }+ MenuDivider()+ MenuItem(PcIcons.MenuRestore, "Restore example palettes") {+ open = false+ vm.restoreExamplePalettes()+ }+ }+ }+}++/**+ * A palette's swatches, ten by three, 36 dp each. Tap a colour to paint with it, tap an empty+ * slot to keep the current colour there, hold a colour to take it out.+ */+@OptIn(ExperimentalFoundationApi::class)+@Composable+private fun SwatchGrid(vm: CanvasViewModel, c: ColorPick, index: Int, p: Palette, modifier: Modifier) {+ Column(modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))) {+ for (row in 0 until 3) {+ Row {+ for (col in 0 until 10) {+ val slot = row * 10 + col+ val rgb = p.colors[slot]+ Box(+ Modifier.weight(1f).height(36.dp).pressScale().background(if (rgb != null) rgbColor(rgb) else Pc.EmptySlot)+ .combinedClickable(+ onClick = { if (rgb != null) c.setRgb(rgb) else vm.setSwatch(index, slot, c.rgb()) },+ onLongClick = { if (rgb != null) vm.setSwatch(index, slot, null) },+ ),+ )+ }+ }+ }+ }+}++/**+ * A palette's colours as named tiles, three across, 120 square: a tap takes the colour, a hold+ * takes it out of the palette.+ */+@OptIn(ExperimentalFoundationApi::class)+@Composable+private fun PaletteTiles(vm: CanvasViewModel, c: ColorPick, index: Int, p: Palette) {+ val filled = p.colors.withIndex().mapNotNull { (slot, rgb) -> rgb?.let { slot to it } }+ Column {+ for (row in filled.chunked(3)) {+ Row {+ for ((slot, rgb) in row) {+ val hsv = FloatArray(3).also { android.graphics.Color.colorToHSV(rgb, it) }+ Box(+ Modifier.size(120.dp).pressScale().background(rgbColor(rgb)).combinedClickable(+ onClick = { c.setRgb(rgb) },+ onLongClick = { vm.setSwatch(index, slot, null) },+ ),+ contentAlignment = Alignment.BottomStart,+ ) {+ // dark lettering on bright colours+ Text(+ colourName(rgb),+ color = if (hsv[2] >= 0.85f) Color.Black else Color.White,+ fontSize = 15.sp,+ lineHeight = 17.sp,+ modifier = Modifier.padding(start = 8.dp, end = 8.dp, bottom = 10.dp),+ )+ }+ }+ }+ }+ }+}++/**+ * A plain name for a colour (0xRRGGBB): a grey by its lightness, or a hue with "Dark", "Light" or+ * "Grayish" before it.+ */+internal fun colourName(rgb: Int): String {+ val r = ((rgb shr 16) and 0xFF) / 255f+ val g = ((rgb shr 8) and 0xFF) / 255f+ val b = (rgb and 0xFF) / 255f+ val max = maxOf(r, g, b)+ val min = minOf(r, g, b)+ val lightness = (max + min) / 2f+ val saturation = if (max > 0f) (max - min) / max else 0f+ if (saturation < 0.05f) {+ return when {+ lightness > 0.98f -> "White"+ lightness > 0.75f -> "Light Gray"+ lightness > 0.35f -> "Gray"+ lightness > 0.08f -> "Dark Gray"+ else -> "Black"+ }+ }+ val hsv = FloatArray(3).also { android.graphics.Color.colorToHSV(rgb, it) }+ val hue = HueNames.firstOrNull { hsv[0] < it.first }?.second ?: "Red"+ return when {+ saturation < 0.2f -> "Grayish $hue"+ lightness < 0.5f -> "Dark $hue"+ lightness > 0.8f -> "Light $hue"+ else -> hue+ }+}++/** Hue names, each up to the hue (degrees) it ends at. */+private val HueNames = listOf(+ 8f to "Red", 20f to "Red Orange", 40f to "Orange", 50f to "Yellow Orange", 65f to "Yellow",+ 80f to "Yellow Green", 150f to "Green", 170f to "Green Cyan", 195f to "Cyan", 220f to "Sky Blue",+ 250f to "Blue", 275f to "Violet", 290f to "Purple", 320f to "Magenta", 325f to "Magenta Pink",+ 342f to "Pink", 352f to "Pink Red", 361f to "Red",+)++/** A CMYK canvas's inks (cyan, magenta, yellow, black; 0..1) for a canvas colour, and back. */+class Inks(val of: (Int) -> FloatArray, val rgb: (FloatArray) -> Int)++/**+ * Number sliders: hue, saturation and brightness, then red, green and blue (on a CMYK canvas:+ * cyan, magenta, yellow and black, the groups closer together), then the hex code.+ */+@Composable+private fun Value(c: ColorPick, compact: Boolean = false, short: Boolean = false, inks: Inks? = null) {+ val rgb = c.rgb()+ val r = (rgb shr 16) and 0xFF+ val g = (rgb shr 8) and 0xFF+ val b = rgb and 0xFF+ if (compact) {+ CompactValue(c)+ return+ }+ if (inks != null) {+ InkValue(c, inks)+ return+ }+ Column(Modifier.padding(horizontal = 8.dp)) {+ ValueGroup(short = short) {+ ValueRow("H", huePosition(SliderHues, c.hue), SliderHues.map { hsvColor(it / 360f, 1f, 1f) }, "${(c.hue * 360f).roundToInt()}°") {+ c.setHsv(hueAt(SliderHues, it), c.saturation, c.brightness)+ }+ ValueRow("S", c.saturation, listOf(Pc.SaturationGrey, hsvColor(c.hue, 1f, 1f)), "${(c.saturation * 100f).roundToInt()}%") {+ c.setHsv(c.hue, it, c.brightness)+ }+ ValueRow("B", c.brightness, listOf(Color.Black, hsvColor(c.hue, c.saturation, 1f)), "${(c.brightness * 100f).roundToInt()}%") {+ c.setHsv(c.hue, c.saturation, it)+ }+ }+ ValueGroup(Modifier.padding(top = 6.dp), short) {+ ValueRow("R", r / 255f, listOf(Color(0, g, b), Color(255, g, b)), "$r") { c.setRgb(((it * 255f).roundToInt() shl 16) or (g shl 8) or b) }+ ValueRow("G", g / 255f, listOf(Color(r, 0, b), Color(r, 255, b)), "$g") { c.setRgb((r shl 16) or ((it * 255f).roundToInt() shl 8) or b) }+ ValueRow("B", b / 255f, listOf(Color(r, g, 0), Color(r, g, 255)), "$b") { c.setRgb((r shl 16) or (g shl 8) or (it * 255f).roundToInt()) }+ }+ HexRow(rgb) { c.setRgb(it) }+ if (short) Spacer(Modifier.height(2.dp))+ }+}++/** Value on a CMYK canvas: the hue, saturation and brightness, the four inks, then the hex code. */+@Composable+private fun InkValue(c: ColorPick, inks: Inks) {+ val rgb = c.rgb()+ // the inks dragged to, kept while the colour they make is the colour (not worked out again+ // from it, which could move the other inks)+ var held by remember { mutableStateOf<Pair<Int, FloatArray>?>(null) }+ val worked = remember(rgb) { inks.of(rgb) }+ val now = held?.takeIf { it.first == rgb }?.second ?: worked+ fun inksWith(k: Int, v: Float) = now.copyOf().also { it[k] = v.coerceIn(0f, 1f) }+ Column(Modifier.padding(horizontal = 8.dp)) {+ ValueGroup(height = 142.dp, gap = 4.dp, top = 1.dp) {+ ValueRow("H", huePosition(SliderHues, c.hue), SliderHues.map { hsvColor(it / 360f, 1f, 1f) }, "${(c.hue * 360f).roundToInt()}°") {+ c.setHsv(hueAt(SliderHues, it), c.saturation, c.brightness)+ }+ ValueRow("S", c.saturation, listOf(Pc.SaturationGrey, hsvColor(c.hue, 1f, 1f)), "${(c.saturation * 100f).roundToInt()}%") {+ c.setHsv(c.hue, it, c.brightness)+ }+ ValueRow("B", c.brightness, listOf(Color.Black, hsvColor(c.hue, c.saturation, 1f)), "${(c.brightness * 100f).roundToInt()}%") {+ c.setHsv(c.hue, c.saturation, it)+ }+ }+ ValueGroup(Modifier.padding(top = 8.dp), height = 187.dp, gap = 3.dp, top = 1.dp) {+ for ((k, letter) in listOf("C", "M", "Y", "K").withIndex()) {+ val v = now.getOrElse(k) { 0f }+ ValueRow(letter, v, listOf(rgbColor(inks.rgb(inksWith(k, 0f))), rgbColor(inks.rgb(inksWith(k, 1f)))), "${(v * 100f).roundToInt()}%") {+ val next = inksWith(k, it)+ val made = inks.rgb(next)+ held = made to next+ c.setRgb(made)+ }+ }+ }+ HexRow(rgb, top = 8.dp, height = 42.dp) { c.setRgb(it) }+ }+}++/** Value, compact: HSB or RGB (a switch picks), then the hex code; 240 wide. */+@Composable+private fun CompactValue(c: ColorPick) {+ var rgbShown by remember { mutableStateOf(false) }+ val rgb = c.rgb()+ val r = (rgb shr 16) and 0xFF+ val g = (rgb shr 8) and 0xFF+ val b = rgb and 0xFF+ Column(Modifier.padding(horizontal = 10.dp)) {+ Row(Modifier.fillMaxWidth().height(36.dp).clip(RoundedCornerShape(9.dp)).background(CompactGroup)) {+ for ((i, label) in listOf("HSB", "RGB").withIndex()) {+ val on = rgbShown == (i == 1)+ Box(+ Modifier.weight(1f).fillMaxSize().clip(RoundedCornerShape(9.dp)).background(if (on) Pc.Accent else Color.Transparent).clickable { rgbShown = i == 1 },+ contentAlignment = Alignment.Center,+ ) {+ Text(label, color = if (on) Color.White else Pc.PanelTitle, fontSize = 15.sp, fontWeight = if (on) FontWeight.SemiBold else FontWeight.Normal)+ }+ }+ }+ Column(+ Modifier.padding(top = 6.dp).fillMaxWidth().height(188.dp).clip(RoundedCornerShape(10.dp)).background(CompactGroup).padding(start = 12.dp, end = 12.dp, top = 10.dp),+ verticalArrangement = Arrangement.spacedBy(18.dp),+ ) {+ if (rgbShown) {+ CompactValueRow("R", r / 255f, listOf(Color(0, g, b), Color(255, g, b)), "$r") { c.setRgb(((it * 255f).roundToInt() shl 16) or (g shl 8) or b) }+ CompactValueRow("G", g / 255f, listOf(Color(r, 0, b), Color(r, 255, b)), "$g") { c.setRgb((r shl 16) or ((it * 255f).roundToInt() shl 8) or b) }+ CompactValueRow("B", b / 255f, listOf(Color(r, g, 0), Color(r, g, 255)), "$b") { c.setRgb((r shl 16) or (g shl 8) or (it * 255f).roundToInt()) }+ } else {+ CompactValueRow("H", huePosition(SliderHues, c.hue), SliderHues.map { hsvColor(it / 360f, 1f, 1f) }, "${(c.hue * 360f).roundToInt()}°") {+ c.setHsv(hueAt(SliderHues, it), c.saturation, c.brightness)+ }+ CompactValueRow("S", c.saturation, listOf(Pc.SaturationGrey, hsvColor(c.hue, 1f, 1f)), "${(c.saturation * 100f).roundToInt()}%") {+ c.setHsv(c.hue, it, c.brightness)+ }+ CompactValueRow("B", c.brightness, listOf(Color.Black, hsvColor(c.hue, c.saturation, 1f)), "${(c.brightness * 100f).roundToInt()}%") {+ c.setHsv(c.hue, c.saturation, it)+ }+ }+ }+ HexRow(rgb, CompactGroup, CompactHexField) { c.setRgb(it) }+ Spacer(Modifier.height(10.dp))+ }+}++/** One compact number slider, 216 wide: its letter, the track and the value. */+@Composable+private fun CompactValueRow(letter: String, value: Float, colours: List<Color>, shown: String, onChange: (Float) -> Unit) {+ Row(Modifier.fillMaxWidth().height(44.dp), verticalAlignment = Alignment.CenterVertically) {+ Text(letter, color = Pc.PanelTitle, fontSize = 15.sp, modifier = Modifier.width(20.dp))+ Box(Modifier.weight(1f)) { SliderRow(value, colours, onChange) }+ Text(shown, color = Pc.PanelTitle, fontSize = 15.sp, maxLines = 1, textAlign = TextAlign.End, modifier = Modifier.width(48.dp))+ }+}++@Composable+private fun ValueGroup(modifier: Modifier = Modifier, short: Boolean = false, rows: @Composable () -> Unit) {+ // short, the rows are 51 apart instead of 53+ if (short) ValueGroup(modifier, 151.dp, 7.dp, 3.dp, rows) else ValueGroup(modifier, 167.dp, 9.dp, 9.dp, rows)+}++/** A group of number sliders [height] tall, [gap] between rows, [top] above the first. */+@Composable+private fun ValueGroup(modifier: Modifier = Modifier, height: Dp, gap: Dp, top: Dp, rows: @Composable () -> Unit) {+ Column(+ modifier.fillMaxWidth().height(height).clip(RoundedCornerShape(10.dp)).background(Pc.ValueGroup).padding(top = top),+ verticalArrangement = Arrangement.spacedBy(gap),+ ) { rows() }+}++/** One number slider: its letter, a track from 32 to 296 dp, and the value centred at 326.5. */+@Composable+private fun ValueRow(letter: String, value: Float, colours: List<Color>, shown: String, onChange: (Float) -> Unit) {+ Box(Modifier.fillMaxWidth().height(44.dp)) {+ Text(letter, color = Pc.PanelTitle, fontSize = 15.sp, modifier = Modifier.align(Alignment.CenterStart).padding(start = 13.dp))+ Box(Modifier.padding(start = 32.dp).width(264.dp).align(Alignment.CenterStart)) {+ SliderRow(value, colours, onChange)+ }+ Box(Modifier.align(Alignment.CenterStart).padding(start = 304.dp).width(45.dp), contentAlignment = Alignment.Center) {+ Text(shown, color = Pc.PanelTitle, fontSize = 15.sp, maxLines = 1)+ }+ }+}++/**+ * The colour as a hex code: a tap opens the hex keypad beside the panel, and the code typed on it+ * (six digits) sets the colour.+ */+@Composable+private fun HexRow(rgb: Int, fill: Color = Pc.HexRow, field: Color = Pc.HexField, top: Dp = 6.dp, height: Dp = 44.dp, onSet: (Int) -> Unit) {+ // the digits typed since the keypad opened; null while it is shut+ var typed by remember { mutableStateOf<String?>(null) }+ Box(Modifier.padding(top = top).fillMaxWidth().height(height).clip(RoundedCornerShape(10.dp)).background(fill)) {+ Text("Hexadecimal", color = Pc.PanelTitle, fontSize = 16.sp, modifier = Modifier.align(Alignment.CenterStart).padding(start = 13.dp))+ val editing = typed != null+ Box(+ Modifier.align(Alignment.CenterEnd).padding(end = 8.dp).size(84.5.dp, 28.dp).clip(RoundedCornerShape(7.dp)).background(field)+ .then(if (editing) Modifier.border(1.dp, Pc.Accent, RoundedCornerShape(7.dp)) else Modifier)+ .clickable { typed = "" },+ contentAlignment = Alignment.Center,+ ) {+ Text("#" + (typed?.takeIf { it.isNotEmpty() } ?: "%06X".format(rgb)), color = Pc.PanelTitle, fontSize = 14.sp, maxLines = 1)+ }+ if (editing) {+ // beside the panel, its middle level with this row+ val gap = with(LocalDensity.current) { HexPadGap.roundToPx() }+ Popup(popupPositionProvider = remember(gap) { BesidePanel(gap) }, onDismissRequest = { typed = null }, properties = PopupProperties(focusable = true)) {+ HexPad(+ onKey = { c ->+ // a seventh digit starts a new code+ val next = ((typed ?: "").let { if (it.length >= 6) "" else it } + c)+ typed = next+ if (next.length == 6) next.toIntOrNull(16)?.let(onSet)+ },+ onBack = { typed = typed?.dropLast(1) },+ )+ }+ }+ }+}++/** From the hex row to the keypad's right edge: the panel's padding, then a small gap. */+private val HexPadGap = 12.5.dp++/** Puts a popup to the left of the anchor, its middle level with the anchor's, inside the window. */+private class BesidePanel(private val gap: Int) : androidx.compose.ui.window.PopupPositionProvider {+ override fun calculatePosition(+ anchorBounds: androidx.compose.ui.unit.IntRect,+ windowSize: IntSize,+ layoutDirection: androidx.compose.ui.unit.LayoutDirection,+ popupContentSize: IntSize,+ ): IntOffset {+ val x = (anchorBounds.left - gap - popupContentSize.width).coerceAtLeast(0)+ val y = (anchorBounds.center.y - popupContentSize.height / 2).coerceIn(0, (windowSize.height - popupContentSize.height).coerceAtLeast(0))+ return IntOffset(x, y)+ }+}++/** The hex keypad: D E F, A B C, 7 8 9, 4 5 6, 1 2 3, then a wide 0 and backspace; 259 × 338. */+@Composable+private fun HexPad(onKey: (Char) -> Unit, onBack: () -> Unit) {+ val rows = listOf("DEF", "ABC", "789", "456", "123")+ Column(+ Modifier.size(259.dp, 338.dp).clip(RoundedCornerShape(22.dp)).background(HexPadFill).border(0.5.dp, HexPadEdge, RoundedCornerShape(22.dp))+ .padding(horizontal = 10.5.dp, vertical = 9.5.dp),+ verticalArrangement = Arrangement.spacedBy(5.dp),+ ) {+ for (row in rows) {+ Row(horizontalArrangement = Arrangement.spacedBy(4.5.dp)) {+ for (c in row) HexKey(Modifier.width(76.5.dp), { onKey(c) }) { Text("$c", color = HexKeyInk, fontSize = 21.sp) }+ }+ }+ Row(horizontalArrangement = Arrangement.spacedBy(4.5.dp)) {+ HexKey(Modifier.width(157.5.dp), { onKey('0') }) { Text("0", color = HexKeyInk, fontSize = 21.sp) }+ HexKey(Modifier.width(76.5.dp), onBack) {+ Icon(PcIcons.HexBackspace, contentDescription = "Delete", tint = HexBackInk, modifier = Modifier.size(26.dp))+ }+ }+ }+}++/** One key of the hex keypad, 49 tall, lighter while held. */+@Composable+private fun HexKey(modifier: Modifier, onClick: () -> Unit, label: @Composable () -> Unit) {+ val press = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }+ val held by press.collectIsPressedAsState()+ Box(+ modifier.height(49.dp).clip(RoundedCornerShape(18.dp)).background(if (held) HexKeyHeld else HexKeyFill)+ .clickable(interactionSource = press, indication = null, onClick = onClick),+ contentAlignment = Alignment.Center,+ ) { label() }+}++private val HexPadFill = Color(0xFF616161)+private val HexPadEdge = Color(0xFF262626)+private val HexKeyFill = Color(0xFF6C6C6C)+private val HexKeyHeld = Color(0xFF8A8A8A)+private val HexKeyInk = Color(0xFFEEEEEE)+private val HexBackInk = Color(0xFFBABABA)++/** The colour at [t] (0..1) along evenly spaced [colours]. */+private fun colourAlong(colours: List<Color>, t: Float): Color {+ val p = t.coerceIn(0f, 1f) * (colours.size - 1)+ val i = p.toInt().coerceAtMost(colours.size - 2)+ return lerp(colours[i], colours[i + 1], p - i)+}++@Composable+private fun History(vm: CanvasViewModel, c: ColorPick) {+ Box(Modifier.fillMaxWidth().height(44.dp)) {+ Text("History", color = Pc.PanelTitle, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, modifier = Modifier.padding(start = 21.dp, top = 13.dp))+ Box(+ Modifier.align(Alignment.TopEnd).padding(top = 11.dp, end = 16.dp).size(86.dp, 22.5.dp).clip(RoundedCornerShape(7.dp))+ .background(Pc.SetCell).clickable { vm.clearHistory() },+ contentAlignment = Alignment.Center,+ ) {+ Text("Clear", color = Pc.ClearText, fontSize = 13.sp)+ }+ }+ HistoryStrip(vm, c)+}++/** The last colours painted with, ten 36 swatches; a tap takes one. */+@Composable+private fun HistoryStrip(vm: CanvasViewModel, c: ColorPick) {+ Row(Modifier.padding(horizontal = 8.dp).fillMaxWidth().height(36.dp).clip(RoundedCornerShape(8.dp))) {+ for (i in 0 until CanvasViewModel.HISTORY_SIZE) {+ val rgb = vm.history.getOrNull(i)+ Box(+ Modifier.weight(1f).height(36.dp)+ .background(if (rgb != null) rgbColor(rgb) else Pc.EmptySwatch)+ .then(if (rgb != null) Modifier.clickable { c.setRgb(rgb) } else Modifier),+ )+ }+ }+}++/**+ * The short panel's last block: the colour history (a 44 header and the strip) or the active+ * palette (a 34 header and its grid), whichever its "•••" menu picked.+ */+@Composable+private fun ShortBottom(vm: CanvasViewModel, c: ColorPick) {+ val palette = vm.palettes.getOrNull(vm.defaultPalette)+ val history = vm.colorHistoryShown || palette == null+ Box(Modifier.fillMaxWidth().height(if (history) 44.dp else 34.dp)) {+ Text(+ if (history) "History" else palette?.name.orEmpty(),+ color = Pc.PanelTitle,+ fontSize = 14.sp,+ fontWeight = FontWeight.SemiBold,+ maxLines = 1,+ modifier = Modifier.padding(start = 21.dp, top = if (history) 13.dp else 8.dp),+ )+ ShortBottomMenu(vm, history, Modifier.align(Alignment.CenterEnd))+ }+ if (history) {+ HistoryStrip(vm, c)+ } else if (palette != null) {+ SwatchGrid(vm, c, vm.defaultPalette, palette, Modifier.padding(horizontal = 8.dp))+ }+}++/**+ * Three dots 31 from the panel's right edge, opening a small menu under them: Color history or+ * Active palette (a radio each), and with the history shown, Clear history.+ */+@Composable+private fun ShortBottomMenu(vm: CanvasViewModel, history: Boolean, modifier: Modifier) {+ var open by remember { mutableStateOf(false) }+ Box(+ modifier.padding(end = 9.dp).size(44.dp, 34.dp).clickable { open = true }.drawBehind {+ val r = 1.8.dp.toPx()+ for (i in -1..1) drawCircle(Pc.PanelTitle, r, center + Offset(i * 6.5.dp.toPx(), 0f))+ },+ ) {+ MenuPresence(open, androidx.compose.ui.graphics.TransformOrigin(1f, 0f)) { look ->+ // its right edge 16 left of the dots, its top 15 below them+ Popup(offset = with(LocalDensity.current) { IntOffset((-246).dp.roundToPx(), 32.dp.roundToPx()) }, properties = PopupProperties(focusable = true), onDismissRequest = { open = false }) {+ Column(+ look.width(252.dp).clip(RoundedCornerShape(17.dp)).background(Pc.GlassMenuOverPanel)+ .border(1.dp, Pc.GlassMenuEdge, RoundedCornerShape(17.dp)).padding(top = 6.dp, bottom = if (history) 9.5.dp else 7.dp),+ ) {+ for ((label, on) in listOf("Color history" to true, "Active palette" to false)) {+ Row(+ Modifier.fillMaxWidth().height(40.dp).clickable {+ vm.changeColorHistoryShown(on)+ open = false+ }.padding(start = 20.dp, end = 19.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(label, color = Color.White, fontSize = 18.sp, maxLines = 1, modifier = Modifier.weight(1f))+ Radio(on == history)+ }+ }+ if (history) {+ Box(Modifier.padding(start = 16.dp, end = 15.dp, top = 11.dp, bottom = 10.dp).fillMaxWidth().height(1.dp).background(Pc.GlassMenuEdge))+ Row(+ Modifier.fillMaxWidth().height(40.dp).clickable {+ vm.clearHistory()+ open = false+ }.padding(start = 9.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ // a 41 frame centred 29.5 in+ Icon(PcIcons.Sweep, contentDescription = null, tint = Pc.MenuDanger, modifier = Modifier.requiredSize(41.dp))+ Text("Clear history", color = Pc.MenuDanger, fontSize = 18.sp, modifier = Modifier.padding(start = 2.dp))+ }+ }+ }+ }+ }+ }+}++/** A round choice mark, 18 across: a grey ring, or filled blue with a white tick when chosen. */+@Composable+private fun Radio(chosen: Boolean) {+ Box(+ Modifier.size(18.dp).clip(CircleShape).then(if (chosen) Modifier.background(Pc.Accent) else Modifier.border(1.5.dp, Pc.RadioRing, CircleShape)),+ contentAlignment = Alignment.Center,+ ) {+ if (chosen) Icon(PcIcons.Tick, contentDescription = null, tint = Color.White, modifier = Modifier.size(12.dp))+ }+}++private val Modes = listOf(+ Triple(ColorMode.DISC, PcIcons.ModeDisc, "Disc"),+ Triple(ColorMode.CLASSIC, PcIcons.ModeClassic, "Classic"),+ Triple(ColorMode.HARMONY, PcIcons.ModeHarmony, "Harmony"),+ Triple(ColorMode.VALUE, PcIcons.ModeValue, "Value"),+ Triple(ColorMode.PALETTES, PcIcons.ModePalettes, "Palettes"),+)++@Composable+private fun ModeTabs(vm: CanvasViewModel) {+ Row(Modifier.fillMaxWidth().height(70.dp)) {+ for ((mode, icon, label) in Modes) {+ ModeTab(icon, label, selected = vm.colorMode == mode, Modifier.weight(1f)) { vm.colorMode = mode }+ }+ }+}++@Composable+private fun ModeTab(icon: ImageVector, label: String, selected: Boolean, modifier: Modifier, onClick: () -> Unit) {+ // the chosen tab lights up as it is let go; held, its icon shrinks+ val press = rememberPressScale(Motion.TAB_PRESSED, Motion.highlightOn(), Motion.highlightOff())+ Box(modifier.fillMaxSize().then(press.touch).clickable(onClick = onClick)) {+ Icon(+ icon,+ contentDescription = null,+ tint = if (selected) Pc.Accent else Pc.PanelTitle,+ // a 36 frame centred 27 down+ modifier = Modifier.align(Alignment.TopCenter).padding(top = 9.dp).requiredSize(36.dp).scaledBy(press),+ )+ Text(+ label,+ color = if (selected) Color.White else Pc.PanelTitle,+ fontSize = 13.sp,+ fontWeight = FontWeight.Medium,+ maxLines = 1,+ modifier = Modifier.align(Alignment.TopCenter).padding(top = 41.dp),+ )+ }+}++/** Calls [onMove] with the touch position as 0..1 fractions of the area while it is held. */+private suspend fun PointerInputScope.track(onMove: (Float, Float) -> Unit) {+ awaitEachGesture {+ val down = awaitFirstDown()+ down.consume()+ fun send(p: Offset) = onMove((p.x / size.width).coerceIn(0f, 1f), (p.y / size.height).coerceIn(0f, 1f))+ send(down.position)+ while (true) {+ val event = awaitPointerEvent()+ val c = event.changes.firstOrNull { it.id == down.id } ?: break+ if (!c.pressed) break+ send(c.position)+ c.consume()+ }+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/CompanionUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/CompanionUi.ktnew file mode 100644index 0000000..9973e8a--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/CompanionUi.kt@@ -0,0 +1,114 @@+package io.github.artcraftandroid.procraft.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.detectDragGestures+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxScope+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.shadow+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import kotlin.math.roundToInt++private val CompanionWidth = 432.dp+private val CompanionHeight = 89.dp+private val CompanionFill = Color(0xE6404040)+private val CompanionInk = Color(0xFFBEBEBE)+private val CompanionGrab = Color(0xFF8A8A8A)+private val CompanionButtonWidth = 80.dp+private val CompanionButtonGap = 4.dp++/** Where the bar sits at first: its middle across the screen and this far down it. */+private const val COMPANION_START_Y = 0.54f++/**+ * The single touch gestures companion: a floating bar standing in for gestures that need more+ * than one finger. Undo, redo, Zoom and Move (while one is on, a finger dragged on the canvas zooms+ * or moves it), and Fit Canvas. Dragged by its top edge.+ */+@Composable+fun BoxScope.TouchCompanion(vm: CanvasViewModel) {+ if (!vm.singleTouchCompanion) return+ BoxWithConstraints(Modifier.fillMaxSize()) {+ val density = LocalDensity.current+ val (w, h) = with(density) { CompanionWidth.toPx() to CompanionHeight.toPx() }+ val (sw, sh) = with(density) { maxWidth.toPx() to maxHeight.toPx() }+ var at by remember { mutableStateOf(Offset((sw - w) / 2f, sh * COMPANION_START_Y - h / 2f)) }+ Column(+ Modifier.offset { IntOffset(at.x.roundToInt(), at.y.roundToInt()) }.size(CompanionWidth, CompanionHeight)+ .shadow(16.dp, RoundedCornerShape(30.dp)).clip(RoundedCornerShape(30.dp)).background(CompanionFill),+ ) {+ // the grab line, and the strip it sits in, drags the bar about, kept on the screen+ Box(+ Modifier.fillMaxWidth().height(24.dp).pointerInput(sw, sh) {+ detectDragGestures { change, amount ->+ change.consume()+ at = Offset((at.x + amount.x).coerceIn(0f, sw - w), (at.y + amount.y).coerceIn(0f, sh - h))+ }+ },+ contentAlignment = Alignment.Center,+ ) {+ Box(Modifier.size(40.dp, 5.dp).clip(CircleShape).background(CompanionGrab))+ }+ Row(Modifier.padding(start = 8.dp)) {+ CompanionButton(PcIcons.Undo, "Undo", false, 30.dp) { vm.undo() }+ Spacer(Modifier.width(CompanionButtonGap))+ CompanionButton(PcIcons.Redo, "Redo", false, 30.dp) { vm.redo() }+ Spacer(Modifier.width(CompanionButtonGap))+ CompanionButton(PcIcons.Zoom, "Zoom", vm.companionMode == CanvasViewModel.CompanionMode.ZOOM, 22.dp) {+ vm.toggleCompanionMode(CanvasViewModel.CompanionMode.ZOOM)+ }+ Spacer(Modifier.width(CompanionButtonGap))+ CompanionButton(PcIcons.MoveCanvas, "Move", vm.companionMode == CanvasViewModel.CompanionMode.MOVE, 22.dp) {+ vm.toggleCompanionMode(CanvasViewModel.CompanionMode.MOVE)+ }+ Spacer(Modifier.width(CompanionButtonGap))+ CompanionButton(PcIcons.FitCanvas, "Fit Canvas", false, 22.dp) { vm.settleToFit() }+ }+ }+ }+}++/** A button of the bar: its icon (blue while its mode is on) over its name. */+@Composable+private fun CompanionButton(icon: ImageVector, label: String, on: Boolean, iconSize: androidx.compose.ui.unit.Dp, onClick: () -> Unit) {+ Column(+ Modifier.size(CompanionButtonWidth, 50.dp).clip(RoundedCornerShape(10.dp)).clickable(onClick = onClick),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ Box(Modifier.height(30.dp), contentAlignment = Alignment.Center) {+ Icon(icon, contentDescription = null, tint = if (on) Pc.Accent else CompanionInk, modifier = Modifier.size(iconSize))+ }+ Text(label, color = CompanionInk, fontSize = 13.sp, maxLines = 1)+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/CopyPasteUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/CopyPasteUi.ktnew file mode 100644index 0000000..a3ed31f--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/CopyPasteUi.kt@@ -0,0 +1,80 @@+package io.github.artcraftandroid.procraft.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxScope+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel++private val PanelFill get() = if (Pc.light) Color(0xFFE2E2E2) else Color(0xFF484848)+private val PanelTitleInk get() = if (Pc.light) Color(0xFF393939) else Color(0xFFC5C5C5)+private val ButtonInk get() = if (Pc.light) Color(0xFF4A4A4A) else Color(0xFFA8A8A8)+private val CloseFill get() = if (Pc.light) Color(0xFFCFCFCF) else Color(0xFF2A2A2A)++/**+ * The Copy & Paste panel (three fingers swiped down): Cut, Copy, Copy All, Duplicate, Cut & Paste+ * and Paste, a little below the middle of the screen; a tap off it or its ✕ closes it.+ */+@Composable+fun BoxScope.CopyPastePanel(vm: CanvasViewModel) {+ if (!vm.copyPasteOpen) return+ fun act(f: () -> Unit) {+ vm.copyPasteOpen = false+ f()+ }+ BoxWithConstraints(Modifier.fillMaxSize().pointerInput(Unit) { detectTapGestures { vm.copyPasteOpen = false } }) {+ Box(+ Modifier.offset(x = (maxWidth - 496.dp) / 2, y = maxHeight * (617f / 1133f)).size(496.dp, 106.dp).clip(RoundedCornerShape(30.dp)).background(PanelFill)+ .pointerInput(Unit) { detectTapGestures { } },+ ) {+ Box(Modifier.align(Alignment.TopCenter).padding(top = 5.dp).size(40.dp, 4.dp).clip(CircleShape).background(Color(0xFF7C7C7C)))+ Text("Copy & Paste", color = PanelTitleInk, fontSize = 22.sp, fontWeight = FontWeight.Bold, modifier = Modifier.offset(x = 18.dp, y = 12.dp))+ Box(Modifier.offset(x = 453.dp, y = 6.dp).size(40.dp).clip(CircleShape).background(CloseFill).clickable { vm.copyPasteOpen = false }, contentAlignment = Alignment.Center) {+ Icon(PcIcons.Cross, contentDescription = "Close", tint = ButtonInk, modifier = Modifier.size(18.dp))+ }+ Row(Modifier.offset(y = 48.dp)) {+ PanelButton(PcIcons.CopyCut, "Cut") { act(vm::cutLayer) }+ PanelButton(PcIcons.CopyOne, "Copy") { act(vm::copyLayer) }+ PanelButton(PcIcons.CopyAll, "Copy All") { act(vm::copyCanvas) }+ PanelButton(PcIcons.CopyDuplicate, "Duplicate") { act(vm::duplicateCurrent) }+ PanelButton(PcIcons.CutPaste, "Cut & Paste") { act(vm::cutAndPaste) }+ PanelButton(PcIcons.PasteDown, "Paste", enabled = vm.canPaste) { act(vm::paste) }+ }+ }+ }+}++@Composable+private fun PanelButton(icon: ImageVector, label: String, enabled: Boolean = true, onClick: () -> Unit) {+ val ink = if (enabled) ButtonInk else ButtonInk.copy(alpha = 0.4f)+ // the icon (a 50 frame) 28 across, centred 17 down; the name from 34+ Box(Modifier.width(82.7.dp).height(50.dp).clickable(enabled = enabled, onClick = onClick)) {+ Icon(icon, contentDescription = null, tint = ink, modifier = Modifier.align(Alignment.TopCenter).padding(top = 3.dp).requiredSize(28.dp))+ Text(label, color = ink, fontSize = 13.sp, maxLines = 1, modifier = Modifier.align(Alignment.TopCenter).padding(top = 33.dp))+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/CropUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/CropUi.ktnew file mode 100644index 0000000..552bd63--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/CropUi.kt@@ -0,0 +1,307 @@+package io.github.artcraftandroid.procraft.ui++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxScope+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.drawBehind+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.graphics.StrokeCap+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.rememberTextMeasurer+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.input.KeyboardType+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import kotlin.math.abs+import kotlin.math.cos+import kotlin.math.roundToInt+import kotlin.math.sin++private val FrameLine = Color(0xCCFFFFFF)+private val GridLine = Color(0x66C8C8C8)+private val Mark = Color(0xFFD0D0D0)+private val PopoverFill = Color(0xF21F1F1F)+private val FieldFill = Color(0xFF242424)+private val GroupFill = Color(0xFF2A2A2A)+private val RowLine = Color(0xFF3A3A3A)+private val Muted = Color(0xFF8E8E93)++/** Which part of the crop's frame a drag takes. */+private enum class Grab { MOVE, LEFT, TOP, RIGHT, BOTTOM, TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT }++/**+ * Crop and Resize: the canvas, fitted inside a margin, with a frame over it in quarters whose+ * corners and sides are dragged to change what is kept (inside it, to move it); the header with+ * Cancel, Settings, Reset and Done.+ */+@Composable+fun BoxScope.CropOverlay(vm: CanvasViewModel) {+ val rect = vm.cropRect ?: return+ val density = LocalDensity.current+ val reach = with(density) { 28.dp.toPx() }+ val snapPx = with(density) { 10.dp.toPx() }+ val current by rememberUpdatedState(rect)+ // the frame's corners in the window, turned with the crop+ fun corners(r: Rect): List<Offset> {+ val c = r.center+ val (s, k) = sin(vm.cropAngle) to cos(vm.cropAngle)+ return listOf(Offset(r.left, r.top), Offset(r.right, r.top), Offset(r.right, r.bottom), Offset(r.left, r.bottom)).map { p ->+ val d = p - c+ vm.canvasToWindow(Offset(c.x + d.x * k - d.y * s, c.y + d.x * s + d.y * k))+ }+ }+ Canvas(+ Modifier.fillMaxSize().pointerInput(Unit) {+ awaitEachGesture {+ val down = awaitFirstDown()+ val cs = corners(current)+ val mid = { a: Offset, b: Offset -> (a + b) / 2f }+ val near = { p: Offset -> (p - down.position).getDistance() < reach }+ val grab = when {+ near(cs[0]) -> Grab.TOP_LEFT+ near(cs[1]) -> Grab.TOP_RIGHT+ near(cs[2]) -> Grab.BOTTOM_RIGHT+ near(cs[3]) -> Grab.BOTTOM_LEFT+ near(mid(cs[0], cs[3])) -> Grab.LEFT+ near(mid(cs[0], cs[1])) -> Grab.TOP+ near(mid(cs[1], cs[2])) -> Grab.RIGHT+ near(mid(cs[2], cs[3])) -> Grab.BOTTOM+ else -> Grab.MOVE+ }+ val start = current+ val from = vm.windowToCanvas(down.position) ?: return@awaitEachGesture+ // canvas pixels a few window points cover, for snapping+ val snap = vm.windowToCanvas(down.position + Offset(snapPx, 0f))?.let { (it - from).getDistance() } ?: 0f+ down.consume()+ while (true) {+ val c = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break+ if (!c.pressed) break+ c.consume()+ val at = vm.windowToCanvas(c.position) ?: continue+ val d = at - from+ var l = start.left+ var t = start.top+ var r = start.right+ var b = start.bottom+ when (grab) {+ Grab.MOVE -> { l += d.x; r += d.x; t += d.y; b += d.y }+ Grab.LEFT -> l += d.x+ Grab.RIGHT -> r += d.x+ Grab.TOP -> t += d.y+ Grab.BOTTOM -> b += d.y+ Grab.TOP_LEFT -> { l += d.x; t += d.y }+ Grab.TOP_RIGHT -> { r += d.x; t += d.y }+ Grab.BOTTOM_LEFT -> { l += d.x; b += d.y }+ Grab.BOTTOM_RIGHT -> { r += d.x; b += d.y }+ }+ // snapping: the frame's sides to the canvas's sides and middle+ if (vm.cropSnapping) {+ val (cw, ch) = vm.canvasSize()+ fun snapTo(v: Float, targets: List<Float>) = targets.firstOrNull { abs(it - v) < snap } ?: v+ val xs = listOf(0f, cw / 2f, cw.toFloat())+ val ys = listOf(0f, ch / 2f, ch.toFloat())+ if (grab == Grab.MOVE) {+ val dl = snapTo(l, xs) - l+ val dr = snapTo(r, xs) - r+ val dx = if (dl != 0f) dl else dr+ l += dx; r += dx+ val dt = snapTo(t, ys) - t+ val db = snapTo(b, ys) - b+ val dy = if (dt != 0f) dt else db+ t += dy; b += dy+ } else {+ l = snapTo(l, xs); r = snapTo(r, xs); t = snapTo(t, ys); b = snapTo(b, ys)+ }+ }+ // a locked aspect follows the width+ if (vm.cropAspectLocked && grab != Grab.MOVE && start.width > 0f) {+ val h = (r - l) * start.height / start.width+ if (grab == Grab.TOP || grab == Grab.TOP_LEFT || grab == Grab.TOP_RIGHT) t = b - h else b = t + h+ }+ if (r - l >= 1f && b - t >= 1f) vm.changeCropRect(Rect(l, t, r, b))+ }+ }+ },+ ) {+ val cs = corners(rect)+ // quarters+ for (i in 1..3) {+ val f = i / 4f+ drawLine(GridLine, cs[0] + (cs[1] - cs[0]) * f, cs[3] + (cs[2] - cs[3]) * f, 1.dp.toPx())+ drawLine(GridLine, cs[0] + (cs[3] - cs[0]) * f, cs[1] + (cs[2] - cs[1]) * f, 1.dp.toPx())+ }+ val frame = Path().apply {+ moveTo(cs[0].x, cs[0].y)+ cs.drop(1).forEach { lineTo(it.x, it.y) }+ close()+ }+ drawPath(frame, FrameLine, style = Stroke(1.dp.toPx()))+ // small marks at the corners and the sides' middles+ val arm = 10.dp.toPx()+ val w = 3.dp.toPx()+ for (i in 0..3) {+ val p = cs[i]+ val next = cs[(i + 1) % 4]+ val toNext = (next - p).let { it / it.getDistance().coerceAtLeast(1f) }+ val toPrev = (cs[(i + 3) % 4] - p).let { it / it.getDistance().coerceAtLeast(1f) }+ drawLine(Mark, p, p + toNext * arm, w, StrokeCap.Butt)+ drawLine(Mark, p, p + toPrev * arm, w, StrokeCap.Butt)+ val m = (p + next) / 2f+ drawLine(Mark, m - toNext * arm, m + toNext * arm, w, StrokeCap.Butt)+ }+ }+ ToolHeader(+ "Crop and Resize",+ listOf(+ ToolButton("Cancel") { vm.endCrop(false) },+ ToolButton("Settings", chosen = vm.cropSettingsOpen) { vm.cropSettingsOpen = !vm.cropSettingsOpen },+ ToolButton("Reset") { vm.resetCrop() },+ ),+ onDone = { vm.endCrop(true) },+ modifier = Modifier.align(Alignment.TopCenter),+ )+ // 9 from the screen's right edge, its arrow up at Settings (183 from that edge)+ if (vm.cropSettingsOpen) CropSettings(vm, Modifier.align(Alignment.TopEnd).offset(x = (-9).dp, y = 66.dp))+}++/** The settings popover: the size (aspect locked or not), DPI, resampling, snapping, the turn. */+@Composable+private fun CropSettings(vm: CanvasViewModel, modifier: Modifier) {+ Popover(348.dp, 174.5.dp, modifier, fill = PopoverFill, corner = 24.dp) {+ Column(Modifier.padding(10.dp)) {+ Box(Modifier.height(40.dp), contentAlignment = Alignment.CenterStart) {+ Text("Settings", color = Color(0xFFD2D2D2), fontSize = 22.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 14.dp))+ }+ val (w, h) = vm.cropSize+ Row(Modifier.padding(top = 10.dp).fillMaxWidth().height(44.dp).padding(horizontal = 2.dp), verticalAlignment = Alignment.CenterVertically) {+ NumberField(w.toString(), "px", Modifier.width(137.dp)) { it.toIntOrNull()?.let { v -> vm.changeCropSize(v, null) } }+ Box(Modifier.padding(horizontal = 8.dp).size(34.dp, 40.dp).clickable { vm.cropAspectLocked = !vm.cropAspectLocked }, contentAlignment = Alignment.Center) {+ Icon(PcIcons.Link, contentDescription = "Aspect lock", tint = if (vm.cropAspectLocked) Pc.Accent else Color(0xFFD2D2D2), modifier = Modifier.size(20.dp))+ }+ NumberField(h.toString(), "px", Modifier.width(137.dp)) { it.toIntOrNull()?.let { v -> vm.changeCropSize(null, v) } }+ }+ Column(Modifier.padding(top = 10.dp).fillMaxWidth().clip(RoundedCornerShape(14.dp)).background(GroupFill)) {+ Row(Modifier.fillMaxWidth().height(44.dp).padding(start = 12.dp, end = 4.dp), verticalAlignment = Alignment.CenterVertically) {+ Text("DPI", color = Color(0xFFD2D2D2), fontSize = 17.sp, modifier = Modifier.weight(1f))+ NumberField("%.1f".format(vm.cropDpi), null, Modifier.width(80.dp).height(36.dp)) { it.toFloatOrNull()?.let(vm::changeCropDpi) }+ }+ Box(Modifier.fillMaxWidth().height(1.dp).background(RowLine))+ SwitchRow("Resample canvas", vm.cropResample, vm::changeCropResample)+ Box(Modifier.fillMaxWidth().height(1.dp).background(RowLine))+ SwitchRow("Snapping", vm.cropSnapping) { vm.cropSnapping = it }+ }+ Box(Modifier.padding(top = 10.dp).fillMaxWidth().height(64.dp).clip(RoundedCornerShape(14.dp)).background(GroupFill)) {+ RotationSlider(vm.cropAngle) { vm.changeCropAngle(it) }+ }+ }+ }+}++@Composable+private fun SwitchRow(label: String, on: Boolean, onChange: (Boolean) -> Unit) {+ Row(Modifier.fillMaxWidth().height(44.dp).clickable { onChange(!on) }.padding(start = 12.dp, end = 6.dp), verticalAlignment = Alignment.CenterVertically) {+ Text(label, color = Color(0xFFD2D2D2), fontSize = 17.sp, modifier = Modifier.weight(1f))+ Switch(on, enabled = true)+ }+}++/** A number typed into a capsule, its unit after it; done as it is typed. */+@Composable+private fun NumberField(value: String, unit: String?, modifier: Modifier, onChange: (String) -> Unit) {+ var text by remember(value) { mutableStateOf(value) }+ val style = TextStyle(color = Color(0xFFD2D2D2), fontSize = 17.sp, textAlign = TextAlign.Center)+ // as wide as its text (and the cursor), so the number and unit sit together in the middle+ val measurer = rememberTextMeasurer()+ val textWidth = with(LocalDensity.current) { measurer.measure(text, style).size.width.toDp() } + 2.dp+ Row(modifier.height(40.dp).clip(CircleShape).background(FieldFill).padding(horizontal = 12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center) {+ BasicTextField(+ text,+ { t ->+ text = t.filter { it.isDigit() || it == '.' }.take(7)+ onChange(text)+ },+ singleLine = true,+ textStyle = style,+ cursorBrush = SolidColor(Color.White),+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),+ modifier = Modifier.width(textWidth),+ )+ if (unit != null) Text(" $unit", color = Color(0xFFD2D2D2), fontSize = 17.sp)+ }+}++/** The turn, -180 to 180 degrees, dragged anywhere along the bar; a tick marks no turn. */+@Composable+private fun RotationSlider(radians: Float, onChange: (Float) -> Unit) {+ val change by rememberUpdatedState(onChange)+ val degrees = Math.toDegrees(radians.toDouble()).toFloat()+ Column(Modifier.padding(horizontal = 10.dp, vertical = 8.dp)) {+ Row {+ Text("Rotation", color = Color(0xFFD2D2D2), fontSize = 17.sp, modifier = Modifier.weight(1f))+ Text("%.1f°".format(degrees), color = Color(0xFFD2D2D2), fontSize = 17.sp)+ }+ Box(+ Modifier.fillMaxWidth().height(22.dp).pointerInput(Unit) {+ awaitEachGesture {+ val down = awaitFirstDown()+ fun at(x: Float) = Math.toRadians(((x / size.width).coerceIn(0f, 1f) * 360f - 180f).let { if (abs(it) < 2f) 0f else it }.toDouble()).toFloat()+ change(at(down.position.x))+ while (true) {+ val c = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break+ if (!c.pressed) break+ change(at(c.position.x))+ c.consume()+ }+ }+ }.drawBehind {+ val y = size.height / 2f+ val h = 3.dp.toPx()+ drawRoundRect(Color(0xFF555555), Offset(0f, y - h / 2f), Size(size.width, h), CornerRadius(h / 2f))+ drawLine(Muted, Offset(size.width / 2f, y - 6.dp.toPx()), Offset(size.width / 2f, y + 6.dp.toPx()), 1.dp.toPx())+ val knob = Size(26.dp.toPx(), 15.dp.toPx())+ val x = (((degrees + 180f) / 360f).coerceIn(0f, 1f) * size.width).coerceIn(knob.width / 2f, size.width - knob.width / 2f)+ drawRoundRect(Color.White, Offset(x - knob.width / 2f, y - knob.height / 2f), knob, CornerRadius(knob.height / 2f))+ },+ )+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/CustomCanvasUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/CustomCanvasUi.ktnew file mode 100644index 0000000..d73be2a--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/CustomCanvasUi.kt@@ -0,0 +1,386 @@+package io.github.artcraftandroid.procraft.ui++import androidx.activity.compose.BackHandler+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ColumnScope+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import io.github.artcraftandroid.procraft.canvas.TimeLapseSettings+import io.github.artcraftandroid.procraft.gallery.CanvasPreset+import kotlinx.coroutines.launch+import kotlin.math.roundToInt++private val ScreenFill = Color(0xFF1F1F1F)+private val PanelFill = Color(0xFF282828)+private val Ink = Color(0xFFAAAAAA)+private val IdleInk = Color(0xFF797979)+private val Editing = Color(0xFF436BF0)+private val KeypadFill = Color(0xFF1A1A1A)+private val DigitFill = Color(0xFF525252)+private val KeyFill = Color(0xFF2B2B2B)+private val UnitChosen = Color(0xFFA1A1A1)+private val SwitchTrack = Color(0xFF353535)+private val SwitchIdle = Color(0xFFC1C1C1)+private val CapsuleFill = Color(0xFF1A1A1A)+private val CapsuleEdge = Color(0xFF373737)+private val DoneBlue = Color(0xFF0190FF)++/** The units sizes are typed in: the key's name, the unit's (as presets keep it) and its mark. */+private enum class SizeUnit(val label: String, val key: String, val mark: String) {+ MILLIMETERS("Millimeters", "mm", "mm"), CENTIMETERS("Centimeters", "cm", "cm"), INCHES("Inches", "in", "″"), PIXELS("Pixels", "px", "px")+}++/** The fields the keypad types into. */+private enum class Field { WIDTH, HEIGHT, DPI }++/** A section of the rail: its name, and its icon shown [size] across. */+private class Section(val label: String, val icon: ImageVector, val size: Dp)++private val Sections = listOf(+ Section("Dimensions", PcIcons.InfoDimensions, 50.dp),+ Section("Color profile", PcIcons.InfoProfile, 35.dp),+ Section("Time-lapse settings", PcIcons.InfoVideo, 60.dp),+ Section("Canvas properties", PcIcons.TabCanvas, 40.dp),+)++/**+ * Custom Canvas, full screen: a panel of sections (dimensions, colour profile, time-lapse+ * settings, canvas properties) on the left, the chosen one on the right with the canvas's name,+ * Cancel and Done; sizes are typed on a keypad of its own, in pixels, inches, centimetres or+ * millimetres. It edits [CanvasViewModel.editingPreset], or makes a new canvas ([onMade] then).+ */+@Composable+fun CustomCanvasScreen(vm: CanvasViewModel, onMade: () -> Unit) {+ val start = remember { vm.editingPreset?.let { vm.canvasPresets.getOrNull(it) } ?: CanvasPreset("Untitled Canvas", "px", 1080f, 1080f, 300f) }+ var section by remember { mutableIntStateOf(0) }+ var name by remember { mutableStateOf(start.name) }+ // the size in the unit chosen+ var width by remember { mutableStateOf(start.sizeWidth) }+ var height by remember { mutableStateOf(start.sizeHeight) }+ var dpi by remember { mutableStateOf(start.dpi) }+ var unit by remember { mutableStateOf(SizeUnit.entries.firstOrNull { it.key == start.unit } ?: SizeUnit.PIXELS) }+ var field by remember { mutableStateOf<Field?>(Field.WIDTH) }+ // what has been typed into the field, until it is left+ var typed by remember { mutableStateOf("") }+ var background by remember { mutableIntStateOf(start.background) }+ var hidden by remember { mutableStateOf(start.backgroundHidden) }+ var resolution by remember { mutableIntStateOf(start.timeLapse.resolution) }+ var quality by remember { mutableIntStateOf(start.timeLapse.quality) }+ var hevc by remember { mutableStateOf(start.timeLapse.hevc) }+ var profile by remember { mutableStateOf(start.profile) }+ // which profiles the list shows+ var cmyk by remember { mutableStateOf(io.github.artcraftandroid.procraft.core.isCmykProfile(start.profile)) }+ val scope = androidx.compose.runtime.rememberCoroutineScope()+ val importer = androidx.activity.compose.rememberLauncherForActivityResult(androidx.activity.result.contract.ActivityResultContracts.OpenDocument()) { uri ->+ uri?.let {+ scope.launch {+ vm.importProfile(it)?.let { name ->+ profile = name+ cmyk = io.github.artcraftandroid.procraft.core.isCmykProfile(name)+ }+ }+ }+ }+ // the background's colour picker is open+ var picking by remember { mutableStateOf(false) }++ fun preset() = CanvasPreset(name.trim().ifEmpty { "Untitled Canvas" }, unit.key, width, height, dpi, background, hidden, TimeLapseSettings(resolution, quality, hevc), profile)+ // what typing has made of the field so far goes into it+ fun commit() {+ val v = typed.toFloatOrNull()+ if (v != null && v > 0f) when (field) {+ Field.WIDTH -> width = v+ Field.HEIGHT -> height = v+ Field.DPI -> dpi = v.coerceIn(1f, 9999f)+ null -> Unit+ }+ typed = ""+ }+ // the size kept, in another unit (straight from one length to another; through the pixels+ // otherwise)+ fun convert(to: SizeUnit) {+ val p = preset()+ val from = CanvasPreset.perInch(unit.key)+ fun change(v: Float, px: Int) = CanvasPreset.perInch(to.key)?.let { if (from != null) v / from * it else px / dpi * it } ?: px.toFloat()+ width = change(width, p.width)+ height = change(height, p.height)+ unit = to+ }+ fun create() {+ commit()+ if (vm.finishCustomCanvas(preset())) onMade()+ }+ BackHandler { vm.closeCustomCanvas() }+ BoxWithConstraints(Modifier.fillMaxSize().background(ScreenFill).pointerInput(Unit) { detectTapGestures { } }) {+ // the sections+ Column(Modifier.padding(start = 10.dp, top = 10.dp, bottom = 10.dp).width(319.dp).fillMaxHeight().clip(RoundedCornerShape(20.dp)).background(PanelFill)) {+ Text("Custom Canvas", color = Ink, fontSize = 22.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 24.dp, top = 16.dp, bottom = 17.dp))+ Sections.forEachIndexed { i, s ->+ val chosen = i == section+ Row(+ Modifier.padding(start = 8.dp, bottom = 10.dp).size(304.dp, 52.dp).clip(CircleShape).background(if (chosen) Pc.Accent else Color.Transparent).clickable {+ commit()+ section = i+ }.padding(start = 16.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ // icons centred 43 in, whatever their size; the names 69 in+ Box(Modifier.width(38.dp), contentAlignment = Alignment.Center) {+ Icon(s.icon, contentDescription = null, tint = if (chosen) Color.White else IdleInk, modifier = Modifier.requiredSize(s.size))+ }+ Text(s.label, color = if (chosen) Color.White else IdleInk, fontSize = 15.sp, modifier = Modifier.padding(start = 7.dp))+ }+ }+ }+ // the name, Cancel and Done+ BasicTextField(+ name, { name = it.take(64) }, singleLine = true,+ textStyle = TextStyle(color = Ink, fontSize = 22.sp, fontWeight = FontWeight.Bold), cursorBrush = SolidColor(Color.White),+ modifier = Modifier.offset(x = 394.dp, y = 28.dp).width(maxWidth - 394.dp - 160.dp),+ )+ Row(Modifier.align(Alignment.TopEnd).padding(top = 20.dp, end = 20.dp), verticalAlignment = Alignment.CenterVertically) {+ // Cancel, and Import beside it on the colour profile page+ Row(Modifier.height(43.dp).clip(CircleShape).background(CapsuleFill).border(1.dp, CapsuleEdge, CircleShape), verticalAlignment = Alignment.CenterVertically) {+ CapsuleText("Cancel") { vm.closeCustomCanvas() }+ if (section == 1) CapsuleText("Import") { importer.launch(arrayOf("*/*")) }+ }+ Spacer(Modifier.width(13.dp))+ Box(Modifier.size(44.dp, 45.dp).clip(CircleShape).background(DoneBlue).clickable { create() }, contentAlignment = Alignment.Center) {+ Icon(PcIcons.DoneTick, contentDescription = "Create", tint = Color.White, modifier = Modifier.requiredSize(40.dp))+ }+ }+ Column(Modifier.padding(start = 372.dp, end = 32.dp, top = 120.dp)) {+ when (section) {+ 0 -> {+ Group {+ SizeRow("Width", if (field == Field.WIDTH && typed.isNotEmpty()) typed else CanvasPreset.number(width), unit.mark, field == Field.WIDTH) { commit(); field = Field.WIDTH }+ Line()+ SizeRow("Height", if (field == Field.HEIGHT && typed.isNotEmpty()) typed else CanvasPreset.number(height), unit.mark, field == Field.HEIGHT) { commit(); field = Field.HEIGHT }+ }+ Spacer(Modifier.height(24.dp))+ Group {+ SizeRow("DPI", if (field == Field.DPI && typed.isNotEmpty()) typed else "${dpi.roundToInt()}", "", field == Field.DPI) { commit(); field = Field.DPI }+ Line()+ val p = preset()+ SizeRow("Maximum Layers", "${vm.layersFor(p.width, p.height)}", "", false) {}+ }+ }+ 1 -> {+ KindSwitch(cmyk) { cmyk = it }+ Spacer(Modifier.height(24.dp))+ Group {+ val names = if (cmyk) io.github.artcraftandroid.procraft.core.cmykProfiles() else io.github.artcraftandroid.procraft.core.colorProfiles()+ for ((i, name) in names.withIndex()) {+ if (i > 0) Line()+ ChoiceRow(name, name == profile) { profile = name }+ }+ }+ }+ 2 -> {+ Group {+ for ((i, pair) in listOf("1080p" to "1920 × 1080px", "2K" to "2732 × 2048px", "4K" to "3840 × 2160px").withIndex()) {+ if (i > 0) Line()+ ChoiceRow(pair.first, i == resolution, pair.second) { resolution = i }+ }+ }+ Spacer(Modifier.height(24.dp))+ Group {+ for ((i, label) in listOf("Low quality", "Good quality", "Studio quality", "Lossless").withIndex()) {+ if (i > 0) Line()+ ChoiceRow(label, i == quality, tick = true) { quality = i }+ }+ }+ Spacer(Modifier.height(24.dp))+ Group { SwitchLine("HEVC", hevc) { hevc = it } }+ }+ else -> {+ Group {+ Row(+ Modifier.fillMaxWidth().height(47.dp).clickable { picking = true }.padding(horizontal = 16.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text("Background color", color = Ink, fontSize = 15.sp, modifier = Modifier.weight(1f))+ Box(Modifier.size(24.dp).clip(CircleShape).background(Color(0xFF000000 or background.toLong())).border(1.dp, Color(0xFF555555), CircleShape))+ }+ }+ Spacer(Modifier.height(24.dp))+ Group { SwitchLine("Background hidden", hidden) { hidden = it } }+ }+ }+ }+ // the keypad, while a size is typed+ if (section == 0 && field != null) {+ Keypad(+ Modifier.align(Alignment.BottomCenter),+ unit,+ onUnit = {+ commit()+ convert(it)+ },+ onKey = { k ->+ when (k) {+ "⌫" -> typed = typed.dropLast(1)+ "." -> if ('.' !in typed && field != Field.DPI && unit != SizeUnit.PIXELS) typed += "."+ else -> if (typed.length < 7) typed += k+ }+ },+ onNext = {+ commit()+ field = when (field) { Field.WIDTH -> Field.HEIGHT; Field.HEIGHT -> Field.DPI; else -> Field.WIDTH }+ },+ onDone = {+ commit()+ field = null+ },+ )+ }+ // the background's colour, in a compact picker hanging from its swatch (60 in from the+ // right, under the row) at the screen's edge+ if (picking && section == 3) {+ Box(Modifier.fillMaxSize().pointerInput(Unit) { detectTapGestures { picking = false } })+ val pick = remember { HeldColor(background) { background = it } }+ CompactColors(vm, pick, arrowX = 200.dp, modifier = Modifier.offset(x = maxWidth - 260.dp, y = 168.dp))+ }+ }+}++/** One of the header capsule's words, a button. */+@Composable+private fun CapsuleText(label: String, onClick: () -> Unit) {+ Box(Modifier.fillMaxHeight().clickable(onClick = onClick).padding(horizontal = 13.dp), contentAlignment = Alignment.Center) {+ Text(label, color = Color(0xFFA5A5A5), fontSize = 17.sp)+ }+}++/** RGB or CMYK: which profiles the colour profile page lists, as wide as the list, the chosen half blue. */+@Composable+private fun KindSwitch(cmyk: Boolean, onChange: (Boolean) -> Unit) {+ Row(Modifier.fillMaxWidth().height(34.dp).clip(CircleShape).background(SwitchTrack).padding(2.dp)) {+ for ((i, label) in listOf("RGB", "CMYK").withIndex()) {+ val on = cmyk == (i == 1)+ val ink = if (on) Color.White else SwitchIdle+ Row(+ Modifier.weight(1f).fillMaxHeight().clip(CircleShape).background(if (on) Pc.Accent else Color.Transparent).clickable { onChange(i == 1) },+ horizontalArrangement = Arrangement.Center,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Icon(if (i == 0) PcIcons.ProfileRgb else PcIcons.ProfileCmyk, contentDescription = null, tint = ink, modifier = Modifier.size(20.dp))+ Text(label, color = ink, fontSize = 15.sp, modifier = Modifier.padding(start = 8.dp))+ }+ }+ }+}++@Composable+private fun Group(content: @Composable ColumnScope.() -> Unit) {+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(16.dp)).background(PanelFill), content = content)+}++@Composable+private fun Line() {+ Box(Modifier.fillMaxWidth().height(1.dp).background(ScreenFill))+}++@Composable+private fun SizeRow(label: String, value: String, unit: String, editing: Boolean, onClick: () -> Unit) {+ Row(Modifier.fillMaxWidth().height(47.dp).clickable(onClick = onClick).padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {+ Text(label, color = Ink, fontSize = 15.sp, modifier = Modifier.weight(1f))+ Text(value, color = if (editing) Editing else Ink, fontSize = 15.sp)+ if (unit.isNotEmpty()) Text(" $unit", color = Ink, fontSize = 15.sp)+ }+}++@Composable+private fun ChoiceRow(label: String, chosen: Boolean, detail: String? = null, tick: Boolean = false, onClick: () -> Unit) {+ Row(+ Modifier.fillMaxWidth().height(47.dp).background(if (chosen) Pc.Accent else Color.Transparent).clickable(onClick = onClick).padding(horizontal = 16.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(label, color = if (chosen) Color.White else Ink, fontSize = 15.sp, modifier = Modifier.weight(1f))+ if (detail != null) Text(detail, color = if (chosen) Color.White else Ink, fontSize = 15.sp)+ if (tick && chosen) Icon(PcIcons.MenuTick, contentDescription = null, tint = Color.White, modifier = Modifier.size(20.dp))+ }+}++@Composable+private fun SwitchLine(label: String, on: Boolean, onChange: (Boolean) -> Unit) {+ Row(Modifier.fillMaxWidth().height(47.dp).clickable { onChange(!on) }.padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {+ Text(label, color = Ink, fontSize = 15.sp, modifier = Modifier.weight(1f))+ Switch(on, enabled = true)+ }+}++/** The keypad: units on the left, the digits, and Backspace, Next and Done on the right. */+@Composable+private fun Keypad(modifier: Modifier, unit: SizeUnit, onUnit: (SizeUnit) -> Unit, onKey: (String) -> Unit, onNext: () -> Unit, onDone: () -> Unit) {+ Box(modifier.fillMaxWidth().height(342.dp).background(KeypadFill), contentAlignment = Alignment.Center) {+ Row(horizontalArrangement = Arrangement.spacedBy(30.dp)) {+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+ for (u in listOf(SizeUnit.MILLIMETERS, SizeUnit.CENTIMETERS, SizeUnit.INCHES, SizeUnit.PIXELS)) {+ Key(u.label, if (u == unit) UnitChosen else KeyFill, if (u == unit) Color(0xFF1F1F1F) else Ink, 15.sp) { onUnit(u) }+ }+ }+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+ for (row in listOf(listOf("7", "8", "9"), listOf("4", "5", "6"), listOf("1", "2", "3"))) {+ Row(horizontalArrangement = Arrangement.spacedBy(9.dp)) { for (k in row) Key(k, DigitFill, Ink, 26.sp) { onKey(k) } }+ }+ Row(horizontalArrangement = Arrangement.spacedBy(9.dp)) {+ Key("0", DigitFill, Ink, 26.sp, width = 249) { onKey("0") }+ Key(".", DigitFill, Ink, 26.sp) { onKey(".") }+ }+ }+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+ Key("Backspace", KeyFill, Ink, 15.sp) { onKey("⌫") }+ Key("Next", KeyFill, Ink, 15.sp) { onNext() }+ Key("Done", KeyFill, Ink, 15.sp, height = 150) { onDone() }+ }+ }+ }+}++@Composable+private fun Key(label: String, fill: Color, ink: Color, size: androidx.compose.ui.unit.TextUnit, width: Int = 120, height: Int = 71, onClick: () -> Unit) {+ Box(Modifier.size(width.dp, height.dp).clip(RoundedCornerShape(8.dp)).background(fill).clickable(onClick = onClick), contentAlignment = Alignment.Center) {+ Text(label, color = ink, fontSize = size)+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Eyedropper.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Eyedropper.ktnew file mode 100644index 0000000..19e9891--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Eyedropper.kt@@ -0,0 +1,97 @@+package io.github.artcraftandroid.procraft.ui++import android.graphics.BlurMaskFilter+import androidx.compose.foundation.Canvas+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.size+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.FilterQuality+import androidx.compose.ui.graphics.Paint+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.graphics.drawscope.clipPath+import androidx.compose.ui.graphics.drawscope.drawIntoCanvas+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.procraft.canvas.PickState+import kotlin.math.roundToInt++private val LoupeOuter = 69.dp+private val LoupeInner = 53.5.dp+private val LoupeLift = 41.dp++/** The bar under the top bar while the eyedropper is open. */+@Composable+fun PickingBar(modifier: Modifier = Modifier) {+ Box(modifier.fillMaxWidth().height(24.dp).background(Pc.MessageBar), contentAlignment = Alignment.Center) {+ Text("Picking color from canvas", color = Pc.MessageText, fontSize = 14.sp)+ }+}++/**+ * The eyedropper's loupe, centred [LoupeLift] above the finger: a ring whose top half is the colour+ * under the finger and bottom half the current colour, around what is shown there at twice the size.+ */+@Composable+fun Loupe(pick: PickState, current: Color) {+ val density = LocalDensity.current+ val side = with(density) { (LoupeOuter * 2 + 12.dp).roundToPx() }+ val cx = pick.x.roundToInt()+ val cy = pick.y.roundToInt() - with(density) { LoupeLift.roundToPx() }+ Canvas(Modifier.offset { IntOffset(cx - side / 2, cy - side / 2) }.size(with(density) { side.toDp() })) {+ val c = center+ val outer = LoupeOuter.toPx()+ val inner = LoupeInner.toPx()+ drawIntoCanvas { canvas ->+ val shadow = Paint().apply {+ color = Color(0x40000000)+ asFrameworkPaint().maskFilter = BlurMaskFilter(3.dp.toPx(), BlurMaskFilter.Blur.NORMAL)+ }+ canvas.drawCircle(c + Offset(0f, 1.5.dp.toPx()), outer, shadow)+ }+ val ringMid = (outer + inner) / 2f+ val ring = Stroke(outer - inner)+ val arcBox = Rect(c.x - ringMid, c.y - ringMid, c.x + ringMid, c.y + ringMid)+ val picked = pick.rgb?.let { CanvasSpace.color(it) } ?: current+ drawArc(picked, 180f, 180f, false, arcBox.topLeft, arcBox.size, style = ring)+ drawArc(current, 0f, 180f, false, arcBox.topLeft, arcBox.size, style = ring)+ pick.image?.let { image ->+ clipPath(Path().apply { addOval(Rect(c, inner)) }) {+ val shown = (inner * 2).roundToInt()+ drawImage(+ image,+ dstOffset = IntOffset((c.x - shown / 2f).roundToInt(), (c.y - shown / 2f).roundToInt()),+ dstSize = IntSize(shown, shown),+ filterQuality = FilterQuality.None,+ )+ }+ }+ val edge = Stroke(0.5.dp.toPx())+ drawCircle(Pc.LoupeEdge, outer, c, style = edge)+ drawCircle(Pc.LoupeEdge, inner, c, style = edge)+ // the crosshair inverts what is under it+ val arm = Size(2.dp.toPx(), 1.dp.toPx())+ val gap = 1.75.dp.toPx()+ for ((dx, dy) in listOf(1f to 0f, -1f to 0f, 0f to 1f, 0f to -1f)) {+ val size = if (dx != 0f) arm else Size(arm.height, arm.width)+ val x = if (dx > 0f) c.x + gap else if (dx < 0f) c.x - gap - arm.width else c.x - arm.height / 2f+ val y = if (dy > 0f) c.y + gap else if (dy < 0f) c.y - gap - arm.width else c.y - arm.height / 2f+ drawRect(Color.White, Offset(x, y), size, blendMode = BlendMode.Difference)+ }+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/GalleryScreen.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/GalleryScreen.ktnew file mode 100644index 0000000..d79cd21--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/GalleryScreen.kt@@ -0,0 +1,1043 @@+package io.github.artcraftandroid.procraft.ui++import androidx.compose.animation.togetherWith+import kotlinx.coroutines.launch+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.gestures.detectHorizontalDragGestures+import androidx.activity.compose.BackHandler+import android.graphics.BitmapFactory+import android.graphics.BlurMaskFilter+import androidx.compose.foundation.ExperimentalFoundationApi+import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.requiredWidth+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.grid.GridCells+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid+import androidx.compose.foundation.lazy.grid.items+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.AlertDialog+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.material3.TextField+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.produceState+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.layout.boundsInWindow+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.drawscope.clipPath+import androidx.compose.animation.core.tween+import androidx.compose.foundation.Canvas+import androidx.compose.ui.layout.positionInWindow+import androidx.compose.ui.focus.onFocusChanged+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.draw.blur+import androidx.compose.ui.draw.drawBehind+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.graphics.Paint+import androidx.compose.ui.graphics.StrokeCap+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.graphics.drawscope.drawIntoCanvas+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalView+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import io.github.artcraftandroid.procraft.gallery.Artwork+import io.github.artcraftandroid.procraft.gallery.CanvasPreset+import androidx.compose.animation.core.animateFloatAsState+import androidx.compose.animation.core.snap+import androidx.compose.animation.core.spring+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.unit.IntOffset+import kotlin.math.roundToInt+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.delay+import kotlinx.coroutines.withContext+import kotlin.math.max+import kotlin.math.min++/**+ * A gallery cell's sizes: its pitch both ways (the screen's width over the columns, three upright+ * and four on its side), the content's width (40 less) and the thumbnail box's height (82 less).+ */+private data class CellSize(val pitch: Dp, val width: Dp, val thumb: Dp)++private fun cellSize(screenWidth: Dp, columns: Int): CellSize {+ val pitch = screenWidth / columns+ return CellSize(pitch, pitch - 40.dp, pitch - 82.dp)+}++private val LocalCell = androidx.compose.runtime.staticCompositionLocalOf { cellSize(747.dp, 3) }+private val NewCanvasWidth = 347.dp++/** How long an artwork can take to open before the gallery says it is opening. */+private const val SLOW_OPENING_MS = 500L++/** The gallery: every artwork as a thumbnail; + makes a new canvas. */+@OptIn(ExperimentalFoundationApi::class)+@Composable+fun GalleryScreen(vm: CanvasViewModel) {+ var newCanvas by remember { mutableStateOf(false) }+ // where each stack's cell is (window pixels), for its artworks to fly out of as it opens+ val stackCellAt = remember { mutableMapOf<String, androidx.compose.ui.geometry.Rect>() }+ var renaming by remember { mutableStateOf<Artwork?>(null) }+ var deleting by remember { mutableStateOf<Artwork?>(null) }+ // the artwork (by folder) whose actions a swipe left is showing+ var swiped by remember { mutableStateOf<String?>(null) }+ // Select: the artworks picked, by folder+ var selecting by remember { mutableStateOf(false) }+ val selected = remember { mutableStateListOf<String>() }+ var moreOpen by remember { mutableStateOf(false) }+ // Share's formats, open for these artworks+ var sharing by remember { mutableStateOf<GalleryShare?>(null) }+ // artworks waiting for their PDF's quality+ var pdfFor by remember { mutableStateOf<List<Artwork>?>(null) }+ var deletingSelected by remember { mutableStateOf(false) }+ var previewing by remember { mutableStateOf<List<Artwork>?>(null) }+ val context = androidx.compose.ui.platform.LocalContext.current+ val scope = rememberCoroutineScope()+ fun picked() = vm.artworks.filter { it.dir.name in selected }+ fun endSelecting() {+ selecting = false+ selected.clear()+ moreOpen = false+ }+ val importFile = androidx.activity.compose.rememberLauncherForActivityResult(androidx.activity.result.contract.ActivityResultContracts.OpenDocument()) { uri ->+ uri?.let(vm::importFile)+ }+ val photo = androidx.activity.compose.rememberLauncherForActivityResult(androidx.activity.result.contract.ActivityResultContracts.PickVisualMedia()) { uri ->+ uri?.let(vm::newFromPicture)+ }+ if (vm.openStack != null && !selecting) BackHandler { vm.showStack(null) }+ BoxWithConstraints(Modifier.fillMaxSize().background(Pc.GalleryBackground)) {+ val (screenWidth, screenHeight) = maxWidth to maxHeight+ vm.windowPx = androidx.compose.ui.unit.IntSize(constraints.maxWidth, constraints.maxHeight)+ // out of focus while an artwork is being renamed+ val blur by androidx.compose.animation.core.animateDpAsState(+ if (renaming != null) RenameBlur else 0.dp,+ if (renaming != null) tween(300) else tween(150),+ label = "blur",+ )+ Column(Modifier.fillMaxSize().then(if (blur > 0.dp) Modifier.blur(blur) else Modifier)) {+ if (selecting) {+ SelectHeader(+ title = vm.openStack?.name ?: "ProCraft",+ any = selected.isNotEmpty(),+ onShare = { sharing = GalleryShare(picked(), null) },+ onDelete = { deletingSelected = true },+ onMore = { moreOpen = !moreOpen },+ onDone = ::endSelecting,+ )+ } else {+ GalleryHeader(+ stack = vm.openStack?.name,+ onBack = { vm.showStack(null) },+ onSelect = { selecting = true },+ onNew = { newCanvas = !newCanvas },+ onImport = { importFile.launch(arrayOf("*/*")) },+ onPhoto = { photo.launch(androidx.activity.result.PickVisualMediaRequest(androidx.activity.result.contract.ActivityResultContracts.PickVisualMedia.ImageOnly)) },+ )+ }+ // into a stack the gallery goes at once and the stack's artworks fly out of its cell to+ // their places; back out, they fly back into it as the gallery grows back into place+ // under them, fading in+ androidx.compose.animation.AnimatedContent(+ targetState = vm.openStack to vm.galleryEntries,+ contentKey = { it.first?.dir?.path },+ transitionSpec = {+ if (targetState.first != null && initialState.first == null) {+ androidx.compose.animation.EnterTransition.None togetherWith androidx.compose.animation.fadeOut(snap())+ } else {+ // the stack's artworks fly over the gallery coming back+ androidx.compose.animation.ContentTransform(+ androidx.compose.animation.fadeIn(Motion.stackPop()) ++ androidx.compose.animation.scaleIn(Motion.stackPop(), initialScale = Motion.STACK_POP_SCALE),+ androidx.compose.animation.ExitTransition.KeepUntilTransitionsFinished,+ targetContentZIndex = -1f,+ sizeTransform = null,+ )+ }+ },+ label = "stack",+ ) { (stack, entries) ->+ // where the stack's cell was, for its artworks to fly out of (and back into)+ val stackFrom = remember(stack) { stack?.let { stackCellAt[it.dir.name] } }+ val leaving = transition.targetState == androidx.compose.animation.EnterExitState.PostExit+ if (entries.isEmpty()) {+ Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {+ Text("Tap + to start a new canvas", color = Pc.GalleryText, fontSize = 17.sp)+ }+ } else {+ val columns = if (screenWidth > screenHeight) 4 else 3+ val cell = cellSize(screenWidth, columns)+ androidx.compose.runtime.CompositionLocalProvider(LocalCell provides cell) {+ // the whole screen under the header, so artworks flying in from a stack lower down+ // aren't clipped by a grid of one short row+ LazyVerticalGrid(+ modifier = Modifier.fillMaxSize(),+ state = if (stack == null) vm.galleryGrid else androidx.compose.foundation.lazy.grid.rememberLazyGridState(),+ columns = GridCells.Fixed(columns),+ contentPadding = PaddingValues(bottom = 24.dp),+ ) {+ items(entries, key = { it.dir.name }) { entry ->+ if (entry is io.github.artcraftandroid.procraft.gallery.Stack) {+ StackCell(entry, vm.galleryVersion, dim = selecting, onPlaced = { stackCellAt[entry.dir.name] = it }) {+ if (!selecting) vm.showStack(entry)+ }+ return@items+ }+ val a = entry as Artwork+ val chosen = a.dir.name in selected+ val view = LocalView.current+ // swiped open, it fades back and its actions grow in over it+ val open = androidx.compose.animation.core.animateFloatAsState(+ if (swiped == a.dir.name) 1f else 0f, Motion.swipeActions(), label = "swipe",+ ).value+ // held, its thumbnail shrinks, then lifts (to be dragged out), and settles when let go+ val lift = remember { androidx.compose.animation.core.Animatable(1f) }+ val cellScope = rememberCoroutineScope()+ Box(Modifier.flyIn(stackFrom, Motion.stackPushMove()).flyOut(stackFrom, leaving, Motion.stackPop())) {+ // across the whole column, so the thumbnail sits in its middle as a stack's does+ Column(+ Modifier.fillMaxWidth().height(cell.pitch).graphicsLayer { alpha = 1f - SWIPED_FADE * open.coerceIn(0f, 1f) }.pointerInput(a, selecting, chosen) {+ // a tap opens it (or picks it), and on its name renames it; swiped left, its+ // actions show (right, they go); held and moved, it is dragged out to other apps+ awaitEachGesture {+ val down = awaitFirstDown()+ // a moment held before it shrinks, so a scroll starting on it leaves it be+ val press = cellScope.launch {+ kotlinx.coroutines.delay(Motion.ARTWORK_PRESS_DELAY_MS)+ lift.animateTo(Motion.ARTWORK_PRESSED, Motion.artworkPress())+ }+ try {+ var up: androidx.compose.ui.input.pointer.PointerInputChange? = null+ var moved: Offset? = null+ val held = withTimeoutOrNull(viewConfiguration.longPressTimeoutMillis) {+ while (up == null && moved == null) {+ val c = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break+ val d = c.position - down.position+ if (!c.pressed) up = c else if (d.getDistance() > viewConfiguration.touchSlop) moved = d+ }+ false+ } ?: true+ val d = moved+ if (d != null) {+ if (!selecting && kotlin.math.abs(d.x) > kotlin.math.abs(d.y)) swiped = if (d.x < 0f) a.dir.name else null+ return@awaitEachGesture+ }+ if (!held) {+ up?.let {+ it.consume()+ when {+ // a tap puts away the actions showing+ swiped != null -> swiped = null+ !selecting && it.position.y > (39.dp + cell.thumb + 8.dp).toPx() -> renaming = a+ !selecting -> vm.openArtwork(a)+ chosen -> selected.remove(a.dir.name)+ else -> selected.add(a.dir.name)+ }+ }+ return@awaitEachGesture+ }+ if (selecting) return@awaitEachGesture+ view.performHapticFeedback(android.view.HapticFeedbackConstants.LONG_PRESS)+ cellScope.launch { lift.animateTo(Motion.ARTWORK_LIFTED, Motion.artworkLift()) }+ while (true) {+ val c = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break+ c.consume()+ if (!c.pressed) break+ if ((c.position - down.position).getDistance() > viewConfiguration.touchSlop) {+ io.github.artcraftandroid.procraft.gallery.startArtworkDrag(view, a, vm.store.root)+ break+ }+ }+ } finally {+ press.cancel()+ cellScope.launch { lift.animateTo(1f, Motion.artworkDrop()) }+ }+ }+ },+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ Box(+ Modifier.padding(top = 39.dp).size(cell.width, cell.thumb).graphicsLayer {+ scaleX = lift.value+ scaleY = lift.value+ },+ contentAlignment = Alignment.BottomCenter,+ ) {+ // where it is, for zooming into it, unless the gallery is zooming itself+ Thumbnail(a, vm.galleryVersion, if (selecting) chosen else null) { if (vm.galleryZoom == null) vm.thumbAt[a.dir.name] = it }+ }+ Text(+ a.name,+ color = if (selecting && chosen) Color.White else Pc.GalleryText,+ fontSize = 13.sp,+ fontWeight = FontWeight.SemiBold,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.padding(top = 12.dp),+ )+ Text("${a.width} × ${a.height}px", color = Pc.GallerySize, fontSize = 10.sp)+ }+ if (open > 0f) {+ SwipeActions(+ open,+ // centred on the thumbnail's frame+ Modifier.align(Alignment.TopCenter).padding(top = 39.dp + cell.thumb / 2 - SwipePillHeight / 2),+ onShare = { at -> sharing = GalleryShare(listOf(a), at) },+ onDuplicate = {+ swiped = null+ vm.duplicateArtwork(a)+ },+ onDelete = {+ swiped = null+ deleting = a+ },+ )+ }+ }+ }+ }+ }+ }+ }+ }++ if (newCanvas) Box(Modifier.fillMaxSize().pointerInput(Unit) { detectTapGestures { newCanvas = false } })+ // hangs from the + button, 2 dp from the screen's edge, and grows out of its arrow+ val newLeft = maxWidth - 2.dp - NewCanvasWidth+ val newArrow = maxWidth - 49.dp - newLeft+ MenuPresence(newCanvas, androidx.compose.ui.graphics.TransformOrigin(newArrow / NewCanvasWidth, 0f)) { look ->+ NewCanvasPanel(+ Modifier.offset(x = newLeft, y = 56.5.dp).then(look), arrowX = newArrow, presets = vm.canvasPresets,+ // Custom Canvas opens over the list, which is still there when it closes+ onCustom = { vm.openCustomCanvas() },+ onEdit = { vm.openCustomCanvas(it) },+ onDelete = vm::deletePreset,+ onPick = {+ newCanvas = false+ vm.newPresetArtwork(it)+ },+ ) { w, h ->+ newCanvas = false+ vm.newArtwork(w, h)+ }+ }+ if (moreOpen) Box(Modifier.fillMaxSize().pointerInput(Unit) { detectTapGestures { moreOpen = false } })+ // under More, kept 4 from the screen's edge+ val morePlace = popoverPlace(250.dp, maxWidth - 20.dp - 44.dp - 13.dp - 61.dp / 2, maxWidth, minRight = 4.dp)+ MenuPresence(moreOpen, androidx.compose.ui.graphics.TransformOrigin(morePlace.arrowX / 250.dp, 0f)) { look ->+ val place = morePlace+ MoreOptions(+ Modifier.offset(x = place.left, y = 60.dp).then(look),+ place.arrowX,+ count = selected.size,+ canStack = vm.openStack == null,+ onStack = {+ moreOpen = false+ vm.stackArtworks(picked())+ endSelecting()+ },+ onPreview = {+ moreOpen = false+ previewing = picked()+ },+ onDuplicate = {+ moreOpen = false+ picked().forEach(vm::duplicateArtwork)+ endSelecting()+ },+ )+ }+ // Share's formats: beside a swiped artwork's Share, or under Select's+ var shown by remember { mutableStateOf<GalleryShare?>(null) }+ sharing?.let { shown = it }+ if (sharing != null) Box(Modifier.fillMaxSize().pointerInput(Unit) { detectTapGestures { sharing = null } })+ shown?.let { share ->+ val density = LocalDensity.current.density+ val from = share.from?.let { r -> androidx.compose.ui.geometry.Rect(r.left / density, r.top / density, r.right / density, r.bottom / density) }+ val place = formatsPlace(from, maxWidth, maxHeight, selectShareCentre(maxWidth))+ MenuPresence(sharing != null, place.origin) { look ->+ ImageFormats(Modifier.offset(x = place.left, y = place.top).then(look), place.side, place.arrowAt) { format ->+ sharing = null+ swiped = null+ val animated = CanvasViewModel.Animated.entries.firstOrNull { it.title == format }+ if (animated != null) {+ share.artworks.firstOrNull()?.let { vm.openForAnimatedExport(it, animated) }+ if (selecting) endSelecting()+ } else if (format == "PDF") {+ pdfFor = share.artworks+ } else {+ scope.launch {+ val (files, mime) = vm.shareableFiles(share.artworks, format)+ if (files.isNotEmpty()) shareFiles(context, files, mime) else vm.message = "The artwork could not be exported."+ }+ }+ }+ }+ }+ PdfQualityAlert(pdfFor != null, onCancel = { pdfFor = null }) { quality ->+ val list = pdfFor.orEmpty()+ pdfFor = null+ scope.launch {+ val (files, mime) = vm.shareableFiles(list, "PDF", quality.jpeg)+ if (files.isNotEmpty()) shareFiles(context, files, mime) else vm.message = "The artwork could not be exported."+ }+ }+ previewing?.let { list -> ArtworkPreview(list, vm.galleryVersion) { previewing = null } }+ // a sheet sliding up over the gallery, and back down+ androidx.compose.animation.AnimatedVisibility(+ vm.customCanvasOpen,+ enter = androidx.compose.animation.slideInVertically(Motion.studioIn()) { it },+ exit = androidx.compose.animation.slideOutVertically(Motion.studioOut()) { it },+ ) { CustomCanvasScreen(vm) { newCanvas = false } }+ // only a slow artwork (a big one) shows it is being opened; a quick one just zooms in+ var slowOpening by remember { mutableStateOf(false) }+ LaunchedEffect(vm.opening) {+ slowOpening = false+ if (vm.opening) {+ delay(SLOW_OPENING_MS)+ slowOpening = true+ }+ }+ if (vm.opening && slowOpening) {+ Box(Modifier.fillMaxSize().background(Color(0x66000000)), contentAlignment = Alignment.Center) {+ Text("Opening…", color = Pc.Text, fontSize = 17.sp)+ }+ }+ vm.message?.let { text ->+ LaunchedEffect(text) {+ delay(3000)+ vm.message = null+ }+ }+ FadingValue(renaming, Motion.renameFade()) { a, shown ->+ RenameArtwork(a, vm.galleryVersion, vm.thumbAt[a.dir.name], closing = renaming == null, shown = shown) { name ->+ if (name != a.name) vm.renameArtwork(a, name)+ renaming = null+ }+ }+ FadingValue(vm.message, Motion.message()) { text, shown ->+ Text(+ text,+ color = Pc.Text,+ modifier = Modifier.align(Alignment.BottomCenter).graphicsLayer { alpha = shown }.padding(32.dp).clip(RoundedCornerShape(10.dp))+ .background(Pc.Panel).padding(horizontal = 18.dp, vertical = 12.dp),+ )+ }+ }++ // deleting the picked artworks, or one swiped to+ Alert(+ if (deletingSelected) selected.size else null,+ title = { n -> if (n == 1) "Delete 1 artwork?" else "Delete $n artworks?" },+ message = { "This can't be undone." },+ action = "Delete",+ icon = PcIcons.Trash,+ onCancel = { deletingSelected = false },+ onAction = {+ picked().forEach(vm::deleteArtwork)+ deletingSelected = false+ endSelecting()+ },+ )+ Alert(+ deleting,+ title = { a -> "Delete “${a.name}”?" },+ message = { "This can't be undone." },+ action = "Delete",+ icon = PcIcons.Trash,+ onCancel = { deleting = null },+ onAction = { a ->+ vm.deleteArtwork(a)+ deleting = null+ },+ )+}++/** The title row: the app's name, the select/import/photo capsule and the new-canvas button. */+@Composable+private fun GalleryHeader(stack: String?, onBack: () -> Unit, onSelect: () -> Unit, onNew: () -> Unit, onImport: () -> Unit, onPhoto: () -> Unit) {+ Box(Modifier.fillMaxWidth().height(55.dp)) {+ // into a stack the title changes at once; back out, the stack's name fades out as the+ // gallery's fades in+ androidx.compose.animation.AnimatedContent(+ stack,+ transitionSpec = {+ if (targetState == null) {+ androidx.compose.animation.ContentTransform(+ androidx.compose.animation.fadeIn(Motion.titleIn()),+ androidx.compose.animation.fadeOut(Motion.titleOut()),+ sizeTransform = null,+ )+ } else {+ androidx.compose.animation.ContentTransform(+ androidx.compose.animation.EnterTransition.None,+ androidx.compose.animation.ExitTransition.None,+ sizeTransform = null,+ )+ }+ },+ label = "title",+ ) { name ->+ if (name != null) {+ // in a stack: back to the gallery (blue while touched), and the stack's name+ val touch = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }+ val ink = if (heldOf(touch)) Pc.Accent else Pc.GalleryTitle+ Row(+ Modifier.padding(start = 20.dp, top = 12.dp).height(41.dp).clickable(touch, indication = null, onClick = onBack),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Box(Modifier.width(40.dp), contentAlignment = Alignment.Center) {+ Icon(PcIcons.ChevronLeft, contentDescription = "Back", tint = ink, modifier = Modifier.size(28.dp))+ }+ Text(name, color = ink, fontSize = 36.sp, fontWeight = FontWeight.Bold, maxLines = 1)+ }+ } else {+ Text(+ "ProCraft",+ color = Pc.GalleryTitle,+ fontSize = 36.sp,+ fontWeight = FontWeight.Bold,+ modifier = Modifier.padding(start = 32.dp, top = 11.dp),+ )+ }+ }+ Row(Modifier.align(Alignment.TopEnd).padding(top = 10.dp, end = 20.dp), verticalAlignment = Alignment.CenterVertically) {+ Row(+ Modifier.height(45.dp).clip(CircleShape).background(Pc.Capsule).border(1.dp, Pc.CapsuleEdge, CircleShape),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ for ((label, width) in listOf("Select" to 69.dp, "Import" to 71.dp, "Photo" to 66.dp)) {+ val action: () -> Unit = when (label) {+ "Import" -> onImport+ "Photo" -> onPhoto+ else -> onSelect+ }+ Box(Modifier.width(width).height(45.dp).clickable(onClick = action), contentAlignment = Alignment.Center) {+ Text(label, color = Pc.GalleryText, fontSize = 16.sp)+ }+ }+ }+ Box(Modifier.padding(start = 12.dp).size(44.dp, 45.dp).clickable(onClick = onNew), contentAlignment = Alignment.Center) {+ Box(Modifier.size(42.dp).clip(CircleShape).background(Pc.Capsule).border(1.dp, Pc.CapsuleEdge, CircleShape))+ Icon(PcIcons.Add, contentDescription = "New canvas", tint = Pc.GalleryText, modifier = Modifier.requiredSize(40.dp))+ }+ }+ }+}++/**+ * Select's title row: Share, Delete and More (dimmed until an artwork is picked), and the blue+ * round button that ends selecting.+ */+@Composable+private fun SelectHeader(title: String, any: Boolean, onShare: () -> Unit, onDelete: () -> Unit, onMore: () -> Unit, onDone: () -> Unit) {+ Box(Modifier.fillMaxWidth().height(55.dp)) {+ Text(title, color = Pc.GalleryTitle, fontSize = 36.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 32.dp, top = 11.dp))+ Row(Modifier.align(Alignment.TopEnd).padding(top = 10.dp, end = 20.dp), verticalAlignment = Alignment.CenterVertically) {+ Row(Modifier.height(45.dp).clip(CircleShape).background(Pc.Capsule).border(1.dp, Pc.CapsuleEdge, CircleShape), verticalAlignment = Alignment.CenterVertically) {+ // More opens with nothing picked too (its rows greyed then)+ for ((label, width, action) in listOf(Triple("Share", 65.dp, onShare), Triple("Delete", 70.dp, onDelete), Triple("More", 61.dp, onMore))) {+ val enabled = any || label == "More"+ Box(Modifier.width(width).height(45.dp).clickable(enabled = enabled, onClick = action), contentAlignment = Alignment.Center) {+ Text(label, color = if (enabled) Pc.GalleryTitle else Pc.GallerySize, fontSize = 16.sp)+ }+ }+ }+ Box(Modifier.padding(start = 13.dp).size(44.dp, 45.dp).clip(CircleShape).background(Color(0xFF0190FF)).clickable(onClick = onDone), contentAlignment = Alignment.Center) {+ Icon(PcIcons.DoneTick, contentDescription = "Done", tint = Color.White, modifier = Modifier.requiredSize(40.dp))+ }+ }+ }+}++private val RenameBlur = 20.dp++/** Where a renamed artwork rises to: fitted in a 281 x 280 frame 20 from the top, the field 20 under it. */+private val RenameFrameWidth = 281.dp+private val RenameFrameHeight = 280.dp+private val RenameTop = 20.dp+private val RenameArtMargin = 12.dp+private val RenameFieldGap = 20.dp+private val RenameFieldWidth = 262.dp+private val RenameFieldHeight = 38.dp+private val RenameFieldFill = Color(0x14FFFFFF)++/**+ * Renaming an artwork: it rises from its cell ([from], window pixels) to the top middle, enlarged,+ * with its name in a field under it and the keyboard up. Done, or tapped away, it calls [onDone]+ * with the name and fades away ([closing], [shown]).+ */+@Composable+private fun RenameArtwork(a: Artwork, version: Int, from: androidx.compose.ui.geometry.Rect?, closing: Boolean, shown: Float, onDone: (String) -> Unit) {+ val image by produceState<ImageBitmap?>(null, a.dir.path, a.modified, version) {+ value = withContext(Dispatchers.IO) { BitmapFactory.decodeFile(a.thumbnail.path)?.asImageBitmap() }+ }+ var text by remember(a) { mutableStateOf(androidx.compose.ui.text.input.TextFieldValue(a.name, androidx.compose.ui.text.TextRange(0, a.name.length))) }+ val rise = remember(a) { androidx.compose.animation.core.Animatable(if (from == null) 1f else 0f) }+ LaunchedEffect(a) { rise.animateTo(1f, Motion.renameRise()) }+ val focus = remember { androidx.compose.ui.focus.FocusRequester() }+ LaunchedEffect(a) { focus.requestFocus() }+ var done by remember(a) { mutableStateOf(false) }+ // losing the focus it had (not the lack of it before it is first given) ends the renaming+ var focused by remember(a) { mutableStateOf(false) }+ fun finish() {+ if (done) return+ done = true+ onDone(text.text.trim().ifEmpty { a.name })+ }+ BackHandler(enabled = !closing) { finish() }+ val ratio = if (a.width > 0 && a.height > 0) a.width.toFloat() / a.height else 0.75f+ BoxWithConstraints(+ Modifier.fillMaxSize().graphicsLayer { alpha = if (closing) shown else 1f }+ .pointerInput(a) { detectTapGestures { finish() } },+ ) {+ val density = LocalDensity.current+ var origin by remember { mutableStateOf(Offset.Zero) }+ // the art fitted in its frame, centred across the screen+ val (fw, fh) = (RenameFrameWidth - RenameArtMargin * 2) to (RenameFrameHeight - RenameArtMargin * 2)+ val (aw, ah) = if (ratio > fw / fh) fw to fw / ratio else fh * ratio to fh+ val to = with(density) {+ val left = (maxWidth - aw).toPx() / 2f+ val top = (RenameTop + (RenameFrameHeight - ah) / 2).toPx()+ androidx.compose.ui.geometry.Rect(left, top, left + aw.toPx(), top + ah.toPx())+ }+ val start = from?.translate(-origin) ?: to+ Canvas(Modifier.fillMaxSize().onGloballyPositioned { origin = it.positionInWindow() }) {+ val at = androidx.compose.ui.geometry.lerp(start, to, rise.value)+ val corner = 8.dp.toPx()+ val outline = androidx.compose.ui.graphics.Path().apply {+ addRoundRect(androidx.compose.ui.geometry.RoundRect(at, androidx.compose.ui.geometry.CornerRadius(corner)))+ }+ drawPath(outline, Color.White)+ image?.let { img ->+ clipPath(outline) {+ drawImage(+ img,+ dstOffset = IntOffset(at.left.toInt(), at.top.toInt()),+ dstSize = IntSize(at.width.toInt().coerceAtLeast(1), at.height.toInt().coerceAtLeast(1)),+ )+ }+ }+ }+ androidx.compose.foundation.text.BasicTextField(+ value = text,+ onValueChange = { text = it },+ singleLine = true,+ textStyle = androidx.compose.material3.LocalTextStyle.current.copy(color = Pc.Text, fontSize = 17.sp, textAlign = androidx.compose.ui.text.style.TextAlign.Center),+ cursorBrush = androidx.compose.ui.graphics.SolidColor(Pc.Accent),+ keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(imeAction = androidx.compose.ui.text.input.ImeAction.Done),+ keyboardActions = androidx.compose.foundation.text.KeyboardActions(onDone = { finish() }),+ modifier = Modifier.align(Alignment.TopCenter).padding(top = RenameTop + RenameFrameHeight + RenameFieldGap)+ .size(RenameFieldWidth, RenameFieldHeight).graphicsLayer { alpha = rise.value }+ .clip(RoundedCornerShape(10.dp)).background(RenameFieldFill).focusRequester(focus)+ .onFocusChanged {+ if (it.isFocused) focused = true else if (focused) finish()+ },+ decorationBox = { field -> Box(Modifier.fillMaxSize().padding(horizontal = 12.dp), contentAlignment = Alignment.Center) { field() } },+ )+ }+}++/** How far a swiped artwork fades back under its actions. */+private const val SWIPED_FADE = 0.64f+private val SwipePillWidth = 94.dp+private val SwipePillHeight = 56.dp+private val SwipePillFill get() = if (Pc.light) Color(0xFFF5F5F5) else Color(0xDB1C1C1C)+private val SwipePillInk get() = if (Pc.light) Color(0xFF575757) else Color(0xFFA9A9A9)+private val SwipeDeleteFill = Color(0xFFFE604D)++/**+ * An artwork's actions, Share, Duplicate and Delete, in a row over it: they grow in from the right+ * as it is swiped open ([open], 0..1, springing), and shrink back as it closes.+ */+@Composable+private fun SwipeActions(open: Float, modifier: Modifier, onShare: (androidx.compose.ui.geometry.Rect) -> Unit, onDuplicate: () -> Unit, onDelete: () -> Unit) {+ var shareAt by remember { mutableStateOf(androidx.compose.ui.geometry.Rect.Zero) }+ Row(+ modifier.requiredWidth(SwipePillWidth * 3 + 6.dp).height(SwipePillHeight).graphicsLayer {+ val k = 0.2f + 0.8f * open+ scaleX = k+ scaleY = k+ alpha = open.coerceIn(0f, 1f)+ transformOrigin = androidx.compose.ui.graphics.TransformOrigin(1f, 0.5f)+ },+ horizontalArrangement = Arrangement.spacedBy(3.dp),+ ) {+ for ((label, delete, action) in listOf(Triple("Share", false, { onShare(shareAt) }), Triple("Duplicate", false, onDuplicate), Triple("Delete", true, onDelete))) {+ Box(+ Modifier.size(SwipePillWidth, SwipePillHeight)+ .then(if (label == "Share") Modifier.onGloballyPositioned { shareAt = it.boundsInWindow() } else Modifier)+ .clip(RoundedCornerShape(12.dp))+ .background(if (delete) SwipeDeleteFill else SwipePillFill).clickable(onClick = action),+ contentAlignment = Alignment.Center,+ ) {+ Text(label, color = if (delete) Color.White else SwipePillInk, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, maxLines = 1)+ }+ }+ }+}++/** Artworks to share, and the swiped Share button's place (window pixels); none from Select. */+private class GalleryShare(val artworks: List<Artwork>, val from: androidx.compose.ui.geometry.Rect?)++private val FormatsWidth = 260.dp+private val FormatsTitleHeight = 55.dp+private val FormatsRow = 40.dp+private val FormatsHeight = FormatsTitleHeight + FormatsRow * 10 + 9.dp + 10.dp++/** Where Share's formats go: their top left, the arrow's side and place, and where they grow from. */+private class FormatsPlace(val left: Dp, val top: Dp, val side: ArrowSide, val arrowAt: Dp, val origin: androidx.compose.ui.graphics.TransformOrigin)++/** Select's Share button's centre: left of Delete and More, in the capsule 77 from the right. */+private fun selectShareCentre(screenWidth: Dp): Dp = screenWidth - 20.dp - 44.dp - 13.dp - 61.dp - 70.dp - 65.dp / 2++/**+ * Beside a swiped artwork's Share ([from], dp), pointing at it, on its right where they fit and+ * else on its left, kept 2 inside the screen; with no button, under Select's Share, centred on it+ * and 15 below it, kept 4 inside.+ */+private fun formatsPlace(from: androidx.compose.ui.geometry.Rect?, screenWidth: Dp, screenHeight: Dp, selectShare: Dp): FormatsPlace {+ if (from == null) {+ val left = (selectShare - FormatsWidth / 2).coerceIn(4.dp, (screenWidth - 4.dp - FormatsWidth).coerceAtLeast(4.dp))+ return FormatsPlace(left, 69.dp, ArrowSide.NONE, 0.dp, androidx.compose.ui.graphics.TransformOrigin((selectShare - left) / FormatsWidth, 0f))+ }+ val gap = 2.dp+ val centreY = from.center.y.dp+ val top = (centreY - FormatsHeight / 2).coerceIn(2.dp, (screenHeight - 2.dp - FormatsHeight).coerceAtLeast(2.dp))+ val arrowAt = (centreY - top).coerceIn(Pc.PopoverCorner + Pc.ArrowHeight, FormatsHeight - Pc.PopoverCorner - Pc.ArrowHeight)+ val total = FormatsWidth + Pc.ArrowHeight+ val y = arrowAt / FormatsHeight+ return if (from.right.dp + gap + total <= screenWidth - 2.dp) {+ FormatsPlace(from.right.dp + gap, top, ArrowSide.LEFT, arrowAt, androidx.compose.ui.graphics.TransformOrigin(0f, y))+ } else {+ FormatsPlace((from.left.dp - gap - total).coerceAtLeast(2.dp), top, ArrowSide.RIGHT, arrowAt, androidx.compose.ui.graphics.TransformOrigin(1f, y))+ }+}++/** Share's formats, the animated ones last: a tap on one shares in it. */+@Composable+private fun ImageFormats(modifier: Modifier, side: ArrowSide, arrowAt: Dp, onPick: (String) -> Unit) {+ Popover(FormatsWidth, arrowAt, modifier, fill = Pc.GalleryPopover, side = side) {+ Box(Modifier.height(FormatsTitleHeight).padding(start = 22.dp), contentAlignment = Alignment.CenterStart) {+ Text("Image Format", color = Pc.PanelTitle, fontSize = 24.sp, fontWeight = FontWeight.Bold)+ }+ Column(Modifier.padding(start = 10.dp, end = 10.dp, bottom = 10.dp).clip(RoundedCornerShape(18.dp)).background(Pc.ActionsGroup)) {+ for ((i, format) in CanvasViewModel.SHARE_FORMATS.withIndex()) {+ if (i > 0) Box(Modifier.fillMaxWidth().height(1.dp).background(Pc.ActionsSeparator))+ Box(Modifier.fillMaxWidth().height(FormatsRow).clickable { onPick(format) }.padding(start = 16.dp), contentAlignment = Alignment.CenterStart) {+ Text(format, color = Pc.PanelTitle, fontSize = 17.sp)+ }+ }+ }+ }+}++/** More options for the picked artworks: Preview, Stack (two or more), Duplicate. */+@Composable+private fun MoreOptions(modifier: Modifier, arrowX: Dp, count: Int, canStack: Boolean, onStack: () -> Unit, onPreview: () -> Unit, onDuplicate: () -> Unit) {+ Popover(250.dp, arrowX, modifier, fill = Pc.GalleryPopover) {+ Text("More Options", color = Pc.PanelTitle, fontSize = 24.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 24.dp, top = 14.dp, bottom = 12.dp))+ Column(Modifier.padding(start = 10.dp, end = 10.dp, bottom = 12.dp).clip(RoundedCornerShape(18.dp)).background(Pc.ActionsGroup)) {+ for ((i, row) in listOf(Triple("Preview", true, onPreview), Triple("Stack", canStack && count >= 2, onStack), Triple("Duplicate", true, onDuplicate)).withIndex()) {+ val (label, ready, action) = row+ val enabled = ready && count > 0+ if (i > 0) Box(Modifier.fillMaxWidth().height(1.dp).background(Pc.ActionsSeparator))+ Box(Modifier.fillMaxWidth().height(44.dp).clickable(enabled = enabled, onClick = action).padding(start = 16.dp), contentAlignment = Alignment.CenterStart) {+ Text(label, color = if (enabled) Pc.PanelTitle else Pc.ActionsDisabled, fontSize = 17.sp)+ }+ }+ }+ }+}++/** A stack: its newest artwork on two more cards, the name, and how many it holds; a tap opens it. */+@Composable+private fun StackCell(+ s: io.github.artcraftandroid.procraft.gallery.Stack,+ version: Int,+ dim: Boolean,+ onPlaced: (androidx.compose.ui.geometry.Rect) -> Unit,+ onOpen: () -> Unit,+) {+ val top = s.artworks.firstOrNull() ?: return+ val cell = LocalCell.current+ Column(+ Modifier.height(cell.pitch).onGloballyPositioned { onPlaced(it.boundsInWindow()) }.clickable(onClick = onOpen),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ Box(Modifier.padding(top = 39.dp).size(cell.width, cell.thumb), contentAlignment = Alignment.BottomCenter) {+ // the cards under the top one, a little turned+ for (turn in listOf(5f, -4f)) {+ Box(+ Modifier.fillMaxHeight().aspectRatio(0.75f).graphicsLayer { rotationZ = turn }+ .clip(RoundedCornerShape(8.dp)).background(Color(0xFFF2F2F2)),+ )+ }+ Thumbnail(top, version)+ }+ Text(s.name, color = if (dim) Pc.GallerySize else Pc.GalleryText, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, modifier = Modifier.padding(top = 12.dp))+ Text("${s.artworks.size} artworks", color = Pc.GallerySize, fontSize = 10.sp)+ }+}++/** The picked artworks one at a time over the whole screen; swiped through, tapped to close. */+@Composable+private fun ArtworkPreview(list: List<Artwork>, version: Int, onClose: () -> Unit) {+ var index by remember { mutableIntStateOf(0) }+ val a = list.getOrNull(index) ?: return onClose()+ BackHandler(onBack = onClose)+ Box(+ Modifier.fillMaxSize().background(Color.Black).pointerInput(list) {+ var moved = 0f+ detectHorizontalDragGestures(+ onDragStart = { moved = 0f },+ onDragEnd = {+ if (moved < -60f && index < list.size - 1) index++ else if (moved > 60f && index > 0) index--+ },+ ) { c, dx ->+ c.consume()+ moved += dx+ }+ }.pointerInput(Unit) { detectTapGestures { onClose() } },+ contentAlignment = Alignment.Center,+ ) {+ val image by produceState<ImageBitmap?>(null, a.dir.path, version) {+ value = withContext(Dispatchers.IO) { BitmapFactory.decodeFile(a.thumbnail.path)?.asImageBitmap() }+ }+ image?.let { Image(it, contentDescription = a.name, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize()) }+ }+}++/**+ * An artwork's thumbnail, as large as fits in its cell's box, with a soft shadow; while selecting,+ * a circle at its top right ([chosen]: filled blue with a tick).+ */+@Composable+private fun Thumbnail(a: Artwork, version: Int, chosen: Boolean? = null, onPlaced: (androidx.compose.ui.geometry.Rect) -> Unit = {}) {+ val image by produceState<ImageBitmap?>(null, a.dir.path, a.modified, version) {+ value = withContext(Dispatchers.IO) { BitmapFactory.decodeFile(a.thumbnail.path)?.asImageBitmap() }+ }+ val ratio = if (a.width > 0 && a.height > 0) a.width.toFloat() / a.height else 0.75f+ val cell = LocalCell.current+ val tall = ratio <= cell.width / cell.thumb+ Box(+ Modifier.then(if (tall) Modifier.fillMaxHeight() else Modifier.fillMaxWidth())+ .aspectRatio(ratio, matchHeightConstraintsFirst = tall)+ .onGloballyPositioned { onPlaced(it.boundsInWindow()) }+ .drawBehind {+ drawIntoCanvas { canvas ->+ val shadow = Paint().apply {+ color = Color(0x80000000)+ asFrameworkPaint().maskFilter = BlurMaskFilter(10.dp.toPx(), BlurMaskFilter.Blur.NORMAL)+ }+ canvas.drawRoundRect(0f, 0f, size.width, size.height, 8.dp.toPx(), 8.dp.toPx(), shadow)+ }+ }+ .clip(RoundedCornerShape(8.dp))+ .background(Color.White),+ ) {+ image?.let { Image(it, contentDescription = a.name, contentScale = ContentScale.FillBounds, modifier = Modifier.fillMaxSize()) }+ // the marks fade in as Select starts, and out as it ends+ FadingValue(chosen, Motion.selectMode()) { chosen, shown ->+ Box(+ Modifier.align(Alignment.TopEnd).padding(top = 12.dp, end = 12.dp).size(14.dp).graphicsLayer { alpha = shown }.clip(CircleShape)+ // unpicked, a thin light ring+ .background(if (chosen) Color(0xFF0F7EFD) else Color.Transparent)+ .then(if (chosen) Modifier else Modifier.border(1.dp, Color(0xFFCCCCCC), CircleShape)),+ contentAlignment = Alignment.Center,+ ) {+ if (chosen) Icon(PcIcons.MenuTick, contentDescription = "Picked", tint = Color.White, modifier = Modifier.size(10.dp))+ }+ }+ }+}++/**+ * The new-canvas list: the screen's size first, then the presets, each with its colour profile and+ * size; a preset row swiped left shows Edit and Delete.+ */+@Composable+private fun NewCanvasPanel(+ modifier: Modifier,+ arrowX: Dp,+ presets: List<CanvasPreset>,+ onCustom: () -> Unit,+ onEdit: (Int) -> Unit,+ onDelete: (Int) -> Unit,+ onPick: (CanvasPreset) -> Unit,+ onScreenSize: (Int, Int) -> Unit,+) {+ val root = LocalView.current.rootView+ val (sw, sh) = min(root.width, root.height).coerceAtLeast(1) to max(root.width, root.height).coerceAtLeast(1)+ // the row swiped open, if one is+ var opened by remember { mutableStateOf<Int?>(null) }+ Popover(NewCanvasWidth, arrowX, modifier, fill = Pc.LightPanel, corner = 32.dp) {+ Box(Modifier.fillMaxWidth()) {+ Text(+ "New canvas",+ color = Pc.LightText,+ fontSize = 26.sp,+ fontWeight = FontWeight.Bold,+ modifier = Modifier.padding(start = 23.dp, top = 21.dp, bottom = 20.dp),+ )+ // the button that makes a custom canvas+ Box(+ Modifier.align(Alignment.TopEnd).padding(top = 18.dp, end = 13.dp).size(44.dp, 34.dp).clickable(onClick = onCustom),+ contentAlignment = Alignment.Center,+ ) {+ Box(+ Modifier.size(27.dp, 16.dp).drawBehind {+ drawRoundRect(Pc.LightText, cornerRadius = CornerRadius(4.dp.toPx()))+ val w = 1.6.dp.toPx()+ val c = Offset(8.dp.toPx(), size.height / 2f)+ val arm = 3.6.dp.toPx()+ drawLine(Pc.LightPanel, c - Offset(arm, 0f), c + Offset(arm, 0f), w, StrokeCap.Round)+ drawLine(Pc.LightPanel, c - Offset(0f, arm), c + Offset(0f, arm), w, StrokeCap.Round)+ },+ )+ }+ }+ PresetRow("Screen Size", "$sw × ${sh}px", CanvasPreset.P3, Modifier.padding(horizontal = 9.dp).height(38.dp).clip(CircleShape).background(Pc.LightRowStrong)) { onScreenSize(sw, sh) }+ // the presets scroll past 376 tall+ Column(+ Modifier.padding(start = 9.dp, end = 9.dp, top = 9.5.dp, bottom = 30.dp).heightIn(max = 376.dp).clip(RoundedCornerShape(24.dp)).background(Pc.LightRow)+ .verticalScroll(rememberScrollState()),+ ) {+ presets.forEachIndexed { i, p ->+ if (i > 0) Box(Modifier.padding(start = 16.dp).fillMaxWidth().height(1.dp).background(Pc.LightSeparator))+ SwipeRow(+ p, Modifier.height(if (i > 0) 44.dp else 45.dp), open = opened == i, onOpen = { opened = if (it) i else null },+ onEdit = {+ opened = null+ onEdit(i)+ },+ onDelete = {+ opened = null+ onDelete(i)+ },+ ) {+ if (opened != null) opened = null else onPick(p)+ }+ }+ }+ }+}++// A swiped preset row: how far it slides, and the two buttons it shows+private val SwipeReveal = 159.dp+private val SwipeBehind = Color(0xFFD6D6D6)+private val EditFill = Color(0xFFC6C6C6)+private val EditInk = Color(0xFF575757)+private val DeleteFill = Color(0xFFFE604D)++/** A preset row that slides left under a finger to show Edit and Delete; a tap picks it (or closes it, open). */+@Composable+private fun SwipeRow(p: CanvasPreset, modifier: Modifier, open: Boolean, onOpen: (Boolean) -> Unit, onEdit: () -> Unit, onDelete: () -> Unit, onClick: () -> Unit) {+ val reveal = with(LocalDensity.current) { SwipeReveal.toPx() }+ var dragging by remember { mutableStateOf(false) }+ var dragX by remember { mutableFloatStateOf(0f) }+ val x by animateFloatAsState(if (dragging) dragX else if (open) -reveal else 0f, if (dragging) snap() else Motion.swipeSettle(), label = "swipe")+ Box(modifier.fillMaxWidth()) {+ Row(+ Modifier.matchParentSize().background(SwipeBehind).padding(end = 13.dp),+ horizontalArrangement = Arrangement.End,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ SwipeButton("Edit", EditFill, EditInk, onEdit)+ Spacer(Modifier.width(3.dp))+ SwipeButton("Delete", DeleteFill, Color.White, onDelete)+ }+ PresetRow(+ p.name, p.label, p.profile,+ Modifier.fillMaxSize().offset { IntOffset(x.roundToInt(), 0) }.background(Pc.LightRow).pointerInput(Unit) {+ detectHorizontalDragGestures(+ onDragStart = {+ dragX = x+ dragging = true+ },+ onDragEnd = {+ dragging = false+ onOpen(dragX < -reveal / 2f)+ },+ onDragCancel = { dragging = false },+ ) { change, dx ->+ change.consume()+ dragX = (dragX + dx).coerceIn(-reveal, 0f)+ }+ },+ onClick,+ )+ }+}++@Composable+private fun SwipeButton(label: String, fill: Color, ink: Color, onClick: () -> Unit) {+ Box(Modifier.size(69.dp, 33.dp).clip(RoundedCornerShape(7.dp)).background(fill).clickable(onClick = onClick), contentAlignment = Alignment.Center) {+ Text(label, color = ink, fontSize = 15.sp, fontWeight = FontWeight.SemiBold)+ }+}++@Composable+private fun PresetRow(name: String, label: String, profile: String, modifier: Modifier, onClick: () -> Unit) {+ Row(modifier.fillMaxWidth().clickable(onClick = onClick).padding(start = 17.dp, end = 16.dp), verticalAlignment = Alignment.CenterVertically) {+ Text(name, color = Pc.LightText, fontSize = 17.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))+ Chip(CanvasPreset.chip(profile))+ Chip(label, Modifier.padding(start = 4.dp))+ }+}++@Composable+private fun Chip(text: String, modifier: Modifier = Modifier) {+ Box(modifier.height(18.dp).clip(CircleShape).background(Pc.LightChip).padding(horizontal = 8.dp), contentAlignment = Alignment.Center) {+ Text(text, color = Pc.LightText, fontSize = 13.sp, maxLines = 1)+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/GestureControlsUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/GestureControlsUi.ktnew file mode 100644index 0000000..d704ba7--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/GestureControlsUi.kt@@ -0,0 +1,202 @@+package io.github.artcraftandroid.procraft.ui++import androidx.activity.compose.BackHandler+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.detectHorizontalDragGestures+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.drawBehind+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import io.github.artcraftandroid.procraft.canvas.GestureOption+import io.github.artcraftandroid.procraft.canvas.GestureOptions+import io.github.artcraftandroid.procraft.canvas.GesturePurpose+import io.github.artcraftandroid.procraft.canvas.GestureSettings++private val ScreenFill = Color(0xFF1F1F1F)+private val RailFill = Color(0xFF272727)+private val CardFill = Color(0xFF252525)+private val Ink = Color(0xFFC1C1C1)+private val Detail = Color(0xFF9A9A9A)+private val RailIdle = Color(0xFFAAAAAA)+private val Track = Color(0xFF414141)+// a delay whose way of touching is off: a dark line and a dim knob, no blue+private val TrackOff = Color(0xFF1D1D1D)+private val KnobOff = Color(0xFF333333)+private val DoneBlue = Color(0xFF0190FF)++private fun icon(p: GesturePurpose): ImageVector = when (p) {+ GesturePurpose.SMUDGE -> PcIcons.Smudge+ GesturePurpose.ERASE -> PcIcons.Erase+ GesturePurpose.ASSISTED -> PcIcons.GestureAssisted+ GesturePurpose.EYEDROPPER -> PcIcons.GestureEyedropper+ GesturePurpose.QUICKSHAPE -> PcIcons.GestureQuickShape+ GesturePurpose.QUICKMENU -> PcIcons.GestureQuickMenu+ GesturePurpose.FULL_SCREEN -> PcIcons.GestureFullScreen+ GesturePurpose.CLEAR_LAYER -> PcIcons.GestureClearLayer+ GesturePurpose.COPY_PASTE -> PcIcons.GestureCopyPaste+ GesturePurpose.LAYER_SELECT -> PcIcons.GestureLayerSelect+ GesturePurpose.HOVER -> PcIcons.GestureHover+ GesturePurpose.GENERAL -> PcIcons.GestureGeneral+}++/**+ * Gesture controls, full screen: a rail of what gestures can do and, for the one chosen, a card of+ * switches for the ways of touching that do it (a delay under the held ones), and Done.+ */+@Composable+fun GestureControls(vm: CanvasViewModel) {+ var page by remember { mutableStateOf(GesturePurpose.EYEDROPPER) }+ var resetting by remember { mutableStateOf(false) }+ val settings = vm.gestures+ BackHandler { vm.gestureControlsOpen = false }+ Box(Modifier.fillMaxSize().background(ScreenFill).pointerInput(Unit) { detectTapGestures { } }) {+ Column(Modifier.width(81.dp).fillMaxHeight().background(RailFill).verticalScroll(rememberScrollState()).padding(start = 8.dp, top = 46.dp, bottom = 20.dp)) {+ for (p in GesturePurpose.entries) {+ val chosen = p == page+ Box(+ Modifier.size(65.dp, 53.dp).clip(CircleShape).background(if (chosen) Pc.Accent else Color.Transparent).clickable { page = p },+ contentAlignment = Alignment.Center,+ ) {+ // each drawn in a padded frame, fitted 37 across+ Icon(icon(p), contentDescription = p.title, tint = if (chosen) Color.White else RailIdle, modifier = Modifier.requiredSize(37.dp))+ }+ Spacer(Modifier.height(3.dp))+ }+ }+ Text(page.heading, color = Ink, fontSize = 20.sp, fontWeight = FontWeight.Bold, maxLines = 1, modifier = Modifier.offset(x = 101.dp, y = 28.dp))+ Box(+ Modifier.align(Alignment.TopEnd).padding(top = 20.dp, end = 20.dp).size(44.dp, 45.dp).clip(CircleShape).background(DoneBlue).clickable { vm.gestureControlsOpen = false },+ contentAlignment = Alignment.Center,+ ) {+ Icon(PcIcons.DoneTick, contentDescription = "Done", tint = Color.White, modifier = Modifier.requiredSize(40.dp))+ }+ Column(Modifier.padding(start = 105.dp, end = 24.dp, top = 100.dp).verticalScroll(rememberScrollState())) {+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(25.dp)).background(CardFill)) {+ val options = GestureOptions[page].orEmpty()+ options.forEachIndexed { i, o ->+ if (i > 0) Box(Modifier.fillMaxWidth().height(1.dp).background(ScreenFill))+ OptionRow(o, settings.isOn(page, o.key)) { settings.set(page, o.key, it) }+ if (o.delayed) DelayRow(settings.delay(page), enabled = settings.isOn(page, o.key)) { settings.setDelay(page, it) }+ }+ }+ // under General's settings, everything back as it ships+ if (page == GesturePurpose.GENERAL) {+ Spacer(Modifier.height(14.dp))+ Box(+ Modifier.fillMaxWidth().height(50.dp).clip(RoundedCornerShape(25.dp)).background(CardFill).clickable { resetting = true },+ contentAlignment = Alignment.Center,+ ) {+ Text("Reset to defaults", color = Ink, fontSize = 15.sp, maxLines = 1)+ }+ }+ Spacer(Modifier.height(40.dp))+ }+ }+ Alert(+ if (resetting) Unit else null,+ title = { "Reset gesture controls?" },+ message = { "Every gesture goes back to how the app starts out." },+ action = "Reset",+ onCancel = { resetting = false },+ onAction = {+ settings.resetAll()+ resetting = false+ },+ )+}++/** A way of touching: its name and what it does, and its switch. */+@Composable+private fun OptionRow(o: GestureOption, on: Boolean, onChange: (Boolean) -> Unit) {+ Row(Modifier.fillMaxWidth().height(72.dp).clickable { onChange(!on) }.padding(start = 28.dp, end = 16.dp), verticalAlignment = Alignment.CenterVertically) {+ Column(Modifier.weight(1f)) {+ Text(o.label, color = Ink, fontSize = 18.sp, fontWeight = FontWeight.Medium, maxLines = 1)+ Text(o.detail, color = Detail, fontSize = 13.sp, maxLines = 1)+ }+ Switch(on, enabled = true)+ }+}++/** How long a hold waits, 0.1 to 1.5 seconds, dragged or tapped along the bar; greyed while its way of touching is off. */+@Composable+private fun DelayRow(seconds: Float, enabled: Boolean, onChange: (Float) -> Unit) {+ val change by rememberUpdatedState(onChange)+ val span = GestureSettings.MAX_DELAY_S - GestureSettings.MIN_DELAY_S+ val fraction = ((seconds - GestureSettings.MIN_DELAY_S) / span).coerceIn(0f, 1f)+ Row(Modifier.fillMaxWidth().height(44.dp).padding(start = 28.dp, end = 24.dp), verticalAlignment = Alignment.CenterVertically) {+ Text("Delay", color = Ink, fontSize = 15.sp, modifier = Modifier.width(74.dp))+ Box(+ Modifier.weight(1f).fillMaxHeight()+ .then(+ if (!enabled) {+ Modifier+ } else {+ Modifier.pointerInput(Unit) {+ fun at(x: Float) = GestureSettings.MIN_DELAY_S + (x / size.width).coerceIn(0f, 1f) * span+ detectTapGestures { change(at(it.x)) }+ }.pointerInput(Unit) {+ fun at(x: Float) = GestureSettings.MIN_DELAY_S + (x / size.width).coerceIn(0f, 1f) * span+ detectHorizontalDragGestures(onDragStart = { change(at(it.x)) }) { c, _ ->+ c.consume()+ change(at(c.position.x))+ }+ }+ },+ )+ .drawBehind {+ val y = size.height / 2f+ val x = fraction * size.width+ if (enabled) {+ val h = 3.dp.toPx()+ drawRect(Track, Offset(0f, y - h / 2f), Size(size.width, h))+ drawRect(Pc.Accent, Offset(0f, y - h / 2f), Size(x, h))+ val knob = Size(16.dp.toPx(), 10.dp.toPx())+ drawRoundRect(Color.White, Offset(x - knob.width / 2f, y - knob.height / 2f), knob, CornerRadius(knob.height / 2f))+ } else {+ val h = 1.5.dp.toPx()+ drawRect(TrackOff, Offset(0f, y - h / 2f), Size(size.width, h))+ val knob = Size(16.dp.toPx(), 10.dp.toPx())+ drawRoundRect(KnobOff, Offset(x - knob.width / 2f, y - knob.height / 2f), knob, CornerRadius(knob.height / 2f))+ }+ },+ )+ Text("%.2fs".format(seconds), color = Ink, fontSize = 15.sp, modifier = Modifier.padding(start = 16.dp))+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/GuideUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/GuideUi.ktnew file mode 100644index 0000000..f0bea8a--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/GuideUi.kt@@ -0,0 +1,257 @@+package io.github.artcraftandroid.procraft.ui++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import io.github.artcraftandroid.procraft.core.GuideType+import io.github.artcraftandroid.procraft.core.SymmetryType+import kotlin.math.roundToInt+import kotlin.math.sqrt++private val GuideTop = Color(0xFF1F1F1F)+private val GuideButton = Color(0xFF1C1C1C)+private val GuideButtonEdge = Color(0xFF383838)+private val GuideTitle = Color(0xFFD8D8D8)+private val GuideDone = Color(0xFF0190FF)+private val GuideNote = Color(0xFF4A4A4A)+private val GuideNodeCentre = Color(0xFF0A84FF)+private val GuideNodeTurn = Color(0xFF30D158)++/** The colour bar's stops, as the engine's (dark through blue, green, orange, red, pink, white). */+private val BAR = listOf(+ 0xFF05040A, 0xFF010C2C, 0xFF001857, 0xFF083984, 0xFF128BB6, 0xFF19C6CB, 0xFF1BD0B8, 0xFF2FD083, 0xFF67C064, 0xFFBC9B4C, 0xFFCE9049,+ 0xFFD97644, 0xFFDA574A, 0xFFDC414D, 0xFFE53D71, 0xFFEC36AB, 0xFFF534DE, 0xFFF55CF9, 0xFFFB92FD, 0xFFFCCAFF, 0xFFE8E1E9,+).map { Color(it) }++/** A grid size slider's position for a size, and back (canvas pixels, 10 to 500). */+private fun sizeToSlider(px: Float) = sqrt(((px - 10f) / 490f).coerceIn(0f, 1f))+private fun sliderToSize(v: Float) = 10f + v * v * 490f++/** The drawing guide's lines over the canvas while it is on (and its handles while editing). */+@Composable+fun GuideOverlay(vm: CanvasViewModel) {+ val g = vm.guide ?: return+ if (!g.on && !vm.guideEditing) return+ val density = androidx.compose.ui.platform.LocalDensity.current.density+ val color = Color(g.color.getOrElse(0) { 0f }, g.color.getOrElse(1) { 0f }, g.color.getOrElse(2) { 0f }, g.opacity)+ Canvas(Modifier.fillMaxSize()) {+ val width = (0.25f + 1.5f * g.thickness) * density+ val l = g.lines+ for (i in 0 until l.size / 4) {+ drawLine(color, Offset(l[i * 4], l[i * 4 + 1]), Offset(l[i * 4 + 2], l[i * 4 + 3]), width)+ }+ if (vm.guideEditing) {+ fun node(at: Offset, fill: Color) {+ drawCircle(Color.White, 7.dp.toPx(), at)+ drawCircle(fill, 5.dp.toPx(), at)+ }+ if (g.kind == GuideType.PERSPECTIVE) {+ for (i in 0 until g.vanishing.size / 2) node(Offset(g.vanishing[i * 2], g.vanishing[i * 2 + 1]), GuideNodeCentre)+ } else {+ node(Offset(g.handle[0], g.handle[1]), GuideNodeTurn)+ node(Offset(g.centre[0], g.centre[1]), GuideNodeCentre)+ }+ }+ }+}++/**+ * The guide editor over the canvas: its title with Cancel and Done, the colour bar, the canvas+ * fitted between them and the toolbar (kinds, look and assisted drawing), the guide's handles+ * dragged on the canvas.+ */+@Composable+fun GuideEditor(vm: CanvasViewModel) {+ if (!vm.guideEditing) return+ val g = vm.guide ?: return+ BoxWithConstraints(Modifier.fillMaxSize()) {+ // the canvas: handles dragged, perspective points added; nothing paints+ Box(Modifier.fillMaxSize().pointerInput(Unit) {+ awaitEachGesture {+ val down = awaitFirstDown()+ down.consume()+ val grab = vm.guideGrab(down.position)+ while (true) {+ val ev = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break+ if (!ev.pressed) break+ vm.guideDrag(grab, ev.position)+ ev.consume()+ }+ }+ })+ Box(Modifier.fillMaxWidth().height(82.dp).background(GuideTop)) {+ Text("Drawing Guides", color = GuideTitle, fontSize = 20.sp, fontWeight = FontWeight.Bold, maxLines = 1, modifier = Modifier.offset(32.dp, 27.dp))+ Row(Modifier.align(Alignment.TopEnd).padding(top = 20.dp, end = 20.dp), verticalAlignment = Alignment.CenterVertically) {+ Box(Modifier.size(73.dp, 43.dp).clip(CircleShape).background(GuideButton).border(1.dp, GuideButtonEdge, CircleShape).tap { vm.closeGuideEditor(keep = false) },+ contentAlignment = Alignment.Center) {+ Text("Cancel", color = GuideTitle, fontSize = 17.sp, maxLines = 1)+ }+ Spacer(Modifier.width(13.dp))+ Box(Modifier.size(44.dp).clip(CircleShape).background(GuideDone).tap { vm.closeGuideEditor(keep = true) }, contentAlignment = Alignment.Center) {+ Icon(PcIcons.DoneTick, contentDescription = "Done", tint = Color.White, modifier = Modifier.requiredSize(40.dp))+ }+ }+ }+ ColorBar(g.hue, Modifier.offset(y = 84.dp)) { vm.setGuideLook(hue = it) }+ if (g.kind == GuideType.PERSPECTIVE && g.vanishing.isEmpty()) {+ Box(Modifier.offset(y = 94.dp).fillMaxWidth().height(24.dp).background(GuideNote), contentAlignment = Alignment.Center) {+ Text("Tap to create vanishing points", color = GuideTitle, fontSize = 12.sp, maxLines = 1)+ }+ }+ GuideToolbar(vm, Modifier.align(Alignment.BottomCenter))+ SymmetryOptions(vm, maxWidth, maxHeight)+ }+}++/** The colour bar: the guide's colour picked by dragging along it. */+@Composable+private fun ColorBar(hue: Float, modifier: Modifier, onChange: (Float) -> Unit) {+ val change by rememberUpdatedState(onChange)+ Canvas(+ modifier.fillMaxWidth().height(10.dp).pointerInput(Unit) {+ awaitEachGesture {+ val down = awaitFirstDown()+ down.consume()+ change((down.position.x / size.width).coerceIn(0f, 1f))+ while (true) {+ val ev = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break+ if (!ev.pressed) break+ change((ev.position.x / size.width).coerceIn(0f, 1f))+ ev.consume()+ }+ }+ },+ ) {+ val y = size.height / 2f+ val bar = 5.5.dp.toPx()+ drawRect(Brush.horizontalGradient(BAR), Offset(0f, y - bar / 2f), androidx.compose.ui.geometry.Size(size.width, bar))+ val x = size.width * hue.coerceIn(0f, 1f)+ drawCircle(Color.White, 7.dp.toPx(), Offset(x.coerceIn(7.dp.toPx(), size.width - 7.dp.toPx()), y))+ drawCircle(BAR[(hue * (BAR.size - 1)).roundToInt().coerceIn(0, BAR.size - 1)], 5.5.dp.toPx(), Offset(x.coerceIn(7.dp.toPx(), size.width - 7.dp.toPx()), y))+ }+}++private val GUIDE_KINDS = listOf(+ Triple(GuideType.GRID, "2D Grid", 114.dp),+ Triple(GuideType.ISOMETRIC, "Isometric", 123.dp),+ Triple(GuideType.PERSPECTIVE, "Perspective", 138.dp),+ Triple(GuideType.SYMMETRY, "Symmetry", 129.dp),+)++private fun GuideType.icon() = when (this) {+ GuideType.GRID -> PcIcons.GuideGrid+ GuideType.ISOMETRIC -> PcIcons.GuideIsometric+ GuideType.PERSPECTIVE -> PcIcons.ChromaPerspective+ GuideType.SYMMETRY -> PcIcons.GuideSymmetry+}++/** The guide editor's toolbar: the four kinds, then the kind's look and assisted drawing. */+@Composable+private fun GuideToolbar(vm: CanvasViewModel, modifier: Modifier) {+ val g = vm.guide ?: return+ OptionsPanel(652.dp, 199.dp, modifier, 16.dp) {+ KindsSwitch(546.dp, GUIDE_KINDS.map { (k, label, w) -> Kind(k.icon(), label, w) }, GUIDE_KINDS.indexOfFirst { it.first == g.kind }) {+ vm.chooseGuideKind(GUIDE_KINDS[it].first)+ }+ Spacer(Modifier.height(14.dp))+ Row(Modifier.width(620.dp), horizontalArrangement = Arrangement.spacedBy(20.dp)) {+ OptionSlider("Opacity", g.opacity, shown(g.opacity, max = true), 300.dp) { vm.setGuideLook(opacity = it) }+ OptionSlider("Thickness", g.thickness, shown(g.thickness, max = true), 300.dp) { vm.setGuideLook(thickness = it) }+ }+ Spacer(Modifier.height(8.dp))+ Row(Modifier.width(620.dp).height(54.dp), horizontalArrangement = Arrangement.spacedBy(20.dp), verticalAlignment = Alignment.CenterVertically) {+ when (g.kind) {+ GuideType.GRID, GuideType.ISOMETRIC -> {+ OptionSlider("Grid size", sizeToSlider(g.size), "${g.size.roundToInt()}px", 300.dp) { vm.setGuideLook(size = sliderToSize(it)) }+ AssistedSwitch(vm, g.assisted)+ }+ GuideType.PERSPECTIVE -> AssistedSwitch(vm, g.assisted)+ GuideType.SYMMETRY -> Box(+ Modifier.size(300.dp, 40.dp).clip(RoundedCornerShape(20.dp)).background(Color(0xFF303030)).tap { vm.symmetryOptionsOpen = !vm.symmetryOptionsOpen },+ contentAlignment = Alignment.Center,+ ) {+ Text("Options", color = Color(0xFFD0D0D0), fontSize = 15.sp, maxLines = 1)+ }+ }+ }+ }+}++@Composable+private fun AssistedSwitch(vm: CanvasViewModel, on: Boolean) {+ Row(Modifier.width(300.dp).padding(start = 8.dp), verticalAlignment = Alignment.CenterVertically) {+ Text("Assisted Drawing", color = Color(0xFFD0D0D0), fontSize = 15.sp, maxLines = 1, modifier = Modifier.weight(1f))+ Box(Modifier.tap { vm.setGuideAssisted(!on) }) { Switch(on, enabled = true) }+ }+}++/** Symmetry's options: vertical, horizontal, quadrant or radial; turned instead of mirrored; assisted. */+@Composable+private fun SymmetryOptions(vm: CanvasViewModel, screenWidth: androidx.compose.ui.unit.Dp, screenHeight: androidx.compose.ui.unit.Dp) {+ val g = vm.guide ?: return+ if (!vm.symmetryOptionsOpen || g.kind != GuideType.SYMMETRY) return+ val toolbarLeft = (screenWidth - 652.dp) / 2+ // over the Options button, its arrow at the button's middle+ MenuPopover(150.dp, toolbarLeft + 16.dp, screenHeight - 98.dp) {+ MenuTitle("Guide Options")+ Spacer(Modifier.height(10.dp))+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(13.dp)).background(MenuGroup)) {+ listOf(SymmetryType.VERTICAL to "Vertical", SymmetryType.HORIZONTAL to "Horizontal", SymmetryType.QUADRANT to "Quadrant", SymmetryType.RADIAL to "Radial")+ .forEachIndexed { i, (kind, label) ->+ if (i > 0) Box(Modifier.fillMaxWidth().height(1.dp).background(MenuLine))+ val chosen = g.symmetry == kind+ Row(+ Modifier.fillMaxWidth().height(44.dp).background(if (chosen) Pc.Accent else Color.Transparent).tap { vm.setGuideSymmetry(kind, g.rotational) }+ .padding(start = 16.dp, end = 14.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ MenuLabel(label, if (chosen) Color.White else MenuText, Modifier.weight(1f))+ if (chosen) Icon(PcIcons.MenuTick, contentDescription = null, tint = Color.White, modifier = Modifier.size(29.dp))+ }+ }+ }+ Spacer(Modifier.height(14.dp))+ Row(Modifier.fillMaxWidth().height(40.dp), verticalAlignment = Alignment.CenterVertically) {+ MenuLabel("Rotational Symmetry", MenuText, Modifier.weight(1f))+ Box(Modifier.tap { vm.setGuideSymmetry(g.symmetry, !g.rotational) }) { Switch(g.rotational, enabled = true) }+ }+ Row(Modifier.fillMaxWidth().height(40.dp), verticalAlignment = Alignment.CenterVertically) {+ MenuLabel("Assisted Drawing", MenuText, Modifier.weight(1f))+ Box(Modifier.tap { vm.setGuideAssisted(!g.assisted) }) { Switch(g.assisted, enabled = true) }+ }+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Icons.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Icons.ktnew file mode 100644index 0000000..b3e0c59--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Icons.kt@@ -0,0 +1,586 @@+package io.github.artcraftandroid.procraft.ui++import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.PathFillType+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.graphics.StrokeCap+import androidx.compose.ui.graphics.StrokeJoin+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.graphics.vector.addPathNodes+import androidx.compose.ui.unit.dp++/**+ * ProCraft's own interface icons on a 24-unit grid. The bar's tool icons are solid shapes+ * (drawn with a thin stroke too, which rounds their corners); the rest are outlines.+ */+object PcIcons {+ val FullScreen by lazy { shape("fullscreen", 50f, "M13.4 36.9C11.9 36.5 10.7 35.4 10.2 33.8C9.9 33.2 9.9 15.8 10.2 15.2C10.7 13.6 11.9 12.4 13.5 12.1C14.2 11.9 35.8 11.9 36.5 12.1C38.1 12.4 39.3 13.6 39.8 15.2C40.1 15.8 40.1 33.2 39.8 33.8C39.3 35.4 38.1 36.6 36.5 36.9C35.8 37.1 14.1 37 13.4 36.9zM15.7 33.8C15.9 33.7 16.2 33.4 16.4 33.1C16.5 32.9 16.5 32.7 16.5 27.5C16.5 21.5 16.5 21.9 16.1 21.5C15.5 20.9 14.5 20.9 13.9 21.5C13.5 21.9 13.5 21.5 13.5 27.5C13.5 32.7 13.5 32.9 13.6 33.1C14.1 33.9 14.9 34.2 15.7 33.8zM35.7 17.8C36.2 17.5 36.5 17.1 36.5 16.5C36.5 15.9 36.2 15.5 35.7 15.2C35.4 15 35.4 15 25 15C14.6 15 14.6 15 14.3 15.2C13.1 15.8 13.3 17.5 14.6 17.9C14.7 18 19.4 18 25.1 18C35.4 18 35.4 18 35.7 17.8z") }+ val Actions by lazy { shape("actions", 44f, "M13.3 32.2C12.4 31.9 11.7 30.9 11.7 30.1C11.7 29.4 11.5 29.6 16 25.1C20.1 21 20.1 21 20 20.8C19 18.2 19.4 15.7 21.2 13.7C22.4 12.4 24.6 11.5 26.1 11.7C26.5 11.8 26.5 11.8 25 13.2C23.4 14.8 23.3 15 23.3 15.8C23.3 16.6 23.3 16.6 25.3 18.7C27.4 20.7 27.4 20.7 28.2 20.7C29 20.7 29.2 20.6 30.8 19C32.4 17.4 32.4 17.4 32.3 18.7C31.9 23.1 27.4 25.7 23.2 24C23 23.9 23 23.9 18.9 28C14.9 32 14.8 32.1 14.4 32.2C14 32.3 13.7 32.3 13.3 32.2z") }+ val Adjustments by lazy { shape("adjustments", 44f, "M16.6 32.2C15.8 31.9 15.3 31.2 15.3 30.4C15.2 29.6 15 29.8 19.5 25.4L23.5 21.4L24.8 22.7L26.1 24L22.2 27.9C19.4 30.7 18.2 31.9 18 32C17.6 32.2 16.9 32.3 16.6 32.2zM25.7 21.8L24.3 20.5L26.2 18.6C28.3 16.5 28.5 16.4 29.1 16.4C30.6 16.4 31.5 17.9 30.9 19.1C30.8 19.4 27.1 23.1 27 23.1C27 23.1 26.4 22.5 25.7 21.8zM18.1 22.4C18.1 22.3 17.9 21.5 17.7 20.6C17.4 18.8 17.3 18.6 17.1 18.4C16.8 18.2 16.7 18.1 14.9 17.8C14 17.6 13.2 17.4 13.1 17.4C13 17.4 13.8 17.2 14.9 17C17.4 16.4 17.2 16.7 17.7 14.1C17.9 13.2 18.1 12.3 18.1 12.3C18.1 12.3 18.3 13.1 18.5 14.1C19.1 16.7 18.8 16.4 21.4 17C22.4 17.2 23.2 17.4 23.2 17.4C23.2 17.4 22.4 17.6 21.4 17.8C19.5 18.2 19.4 18.2 19.1 18.5C18.9 18.7 18.9 18.7 18.4 21.1C18.3 21.9 18.1 22.5 18.1 22.4zM24.6 16.7C24.5 16.2 24.2 14.8 24.2 14.8C24.1 14.7 23.8 14.6 23.1 14.4C22.7 14.4 22.4 14.3 22.3 14.3C22.3 14.3 22.6 14.2 23 14.1C24.2 13.8 24.1 13.8 24.2 13.6C24.3 13.5 24.4 13.1 24.4 12.7C24.5 12.3 24.6 12 24.6 11.9C24.6 11.8 24.7 12.1 24.8 12.6C25.1 13.9 25 13.8 26.3 14.1C26.7 14.1 27 14.2 27 14.2C27 14.3 26.6 14.3 26.1 14.4C25 14.7 25.1 14.6 24.8 15.8C24.7 16.3 24.6 16.7 24.6 16.7z") }+ val Selection by lazy { shape("selection", 44f, "M13 32.2C11.6 31.8 11.3 29.9 12.5 29C13 28.7 13 28.7 19.3 28.7C25.9 28.7 25.4 28.6 24.4 29.7C23.4 30.9 22 31.7 20.3 32.1C19.7 32.2 13.5 32.3 13 32.2zM20.6 26.5C20.6 26.5 20.6 26.4 20.7 26.2C20.9 25.3 20.6 24.3 19.7 23.2C18.3 21.5 17.9 20.3 17.8 18.8C17.8 17.2 17.6 17.4 20.1 17.4C22.1 17.4 22.2 17.4 22.2 17.5C22.2 17.5 22.2 17.7 22.2 17.9C22.1 18.8 22.4 19.6 23.3 20.9C24.7 22.7 25.3 24.6 25.1 26.2C25.1 26.6 25.1 26.6 22.8 26.6C21.6 26.6 20.6 26.6 20.6 26.5zM18.5 15.2C19.3 13.8 21.6 12.3 23.7 11.9C24.7 11.7 30.9 11.7 31.2 11.9C32.6 12.6 32.6 14.5 31.2 15.1C30.9 15.3 30.9 15.3 24.7 15.3C19.6 15.3 18.4 15.3 18.5 15.2z") }+ val Transform by lazy { shape("transform", 44f, "M14.9 29.7C14.3 29.5 14 28.7 14.4 28.1C14.5 28 16 26.5 17.7 24.8C20.9 21.6 20.9 21.6 20.7 21.6C20.6 21.5 19.4 21.4 18.1 21.3C16.7 21.2 15.6 21 15.5 21C15.5 21 17.5 20 22.6 17.6C26.5 15.8 29.7 14.3 29.7 14.3C29.7 14.3 28.2 17.5 26.4 21.4C24.5 25.3 23 28.5 23 28.5C23 28.5 22.8 27.3 22.7 25.8C22.6 24.3 22.4 23.1 22.4 23.1C22.4 23.1 20.9 24.5 19 26.4C15.3 30.1 15.5 29.9 14.9 29.7z") }+ val Brush by lazy { shape("brush", 44f, "M8.8 34.4C8.7 34.4 8.5 34.3 8.5 34.3C8.4 34.3 8 33.9 7.9 33.8C7.9 33.6 8 33.5 8.4 33.2C9.8 32.4 10.5 31.6 11.2 29.9C11.6 29.1 11.8 28.7 12.3 28.2C13.9 26.8 17.1 26.2 18 27.2C19.1 28.5 16.7 32.2 13.9 33.5C12.2 34.3 9.9 34.7 8.8 34.4zM18.6 26C18.3 25.7 18.1 25.5 18.1 25.5C18.1 25.3 21 22.1 22.9 20.1C28.1 14.5 32.5 10.9 35.4 9.7C36.1 9.5 36.1 9.5 36.1 9.8C35.6 12.9 28.6 19.7 19.3 26.4C19.1 26.5 19.1 26.5 18.6 26z") }+ val Smudge by lazy { shape("smudge", 44f, "M11 34.7C10.3 34.3 9.9 33.2 10 32.1C10.1 31.4 10.1 31.5 12.6 28.1C13.8 26.4 14.8 25 14.8 25C14.9 24.9 14.5 23.9 14 22.7C13 20.3 13 20.1 13 19.2C13.1 18.3 13.1 18.3 15 15.7C17.2 12.7 17.5 12.4 18.9 12.3C19.5 12.2 25 11.9 25.2 11.9C25.2 11.9 25.8 11.3 26.4 10.6C27.9 9.1 28 9 28.6 9.3C28.9 9.3 33.8 14.4 33.9 14.7C34.1 15.2 34.1 15.3 32.7 16.8L31.5 18.1L31.5 20.4C31.5 22.7 31.5 22.7 31.2 23.4C30.9 24.4 30.4 25.4 30.1 25.9C29.8 26.3 25.4 30.2 25 30.5C24.1 30.9 23.4 30.9 21.5 30.5C21.4 30.4 21.7 30.1 24.5 27.3C27.6 24.2 27.6 24.2 27.6 23.9C27.6 23.5 27.2 23.1 26.8 23.2C26.6 23.3 25.4 24.4 23 26.8C21 28.8 18.3 31.4 17 32.6L14.7 34.8L12.9 34.8C11.3 34.8 11.1 34.8 11 34.7z") }+ val Erase by lazy { shape("erase", 44f, "M16.2 33.6C15.7 33.5 14.8 33.2 14.4 32.8C14.1 32.7 11.1 29.9 8.5 27.4C8.3 27.2 8.3 27.2 10.4 25.2L12.5 23.1L16.7 27.3L20.9 31.5L20.4 32C19 33.3 17.8 33.8 16.2 33.6zM17.4 26.5L13.3 22.3L18.7 16.9C21.7 13.9 24.3 11.4 24.5 11.3C26.1 10.1 28.4 10.1 30 11.3C30.2 11.4 31.5 12.6 33 14.1L35.6 16.7L28.6 23.7C24.8 27.5 21.6 30.7 21.6 30.7C21.6 30.7 19.7 28.8 17.4 26.5z") }+ val Layers by lazy { shape("layers", 44f, "M11.9 33.9C11.2 33.6 10.6 33.1 10.2 32.4C10 32 10 32 10 25.2C10 18.5 10 18.3 10.1 17.9C10.4 17.2 11 16.5 11.8 16.2C12.2 16 12.2 16 18.7 16C26.6 16 26.3 16 27.2 16.8C28 17.7 28 17.4 28 25.3C28 31.8 28 31.8 27.8 32.2C27.5 33 26.9 33.6 26.1 33.9C25.5 34.1 12.4 34.1 11.9 33.9zM29 23C29 18.3 29 17.9 28.9 17.6C28.5 16.4 27.6 15.5 26.4 15.1C26.1 15 25.7 15 21 15L16 15L16 13.8C16 13.1 16 12.4 16.1 12.2C16.2 11.4 16.8 10.6 17.6 10.3C18.1 10 18.1 10 24.8 10C32.4 10 32 10 32.7 10.4C33.2 10.7 33.5 11.1 33.8 11.6C34 12 34 12 34 18.8C34 26.6 34 26.1 33.5 26.9C32.8 27.8 32.3 28 30.4 28L29 28L29 23z") }+ val Undo by lazy { shape("undo", 50f, "M14.4 36.3C12.9 36 12.7 34 14 33.4C14.3 33.3 14.4 33.3 22.1 33.3C30 33.3 30.7 33.3 31.5 33.1C35.6 32.1 37.5 27.2 35.1 23.6C34.4 22.5 33.1 21.6 31.7 21.2C30.8 20.9 30.1 20.9 25.7 20.9L21.6 20.9L21.6 22.7C21.5 24.4 21.5 24.5 21.4 24.8C21 25.5 20.2 25.8 19.5 25.5C18.9 25.2 11.8 20.7 11.5 20.4C11 19.8 11 18.9 11.6 18.3C11.8 18.1 18.9 13.6 19.4 13.4C20.1 13 21 13.3 21.4 14C21.5 14.3 21.5 14.4 21.6 16.1L21.6 17.9L26.3 17.9C30.4 17.9 31.1 17.9 31.6 18C36.1 18.9 39.2 22.6 39.2 27.1C39.2 31.6 36.1 35.3 31.6 36.2C31 36.3 14.9 36.4 14.4 36.3z") }+ val Redo by lazy { shape("redo", 50f, "M19.5 36.2C14.5 35.8 10.8 31.4 11.1 26.4C11.4 22.4 14.4 19 18.3 18.1C19.3 17.9 20.2 17.9 24.5 17.9L28.7 17.9L28.7 16.1C28.7 14.5 28.7 14.4 28.9 14.1C29.2 13.4 30.1 13 30.8 13.4C31.1 13.5 38.2 18 38.6 18.2C39.3 18.8 39.3 20 38.6 20.6C38.2 20.9 31 25.4 30.8 25.5C30.2 25.7 29.5 25.5 29.1 25.1C28.7 24.7 28.7 24.6 28.7 22.6L28.7 20.9L24.1 20.9C19.7 20.9 19.4 20.9 18.9 21C13.2 22.4 12.4 30.1 17.6 32.7C19 33.3 18.8 33.3 28.1 33.3C36.8 33.3 36.2 33.3 36.7 33.7C37.5 34.5 37.2 35.7 36.2 36.2C36 36.3 20.9 36.4 19.5 36.2z") }+ val TransformReset by lazy { shape("transformreset", 44f, "M14.6 29.6C13.2 28.6 12.1 27.7 12.1 27.6C12.1 27.6 17 23.8 17.1 23.8C17.1 23.8 17.1 24.3 17.1 25L17.2 26.2L21.4 26.2C26.1 26.2 26 26.2 26.5 25.8C26.8 25.4 26.9 25.2 26.9 24.2L26.9 23.2L28.4 23.2L29.9 23.2L29.9 24.3C29.9 26.4 29.1 27.8 27.6 28.6C26.5 29.1 26.8 29.1 21.7 29.1L17.1 29.1L17.1 30.3L17.1 31.5L14.6 29.6zM14.1 19.7C14.1 17.5 14.9 16.1 16.6 15.3C17.5 14.9 17.3 14.9 22.3 14.9L26.9 14.9L26.9 13.7L26.9 12.5L29.4 14.4C30.8 15.5 32 16.3 32 16.3C32 16.4 26.9 20.2 26.9 20.2C26.9 20.2 26.9 19.7 26.9 19L26.8 17.8L22.7 17.8C18.3 17.8 18.1 17.8 17.7 18.1C17.2 18.4 17.1 18.7 17.1 19.8L17.1 20.8L15.6 20.8L14.1 20.8L14.1 19.7z") }+ val SelectCopyPaste by lazy { shape("selectcopypaste", 44f, "M15.8 30.1C10.9 29.2 7.9 24.3 9.4 19.5C10.8 15.2 15.5 12.8 19.8 14.2C22.2 15 24.2 17 25 19.4C26.5 24.1 23.7 29 18.9 30C18.2 30.2 16.5 30.2 15.8 30.1zM26.4 30.2C26.4 30.1 26.6 29.9 26.8 29.5C29.9 24.9 29.4 18.5 25.6 14.4L25.2 14L25.7 13.9C30.6 13.2 34.9 17 35 22C35 26.1 32.1 29.5 28 30.1C27.5 30.2 26.4 30.2 26.4 30.2z") }+ /** A plus. */+ val PlusMedium by lazy { icon("plus-medium", Part("M20.5 8.6v22.8", 2.3f, false), Part("M9.1 20h22.8", 2.3f, false), viewport = 41f, viewportHeight = 40f) }+ val StudioShape by lazy { shape("studioshape", 50f, "M24.6 33.9C24.3 33.8 24.2 33.6 23.5 32.4C22.7 31.1 22.6 30.9 22.4 30.9C22.3 30.9 21.7 31.1 20.9 31.3C19.2 31.7 18.9 31.7 18.6 31.3C18.3 30.9 18.3 30.8 18.7 29.3C19.1 27.6 19.1 27.5 19 27.4C18.9 27.3 18.3 26.9 17.6 26.5C16.3 25.8 16.1 25.6 16 25.2C15.9 24.6 16.1 24.4 17.6 23.5C18.3 23.1 18.9 22.7 19 22.6C19.1 22.5 19.1 22.4 18.7 20.7C18.3 19.2 18.3 19 18.7 18.6C19 18.3 19.2 18.3 20.8 18.7C21.6 18.9 22.3 19.1 22.4 19.1C22.6 19.1 22.7 18.9 23.5 17.6C24.4 16.1 24.6 15.9 25.2 16C25.6 16.1 25.8 16.3 26.5 17.6C27.3 18.9 27.4 19.1 27.6 19.1C27.7 19.1 28.4 18.9 29.2 18.7C30.8 18.3 30.9 18.3 31.3 18.6C31.7 18.9 31.7 19.2 31.3 20.9C31.1 21.7 30.9 22.3 30.9 22.4C30.9 22.6 31.1 22.7 32.4 23.5C33.9 24.4 34.1 24.6 34 25.2C33.9 25.6 33.7 25.8 32.4 26.5C31.1 27.3 30.9 27.4 30.9 27.6C30.9 27.7 31.1 28.3 31.3 29.1C31.7 30.8 31.7 31.1 31.2 31.5C30.9 31.7 30.6 31.7 29.1 31.3C28.3 31.1 27.7 30.9 27.6 30.9C27.4 30.9 27.3 31.1 26.5 32.4C26.2 33 25.8 33.6 25.7 33.7C25.5 34 25 34.1 24.6 33.9z") }+ val GestureCopyPaste by lazy { shape("gesturecopypaste", 50f, "M15.7 36.4C15.2 36.2 14.8 35.9 14.6 35.3C14.4 34.8 14.4 20.2 14.6 19.7C14.8 19.2 15 18.9 15.4 18.7C15.8 18.5 15.8 18.5 22.4 18.5C29.9 18.5 29.4 18.5 30 19C30.5 19.6 30.5 19 30.5 27.5C30.5 36 30.5 35.4 30 36C29.4 36.5 29.9 36.5 22.5 36.5C17.3 36.5 15.9 36.5 15.7 36.4zM29.1 35.4C29.5 35.2 29.5 35.8 29.5 27.5C29.5 19.2 29.5 19.8 29.1 19.6C28.7 19.4 16.2 19.5 15.9 19.6C15.5 19.9 15.5 19.3 15.5 27.5C15.5 35.7 15.5 35.1 15.9 35.4C16.2 35.5 28.7 35.6 29.1 35.4zM32 27.2C32 22.2 32 19.3 31.9 19.1C31.7 18.1 30.9 17.3 29.9 17.1C29.7 17 27.3 17 23.3 17L17 17L17 15.6C17 14 17.1 13.9 17.5 13.5C18 13 17.9 13 20.6 13C23 13 23 13 23 12.7C23 12.5 23.1 12.4 23.2 12.2C23.6 11.9 29.4 11.9 29.8 12.2C29.9 12.4 30 12.5 30 12.7C30 13 30 13 32.4 13C35.1 13 35 13 35.5 13.5C36 14 36 12.9 36 24C36 35.1 36 34 35.5 34.5C35.1 35 35 35 33.4 35L32 35L32 27.2zM29 14L29 13L26.5 13L24 13L24 14L24 15L26.5 15L29 15L29 14z") }+ val MenuNewBrush by lazy { shape("menunewbrush", 40f, "M10.1 30.4C10.1 29.3 10.1 27.7 10.2 27.2C10.6 23.1 12.4 20.3 16.4 18C17.8 17.2 19 16.7 21 16.1C23.2 15.5 24.1 15.2 25.1 14.8C27.3 13.7 28.8 11.8 29.5 9L29.6 8.7L29.6 9.1C29.7 9.8 29.7 11.7 29.6 12C29.4 15 28.4 17.1 26.7 19C26.5 19.2 26.5 19.2 26.4 19.2C26 19.1 25.6 19 25.3 18.9C25.1 18.9 25.1 18.9 25.4 18.7C26.6 17.6 27.5 16.1 28 14.5C28.2 14 28.2 14 27.9 14.3C26.4 15.6 25.1 16.2 21.2 17.3C19.3 17.8 18.1 18.3 16.7 19.2C13.9 20.9 12.3 22.7 11.6 25.4L11.6 25.7L11.8 25.5C12.5 24.7 13.2 24.3 14.3 23.7C15.2 23.3 15.9 23 18.3 22.4C18.9 22.2 19.7 21.9 19.8 21.9C19.8 21.9 19.8 21.9 19.7 22.1C19.6 22.3 19.4 22.7 19.3 23C19.3 23.1 19.3 23.3 19.3 23.3C19.2 23.3 18.9 23.4 18.4 23.5C17.4 23.8 16.6 24.1 16.2 24.2C12.9 25.3 11.2 27.2 10.3 30.6C10.2 30.7 10.2 30.9 10.2 30.9C10.2 30.9 10.1 30.7 10.1 30.4zM24.3 29C21.8 28.7 20 26.5 20.3 23.9C20.5 22 22 20.4 23.9 20C27.2 19.4 30 22.4 29.2 25.6C28.6 27.7 26.5 29.2 24.3 29zM25 27.3C25.1 27.2 25.3 27.1 25.3 27C25.3 26.9 25.3 26.6 25.3 26L25.3 25L26.3 25C27.2 25 27.2 25 27.3 25C27.7 24.8 27.7 24.2 27.3 24C27.2 23.9 27.2 23.9 26.3 23.9L25.3 23.9L25.3 23C25.3 22 25.3 22 25.3 21.9C25.1 21.5 24.4 21.5 24.3 22C24.2 22.1 24.2 22.3 24.2 23L24.2 23.9L23.3 23.9C22.2 23.9 22.3 23.9 22.1 24.1C21.9 24.3 21.9 24.7 22.1 24.9C22.3 25 22.4 25 23.3 25L24.2 25L24.2 25.9C24.2 27 24.2 27 24.4 27.1C24.5 27.3 24.8 27.4 25 27.3z") }+ val MenuNewSet by lazy { shape("menunewset", 40f, "M27.9 28.4C24.6 27.7 23.2 23.8 25.3 21.2C27.6 18.3 32 19.1 33.2 22.6C33.4 23.3 33.4 24.6 33.2 25.3C32.4 27.5 30.1 28.9 27.9 28.4zM29.2 26.7C29.3 26.6 29.3 26.5 29.4 25.6L29.4 24.5L30.4 24.5C31.6 24.5 31.7 24.4 31.7 24C31.7 23.5 31.5 23.4 30.4 23.4L29.4 23.4L29.4 22.5C29.4 21.3 29.3 21.2 29 21.2C28.7 21.1 28.4 21.2 28.4 21.4C28.3 21.5 28.3 21.9 28.3 22.5L28.3 23.4L27.3 23.4C26.4 23.4 26.3 23.4 26.2 23.6C26 23.7 26 24 26.1 24.2C26.2 24.5 26.3 24.5 27.3 24.5L28.3 24.5L28.3 25.5C28.3 26.5 28.3 26.5 28.5 26.7C28.7 26.8 29 26.9 29.2 26.7zM12.3 25.9C11.2 25.6 10.3 24.7 10.1 23.5C10 23 10 16 10.1 15.5C10.3 14.3 11.2 13.4 12.4 13.1C12.8 13 26.1 13 26.7 13.1C27.5 13.2 28.3 13.8 28.7 14.5C29 15.1 29.1 15.4 29.1 17C29.1 18.5 29.1 18.5 28.7 18.5C28.4 18.5 28.1 18.5 28 18.5C27.7 18.6 27.7 18.6 27.7 17.2C27.7 15.4 27.6 15 26.8 14.6C26.5 14.4 26.5 14.4 19.6 14.4C12 14.4 12.5 14.4 12 14.8C11.5 15.3 11.5 15.1 11.5 19.5C11.5 23.9 11.5 23.7 12 24.1C12.5 24.6 12.1 24.6 18 24.6C23.4 24.6 23.4 24.6 23.4 24.8C23.5 25.3 23.6 25.6 23.7 25.8C23.7 26 23.7 26 18.2 26C13.6 26 12.6 26 12.3 25.9z") }+ /** A folder. */+ val MenuFolder by lazy {+ icon(+ "menu-folder",+ Part("M9.5 14.2a2.6 2.6 0 0 1 2.6-2.6h4.9l2.2 2.4h8.7a2.6 2.6 0 0 1 2.6 2.6v9.9a2.6 2.6 0 0 1-2.6 2.6H12.1a2.6 2.6 0 0 1-2.6-2.6z", 1.8f, false),+ Part("M9.5 17.4h21", 1.8f, false),+ viewport = 40f,+ )+ }+ /** A pencil over a square. */+ val MenuRename by lazy {+ icon(+ "menu-rename",+ Part("M21.5 12.2H15a3.4 3.4 0 0 0-3.4 3.4v10.8a3.4 3.4 0 0 0 3.4 3.4h10.8a3.4 3.4 0 0 0 3.4-3.4V19.6", 1.8f, false),+ Part("M19.6 23.1l.9-3.4 8.1-8.1 2.5 2.5-8.1 8.1z", 1.5f, false),+ viewport = 40f,+ )+ }+ /** A square with a plus, another behind it. */+ val MenuDuplicate by lazy {+ icon(+ "menu-duplicate",+ Part("M11.2 25.4V14.6a3.3 3.3 0 0 1 3.3-3.3h10.8", 1.8f, false),+ Part("M17.9 15.2h8.8a3 3 0 0 1 3 3v8.8a3 3 0 0 1-3 3h-8.8a3 3 0 0 1-3-3v-8.8a3 3 0 0 1 3-3z", 1.8f, false),+ Part("M22.3 18.9v7.4", 1.8f, false),+ Part("M18.6 22.6h7.4", 1.8f, false),+ viewport = 40f,+ )+ }+ val MenuShare by lazy { shape("menushare", 40f, "M13.9 31C12.3 30.8 11.5 30 11.4 28.4C11.3 28.1 11.3 18.1 11.4 17.8C11.5 16.5 12.1 15.7 13.2 15.4C13.7 15.2 13.7 15.2 15.5 15.2L17.1 15.2L17.1 16L17.1 16.8L15.6 16.8C14.2 16.8 14 16.8 13.9 16.8C13.4 17 13 17.4 12.9 18C12.9 18.2 12.9 28 12.9 28.2C13 28.8 13.4 29.2 13.9 29.4C14.1 29.4 25.6 29.4 25.9 29.4C26.5 29.3 27 28.9 27.1 28.2C27.1 28 27.1 18.2 27.1 18C27 17.5 26.7 17.1 26.3 16.9C26 16.8 26.1 16.8 24.4 16.8L22.9 16.8L22.9 16L22.9 15.2L24.5 15.2C26.4 15.2 26.4 15.2 26.9 15.4C27.9 15.7 28.5 16.5 28.6 17.8C28.7 18.1 28.7 28.1 28.6 28.4C28.5 30 27.6 30.8 26.1 31C25.8 31 14.2 31 13.9 31zM19.8 23.3C19.6 23.3 19.3 23.1 19.3 22.9C19.2 22.7 19.2 22.7 19.2 17.2C19.2 14.2 19.3 11.5 19.3 11.4L19.3 11.1L19.1 11.3C19 11.4 18.6 11.9 18.1 12.3C16.9 13.7 17 13.6 16.6 13.6C16.3 13.6 16.2 13.6 16.1 13.4C15.9 13.2 15.9 12.8 16 12.6C16 12.5 19.5 9.2 19.6 9.1C19.8 9 20.2 9 20.4 9.1C20.6 9.3 23.9 12.5 24 12.6C24.1 12.7 24.1 13 24.1 13.2C23.9 13.6 23.3 13.8 23 13.5C22.9 13.5 21.6 12 21.1 11.5C20.7 11.1 20.7 11 20.7 11.8C20.8 12.2 20.8 14.2 20.8 17.6C20.8 22.7 20.8 22.7 20.7 22.9C20.6 23.2 20.2 23.4 19.8 23.3z") }+ /** A bin with a lid. */+ val MenuTrash by lazy {+ icon(+ "menu-trash",+ Part("M10.8 12.9h18.4", 1.8f, false),+ Part("M16.9 12.6v-1.4a1.6 1.6 0 0 1 1.6-1.6h3a1.6 1.6 0 0 1 1.6 1.6v1.4", 1.8f, false),+ Part("M12.9 13.2l1 15.3a2.2 2.2 0 0 0 2.2 2h7.8a2.2 2.2 0 0 0 2.2-2l1-15.3", 1.8f, false),+ Part("M18 17v9.5", 1.6f, false),+ Part("M22 17v9.5", 1.6f, false),+ viewport = 40f,+ )+ }+ /** A small glyph for each blend mode, by its name, as the blend lists show them. */+ val BlendGlyphs: Map<String, ImageVector> by lazy {+ val box = "M5 3h10a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-10a2 2 0 0 1-2-2v-10a2 2 0 0 1 2-2z"+ val ring = "M10 3a7 7 0 1 1 0 14a7 7 0 1 1 0-14z"+ fun glyph(name: String, vararg parts: Part) = name to icon("blend-$name", *parts, viewport = 20f)+ fun line(d: String) = Part(d, 1.5f, false)+ fun dot(x: Float, y: Float, r: Float) = Part("M${x - r} ${y}a$r $r 0 1 0 ${2 * r} 0a$r $r 0 1 0 ${-2 * r} 0z", 0f, true)+ val rays = (0 until 8).map { k ->+ val a = Math.PI * k / 4+ val (c, s) = Math.cos(a).toFloat() to Math.sin(a).toFloat()+ line("M${10 + 5.2f * c} ${10 + 5.2f * s}L${10 + 7.2f * c} ${10 + 7.2f * s}")+ }+ val sparks = (0 until 8).map { k ->+ val a = Math.PI * k / 4+ dot(10 + 6.4f * Math.cos(a).toFloat(), 10 + 6.4f * Math.sin(a).toFloat(), 0.9f)+ }+ mapOf(+ glyph("Multiply", line(box), line("M7.5 7.5l5 5"), line("M12.5 7.5l-5 5")),+ glyph("Darken", Part("M12.6 3.3a7 7 0 1 0 4.1 9.3a5.4 5.4 0 0 1-4.1-9.3z", 0f, true)),+ glyph("Shade", line("M8 5a5 5 0 1 1 0 10a5 5 0 1 1 0-10z"), Part("M12 5a5 5 0 1 1 0 10a5 5 0 1 1 0-10z", 0f, true)),+ glyph("Color Burn", line("M10 3c2.5 3.2 5 6 5 8.6a5 5 0 0 1-10 0c0-2.6 2.5-5.4 5-8.6z"), line("M5.5 15.5l9-9")),+ glyph("Linear Burn", Part("M10 2.8c.6 2.6 4 4.1 4 8.2a4 4 0 0 1-8 0c0-1.7.9-2.7 1.7-3.5.2 1.3.8 1.9 1.7 2.1.3-2.5-.6-4.8.6-6.8z", 0f, true)),+ glyph("Darker Color", line(ring), line("M6.5 10h7")),+ glyph("Normal", line(box), line("M7.5 13.5v-7l5 7v-7")),+ glyph("Lighten", line("M10 6.8a3.2 3.2 0 1 1 0 6.4a3.2 3.2 0 1 1 0-6.4z"), *rays.toTypedArray()),+ glyph("Screen", line(box), line("M4 10.5l6.5-6.5"), line("M4.2 15.8l11.6-11.6"), line("M9.5 16l6.5-6.5")),+ glyph("Color Dodge", line("M8.5 4a4.5 4.5 0 1 1 0 9a4.5 4.5 0 1 1 0-9z"), line("M11.8 11.8l4.7 4.7")),+ glyph("Add", line(box), line("M10 6.5v7"), line("M6.5 10h7")),+ glyph("Lighter Color", line(ring), line("M10 6.5v7"), line("M6.5 10h7")),+ glyph("Overlay", line("M4.5 3.5h8a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1h-8a1 1 0 0 1-1-1v-8a1 1 0 0 1 1-1z"), line("M13.5 6.5h2a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1h-8a1 1 0 0 1-1-1v-2")),+ glyph("Soft Light", line(ring), Part("M10 3a7 7 0 0 1 0 14z", 0f, true)),+ glyph("Hard Light", Part("M11.2 2.5L5 11h4.2l-1.2 6.5L15 9h-4.3z", 0f, true)),+ glyph("Vivid Light", line("M10 2.8l7.2 7.2-7.2 7.2-7.2-7.2z"), dot(10f, 10f, 1.8f)),+ glyph("Linear Light", line("M5.5 4v12"), line("M10 4v12"), line("M14.5 4v12")),+ glyph("Pin Light", line("M10 17.5s-5.2-5.3-5.2-9.2a5.2 5.2 0 0 1 10.4 0c0 3.9-5.2 9.2-5.2 9.2z"), dot(10f, 8.3f, 1.7f)),+ glyph("Hard Mix", line(box), line("M10 3v14"), line("M3 10h14")),+ glyph("Difference", line(box), Part("M3.8 16.2L16.2 3.8V15a1.2 1.2 0 0 1-1.2 1.2z", 0f, true)),+ glyph("Exclusion", line(ring), line("M5.1 14.9l9.8-9.8")),+ glyph("Subtract", line(box), line("M6.5 10h7")),+ glyph("Divide", line(box), line("M6.5 10h7"), dot(10f, 6.8f, 0.95f), dot(10f, 13.2f, 0.95f)),+ glyph("Hue", line(ring), line("M10 10V3"), line("M10 10l6.1 3.5"), line("M10 10l-6.1 3.5")),+ glyph("Saturation", Part("M4.5 16v-3", 1.8f, false), Part("M8.5 16v-6", 1.8f, false), Part("M12.5 16v-9", 1.8f, false), Part("M16.5 16v-12", 1.8f, false)),+ glyph("Color", line(ring), line("M3.8 7h12.4"), line("M3 10h14"), line("M3.8 13h12.4")),+ glyph("Luminosity", dot(10f, 10f, 2.2f), *sparks.toTypedArray()),+ )+ }++ /** Nine small squares. */+ val MenuGrid by lazy {+ val cells = (0 until 9).map { k ->+ val (x, y) = 11.5f + (k % 3) * 6.2f to 11.5f + (k / 3) * 6.2f+ Part("M${x + 0.8f} ${y}h3.4a0.8 0.8 0 0 1 0.8 0.8v3.4a0.8 0.8 0 0 1-0.8 0.8h-3.4a0.8 0.8 0 0 1-0.8-0.8v-3.4a0.8 0.8 0 0 1 0.8-0.8z", 0f, true)+ }+ icon("menu-grid", *cells.toTypedArray(), viewport = 40f)+ }+ /** A camera. */+ val MenuCamera by lazy {+ icon(+ "menu-camera",+ Part("M11.5 15.5h3.6l1.8-2.6h6.2l1.8 2.6h3.6a1.6 1.6 0 0 1 1.6 1.6v9.8a1.6 1.6 0 0 1-1.6 1.6h-17a1.6 1.6 0 0 1-1.6-1.6v-9.8a1.6 1.6 0 0 1 1.6-1.6z", 1.8f, false),+ Part("M20 17.6a4 4 0 1 1 0 8a4 4 0 1 1 0-8z", 1.8f, false),+ viewport = 40f,+ )+ }+ /** A picture: a sun over hills in a frame. */+ val MenuPhoto by lazy {+ icon(+ "menu-photo",+ Part("M12.4 12.5h15.2a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2h-15.2a2 2 0 0 1-2-2v-11a2 2 0 0 1 2-2z", 1.8f, false),+ Part("M10.6 24.5l5-5 4.4 4.4 3-3 6.6 6.4", 1.8f, false),+ Part("M24.2 15.6a1.7 1.7 0 1 1 0 3.4a1.7 1.7 0 1 1 0-3.4z", 0f, true),+ viewport = 40f,+ )+ }+ /** Two arrows chasing each other round. */+ val MenuRestore by lazy {+ icon(+ "menu-restore",+ Part("M13.2 18.4a7.2 7.2 0 0 1 12.6-3.4", 1.8f, false),+ Part("M26.3 11.8v3.6h-3.6", 1.8f, false),+ Part("M26.8 21.6a7.2 7.2 0 0 1-12.6 3.4", 1.8f, false),+ Part("M13.7 28.2v-3.6h3.6", 1.8f, false),+ viewport = 40f,+ )+ }+ /** A tick in a ring. */+ val MenuCheckCircle by lazy {+ icon(+ "menu-check-circle",+ Part("M20 11.5a8.5 8.5 0 1 1 0 17a8.5 8.5 0 1 1 0-17z", 1.8f, false),+ Part("M16.2 20.2l2.6 2.6 5-5.4", 1.8f, false),+ viewport = 40f,+ )+ }+ /** A tag pointing left with a cross in it: delete the last character. */+ val HexBackspace by lazy {+ icon(+ "hex-backspace",+ // the cross cut out of the tag+ Part("M9.2 5.5h10.3a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-10.3l-6.7-6.5zM15.99 9.21L17.19 10.41L15.60 12.00L17.19 13.59L15.99 14.79L14.40 13.20L12.81 14.79L11.61 13.59L13.20 12.00L11.61 10.41L12.81 9.21L14.40 10.80z", 0f, true, evenOdd = true),+ )+ }+ /** Three overlapping rings: RGB. */+ val ProfileRgb by lazy {+ outline(+ "profile-rgb",+ 1.6f,+ "M12 3.4a4.9 4.9 0 1 1 0 9.8a4.9 4.9 0 1 1 0-9.8z",+ "M8.5 9.6a4.9 4.9 0 1 1 0 9.8a4.9 4.9 0 1 1 0-9.8z",+ "M15.5 9.6a4.9 4.9 0 1 1 0 9.8a4.9 4.9 0 1 1 0-9.8z",+ )+ }+ /** A ring quartered by a cross: CMYK. */+ val ProfileCmyk by lazy { outline("profile-cmyk", 1.6f, "M12 4.2a7.8 7.8 0 1 1 0 15.6a7.8 7.8 0 1 1 0-15.6z", "M12 2.2v19.6", "M2.2 12h19.6") }+ /** A clock face. */+ val Clock by lazy {+ icon(+ "clock",+ Part("M12 3.5a8.5 8.5 0 1 1 0 17a8.5 8.5 0 1 1 0-17z", 1.6f, false),+ Part("M12 7.5V12l3 1.8", 1.6f, false),+ )+ }++ /** A page with its corner folded. */+ val Page by lazy {+ icon(+ "page",+ Part("M7 3h6.5l4.5 4.5V20a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z", 1.6f, false),+ Part("M13.5 3v4.5H18", 1.6f, false),+ )+ }++ /** A ticked box with two edges stacked above it. */+ val MenuSelectAll by lazy {+ icon(+ "menu-select-all",+ Part("M13.6 17.2h12.8a2.6 2.6 0 0 1 2.6 2.6v8.6a2.6 2.6 0 0 1-2.6 2.6h-12.8a2.6 2.6 0 0 1-2.6-2.6v-8.6a2.6 2.6 0 0 1 2.6-2.6z", 1.8f, false),+ Part("M13.2 13.6h13.6", 1.8f, false),+ Part("M15 10.2h10", 1.8f, false),+ Part("M16.4 24l2.6 2.6 4.8-5.2", 1.8f, false),+ viewport = 40f,+ )+ }+ /** A folder. */+ val MenuGroup by lazy {+ icon(+ "menu-group",+ Part("M10.8 14.4a2.4 2.4 0 0 1 2.4-2.4h4.4l2.2 2.4h7a2.4 2.4 0 0 1 2.4 2.4v9.6a2.4 2.4 0 0 1-2.4 2.4h-13.6a2.4 2.4 0 0 1-2.4-2.4z", 1.8f, false),+ Part("M10.8 18.2h18.4", 1.8f, false),+ viewport = 40f,+ )+ }+ /** Two layers with an arrow down out of them. */+ val MenuMerge by lazy {+ icon(+ "menu-merge",+ Part("M20 9l8.4 4.2-8.4 4.2-8.4-4.2z", 1.8f, false),+ Part("M11.6 18.4l8.4 4.2 8.4-4.2", 1.8f, false),+ Part("M20 25.4v6", 1.8f, false),+ Part("M17.6 29.2l2.4 2.4 2.4-2.4", 1.8f, false),+ viewport = 40f,+ )+ }+ val MenuChevron by lazy { shape("menuchevron", 40f, "M18.3 25.6C17.8 25.5 17.4 25 17.5 24.5C17.5 24.1 17.4 24.3 19.6 22L21.7 20L19.6 18C17.7 16.1 17.6 15.9 17.5 15.8C17.2 14.9 18 14.1 18.9 14.5C19 14.6 19.1 14.7 21.4 17C22.7 18.3 23.8 19.4 23.8 19.5C24 19.7 24.1 20.1 23.9 20.4C23.8 20.6 19.1 25.4 18.9 25.5C18.7 25.6 18.5 25.6 18.3 25.6z") }+ val PieUndo by lazy { shape("pieundo", 50f, "M17.4 36.7C16.3 36.2 16 34.8 16.8 34C17.3 33.5 16.9 33.5 24.3 33.5C31.3 33.5 31.2 33.5 32.2 33.2C37.6 31.3 37.9 23.7 32.6 21.3C31.4 20.7 31.5 20.7 25.8 20.7L20.6 20.7L20.6 23.5C20.6 26.3 20.6 26.3 20.4 26.5C20.1 26.8 20.3 26.9 13.3 23.2C5.9 19.4 6.3 19.7 6.3 19C6.3 18.3 6.2 18.4 10.2 16.3C12.1 15.3 15.1 13.8 16.8 12.9C20 11.2 20 11.2 20.3 11.3C20.6 11.5 20.6 11.5 20.6 14.6L20.6 17.4L25.9 17.5C31.7 17.5 31.5 17.5 32.9 17.9C38 19.6 40.9 25.2 39.2 30.2C38.1 33.4 35.5 35.8 32 36.6C31.2 36.7 17.9 36.8 17.4 36.7z") }+ val PieReset by lazy { shape("piereset", 50f, "M13.8 37.7C9.8 34.6 9.6 34.5 9.7 34.4C9.8 34.3 11.7 32.8 13.9 31.1L18 27.9L18 30L18.1 32L25.1 32C33.3 32 32.6 32 33.3 31.3C34 30.7 34 30.5 34 28.6L34 27.1L36.5 27.1L38.9 27.1L38.9 28.7C38.9 30.7 38.9 31.2 38.5 32.2C37.7 34.4 35.9 36 33.4 36.7C33 36.8 32.9 36.8 25.5 36.9L18.1 36.9L18.1 38.9C18.1 40 18 40.9 18 40.9C18 40.9 16.1 39.5 13.8 37.7zM13.1 21.3C13.1 19.3 13.1 18.8 13.5 17.8C14.3 15.5 16.1 14 18.6 13.3C19 13.2 19.1 13.2 26.5 13.1L33.9 13.1L33.9 11.1C33.9 9.4 34 9.1 34 9.1C34.1 9.1 36 10.6 38.2 12.3C42.2 15.4 42.4 15.5 42.3 15.6C42.2 15.7 40.3 17.2 38.1 18.9L34 22.1L34 20L33.9 18L26.9 18C18.7 18 19.4 18 18.7 18.7C18 19.3 18 19.5 18 21.4L17.9 22.9L15.5 22.9L13.1 22.9L13.1 21.3z") }+ val ShapeEquilateral by lazy { shape("shapeequilateral", 28f, "M10.2 18.5C8.7 18.2 7.8 16.6 8.4 15.2C8.5 14.8 11.9 9 12.2 8.7C13.1 7.6 15.2 7.7 16 8.9C16.2 9.2 19.3 14.6 19.6 15C20.3 16.5 19.3 18.3 17.7 18.6C17.1 18.7 10.6 18.6 10.2 18.5zM17.6 16.5C17.9 16.2 17.9 16.1 16.1 13.1C14.4 10 14.3 9.9 14 9.9C13.7 9.9 13.7 10 11.9 13C10.1 16.1 10.1 16.1 10.3 16.3C10.4 16.6 10.4 16.6 14.1 16.6C17.5 16.6 17.5 16.6 17.6 16.5z") }+ val ShapeSquare by lazy { shape("shapesquare", 28f, "M11.4 18.9C10.2 18.8 9.3 17.8 9.1 16.4C9.1 16.2 9.1 11.8 9.1 11.6C9.2 10.5 10 9.5 10.9 9.2C11.3 9.1 11.1 9.1 13.9 9.1C15.5 9.1 16.4 9.1 16.6 9.1C17.7 9.2 18.6 10.1 18.9 11.3C18.9 11.7 18.9 16.3 18.9 16.7C18.6 17.9 17.7 18.8 16.6 18.9C16.4 18.9 11.7 18.9 11.4 18.9zM16.6 17C16.8 16.9 17 16.7 17.1 16.4C17.1 16.2 17.1 11.8 17.1 11.6C17 11.2 16.7 10.9 16.4 10.9C16.3 10.9 15.5 10.9 13.9 10.9C11.6 10.9 11.6 10.9 11.4 11C11.2 11.1 11 11.3 10.9 11.6C10.9 11.8 10.9 16.2 10.9 16.4C11 16.7 11.2 16.9 11.4 17C11.5 17.1 11.5 17.1 14 17.1C16.5 17.1 16.5 17.1 16.6 17z") }+ val CopyCut by lazy { shape("copycut", 50f, "M20.3 45.2C20.1 45.1 19.8 45 19.6 44.9C16.7 43.5 16.6 40 19.3 34.8C20.4 32.8 20.5 32.5 21.2 31C21.6 30.1 22 29.4 22 29.4C22.1 29.3 25.2 28.5 25.4 28.5C25.5 28.5 25.5 28.6 25.4 28.8C25.4 29.1 25.4 29.2 25.6 29.9C26.7 33.6 27 38.2 26.2 40.4C25.5 42.7 23.7 44.7 22 45.2C21.6 45.3 20.7 45.3 20.3 45.2zM22.2 43.4C25.1 41.9 26.2 35.8 23.9 34.3C21.2 32.5 17.7 38.8 19.5 42.4C20 43.6 21.1 44 22.2 43.4zM8 32.4C5.5 32.1 3.8 29.6 4.7 27.4C5.3 25.9 7.2 24.2 9.2 23.6C11.4 22.8 15.7 23 19.5 24.1C20 24.2 20.5 24.3 20.6 24.4C20.7 24.4 26.2 23.2 32.9 21.7C39.6 20.2 45 19 45.1 19C45.1 19.1 44.9 19.5 44.6 19.8C42.3 22 34.2 24.8 22.1 27.4C20.4 27.8 20.4 27.8 18.6 28.6C17.6 29.1 16.4 29.7 16 29.9C12.4 31.9 10.1 32.6 8 32.4zM11.1 30.6C14.2 30 16.4 27.8 15.6 26.1C14.5 23.9 9.6 24.2 7.1 26.5C4.6 28.9 7 31.4 11.1 30.6zM23.7 21.9C23.7 21.8 24.2 19.8 24.7 18.1C26.5 11.2 28.3 6.8 29.9 5.2C30.4 4.7 30.8 4.5 30.7 4.8C30.7 4.8 29.9 8.5 28.9 13C27.9 17.5 27.1 21.1 27.1 21.1C27.1 21.2 26.4 21.3 25.6 21.5C24.8 21.7 24.1 21.8 23.9 21.9C23.8 21.9 23.7 21.9 23.7 21.9z") }+ val CopyDuplicate by lazy { shape("copyduplicate", 50f, "M13.7 40.2C12.8 39.9 11.8 39.2 11.4 38.3C11 37.4 11 37.9 11 28.7C11 20.5 11 20.5 11.2 20C11.7 18.6 12.9 17.7 14.4 17.6L14.8 17.5L14.8 25.4C14.8 32.9 14.9 33.4 15 33.7C15.4 34.9 16.3 35.8 17.4 36.2C17.8 36.3 18.2 36.3 25.7 36.3L33.7 36.3L33.7 36.8C33.7 38.3 32.4 39.9 30.9 40.2C30.3 40.3 14.1 40.3 13.7 40.2zM17.9 35C17.1 34.7 16.5 34.1 16.2 33.3C16.1 32.7 16.1 14.7 16.2 14.1C16.5 13.4 17.1 12.7 17.9 12.5C18.4 12.3 36.4 12.3 37 12.5C37.7 12.6 38.3 13.2 38.6 13.9C38.8 14.2 38.8 14.2 38.8 23.7C38.8 34.4 38.8 33.6 38.1 34.3C37.3 35.1 38.2 35 27.6 35C20.1 35.1 18.1 35 17.9 35z") }+ val DoneTick by lazy { shape("donetick", 40f, "M17.4 26.8C17.2 26.7 11.7 21.3 11.5 20.9C11.1 20.3 11.5 19.3 12.2 19.1C12.9 18.9 12.9 18.9 15.6 21.6L18 23.9L22.4 19.5C24.9 17 26.9 15 27.1 14.9C28 14.4 29.1 15.4 28.8 16.4C28.7 16.7 18.9 26.6 18.5 26.8C18.2 27 17.7 27 17.4 26.8z") }+ val Add by lazy { shape("add", 40f, "M19.3 30.4C19 30.2 18.6 29.9 18.4 29.5C18.3 29.2 18.3 29.2 18.3 25.5L18.2 21.8L14.6 21.8C10.4 21.8 10.6 21.8 10 21.2C9.2 20.3 9.4 18.9 10.5 18.4C10.7 18.2 10.7 18.2 14.5 18.2L18.2 18.2L18.3 14.5C18.3 10.8 18.3 10.8 18.4 10.5C19.2 9.1 21.2 9.3 21.6 10.7C21.7 10.9 21.7 12.3 21.7 14.6L21.7 18.2L25.3 18.2C29.6 18.2 29.4 18.2 30 18.7C30.8 19.6 30.6 21 29.5 21.6C29.2 21.7 29.2 21.7 25.5 21.7L21.7 21.8L21.7 25.4C21.7 27.8 21.7 29.2 21.6 29.3C21.4 30.2 20.2 30.7 19.3 30.4z") }+ val ChevronDown by lazy { outline("chevron-down", 3f, "M6 9.5l6 6 6-6") }+ val ChevronRight by lazy { outline("chevron-right", 3f, "M9.5 6l6 6-6 6") }+ val ChevronLeft by lazy { outline("chevron-left", 3f, "M14.5 6l-6 6 6 6") }+ val Cross by lazy { outline("cross", 2.5f, "M6 6l12 12", "M18 6L6 18") }++ // the canvas information rail+ val InfoAbout by lazy { shape("infoabout", 50f, "M23.6 38.9C13.8 37.9 8.2 27.6 12.5 18.8C15.3 12.9 22.1 9.8 28.4 11.4C35.9 13.3 40.5 21 38.6 28.5C37.2 33.9 32.7 38 27.1 38.8C26.3 39 24.3 39 23.6 38.9zM25.9 34.7C26.3 34.4 26.7 34 26.9 33.5C27.1 32.9 27 22.6 26.8 22.1C26.1 20.6 23.9 20.6 23.2 22C23 22.6 22.9 32.9 23.1 33.5C23.5 34.6 24.8 35.2 25.9 34.7zM25.8 18.9C27.1 18.4 27.4 16.8 26.5 15.8C25.4 14.7 23.7 15.1 23.1 16.5C22.5 18.1 24.2 19.7 25.8 18.9z") }+ val InfoDimensions by lazy { shape("infodimensions", 50f, "M30 33.3C30 33.2 30 33 30 32.6L30 32L24.5 32C18.4 32 18.7 32 18.3 31.6C18 31.2 18 31.5 18 25.5L18 20L17.4 20C16.8 20 16.7 20 16.7 19.8C16.7 19.7 18.9 16.1 19 16.1C19.1 16.1 21.3 19.7 21.3 19.8C21.3 20 21.2 20 20.6 20L20 20L20 24.9C20 28.7 20 29.9 20.1 29.9C20.1 30 21.3 30 25.1 30L30 30L30 29.4C30 28.8 30 28.7 30.2 28.7C30.3 28.7 33.9 30.9 33.9 31C33.9 31.1 30.3 33.3 30.2 33.3C30.1 33.3 30.1 33.3 30 33.3zM30 24.9C30 24.8 30 23.8 30 22.5C30 20.8 30 20.1 29.9 20.1C29.9 20 29.2 20 27.5 20C25.3 20 25.1 20 25 19.9C25 19.7 25 18.2 25.1 18.1C25.1 18 25.9 18 28.1 18C32.4 18 32 17.6 32 21.9C32 24.1 32 24.9 31.9 24.9C31.8 25 30.1 25 30 24.9z") }+ val InfoLayers by lazy { shape("infolayers", 50f, "M15.1 36.9C14.1 36.6 13.3 35.8 13.1 34.9C13 34.5 13 21.5 13.1 21.1C13.3 20.1 14.2 19.3 15.2 19.1C15.4 19 17.7 19 22.2 19C28.9 19 28.9 19 29.4 19.3C30.2 19.6 30.7 20.3 30.9 21.1C31 21.5 31 34.5 30.9 34.9C30.7 35.7 30.2 36.4 29.4 36.7C28.9 37 28.9 37 22.1 37C16.9 37 15.3 37 15.1 36.9zM32 26C32 20 32 20.1 30.9 19.1C29.9 18 30 18 24 18L19.1 18L19.1 16.5C19.1 15 19.1 15 19.3 14.5C19.7 13.8 20.3 13.3 21 13.1C21.7 12.9 34.5 12.9 35.1 13.1C36.1 13.5 36.8 14.3 37 15.4C37.1 15.9 37.1 28 37 28.6C36.9 29.5 36.3 30.3 35.5 30.7C35 30.9 35 30.9 33.5 30.9L32 30.9L32 26z") }+ val InfoProfile by lazy { shape("infoprofile", 50f, "M13.3 35.9C12.7 35.7 12.2 35.2 12 34.6C11.8 34.2 11.8 12.8 12 12.4C12.1 11.9 12.5 11.5 12.9 11.3C13.3 11 13.3 11 15.9 11C18.8 11 18.8 11 19.4 11.6C20 12.2 20 11 20 23.5C20 36 20 34.8 19.4 35.4C18.8 36 18.8 36 16 36C14.1 36 13.5 36 13.3 35.9zM22.8 35.9C22.1 35.7 21.8 34.8 22.2 34.1C22.4 33.7 22.1 33.9 28.2 30.9C33.3 28.4 33.8 28.2 34.2 28.1C34.7 28.1 35.2 28.4 35.5 28.9C35.7 29.4 36.1 31.7 36.1 33C36.1 34 36.1 34 35.9 34.4C35.3 35.5 34.7 35.9 33.2 35.9C31.7 36 23.1 36 22.8 35.9zM16.9 33.5C18.5 32.6 18.1 30.1 16.2 29.7C14.3 29.4 13.1 31.9 14.6 33.2C15.2 33.7 16.2 33.9 16.9 33.5zM22.6 30.9C22.5 30.9 22.5 30.8 22.5 30.7C22.6 30.4 29.5 18.5 29.7 18.3C30.1 18 30.7 18 31 18.4C32 19.3 34.3 23.5 34.4 24.3C34.4 24.8 34.2 25.2 34 25.4C33.9 25.4 32.2 26.3 30.2 27.3C22 31.5 22.8 31.2 22.6 30.9zM22.1 26.2C21.9 25.9 22 13.7 22.1 13.3C22.5 12.6 23.2 12.5 24.1 12.9C26.1 13.9 27.9 15.2 28.1 15.7C28.4 16.4 28.5 16.2 25.5 21.4C24 24 22.7 26.1 22.7 26.2C22.6 26.4 22.2 26.3 22.1 26.2z") }+ val InfoVideo by lazy { shape("infovideo", 50f, "M17.7 29.9C16.9 29.6 16.4 29.1 16.1 28.3C15.9 27.7 15.9 22.3 16.1 21.7C16.4 20.9 16.9 20.4 17.7 20.1C18.3 19.9 25.7 19.9 26.3 20.1C27.1 20.4 27.6 20.9 27.9 21.7C28.1 22.3 28.1 27.7 27.9 28.3C27.6 29.1 27.1 29.6 26.3 29.9C25.7 30.1 18.2 30.1 17.7 29.9zM31 27.5C28.3 25.3 28.2 25.2 28.3 24.9C28.3 24.6 33.6 20.3 33.8 20.3C34 20.3 34.1 29.7 33.8 29.7C33.7 29.8 33 29.1 31 27.5z") }+ val InfoStatistics by lazy { shape("infostatistics", 50f, "M13.7 35.9C13.2 35.8 12.7 35.3 12.6 34.8C12.5 34.3 12.5 27.7 12.6 27.2C12.7 26.7 13.2 26.2 13.7 26.1C14.2 26 16.8 26 17.3 26.1C17.8 26.2 18.3 26.7 18.4 27.2C18.5 27.7 18.5 34.3 18.4 34.8C18.3 35.3 17.8 35.8 17.3 35.9C16.8 36 14.1 36 13.7 35.9zM22.2 35.9C21.7 35.8 21.2 35.3 21.1 34.8C20.9 34.3 20.9 20.7 21.1 20.2C21.2 19.7 21.7 19.2 22.2 19.1C22.7 19 25.3 19 25.8 19.1C26.3 19.2 26.8 19.7 26.9 20.2C27.1 20.7 27.1 34.3 26.9 34.8C26.8 35.3 26.3 35.8 25.8 35.9C25.3 36 22.6 36 22.2 35.9zM30.7 35.9C30.2 35.8 29.7 35.3 29.6 34.8C29.4 34.3 29.4 13.7 29.6 13.2C29.7 12.7 30.2 12.2 30.7 12.1C31.2 12 33.8 12 34.3 12.1C34.8 12.2 35.3 12.7 35.4 13.2C35.6 13.7 35.6 34.3 35.4 34.8C35.3 35.3 34.8 35.8 34.3 35.9C33.8 36 31.1 36 30.7 35.9z") }+ // the text style sheet+ val Keyboard by lazy { shape("keyboard", 40f, "M19.6 31.6C18.6 31.3 13.2 28.7 13.1 28.5C12.6 27.9 13.1 27 13.8 27C14.1 27 14.5 27.1 16.7 28.2C18.1 28.8 19.4 29.4 19.6 29.5C19.9 29.6 19.9 29.6 22.7 28.3C25.8 26.9 25.8 26.9 26.2 27.1C26.7 27.3 26.9 27.9 26.7 28.4C26.5 28.7 26.7 28.6 23.2 30.2C20.3 31.6 19.9 31.8 19.6 31.6zM10.7 24.9C9.8 24.7 9.2 24.1 9.1 23.1C8.9 22.4 9 12.9 9.1 12.5C9.4 11.9 9.9 11.3 10.6 11.1C11.2 10.9 29.1 11 29.6 11.2C30.3 11.5 30.8 11.9 31 12.6C31.2 13.2 31.2 22.8 31 23.4C30.8 24.1 30.3 24.5 29.6 24.8C29.3 25 29.3 25 20.2 25C12.4 25 11 25 10.7 24.9zM13.4 21.6C13.5 21.5 13.5 21.4 13.5 20.9C13.5 20.2 13.5 20.2 12.7 20.2C12 20.2 11.9 20.2 11.9 21C11.9 21.7 12 21.8 12.7 21.8C13.2 21.8 13.3 21.7 13.4 21.6zM25 21.6C25.2 21.5 25.2 20.5 25 20.3C24.9 20.1 15.1 20.1 15 20.3C14.7 20.5 14.8 21.5 15.1 21.7C15.4 21.8 24.8 21.8 25 21.6zM27.9 21.7C28.1 21.6 28.1 21.5 28.1 20.9C28.1 20.2 28 20.2 27.3 20.2C26.6 20.2 26.6 20.2 26.6 20.9C26.6 21.7 26.6 21.8 27.3 21.8C27.6 21.8 27.8 21.7 27.9 21.7zM13.4 18.6C13.5 18.5 13.6 17.5 13.4 17.3C13.3 17.1 12.2 17.1 12.1 17.3C11.9 17.4 11.9 18.5 12 18.7C12.2 18.8 13.2 18.8 13.4 18.6zM16.3 18.6C16.4 18.6 16.4 18.4 16.4 18C16.4 17.2 16.4 17.2 15.6 17.2C14.9 17.2 14.8 17.2 14.8 18C14.8 18.7 14.9 18.8 15.6 18.8C16.1 18.8 16.3 18.7 16.3 18.6zM19.2 18.7C19.3 18.6 19.3 18.4 19.3 18C19.3 17.2 19.3 17.2 18.5 17.2C17.8 17.2 17.8 17.2 17.8 18C17.8 18.7 17.8 18.8 18.5 18.8C19 18.8 19.1 18.7 19.2 18.7zM22.2 18.7C22.2 18.6 22.2 18.4 22.2 18C22.2 17.2 22.2 17.2 21.5 17.2C20.7 17.2 20.7 17.2 20.7 18C20.7 18.7 20.7 18.8 21.5 18.8C21.9 18.8 22.1 18.7 22.2 18.7zM25.1 18.6C25.1 18.6 25.2 18.4 25.2 18C25.2 17.2 25.1 17.2 24.4 17.2C23.6 17.2 23.6 17.2 23.6 18C23.6 18.7 23.6 18.8 24.4 18.8C24.9 18.8 25 18.7 25.1 18.6zM28 18.7C28 18.6 28.1 18.4 28.1 18C28.1 17.2 28.1 17.2 27.3 17.2C26.6 17.2 26.6 17.2 26.6 18C26.6 18.4 26.6 18.6 26.6 18.7C26.7 18.8 27.9 18.8 28 18.7zM13.4 15.7C13.5 15.5 13.6 14.5 13.4 14.3C13.2 14.2 12.1 14.2 12 14.4C11.9 14.6 11.9 15.6 12.1 15.7C12.3 15.9 13.2 15.9 13.4 15.7zM16.3 15.7C16.4 15.6 16.5 14.5 16.3 14.4C16.2 14.2 15.1 14.2 14.9 14.3C14.8 14.6 14.8 15.5 15 15.7C15.1 15.8 16.1 15.9 16.3 15.7zM19.2 15.7C19.3 15.6 19.4 14.5 19.2 14.3C19.1 14.2 18 14.2 17.8 14.4C17.7 14.6 17.7 15.6 17.9 15.7C18.1 15.9 19 15.8 19.2 15.7zM22.1 15.7C22.3 15.6 22.3 14.6 22.2 14.4C22.1 14.2 20.9 14.2 20.8 14.3C20.6 14.5 20.6 15.5 20.8 15.7C21 15.9 21.9 15.9 22.1 15.7zM25 15.7C25.2 15.6 25.2 14.5 25.1 14.4C25 14.2 23.8 14.2 23.7 14.3C23.6 14.5 23.6 15.6 23.8 15.7C23.9 15.8 24.9 15.9 25 15.7zM28 15.7C28.1 15.6 28.1 14.4 28 14.3C27.9 14.3 27.7 14.2 27.3 14.2C26.6 14.2 26.6 14.2 26.6 15C26.6 15.8 26.6 15.8 27.3 15.8C27.7 15.8 27.9 15.8 28 15.7z") }+ val TextCut by lazy { shape("textcut", 40f, "M17.6 33.2C16.4 33.1 15.2 32.2 14.6 31.1C13.4 28.8 14.7 26.1 17.3 25.4C18.2 25.1 18.3 25 18.8 23.1C19.4 21.3 19.4 21.4 18.8 20.3C18.2 19.3 18.1 18.7 18.3 17.9C18.5 17.6 22.1 9.7 22.6 8.7C23.1 7.7 23.8 6.8 24.5 6.5C24.9 6.3 25.8 6.3 25.8 6.5C25.8 6.6 24.5 10.8 22.9 15.9C21.4 21 20.1 25.2 20.1 25.3C20.1 25.5 20.3 25.8 20.8 26.3C21.4 27 21.7 27.4 21.9 28C22.9 30.8 20.5 33.7 17.6 33.2zM18.9 31.8C20.7 31.3 21.4 29.1 20.2 27.7C18.8 25.9 15.9 26.6 15.5 28.9C15.2 30.8 17.1 32.4 18.9 31.8zM9.2 25.1C7.9 24.8 6.8 23.8 6.3 22.5C5.3 19.8 7.3 17.1 10.2 17.2C11.3 17.3 12 17.6 13 18.5C13.8 19.3 13.8 19.3 15.4 18.8C16.7 18.4 16.6 18.4 16.6 18.9C16.6 19.2 16.7 19.7 16.9 20.1C16.9 20.2 16.9 20.3 16.4 20.4C14.2 21.1 14.3 21 13.9 22.1C13.2 24.3 11.3 25.5 9.2 25.1zM10.9 23.6C12.6 23 13.2 20.9 12 19.4C10.5 17.6 7.4 18.7 7.4 21.1C7.4 23 9.2 24.3 10.9 23.6zM23.4 19.9C23.4 19.8 24.5 16.1 24.6 16.1C24.6 16.1 32.7 13.6 32.8 13.5C32.8 13.5 32.9 13.7 32.9 13.8C33.2 14.6 32.7 15.4 31.6 16.2C31 16.6 30.9 16.7 27 18.3C25.2 19.2 23.6 19.9 23.5 19.9C23.5 19.9 23.4 19.9 23.4 19.9z") }+ val TextCopy by lazy { shape("textcopy", 40f, "M11.9 32.3C10.6 32.1 9.6 31.2 9.4 29.7C9.3 29 9.3 17.8 9.4 17C9.6 15.8 10.4 14.8 11.5 14.5C11.7 14.5 12.3 14.4 13.3 14.4L14.8 14.4L14.8 17.7C14.9 21.8 14.9 22.1 15.8 22.9C16.6 23.6 16.9 23.7 20.6 23.7L23.5 23.7L23.5 26.7C23.5 29.3 23.4 29.8 23.3 30.2C23.1 31.2 22.3 31.9 21.3 32.2C21 32.4 12.7 32.4 11.9 32.3zM25.1 24.8L25.1 24L26.6 24C28.4 24 28.7 23.8 28.9 22.9C29 22.4 29 10.8 28.9 10.3C28.8 9.9 28.6 9.6 28.2 9.4C27.9 9.2 19.1 9.2 18.8 9.4C18.2 9.7 18.1 10 18 11.9C18 13 18 13.1 17.9 13.1C17.6 13 17 12.8 16.8 12.8C16.4 12.8 16.4 12.8 16.5 11.4C16.5 9.7 16.7 9.2 17.4 8.5C17.9 8 18.4 7.8 19.1 7.7C19.8 7.6 27.2 7.6 27.9 7.7C29.2 7.8 30.1 8.6 30.4 9.8C30.7 10.7 30.7 22.6 30.4 23.5C30.3 24 30.1 24.3 29.7 24.7C29 25.4 28.6 25.6 26.6 25.6L25.1 25.6L25.1 24.8zM17.8 22.1C17.2 22 16.9 21.8 16.6 21.3C16.5 21 16.5 21 16.4 17.7C16.4 15.9 16.4 14.4 16.4 14.4C16.5 14.3 17.1 14.5 17.4 14.7C17.7 14.8 22.8 20.9 23.1 21.5C23.5 22.2 23.7 22.1 20.8 22.1C19.4 22.1 18 22.1 17.8 22.1zM20.4 12.4C20.2 12.2 19.9 11.9 19.9 11.7C19.9 11.4 20.2 11.1 20.4 11C20.5 10.9 21.2 10.9 23.5 10.9C26.4 10.9 26.4 10.9 26.7 11.1C26.9 11.3 26.9 11.3 26.9 11.7C26.9 12 26.9 12 26.7 12.2C26.4 12.4 26.4 12.4 23.5 12.4C21.2 12.4 20.5 12.4 20.4 12.4z") }+ val TextPaste by lazy { shape("textpaste", 40f, "M19 32.3C17.9 32.2 17 31.3 16.6 30.2C16.4 29.4 16.4 17.4 16.7 16.5C16.9 15.6 17.7 14.8 18.7 14.5C18.9 14.5 19.4 14.4 20.5 14.4L21.9 14.4L21.9 15.3C21.9 18.2 22 21.2 22.1 21.5C22.4 22.6 23.3 23.5 24.4 23.6C24.6 23.7 26 23.7 27.7 23.7C30.1 23.7 30.6 23.7 30.7 23.8C30.7 24 30.6 29.9 30.5 30.2C30.2 31.4 29.2 32.2 28 32.3C27.4 32.4 19.7 32.4 19 32.3zM12 25.6C10.4 25.4 9.5 24.4 9.4 22.5C9.3 21.4 9.3 10.4 9.4 10C9.7 8.9 10.5 8.1 11.5 7.8C12.1 7.6 20.7 7.6 21.3 7.8C22.6 8.1 23.3 9.1 23.4 10.7C23.4 11.1 23.4 11.7 23.5 12.1L23.5 12.8L22 12.8C18.3 12.8 17.5 13 16.3 14.2C15 15.5 14.9 16 14.9 22.1L14.9 25.6L13.6 25.6C13 25.6 12.2 25.6 12 25.6zM24.8 22.1C24.2 22 23.7 21.6 23.6 21.1C23.6 20.9 23.5 19.3 23.5 17.6C23.5 14.4 23.5 14.4 23.8 14.4C24.6 14.5 24.5 14.4 27.6 18.2C29.9 21 30.5 21.7 30.5 22C30.5 22.1 25.8 22.2 24.8 22.1zM20 11.1C20.4 10.8 20.5 10.3 20.2 9.9C19.9 9.7 19.9 9.7 16.5 9.6C12.8 9.6 12.9 9.6 12.6 9.9C12.2 10.3 12.4 11 13 11.2C13.4 11.3 19.8 11.2 20 11.1z") }+ val AlignLeft by lazy { shape("alignleft", 32f, "M6 24L6 23L16 23L26 23L26 24L26 25L16 25L6 25L6 24zM6 20L6 19L12 19L18 19L18 20L18 21L12 21L6 21L6 20zM6 16L6 15L16 15L26 15L26 16L26 17L16 17L6 17L6 16zM6 12L6 11L12 11L18 11L18 12L18 13L12 13L6 13L6 12zM6 8L6 7L16 7L26 7L26 8L26 9L16 9L6 9L6 8z") }+ val AlignCenter by lazy { shape("aligncenter", 32f, "M6 24L6 23L16 23L26 23L26 24L26 25L16 25L6 25L6 24zM10 20L10 19L16 19L22 19L22 20L22 21L16 21L10 21L10 20zM6 16L6 15L16 15L26 15L26 16L26 17L16 17L6 17L6 16zM10 12L10 11L16 11L22 11L22 12L22 13L16 13L10 13L10 12zM6 8L6 7L16 7L26 7L26 8L26 9L16 9L6 9L6 8z") }+ val AlignRight by lazy { shape("alignright", 32f, "M6 24L6 23L16 23L26 23L26 24L26 25L16 25L6 25L6 24zM14 20L14 19L20 19L26 19L26 20L26 21L20 21L14 21L14 20zM6 16L6 15L16 15L26 15L26 16L26 17L16 17L6 17L6 16zM14 12L14 11L20 11L26 11L26 12L26 13L20 13L14 13L14 12zM6 8L6 7L16 7L26 7L26 8L26 9L16 9L6 9L6 8z") }+ val AlignJustify by lazy { shape("alignjustify", 32f, "M6 24L6 23L16 23L26 23L26 24L26 25L16 25L6 25L6 24zM6 20L6 19L16 19L26 19L26 20L26 21L16 21L6 21L6 20zM6 16L6 15L16 15L26 15L26 16L26 17L16 17L6 17L6 16zM6 12L6 11L16 11L26 11L26 12L26 13L16 13L6 13L6 12zM6 8L6 7L16 7L26 7L26 8L26 9L16 9L6 9L6 8z") }+ val TextUnderline by lazy { shape("textunderline", 38f, "M12.6 27L12.6 26L19 26L25.4 26L25.4 27L25.4 27.9L19 27.9L12.6 27.9L12.6 27zM18.3 25.3C15.4 25 13.6 23.7 13 21.3C12.8 20.8 12.8 20.8 12.8 15.5L12.8 10.1L14.3 10.1L15.9 10.1L15.9 15.1C15.9 20.7 15.9 20.5 16.3 21.2C17.3 23.1 20.7 23.1 21.7 21.2C22.1 20.5 22.1 20.7 22.1 15.1L22.1 10.1L23.7 10.1L25.2 10.1L25.2 15.5C25.2 20.8 25.2 20.8 25 21.3C24.4 23.4 22.8 24.8 20.6 25.2C20.1 25.3 18.7 25.4 18.3 25.3z") }+ val TextOutline by lazy { shape("textoutline", 38f, "M18.2 28.4C15.7 28.2 13.6 27.1 12 25.1C10.4 23.1 9.7 20.4 10.1 17.5C10.5 14.5 12 12.1 14.5 10.7C16.2 9.7 18.3 9.4 20.5 9.7C23.7 10.1 26.4 12.4 27.4 15.5C28.1 17.6 28.1 20.3 27.5 22.4C26.5 25.5 23.8 27.8 20.6 28.3C20 28.4 18.8 28.4 18.2 28.4zM20 27.5C23.3 27.1 26 24.8 26.8 21.6C27.2 20 27.2 18 26.8 16.4C26.1 13.6 23.9 11.4 21.1 10.7C19.6 10.3 17.7 10.4 16.3 10.9C14.2 11.6 12.4 13.2 11.6 15.3C10.8 17.3 10.7 20.1 11.4 22.2C12.2 24.6 14.2 26.5 16.6 27.2C17.6 27.5 18.9 27.6 20 27.5zM18.4 27.5C17.2 27.3 16.1 26.8 15.2 25.9C13.7 24.5 13 22.5 13 19.3C12.9 16.5 13.5 14.1 14.6 12.7C15.8 11.2 17.2 10.5 19 10.5C20.3 10.5 21.4 10.9 22.4 11.7C24.2 13.1 25 15.3 25 18.7C25 21 24.8 22.6 24.2 24C23.3 25.8 21.7 27.1 19.8 27.4C19.5 27.5 18.7 27.5 18.4 27.5zM19.4 26.6C20.7 26.4 21.8 25.8 22.7 24.7C23.5 23.7 24 22.1 24.1 20C24.1 19.2 24.1 17.7 24 17.1C23.7 14.7 23 13.3 21.6 12.3C20.1 11.2 18.1 11.1 16.6 12.1C15 13.2 14.2 14.9 13.9 17.4C13.7 19.4 13.9 21.5 14.4 22.9C15.2 25.4 17.2 26.8 19.4 26.6z") }+ val TextVertical by lazy { shape("textvertical", 50f, "M15.7 39.2C5.8 38.3 -0.3 28.3 3.5 19.2C5.4 14.7 9.6 11.4 14.7 10.6C15.5 10.4 32.9 10.4 34.4 10.5C43.6 11.3 49.7 20.4 46.9 29.2C45.2 34.7 40.3 38.6 34.5 39.2C33.9 39.2 16.3 39.3 15.7 39.2zM28.4 34.5C29.1 34.2 29 34.3 29 30.7C29.1 26.2 29.4 26.5 25 26.5C22 26.5 21.8 26.5 21.4 26.8C20.9 27.2 20.9 27.1 21 30.7C21 35.1 20.6 34.7 25 34.7C28 34.7 28 34.7 28.4 34.5zM28.4 23C29 22.6 29 22.7 29 19.2C29.1 15.7 29.1 15.8 28.6 15.4C28.3 15 28.3 15 25 15C21.7 15 21.7 15 21.4 15.4C20.9 15.8 20.9 15.7 21 19.2C21 23.5 20.6 23.2 25.1 23.2C28.1 23.2 28.1 23.2 28.4 23z") }+ /** The icons a brush set can show (Customize icon), our own glyphs. */+ /**+ * The brush set icons, drawn in 40-unit frames: the first [PICKED_SET_ICONS] are the ones to+ * choose from, the rest are the shipped sets' own.+ */+ val SetIcons: List<ImageVector> by lazy {+ listOf(+ shape("set-0", 40f, "M15 30C14.9 29.9 14.8 29.9 14.9 29.3C14.9 28.4 14.9 28.4 13.7 28.2C12.6 28.1 12.7 28.1 12.6 27C12.5 26 12.4 25.9 11.5 25.9C10.8 25.9 10.7 25.9 10.6 25.6C10.4 25.3 10.5 25.2 12.2 23.6C13.9 21.9 14 21.8 14.6 21.8C15.3 21.7 15.5 21.9 17.2 23.5C18.8 25.2 19 25.4 19 26C19 26.7 18.9 26.8 17.1 28.6C15.4 30.3 15.4 30.3 15 30zM18.3 22.6C18 22.4 18 22.4 18.2 21.9C19.7 18.7 21.7 15.9 24.8 13C27.2 10.6 28.6 10 29.8 10.9C31 11.8 30.3 13.6 27.8 16.1C25.1 19 22.7 20.8 19.5 22.3C18.5 22.9 18.5 22.9 18.3 22.6z"),+ shape("set-1", 40f, "M14.1 29.8C13.6 29.7 13.4 29.3 13.5 28.8C13.5 28.6 13.6 28.3 14.2 27.4L15 26.3L13.6 26.3C12 26.3 11.8 26.2 11.4 25.9C10.7 25.4 10.6 24.8 10.6 18.6C10.7 14.1 10.7 14 11.4 13.5C11.8 13.2 11.8 13.2 15.5 13.1L19 13.1L19 12C19 10.5 19.2 10.1 20 10.1C20.8 10.1 21 10.5 21 12L21 13.1L24.3 13.1C27.8 13.2 27.8 13.2 28.3 13.5C28.9 14 29 14.5 29 19.7C29 25 28.9 25.4 28.3 25.9C27.9 26.2 27.7 26.2 26.3 26.3L25 26.3L25.8 27.4C26.5 28.5 26.5 28.5 26.5 28.9C26.5 29.5 26.2 29.9 25.6 29.9C25.1 29.9 25 29.8 23.7 28L22.5 26.3L20 26.3L17.5 26.3L16.4 27.9C15.1 29.7 15 29.8 14.7 29.9C14.4 30 14.4 30 14.1 29.8z"),+ shape("set-2", 40f, "M19.3 28.9C17.6 28.5 16.6 26.6 17.2 25.1C17.3 24.8 17.3 24.8 16.9 25.1C15.5 26.5 13.4 26.2 12.3 24.7C11.4 23.4 11.8 21.5 13 20.6C13.4 20.3 14 20.1 14.2 20.1C14.3 20.1 14.4 20 14.4 20C14.4 20 14.3 19.9 14.2 19.9C14 19.9 13.4 19.7 13 19.4C11.8 18.5 11.4 16.6 12.3 15.3C13.4 13.8 15.5 13.5 16.9 14.9C17.3 15.2 17.3 15.2 17.2 14.9C16.5 13.1 18 11 20 11C22 11 23.5 13.1 22.8 14.9C22.7 15.2 22.7 15.2 23.1 14.9C25 13 28.2 14.3 28.2 17C28.2 18.4 27.1 19.7 25.9 19.9C25.6 20 25.6 20 25.9 20.1C27.1 20.3 28.2 21.6 28.2 23C28.2 25.7 25 27 23.1 25.1C22.7 24.8 22.7 24.8 22.8 25.1C23.6 27.2 21.5 29.5 19.3 28.9z"),+ shape("set-3", 40f, "M19.4 28.4C18.2 28.2 17.2 27.2 17.1 26.2C17 25.9 17 25.9 15.6 25.9C14.8 25.8 13.7 25.8 13.2 25.8C11.4 25.8 11.4 25.7 12 24.9C13.5 22.7 13.9 21.6 13.9 18.8C14 16.8 14.1 16.5 14.5 15.5C15.2 14.1 16.4 13 17.8 12.5C18.2 12.3 18.2 12.3 18.4 12C18.8 10.8 20.4 10.6 21.1 11.7C21.2 11.8 21.3 12 21.4 12.1C21.4 12.3 21.4 12.3 21.7 12.4C23.5 13 24.9 14.5 25.5 16.4C25.6 16.9 25.6 17 25.7 18.5C25.8 21.5 26.1 22.4 27.5 24.5C28.1 25.5 28.1 25.6 28 25.7C27.9 25.8 26 25.8 23.3 25.9C22.6 25.9 22.6 25.9 22.6 26.2C22.3 27.7 20.8 28.7 19.4 28.4z"),+ shape("set-4", 40f, "M14.3 28.8C13.6 28.6 13.3 28.2 13.1 27.4C13 26.9 13 17.4 13 14.5C13.1 10.9 12.9 11 19.5 11C24.9 11 25.4 11.1 25.8 12.1C26 12.6 26.1 26.4 25.9 27.5C25.7 28.4 25.2 28.8 24.3 28.8C23.6 28.8 23.1 28.4 21.9 26.8C21.5 26.4 20.9 25.7 20.5 25.2C19.8 24.2 19.6 24.1 19.3 24.2C19.3 24.2 18.9 24.7 18.5 25.2C16.8 27.3 16.5 27.6 16.1 28.1C15.4 28.8 14.9 29 14.3 28.8z"),+ shape("set-5", 40f, "M12.6 29C12 28.9 11.4 28.7 10.8 28.4C10.4 28.1 10.4 28.1 10.6 28C10.8 28 11 27.9 11.2 27.6C11.6 27.2 11.7 27.1 12.5 25.4C13.2 24 14.7 22.9 16.3 22.9C17.6 22.9 18.3 23.8 18 25.3C17.5 27.5 15 29.3 12.6 29zM18.3 22.6C18 22.4 18 22.4 18.2 21.9C19.7 18.7 21.7 16 24.7 13C27.2 10.6 28.6 10 29.8 10.9C31 11.8 30.3 13.6 27.8 16.2C25 19 22.6 20.8 19.5 22.3C18.5 22.9 18.5 22.9 18.3 22.6z"),+ shape("set-6", 40f, "M18.4 29.1C18.1 28.9 18.1 28.8 18 26.7C17.9 25.5 17.8 24.6 17.8 24.5C17.8 24.5 17.5 24.4 17 24.4C14.4 24.4 12.9 22.8 12.3 19.4C12 17.6 12 15.3 12.2 14.8C13.1 13.3 15.4 13.6 15.7 15.3C15.8 15.5 15.8 15.8 15.7 16.6C15.4 18.7 15.5 20.5 15.9 21.3C16.3 22 17.7 22.2 17.7 21.5C17.6 21.4 17.6 20.6 17.5 19.7C17.4 18.7 17.3 16.8 17.2 15.4C16.9 12.5 16.9 12.4 17.2 11.7C18.3 9.5 21.7 9.7 22.4 12.1C22.5 12.6 22.5 12.7 22.2 16.6C21.7 23.5 21.6 23.9 21.9 23.9C22.1 23.9 22.7 23.6 23 23.3C23.8 22.6 24 21.4 23.9 18.6C23.8 16.9 23.8 16.7 24.3 16.2C25.2 15.1 26.7 15.3 27.4 16.5C27.8 17.4 27.6 20.3 27 22.3C26.2 24.8 24.5 26.1 22.2 26.3C21.9 26.3 21.6 26.4 21.6 26.4C21.6 26.4 21.5 27 21.5 27.6C21.4 29.3 21.5 29.2 19.8 29.2C18.8 29.2 18.5 29.2 18.4 29.1z"),+ shape("set-7", 40f, "M19.6 29.3C19.2 29.1 19.1 29 18.2 28.2C17 27 17.1 27 15.6 27.1C14.1 27.1 13.9 27 13.4 26.6C13 26.1 12.9 25.9 12.9 24.4C13 22.9 13 23 11.8 21.8C10.8 20.7 10.7 20.6 10.7 20C10.7 19.4 10.8 19.3 11.8 18.2C13 17 13 17.1 12.9 15.6C12.9 14.1 13 13.9 13.4 13.4C13.9 13 14.1 12.9 15.6 12.9C17.1 12.9 17 13 18.2 11.8C19.3 10.8 19.4 10.7 20 10.7C20.6 10.7 20.7 10.8 21.8 11.8C23 13 22.9 12.9 24.4 12.9C25.9 12.9 26.1 13 26.6 13.4C27 13.9 27.1 14.1 27.1 15.6C27 17.1 27 17 28.2 18.2C29.2 19.3 29.3 19.4 29.3 20C29.3 20.6 29.2 20.7 28.2 21.8C27 23 27 22.9 27.1 24.4C27.1 25.9 27 26.1 26.6 26.6C26.1 27 25.9 27.1 24.4 27.1C22.9 27.1 23 27 21.8 28.2C21.3 28.6 20.8 29.1 20.7 29.2C20.4 29.3 19.8 29.3 19.6 29.3zM19.7 23.7C20 23.3 23.8 17.9 23.8 17.7C23.8 17.5 23.7 17.3 23 16.9C22.3 16.4 22.5 16.3 20.6 18.9L19.1 21.1L18.3 20.3C17.4 19.4 17.4 19.4 16.7 20.1C15.9 20.8 15.9 20.7 17.5 22.3C19.2 23.9 19.3 24 19.7 23.7z"),+ shape("set-8", 40f, "M14.1 26.2C12.8 25.9 11.7 25.1 11.2 24C10.3 22 11.4 19.3 13.3 19C13.5 18.9 13.5 18.9 13.5 18.6C13.8 17 15.1 15.8 16.8 16C17.3 16 17.3 16 17.6 15.6C20.5 12 26.2 13.8 26.8 18.6C26.8 19.3 26.8 19.3 27.2 19.5C27.7 19.7 28.4 20.5 28.7 21C29.7 23.2 28.6 25.6 26.2 26.2C25.5 26.4 14.8 26.4 14.1 26.2zM26.1 25C28.2 24.4 28.6 21.7 26.7 20.6C26.5 20.4 26.2 20.3 26.1 20.2C25.6 20.1 25.6 20.1 25.7 19.6C26 15.1 20.5 13.1 18.1 16.8C17.8 17.2 17.8 17.3 17.6 17.2C16 16.8 14.8 17.6 14.6 19.2C14.5 19.8 14.5 19.8 14.1 19.8C13 19.9 12.2 20.8 12.1 22C11.9 23.3 12.8 24.6 14.2 25C14.8 25.2 25.6 25.2 26.1 25z"),+ shape("set-9", 40f, "M9.9 27.3C8 26.6 7.9 22.7 9.8 17.9C11.8 12.9 13.3 11.9 19.5 11.9C23.9 11.9 25.6 12.4 27.3 14.1C30.3 17.1 32.1 24.5 30.3 26.8C29.3 28.1 26.5 27.3 24.2 24.8C23.8 24.5 23.5 24.1 23.4 24.1C23.2 24 16.4 24 16.2 24.1C16.1 24.1 15.6 24.5 15.2 24.9C13.4 26.7 11.1 27.8 9.9 27.3zM15.7 20.7C15.8 20.6 15.8 20.5 15.9 19.9L15.9 19.2L16.6 19.2C17.5 19.1 17.5 19.1 17.6 18.3C17.6 17.3 17.5 17.2 16.5 17.2C15.9 17.2 15.9 17.2 15.9 16.6C15.9 15.6 15.8 15.5 14.8 15.5C14 15.5 13.9 15.7 13.9 16.6L13.9 17.2L13.2 17.2C12.4 17.2 12.2 17.3 12.2 18C12.1 19 12.3 19.1 13.2 19.2L13.8 19.2L13.9 19.9C13.9 20.8 14 20.9 14.9 20.9C15.4 20.9 15.5 20.9 15.7 20.7zM25.6 20.4C27.4 19.5 27.4 16.7 25.5 16C23.1 15.1 21.2 18 22.8 19.8C23.5 20.5 24.7 20.8 25.6 20.4z"),+ shape("set-10", 40f, "M11.5 28.7C11.3 28.5 11.2 28.1 11.3 27.8C11.4 27.7 11.9 27.2 12.5 26.6L13.6 25.5L14.1 26.1L14.7 26.7L13.5 27.8C12.4 28.9 12.4 28.9 12.1 28.9C11.8 28.9 11.7 28.9 11.5 28.7zM16.6 26.8C15.4 26.1 13.2 23.7 13.2 23.2C13.2 23.1 13.2 22.9 13.3 22.9C13.3 22.8 19.5 18.1 21.8 16.5C21.9 16.4 21.9 16.4 21.7 16C21.5 15.5 21.2 14.5 21 13.9C20.8 13 20.7 13.1 23 10.8C24.9 8.9 25.2 8.7 25.8 9C26.2 9.2 26.2 9.4 26.7 11.5C26.9 12.3 27.1 13.1 27.1 13.1C27.2 13.1 27.9 13.3 28.7 13.5C30.9 14 31.1 14.1 31.3 14.6C31.4 15 31.3 15.3 30.5 16.1C29.6 17.1 27.5 19.1 27.2 19.2C26.9 19.4 26 19.2 24.5 18.6L23.8 18.3L20.6 22.6C17.8 26.5 17.4 26.9 17.3 27C17 27.1 17 27.1 16.6 26.8z"),+ shape("set-11", 40f, "M19.3 27.2C19.2 27.2 18.9 27 18.7 26.7C18.3 26.3 11.3 18 10.8 17.4C10.4 16.8 10.3 16.3 10.6 15.8C10.9 15.4 13.6 12.5 13.9 12.3C14.2 12.1 14.2 12.1 19.8 12.1C25.1 12.1 25.4 12.1 25.7 12.2C25.9 12.4 28.6 15.1 29 15.7C29.2 16 29.3 16.6 29.1 17C28.9 17.4 20.9 26.9 20.6 27.1C20.3 27.3 19.6 27.4 19.3 27.2z"),+ shape("set-12", 40f, "M14.7 28.4C12.8 28.4 12.7 28.3 12.1 27.8C11.5 27.1 11.5 27.4 11.5 20C11.5 12.6 11.5 12.8 12.2 12.1C12.9 11.5 12.6 11.5 20 11.5C27.4 11.5 27.1 11.5 27.8 12.1C28.5 12.8 28.5 12.6 28.5 20C28.5 27.4 28.5 27.2 27.8 27.9C27.5 28.2 27.2 28.3 26.7 28.4C26.2 28.5 17 28.5 14.7 28.4zM15.7 26.3C17.2 25.7 16.7 23.4 15.1 23.4C13.5 23.4 13 25.6 14.5 26.3C14.8 26.4 15.4 26.4 15.7 26.3zM25.7 26.2C27 25.5 26.5 23.4 25 23.4C23.9 23.4 23.2 24.5 23.6 25.5C24 26.3 24.9 26.6 25.7 26.2zM20.5 21.4C21 21.3 21.5 20.6 21.5 20C21.5 19.2 20.8 18.5 20 18.5C19.4 18.5 18.7 19 18.6 19.5C18.2 20.7 19.3 21.8 20.5 21.4zM15.8 16.4C16.5 16 16.8 15.1 16.5 14.5C15.7 13.1 13.6 13.5 13.6 15.1C13.6 16.3 14.8 16.9 15.8 16.4zM25.7 16.4C26.2 16.2 26.6 15.5 26.4 14.8C26.2 13.4 24.3 13.2 23.6 14.5C23 15.8 24.4 17 25.7 16.4z"),+ shape("set-13", 40f, "M19.1 28.6C16.1 28.1 13.9 25.7 13.5 22.6C13.3 20.3 15.2 16.5 19.2 11.4C20.1 10.4 19.9 10.3 21.7 12.7C24.5 16.4 26.2 19.5 26.4 21.4C26.8 24 25 27.1 22.4 28.2C21.5 28.5 20 28.7 19.1 28.6z"),+ shape("set-14", 40f, "M16.2 29.2C14.1 28.7 12.3 27.1 11.7 24.9C11.5 24.1 11.5 22.1 11.8 22.1C11.8 22.1 13.1 22.4 14.6 22.7C17.1 23.3 17.4 23.4 17.5 23.5C17.5 23.9 18.2 29.2 18.2 29.3C18.1 29.4 16.8 29.3 16.2 29.2zM18.3 22.6C18 22.4 18 22.4 18.2 21.9C19.7 18.7 21.7 15.9 24.8 13C27.2 10.6 28.6 10 29.8 10.9C31 11.8 30.3 13.6 27.8 16.1C25.1 19 22.7 20.8 19.5 22.3C18.5 22.9 18.5 22.9 18.3 22.6z"),+ shape("set-15", 40f, "M18.6 29.1C12.5 28.1 9.1 21.6 11.7 16.1C13.8 11.5 19.5 9.5 24 11.7C28.5 14 30.4 19.4 28.3 23.9C27.8 25 27 26.1 26.1 26.8L25.7 27.2L27.5 27.2C29 27.2 29.2 27.2 29.4 27.3C30.1 27.6 30.2 28.5 29.5 29C29.3 29.2 19.6 29.3 18.6 29.1zM21 26.6C22.7 25.8 22.6 23.1 20.8 22.4C18.8 21.6 16.9 23.9 18.1 25.8C18.7 26.7 20 27.1 21 26.6zM16.5 22C18.6 21 17.9 17.8 15.5 17.8C12.9 17.8 12.3 21.1 14.6 22.1C15.1 22.3 15.9 22.3 16.5 22zM25.5 22.1C26.9 21.4 27.2 19.5 26.1 18.4C25 17.3 23 17.7 22.4 19.2C21.7 21.1 23.7 22.9 25.5 22.1zM20.4 20.9C21 20.6 21.2 19.8 20.7 19.3C20 18.6 18.8 19.2 19 20.2C19.1 20.8 19.8 21.2 20.4 20.9zM20.9 17.6C22.3 17 22.7 15 21.6 13.8C20.5 12.8 18.6 13.1 18 14.5C17.7 15 17.7 15.9 18 16.5C18.5 17.5 19.7 18 20.9 17.6z"),+ shape("set-16", 40f, "M21.1 26.8C18.3 26.5 15.7 25 13.9 22.7C13.6 22.2 13.5 22.2 13.4 22.3C13.3 22.3 12.4 22.9 11.2 23.6C9 25 8.9 25.1 8.6 24.7C8.4 24.5 8.4 24.4 8.7 23.4C9.5 20.7 9.5 19.3 8.7 16.6C8.4 15.6 8.4 15.5 8.6 15.3C8.9 14.9 9 15 11.2 16.4C12.4 17.1 13.3 17.7 13.4 17.7C13.5 17.8 13.6 17.8 13.9 17.3C16 14.6 18.9 13.2 22.2 13.2C25.9 13.2 29.2 15.2 31.5 18.9C32.1 19.9 32.1 20 31.9 20.3C30.6 23 27.9 25.5 25.3 26.4C24.1 26.8 22.2 27 21.1 26.8zM28.5 20C28.9 19.7 29.1 19.3 29.1 18.9C29.1 17.7 27.7 17.2 26.9 18C25.8 19 27.1 20.7 28.5 20z"),+ shape("set-17", 40f, "M18.4 29.9C18 29.7 17.7 29.2 17.8 28.7C17.8 28.6 18.5 27.1 19.7 25C20.7 23.1 21.6 21.5 21.6 21.5C21.6 21.3 20.2 21.5 18.9 21.8C15.7 22.7 14.2 22.6 12 21.6C11.1 21.2 11.1 21.2 11.9 19.6C12.2 18.9 13.1 17.1 13.7 15.7C14.4 14.3 15 13.1 15 13C15.2 12.8 15.5 12.8 15.9 13.1C17.8 14 19.5 13.9 23.3 12.7C25.8 11.9 27.6 11.8 28.5 12.3C28.8 12.6 28.9 12.4 26.2 17.5C24.8 20.1 22.7 23.8 21.7 25.8C20.6 27.9 19.6 29.6 19.5 29.7C19.3 30 18.8 30.1 18.4 29.9z"),+ shape("set-18", 40f, "M18.8 29.5C15.4 28.9 13.4 26.6 13.4 23.2C13.4 21.9 13.6 21.4 14.5 19.5C15.2 17.8 15.4 17.4 15.4 16.8C15.4 16.4 15.4 16.3 15.6 16.3C15.9 16.3 17.5 17.8 18.2 18.7L18.5 19.1L18.7 18.8C19.5 17 19.4 14.3 18.4 10.9C18.3 10.5 18.4 10.4 19 10.7C25.9 13.1 29.5 21.4 25.9 26.8C24.4 28.9 21.7 30 18.8 29.5z"),+ shape("set-19", 40f, "M16.9 28.4C16.5 28.1 16.5 28.1 17.6 24.5C18.2 22.7 18.6 21.3 18.6 21.2C18.6 21.2 17.5 21.2 16.1 21.2C14.7 21.2 13.4 21.2 13.3 21.1C12.6 21 12.2 20.2 12.5 19.6C12.6 19.3 21.2 10.8 21.7 10.4C22 10.2 22.5 10.3 22.7 10.5C23.1 10.9 23.1 10.9 22 14.5C21.5 16.2 21 17.7 21 17.7C21 17.8 22.1 17.8 23.7 17.8C26.4 17.8 26.4 17.8 26.7 18C27.2 18.3 27.4 19 27.1 19.5C27.1 19.7 18.2 28.3 17.9 28.6C17.6 28.8 17.1 28.7 16.9 28.4z"),+ shape("set-20", 40f, "M15.1 27.8C13.7 27.5 12.5 26.3 12.1 24.9C11.5 22.9 12.9 20.6 14.9 20.1C15.2 20.1 15.4 20 15.4 20C15.4 20 15.2 19.9 14.9 19.9C13.9 19.6 12.9 18.8 12.4 17.9C11.4 15.9 12.2 13.5 14.1 12.6C16.5 11.4 19.1 12.7 19.7 15.2C19.8 15.6 19.9 15.7 19.9 15.5C19.9 14.6 20.7 13.3 21.7 12.8C24.3 11.1 27.7 13 27.7 16.1C27.7 17.9 26.2 19.7 24.5 19.9C24.2 20 24.2 20 24.5 20.1C26.2 20.3 27.7 22.1 27.7 23.9C27.7 27 24.5 28.8 21.8 27.3C20.9 26.8 19.9 25.4 19.9 24.5C19.9 24.3 19.8 24.4 19.7 24.8C19.2 26.9 17.1 28.2 15.1 27.8z"),+ shape("set-21", 40f, "M18.5 29.6C17.9 29.5 17.5 29.1 17.5 28.5C17.5 28.4 17.7 26.8 17.9 24.9C18.1 23.1 18.2 21.5 18.2 21.5C18.2 21.4 18.6 21.4 20.3 21.4C21.4 21.4 22.4 21.4 22.4 21.4C22.4 21.4 22.5 23 22.7 24.8C23 28.6 23 28.8 22.7 29.2C22.4 29.6 22.3 29.6 20.5 29.6C19.6 29.6 18.7 29.6 18.5 29.6zM18.2 19.9C17.8 17.8 17.7 17.5 17.2 17.1C16.2 16.2 14.8 16.7 14.3 18.1C14.1 18.8 14.1 18.8 13 18.5C11.2 18.1 11.3 18.3 11.3 15.2C11.3 12.1 11.2 12.4 12.9 12C13.9 11.7 14.1 11.7 14.2 12.1C14.2 12.2 14.3 12.4 14.3 12.5C14.6 13.6 16.1 14 17.1 13.3C17.4 13.1 17.7 12.6 17.8 12.2C17.9 11.6 17.8 11.6 18.8 11.4C21.2 11.1 24 11.4 25.8 12.3C27.7 13.3 28.7 14.7 28.7 16.7C28.7 18 28.7 18 28.2 17.4C26.5 15 24.7 14.6 23.5 16.5C23.1 17 22.9 17.6 22.7 18.8C22.6 19.5 22.5 20 22.5 20.1C22.4 20.2 22.4 20.2 20.3 20.2C18.3 20.2 18.3 20.2 18.2 19.9z"),+ shape("set-22", 40f, "M13.7 29.1C11.7 28.9 11.3 28.5 10.9 25.6C10.2 21.6 10.5 17.7 11.4 15.6C12.9 12.6 15.5 11 19.4 10.8C24.9 10.6 28.5 13.3 29.3 18.1C29.7 20.7 29.4 24.7 28.8 27.3C28.4 28.8 27.6 29.2 25.1 29.1C22.7 29.1 22 28.9 21.5 27.9C21.2 27.3 21.4 24.9 21.7 23.4C22.2 21.5 22.7 21.3 25.7 21.3L27.2 21.3L27.2 20.2C27.1 17.4 26.3 15.7 24.7 14.4C22.3 12.6 17.7 12.6 15.4 14.4C13.6 15.7 12.8 17.6 12.8 20.6L12.8 21.3L14.3 21.3C17.3 21.3 17.8 21.5 18.3 23.4C18.6 24.9 18.8 27.3 18.5 27.9C18.2 28.6 17.6 29 16.7 29.1C15.9 29.2 14.3 29.2 13.7 29.1z"),+ shape("set-23", 40f, "M19 27C13.6 23.5 10.6 19.8 10.6 16.8C10.6 12.1 16.1 9.8 19.5 13L19.8 13.3L20.2 13C22.5 10.8 26.1 11.1 28 13.5C30.5 16.8 28.8 21 23.1 25.3C22.1 26.1 19.9 27.5 19.8 27.5C19.8 27.5 19.4 27.3 19 27z"),+ shape("set-24", 40f, "M14.9 29.2C14.3 29.1 13.8 28.7 13.6 28.2C13.4 27.9 13.4 25.1 13.4 22.6L13.4 20.8L12.9 20.7C12.2 20.7 11.5 20.7 11.3 20.5C10.9 20.3 10.7 19.5 10.9 19C11.2 18.6 13.6 16.3 17.2 13.2C19.4 11.3 19.5 11.2 20 11.2C20.5 11.2 20.5 11.1 24.3 14.5C29.1 18.8 29.4 19.2 29.1 20C28.9 20.5 28.6 20.7 27.4 20.7L26.5 20.8L26.6 22.5C26.6 24.9 26.6 27.9 26.4 28.2C26.1 29 25.6 29.2 23.7 29.2L22.2 29.3L22.2 27.2C22.2 24.2 22.3 24.3 20 24.3C17.7 24.3 17.8 24.2 17.8 27.2L17.8 29.2L16.5 29.2C15.8 29.2 15.1 29.2 14.9 29.2z"),+ shape("set-25", 40f, "M19.8 28.3C15 27.5 11.9 23.1 12.7 18.4C13.4 14.5 16.7 11.5 20.6 11.3C21.3 11.2 21.3 11.2 21 11.5C17.9 15.3 18.7 20.5 22.6 22.6C24.5 23.5 26.8 23.6 28.8 22.9C29.3 22.8 29.3 22.8 29 23.3C28 25.8 25.6 27.7 22.9 28.3C22.3 28.4 20.4 28.5 19.8 28.3z"),+ shape("set-26", 40f, "M12.9 29.4C10.8 28.8 10 26.3 11.5 24.6C12.4 23.7 13.6 23.4 14.8 23.7L15.2 23.9L15.2 18.5C15.2 13.3 15.2 13.2 15.3 13.1C15.5 12.9 26.7 10.1 26.9 10.2C27.3 10.3 27.2 9.8 27.2 18C27.3 26.4 27.3 25.9 26.8 26.6C25.1 29.3 20.9 28 21.1 24.9C21.2 22.8 23.4 21.5 25.4 22.3C25.5 22.4 25.5 22.2 25.5 19.3C25.5 16.1 25.5 16.1 25.2 16.1C25 16.1 17.1 17.6 17.1 17.7C17 17.7 17 18.9 17 22.4C17 27.6 17 27.4 16.5 28.1C15.8 29.3 14.2 29.9 12.9 29.4z"),+ shape("set-27", 40f, "M11.1 29C10.7 28.6 11.4 27.2 13.3 24.8L13.7 24.2L14.7 25.3C15.3 25.8 15.8 26.3 15.8 26.3C15.8 26.3 15.3 26.7 14.8 27C12.7 28.6 11.5 29.2 11.1 29zM15.9 24.1L14.7 23L15.4 22.1C16.4 20.9 17.1 20.2 18.8 18.3C19.6 17.4 20.6 16.2 21.1 15.7C25.2 11 27.5 9.7 28.9 11.1C30.4 12.5 29 14.8 23.9 19.3C23.2 19.9 22.3 20.7 22 21C20.4 22.5 17.1 25.2 17.1 25.2C17 25.2 16.5 24.7 15.9 24.1z"),+ shape("set-28", 40f, "M12.8 28.5C12.3 28.3 12 27.6 12.3 27.1C12.3 27 13.4 25.9 14.6 24.6L16.9 22.3L15.1 20.4C12.9 18.1 12.7 17.9 13 17.2C13.3 16.6 13.5 16.5 16.5 15.9C19.7 15.3 19.4 15.5 20 13.4C20.6 11.6 20.7 11.4 21.3 11.2C21.7 11.1 22 11.2 22.4 11.4C23.1 11.9 28.6 17.5 29 18.1C29.4 18.6 29.4 19.1 29 19.6C28.8 19.8 28.3 20 26.9 20.5C25 21 25.2 20.8 24.5 23.9C24 26.4 23.9 26.9 23.7 27.1C23.5 27.3 23.1 27.5 22.8 27.5C22.3 27.5 22.1 27.4 19.1 24.4L18.4 23.8L16.1 26.1C14.8 27.4 13.7 28.5 13.6 28.5C13.4 28.6 13 28.6 12.8 28.5z"),+ shape("set-29", 40f, "M15.1 29.8C15.1 29.7 15.6 27.9 16.3 25.8C17 23.6 17.5 21.9 17.5 21.8C17.4 21.8 12.7 21.3 12.6 21.4C12.6 21.4 12.4 21.9 12.2 22.6C11.7 23.9 11.6 24.1 11.1 24.3C10.4 24.7 10.5 25.1 10.5 20C10.5 14.9 10.4 15.3 11.1 15.7C11.6 15.9 11.7 16.1 12.2 17.4C12.4 18.1 12.6 18.6 12.6 18.6C12.7 18.7 17.4 18.2 17.5 18.2C17.5 18.1 15.2 10.5 15 10.1C15 10 16.7 10 17.3 10.1C18.3 10.4 18.3 10.3 21.7 14.6L24.5 18L26.7 18C29 18 29 18 29.3 18.2C30.8 18.9 30.8 21.1 29.3 21.8C29 22 29 22 26.7 22L24.5 22L21.7 25.5C18.6 29.2 18.5 29.3 18 29.6C17.4 29.9 17 30 16 30C15 30 15 30 15.1 29.8z"),+ shape("set-30", 40f, "M14.7 27.9C13.7 27.9 13.6 27.9 13.3 27.7C12.7 27.3 12.6 26.9 12.6 23.8C12.6 22.7 12.5 22.7 11.8 22.8C9.9 23.1 8.2 21.4 8.6 19.5C8.8 17.9 10.4 16.8 12 17.2C12.5 17.3 12.6 17.2 12.6 16.2C12.6 12.3 12.7 12.2 14.7 12.1C17.6 11.9 17.5 11.9 17.2 13C16.8 14.6 17.9 16.2 19.6 16.5C21.5 16.8 23.3 14.9 22.8 13C22.5 11.9 22.4 12 24.5 12C26.5 12.1 26.7 12.1 27.1 12.7C27.3 13.1 27.4 13.2 27.4 15.3C27.5 17.3 27.5 17.3 28 17.2C29.4 16.8 31 17.8 31.4 19.3C31.9 21.2 30.2 23.1 28.2 22.8C27.4 22.7 27.5 22.5 27.4 25C27.3 27.1 27.3 27.1 26.9 27.5C26.5 27.9 26.5 27.9 24.7 28C22.5 28 22.5 28 22.7 27.3C23.3 25.5 22.2 23.8 20.4 23.5C18.5 23.1 16.7 25.1 17.2 27C17.5 28.1 17.6 28.1 14.7 27.9z"),+ shape("set-31", 40f, "M13.5 28.9C13 28.7 11.1 26.8 11.1 26.5C11 25.8 10.9 25.9 13.9 23.5L16.1 21.8L17.2 22.9L18.3 24.1L16.5 26.3C14.1 29.3 14.2 29.3 13.5 28.9zM22.1 24.7C21 24.4 19.8 23.6 18.2 21.9C14.3 18 14.2 15.9 18 12.5C20.3 10.6 22.6 10.2 24.9 11.3C26.8 12.3 28.7 14.5 29.2 16.4C29.7 18.6 29 20.5 26.7 22.8C25 24.5 23.6 25.1 22.1 24.7z"),+ shape("set-32", 40f, "M19.6 28.8C19.3 28.6 19.3 28.5 19.1 27.7C18.4 24.2 15.8 21.6 12.3 20.9C11.4 20.7 11.1 20.5 11.1 20C11.1 19.5 11.4 19.3 12.3 19.1C15.8 18.4 18.4 15.8 19.1 12.3C19.3 11.4 19.5 11.1 20 11.1C20.5 11.1 20.7 11.4 20.9 12.3C21.5 15.8 24.2 18.5 27.6 19.1C28.6 19.3 28.9 19.5 28.9 20C28.9 20.5 28.6 20.7 27.6 20.9C24.2 21.5 21.5 24.2 20.9 27.7C20.7 28.6 20.5 28.9 20 28.9C19.9 28.9 19.7 28.8 19.6 28.8z"),+ shape("set-33", 40f, "M14.3 28.4C14.1 28.2 13.9 28 13.8 27.7C13.8 27.6 14 26.8 14.4 25C14.8 23.6 15.1 22.4 15.1 22.3C15.1 21.9 15 21.9 12.8 20C10.6 18.2 10.6 18.1 10.7 17.6C10.9 17 10.8 17 13.9 16.8C15.3 16.7 16.4 16.6 16.5 16.6C16.9 16.5 17.1 16.3 17.8 14.4C19.3 10.8 19.2 10.9 19.8 10.9C20.4 10.9 20.4 11 21.5 13.7C22 15 22.5 16.2 22.6 16.3C22.8 16.6 22.9 16.6 25.7 16.8C28.5 17 28.6 17 28.8 17.3C28.9 17.6 29 18 28.9 18.2C28.8 18.3 27.9 19.1 26.8 20C25.7 21 24.7 21.8 24.7 21.9C24.5 22.2 24.5 22.5 25.2 25C25.9 27.7 25.9 27.8 25.6 28.1C25.1 28.7 25 28.6 22.4 27C20.3 25.6 20.1 25.5 19.8 25.5C19.5 25.5 19.4 25.6 17.3 27C14.9 28.5 14.7 28.5 14.3 28.4z"),+ shape("set-34", 40f, "M19.7 29.5C19.7 29.5 19.2 28.8 18.6 28C17.9 27.1 17.5 26.4 17.4 26.4C17.2 26.3 16.9 26.4 15.5 26.6C13.5 27 13.4 27 13.2 26.8C13 26.6 13 26.6 13.4 24.6C13.6 23.1 13.7 22.8 13.6 22.6C13.6 22.5 12.9 22.1 12 21.4C10.9 20.6 10.5 20.3 10.4 20.2C10.3 19.8 10.4 19.7 12 18.6C12.9 17.9 13.6 17.5 13.6 17.4C13.7 17.2 13.6 16.9 13.4 15.4C13 13.4 13 13.4 13.2 13.2C13.4 13 13.5 13 15.5 13.4C16.9 13.6 17.2 13.7 17.4 13.6C17.5 13.6 18 12.9 18.6 12C20.1 9.9 19.9 9.9 21.4 12C22 12.9 22.5 13.6 22.6 13.6C22.8 13.7 23.1 13.6 24.5 13.4C26.5 13 26.6 13 26.8 13.2C27 13.4 27 13.4 26.6 15.4C26.4 16.9 26.3 17.2 26.4 17.4C26.4 17.5 27.1 17.9 28 18.6C29.1 19.4 29.5 19.7 29.6 19.8C29.7 20.2 29.6 20.3 28 21.4C27.1 22.1 26.4 22.5 26.4 22.6C26.3 22.8 26.4 23.1 26.6 24.6C27 26.6 27 26.6 26.8 26.8C26.6 27 26.5 27 24.5 26.6C23.1 26.4 22.8 26.3 22.6 26.4C22.5 26.4 22.1 27.1 21.4 28C20.3 29.6 20.3 29.6 20 29.6C19.9 29.6 19.8 29.6 19.7 29.5zM20.7 22.9C23 22.3 23.7 19.6 22.1 17.9C20.5 16.2 17.7 17 17.1 19.3C16.5 21.4 18.6 23.5 20.7 22.9z"),+ shape("set-35", 40f, "M10.6 29.2C10.4 25.5 11.7 22 14.2 19.9C16 18.4 17.5 17.8 21.1 16.9C22.9 16.5 23.3 16.4 24.2 16.1C26.8 15.2 28.4 13.5 29.1 10.9C29.3 10.1 29.3 10.1 29.3 10.5C29.4 11 29.3 13.5 29.2 14.1C28.6 17.5 26.7 20 23.4 21.6C22 22.3 21.2 22.5 18.2 23.2C13.6 24.2 11.9 25.6 10.7 29.8C10.7 29.9 10.6 29.7 10.6 29.2z"),+ shape("set-36", 40f, "M11 29.2C10 28.3 10 28.5 11.8 26.7C12.6 25.9 13.3 25.1 13.4 25C13.5 24.9 13.5 24.9 12.2 23.5C10.5 21.8 10.5 21.9 11.5 21C12.3 20.2 12.4 20.2 13.1 20.9L13.5 21.4L14.3 20.5C19 15.5 23.6 11.7 26.4 10.8C27.6 10.4 28.4 10.5 29.1 11.1C30.3 12.3 29.6 14.5 27 18.1C25.7 19.8 21.6 24.2 19.4 26.2L18.8 26.7L19.3 27.2C20 27.9 20 28.1 19.2 28.9C18.3 29.7 18.4 29.8 16.7 28L15.3 26.7L13.8 28.2C11.7 30.2 11.9 30.2 11 29.2z"),+ shape("set-37", 40f, "M16.1 29.7C15.7 29.6 14.6 28.6 14.6 28.4C14.6 28.4 14.7 28.2 14.8 28C15.7 26.5 15.1 24.8 13.6 24.1C12.9 23.8 11.7 24 11.1 24.4C10.8 24.7 10.7 24.6 10.2 24.1C9.5 23.3 9.4 22.8 9.7 22.1C9.9 21.7 17.1 14.4 17.2 14.4C17.3 14.4 17.5 14.6 17.7 14.8C18.3 15.3 18.8 15.4 19.2 14.9C19.6 14.5 19.5 14.1 19 13.5C18.8 13.3 18.6 13.1 18.6 13C18.6 13 21.2 10.4 21.5 10.2C22.3 9.7 23 9.8 23.9 10.7C24.3 11.1 24.3 11.1 24 11.5C22.6 13.9 25.2 16.7 27.6 15.2C28.1 14.9 28.1 14.9 28.7 15.5C29.5 16.4 29.6 16.9 29.3 17.6C29.1 18 26.5 20.7 26.3 20.7C26.2 20.7 26 20.6 25.9 20.4C25.3 19.8 24.6 19.8 24.2 20.3C24 20.8 24.1 21.2 24.6 21.7C25 22.1 25 22.1 23.7 23.4C21.3 25.9 17.6 29.4 17.3 29.6C17 29.8 16.5 29.9 16.1 29.7zM22.9 19C23.3 18.8 23.4 18.2 23.2 17.8C23 17.5 21.6 16.1 21.3 16.1C20.7 15.9 20.1 16.5 20.2 17.2C20.3 17.4 21.7 18.9 22 19.1C22.2 19.2 22.7 19.1 22.9 19z"),+ shape("set-38", 40f, "M19.1 29C19 28.9 19 28.9 18.9 27.7L18.9 26.6L15.1 26.6C11 26.5 11.2 26.6 11.1 26.1C10.9 25.7 10.9 25.7 14.2 22.5L17.4 19.5L15.3 19.5C13.2 19.5 13.1 19.5 12.9 19.2C12.8 19.1 12.8 18.6 12.9 18.4C13.2 18.1 19.4 11.3 19.6 11.2C19.7 11.2 19.9 11.1 20 11.1C20.1 11.1 20.3 11.2 20.4 11.2C20.6 11.3 26.8 18.1 27.1 18.4C27.2 18.6 27.2 19.1 27.1 19.2C26.9 19.5 26.8 19.5 24.7 19.5L22.6 19.5L25.8 22.5C29.1 25.7 29.1 25.7 28.9 26.1C28.8 26.6 29 26.5 24.9 26.6L21.1 26.6L21.1 27.7C21 29.1 21.1 29.1 20 29.1C19.5 29.1 19.2 29 19.1 29z"),+ shape("set-39", 40f, "M17.6 29.4C16.6 29.1 15.7 28.1 15.5 27C15.4 26.4 15.6 26.3 16.6 26.3C17.5 26.3 17.6 26.4 17.6 26.7C17.6 27.2 18.3 27.5 18.7 27.2C19.1 27 19.1 26.9 19.1 24.2L19.1 21.8L18.5 21.8C16.5 21.8 13.4 22.2 11.7 22.8C11.3 22.9 11 23 11 23C11 22.9 11.1 20.1 11.2 19.4C11.8 14.9 14.2 12.6 18.6 12.2C19.1 12.1 19.1 12.1 19.1 11.3C19.1 10.4 19 10.4 20.1 10.4C21.1 10.4 21.1 10.4 21.1 11.3C21.1 12.1 21.1 12.1 21.5 12.2C26 12.7 28.1 14.8 28.8 19.5C28.9 20.3 29 23 28.9 23C28.9 23 28.7 22.9 28.5 22.9C27.2 22.4 24.3 21.9 22 21.8L21.1 21.7L21.1 24.4C21.1 27 21.1 27.1 21 27.5C20.5 28.9 19.1 29.7 17.6 29.4z"),+ shape("set-40", 40f, "M11.2 29.9C10.4 29.7 10 29.1 10 28.3C10 27.2 10.8 26.1 12.8 24.1C15.5 21.3 17.7 19.7 20.7 18.2C21.8 17.7 21.8 17.7 22 17.9C22.3 18.1 22.3 18.1 21.7 19.3C20.3 22.1 19.1 23.8 16.5 26.6C14.1 29.2 12.3 30.3 11.2 29.9zM24.5 19.4C24.2 19.3 24.1 19 23.7 18.1C23.2 16.7 23.3 16.8 22 16.3C20.7 15.8 20.5 15.7 20.5 15.2C20.5 14.8 20.5 14.7 21.6 13.9C22.7 13 22.6 13.2 22.7 11.2C22.8 10.4 22.9 10.1 23.3 10C23.6 9.9 23.7 9.9 24.8 10.6C25.9 11.3 26 11.3 26.7 11.2C28.3 10.7 28.7 10.6 29 11C29.3 11.3 29.3 11.4 29 12.6C28.6 14.1 28.5 13.9 29.4 15.3C30 16.2 30.1 16.5 29.9 16.8C29.6 17.1 29.5 17.2 28.2 17.3C26.8 17.3 26.9 17.3 26.1 18.4C25.2 19.4 25 19.6 24.5 19.4z"),+ shape("set-41", 40f, "M10.1 28.9C8.9 28.7 8.5 28.2 8.9 27.3C9.7 25.7 13.7 24.4 18.6 24.1C24.8 23.8 31.2 25.7 31.2 27.9C31.2 28.9 30.1 29.1 25.1 28.7C22.4 28.5 17.6 28.5 14.9 28.7C12.7 28.9 10.6 29 10.1 28.9zM13.6 23.5C13.9 22.7 17.4 15.2 18.2 13.5C19.1 11.8 19 11.8 22.1 12.1C24.9 12.3 25.2 12.4 25.5 13C26 13.9 25.7 14.3 23.9 15.6C23.4 16 22.9 16.4 22.8 16.4C22.8 16.4 23.2 17.3 23.7 18.5C25 21.3 26 23.5 26 23.5C26 23.6 25.8 23.5 25.6 23.5C22.2 22.8 17.5 22.8 14 23.6C13.5 23.7 13.5 23.7 13.6 23.5z"),+ shape("set-42", 40f, "M16.7 29.9C16.4 29.8 16 29.5 15.6 28.9C15.1 28.2 14.7 27.9 14.3 27.8C14 27.7 14 27.7 16.2 21.6C17.3 18.2 18.3 15.5 18.3 15.5C18.3 15.4 19.1 15.4 20.2 15.4C22 15.4 22 15.4 22.1 15.7C22.1 15.8 23.1 18.6 24.2 21.9C26.3 27.7 26.3 27.7 25.9 27.8C25.5 27.9 25.3 28.2 24.8 28.9C23.7 30.4 22.8 30.4 21.7 28.9C20.6 27.4 19.7 27.4 18.6 28.9C17.9 29.9 17.4 30.2 16.7 29.9zM18.7 14.3C18.7 14.2 19 13.6 19.3 12.8C19.9 11.1 20 10.9 20.4 11.2C20.5 11.3 21.6 14 21.6 14.3C21.6 14.3 20.9 14.3 20.2 14.3C19.4 14.3 18.7 14.3 18.7 14.3z"),+ shape("set-43", 40f, "M18.6 28.9C16.4 28.4 14.7 26.9 14.1 24.9C13.5 22.5 15.3 17.8 19.2 12C19.8 11 19.8 11 19.9 11.1C20.4 11.7 22 14.4 22.8 15.8C25.9 21.4 26.4 24.5 24.5 26.9C23.2 28.5 20.7 29.4 18.6 28.9z"),+ shape("set-44", 40f, "M21.2 27.2C21.7 26.6 21.7 25.7 21.2 25.4C20.8 25.2 20.2 25.5 19 26.4C17.5 27.6 17.4 27.4 18.7 25.7C20.1 23.7 20.4 23.1 20.1 22.8C19.8 22.5 19.2 22.7 18 23.4C17 24.1 17 24.1 17.7 23.1C18.2 22.4 18.3 22.2 18.3 22C18.2 21.8 16.4 21.1 15.9 21.1C15.6 21.1 14 22.3 11.9 24.1C11.6 24.3 11.4 24.5 11.4 24.4C11.5 24.2 12.6 22.8 13.8 21.2C16 18.5 16.5 17.6 16.4 17.5C16.3 17.4 15.8 17.6 15 18.2C13.8 19.1 12.9 19.7 12.8 19.7C12.8 19.7 13.3 19.1 14 18.3C18 14 21.2 10.7 22.2 10.1C22.6 9.8 23.1 10 24.4 10.9C26.9 12.5 30.1 16.2 30.6 18C30.8 18.4 28.1 21.1 22.6 26.1C21.1 27.4 21 27.5 21.2 27.2z"),+ shape("set-45", 40f, "M19.8 27.2C18.6 27 18.1 25.5 19 24.5C20 23.5 21.8 24.2 21.8 25.7C21.8 26.7 20.8 27.5 19.8 27.2zM17.8 23.9C16.4 23.3 16.8 21.2 18.3 21.2C19.8 21.2 20.3 23.2 19 23.8C18.6 24 18.1 24.1 17.8 23.9zM21.4 23.9C21 23.7 20.7 23.3 20.6 22.9C20.3 21.5 22.1 20.6 23.1 21.7C23.9 22.6 23.2 24 22 24C21.8 24 21.6 23.9 21.4 23.9zM16 20.6C14.8 20 15.3 18.2 16.6 18.3C17.7 18.4 18.1 19.9 17.1 20.6C16.8 20.8 16.3 20.8 16 20.6zM19.7 20.6C18.7 20.2 18.7 18.8 19.7 18.4C20.5 18.1 21.4 18.7 21.4 19.5C21.4 20.4 20.5 21 19.7 20.6zM23.4 20.7C22.4 20.2 22.4 18.8 23.4 18.4C24 18.2 24.7 18.4 24.9 19C25.4 20 24.4 21.1 23.4 20.7zM14.2 17.4C13.5 17 13.5 16 14.2 15.6C14.6 15.3 15.1 15.4 15.4 15.8C16.1 16.7 15.2 17.9 14.2 17.4zM17.9 17.4C17.1 17 17.1 15.9 17.9 15.5C18.3 15.4 18.7 15.4 19 15.7C19.8 16.6 19 17.9 17.9 17.4zM21.6 17.4C20.6 16.9 21 15.4 22 15.4C22.3 15.4 22.7 15.7 22.9 15.9C23.3 16.5 22.7 17.5 22 17.5C21.9 17.5 21.7 17.4 21.6 17.4zM25.3 17.4C24.4 17.1 24.5 15.6 25.5 15.5C26.7 15.3 27.1 16.9 26.1 17.4C25.8 17.5 25.6 17.5 25.3 17.4zM12.4 14.5C11.9 14.2 11.9 13.4 12.4 13.1C12.8 12.9 13.3 13 13.5 13.4C13.9 14.1 13.1 14.9 12.4 14.5zM16.1 14.5C15.2 13.9 15.9 12.7 16.8 13.1C16.9 13.1 17.1 13.2 17.1 13.3C17.6 14.1 16.8 15 16.1 14.5zM19.8 14.6C19.6 14.5 19.4 14.1 19.4 13.8C19.4 13.1 20.2 12.7 20.7 13.2C21.3 13.9 20.7 14.9 19.8 14.6zM23.4 14.5C23.1 14.3 23 13.9 23.1 13.6C23.3 13 23.9 12.8 24.4 13.3C25.1 13.9 24.2 15 23.4 14.5zM27.1 14.5C26.5 14.2 26.6 13.3 27.2 13.1C27.8 12.8 28.4 13.3 28.3 13.9C28.2 14.5 27.6 14.8 27.1 14.5z"),+ shape("set-46", 40f, "M18.9 29.4C16.7 28.6 17.2 25.5 19.5 25.5C21.6 25.5 22.3 28.4 20.3 29.3C19.9 29.5 19.3 29.5 18.9 29.4zM23.3 28.5C22.6 28.2 23.2 26.8 24.1 26.6C25.4 26.2 25.8 27.5 24.5 28.3C24.1 28.6 23.6 28.7 23.3 28.5zM14.2 27.6C13.7 27.5 13 26.8 12.4 26C11.5 24.8 11.8 23.5 13.1 23.5C14.6 23.5 16 24.9 16 26.5C16 27.3 15.1 27.9 14.2 27.6zM26.6 25.4C26 25.1 25.8 24.3 26.3 23.8C27 23.1 28.2 23.7 28 24.7C27.9 25.3 27.2 25.7 26.6 25.4zM22 24.9C21.5 24.8 21 24.1 21 23.5C21 22.7 21.7 22 22.5 22C23.3 22 24 22.7 24 23.5C24 24.5 23 25.2 22 24.9zM17.4 23.4C15.2 22.6 15.7 19.5 18 19.5C20.1 19.5 20.8 22.4 18.8 23.3C18.4 23.5 17.8 23.5 17.4 23.4zM11.5 21.9C10.4 21.6 10 19.8 10.8 18.6C12 16.9 14.7 18.9 13.8 20.8C13.4 21.7 12.3 22.2 11.5 21.9zM28.5 21.8C28 21.6 28.1 20.9 28.5 20.7C28.9 20.5 29.1 20.7 29.1 21.3C29.1 21.7 28.9 21.9 28.5 21.8zM24.6 21.4C24 21.1 23.8 20.3 24.3 19.8C25 19.1 26.2 19.7 26 20.7C25.9 21.3 25.2 21.7 24.6 21.4zM21.2 19C19.9 18.4 20.1 16.5 21.5 16.2C22.7 15.9 23.7 17.2 23.2 18.3C22.8 19 21.9 19.3 21.2 19zM15.5 18.4C15 18.3 14.5 17.6 14.5 17C14.5 16.2 15.2 15.5 16 15.5C16.8 15.5 17.5 16.2 17.5 17C17.5 18 16.5 18.7 15.5 18.4zM27 18.3C26.5 18.1 26.6 17.4 27 17.2C27.2 17.1 27.3 17.1 27.5 17.2C28 17.4 28 18.1 27.5 18.3C27.2 18.4 27.3 18.4 27 18.3zM11.3 16.4C11.3 16.3 11.3 16.2 11.5 15.8C12 14.9 12.2 14.6 12.5 14.6C13.2 14.5 13.2 15.4 12.5 16C12.1 16.5 11.5 16.6 11.3 16.4zM18.6 15.4C18.3 15.3 18.1 15 18 14.7C17.8 13.7 19 13.1 19.7 13.8C20.5 14.6 19.6 15.9 18.6 15.4zM24.4 15.2C23.8 14.5 24.6 13.5 25.3 14C25.9 14.4 25.6 15.4 24.9 15.4C24.7 15.4 24.6 15.3 24.4 15.2zM14.7 13.4C14.1 13.2 14.3 12.5 15 12.2C15.6 11.8 16.1 12.1 16 12.7C15.9 13.3 15.2 13.7 14.7 13.4zM21.5 12.8C21 12.6 21.1 11.9 21.5 11.7C21.7 11.6 21.8 11.6 22 11.7C22.5 11.9 22.5 12.6 22 12.8C21.7 12.9 21.8 12.9 21.5 12.8zM17.6 11.3C17.5 11.2 17.7 11 17.9 11C18 11 18.1 11.2 18 11.2C17.9 11.4 17.7 11.4 17.6 11.3z"),+ shape("set-47", 40f, "M15 27.4C14.7 27.3 14.2 27.1 14.2 27C14.1 27 17 24.1 20.6 20.5C26.7 14.4 27 14.1 27.1 14.2C27.5 14.7 27.6 15.2 27.6 17.4L27.6 19.2L23.4 23.4L19.3 27.5L17.3 27.5C15.8 27.5 15.3 27.5 15 27.4zM24.1 24.1L27.5 20.6L27.5 22.8C27.6 25.5 27.5 25.9 26.8 26.6C26.1 27.4 25.8 27.5 22.9 27.5L20.7 27.5L24.1 24.1zM13.3 25.9C13 25.4 13 25.1 13 23.4L13 21.7L17.4 17.4L21.7 13L23.6 13C25.5 13 26.1 13.1 26.2 13.4C26.3 13.4 13.5 26.2 13.4 26.2C13.4 26.2 13.3 26.1 13.3 25.9zM13 17.9C13 14.8 13 14.6 13.8 13.9C14.5 13.1 14.8 13 17.9 13L20.3 13L16.7 16.7L13 20.3L13 17.9z"),+ )+ }+ const val PICKED_SET_ICONS = 42+ val SetIconNames = listOf("Angled Brush", "Artboard", "Asterisk", "Bell", "Bookmark", "Brush", "Cactus", "Checkmark", "Cloud", "Controller", "Dart", "Diamond", "Dice", "Drop", "Fan Brush", "Film Tape", "Fish", "Flag", "Flame", "Flash", "Flower", "Hammer", "Headphones", "Heart", "Home", "Moon", "Note", "Pen", "Pin", "Plane", "Puzzle", "Rocket", "Spark", "Star", "Sun", "Swoosh", "Sword", "Ticket", "Tree", "Umbrella", "Wand", "Wizard Hat", "Sketching", "Inking", "Painting", "Airbrushing", "Charcoals", "Textures")++ // the Copy & Paste panel+ val CopyOne by lazy { shape("copyone", 50f, "M15.7 39.2C5.8 38.3 -0.3 28.3 3.5 19.2C5.4 14.7 9.6 11.4 14.7 10.6C15.5 10.4 32.9 10.4 34.4 10.5C43.6 11.3 49.7 20.4 46.9 29.2C45.2 34.7 40.3 38.6 34.5 39.2C33.9 39.2 16.3 39.3 15.7 39.2zM25.7 32.2C26 32 26.3 31.6 26.4 31.3C26.5 31.2 26.5 30.3 26.5 28.7L26.5 26.4L29 26.4C31.3 26.3 31.4 26.3 31.7 26.2C32.8 25.6 32.8 24.1 31.7 23.5C31.4 23.3 31.3 23.3 29 23.3L26.5 23.3L26.5 21C26.5 18.4 26.5 18.3 26.1 17.9C25.4 17 23.9 17.3 23.6 18.4C23.5 18.5 23.5 19.4 23.5 21L23.5 23.3L21 23.3C18.7 23.3 18.6 23.3 18.3 23.5C17.2 24.1 17.2 25.6 18.3 26.2C18.6 26.3 18.7 26.3 21 26.4L23.5 26.4L23.5 28.7C23.5 31.3 23.5 31.4 23.8 31.8C24.3 32.4 25.1 32.5 25.7 32.2z") }+ val CopyAll by lazy { shape("copyall", 50f, "M15.7 39.2C5.8 38.3 -0.3 28.3 3.5 19.2C5.4 14.7 9.6 11.4 14.7 10.6C15.5 10.4 32.9 10.4 34.4 10.5C43.6 11.3 49.7 20.4 46.9 29.2C45.2 34.7 40.3 38.6 34.5 39.2C33.9 39.2 16.3 39.3 15.7 39.2zM34.4 37.2C42.3 36.4 47.5 28.5 45 21C43.5 16.3 39.3 13 34.4 12.5C33.5 12.4 16.5 12.4 15.6 12.5C7.7 13.3 2.5 21.1 5 28.7C6.5 33.3 10.7 36.7 15.5 37.2C16.3 37.3 33.6 37.3 34.4 37.2zM15.6 35.2C8.9 34.3 4.8 27.7 7 21.4C8.2 17.8 11.3 15.3 15.2 14.6C16.1 14.4 34.1 14.4 34.9 14.6C39.3 15.4 42.6 18.6 43.5 23C43.7 23.9 43.6 25.9 43.5 26.8C42.6 31.1 39.4 34.2 35.1 35.1C34.5 35.2 16.4 35.3 15.6 35.2zM25.7 32.2C26 32 26.3 31.6 26.4 31.3C26.5 31.2 26.5 30.3 26.5 28.7L26.5 26.4L29 26.4C31.3 26.3 31.4 26.3 31.7 26.2C32.8 25.6 32.8 24.1 31.7 23.5C31.4 23.3 31.3 23.3 29 23.3L26.5 23.3L26.5 21C26.5 18.4 26.5 18.3 26.1 17.9C25.4 17 23.9 17.3 23.6 18.4C23.5 18.5 23.5 19.4 23.5 21L23.5 23.3L21 23.3C18.7 23.3 18.6 23.3 18.3 23.5C17.2 24.1 17.2 25.6 18.3 26.2C18.6 26.3 18.7 26.3 21 26.4L23.5 26.4L23.5 28.7C23.5 31.3 23.5 31.4 23.8 31.8C24.3 32.4 25.1 32.5 25.7 32.2z") }+ val CutPaste by lazy { shape("cutpaste", 50f, "M16.3 40.2C15.5 39.8 15.5 38.8 16.2 38.4C16.5 38.3 18.8 38.3 19.1 38.4C19.8 38.8 19.8 39.8 19.1 40.2C18.8 40.3 16.7 40.4 16.3 40.2zM28.6 40.1C28 39.9 27.4 39.3 27.2 38.7C27.1 38.4 27.1 37.5 27.1 26.2C27.2 12.5 27.1 13.8 27.8 13.1C28.5 12.4 28.2 12.4 33.7 12.4C39.1 12.4 39 12.4 39.6 13.1C40.3 13.8 40.2 12.5 40.2 26.3C40.2 40.1 40.3 38.8 39.6 39.5C38.9 40.2 39.2 40.2 33.8 40.2C29.2 40.2 28.9 40.2 28.6 40.1zM22.2 40C21.4 39.6 21.5 38.7 22.3 38.3C22.7 38.1 22.9 37.8 23.1 37.5C23.6 36.5 25 36.8 25 37.9C25 38.6 23.9 39.8 23 40.1C22.6 40.2 22.5 40.2 22.2 40zM12.4 39.7C11.6 39.4 10.7 37.4 11.2 36.5C11.6 35.6 12.9 35.9 13 36.9C13.1 37.1 13.1 37.3 13.1 37.4C13.1 37.5 13.3 37.8 13.4 38C14.2 38.9 13.5 40 12.4 39.7zM23.7 34.7C23.2 34.5 23.2 34.3 23.2 32.8C23.2 31.5 23.2 31.5 23.3 31.3C23.8 30.7 24.8 30.8 25 31.4C25.2 31.9 25.2 34 25 34.3C24.7 34.8 24.1 34.9 23.7 34.7zM11.6 33.8C11.1 33.6 11.1 33.4 11.1 32C11.1 31 11.1 30.7 11.2 30.5C11.5 29.8 12.5 29.8 12.9 30.5C13.1 30.8 13.1 33.1 12.9 33.4C12.6 33.9 12 34.1 11.6 33.8zM23.7 28.7C23.2 28.5 23.2 28.3 23.2 26.8C23.2 25.5 23.2 25.5 23.3 25.3C23.8 24.7 24.8 24.8 25 25.4C25.2 25.9 25.2 28 25 28.3C24.7 28.8 24.1 28.9 23.7 28.7zM11.6 27.8C11.1 27.6 11.1 27.4 11.1 26C11.1 25 11.1 24.7 11.2 24.5C11.5 23.8 12.5 23.8 12.9 24.5C13.1 24.8 13.1 27.1 12.9 27.4C12.6 27.9 12 28.1 11.6 27.8zM23.7 22.7C23.2 22.5 23.2 22.3 23.2 20.8C23.2 19.5 23.2 19.5 23.3 19.3C23.8 18.7 24.8 18.8 25 19.4C25.2 19.9 25.2 22 25 22.3C24.7 22.8 24.1 22.9 23.7 22.7zM11.6 21.8C11.1 21.6 11.1 21.4 11.1 20C11.1 19 11.1 18.7 11.2 18.5C11.5 17.8 12.5 17.8 12.9 18.5C13.1 18.8 13.1 21.1 12.9 21.4C12.6 21.9 12 22.1 11.6 21.8zM23.7 16.7C23.4 16.6 23.2 16.3 23.1 15.7C23.1 15.1 23 15 22.7 14.6C22 13.9 22.3 13 23.1 12.8C24.3 12.6 25.7 15.2 25 16.3C24.7 16.8 24.1 16.9 23.7 16.7zM11.7 15.9C11.5 15.8 11.3 15.5 11.2 15.3C10.9 14.3 12.3 12.5 13.4 12.6C14.4 12.6 14.7 13.8 13.9 14.4C13.4 14.7 13.3 14.8 13.1 15.1C12.8 15.8 12.3 16.1 11.7 15.9zM17 14.3C16.3 14 16.2 13 16.8 12.6C17.2 12.3 19.6 12.3 20 12.6C20.5 13 20.5 13.9 19.9 14.2C19.6 14.4 17.5 14.4 17 14.3z") }+ val PasteDown by lazy { shape("pastedown", 50f, "M15.7 39.2C5.8 38.3 -0.3 28.3 3.5 19.2C5.4 14.7 9.6 11.4 14.7 10.6C15.5 10.4 32.9 10.4 34.4 10.5C43.6 11.3 49.7 20.4 46.9 29.2C45.2 34.7 40.3 38.6 34.5 39.2C33.9 39.2 16.3 39.3 15.7 39.2zM31.6 25.6L38.1 19.1L25 19.1L11.9 19.1L18.4 25.6C22 29.1 25 32.1 25 32.1C25 32.1 28 29.1 31.6 25.6z") }+ // the gesture controls rail (smudge, erase, layers, copy and paste use the tools' own)+ val GestureAssisted by lazy { shape("gestureassisted", 50f, "M25 37.4C24.5 37.3 15.1 31.7 14.8 31.4C14.6 31.2 14.4 30.9 14.3 30.6C14 30.2 14 30.2 14 24.5C14 18.8 14 18.8 14.3 18.4C14.4 18.1 14.6 17.8 14.8 17.6C15.1 17.3 24.5 11.7 25 11.6C25.9 11.3 26.5 11.4 28 12.3C37.7 18.1 36.9 17.6 37.3 18.4C37.6 19.1 37.6 29.9 37.3 30.6C36.9 31.4 37.7 30.9 28 36.7C26.5 37.6 25.9 37.7 25 37.4zM26.5 36.4C27 36.1 27 36.1 27 34.3C27.2 29.1 27.2 28 27.2 26.8L27.2 25.5L29.3 24.2C34.1 21.4 36.6 19.9 36.8 19.6C37.2 19 36.8 18.1 36 18C35.8 18 35.7 18 33.9 19.1C29.3 21.8 28.2 22.4 27.1 23.1C26.1 23.7 26 23.8 25.9 23.7C25.8 23.7 24.4 22.8 22.7 21.8C18.1 19 16.5 18.1 16.1 18C15.3 17.9 14.7 18.9 15.2 19.6C15.3 19.7 16 20.2 16.8 20.7C17.7 21.2 19.2 22.1 20.3 22.8C21.4 23.5 23 24.4 23.8 24.9L25.2 25.7L25.1 26.4C25 31.6 25 35.7 25.1 36.1C25.3 36.6 25.9 36.7 26.5 36.4z") }+ val GestureEyedropper by lazy { shape("gestureeyedropper", 50f, "M23.8 36.9C15.4 35.7 10.6 26.7 14.2 19.2C18 11.3 28.2 9.6 34.4 15.7C40.4 21.8 38.7 32.1 30.9 35.8C28.8 36.8 26 37.2 23.8 36.9zM27.6 33.3C31.3 32.3 33.8 29.5 34.4 25.9C35.4 19.6 29.5 14.2 23.3 15.8C17.7 17.2 14.9 23.4 17.5 28.5C18.6 30.8 20.8 32.6 23.2 33.2C24.5 33.6 26.4 33.6 27.6 33.3zM25 26L25 25L24 25L23 25L23 24.5L23 24L24 24L25 24L25 23L25 22L25.5 22L26 22L26 23L26 24L27 24L28 24L28 24.5L28 25L27 25L26 25L26 26L26 27L25.5 27L25 27L25 26z") }+ val GestureQuickShape by lazy { shape("gesturequickshape", 50f, "M21.2 36.7C21 36.5 20.9 36.3 20.9 36.1C20.9 35.8 24 30 24.3 29.7C24.7 29.3 25.3 29.3 25.7 29.7C25.8 29.8 29 35.6 29.1 35.9C29.2 36.1 29.1 36.5 28.9 36.6C28.6 36.8 21.5 36.8 21.2 36.7zM18.6 35.2C17.7 34.8 16 33.1 15 31.7C11 25.6 13.2 17.4 19.8 14.2C25.2 11.6 31.7 13.4 35 18.4C38.4 23.5 37.4 30.3 32.7 34.2C31 35.6 30.7 35.6 29.9 34.1C29.2 32.9 29.2 32.7 30 32.1C33.9 29.4 34.8 24 32.2 20.1C29 15.5 22.5 15 18.7 19C15.1 22.9 15.7 28.9 19.9 32C20.8 32.7 20.8 32.9 20.2 34C19.6 35.2 19.3 35.4 18.6 35.2z") }+ val GestureQuickMenu by lazy { shape("gesturequickmenu", 50f, "M18.6 32.9C18.1 32.6 18 32.5 18 31C18 29.5 18.1 29.3 18.6 29.1C18.9 28.9 30.1 28.9 30.4 29.1C30.9 29.3 31 29.5 31 31C31 32.5 30.9 32.7 30.4 32.9C30.1 33.1 18.9 33.1 18.6 32.9zM5.6 28.9C5.1 28.6 5 28.5 5 27C5 25.5 5.1 25.3 5.6 25.1C5.9 24.9 16.1 24.9 16.4 25.1C16.9 25.3 17 25.5 17 27C17 28.5 16.9 28.7 16.4 28.9C16.1 29.1 5.9 29.1 5.6 28.9zM32.6 28.9C32.1 28.6 32 28.5 32 27C32 25.5 32.1 25.3 32.6 25.1C32.9 24.9 43.1 24.9 43.4 25.1C43.9 25.3 44 25.5 44 27C44 28.5 43.9 28.7 43.4 28.9C43.1 29.1 32.9 29.1 32.6 28.9zM5.6 23.9C5.1 23.6 5 23.5 5 22C5 20.5 5.1 20.3 5.6 20.1C5.9 19.9 16.1 19.9 16.4 20.1C16.9 20.3 17 20.5 17 22C17 23.5 16.9 23.7 16.4 23.9C16.1 24.1 5.9 24.1 5.6 23.9zM32.6 23.9C32.1 23.6 32 23.5 32 22C32 20.5 32.1 20.3 32.6 20.1C32.9 19.9 43.1 19.9 43.4 20.1C43.9 20.3 44 20.5 44 22C44 23.5 43.9 23.7 43.4 23.9C43.1 24.1 32.9 24.1 32.6 23.9zM18.6 19.9C18.1 19.6 18 19.5 18 18C18 16.5 18.1 16.3 18.6 16.1C18.9 15.9 30.1 15.9 30.4 16.1C30.9 16.3 31 16.5 31 18C31 19.5 30.9 19.7 30.4 19.9C30.1 20.1 18.9 20.1 18.6 19.9z") }+ val GestureFullScreen by lazy { shape("gesturefullscreen", 50f, "M13.4 36.9C11.9 36.5 10.7 35.4 10.2 33.8C9.9 33.2 9.9 15.8 10.2 15.2C10.7 13.6 11.9 12.4 13.5 12.1C14.2 11.9 35.8 11.9 36.5 12.1C38.1 12.4 39.3 13.6 39.8 15.2C40.1 15.8 40.1 33.2 39.8 33.8C39.3 35.4 38.1 36.6 36.5 36.9C35.8 37.1 14.1 37 13.4 36.9zM15.7 33.8C15.9 33.7 16.2 33.4 16.4 33.1C16.5 32.9 16.5 32.7 16.5 27.5C16.5 21.5 16.5 21.9 16.1 21.5C15.5 20.9 14.5 20.9 13.9 21.5C13.5 21.9 13.5 21.5 13.5 27.5C13.5 32.7 13.5 32.9 13.6 33.1C14.1 33.9 14.9 34.2 15.7 33.8zM35.7 17.8C36.2 17.5 36.5 17.1 36.5 16.5C36.5 15.9 36.2 15.5 35.7 15.2C35.4 15 35.4 15 25 15C14.6 15 14.6 15 14.3 15.2C13.1 15.8 13.3 17.5 14.6 17.9C14.7 18 19.4 18 25.1 18C35.4 18 35.4 18 35.7 17.8z") }+ val GestureClearLayer by lazy { shape("gestureclearlayer", 50f, "M9 24.5L9 13L24.5 13L40 13L40 24.5L40 36L24.5 36L9 36L9 24.5zM24.2 30.4C24.8 30.1 32.4 22.5 32.7 21.9C33.4 20.6 32.4 19 30.9 19C30.1 19 30.2 18.9 26.4 22.7L23 26.2L21.6 24.7C20 23.1 19.8 23 19.1 23C17.8 23 16.6 24.6 17.1 25.8C17.3 26.2 21.5 30.1 22.2 30.4C22.8 30.8 23.6 30.8 24.2 30.4z") }+ val GestureLayerSelect by lazy { shape("gesturelayerselect", 50f, "M17.4 37C16.9 36.9 16.5 36.6 16.2 36.1C16 35.8 16 35.8 16 33.7C16 31.3 16 31.1 16.5 30.6C17 30 16 30.1 27.5 30.1C39 30.1 38 30 38.5 30.6C39 31.1 39 31.3 39 33.7C39 36.2 38.9 36.5 37.9 36.9C37.6 37 18 37.1 17.4 37zM17.2 27.9C16.7 27.8 16.2 27.3 16.1 26.8C16 26.3 16 22.7 16.1 22.2C16.2 21.7 16.7 21.2 17.2 21.1C17.7 20.9 37.3 20.9 37.8 21.1C38.3 21.2 38.8 21.7 38.9 22.2C39 22.7 39 26.3 38.9 26.8C38.8 27.3 38.3 27.8 37.8 27.9C37.3 28 17.6 28 17.2 27.9zM11.2 18.9C10.7 18.8 10.2 18.3 10.1 17.8C10 17.3 10 13.7 10.1 13.2C10.2 12.7 10.7 12.2 11.2 12.1C11.7 11.9 37.3 11.9 37.8 12.1C38.3 12.2 38.8 12.7 38.9 13.2C39 13.7 39 17.3 38.9 17.8C38.8 18.3 38.3 18.8 37.8 18.9C37.3 19 11.6 19 11.2 18.9z") }+ val GestureHover by lazy { shape("gesturehover", 40f, "M19.1 32.7C17.2 32.6 14.6 31.2 14.8 30.5C14.9 30 15.3 30 15.9 30.5C18.4 32.2 21.7 32.2 24.2 30.4C24.6 30.1 24.8 30.1 25 30.2C25.4 30.6 25.3 30.8 24.7 31.3C23.3 32.4 21.1 33 19.1 32.7zM19.3 29.5C18.1 29.3 16.7 28.6 16.7 28.1C16.7 27.6 17.1 27.5 17.6 27.8C19 28.9 20.9 28.9 22.4 27.9C22.8 27.6 22.9 27.6 23.1 27.8C23.6 28.1 23 28.8 21.7 29.3C20.8 29.5 20.1 29.6 19.3 29.5zM19.6 25.9C19.3 25.7 19.1 25.4 19 25C19 24.9 18.6 23.1 18.1 21.1C17.6 18.6 17.4 17.4 17.4 17.4C17.4 17.3 17.7 17.3 18 17.2C19.1 17.1 22.3 17.2 22.6 17.4C22.7 17.4 21 25.3 20.8 25.5C20.5 25.9 20 26 19.6 25.9zM17 16.1C17 16 16.7 14.5 16.3 12.6C15.4 8.4 15.3 8.5 16.5 8C18.6 7 21.4 7 23.5 8C24.7 8.5 24.7 8.4 23.7 12.7C23.3 14.6 22.9 16.1 22.9 16.2C22.9 16.2 22.7 16.1 22.4 16.1C20.9 15.8 18.4 15.9 17.2 16.2C17.1 16.2 17.1 16.2 17 16.1z") }+ val GestureGeneral by lazy { shape("gesturegeneral", 50f, "M22.8 36.9C22.4 36.8 22.1 36.8 22.1 36.8C22.1 36.8 22 36 21.9 35.2C21.8 34.3 21.7 33.5 21.7 33.5C21.7 33.5 21.4 33.3 21.1 33.2C20.1 32.8 19 32.2 18.4 31.6C18.1 31.4 18.3 31.3 16.6 32.1C14.9 32.9 15.1 32.9 14.5 32C13.7 30.9 12.6 28.8 12.7 28.5C12.7 28.5 13.3 28 14.1 27.5C14.9 26.9 15.4 26.6 15.3 26.5C15.1 25.8 15.1 23.4 15.3 22.6C15.4 22.5 15 22.2 14.1 21.5C13.3 21 12.7 20.5 12.7 20.5C12.6 20.1 14.8 16.2 15.2 16.3C15.2 16.3 15.9 16.6 16.7 17L18.1 17.6L18.5 17.3C19.3 16.6 20.5 16 21.4 15.7C21.6 15.6 21.8 15.5 21.8 15.4C21.8 15 22.1 12.3 22.1 12.2C22.6 12 26.4 12 26.9 12.2C26.9 12.3 27 12.8 27.1 13.9C27.2 14.8 27.3 15.5 27.3 15.6C27.4 15.6 27.6 15.7 27.8 15.7C28.7 16.1 29.7 16.7 30.5 17.3L30.9 17.6L32.1 17.1C32.7 16.8 33.4 16.5 33.6 16.4C33.9 16.3 33.9 16.3 34.3 16.8C35.1 17.7 35.8 19 36.2 20.1C36.4 20.5 36.4 20.5 35.1 21.4C34.4 21.9 33.8 22.4 33.7 22.4C33.7 22.4 33.7 22.7 33.8 23.1C33.9 23.9 33.9 25.1 33.8 25.7C33.7 26.7 33.5 26.5 35 27.6C36.5 28.7 36.5 28.5 35.8 29.9C35.3 30.8 34.4 32.4 34 32.7C33.9 32.7 33.6 32.6 32.4 32.1C31.6 31.7 30.9 31.4 30.9 31.4C30.9 31.4 30.7 31.6 30.5 31.7C29.7 32.4 28.7 32.9 27.8 33.3C27.6 33.4 27.3 33.5 27.3 33.5C27.3 33.5 27.2 34.2 27.1 35.1C27 36 26.9 36.8 26.9 36.8C26.7 37 23.9 37.1 22.8 36.9zM25.6 30.3C30.8 29.3 32.2 22.6 27.8 19.6C23.9 16.9 18.6 19.8 18.6 24.5C18.6 28.2 22 31.1 25.6 30.3z") }+ val Person by lazy { solid("person", "M12 4a4 4 0 1 1 0 8a4 4 0 1 1 0-8z", "M4.5 21c0-4.2 3.4-7 7.5-7s7.5 2.8 7.5 7z") }+ val ModeDisc by lazy { shape("modedisc", 36f, "M16.8 27.8C12.5 27.2 9.2 24.2 8.3 20C8.1 19 8.1 17 8.3 16C9.2 12.1 12.1 9.2 16 8.3C17 8.1 19 8.1 20 8.3C23.9 9.2 26.8 12.1 27.7 16C27.9 17 27.9 19 27.7 20C26.8 23.9 24 26.7 20.1 27.7C19.5 27.8 17.4 27.9 16.8 27.8zM18.8 25.1C24.2 24.5 27 18.1 23.7 13.8C20.6 9.6 14.1 10.1 11.7 14.7C9.1 19.8 13.2 25.7 18.8 25.1z") }+ val ModeClassic by lazy { shape("modeclassic", 36f, "M13.4 26.1C11.8 25.8 10.5 24.7 10 23.1C9.8 22.4 9.8 13.6 10 12.9C10.4 11.5 11.6 10.4 13.1 10C13.6 9.9 22.4 9.9 22.9 10C24.4 10.4 25.6 11.5 26 12.9C26.1 13.3 26.1 13.7 26.1 18C26.1 22.3 26.1 22.7 26 23.1C25.6 24.5 24.5 25.5 23 26C22.7 26.1 14.2 26.2 13.4 26.1z") }+ val ModeHarmony by lazy { shape("modeharmony", 36f, "M10.6 27.6C9.6 27.3 9.2 26.1 9.6 25.3C9.8 24.9 12.4 21.3 12.6 21.1C13.8 19.9 15.9 21.2 15.3 22.8C15.1 23.2 12.3 27.1 12 27.3C11.6 27.6 11.1 27.7 10.6 27.6zM16.7 19C16.2 18.8 16 18.6 13.4 14.8C10.3 10.3 10.4 10.6 10.4 10C10.4 8.9 11.4 8.2 12.4 8.5C13 8.6 13.1 8.7 15.6 12.4L18 15.8L22.6 15.9C27.2 15.9 27.2 15.9 27.5 16C28.7 16.7 28.6 18.4 27.4 18.9C27.1 19.1 27.1 19.1 22 19.1C18 19.1 16.9 19 16.7 19z") }+ val ModeValue by lazy { shape("modevalue", 36f, "M15.3 24.7C14.6 24.5 14 24.1 13.6 23.4L13.4 23L11.1 23C8.8 23 8.8 23 8.6 22.8C8.1 22.5 8 21.9 8.3 21.4C8.6 21 8.6 21 11.1 21C13.4 21 13.4 21 13.6 20.6C14.1 19.7 14.9 19.2 16 19.2C17.2 19.2 18 19.7 18.5 20.6L18.7 21L22.9 21C27.6 21 27.4 21 27.7 21.4C28 21.9 27.9 22.5 27.4 22.8C27.2 23 27.2 23 23 23L18.7 23L18.5 23.4C17.8 24.5 16.5 25.1 15.3 24.7zM19 17.3C18.3 17.1 17.6 16.6 17.2 15.9C17 15.6 17 15.6 12.9 15.5C8.9 15.5 8.8 15.5 8.6 15.4C7.9 15 8 14 8.7 13.6C9 13.5 9 13.5 13 13.5C17 13.5 17 13.5 17.2 13.2C18.1 11.3 21.1 11.3 22.1 13.2C22.3 13.5 22.3 13.5 24.7 13.5C27 13.5 27 13.5 27.3 13.6C28 14 28.1 15 27.4 15.4C27.2 15.5 27 15.5 24.7 15.5C22.3 15.6 22.3 15.6 22.1 15.9C21.5 17 20.2 17.5 19 17.3z") }+ val ModePalettes by lazy { shape("modepalettes", 36f, "M8.9 24.3C8.6 24.2 8.3 23.8 8.2 23.5C8.1 23.4 8.1 22.6 8.1 21.4C8.2 19.2 8.2 19.1 8.8 18.8C9.2 18.5 12.7 18.5 13.2 18.7C13.9 19.1 14 19.4 13.9 21.7C13.9 23.8 13.8 24 13.1 24.3C12.8 24.4 9.2 24.4 8.9 24.3zM15.8 24.2C15.1 23.9 15 23.5 15.1 21.2C15.1 19.3 15.2 19.1 15.9 18.7C16.2 18.5 19.8 18.5 20.2 18.7C20.9 19.1 20.9 19.2 20.9 21.5C20.9 23.7 20.9 23.8 20.3 24.2C19.9 24.4 16.3 24.5 15.8 24.2zM22.9 24.3C22.2 24 22.1 23.7 22.1 21.7C22 19.4 22.1 19.1 22.8 18.7C23.3 18.5 26.8 18.5 27.2 18.8C27.8 19.1 27.8 19.2 27.8 21.5C27.8 23.8 27.8 23.8 27.3 24.2C27 24.3 27 24.3 25.1 24.4C23.4 24.4 23.1 24.4 22.9 24.3zM9.1 17.4C8.8 17.3 8.4 17 8.3 16.7C8.1 16.4 8 12.8 8.2 12.4C8.3 12.1 8.7 11.8 9 11.7C9.3 11.6 12.7 11.6 13 11.7C13.8 12 13.9 12.2 13.9 14.3C14 16.2 13.9 16.5 13.6 16.9C13.2 17.4 13.1 17.4 11.1 17.4C10.1 17.4 9.2 17.4 9.1 17.4zM16.1 17.4C15.7 17.2 15.4 17 15.2 16.6C15.1 16.4 15.1 16.2 15.1 14.5C15.1 11.6 15.2 11.6 18 11.6C20 11.6 20.4 11.7 20.7 12.3C20.9 12.6 20.9 12.6 20.9 14.5C20.9 16.8 20.9 16.9 20.1 17.3C19.9 17.4 16.5 17.5 16.1 17.4zM23 17.4C22.1 17 22 16.7 22.1 14.3C22.1 12.4 22.1 12.3 22.5 12C22.9 11.6 22.9 11.6 24.9 11.6C27 11.6 27.1 11.6 27.5 12C27.9 12.4 27.9 12.5 27.9 14.6C27.8 16.8 27.8 16.9 27.2 17.2C26.9 17.4 26.9 17.4 25.1 17.4C23.7 17.4 23.2 17.4 23 17.4z") }+ /** A brush sweeping, with two specks: clearing something away. */+ val Sweep by lazy { shape("sweep", 41f, 40f, "M18.1 29C18 28.9 18 28.9 18 28.8C18.2 28.2 18 28 17.1 28C16.3 28 15.9 27.8 15.6 27.2C15.4 26.8 15.5 26.7 16.4 25.2C16.9 24.5 17.3 23.9 17.3 23.9C17.3 23.9 16.7 24.3 16 24.8C14.2 26 14.3 26 13.2 24.4C12.4 23.2 12.3 23 12.4 22.7C12.5 22.5 12.5 22.5 12.3 22.6C12 22.7 12 22.7 11.3 22.4C10.1 21.8 10.2 21.7 11.9 20.5C12.7 20 14.1 19 15.1 18.2C17.1 16.7 17.2 16.7 17.7 16.9C17.9 17 23.2 22.3 23.2 22.5C23.4 23.1 23.5 23 21.8 25.2C20.6 26.9 20.3 27.2 19.4 28.1C18.3 29.2 18.3 29.2 18.1 29zM24.8 29C24 28.8 23.5 27.9 23.7 27.1C24.1 25.7 26 25.5 26.6 26.8C27.2 28 26 29.4 24.8 29zM28.3 26.8C27.6 26.3 27.7 25.4 28.4 25C29.6 24.4 30.5 26.1 29.4 26.8C29.1 27 28.6 27 28.3 26.8zM22.3 18.3C21.8 17.7 21.4 17.2 21.4 17.2C21.4 17.2 22.9 15.9 24.6 14.3C29.6 9.9 30.3 9.5 31.2 10.4C31.7 11 31.6 11.4 30.6 12.7C30 13.5 29.8 13.7 26.8 16.3C25.1 17.8 23.6 19.1 23.5 19.2C23.3 19.4 23.3 19.4 22.3 18.3z") }+ val More by lazy { solid("more", "M4 10.3a1.7 1.7 0 1 0 0 3.4a1.7 1.7 0 1 0 0-3.4z", "M12 10.3a1.7 1.7 0 1 0 0 3.4a1.7 1.7 0 1 0 0-3.4z", "M20 10.3a1.7 1.7 0 1 0 0 3.4a1.7 1.7 0 1 0 0-3.4z") }+ val CardCompact by lazy { shape("cardcompact", 21f, 32f, "M2.8 22.6C2.4 22.5 2.1 22.3 1.8 21.9C1.4 21.4 1.4 21.5 1.4 15.9C1.4 10.1 1.4 10.5 1.9 9.9C2.6 9.2 1.9 9.3 10.5 9.3C19.1 9.3 18.4 9.2 19.1 9.9C19.6 10.5 19.6 10.1 19.6 16C19.6 21.9 19.6 21.5 19.1 22.1C18.4 22.8 19.1 22.7 10.6 22.7C3.5 22.7 3.1 22.7 2.8 22.6zM17.4 13.7C17.8 13.5 17.9 13.3 17.9 12.4C17.9 11.5 17.9 11.5 17.6 11.2C17.3 10.9 17.6 10.9 10.2 10.9C3.7 11 3.7 11 3.5 11.1C3.1 11.4 3.1 11.5 3.1 12.4C3.1 13.3 3.2 13.5 3.6 13.7C3.9 13.9 17.1 13.9 17.4 13.7z") }+ val CardStack by lazy { shape("cardstack", 21f, 32f, "M4.5 23.6C3.9 23.5 3.5 23.1 3.2 22.7C3 22.3 0.4 12.8 0.4 12.2C0.4 11.6 0.9 10.8 1.4 10.5C1.6 10.4 4.1 9.8 4.2 9.7C4.3 9.7 4.3 12.1 4.3 15.1C4.2 21.3 4.2 21.1 5 21.9C5.6 22.6 6.1 22.8 7.3 22.8L8.3 22.8L6.8 23.2C5.2 23.7 4.9 23.7 4.5 23.6zM6.3 21.9C5.9 21.8 5.4 21.3 5.2 20.9C5.1 20.5 5.1 20.5 5.1 15.2C5.1 9.1 5.1 9.5 5.7 8.9C6.3 8.3 5.9 8.3 12.3 8.3C18.9 8.3 18.5 8.3 19.1 9C19.6 9.6 19.6 9.2 19.6 15C19.6 20.9 19.6 20.9 19 21.5C18.4 22 18.8 22 12.3 22C7.4 22 6.6 22 6.3 21.9zM17.7 20.1C17.9 19.9 17.9 19.9 17.9 19.1C17.9 18.2 17.9 17.9 17.5 17.7C17.3 17.6 17 17.6 12.3 17.6C6.2 17.6 6.8 17.5 6.8 19C6.8 19.7 6.8 19.8 6.9 20C7.1 20.4 6.9 20.4 12.4 20.4C17.4 20.3 17.4 20.3 17.7 20.1z") }+ val TabAdd by lazy { shape("tabadd", 50f, "M21.7 34.9C20.4 34.7 19.2 33.7 18.8 32.3C18.6 31.8 18.6 21.8 18.7 21.1C19 19.9 20 18.9 21.2 18.5C21.7 18.3 21.7 18.3 26.9 18.3C32.7 18.3 32.5 18.3 33.4 18.7C34.2 19.1 34.9 20 35.2 20.9C35.3 21.4 35.3 21.4 35.3 26.6C35.3 30.8 35.3 31.8 35.3 32.1C34.9 33.4 34 34.4 32.8 34.8C32.3 35 32.3 35 27.2 35C24.4 35 21.9 35 21.7 34.9zM27.5 31.5C27.6 31.3 27.6 31.3 27.6 29.3L27.6 27.2L29.7 27.2C31.7 27.2 31.7 27.2 31.9 27.1C32.1 26.9 32.1 26.5 31.9 26.2C31.8 26 31.8 26 29.7 26L27.6 26L27.6 23.9C27.6 21.9 27.6 21.9 27.4 21.7C27.2 21.5 26.8 21.5 26.6 21.7C26.4 21.9 26.4 21.9 26.4 24L26.4 26L24.4 26C23.3 26 22.4 26 22.3 26.1C21.9 26.2 21.8 26.8 22.1 27.1C22.3 27.2 22.3 27.2 24.3 27.2L26.4 27.2L26.4 29.3C26.4 31.2 26.4 31.3 26.5 31.5C26.8 31.8 27.2 31.8 27.5 31.5zM17 30.7C15.8 30.1 14.8 28.8 14.5 27.4C14.3 26.6 14.3 19.3 14.5 18.5C14.9 16.7 16.3 15.3 18.2 14.8C18.7 14.6 26.1 14.6 26.9 14.7C28.2 15 29.2 15.6 30 16.6L30.3 17L25.8 17C20.8 17 21 17 20 17.5C19.1 18 18.3 18.7 17.9 19.7C17.4 20.7 17.4 20.3 17.4 25.9C17.3 30.9 17.3 30.9 17 30.7z") }+ val TabCanvas by lazy { shape("tabcanvas", 50f, "M14.7 33.6C13.3 33.4 12.1 32.3 11.8 30.9C11.7 30.3 11.7 17.7 11.8 17.2C12.1 16 13.2 14.9 14.4 14.6C14.9 14.5 35.4 14.4 36 14.6C37.1 14.8 38.1 15.7 38.6 17C38.8 17.5 38.8 30 38.7 30.8C38.4 32.2 37.3 33.3 36 33.6C35.6 33.7 15.2 33.7 14.7 33.6zM28.6 30.6C29.4 30.4 30 29.9 30.3 29.2C30.6 28.5 30.6 28.3 30.6 25.8C30.6 23.6 30.6 23.6 30.4 23.3C30 22.8 29.2 22.8 28.8 23.4C28.7 23.6 28.7 23.7 28.6 25.9C28.6 28.5 28.6 28.5 28.1 28.7C27.8 28.8 27.2 28.8 27 28.6C26.5 28.3 26.5 28.6 26.5 24.4C26.5 20.8 26.5 20.7 26.3 20.4C25.9 19.1 24.9 18.5 23.5 18.5C22 18.5 21 19.3 20.6 20.7C20.4 21.4 20.5 25.1 20.7 25.4C21.1 26 22 25.9 22.4 25.3C22.5 25 22.5 24.9 22.5 23.1C22.5 21 22.5 20.8 22.9 20.6C23.2 20.5 23.8 20.4 24.1 20.6C24.5 20.7 24.5 20.7 24.5 24.6C24.5 28.4 24.5 28.6 24.9 29.3C25.6 30.5 27.1 31.1 28.6 30.6z") }+ val TabShare by lazy { shape("tabshare", 50f, "M18.8 34.2C17.5 34 16.4 33 16.1 31.6C16 31 16 20.7 16.1 20C16.3 18.9 17.1 18 18.3 17.6C18.7 17.4 18.8 17.4 20.8 17.4L22.8 17.4L22.8 21.4C22.8 25.4 22.8 25.4 23 25.8C23.6 27.3 25.7 27.7 26.9 26.5C27.6 25.9 27.5 26.1 27.6 21.5L27.6 17.4L29.4 17.4C31.5 17.4 31.8 17.4 32.5 17.8C33.4 18.2 34 18.9 34.3 19.8C34.4 20.4 34.4 31.3 34.3 31.8C34 32.9 33.1 33.8 32 34.2C31.6 34.3 19.6 34.4 18.8 34.2zM24.9 25.5C24.7 25.4 24.7 25.4 24.7 18.4L24.7 11.4L23.1 12.9C22.1 13.9 21.5 14.5 21.4 14.5C20.9 14.6 20.5 14.2 20.6 13.7C20.7 13.6 21.4 12.8 22.8 11.4C24.9 9.3 24.9 9.3 25.2 9.3C25.5 9.3 25.5 9.3 27.6 11.5C30 13.8 29.9 13.8 29.7 14.2C29.6 14.4 29.4 14.5 29.1 14.5C28.9 14.5 28.8 14.4 27.3 12.9L25.7 11.3L25.7 18.3C25.7 25.4 25.7 25.4 25.5 25.5C25.3 25.7 25.1 25.7 24.9 25.5z") }+ val TabVideo by lazy { shape("tabvideo", 50f, "M18.4 34.2C18 34.1 17.6 33.8 17.3 33.5C17.1 33 17 15.6 17.3 15C17.6 14.5 17.9 14.3 18.5 14.3C19 14.3 19 14.3 26.9 18.5C35.8 23.3 35.3 23 35.5 23.2C36 23.8 36 24.8 35.4 25.4C35.3 25.5 20.7 33.3 19.3 34C19 34.2 18.7 34.2 18.4 34.2z") }+ val TabPrefs by lazy { shape("tabprefs", 50f, "M17.5 32.7C14.8 32.3 12.4 30.5 11.1 28.1C8.1 22.4 11.9 15.6 18.3 14.9C18.7 14.9 21.1 14.9 25.5 14.9C32.1 14.9 32.1 14.9 32.8 15.1C36.2 15.8 38.9 18.3 39.8 21.6C41.1 26.7 37.8 31.9 32.6 32.8C31.5 32.9 18.5 32.9 17.5 32.7zM32.7 31.2C37.4 30.2 39.9 24.9 37.8 20.6C35.3 15.6 28.4 14.9 25.1 19.4C21.7 23.8 24.2 30.2 29.8 31.3C30.4 31.4 32.1 31.4 32.7 31.2z") }+ val TabHelp by lazy { shape("tabhelp", 50f, "M24 34.2C19.6 33.8 15.8 30.5 14.8 26.1C13.1 18.8 19.6 12 27 13.4C33.2 14.7 36.9 21 35 27C33.5 31.6 28.9 34.6 24 34.2zM25.3 30C26.1 29.8 26.4 28.6 25.8 28C25 27.1 23.7 27.7 23.7 28.8C23.7 29.7 24.4 30.2 25.3 30zM25.3 26.7C25.6 26.5 25.7 26.4 25.9 25.7C26 25 26.1 24.9 27.1 23.9C28.3 22.9 28.5 22.7 28.7 22.3C29.5 21.1 29.3 19.6 28.2 18.6C26.8 17.1 23.9 17.1 22.2 18.4C20.7 19.7 20.4 21.7 21.7 21.9C22.4 22 22.7 21.8 23.1 20.9C23.6 19.6 24 19.2 25.1 19.2C26.2 19.2 27 19.9 26.9 20.9C26.8 21.4 26.5 21.8 25.7 22.6C24.2 23.9 23.8 24.5 23.8 25.6C23.8 26.6 24.5 27.1 25.3 26.7z") }+ val Tick by lazy { outline("tick", 3.2f, "M5.5 12.5l4 4 9-9") }+ val MenuTick by lazy { outline("menu-tick", 2.1f, "M5.5 12.5l4 4 9-9") }+ val BrushSet by lazy { solid("brush-set", "M3.5 18.5c3.4-6.6 8.6-10.4 17-11.5-4.4 2.2-7.6 6-9.6 11.2-2.4-.6-4.8-.4-7.4.3z") }+ val Lock by lazy { outline("lock", 1.7f, "M6 11h12v9H6z", "M8.5 11V8a3.5 3.5 0 0 1 7 0v3") }+ // the slider panel's button: save the value as a notch, or take the notch away+ val NotchAdd by lazy { outline("notch-add", 1.8f, "M12 5v14", "M5 12h14") }+ val NotchRemove by lazy { outline("notch-remove", 1.8f, "M5 12h14") }+ // a locked layer's row: a small padlock before the name, its body filled+ val LockRow by lazy { icon("lock-row", Part("M6 12.4h12v7.8H6z", 0f, true), Part("M8.25 12.4V8.6a3.75 3.75 0 0 1 7.5 0v3.8", 1.7f, false)) }+ // the dialogs a locked or hidden layer brings up: a page with a padlock on it; an eye struck through+ val PageLocked by lazy {+ icon(+ "page-locked",+ Part("M5 2.25h10.5l6.5 6.5v10a3 3 0 0 1-3 3H5a3 3 0 0 1-3-3v-13.5a3 3 0 0 1 3-3z", 1.8f, false),+ Part("M8 12.6h8v5.6H8z", 0f, true),+ Part("M9.6 12.6V10.4a2.4 2.4 0 0 1 4.8 0v2.2", 1.8f, false),+ )+ }+ val EyeStruck by lazy {+ icon(+ "eye-struck",+ Part("M1.5 12C4 7.5 7.8 5.5 12 5.5s8 2 10.5 6.5c-2.5 4.5-6.3 6.5-10.5 6.5S4 16.5 1.5 12z", 1.8f, false),+ Part("M12 8.8a3.2 3.2 0 1 1 0 6.4a3.2 3.2 0 1 1 0-6.4z", 0f, true),+ Part("M5 20.5L19 3.5", 1.8f, false),+ )+ }++ val Backspace by lazy { outline("backspace", 1.7f, "M9 6h11v12H9l-6-6z", "M12 9.5l5 5", "M17 9.5l-5 5") }+ val Link by lazy { outline("link", 1.8f, "M10 7.5H7.5a4.5 4.5 0 0 0 0 9H10", "M14 7.5h2.5a4.5 4.5 0 0 1 0 9H14", "M8.5 12h7") }++ // the single touch companion: zoom (a lens with a plus), move (arrows four ways), fit (a frame with its corners drawn in)+ val Zoom by lazy { outline("zoom", 1.8f, "M10 3.5a6.5 6.5 0 1 1 0 13a6.5 6.5 0 1 1 0-13z", "M14.8 14.8L20.5 20.5", "M7 10h6", "M10 7v6") }+ val MoveCanvas by lazy {+ outline(+ "move-canvas", 1.7f, "M12 3v18", "M3 12h18", "M9.5 5.5L12 3l2.5 2.5", "M9.5 18.5L12 21l2.5-2.5", "M5.5 9.5L3 12l2.5 2.5", "M18.5 9.5L21 12l-2.5 2.5",+ )+ }+ val FitCanvas by lazy { outline("fit-canvas", 1.7f, "M4 4h16v16H4z", "M8 8h3", "M8 8v3", "M16 16h-3", "M16 16v-3") }++ // editing the brush library+ val ShareOut by lazy { outline("share-out", 1.7f, "M8.5 9.5H6v11h12v-11h-2.5", "M12 3v11", "M8.5 6.5L12 3l3.5 3.5") }+ val Duplicate by lazy { outline("duplicate", 1.7f, "M9 9h11v11H9z", "M5.5 15.5V4.5h11", "M14.5 12v5", "M12 14.5h5") }+ val Trash by lazy { outline("trash", 1.7f, "M4.5 6.5h15", "M9.5 6.5V4h5v2.5", "M6.5 6.5l1 14h9l1-14", "M10.5 10v7", "M13.5 10v7") }+ val Folder by lazy { outline("folder", 1.6f, "M3 6.5h6l2 2h10V19H3z") }+ // the shape and grain editors' Import menu+ val SourcePhoto by lazy { outline("source-photo", 1.6f, "M4 5.5h16v13H4z", "M4 16l5-5 4 4 2.5-2.5L20 17", "M15.5 9.5a1 1 0 1 0 0-.01") }+ val SourceBooks by lazy { outline("source-books", 1.6f, "M4.5 4.5h3.5v15H4.5z", "M9.5 4.5H13v15H9.5z", "M14.5 5.5l3.3-1 3.7 14.2-3.3 1z") }+ val Clip by lazy { outline("clip", 1.7f, "M8 4v9a4 4 0 0 0 4 4h6", "M15 14l3 3-3 3") }++ // the transform toolbar: its four ways (shown 30 across) and its buttons+ val Freeform by lazy { shape("freeform", 44f, "M14.2 29.4C13.8 29.3 13.4 28.8 13.3 28.5C13.3 28.3 13.3 26.5 13.3 22.3C13.3 16.3 13.3 16.3 13.5 15.9C13.8 15.2 14.4 14.7 15.2 14.6C15.4 14.5 17.8 14.5 22.2 14.5C29.7 14.5 29.3 14.5 30 15.2C30.7 15.9 30.7 15.6 30.7 22C30.7 27.7 30.7 27.7 30.5 28C30.2 28.7 29.7 29.2 29 29.4C28.4 29.5 14.5 29.5 14.2 29.4zM29 28.1C29.5 27.7 29.5 28.1 29.5 21.9C29.5 16.5 29.5 16.5 29.3 16.3C28.9 15.7 29.5 15.7 22 15.7C15.4 15.7 15.4 15.8 15.1 15.9C14.6 16.1 14.5 16.4 14.5 17.4L14.5 18.2L17.6 18.3C21.2 18.3 21.1 18.2 21.6 18.7C22 19.1 22 19 22 23.9L22 28.3L25.4 28.2C28.7 28.2 28.7 28.2 29 28.1z") }+ val Uniform by lazy { shape("uniform", 44f, "M14.4 29.4C14 29.2 13.5 28.8 13.4 28.3C13.2 27.9 13.2 16.9 13.3 16.3C13.5 15.5 14.2 14.9 14.9 14.6C15.5 14.4 28.5 14.4 29.1 14.6C29.8 14.9 30.5 15.5 30.7 16.3C30.8 16.9 30.8 27.3 30.6 27.8C30.4 28.6 29.8 29.1 29.1 29.4C28.4 29.6 14.9 29.6 14.4 29.4zM29 28.1C29.5 27.7 29.5 28.1 29.5 22C29.5 15.9 29.5 16.3 29 15.9C28.6 15.7 15.4 15.7 15 15.9C14.6 16.2 14.5 16.5 14.5 17.5L14.5 18.3L20 18.3C26.3 18.2 25.9 18.2 26.5 18.8C27 19.3 27 19.2 27 24L27 28.3L27.8 28.2C28.7 28.2 28.7 28.2 29 28.1z") }+ val Distort by lazy { shape("distort", 44f, "M14.8 29.4C14.2 29.2 13.7 28.8 13.4 28.3C13.2 27.9 13.2 17 13.3 16.3C13.5 15.5 14.2 14.9 14.9 14.6C15.5 14.4 28.5 14.4 29.1 14.6C29.8 14.9 30.5 15.5 30.7 16.3C30.8 16.9 30.8 27.3 30.6 27.8C30.4 28.6 29.8 29.1 29.1 29.4C28.6 29.5 15.4 29.6 14.8 29.4zM29 28C29.5 27.7 29.5 28 29.5 22C29.5 15.9 29.5 16.3 29 15.9C28.6 15.7 15.4 15.7 15 15.9C14.5 16.3 14.3 16.9 14.7 17.1C14.8 17.1 17 17.7 19.6 18.3C24.9 19.7 25 19.7 25.6 20.4C26.2 21 26.3 21.1 27.2 24.5C27.6 26.2 28 27.7 28 27.9C28.1 28.3 28.1 28.3 28.4 28.2C28.6 28.2 28.8 28.1 29 28z") }+ val Warp by lazy { shape("warp", 44f, "M13.8 29.4C13 29.2 12.4 28.6 12.1 27.8C12 27.3 11.9 17 12.1 16.3C12.3 15.6 12.9 14.9 13.6 14.6C14.2 14.4 28 14.5 28.4 14.7C30.7 15.6 32 18.4 32 22.5C32 25.6 31.1 27.4 28.9 28.8C27.7 29.5 28.6 29.5 20.9 29.5C15.1 29.5 14 29.5 13.8 29.4zM14.5 27C17.9 23.6 17.7 20.5 14.1 16.6C13.6 16 13.6 16 13.4 16.3C13.2 16.6 13.2 27.1 13.4 27.6C13.5 27.8 13.5 27.9 13.6 27.9C13.6 27.9 14 27.5 14.5 27z") }+ val Snapping by lazy { shape("snapping", 44f, "M21 32C20.2 31.9 18.9 31.6 18.6 31.4C18.5 31.4 19.8 30 23.4 26.2C26.1 23.4 28.3 21 28.3 21C28.3 21 26.9 20.9 25.1 20.9L22 20.9L23.8 16.9C24.9 14.7 25.8 12.8 25.8 12.8C25.8 12.7 26.6 13.1 27.3 13.5C32.4 16.7 33.6 23.8 29.6 28.4C27.6 30.9 24.1 32.3 21 32zM16.8 30.5C12.4 27.8 10.8 22.3 13 17.7C15 13.6 19.6 11.3 24 12.2C25.4 12.5 25.8 11.8 20.5 17.7L16 22.9L18.9 22.9C20.6 22.9 21.9 23 21.9 23C21.9 23.1 17.6 30.9 17.5 30.9C17.5 30.9 17.2 30.8 16.8 30.5z") }+ val FlipHorizontal by lazy { shape("fliphorizontal", 50f, "M15.4 34C15 33.8 14.8 33.4 14.9 33C15 32.8 22.7 23.5 23 23.4C23.2 23.3 23.6 23.4 23.8 23.6C24 23.8 24.1 33.2 23.9 33.5C23.6 34 23.8 34 19.4 34C17.2 34 15.4 34 15.4 34zM25.5 33.9C25 33.6 25 33.9 25 28.6C25 23.8 25 23.8 25.2 23.6C25.4 23.4 25.8 23.3 26 23.4C26.3 23.5 34 32.8 34.1 33C34.2 33.3 34.1 33.6 33.9 33.8C33.7 34 33.7 34 29.7 34C25.8 34 25.7 34 25.5 33.9zM16.8 19.7C15.2 18.7 15 18.6 15.2 18.4C15.2 18.3 18.3 16.3 18.5 16.3C18.8 16.2 18.9 16.4 18.9 17.2L18.9 18L24.5 18L30.1 18L30.1 17.2C30.1 16 30.1 16 32.2 17.3C33.8 18.3 34 18.4 33.8 18.6C33.8 18.8 30.6 20.8 30.4 20.8C30.2 20.8 30.1 20.6 30.1 19.8L30.1 19L24.5 19L18.9 19L18.9 19.8C18.9 21 18.9 21 16.8 19.7z") }+ val FlipVertical by lazy { shape("flipvertical", 50f, "M15.7 35.1C15.2 34.9 15.2 35.1 15.2 30.8C15.2 26.3 15.2 26.5 15.6 26.2C15.8 26.1 15.8 26.1 20.6 26.1C25.7 26.1 25.5 26 25.7 26.4C25.9 26.7 25.9 27.1 25.6 27.3C25.3 27.7 16.6 34.9 16.3 35.1C16.1 35.2 15.9 35.2 15.7 35.1zM30.4 34.3C30.1 33.9 28.5 31.2 28.5 31.1C28.4 30.8 28.6 30.8 29.4 30.8L30.2 30.8L30.2 25.1L30.2 19.5L29.4 19.5C28.6 19.5 28.4 19.5 28.4 19.2C28.4 19.1 30.4 15.9 30.6 15.8C30.8 15.7 30.9 15.8 31.9 17.4C33.2 19.5 33.2 19.5 32 19.5L31.2 19.5L31.2 25.1L31.2 30.8L32 30.8C33.2 30.8 33.2 30.7 32 32.7C30.7 34.7 30.7 34.7 30.4 34.3zM15.6 24C15.2 23.7 15.2 23.9 15.2 19.6C15.2 16.8 15.2 15.6 15.3 15.5C15.4 15.2 15.8 15 16.2 15.1C16.4 15.1 25.7 22.9 25.8 23.1C25.9 23.4 25.9 23.6 25.7 23.8C25.5 24.2 25.7 24.2 20.6 24.2C15.8 24.2 15.8 24.2 15.6 24z") }+ val Rotate45 by lazy { shape("rotate45", 44f, "M18.6 31.3C18.2 31.2 17.9 30.8 17.8 30.4C17.8 30.3 17.8 28.4 17.8 25.1C17.8 19.4 17.7 19.7 18.5 19.2C18.9 18.9 29.6 18.9 30 19.2C30.8 19.7 30.7 19.4 30.7 25.1C30.8 30.5 30.8 30.5 30.4 30.9C30 31.5 30.3 31.5 24.2 31.5C18.9 31.5 18.9 31.5 18.6 31.3zM13.4 20.4C13.1 20.1 13.3 18.1 13.7 17C14.3 15.4 15.7 14.1 17.4 13.7C17.8 13.7 17.8 13.7 17.8 12.9C17.8 11.7 17.7 11.7 19.8 13C21.4 14 21.6 14.2 21.4 14.4C21.4 14.5 18.2 16.5 18 16.5C17.8 16.5 17.8 16.3 17.8 15.5C17.8 14.6 17.8 14.6 17 14.9C15.3 15.6 14.4 17.1 14.3 19.3C14.2 20.1 14.2 20.2 14.1 20.4C13.9 20.5 13.6 20.5 13.4 20.4z") }+ val FitToCanvas by lazy { shape("fittocanvas", 44f, "M15.3 29.4C15 29.4 14.6 29 14.6 28.7C14.5 28.4 14.5 15.6 14.6 15.3C14.6 15 15 14.6 15.3 14.6C15.6 14.5 28.4 14.5 28.7 14.6C29 14.7 29.2 14.9 29.4 15.2C29.6 15.6 29.6 28.4 29.4 28.8C29.2 29.1 29 29.3 28.7 29.4C28.4 29.5 15.6 29.5 15.3 29.4zM18.2 27.2C20.2 26.8 20.2 26.8 19.4 26.1L19 25.6L22.3 22.3L25.6 19L26.1 19.4C26.5 19.9 26.7 20 26.8 19.8C26.9 19.7 27.6 16.9 27.6 16.7C27.6 16.4 27.4 16.4 25.8 16.8C25 16.9 24.2 17.1 24.2 17.2C24 17.3 24.1 17.5 24.6 17.9L25 18.4L21.7 21.7L18.4 25L17.9 24.6C17.5 24.1 17.3 24 17.2 24.2C17 24.4 16.4 27.4 16.4 27.5C16.5 27.6 16.7 27.6 18.2 27.2z") }+ val Interpolation by lazy { shape("interpolation", 44f, "M20.9 31.9C12.9 30.9 9.2 21.7 14.4 15.6C17 12.4 21.3 11.2 25.2 12.5C32 14.8 34.2 23.2 29.5 28.6C27.4 31 24 32.3 20.9 31.9zM19.2 28.7L19.2 27L20.9 27L22.6 27L22.6 25.3L22.6 23.7L24.2 23.7L25.9 23.7L25.9 22L25.9 20.3L24.2 20.3L22.6 20.3L22.6 18.7L22.6 17L20.9 17L19.2 17L19.2 15.3C19.2 13.7 19.2 13.7 19 13.7C18.6 13.7 17 14.5 16.2 15.3C15.9 15.6 15.9 15.6 15.9 16.3L15.9 17L15.3 17C14.6 17 14.6 17 14.4 17.4C13.9 18.1 13.7 18.8 13.4 19.8L13.3 20.3L14.6 20.3L15.9 20.3L15.9 22L15.9 23.7L14.6 23.7L13.3 23.7L13.4 24.2C13.7 25.2 13.9 25.9 14.4 26.6C14.6 27 14.6 27 15.3 27L15.9 27L15.9 27.7C15.9 28.4 15.9 28.4 16.2 28.7C17 29.5 18.5 30.3 19 30.3C19.2 30.3 19.2 30.3 19.2 28.7zM15.9 25.3L15.9 23.7L17.6 23.7L19.2 23.7L19.2 22L19.2 20.3L17.6 20.3L15.9 20.3L15.9 18.7L15.9 17L17.6 17L19.2 17L19.2 18.7L19.2 20.3L20.9 20.3L22.6 20.3L22.6 22L22.6 23.7L20.9 23.7L19.2 23.7L19.2 25.3L19.2 27L17.6 27L15.9 27L15.9 25.3z") }+ val AdvancedMesh by lazy { icon("advanced-mesh", Part(MESH_CELLS, 0.6f, true)) }++ /** The advanced mesh icon's cells: four across, three down, with thin gaps. */+ private val MESH_CELLS = buildString {+ for (row in 0 until 3) for (col in 0 until 4) {+ val x = 1.5f + col * 5.625f+ val y = 4.9f + row * 5.233f+ append("M$x ${y}h4.425v4.033h-4.425z")+ }+ }++ // the adjustments' bar+ val AdjustHsb by lazy { shape("adjusthsb", 32f, "M11.8 22.9C8.9 22.2 8.4 18.2 11 16.8C13.2 15.7 15.8 17.2 15.8 19.7C15.8 21.8 13.8 23.4 11.8 22.9zM18.6 19.2C15.7 18.4 15.3 14.5 17.9 13.1C20.1 12 22.7 13.5 22.7 16C22.7 18.1 20.6 19.7 18.6 19.2zM11.8 15.5C10.3 15.1 9.3 13.8 9.3 12.3C9.3 9 13.5 7.8 15.3 10.5C16.9 13 14.6 16.2 11.8 15.5z") }+ val AdjustBlur by lazy { shape("adjustblur", 32f, "M15.2 24C15.1 24 14.8 23.9 14.6 23.9C9.9 23.1 6.8 18 8.5 13.4C10.4 7.8 17.4 6.2 21.6 10.3C26.1 14.7 23.9 22.4 17.7 23.8C17.2 23.9 15.6 24 15.2 24zM17.5 23.3C23.3 22.1 25.4 15 21.2 10.8C18.4 7.9 13.7 7.9 10.8 10.7C7.9 13.6 7.9 18.4 10.8 21.3C12 22.5 13.5 23.2 15.2 23.4C15.7 23.5 17 23.4 17.5 23.3zM15.4 22.2C10.1 21.7 7.8 15.3 11.6 11.6C15.3 7.8 21.7 10.1 22.2 15.4C22.6 19.3 19.3 22.7 15.4 22.2zM17.3 21C20.4 20.1 22 16.6 20.6 13.8C19.4 11.2 16.3 10.1 13.7 11.4C11.9 12.3 10.9 13.9 10.9 16C10.9 17.3 11.2 18.2 11.9 19.1C13.1 20.7 15.4 21.5 17.3 21zM15 19.9C12 19.1 11 15.4 13.2 13.2C14 12.3 14.7 12 16 12C17.8 12 19.1 13 19.8 14.7C20 15.3 20 16.7 19.8 17.3C19.3 18.5 18.5 19.4 17.3 19.8C16.8 20 15.6 20.1 15 19.9zM17 18.1C18.9 17.2 18.7 14.4 16.7 13.8C14.9 13.3 13.3 14.9 13.8 16.7C14.2 18 15.7 18.7 17 18.1zM15.4 17C14.4 16.4 14.9 14.9 16 14.9C16.9 14.9 17.4 15.8 17 16.6C16.7 17.1 15.9 17.3 15.4 17z") }+ val AdjustBalance by lazy { shape("adjustbalance", 32f, "M15.2 23.5C15.2 23.5 14.9 23.4 14.7 23.4C9.3 22.5 6.7 16 10 11.5C14.3 5.8 23.5 8.8 23.5 16C23.5 19.6 21.1 22.5 17.6 23.3C17.1 23.4 15.5 23.5 15.2 23.5zM17.2 21.8C19 21.4 20.6 20.1 21.3 18.5C22.2 16.7 22 14.3 20.9 12.8C20.6 12.3 20.2 11.9 20.2 11.9C20.1 11.9 18.2 13.7 16 16C11.8 20.2 11.8 20.2 12.1 20.4C13.5 21.6 15.4 22.1 17.2 21.8z") }+ val AdjustCurves by lazy { shape("adjustcurves", 32f, "M11.7 22.9C11 22.7 9.9 22.1 9.9 21.8C9.9 21.6 10.4 20.4 10.6 19.9C11.7 17.9 13.4 16.9 16.1 16.7C19.3 16.6 21.4 15.3 22.7 12.8C23 12.2 23 12.2 23 16C23 20.3 23 20.4 22.6 21.1C22.1 22 21.2 22.7 20.3 22.9C19.7 23 12.2 23 11.7 22.9zM9 16C9 11.7 9 11.6 9.4 10.9C9.9 10 10.8 9.3 11.7 9.1C12.2 9 19.5 9 20.2 9.1C20.9 9.2 22.1 9.9 22.1 10.2C22.1 10.4 21.6 11.6 21.4 12.1C20.3 14.1 18.3 15.2 16 15.2C13 15.3 10.6 16.7 9.3 19.2C9 19.8 9 19.8 9 16z") }+ val AdjustGradient by lazy { shape("adjustgradient", 32f, "M11.7 23.5C10.2 23.1 9.2 22.3 8.7 20.9C8.5 20.5 8.5 20.5 8.5 16C8.5 11.5 8.5 11.5 8.7 11.1C9.1 9.9 10.1 9 11.3 8.6C11.8 8.5 20.4 8.5 20.8 8.6C22 9.1 22.9 9.9 23.3 11.1C23.5 11.5 23.5 11.5 23.5 16C23.5 20.5 23.5 20.5 23.3 20.9C22.9 22.1 22.1 22.9 20.9 23.3C20.5 23.5 20.5 23.5 16.2 23.5C13.8 23.5 11.7 23.5 11.7 23.5zM15.1 18.2L15.1 17.3L16 17.3L16.9 17.2L16.9 18.2L16.9 19.1L17.8 19.1L18.7 19.1L18.8 18.2L18.8 17.3L19.7 17.3L20.6 17.2L20.6 16.3L20.6 15.4L21.5 15.4L22.4 15.4L22.4 13.5C22.4 11.3 22.4 11.1 21.7 10.4C20.9 9.6 20.9 9.6 16 9.6C11.1 9.6 11.1 9.6 10.3 10.4C9.6 11.1 9.6 11.3 9.6 13.5L9.6 15.4L10.5 15.4L11.4 15.4L11.4 16.3L11.4 17.2L12.3 17.3L13.2 17.3L13.2 18.2L13.3 19.1L14.2 19.1L15.1 19.1L15.1 18.2zM13.2 16.3L13.2 15.4L12.3 15.4L11.4 15.4L11.4 14.5L11.4 13.6L12.3 13.6L13.2 13.6L13.2 14.5L13.2 15.4L14.2 15.4L15.1 15.4L15.1 14.5L15.1 13.6L16 13.6L16.9 13.6L16.9 14.5L16.9 15.4L17.8 15.4L18.7 15.4L18.8 14.5L18.8 13.6L19.7 13.6L20.6 13.6L20.6 14.5L20.6 15.4L19.7 15.4L18.8 15.4L18.8 16.3L18.8 17.2L17.8 17.2L16.9 17.2L16.9 16.3L16.9 15.4L16 15.4L15.1 15.4L15.1 16.3L15.1 17.2L14.2 17.2L13.2 17.2L13.2 16.3z") }+ val AdjustMotion by lazy { shape("adjustmotion", 32f, "M11.7 22.9C10.4 22.6 9.3 21.4 9.1 20.1C9 19.9 9 19 9 17.6L9 15.4L15.1 18.9C18.5 20.9 21.2 22.5 21.2 22.5C21.3 22.6 20.5 22.9 20.1 22.9C19.6 23 12.1 23 11.7 22.9zM15.7 17.5L9 13.7L9 12.9C9 12.3 9.1 11.5 9.2 11.4C9.2 11.3 11.2 12.5 16.1 15.3C23 19.2 23 19.2 23 19.5C23 20 22.6 21.4 22.4 21.4C22.4 21.4 19.4 19.6 15.7 17.5zM16.5 13.8C13 11.7 10.1 10 10.1 10C10.1 9.9 10.5 9.6 10.8 9.5C10.9 9.4 11.2 9.6 16.9 12.9C20.2 14.8 22.9 16.3 23 16.4C23 16.4 23 16.7 23 17L23 17.5L16.5 13.8zM18.2 11.9C15.6 10.4 13.4 9.1 13.4 9.1C13.3 9 13.5 9 13.9 9C14.5 9 14.5 9 18.7 11.4C21.1 12.8 23 13.9 23 13.9C23 13.9 23 14.1 23 14.3C23 14.6 23 14.6 18.2 11.9zM20.2 10.6C17.8 9.2 17.6 9 17.8 9C18.1 9 22.9 11.8 23 12C23 12.2 23.2 12.3 20.2 10.6z") }+ val AdjustPerspective by lazy { shape("adjustperspective", 32f, "M9.1 22L9.1 21.1L12.5 18.5C14.4 17.1 15.9 16 15.9 16C15.9 16.1 15.2 17.6 14.3 19.5L12.6 23L10.8 23L9.1 23L9.1 22zM18.9 21.9C18.6 21.3 17.9 19.8 17.2 18.4C16.6 17.1 16.1 16 16.1 16C16.1 16 17.6 17.1 19.5 18.5L22.8 21L22.9 22L22.9 23L21.2 23L19.4 23L18.9 21.9zM12.5 13.4L9.1 10.9L9.1 10L9.1 9L10.8 9L12.5 9L14.2 12.4C15.2 14.3 15.9 15.8 15.9 15.9C15.9 15.9 14.4 14.8 12.5 13.4zM16.1 15.9C16.1 15.8 16.8 14.3 17.8 12.4L19.4 9L21.2 9L22.9 9L22.9 10L22.9 10.9L19.6 13.3C16.3 15.8 16.1 15.9 16.1 15.9z") }+ val AdjustNoise by lazy { shape("adjustnoise", 32f, "M9.7 22.9C8.5 22.5 8.4 20.7 9.6 20.1C10.4 19.8 11.4 20.2 11.7 21C12 22.2 10.9 23.3 9.7 22.9zM13.5 22.9C12 22.2 12.5 20 14.1 20C15.3 20 16 21.3 15.3 22.3C15 22.9 14.1 23.2 13.5 22.9zM17.4 22.9C16.2 22.5 16.1 20.7 17.3 20.1C18.3 19.7 19.4 20.4 19.4 21.5C19.4 22.5 18.4 23.3 17.4 22.9zM21.3 22.9C20.5 22.6 20.1 21.8 20.3 21C20.8 19.7 22.6 19.6 23.1 20.9C23.7 22.1 22.5 23.4 21.3 22.9zM9.6 19.2C8.2 18.5 8.7 16.3 10.2 16.3C11.7 16.3 12.3 18.3 11 19.1C10.6 19.3 10 19.4 9.6 19.2zM13.4 19.2C12.5 18.7 12.3 17.4 13.1 16.7C14.1 15.8 15.6 16.6 15.6 18C15.5 19 14.4 19.6 13.4 19.2zM17.3 19.2C16 18.6 16.2 16.7 17.6 16.4C18.9 16 20 17.6 19.1 18.7C18.7 19.3 17.9 19.5 17.3 19.2zM21.1 19.1C20.2 18.7 20 17.5 20.7 16.8C21.6 15.8 23.2 16.5 23.2 17.8C23.2 19 22.1 19.7 21.1 19.1zM9.9 15.6C8.1 15.1 8.5 12.6 10.3 12.7C11.9 12.8 12.3 14.8 10.9 15.5C10.6 15.6 10.1 15.7 9.9 15.6zM13.6 15.6C12.3 15.1 12.2 13.4 13.4 12.8C14.6 12.2 16 13.4 15.5 14.7C15.2 15.4 14.3 15.9 13.6 15.6zM17.5 15.6C15.9 15.1 16.2 12.8 17.8 12.7C19.5 12.6 20.1 14.8 18.5 15.5C18.3 15.7 17.8 15.7 17.5 15.6zM21.4 15.6C20.1 15.2 19.9 13.6 21 12.9C22 12.3 23.2 13 23.2 14.2C23.2 15.1 22.2 15.9 21.4 15.6zM9.6 11.9C8.3 11.2 8.6 9.2 10 9C11.1 8.9 12 9.9 11.7 11C11.4 11.8 10.4 12.2 9.6 11.9zM13.5 11.9C11.9 11.2 12.5 8.8 14.2 9C15.7 9.2 16.1 11.2 14.7 11.9C14.4 12 13.8 12 13.5 11.9zM17.3 11.9C15.9 11.2 16.3 9.2 17.8 9C19.2 8.9 20 10.6 18.9 11.6C18.5 12 17.9 12.1 17.3 11.9zM21.2 11.9C20.1 11.4 20 10.1 20.8 9.4C22 8.3 23.8 9.7 23.1 11.2C22.8 11.9 21.9 12.2 21.2 11.9z") }+ val StudioGrain by lazy { shape("studiograin", 50f, "M18 31L18 30L19 30L20 30L20 29L20 28L19 28L18 28L18 27L18 26L19 26L20 26L20 25L20 24L19 24L18 24L18 23L18 22L19 22L20 22L20 21L20 20L19 20L18 20L18 19L18 18L19 18L20 18L20 19L20 20L21 20L22 20L22 19L22 18L23 18L24 18L24 19L24 20L25 20L26 20L26 19L26 18L27 18L28 18L28 19L28 20L29 20L30 20L30 19L30 18L31 18L32 18L32 19L32 20L31 20L30 20L30 21L30 22L31 22L32 22L32 23L32 24L31 24L30 24L30 25L30 26L31 26L32 26L32 27L32 28L31 28L30 28L30 29L30 30L31 30L32 30L32 31L32 32L31 32L30 32L30 31L30 30L29 30L28 30L28 31L28 32L27 32L26 32L26 31L26 30L25 30L24 30L24 31L24 32L23 32L22 32L22 31L22 30L21 30L20 30L20 31L20 32L19 32L18 32L18 31zM24 29L24 28L25 28L26 28L26 29L26 30L27 30L28 30L28 29L28 28L29 28L30 28L30 27L30 26L29 26L28 26L28 25L28 24L29 24L30 24L30 23L30 22L29 22L28 22L28 21L28 20L27 20L26 20L26 21L26 22L25 22L24 22L24 21L24 20L23 20L22 20L22 21L22 22L21 22L20 22L20 23L20 24L21 24L22 24L22 25L22 26L21 26L20 26L20 27L20 28L21 28L22 28L22 29L22 30L23 30L24 30L24 29zM22 27L22 26L23 26L24 26L24 25L24 24L23 24L22 24L22 23L22 22L23 22L24 22L24 23L24 24L25 24L26 24L26 23L26 22L27 22L28 22L28 23L28 24L27 24L26 24L26 25L26 26L27 26L28 26L28 27L28 28L27 28L26 28L26 27L26 26L25 26L24 26L24 27L24 28L23 28L22 28L22 27z") }+ val AdjustSharpen by lazy { shape("adjustsharpen", 32f, "M12.5 19.5L9 16L12.5 12.5L16 9L19.5 12.5L23 16L19.5 19.5C17.6 21.4 16 23 16 23C16 23 14.4 21.4 12.5 19.5z") }+ val AdjustBloom by lazy { shape("adjustbloom", 32f, "M15.1 22.9C14.7 22.7 14.7 22.5 14.7 21C14.7 19.5 14.7 19.4 15.2 19.2C15.5 19 15.9 19.2 16.2 19.5C16.3 19.7 16.4 22.2 16.2 22.5C16 22.9 15.5 23.1 15.1 22.9zM10.5 21C10.1 20.9 9.8 20.4 10.1 19.9C10.2 19.6 11.8 18 12.1 17.9C12.7 17.7 13.3 18.3 13.1 18.8C13 19.1 11.1 21 11 21C10.9 21 10.8 21 10.8 21C10.8 21 10.6 21 10.5 21zM20 21C19.8 20.9 18 19.1 17.9 18.8C17.7 18.3 18.3 17.7 18.9 17.9C19.2 18 20.9 19.8 21 20C21.1 20.4 20.8 21 20.5 21C20.4 21 20.3 21 20.3 21C20.3 21 20.1 21 20 21zM14.9 17.8C13.8 17.4 13.2 16.6 13.2 15.5C13.2 14.1 14.1 13.2 15.5 13.2C16.5 13.2 17.1 13.6 17.6 14.5C18 15.3 17.8 16.5 17.1 17.2C16.6 17.7 15.5 18 14.9 17.8zM8.4 16.2C7.9 15.9 7.9 15.1 8.5 14.8C8.8 14.6 11.3 14.7 11.5 14.8C12 15.1 12 15.9 11.5 16.2C11.3 16.3 8.8 16.4 8.4 16.2zM19.7 16.3C19.2 16.2 19 15.4 19.4 14.9C19.6 14.7 19.8 14.7 21.1 14.7C22.5 14.7 22.7 14.7 22.9 15.1C23.1 15.5 23 16 22.5 16.2C22.3 16.3 20.2 16.4 19.7 16.3zM12.1 13.1C11.8 13 10.2 11.4 10.1 11.1C9.8 10.5 10.3 9.8 11 10C11.3 10.1 13.1 12 13.2 12.2C13.3 12.8 12.6 13.3 12.1 13.1zM18.4 13.1C18 13 17.8 12.5 17.9 12.2C18 11.9 19.8 10.1 20 10C20.6 9.8 21.2 10.4 21 11C20.9 11.2 20.7 11.4 20 12.1C18.9 13.2 18.8 13.3 18.4 13.1zM15.1 11.8C14.7 11.6 14.7 11.5 14.7 9.9C14.7 8.3 14.8 8.2 15.3 8.1C15.6 8 15.9 8.1 16.1 8.3C16.3 8.6 16.4 11.2 16.2 11.5C15.9 11.8 15.5 12 15.1 11.8z") }+ val AdjustGlitch by lazy { shape("adjustglitch", 32f, "M10.9 21.3C9.8 21 8.9 20.2 8.6 19.1C8.5 18.8 8.5 18.5 8.5 17.8C8.5 16.8 8.5 16.8 8.7 16.8C8.8 16.8 11.5 16.6 14.6 16.3C21.7 15.8 20.9 15.9 20.9 15.5C20.9 15.3 20.9 15.2 20.9 15.2C20.9 15.2 18.1 14.9 14.8 14.6C11.5 14.3 8.7 14.1 8.6 14.1C8.5 14.1 8.4 12.1 8.6 11.4C8.9 10.3 9.8 9.4 10.9 9.1C11.4 9 17.9 9 18.5 9.1C19.6 9.3 20.5 10.2 20.8 11.4C20.9 11.7 20.9 12.2 20.9 13.5C20.9 15.2 20.9 15.2 21.2 15.2C21.3 15.2 22.2 15.3 23.1 15.4C24.1 15.5 24.8 15.6 24.9 15.6C24.9 15.6 24.2 15.6 23.3 15.7C22.5 15.8 21.6 15.8 21.4 15.9L20.9 15.9L20.9 17.4C20.9 18.8 20.9 19 20.8 19.3C20.4 20.3 19.8 20.9 18.8 21.3C18.4 21.4 11.5 21.5 10.9 21.3z") }+ val AdjustHalftone by lazy { shape("adjusthalftone", 32f, "M16.9 23.8C16.8 23.7 16.7 23.6 16.7 23.5C16.7 23.3 17 23 17.2 23C17.4 23 17.7 23.3 17.7 23.5C17.7 23.9 17.2 24.1 16.9 23.8zM14.5 22.9C13.9 22.5 14 21.7 14.6 21.4C15.2 21.2 15.8 21.5 15.7 22.2C15.7 22.8 15.1 23.2 14.5 22.9zM18.5 22.1C17.9 21.8 17.8 21.2 18.2 20.7C18.9 20.1 20 21 19.5 21.7C19.3 22.1 18.8 22.3 18.5 22.1zM12.5 21.3C11.6 21 11.8 19.6 12.8 19.6C13.7 19.6 13.9 20.9 13 21.2C12.8 21.3 12.7 21.3 12.5 21.3zM22.3 20.9C22.1 20.6 22.2 20.2 22.6 20.2C22.7 20.2 22.8 20.2 22.9 20.3C23.1 20.6 22.9 21 22.6 21C22.5 21 22.4 20.9 22.3 20.9zM16.1 20.6C15.7 20.4 15.5 19.9 15.7 19.5C15.8 19.2 15.7 18.9 15.4 18.8C15.1 18.7 15.1 18.7 14.8 18.9C14 19.5 13.1 18.9 13.4 17.9C13.5 17.4 13.1 17.1 12.8 17.4C12.2 18.1 11.2 17.6 11.2 16.8C11.2 16.1 11.7 15.8 12.6 16C12.9 16.1 13.3 15.4 13 15.2C12.6 14.8 12.7 14 13.2 13.7C13.4 13.6 13.8 13.6 14.2 13.7C14.5 13.8 14.7 13.3 14.4 13C13.9 12.3 14.3 11.5 15.1 11.5C15.7 11.5 16.2 12.1 15.9 12.7C15.8 13 15.9 13.2 16.2 13.3C16.4 13.4 16.5 13.4 16.8 13.2C16.9 13 17.1 12.9 17.2 12.9C17.6 12.8 17.8 12.5 17.8 11.9C17.8 11.1 18 10.8 18.6 10.8C19.5 10.7 19.7 11.8 19 12.3C18.5 12.6 18.5 12.7 18.4 13.4C18.4 13.7 18.3 14.1 18.2 14.2C18.1 14.4 18.1 14.6 18.2 14.8C18.4 14.9 18.8 14.9 18.9 14.8C19.1 14.5 19.7 14.4 20 14.6C20.9 15.2 20.2 16.6 19.2 16.2C19.1 16.2 18.9 16.1 18.9 16.2C18 16.5 19.2 18.3 20.3 18.3C20.5 18.3 20.6 18.4 20.8 18.6C21.4 19.1 21 19.9 20.2 19.9C19.8 19.9 19.4 19.6 19.4 19.3C19.4 18.9 18.8 18.4 18.2 18.3C17.2 18.2 16.7 18.7 17.2 19.2C17.8 20 17 21.1 16.1 20.6zM10 19.5C9.4 19.1 9.7 18.3 10.3 18.3C10.9 18.3 11.2 19 10.8 19.4C10.6 19.6 10.2 19.7 10 19.5zM16.3 18.2C17 17.9 16.8 16.9 16 16.9C15.3 16.9 15.1 17.9 15.8 18.2C16 18.3 16 18.3 16.3 18.2zM21.4 17.6C20.6 17.2 20.7 16.1 21.5 15.9C22 15.8 22.5 16 22.6 16.5C22.9 17.2 22.1 17.9 21.4 17.6zM14.7 16.9C15.3 16.2 14.4 15.4 13.8 15.9C13.3 16.3 13.6 17.1 14.3 17.1C14.5 17.1 14.6 17 14.7 16.9zM17.5 16.3C18.2 16 18 15 17.3 15C16.5 15 16.3 15.9 17 16.3C17.3 16.4 17.3 16.4 17.5 16.3zM9.4 15.8C8.9 15.6 8.9 14.9 9.4 14.6C10.2 14.3 10.7 15.5 9.9 15.8C9.7 16 9.7 16 9.4 15.8zM16 14.9C16.4 14.5 16.1 13.8 15.5 13.8C15.3 13.8 15.2 13.9 15 14C14.4 14.6 15.3 15.5 16 14.9zM22.7 14.8C22.5 14.6 22.5 14.5 22.6 14.3C22.8 13.8 23.5 14 23.5 14.5C23.5 14.9 23 15.1 22.7 14.8zM10.9 13.7C10.5 13.6 10.2 13.1 10.4 12.7C10.6 12 11.6 11.9 11.9 12.6C12.2 13.2 11.6 14 10.9 13.7zM20.9 13.7C20 13.5 20.1 12.1 21.1 12.1C22 12.1 22.2 13.5 21.3 13.7C21.1 13.8 21.1 13.8 20.9 13.7zM12.3 11.5C11.8 11.2 11.8 10.5 12.2 10.2C12.8 9.5 13.8 10.2 13.5 11.1C13.3 11.5 12.7 11.7 12.3 11.5zM16.1 10.7C15.6 10.5 15.5 9.8 15.8 9.4C16.2 8.8 17.3 9.1 17.2 9.9C17.2 10.5 16.7 10.9 16.1 10.7zM20 9.4C19.9 9.2 19.9 9 20 8.8C20.2 8.6 20.3 8.6 20.5 8.8C20.8 9.2 20.4 9.6 20 9.4zM14 8.5C13.9 8.4 13.9 8.3 13.9 8.3C14 8 14.4 7.9 14.6 8.2C14.7 8.6 14.2 8.9 14 8.5z") }+ val AdjustChromatic by lazy { shape("adjustchromatic", 32f, "M9.6 19.6C7 16.3 7.1 16.4 7.1 16C7.1 15.6 7 15.7 9.6 12.4L11.9 9.5L12.9 9.5C13.6 9.5 13.8 9.5 13.8 9.6C13.8 9.6 12.7 11 11.4 12.6C9 15.6 9 15.6 9 16C9.1 16.4 8.9 16.2 12.7 21C13.1 21.6 13.6 22.1 13.7 22.3C13.8 22.5 13.8 22.5 12.9 22.5L11.9 22.5L9.6 19.6zM18.2 22.4C18.2 22.4 19.3 21.1 20.5 19.5C23 16.4 23 16.4 23 16C23 15.6 23 15.6 20.5 12.5C19.3 10.9 18.2 9.6 18.2 9.6C18.2 9.5 18.6 9.5 19.1 9.5L20.1 9.5L21.1 10.7C25.1 15.8 24.9 15.6 24.9 16C24.9 16.4 25.1 16.2 21.1 21.3L20.1 22.5L19.1 22.5C18.6 22.5 18.2 22.5 18.2 22.4zM13.7 19.6C10.8 15.9 10.9 16.1 11.3 15.6C11.5 15.2 15.9 9.6 16 9.6C16.1 9.6 20.8 15.6 20.8 15.8C20.9 15.9 20.9 16.1 20.8 16.2C20.8 16.4 16.1 22.4 16 22.4C16 22.4 14.9 21.1 13.7 19.6z") }+ val AdjustLiquify by lazy { shape("adjustliquify", 32f, "M21.6 22.3C23.9 18.9 23.8 15 21.4 12.5C19.6 10.6 17 10.1 15 11.3C14.1 11.8 13.3 12.8 13.2 13.6C13.1 14.4 13.7 14.5 14.1 13.7C14.9 11.9 17.6 11.5 19.4 12.9C22 15 21.2 19.6 18 21.2C17 21.7 16.5 21.8 15.2 21.8C13.1 21.8 11.8 21.2 10.4 19.9C7.2 16.9 7.2 11.9 10.4 8.7C11 8 11 8.1 10.5 8.8C8.5 11.7 8.3 15.1 10 17.7C12.1 20.7 16.1 21.3 18.3 18.8C18.8 18.2 19.1 17.1 18.8 16.8C18.5 16.7 18.3 16.8 18.1 17.3C17.1 19.3 14.1 19.6 12.3 17.7C10.4 15.6 11 11.9 13.4 10.3C17.9 7.2 23.9 10.7 24.1 16.3C24.2 18.7 23.4 20.8 21.7 22.4L21.2 22.9L21.6 22.3z") }+ val AdjustClone by lazy { shape("adjustclone", 32f, "M12.1 20.9C7.6 20 6.5 14.3 10.3 11.8C12.4 10.5 15.3 10.9 16.8 12.8C19.2 15.7 17.8 19.9 14.2 20.9C13.7 21 12.6 21 12.1 20.9zM18.8 20.7C20.7 17.8 20.5 14.1 18.2 11.5L17.9 11.1L18.4 11C20.7 10.8 22.9 12.2 23.6 14.5C23.9 15.3 23.9 16.8 23.6 17.6C22.9 19.6 21.2 20.8 19.1 21C18.5 21 18.5 21 18.8 20.7z") }+ val Disclose by lazy { shape("disclose", 32f, "M12.5 19.1C12.2 18.9 9 15.4 8.7 14.8C8.3 14 8.6 12.9 9.5 12.5C9.8 12.3 9.8 12.3 13.3 12.3C17.2 12.3 16.9 12.3 17.4 12.8C17.9 13.3 18.1 14.1 17.8 14.8C17.6 15.1 14.4 18.8 14 19C13.6 19.3 13 19.3 12.5 19.1z") }+ val NoiseClouds by lazy { shape("noiseclouds", 50f, "M15.8 39C12.3 38.6 9.5 36.3 8.4 33C6.9 28.5 9.4 23.5 14 22C14.4 21.9 14.4 21.9 14.4 21.7C14.1 20.1 14.2 19.1 14.5 17.8C16.1 11.1 24.6 8.7 29.4 13.7C30.2 14.4 30.2 14.4 30.6 14.2C33.3 12.8 36.7 14.2 37.7 17C38 17.7 38.1 18.4 38 19.1C38 19.7 38 19.7 38.3 19.9C42.3 22.2 44.2 27.4 42.7 31.9C41.8 34.8 39.4 37.3 36.5 38.4C34.9 39 35.6 39 25.2 39C20.1 39 15.9 39 15.8 39z") }+ val NoiseBillows by lazy { shape("noisebillows", 50f, "M24.8 41.2C22.9 40.6 21.4 38 21.4 35.3C21.4 35 21.4 35 20.8 35.5C18.1 37.8 14.9 38 13.6 36C12.6 34.4 13.2 31.6 15.2 29.4C15.5 29.1 15.5 29.1 15.2 29.1C12.1 29.1 9.3 27.1 9.3 25C9.3 22.9 12.1 20.9 15.2 20.9C15.5 20.9 15.5 20.9 15.2 20.6C12.8 17.8 12.4 14.4 14.5 13.1C16.1 12.1 18.6 12.7 20.8 14.5C21.4 15 21.4 15 21.4 14.7C21.4 12.9 22.2 10.7 23.4 9.7C25.9 7.3 29.3 9.8 29.6 14.4C29.6 15 29.6 15 29.9 14.7C32.1 12.7 34.9 12.1 36.5 13.1C38.5 14.4 38.3 17.6 36 20.3C35.5 20.9 35.5 20.9 35.8 20.9C38.9 20.9 41.7 22.9 41.7 25C41.7 27.1 38.9 29.1 35.8 29.1C35.5 29.1 35.5 29.1 36 29.7C37.8 31.9 38.4 34.4 37.4 36C36.1 38.1 32.7 37.7 29.9 35.3C29.6 35 29.6 35 29.6 35.6C29.4 39.2 27.1 41.8 24.8 41.2z") }+ val NoiseRidges by lazy { shape("noiseridges", 50f, "M13.6 38.9C12.3 38.6 11.3 37.5 11.1 36.2C11 36 11 34.9 11 33.4C11 30.5 11 30.6 12.4 29.2C13.6 28 14.3 27.5 16.8 26.5C25.3 22.9 30.2 19.6 33.2 15.6C34.2 14.3 35.2 12.4 35.5 11.1C35.6 10.9 35.7 11 35.8 11.3C36.1 13.7 34.7 16.7 32.1 19.3C31 20.5 30.2 21.1 27.7 22.9C19.4 28.9 16.8 33.3 18.5 38.9C18.6 39 14.2 39.1 13.6 38.9zM23.3 38.7C21.3 34.6 23.1 31.7 31.1 26C34.8 23.3 37.3 20.8 38.7 18.1C39 17.5 39 17.5 39 26.7C39 33 39 36 38.9 36.2C38.7 37.4 37.9 38.4 36.7 38.8C36.3 39 36.3 39 29.8 39C23.4 39 23.4 39 23.3 38.7zM11 20.2C11 16.2 11 14 11.1 13.8C11.3 12.5 12.4 11.4 13.7 11.1C14 11 15.5 11 23.2 11C32.4 11 32.4 11 32.3 11.1C32.1 11.9 31 13.6 30.2 14.6C27.4 17.8 23 20.6 15.6 23.7C13.4 24.6 12.5 25.1 11.5 25.9C11.3 26.1 11 26.2 11 26.2C11 26.2 11 23.5 11 20.2z") }+ val HalftoneFull by lazy { shape("halftonefull", 50f, "M8.8 38.9C8.4 38.7 8.4 39.5 8.4 26C8.4 16.4 8.5 13.5 8.5 13.3C8.6 13.1 8.9 13 9.7 13C11.1 13 10.9 11.6 10.9 24C11 36.1 10.9 35 11.7 35.7C12.4 36.3 12.3 36.3 15.8 36.3C19 36.4 19.8 36.4 21.3 36.7C23.6 37.1 24.8 37.8 24.8 38.7C24.8 39 24.8 39 16.8 39C10.4 39 8.9 39 8.8 38.9zM26.3 38.9C26.2 38.7 26.5 38 26.9 37.8C28 36.8 30.4 36.4 35.3 36.3C38.9 36.3 39 36.3 39.7 35.5C40.2 34.8 40.2 35.9 40.2 24C40.2 15.8 40.2 13.4 40.3 13.3C40.4 13.1 40.6 13 41.5 13C42.8 13 42.7 11.3 42.7 26C42.7 38.6 42.7 38.6 42.5 38.8C42.2 39 42.2 39 34.3 39C28.8 39 26.4 39 26.3 38.9zM24.2 36.7C21.7 35.5 19 35 15.5 34.9C13.5 34.8 13.4 34.8 13.1 34.2C12.9 33.8 12.9 11.8 13.1 11.4C13.4 10.9 13.5 10.9 15.2 10.9C18.2 10.9 20.4 11.4 22.7 12.7C23.4 13.1 24.7 13.9 24.7 14C24.7 14.1 24.7 19.2 24.7 25.5L24.7 37L24.2 36.7zM26.4 25.5L26.4 14L27 13.5C29.9 11.7 32.4 10.9 35.9 10.9C37.6 10.9 37.9 11 38.1 11.7C38.2 12 38.1 33.7 38.1 34C37.8 34.8 37.7 34.9 35.5 34.9C32.1 35 29.5 35.5 27 36.7L26.4 37L26.4 25.5z") }+ val HalftoneScreen by lazy { shape("halftonescreen", 50f, "M24.2 39.6L24.2 38.2L23.4 38.1C17.7 37.4 13 33.3 11.5 27.8C11.2 27 11 25.7 11 25.3C11 25 11 25 9.6 25L8.2 25L8.2 24L8.2 23L9.6 23C11 23 11 23 11 22.7C11 22.3 11.2 21 11.5 20.2C13 14.7 17.7 10.6 23.4 9.9L24.2 9.8L24.2 8.4L24.2 7.1L25.1 7.1L26.1 7.1L26.1 7.6C26.2 7.9 26.2 8.5 26.2 8.9L26.2 9.8L27 9.9C31.7 10.5 35.8 13.4 37.9 17.6C38.7 19.2 39.1 20.6 39.3 22.7C39.4 23 39.4 23 40.7 23L42.1 23L42.1 24L42.1 25L40.7 25C39.4 25 39.4 25 39.3 25.3C39.1 27.4 38.7 28.8 37.9 30.4C35.8 34.6 31.7 37.5 27 38.1L26.2 38.2L26.2 39.1C26.2 39.5 26.2 40.1 26.1 40.4L26.1 40.9L25.1 40.9L24.2 40.9L24.2 39.6zM24.2 34.4C24.2 33.4 24.2 32.6 24.2 32.6C24.1 32.6 23.9 32.5 23.6 32.5C20.6 31.9 18.1 29.8 17.1 26.9C16.9 26.3 16.6 25.4 16.6 25.1C16.6 25 17.2 25 20.4 25L24.2 25L24.2 28.8L24.2 32.6L25.2 32.6L26.1 32.6L26.1 34.4C26.1 36.1 26.1 36.2 26.2 36.2C26.5 36.2 27.6 36 28.2 35.8C32.9 34.7 36.5 30.6 37.2 25.9C37.4 24.9 37.6 25 35.6 25L33.8 25L33.8 24L33.8 23L35.6 23C37.6 23 37.4 23.1 37.2 22.1C36.5 17.4 32.9 13.3 28.2 12.2C27.6 12 26.5 11.8 26.2 11.8C26.1 11.8 26.1 11.9 26.1 13.6L26.1 15.4L25.2 15.4L24.2 15.4L24.2 19.2L24.2 23L20.4 23C17.2 23 16.6 23 16.6 22.9C16.6 22.6 16.9 21.7 17.1 21.1C18.1 18.2 20.6 16.1 23.6 15.5C23.9 15.5 24.1 15.4 24.2 15.4C24.2 15.4 24.2 14.6 24.2 13.6C24.2 11.9 24.2 11.8 24.1 11.8C23 11.8 20.8 12.5 19.4 13.2C15.9 15.1 13.4 18.8 13 22.5L13 23L14.8 23L16.6 23L16.6 24L16.6 25L14.8 25L13 25L13 25.5C13.5 30.7 17.9 35.3 23.3 36.1C24.3 36.2 24.2 36.5 24.2 34.4zM26.2 32.5C26.1 32.5 26.1 30.8 26.1 28.7L26.1 25L29.9 25C34.2 25 33.8 24.9 33.6 25.8C33 28.6 30.9 31.1 28.1 32.1C27.4 32.3 26.2 32.6 26.2 32.5zM26.1 19.3C26.1 17.2 26.1 15.5 26.2 15.5C26.3 15.4 27.3 15.6 27.8 15.8C30.7 16.8 33 19.3 33.6 22.2C33.8 23.1 34.2 23 29.9 23L26.1 23L26.1 19.3z") }+ val HalftoneNews by lazy { shape("halftonenews", 50f, "M12.3 38.9C11.2 38.6 10.3 37.8 10 36.7C9.8 36.1 9.8 11.8 10 11.5C10.2 11 9.3 11 20.4 11C31.5 11 30.6 11 30.9 11.5C31 11.6 31 11.6 31 23.7C31.1 32 31 36 31 36.3C30.8 37.5 29.9 38.6 28.6 38.9C28.1 39 12.8 39 12.3 38.9zM30.3 38.9C31.5 38.6 32.4 37.6 32.6 36.6C32.7 36.4 32.7 32.7 32.7 25.4L32.7 14.5L34.2 14.5C36 14.5 36.1 14.5 36.4 15C36.5 15.3 36.5 15.3 36.5 25.7C36.5 34.4 36.5 36.1 36.4 36.5C36.2 37.6 35.2 38.6 34 38.9C33.4 39.1 29.8 39 30.3 38.9zM28.2 25.9C28.5 25.7 28.5 24.5 28.2 24.2C27.9 23.9 13 23.9 12.7 24.2C12.4 24.5 12.4 25.7 12.7 25.9C13 26.2 27.9 26.2 28.2 25.9zM28.2 20.9C28.5 20.7 28.5 19.5 28.2 19.2C27.9 18.9 13 18.9 12.7 19.2C12.4 19.5 12.4 20.7 12.7 20.9C13 21.2 27.9 21.2 28.2 20.9zM28.1 16.2C28.3 16.1 28.4 15.8 28.4 15.2C28.4 14 29.3 14.1 20.4 14.1C11.6 14.1 12.5 14 12.5 15.2C12.5 15.8 12.5 16 12.7 16.2C12.9 16.3 27.9 16.3 28.1 16.2z") }+ val ChromaPerspective by lazy { shape("chromaperspective", 50f, "M20 33.1L15.5 30.5L15.5 25L15.5 19.5L20 16.9L24.5 14.3L24.5 19.7C24.5 22.6 24.5 27.4 24.5 30.3L24.5 35.7L20 33.1zM25.5 25C25.5 19.1 25.5 14.3 25.6 14.3C25.6 14.3 27.6 15.5 30 16.9L34.5 19.5L34.5 25L34.5 30.5L30 33.1C27.6 34.5 25.6 35.7 25.6 35.7C25.5 35.7 25.5 30.9 25.5 25z") }+ val ChromaDisplace by lazy { shape("chromadisplace", 50f, "M13.7 38.9C12.5 38.7 11.6 37.8 11.1 36.6C11 36.3 11 35.9 11 25C11 14.1 11 13.7 11.1 13.4C11.5 12.3 12.2 11.6 13.2 11.2C13.7 11 13.7 11 22.4 11C27.2 11 31.2 11 31.2 11C31.2 11 28.4 17.3 25 25L18.8 39L16.4 39C15 39 13.9 39 13.7 38.9zM22.6 38.9C22.7 38.9 25.5 32.6 28.9 24.9L35.1 11L35.7 11C37.4 11 38.8 12.3 39 14C39 14.4 39 14.4 33.5 26.7L28.1 39L25.3 39C23.2 39 22.6 39 22.6 38.9zM32 38.9C32.1 38.6 38.9 23.2 39 23.2C39 23.2 39 26.1 39 29.8C39 36.3 39 36.3 38.8 36.8C38.4 37.7 37.7 38.5 36.7 38.8C36.3 39 31.9 39.1 32 38.9z") }+ // the drawing guide's kinds+ val GuideGrid by lazy { shape("guidegrid", 50f, "M14.5 33.9C13.2 33.6 12.2 32.7 11.7 31.4C11.5 31 11.5 31 11.5 27.7L11.5 24.5L18.5 24.5L25.5 24.5L25.5 29.2L25.5 34L20.2 34C16 34 14.8 34 14.5 33.9zM26.5 29.3L26.5 24.5L33.5 24.5L40.5 24.5L40.5 27.7C40.5 31 40.5 31 40.3 31.4C39.9 32.6 39.1 33.4 37.9 33.8C37.5 34 37.5 34 32 34L26.5 34L26.5 29.3zM11.5 20.3C11.5 17 11.5 17 11.7 16.6C12.1 15.4 12.9 14.6 14.1 14.2C14.5 14 14.5 14 20 14L25.5 14L25.5 18.7L25.5 23.5L18.5 23.5L11.5 23.5L11.5 20.3zM26.5 18.7L26.5 14L32 14C37.5 14 37.5 14 37.9 14.2C39.1 14.6 39.9 15.4 40.3 16.6C40.5 17 40.5 17 40.5 20.3L40.5 23.5L33.5 23.5L26.5 23.5L26.5 18.7z") }+ val GuideIsometric by lazy { shape("guideisometric", 50f, "M20.2 33.2C17.9 31.9 16 30.8 16 30.7C16 30.7 17.9 29.6 20.2 28.3L24.5 25.9L24.5 28.3C24.5 29.7 24.5 31.9 24.5 33.3L24.5 35.7L20.2 33.2zM25.5 30.8C25.5 25.9 25.5 25.9 25.8 26C28.1 27.4 33.9 30.8 33.9 30.8C33.9 30.8 25.7 35.6 25.6 35.7C25.5 35.7 25.5 33.5 25.5 30.8zM30.2 27.5C28 26.2 26.1 25 26.1 25C26.1 25 34.2 20.3 34.4 20.2C34.5 20.2 34.5 21.9 34.5 25.1C34.5 27.7 34.5 29.9 34.5 29.9C34.4 29.9 32.5 28.8 30.2 27.5zM15.5 24.9C15.5 22.3 15.5 20.1 15.5 20.1C15.6 20.1 23.9 24.9 23.9 25C23.9 25 15.6 29.8 15.5 29.8C15.5 29.8 15.5 27.6 15.5 24.9zM20.3 21.7C18 20.3 16.1 19.2 16.1 19.2C16.1 19.2 18 18.1 20.3 16.7L24.5 14.3L24.5 16.8C24.5 18.1 24.5 20.4 24.5 21.7L24.5 24.1L20.3 21.7zM25.5 19.2C25.5 16.5 25.5 14.3 25.6 14.3C25.8 14.4 34 19.2 34 19.3C34 19.3 26 23.9 25.7 24C25.5 24.1 25.5 24.1 25.5 19.2z") }+ val GuideSymmetry by lazy { shape("guidesymmetry", 50f, "M13 34.9C11.7 34.6 10.6 33.6 10.2 32.4C9.9 31.6 9.9 17.4 10.2 16.6C10.6 15.5 11.4 14.6 12.6 14.2C13 14 13 14 18.5 14L24 14L24 24.5L24 35L18.7 35C14.5 35 13.3 35 13 34.9zM25 34.5L25 34L30.4 34C35.7 34 35.7 34 36.1 33.8C36.9 33.5 37.5 32.9 37.8 32.1C38.1 31.5 38.1 17.5 37.8 16.9C37.5 16.1 36.9 15.5 36.1 15.2C35.7 15 35.7 15 30.4 15L25 15L25 14.5L25 14L30.5 14C36 14 36 14 36.4 14.2C37.6 14.6 38.4 15.5 38.8 16.6C39 17.1 39 17.1 39 24.5C39 31.9 39 31.9 38.8 32.4C38.4 33.5 37.6 34.4 36.4 34.8C36 35 36 35 30.5 35L25 35L25 34.5z") }+ // QuickShape's kinds+ val ShapeLine by lazy { shape("shapeline", 28f, "M9.2 19.4C8.6 19.1 8.3 18.5 8.5 17.9C8.6 17.7 14.9 9.8 15.6 9C16.5 8 18.1 9 17.6 10.2C17.4 10.7 10.5 19.2 10.2 19.4C9.8 19.5 9.4 19.5 9.2 19.4z") }+ val ShapePolyline by lazy { shape("shapepolyline", 28f, "M13.3 20.9C12.9 20.7 12.8 20.4 12.8 19.9C12.8 19.5 12.8 19.5 14.2 17.2C14.9 15.9 15.6 14.8 15.5 14.8C15.5 14.8 14.6 15 13.4 15.4C12.1 15.8 11.2 16.1 11 16.1C10.3 16.1 9.8 15.2 10.2 14.5C10.5 14 15 7.5 15.1 7.3C15.8 6.7 16.9 7.1 16.9 8.1C16.9 8.5 17 8.3 15.3 10.8C13.5 13.3 13.7 13.1 13.8 13.1C14.7 12.8 17.7 11.9 17.9 11.9C18.5 11.9 19 12.4 18.9 13C18.9 13.2 16.1 18.2 14.8 20.3C14.4 20.9 13.9 21.1 13.3 20.9z") }+ val ShapeArc by lazy { shape("shapearc", 28f, "M8.6 17.4C8 17.2 7.9 16.6 8.1 15.5C8.6 12.6 11.1 10.5 14 10.5C17.2 10.5 19.9 13.1 20 16.2C20 17.1 19.7 17.5 19 17.5C18.3 17.5 18.1 17.2 18 16.3C17.9 14.8 17.1 13.6 15.8 12.9C13.2 11.6 10.3 13.3 10 16.3C10 16.9 9.9 17.1 9.5 17.3C9.3 17.5 8.8 17.5 8.6 17.4z") }+ val ShapeEllipse by lazy { shape("shapeellipse", 28f, "M12.9 18.9C7.4 18.1 5.6 12.9 9.9 10.2C12.2 8.7 15.8 8.7 18.1 10.1C22.7 13.1 20.3 18.8 14.2 18.9C13.7 18.9 13.1 18.9 12.9 18.9zM15.6 16.8C18.3 16.1 19.3 13.9 17.7 12.3C15.9 10.7 12.1 10.7 10.3 12.3C7.8 14.7 11.5 17.8 15.6 16.8z") }+ val ShapeCircle by lazy { shape("shapecircle", 28f, "M13.1 19.9C10.1 19.3 8.1 17 8.1 14C8.1 11.6 9.4 9.6 11.5 8.6C13 7.9 15 7.9 16.5 8.6C19.8 10.1 21 14.3 18.9 17.4C18.1 18.5 16.9 19.4 15.5 19.8C15 19.9 13.5 20 13.1 19.9zM15.2 17.9C16.9 17.3 18 15.8 18 14C18 12.8 17.7 12 16.8 11.2C14.3 8.6 10 10.4 10 14C10 16.7 12.6 18.7 15.2 17.9z") }+ val ShapeTriangle by lazy { shape("shapetriangle", 28f, "M9.1 19C8.4 18.8 7.9 18.3 7.6 17.6C7.3 17.1 7.3 16.1 7.6 15.6C7.7 15.3 11.6 10.5 12.2 9.8C13.1 8.9 14.7 8.8 15.6 9.7C15.9 9.9 19.9 14.8 20.3 15.3C21.1 16.5 20.5 18.4 19.1 18.9C18.6 19.2 9.7 19.2 9.1 19zM18.5 17C18.8 16.7 18.7 16.5 18 15.7C14.4 11.3 14.3 11.1 14 11.1C13.7 11.1 13.7 11.1 10 15.7C9.3 16.5 9.2 16.7 9.5 17C9.8 17.2 18.2 17.2 18.5 17z") }+ val ShapeQuad by lazy { shape("shapequad", 28f, "M10 19C8.3 18.8 7.1 17.2 7.4 15.5C7.5 15.2 8.9 11 9 10.7C9.4 9.8 10.2 9.2 11.1 9C11.4 9 16.6 9 16.9 9C17.8 9.2 18.6 9.8 19 10.7C19.1 10.9 20.5 15.2 20.6 15.4C20.6 15.6 20.6 16.2 20.6 16.4C20.4 17.7 19.4 18.8 18.1 19C17.9 19 17.8 19 14 19C11.8 19 10 19 10 19zM18 16.9C18.4 16.8 18.6 16.4 18.6 16C18.6 15.8 18.6 15.8 17.9 13.7C17.5 12.6 17.2 11.6 17.2 11.5C17 11.3 16.8 11.1 16.5 11C16.4 11 16 11 14 11C12 11 11.6 11 11.5 11C11.2 11.1 11 11.2 10.9 11.4C10.8 11.5 10.6 12.2 10.1 13.7C9.4 15.8 9.4 15.8 9.4 16C9.4 16.5 9.6 16.8 10 17C10.2 17 10.2 17 14 17C17.9 17 17.9 17 18 16.9z") }+ val ShapeRect by lazy { shape("shaperect", 28f, "M10.3 19C9.1 18.9 8 17.9 7.8 16.6C7.7 16.3 7.7 11.7 7.8 11.4C8 10.2 8.9 9.3 10.1 9C10.4 9 17.6 9 17.9 9C19.1 9.3 20 10.2 20.2 11.4C20.3 11.7 20.3 16.3 20.2 16.6C20 17.6 19.3 18.5 18.3 18.9C17.8 19 18.1 19 14.1 19C12.1 19 10.4 19 10.3 19zM17.7 17.1C17.9 17 18.1 16.8 18.3 16.5C18.3 16.4 18.3 16.4 18.3 14C18.3 11.6 18.3 11.6 18.3 11.5C18.1 11.2 17.9 11 17.7 10.9C17.5 10.9 17.5 10.9 14 10.9C10.5 10.9 10.5 10.9 10.3 10.9C10 11 9.7 11.3 9.7 11.6C9.6 11.8 9.6 16.2 9.7 16.4C9.7 16.7 10 17 10.3 17.1C10.5 17.1 17.5 17.1 17.7 17.1z") }+ // the brush studio's tabs+ val StudioStroke by lazy { shape("studiostroke", 50f, "M19.1 37.2C13.5 35.7 12.8 27.9 18.1 25.5C19.3 25 19.1 25 25.3 24.9C30.8 24.9 30.8 24.9 31.2 24.7C33.1 23.7 33.1 21 31.1 20C30.7 19.8 30.7 19.8 24 19.8C17.4 19.7 17.3 19.7 17.1 19.6C15.7 18.9 15.7 17.1 17.1 16.4C17.4 16.2 30.9 16.2 31.6 16.4C37.1 18 37.8 25.5 32.6 27.9C31.4 28.5 31.7 28.4 25.7 28.4C22.1 28.4 20.3 28.5 20.1 28.5C17.6 29 17.2 32.5 19.5 33.6C19.8 33.8 19.8 33.8 23.2 33.8C27 33.8 26.9 33.8 27.5 34.3C28.4 35 28.1 36.8 27 37.2C26.5 37.4 19.8 37.4 19.1 37.2z") }+ val StudioStabilize by lazy { shape("studiostabilize", 50f, "M23.9 33.3C18.2 32.4 15 26.3 17.6 21.1C21 14.5 30.8 15.2 33.2 22.3C35.1 28.2 30.1 34.2 23.9 33.3zM23.8 28.1C23.9 28 24.4 27.5 25.4 26.4L26.8 24.8L29.1 24.8C31.7 24.7 31.7 24.7 31.9 24.2C32.2 23.7 32 23.2 31.6 22.9C31.3 22.6 26.1 22.6 25.7 22.8C25.6 22.9 24.9 23.7 24.2 24.5L22.9 26.1L21.1 26.1C18.9 26.1 18.7 26.1 18.4 26.7C18.1 27.2 18.4 27.9 18.9 28.1C19.2 28.2 23.6 28.2 23.8 28.1z") }+ val StudioTaper by lazy { shape("studiotaper", 50f, "M28.2 30C26.3 29.7 24.8 29 22.4 27.4C20.1 25.9 19.5 25.6 18.5 25.6C17.1 25.6 15.7 26.5 13.8 28.7C13.4 29.1 13.4 29.1 13.7 28.1C15.6 21.4 20.5 18.6 25.6 21.2C26.4 21.6 27.2 22.1 28.9 23.2C30.7 24.5 31.6 24.9 32.7 24.9C34.1 24.9 35.5 23.8 36.9 21.4C37.1 21.1 37.2 20.9 37.2 20.9C37.3 20.9 36.9 22.6 36.6 23.3C34.9 28.2 32 30.6 28.2 30z") }+ val StudioRendering by lazy { shape("studiorendering", 50f, "M16.2 33.7C15.2 33.4 14.7 32.4 15.2 31.4C15.3 31.3 16.4 29.4 17.7 27.3C18.9 25.1 21 21.6 22.2 19.5C25 14.9 24.9 15 25.9 15C26.7 15 26.9 15.2 28 17.1L28.9 18.6L24.5 26.2L20.2 33.8L18.3 33.8C17.1 33.8 16.4 33.8 16.2 33.7zM22.3 33.7C22.4 33.6 30 20.4 30 20.4C30 20.4 31.1 22.3 32.6 24.8C32.8 25.1 32.8 25.1 30.3 29.4L27.8 33.8L25 33.8C22.7 33.8 22.3 33.8 22.3 33.7zM29.9 33.8C29.9 33.8 33.8 26.9 33.8 26.9C33.9 26.8 36.6 31.6 36.7 31.8C36.9 32.6 36.4 33.5 35.5 33.7C35.2 33.8 29.9 33.9 29.9 33.8z") }+ val StudioWet by lazy { shape("studiowet", 50f, "M23.5 32.9C21.7 32.5 20.1 31.3 19.3 29.6C18.3 27.4 18.8 25.3 21.3 20.8C22.1 19.4 24.4 15.5 24.6 15.3C24.7 15.2 26.2 17.6 27.4 19.7C29.7 23.6 30.6 25.9 30.5 27.6C30.3 31 26.9 33.6 23.5 32.9zM24.1 30.6C24.9 30.2 24.7 28.9 23.5 27.7C22.9 27.1 22.7 26.7 22.6 26C22.4 25.3 22.5 23.9 22.7 22.4C22.8 21.8 22.9 21.3 22.9 21.3C22.9 21.3 22.5 22 22.1 22.8C20.4 26.4 20.1 27.7 20.8 29.2C21.5 30.4 23.1 31.1 24.1 30.6z") }+ val StudioColor by lazy { shape("studiocolor", 50f, "M19.8 33.4C19.3 33.4 18.4 33.1 18 32.9C17.6 32.8 17.6 32.8 20.1 30.3C24.9 25.6 24.4 26 24.5 26.5C24.7 29.3 24.4 31.4 23.5 32.8C23.2 33.2 23.2 33.2 22.7 33.3C22 33.5 20.5 33.5 19.8 33.4zM29.3 28.9C26.3 25.8 26 25.5 26.1 25.5C26.4 25.4 29.1 25.4 29.8 25.4C31.1 25.6 32.2 26 32.9 26.5C33.2 26.8 33.5 28.4 33.4 29.4C33.3 30.4 32.8 32.3 32.6 32.2C32.6 32.2 31.1 30.7 29.3 28.9zM25.2 32.1C25.2 32.1 25.3 31.8 25.4 31.5C25.7 30.6 25.8 29.7 25.8 28.2L25.8 26.8L26.2 27.2C26.4 27.5 27 28 27.4 28.4L28.1 29.2L27.7 29.8C27 30.7 25.2 32.3 25.2 32.1zM20.3 28C19.5 27.3 17.8 25.7 18 25.5C18 25.5 18.1 25.5 18.2 25.6C19.2 25.9 20.8 26.1 22.2 26L23.3 26L22.3 27C20.8 28.5 20.9 28.5 20.3 28zM20.2 24.7C19 24.6 17.6 24.1 17.1 23.6C16.4 23.1 16.4 20.2 17.1 18.4C17.2 18.2 17.3 17.9 17.3 17.9C17.3 17.9 18.8 19.5 20.7 21.3C24 24.7 24 24.7 23.8 24.7C23.3 24.8 20.7 24.8 20.2 24.7zM31.7 24.6C30.9 24.3 29.4 24.1 27.9 24.1L26.7 24.2L27.6 23.2C29.2 21.7 29 21.7 29.7 22.2C30.3 22.7 31.5 23.9 31.9 24.4C32.1 24.7 32.1 24.7 31.7 24.6zM25.5 24C25.5 24 25.5 23.5 25.4 22.9C25.3 20.4 25.7 18.2 26.6 17.2C27 16.7 29.2 16.5 30.8 16.9C31.3 17 32.3 17.4 32.3 17.4C32.3 17.4 29.1 20.6 26.6 23C26.1 23.6 25.6 24.1 25.5 24zM23 22.2C21.7 20.8 21.7 21 22.4 20.2C23 19.4 24.5 18 24.7 18C24.7 18 24.7 18.2 24.6 18.5C24.3 19.6 24.2 20 24.2 21.8C24.2 22.7 24.2 23.4 24.2 23.4C24.2 23.4 23.6 22.8 23 22.2z") }+ val StudioDynamics by lazy { shape("studiodynamics", 50f, "M16.3 33C14.1 30.2 13.8 25.6 15.6 22.1C17.1 19 20 16.9 23.4 16.2C24.4 16 26.6 16 27.6 16.2C30.1 16.7 32.2 17.9 33.9 19.9C34.3 20.3 35 21.2 34.9 21.2C34.9 21.2 32.4 22.2 32.3 22.2C32.3 22.2 32.2 22 32.1 21.8C29.5 17.9 24.4 16.6 20.2 18.6C17.6 19.8 15.7 22.3 15.1 25.1C14.6 27.2 15.1 30.3 16.2 32.5C16.4 32.9 16.5 33.2 16.5 33.2C16.5 33.2 16.4 33.1 16.3 33zM23.3 29.9C23.2 29.9 22.6 28.8 22.6 28.7C22.6 28.5 22.8 28.3 23.3 28C23.9 27.7 23.9 27.6 23.9 27.4C23.9 26.9 24.8 26 25.4 26C25.5 26 27.7 25.1 30.4 24.1C33.1 23 35.3 22.1 35.3 22.1C35.3 22.2 33.5 23.6 31.2 25.4C29 27.2 27.1 28.7 27 28.8C26.6 29.3 25.6 29.6 25.1 29.4C24.8 29.3 24.8 29.3 24.3 29.6C23.8 29.9 23.5 30 23.3 29.9zM34.9 29C33.5 28.4 33.6 28.5 33.6 27.2C33.6 26.6 33.6 25.9 33.5 25.6C33.5 25.3 33.5 25 33.5 25C33.5 25 34.1 24.5 34.7 24C36 22.9 35.9 22.9 36.2 24C36.6 25.4 36.7 27.3 36.5 28.7C36.3 29.6 36.4 29.6 34.9 29zM26.2 28.6C26.7 28.3 26.8 27.5 26.3 27C25.5 26.1 24.1 27.3 24.7 28.3C25 28.7 25.7 28.9 26.2 28.6z") }+ val StudioStylus by lazy { shape("studiostylus", 50f, "M23.5 33.3C18 32.3 15 26.3 17.4 21.3C20.5 15 29.5 15 32.6 21.3C35.6 27.5 30.3 34.5 23.5 33.3zM26.2 31.3C27.2 31.1 27.9 30.6 27.9 30.2C27.9 30.1 27.1 26 27 25.6C26.9 25.5 26.9 25.5 26.4 25.5C26.1 25.6 25.5 25.6 25 25.6C24.5 25.6 23.9 25.6 23.6 25.5C23.1 25.5 23.1 25.5 23 25.6C22.9 26 22.1 30.1 22.1 30.2C22.1 31 24.4 31.6 26.2 31.3zM26.3 24.7C26.5 24.7 26.7 24.7 26.7 24.7C26.8 24.6 25.7 19.8 25.6 19.4C25.5 19 24.7 18.9 24.4 19.3C24.4 19.4 23.2 24.5 23.2 24.6C23.2 24.8 25.3 24.9 26.3 24.7z") }+ val StudioProperties by lazy { shape("studioproperties", 50f, "M18.4 28.6C18 28.4 17.9 28.1 17.9 27.7C17.9 26.7 19.3 26.4 19.7 27.4C20 28.2 19.1 29 18.4 28.6zM21.6 28.5C20.9 28.1 20.9 27.4 21.5 26.9C21.8 26.7 30.6 26.7 31.1 26.8C31.9 27.1 31.9 28.2 31.2 28.6C30.8 28.8 21.9 28.7 21.6 28.5zM18.3 24.6C18 24.4 17.9 24.2 17.9 23.9C17.9 22.6 19.6 22.5 19.7 23.7C19.8 24.5 19 25 18.3 24.6zM21.5 24.6C20.9 24.2 20.9 23.3 21.6 23C22 22.8 30.9 22.8 31.2 23C31.8 23.3 31.8 24.1 31.4 24.5C31.2 24.7 31.2 24.7 26.4 24.7C21.7 24.8 21.7 24.8 21.5 24.6zM18.3 20.8C17.9 20.5 17.7 19.8 18 19.4C18.7 18.7 19.8 19.1 19.7 20.1C19.7 20.8 18.9 21.2 18.3 20.8zM21.6 20.8C20.9 20.5 20.9 19.6 21.5 19.2C21.7 19.1 21.7 19.1 26.4 19.1C31.2 19.1 31.2 19.1 31.4 19.3C31.8 19.8 31.8 20.5 31.2 20.8C30.9 21 21.9 21 21.6 20.8z") }+ val StudioMaterials by lazy { shape("studiomaterials", 50f, "M24.8 38.2C24.4 38.1 14.8 32.6 14.3 32.3C13.6 31.7 13.2 31.1 13.1 30.2C13 29.4 13 20.1 13.1 19.5C13.3 18 13.2 18.1 18.9 14.9C24.4 11.7 24.2 11.8 25.4 11.8C26.5 11.8 26.3 11.7 31.9 14.9C37.3 17.9 37.3 18 37.6 19.1C37.7 19.7 37.6 30.6 37.5 31C37.1 31.9 37 32 31.2 35.3C25.5 38.5 25.6 38.5 24.8 38.2zM24.4 31.3C24.4 28.3 24.4 26.8 24.4 26.8C24.3 26.8 23.9 27 23.4 27.2C22.9 27.5 22.4 27.7 22.4 27.7C22.4 27.7 21.7 26.2 21.7 26.2C21.7 26.2 22.1 26 22.6 25.7C23.1 25.5 23.5 25.3 23.5 25.3C23.5 25.2 15 20.4 15 20.4C15 20.4 14.9 22.4 14.9 24.9C14.9 27.4 15 29.5 15 29.5C15 29.5 15.3 29.3 15.8 29.1C16.2 28.9 16.5 28.8 16.5 28.8C16.5 28.8 16.7 29.1 16.9 29.5L17.3 30.2L16.6 30.6C16.2 30.8 15.9 31 15.9 31C16 31 24.3 35.8 24.4 35.8C24.4 35.8 24.4 33.8 24.4 31.3zM30.6 33.4C32.9 32.1 34.8 31 34.8 31C34.9 31 34.6 30.8 34.2 30.6L33.4 30.2L33.8 29.5C34 29.1 34.2 28.8 34.2 28.8C34.2 28.8 34.6 28.9 35 29.1C35.4 29.3 35.8 29.5 35.8 29.5C35.8 29.5 35.8 27.4 35.8 24.9C35.8 22.4 35.8 20.4 35.8 20.4C35.7 20.4 27.3 25.2 27.3 25.3C27.3 25.3 27.6 25.5 28.1 25.7C28.6 26 29 26.2 29 26.2C29.1 26.2 28.4 27.6 28.3 27.7C28.3 27.7 27.9 27.5 27.3 27.2L26.3 26.7L26.3 31.2C26.3 33.8 26.3 35.8 26.3 35.8C26.4 35.8 28.3 34.7 30.6 33.4zM18 29C17.8 28.6 17.7 28.2 17.7 28.2C17.7 28.2 18.3 27.9 19.1 27.5L20.5 26.8L20.9 27.5C21.1 27.9 21.3 28.3 21.2 28.3C21.2 28.3 18.4 29.7 18.4 29.7C18.4 29.7 18.2 29.4 18 29zM30.9 29C30.1 28.6 29.5 28.3 29.5 28.3C29.5 28.3 29.6 27.9 29.8 27.5L30.2 26.8L31.6 27.5C32.4 27.9 33.1 28.2 33.1 28.2C33.1 28.3 32.3 29.7 32.3 29.7C32.3 29.7 31.7 29.4 30.9 29zM25.4 21.6L26.2 21.6L26.2 22.6C26.2 23.1 26.2 23.6 26.2 23.6C26.4 23.5 34.8 18.7 34.7 18.7C34.7 18.7 26.8 14.2 26.6 14.1C26.2 13.9 26.2 13.8 26.2 14.9L26.2 15.9L25.4 15.9L24.6 15.9L24.6 14.9C24.6 13.8 24.6 13.9 24.2 14.1C24 14.2 16.1 18.7 16 18.7C16 18.7 17.9 19.8 20.3 21.1L24.5 23.6L24.5 22.6L24.6 21.6L25.4 21.6zM24.6 18.8L24.6 17.2L25.4 17.2L26.2 17.2L26.2 18.8L26.2 20.4L25.4 20.4L24.6 20.4L24.6 18.8z") }+ val StudioPreview by lazy { shape("studiopreview", 50f, "M19.8 31.9C18.3 31.9 17.7 31.6 16.9 30.8C15.8 29.7 15.6 28.9 15.6 25C15.6 21.1 15.8 20.3 16.9 19.2C18.1 18 18.4 18 25.9 18C31 18.1 31.3 18.1 32 18.4C33.1 18.9 34 20 34.2 21.3C34.4 22 34.4 28 34.2 28.7C33.9 30.3 32.7 31.6 31.2 31.8C30.6 32 21.3 32 19.8 31.9zM28.7 27.2C29.9 27 30.9 26.5 31.9 25.4C32.8 24.5 32.9 24.4 32.4 24.7C30.7 25.8 29.2 25.6 26.8 24.1C25.6 23.4 25.3 23.3 24.8 23.1C22.8 22.3 20.8 22.5 19.1 23.6C18.7 23.9 17.5 24.9 17.3 25.3C17.2 25.5 17.2 25.5 17.4 25.3C18.2 24.8 19 24.5 19.9 24.5C21 24.5 21.6 24.8 23.3 25.8C25.5 27.1 27 27.5 28.7 27.2z") }+ val StudioAbout by lazy { shape("studioabout", 50f, "M23.9 33.3C18.2 32.4 15 26.3 17.6 21.1C21 14.5 30.8 15.2 33.2 22.3C35.1 28.2 30.1 34.2 23.9 33.3zM25.5 30.7C25.9 30.6 26.2 30.3 26.3 30C26.6 29.5 26.6 23.9 26.4 23.5C25.9 22.4 24.4 22.4 23.9 23.5C23.7 24 23.8 29.6 24 30C24.2 30.6 24.9 30.8 25.5 30.7zM25.7 21.7C26.8 21.2 26.7 19.8 25.7 19.3C24.4 18.6 23.2 20.3 24.2 21.4C24.6 21.8 25.2 21.9 25.7 21.7z") }+ val StudioPad by lazy { outline("studio-pad", 2.6f, "M4 16.5C6 10 8.5 5.5 10 7c1.4 1.4-2.6 9-1 10s4.2-8 5.8-7c1.5.9-1.8 7.2-.3 7.9 1.2.6 2.8-1.6 3.9-3.4") }+ val GrainMoving by lazy { shape("grainmoving", 50f, "M17 38.9C13.7 38.5 11 35.5 11 32.4C11 31.9 11 31.9 12.4 31.2C16.2 29.4 20.3 29.3 25.5 31C30.7 32.7 35.3 32.8 38.5 31.2L38.9 31L38.9 31.9C38.9 35.3 36.9 37.9 33.6 38.8C33 39 33 39 25.2 39C20.9 39 17.2 39 17 38.9zM31.2 30.4C29.7 30.2 28 29.8 25.8 29.1C20.3 27.3 16 27.4 11.8 29.4C11.4 29.6 11 29.8 11 29.8C11 29.8 10.9 29.2 10.9 28.5C10.9 26.9 10.9 27.1 12.5 26.3C16.3 24.5 20.4 24.4 25.4 26.1C28.5 27.1 30.1 27.4 32.8 27.4C35.2 27.4 36.7 27.1 38.4 26.4C38.7 26.2 38.9 26.1 38.9 26.1C38.9 26.1 38.9 26.7 38.9 27.5C38.9 29.1 39 28.9 38.2 29.3C36.4 30.2 33.8 30.6 31.2 30.4zM30.8 25.4C29.2 25.2 28 24.9 25.9 24.2C20.4 22.4 15.9 22.5 11.8 24.5C11.4 24.7 11 24.9 11 24.9C11 24.9 10.9 24.4 10.9 23.7C10.9 22.2 10.9 22.3 11.8 21.8C15.6 19.7 20 19.5 25.4 21.3C30.7 23 35 23.1 38.4 21.6L38.9 21.3L38.9 22.7L38.9 24L38.3 24.4C36.3 25.3 33.5 25.7 30.8 25.4zM31.8 20.7C29.9 20.6 27.5 20.1 25.9 19.4C20.9 17.6 16 17.7 11.8 19.7C11.4 19.9 11 20.1 11 20.1C10.9 20.1 11 17.1 11.1 16.7C11.7 13.7 14.1 11.5 17.1 11.1C17.4 11 20 11 25.3 11C33 11 33 11 33.6 11.2C35.7 11.8 37.3 13 38.2 14.9C38.8 16 39 16.9 38.9 18.3C38.9 19.2 38.9 19.2 38.5 19.4C36.9 20.3 34 20.9 31.8 20.7z") }+ val GrainTexturized by lazy { shape("graintexturized", 50f, "M16.8 38.9C15.6 38.7 14.3 38.1 13.3 37.2C13.1 37 13.1 37 19 37L25 37L25 38L25 39L21.2 39C18.2 39 17.2 39 16.8 38.9zM27 32L27 25L28.5 25L30 25L30 32L30 39L28.5 39L27 39L27 32zM32 32L32 25L33.5 25L35 25L35 31.7L35 38.3L34.7 38.5C34.1 38.7 33.2 38.9 32.6 39L32 39L32 32zM37 31L37 25L38 25L39 25L39 28.8C39 32.8 39 33.2 38.6 34.2C38.4 35.1 37.8 36 37.2 36.7C37 36.9 37 36.9 37 31zM11.5 34.7C11.3 34 11 32.9 11 32.3C11 32 11 32 18 32L25 32L25 33.5L25 35L18.3 35C11.7 35 11.7 35 11.5 34.7zM11 28.5L11 27L18 27L25 27L25 28.5L25 30L18 30L11 30L11 28.5zM11 21.2C11 17.2 11 16.8 11.4 15.8C11.6 14.9 12.2 14 12.8 13.3C13 13.1 13 13.1 13 19L13 25L12 25L11 25L11 21.2zM15 18.3L15 11.7L15.3 11.5C15.9 11.3 16.8 11.1 17.4 11L18 11L18 18L18 25L16.5 25L15 25L15 18.3zM20 18L20 11L21.5 11L23 11L23 18L23 25L21.5 25L20 25L20 18zM25 21.5L25 20L32 20L39 20L39 21.5L39 23L32 23L25 23L25 21.5zM25 16.5L25 15L31.7 15L38.3 15L38.5 15.5C38.8 16.1 38.9 16.8 39 17.5L39 18L32 18L25 18L25 16.5zM25 12L25 11L28.8 11C33.7 11 34.2 11.1 35.9 12.2C37.2 13.1 37.6 13 31 13L25 13L25 12z") }+ val GlitchArtifact by lazy { shape("glitchartifact", 50f, "M13.8 38.9C12.5 38.7 11.3 37.5 11.1 36.2C11 35.9 11 34.3 11 31.6L11 27.5L9.2 27.2C8.2 27 7.4 26.8 7.4 26.8C7.4 26.8 11.3 26.1 16.1 25.3C20.9 24.5 24.8 23.8 24.8 23.8C24.8 23.7 20 22.9 14.1 21.9C8.2 20.9 3.4 20 3.4 20C3.4 20 4.1 19.9 5 19.7C5.8 19.6 7.5 19.3 8.7 19.1L11 18.7L11 16.4C11 13.9 11 13.7 11.4 13C11.8 12.1 12.4 11.6 13.4 11.2C13.8 11 13.8 11 24.8 11C32.5 11 35.8 11 36.1 11.1C37.5 11.3 38.7 12.5 38.9 13.8C39 14.1 39 15.7 39 18.4L39 22.5L39.5 22.6C39.8 22.7 40.5 22.8 41.1 22.9C41.6 23 42 23.1 42 23.1C41.7 23.2 39.1 23.6 35.2 24.3C33.1 24.7 31.3 25 31.3 25C31.3 25 34.5 25.6 38.4 26.3C42.3 26.9 45.4 27.5 45.4 27.5C45.4 27.5 40.6 28.4 39.2 28.6C39 28.6 39 28.6 39 32.4C39 36.2 39 36.2 38.8 36.6C38.4 37.7 37.7 38.4 36.6 38.8C36.2 39 36.2 39 25.2 39C19.1 39 14 39 13.8 38.9z") }+ val GlitchWave by lazy { shape("glitchwave", 50f, "M13.9 39C13.3 38.9 12.1 38.2 12.1 38C12.1 38 14.4 38 17.3 38C23.2 38 24.8 37.9 28.5 37.4C34.7 36.6 37.1 35.5 37.5 33.5C37.8 31.8 36.3 30.4 33.6 29.7C32.3 29.4 28.7 28.8 26.2 28.6C23.2 28.3 20.6 27.9 20.4 27.8C20.2 27.8 22 27.5 25.8 27.1C33.7 26.1 35.5 25.7 37 24.6C38.5 23.4 38.6 21.5 37.1 20.3C35.6 19.2 33.8 18.7 25.9 17.8C23.1 17.5 20.6 17.2 20.3 17.1C20 17 20.5 16.9 22.4 16.7C25.8 16.3 28.2 16.2 36.6 16L39 16L39 25.9C39 32.6 39 35.9 38.9 36.2C38.7 37.5 37.5 38.7 36.2 38.9C35.8 39 14.3 39 13.9 39zM11.9 34L11 33.9L11 23.9C11 12.6 11 13.7 11.4 12.8C11.9 12 12.9 11.2 13.8 11.1C14.4 11 35.6 11 36.2 11.1C36.6 11.2 37.3 11.5 37.7 11.8C37.9 12 37.9 12 37.5 12C37.3 12 35.6 12.1 33.7 12.1C23.8 12.2 17.2 13 14.4 14.5C12.3 15.5 11.9 17.5 13.4 18.9C14.7 20.3 16.5 20.7 24.5 21.7C28.3 22.1 30.3 22.4 30.3 22.4C30.2 22.5 28.1 22.8 24.6 23.2C20.2 23.7 17.6 24.1 16.3 24.4C13.6 25.2 12.1 26.7 12.6 28.4C13.1 30.6 15.9 31.5 24.6 32.4C27.3 32.7 29.9 33 29.9 33.1C29.9 33.2 26.5 33.6 23.9 33.9C22.7 33.9 14.4 34 11.9 34z") }+ val GlitchSignal by lazy { shape("glitchsignal", 50f, "M12.7 38.4C12.3 38.3 12 38 11.8 37.6C11.5 37 11.5 33.5 11.8 32.9C12.2 32.1 12.4 32 15 32C17.3 32 17.3 32 17.8 32.6C18.2 33 18.2 33.2 18.2 35.2C18.2 37.3 18.2 37.5 17.8 37.9C17.3 38.5 17.3 38.5 15 38.5C13.3 38.5 12.9 38.5 12.7 38.4zM23.5 38.4C23 38.3 22.6 38 22.4 37.5C22.3 37.2 22.3 37.1 22.3 30.5C22.3 23 22.3 23.5 22.8 23C23.2 22.5 23.2 22.5 25.6 22.5C28 22.5 28 22.5 28.4 23C28.9 23.5 28.9 23 28.9 30.5C28.9 38 28.9 37.5 28.4 38C28 38.5 28 38.5 25.7 38.5C24.6 38.5 23.6 38.5 23.5 38.4zM34.1 38.4C33.7 38.3 33.2 37.8 33.1 37.4C32.9 36.9 32.9 12.1 33.1 11.6C33.2 11.2 33.7 10.7 34.1 10.6C34.6 10.4 38.3 10.5 38.7 10.7C39 10.8 39.3 11.2 39.5 11.5C39.6 11.9 39.6 37.1 39.5 37.5C39.3 37.8 39 38.2 38.7 38.3C38.3 38.5 34.5 38.6 34.1 38.4z") }+ val GlitchDiverge by lazy { shape("glitchdiverge", 50f, "M9 27.3C9 16.8 9 16.8 9.2 16.4C9.7 15.1 10.6 14.3 11.9 14.1C12.2 14 15.4 14 22.6 14L32.9 14L20.9 26L9 37.9L9 27.3zM28.1 24L40 12.1L40 22.3C40 29.6 40 32.7 39.9 33C39.7 34.2 38.9 35.2 37.7 35.7C37.3 35.8 37.3 35.8 26.7 35.9L16.2 35.9L28.1 24z") }+ val BrushPaintedOn by lazy { shape("brushpaintedon", 50f, "M13.3 37.2C13 37.1 12.7 36.6 12.8 36.3C12.8 36.1 15.2 31.9 15.3 31.8C15.4 31.7 15.7 32 16.9 33.2C17.7 34 18.3 34.6 18.3 34.6C18.3 34.7 17.1 35.4 15.1 36.5C13.9 37.2 13.6 37.3 13.3 37.2zM30.7 35C30.6 35 30.5 34.5 30.4 34C30.2 32.8 30.2 32.8 29 32.6C27.7 32.3 27.7 32.3 28.9 32.1C30.3 31.8 30.2 31.9 30.5 30.5C30.6 30 30.7 29.6 30.7 29.5C30.7 29.5 30.8 29.9 30.9 30.4C31.2 31.9 31.1 31.8 32.6 32.1C33.2 32.2 33.5 32.3 33.5 32.3C33.4 32.3 33 32.4 32.5 32.5C31.1 32.8 31.2 32.7 30.9 34.1C30.7 35.2 30.7 35.2 30.7 35zM18.1 31.9C17.1 31 16.3 30.1 16.3 30.1C16.3 29.7 16.9 29.1 24.6 21.4C33.2 12.8 32.6 13.4 33.6 13.3C34.7 13.2 36 14 36.5 15.1C36.6 15.4 36.7 15.5 36.7 16.1C36.7 17.4 37.4 16.6 28.6 25.4C21 33 20.3 33.7 19.9 33.7C19.9 33.7 19 32.9 18.1 31.9zM12.7 29.8C12.7 29.6 12.4 28.5 12.2 27.4C11.6 24.4 11.9 24.7 8.6 24C7.4 23.7 6.4 23.5 6.3 23.5C6.3 23.5 7.3 23.3 8.5 23C11.1 22.5 11.2 22.5 11.5 22.1C11.8 21.8 11.7 22 12.3 19.2C12.5 18 12.8 17 12.8 17C12.8 16.9 13 18 13.3 19.3C14 22.6 13.6 22.3 17 23C18.3 23.3 19.3 23.5 19.2 23.5C19.1 23.5 18.1 23.8 16.9 24C13.6 24.7 14 24.3 13.3 27.6C13 28.8 12.8 29.9 12.8 30C12.8 30 12.7 30 12.7 29.8z") }+ val ModeLayer by lazy { shape("modelayer", 27f, 32f, "M10.3 22.2C9.6 22 9.2 21.6 9 21C8.9 20.8 8.9 20.8 8.9 16.6C8.9 12.4 8.9 12.4 9 12.2C9.2 11.6 9.7 11.2 10.3 11.1C10.5 11 18.6 11 18.8 11.1C19.4 11.3 19.8 11.7 20 12.3C20 12.5 20.1 20.4 20 20.8C19.9 21.5 19.3 22.1 18.6 22.2C18.4 22.2 10.5 22.2 10.3 22.2zM18.4 19.3C18.8 19.2 19.2 18.8 19.3 18.4C19.4 18.2 19.4 12.9 19.3 12.7C19.2 12.2 18.8 11.9 18.3 11.8C18.1 11.7 10.8 11.7 10.6 11.8C10.1 11.9 9.7 12.3 9.6 12.7C9.5 13 9.5 18.1 9.6 18.4C9.7 18.8 10.1 19.2 10.5 19.3C10.7 19.3 18.2 19.3 18.4 19.3zM3.6 16.2C3.3 14.7 3.3 14.6 3.1 14.5C2.9 14.3 2.8 14.3 1.4 14C0.7 13.9 0.1 13.7 0 13.7C0 13.7 0.5 13.6 1.3 13.4C3 13.1 3 13.1 3.2 12.8C3.3 12.7 3.3 12.7 3.6 11.2C3.7 10.5 3.9 9.9 3.9 9.9C3.9 9.9 4 10.5 4.1 11.2C4.4 12.7 4.4 12.7 4.6 12.8C4.7 13.1 4.7 13.1 6.4 13.4C7.2 13.6 7.7 13.7 7.7 13.7C7.7 13.7 7 13.9 6.3 14C4.9 14.3 4.8 14.3 4.6 14.5C4.5 14.6 4.4 14.7 4.1 16.2C4 16.9 3.9 17.5 3.9 17.5C3.8 17.5 3.7 16.9 3.6 16.2zM12.2 16.8C12 15.9 12.1 16 11.1 15.8C10.7 15.7 10.4 15.6 10.5 15.6C10.5 15.6 10.8 15.5 11.2 15.4C11.9 15.3 11.9 15.3 12 15.2C12.1 15.1 12.1 15.1 12.2 14.3C12.3 14 12.4 13.7 12.4 13.7C12.4 13.7 12.4 14 12.5 14.4C12.7 15.4 12.6 15.3 13.6 15.5C14 15.5 14.3 15.6 14.3 15.6C14.3 15.6 14 15.7 13.6 15.8C12.9 15.9 12.8 15.9 12.7 16.1C12.7 16.1 12.6 16.4 12.5 16.8C12.5 17.2 12.4 17.5 12.4 17.5C12.4 17.5 12.3 17.2 12.2 16.8z") }+ val ModePencil by lazy { shape("modepencil", 24f, 32f, "M3.7 22.3C3.5 22.3 3.4 22 3.4 21.8C3.4 21.8 4.6 19.7 4.8 19.4C4.8 19.4 5 19.6 5.6 20.2L6.4 21L6.1 21.2C5.1 21.7 4 22.3 4 22.3C3.9 22.4 3.8 22.4 3.7 22.3zM12.8 20.7C12.6 20 12.7 20 12 19.9C11.3 19.7 11.4 19.7 11.5 19.7C12.6 19.5 12.6 19.5 12.6 19.4C12.7 19.3 12.7 19.1 12.8 18.8C12.9 18.5 12.9 18.2 12.9 18.2C12.9 18.2 13 18.5 13 18.7C13.1 19.3 13.2 19.4 13.3 19.5C13.3 19.5 13.5 19.5 13.9 19.6C14.2 19.7 14.4 19.7 14.4 19.7C14.5 19.7 14.2 19.8 13.9 19.9C13.5 19.9 13.3 20 13.3 20C13.2 20.1 13.1 20.2 13 20.7C13 21 12.9 21.2 12.9 21.2C12.9 21.2 12.9 21 12.8 20.7zM6.2 19.5L5.3 18.6L5.4 18.3C5.6 18.1 5.6 18.1 9.6 14C12.3 11.4 13.7 10 13.8 9.9C14.3 9.5 14.9 9.5 15.4 9.9C16.1 10.4 16.3 11.2 15.9 11.9C15.8 12.1 7.8 20.1 7.6 20.2C7.6 20.3 7.4 20.3 7.3 20.4L7.2 20.5L6.2 19.5zM3.4 18.5C3.4 18.5 2.9 16.1 2.8 16C2.8 15.8 2.6 15.7 2.5 15.6C2.4 15.6 2 15.5 1.2 15.3C0.1 15.1 0 15.1 0 15C0 15 0.6 14.9 1.2 14.8C2.5 14.5 2.6 14.5 2.7 14.4C2.9 14.2 2.9 14.2 3.1 12.8C3.4 11.7 3.4 11.5 3.4 11.6C3.4 11.7 3.9 14.1 4 14.2C4 14.3 4.2 14.5 4.3 14.5C4.4 14.5 5 14.7 5.7 14.8C6.3 14.9 6.9 15.1 6.9 15.1C6.9 15.1 6.3 15.2 5.6 15.3C4.3 15.6 4.3 15.6 4.1 15.8C4 15.9 3.9 16 3.7 17.3C3.4 18.4 3.4 18.6 3.4 18.5z") }+ val AdjustKnob by lazy { shape("adjustknob", 50f, "M24.4 34.9C17.6 33.9 14.9 25.6 19.8 20.7C22.6 17.9 27 17.4 30.3 19.7C31.5 20.4 31.6 20.2 29.5 22C28.5 22.9 27.7 23.6 27.6 23.7C27.5 23.8 27.5 23.8 28.5 25C29.1 25.7 29.6 26.2 29.7 26.2C29.7 26.2 30.5 25.5 31.5 24.6C32.4 23.8 33.2 23.1 33.2 23.1C33.4 23 33.8 24.6 34 25.4C34.8 30.9 29.9 35.7 24.4 34.9zM14.4 30.8C13.8 30.6 13.5 30.2 13.3 29.1C11.7 21.5 17.4 14.3 25.2 14C33.3 13.6 39.7 21 38.1 29C37.9 30.4 37.2 31 36.2 30.8C35.3 30.6 34.9 29.8 35.2 28.6C36.7 21.4 29.7 15.1 22.6 17.4C17.9 19 15 24.2 16.2 28.8C16.6 30.1 15.6 31.2 14.4 30.8z") }+ val Apply by lazy { shape("apply", 50f, "M15.7 39.2C5.8 38.3 -0.3 28.3 3.5 19.2C5.4 14.7 9.6 11.4 14.7 10.6C15.5 10.4 32.9 10.4 34.4 10.5C43.6 11.3 49.7 20.4 46.9 29.2C45.2 34.7 40.3 38.6 34.5 39.2C33.9 39.2 16.3 39.3 15.7 39.2zM22.9 32.5C23.2 32.4 24.3 31.3 29.3 26.3C36.2 19.4 35.7 20.1 35.6 19C35.6 17.8 34.7 17 33.5 17C32.5 17 32.9 16.6 27.1 22.4L22 27.5L19.9 25.4C17.7 23.2 17.6 23.1 16.9 22.9C15.2 22.6 13.8 24.5 14.6 26C14.7 26.4 20.4 32.1 20.9 32.4C21.5 32.8 22.3 32.9 22.9 32.5z") }+ val Preview by lazy { shape("preview", 50f, "M23.2 39.2C23.1 39.2 22.6 39.2 22.2 39.1C17.5 38.7 12.8 36.4 9.3 33C9 32.7 7.3 30.8 5.5 28.8C3.7 26.7 2.2 25 2.1 25C1.9 24.7 9 16.8 10.6 15.5C16 11 23 9.4 29.7 11.1C33.4 12 36.8 13.9 39.5 16.5C39.9 16.9 41.7 18.9 43.5 20.9C45.3 22.9 46.8 24.6 46.9 24.7C47 24.8 47 24.8 43.8 28.4C42.1 30.4 40.3 32.4 39.8 32.8C36.4 36.3 31.9 38.5 27 39.1C26.3 39.2 23.7 39.3 23.2 39.2zM25.4 35C30 34.6 33.7 31.2 34.5 26.7C34.7 25.8 34.7 23.9 34.5 23C33.5 17.3 27.9 13.6 22.2 14.9C16.4 16.2 13 22.3 14.8 28C16.3 32.5 20.7 35.4 25.4 35z") }+ val CancelAdjust by lazy { shape("canceladjust", 50f, "M24 40.7C14.4 39.4 8.2 30.3 10.5 21C12.8 11.7 22.8 6.5 31.7 9.9C39.3 12.8 43.4 20.8 41.5 28.7C40.1 34.6 35.2 39.3 29.3 40.5C27.8 40.8 25.4 40.9 24 40.7zM28.3 36.6C36 35.1 40.2 26.7 36.8 19.6C36.5 19 35.8 17.8 35.6 17.7C35.5 17.7 18.8 34.4 18.9 34.5C19.1 34.7 19.9 35.2 20.7 35.6C21.8 36.1 23.3 36.6 24.6 36.8C25.2 36.9 27.6 36.8 28.3 36.6zM32.7 14.9C32.7 14.8 30.7 13.8 29.7 13.4C23 11.2 15.8 15.3 14.3 22.3C13.6 25.3 14.2 28.7 15.8 31.2L16.1 31.6L24.4 23.3C28.9 18.7 32.7 14.9 32.7 14.9z") }+ // the selection toolbar+ val Automatic by lazy { shape("automatic", 44f, "M21.2 30C20.8 29.3 20.5 28.8 20.5 28.8C20.4 28.8 19.9 29.1 19.2 29.5C18 30.3 18 30.3 18 30.1C18 30 17.9 29.4 17.8 28.7C17.8 28 17.7 27.4 17.7 27.4C17.7 27.4 17 27.5 16.3 27.6C15.5 27.7 14.8 27.7 14.8 27.7C14.8 27.7 15 27.1 15.3 26.4C15.6 25.6 15.8 25 15.8 25C15.7 25 15.1 24.8 14.4 24.5L13 24.1L14 23.1C14.5 22.6 15 22.1 15 22.1C15.1 22 15 21.9 14.1 21L13 19.9L14.4 19.5C15.1 19.2 15.7 19 15.8 19C15.8 19 15.6 18.4 15.3 17.6C15 16.9 14.8 16.3 14.8 16.3C14.8 16.3 15.5 16.3 16.3 16.4C17 16.5 17.7 16.6 17.7 16.6C17.7 16.6 17.8 16 17.8 15.3C17.9 14.6 18 14 18 13.9C18 13.7 18 13.7 19.2 14.5C19.9 14.9 20.4 15.2 20.5 15.2C20.5 15.2 20.8 14.7 21.2 14C21.6 13.4 22 12.8 22 12.8C22 12.8 22.4 13.4 22.8 14C23.2 14.7 23.5 15.2 23.5 15.2C23.6 15.2 24.1 14.9 24.8 14.5C26 13.7 26 13.7 26 13.9C26 14 26.1 14.6 26.2 15.3C26.2 16 26.3 16.6 26.3 16.6C26.3 16.6 27 16.5 27.7 16.4C28.5 16.3 29.2 16.3 29.2 16.3C29.2 16.3 29 16.9 28.7 17.6C28.4 18.4 28.2 19 28.2 19C28.3 19 28.9 19.2 29.6 19.5L31 19.9L29.9 21L28.9 22L29.8 22.9C30.3 23.3 30.7 23.8 30.8 23.9C31 24 31 24 29.7 24.5C28.9 24.7 28.3 25 28.2 25C28.2 25 28.4 25.6 28.7 26.4C29 27.1 29.2 27.7 29.2 27.7C29.2 27.7 28.5 27.7 27.7 27.6C27 27.5 26.3 27.4 26.3 27.4C26.3 27.4 26.2 28 26.2 28.7C26.1 29.4 26 30 26 30.1C26 30.3 26 30.3 24.8 29.5C24.1 29.1 23.6 28.8 23.5 28.8C23.5 28.8 23.2 29.3 22.8 30C22.4 30.6 22 31.2 22 31.2C22 31.2 21.6 30.6 21.2 30z") }+ val Freehand by lazy { shape("freehand", 44f, "M15.6 30.3C13.4 29.8 12.4 27.5 13.3 24.8C14.1 22.5 16.1 20 19.5 17C23.1 13.8 23.7 13.4 25 13.6C27.3 14 28 17.1 26 18.4C21.5 21.2 18.3 24.1 17.2 26.2C17 26.6 17 26.6 17.2 26.6C17.5 26.6 18.4 26.4 19.6 26C20.5 25.7 21.2 25.4 24.4 24.1C27.5 22.9 29.1 22.5 30 22.9C31.6 23.6 31.2 25.4 29 27.6C28.5 28.2 28.4 28.2 28.9 28.1C29.7 27.8 30.1 28.4 29.5 28.9C28.4 29.7 26.6 30.2 26.1 29.9C25.4 29.5 25.8 28.5 27.3 26.7C28.2 25.8 28.5 25.4 28.4 25.3C28.4 25.3 25.5 26.7 23.9 27.6C19.6 29.9 17.3 30.7 15.6 30.3z") }+ val RectangleShape by lazy { shape("rectangleshape", 44f, "M14.5 28.3C13.9 28.2 13.4 27.7 13.2 27.2C13 26.7 13 17.3 13.2 16.8C13.4 16.2 13.9 15.8 14.5 15.7C15 15.5 29 15.5 29.5 15.7C30.1 15.8 30.6 16.2 30.8 16.8C31 17.3 31 26.7 30.8 27.2C30.6 27.8 30.1 28.2 29.5 28.3C29 28.5 15 28.5 14.5 28.3z") }+ val EllipseShape by lazy { shape("ellipseshape", 44f, "M20.8 28.4C16.8 28 13.7 25.7 13.1 22.9C12.2 18.3 18.2 14.6 24.5 15.8C27.8 16.5 30.4 18.6 30.9 21.1C31.8 25.3 26.6 29 20.8 28.4z") }+ val SelectAdd by lazy { shape("selectadd", 44f, "M12.6 30C11.3 29.6 10.3 28.7 9.9 27.3C9.6 26.7 9.6 17.3 9.9 16.7C10.4 15 11.7 14 13.5 13.8C14.2 13.7 29.8 13.7 30.5 13.8C32.3 14 33.6 15 34.1 16.7C34.4 17.3 34.4 26.7 34.1 27.3C33.7 28.6 32.7 29.6 31.5 30C30.9 30.2 13.4 30.3 12.6 30zM23 25.1L23 23L25.1 23L27.1 23L27.1 22L27.1 21L25.1 21L23 21L23 18.9L23 16.9L22 16.9L21 16.9L21 18.9L21 21L18.9 21L16.9 21L16.9 22L16.9 23L18.9 23L21 23L21 25.1L21 27.1L22 27.1L23 27.1L23 25.1z") }+ val SelectRemove by lazy { shape("selectremove", 44f, "M12.6 30C11.3 29.6 10.3 28.7 9.9 27.3C9.6 26.7 9.6 17.3 9.9 16.7C10.4 15 11.7 14 13.5 13.8C14.2 13.7 29.8 13.7 30.5 13.8C32.3 14 33.6 15 34.1 16.7C34.4 17.3 34.4 26.7 34.1 27.3C33.7 28.6 32.7 29.6 31.5 30C30.9 30.2 13.4 30.3 12.6 30zM27.1 22L27.1 21L22 21L16.9 21L16.9 22L16.9 23L22 23L27.1 23L27.1 22z") }+ val Invert by lazy { shape("invert", 44f, "M16.6 30C15 29.7 13.7 28.4 13.4 26.8C13.3 26.2 13.3 17.8 13.4 17.2C13.7 16 14.4 15 15.4 14.4C16.3 14 15.9 14 22 14C28.1 14 27.7 14 28.6 14.4C29.6 15 30.3 16 30.6 17.2C30.7 17.8 30.7 26.2 30.6 26.8C30.4 28 29.6 29 28.6 29.5C27.7 30 28.2 30 22.2 30C19.2 30 16.6 30 16.6 30zM28 27.8C28.3 27.6 28.6 27.2 28.7 26.9C28.7 26.7 28.7 25.3 28.7 21.6L28.7 16.6L22.7 21.9C19.4 24.9 16.5 27.4 16.2 27.6L15.8 28L21.8 28C27.7 28 27.7 28 28 27.8z") }+ val Feather by lazy { shape("feather", 44f, "M20.6 32.9C20.3 32.9 20.1 32.8 20 32.8C20 32.8 20.2 31.5 20.3 31.5C20.3 31.4 20.5 31.5 20.7 31.5C21.2 31.6 22.7 31.6 23.2 31.5C23.4 31.5 23.5 31.5 23.5 31.5C23.6 31.5 23.8 32.8 23.8 32.8C23.7 33 21.5 33 20.6 32.9zM26.4 31.7C26.3 31.6 26.2 31.3 26.1 31.1C25.9 30.7 25.9 30.7 26.3 30.6C26.7 30.4 27.4 30 27.7 29.7C28.1 29.4 27.9 29.4 28.6 30.2C28.9 30.6 28.9 30.6 28.5 30.9C28 31.3 26.9 31.9 26.6 32C26.5 32 26.5 32 26.4 31.7zM16.7 31.7C16.1 31.3 15.5 30.9 15.2 30.6C14.9 30.4 14.9 30.4 15.4 29.9C15.6 29.6 15.8 29.4 15.8 29.4C15.9 29.4 16.1 29.5 16.4 29.7C16.6 29.9 17.1 30.2 17.4 30.4C17.6 30.5 17.9 30.7 17.9 30.7C17.9 30.8 17.3 31.9 17.3 31.9C17.2 31.9 17 31.8 16.7 31.7zM30.3 28.1C30.1 27.9 29.8 27.7 29.8 27.7C29.8 27.7 29.9 27.5 30 27.2C30.2 27 30.5 26.5 30.6 26.1C30.9 25.5 30.9 25.5 31.3 25.6C31.4 25.7 31.7 25.8 31.9 25.9C32.3 26 32.3 26 31.9 26.9C31.6 27.3 30.9 28.5 30.9 28.5C30.9 28.5 30.6 28.3 30.3 28.1zM12.9 28.2C12.8 28.1 12.6 27.6 12.3 27.2C12.1 26.8 11.7 25.9 11.7 25.8C11.7 25.8 12.9 25.4 13 25.4C13 25.4 13.1 25.6 13.2 25.8C13.3 26.1 13.6 26.5 13.8 26.9C14 27.2 14.1 27.5 14.1 27.6C14 27.6 13.2 28.2 13.1 28.3C13 28.3 13 28.3 12.9 28.2zM20.9 26.7C17.8 26 16.1 22.5 17.6 19.6C18.8 17.2 21.9 16.2 24.3 17.5C27.8 19.4 27.8 24.2 24.4 26.2C23.5 26.7 21.9 27 20.9 26.7zM32 23.2L31.6 23.1L31.5 21.9L31.5 20.6L32 20.6C32.3 20.5 32.6 20.5 32.7 20.5C32.8 20.4 32.9 20.5 32.9 20.5C33 20.7 33 22.4 33 22.8C32.9 23.3 33 23.3 32 23.2zM11 22.9C11 22.4 11 20.4 11.1 20.3C11.2 20.3 11.5 20.3 11.8 20.4C12.5 20.5 12.5 20.5 12.5 20.9C12.5 21.1 12.4 21.7 12.4 22.1C12.4 23 12.5 22.9 11.5 23C11.1 23.1 11.1 23.1 11 22.9zM30.6 17.7C30.4 17.5 30.2 17 30 16.7C29.8 16.4 29.6 16.2 29.6 16.1C29.6 16.1 30.6 15.3 30.7 15.3C30.9 15.3 32.2 17.6 32.1 17.7C32.1 17.7 31.5 18 30.9 18.2C30.9 18.2 30.7 18 30.6 17.7zM12.6 17.8C12.3 17.7 12 17.5 12 17.5C12 17.3 13.3 15.1 13.4 15.1C13.5 15.1 14.5 16 14.5 16C14.5 16.1 14.3 16.3 14.2 16.5C14.1 16.6 13.8 17.1 13.6 17.4L13.2 18.1L12.6 17.8zM27.3 14.1C27.1 13.9 26.6 13.6 26.3 13.5L25.7 13.1L26 12.6C26.1 12.2 26.2 11.9 26.2 11.9C26.3 11.8 28.5 13 28.7 13.2C28.7 13.3 27.9 14.3 27.8 14.4C27.8 14.4 27.6 14.2 27.3 14.1zM15.9 13.7C15.5 13.2 15.5 13.2 15.6 13C16.1 12.7 17.8 11.8 17.9 11.8C18 11.9 18.5 13 18.4 13.1C18.4 13.1 18.1 13.2 17.8 13.4C17.5 13.5 17 13.8 16.8 14C16.3 14.3 16.3 14.3 15.9 13.7zM20.8 12.4C20.8 12.2 20.7 11.1 20.7 11.1C20.8 11 23.4 11 23.4 11.1C23.5 11.2 23.5 11.8 23.3 12.3C23.3 12.5 23.3 12.5 22.1 12.5C21.3 12.5 20.9 12.4 20.8 12.4z") }+ /** A ring of short arcs around the feather icon's dot. */+ private val FEATHER_RING = buildString {+ val arcs = 12+ val r = 8.8f+ for (i in 0 until arcs) {+ val a0 = Math.PI * 2 * i / arcs+ val a1 = a0 + Math.PI * 2 / arcs * 0.55+ append("M${12f + r * kotlin.math.cos(a0).toFloat()} ${12f + r * kotlin.math.sin(a0).toFloat()}")+ append("A$r $r 0 0 1 ${12f + r * kotlin.math.cos(a1).toFloat()} ${12f + r * kotlin.math.sin(a1).toFloat()}")+ }+ }+ val SaveLoad by lazy { shape("saveload", 44f, "M18.7 27.8C16.9 26.1 14.8 24.1 14.1 23.4C12.6 22 12.3 21.6 11.9 20.9C10.8 18.7 11.3 16.1 13.1 14.5C15.8 12 20.1 12.8 21.7 16.1C21.8 16.4 21.9 16.6 21.9 16.7C21.9 16.7 22 16.8 22 16.8C22 16.8 22.1 16.7 22.1 16.7C22.1 16.5 22.5 15.7 22.7 15.4C24.5 12.8 28.1 12.2 30.6 14.1C32.5 15.7 33.2 18.5 32.2 20.7C31.8 21.5 31.5 21.9 30.7 22.7C26.7 26.5 22.1 30.9 22 30.9C22 31 20.5 29.6 18.7 27.8z") }+ val ColorFill by lazy { shape("colorfill", 44f, "M29.1 31.9C28.2 30.9 28.9 28.8 29.9 29.5C30.8 30.1 30.6 32.1 29.6 32.1C29.3 32.1 29.3 32.1 29.1 31.9zM20 29C16.1 28.3 12 22.9 13.2 20.2C13.5 19.7 20.9 12.2 21.4 12.1C23.6 11.1 27.5 13.5 29.6 17.1C30.8 19.2 31.2 21.3 30.9 24.2C30.7 26.9 30.4 27.9 29.7 27.6C29.4 27.4 29.3 27.1 29.2 26C29.2 24.2 29 23.2 28.5 21.8C28 20.1 27.5 19.5 26.4 18.6C25.6 18 25.6 17.8 26.4 17.9C27.9 18.1 28.5 17.8 28 17.1C26.1 14.1 22.3 12.2 21.5 13.8C20.8 15.1 23 18.2 25.8 20C26.1 20.2 26.5 20.5 26.6 20.6C27.1 21.1 27.5 23 27.2 23.6C27 24.1 22.2 28.8 21.8 28.9C21.3 29.1 20.6 29.1 20 29z") }+ val ClearSelection by lazy { shape("clearselection", 44f, "M19.1 31.5C19 31.4 19 31.4 19 31.4C19 31.3 19 31.3 19.1 31.2C19.2 30.6 18.9 30.4 17.9 30.4C17.3 30.4 17.3 30.4 16.9 30.1C16.3 29.4 16.3 29.4 17.4 27.7C17.9 27 18.3 26.4 18.3 26.3C18.3 26.3 17.7 26.7 17 27.2C15.2 28.4 15.2 28.4 14.2 26.8C13.5 25.7 13.3 25.5 13.4 25.2C13.5 24.9 13.5 24.9 13.3 25C13 25.2 13 25.2 12.3 24.8C11.2 24.2 11.2 24.1 12.7 23.1C13.3 22.7 14.8 21.7 15.9 20.8C18 19.3 18.1 19.2 18.5 19.3C18.7 19.3 24 24.5 24.2 24.9C24.5 25.4 24.5 25.5 22.8 27.6C21.8 29.1 21.5 29.4 20.5 30.4C19.3 31.6 19.3 31.6 19.1 31.5zM25.7 31.4C24 30.9 24.4 28.4 26.2 28.4C28.2 28.4 28.3 31.4 26.3 31.5C26.1 31.5 25.8 31.5 25.7 31.4zM29.5 29.4C28.9 29.2 28.6 28.4 29 27.9C29.5 26.9 30.9 27.3 30.9 28.4C30.9 29.1 30.2 29.6 29.5 29.4zM23.3 20.8C22.8 20.2 22.4 19.7 22.4 19.6C22.4 19.6 23.9 18.3 25.7 16.7C30.5 12.4 31.2 12 32.1 12.7C32.3 12.9 32.5 13.3 32.5 13.6C32.5 14 32.3 14.2 31.6 15.1C31 16 30.8 16.1 27.8 18.8C26 20.3 24.5 21.6 24.4 21.7C24.3 21.9 24.3 21.9 23.3 20.8z") }+ /** A disc with a ring of short rays, for selecting by colour. */+ private val AUTOMATIC = buildString {+ val rays = 16+ append("M")+ for (i in 0 until rays * 2) {+ val r = if (i % 2 == 0) 8.4f else 7f+ val a = Math.PI * i / rays+ append("${12f + r * kotlin.math.cos(a).toFloat()} ${12f + r * kotlin.math.sin(a).toFloat()} ")+ }+ append("z")+ }++ /** The frame the four ways' icons share. */+ private const val FRAME = "M6.6 6.2h10.8a1.6 1.6 0 0 1 1.6 1.6v8.4a1.6 1.6 0 0 1-1.6 1.6H6.6A1.6 1.6 0 0 1 5 16.2V7.8a1.6 1.6 0 0 1 1.6-1.6z"++ /** A checkerboard of squares cut out of a disc. */+ private val CHECKS = buildString {+ for (row in 0 until 4) for (col in 0 until 4) {+ if ((row + col) % 2 == 1) continue+ val x = 5.2f + col * 3.4f+ val y = 5.2f + row * 3.4f+ append("M$x ${y}h3.4v3.4h-3.4z")+ }+ }++ /** One path of an icon: filled (and stroked, to round its corners) or stroked only. */+ private class Part(val d: String, val width: Float, val fill: Boolean, val evenOdd: Boolean = false)++ /** A four-pointed sparkle centred at ([x], [y]), [r] from its centre to a point. */+ private fun star(x: Float, y: Float, r: Float): Part {+ val k = r * 0.28f+ return Part("M$x ${y - r}L${x + k} ${y - k} ${x + r} $y ${x + k} ${y + k} $x ${y + r} ${x - k} ${y + k} ${x - r} $y ${x - k} ${y - k}z", 0.8f, true)+ }++ private fun solid(name: String, vararg paths: String): ImageVector = icon(name, *paths.map { Part(it, 1.2f, true) }.toTypedArray())++ private fun outline(name: String, width: Float, vararg paths: String): ImageVector = icon(name, *paths.map { Part(it, width, false) }.toTypedArray())++ /** A filled shape drawn in a [frame] unit square (the frame it is shown in, padding and all). */+ private fun shape(name: String, frame: Float, d: String): ImageVector = shape(name, frame, frame, d)++ /** A filled shape drawn in a [width] x [height] unit frame. */+ private fun shape(name: String, width: Float, height: Float, d: String): ImageVector =+ icon(name, Part(d, 0f, true, evenOdd = true), viewport = width, viewportHeight = height)++ private fun icon(name: String, vararg parts: Part, viewport: Float = 24f, viewportHeight: Float = viewport): ImageVector {+ val b = ImageVector.Builder(name = name, defaultWidth = viewport.dp, defaultHeight = viewportHeight.dp, viewportWidth = viewport, viewportHeight = viewportHeight)+ for (p in parts) {+ b.addPath(+ pathData = addPathNodes(p.d),+ pathFillType = if (p.evenOdd) PathFillType.EvenOdd else PathFillType.NonZero,+ fill = if (p.fill) SolidColor(Color.White) else null,+ stroke = if (p.width > 0f) SolidColor(Color.White) else null,+ strokeLineWidth = p.width,+ strokeLineCap = StrokeCap.Round,+ strokeLineJoin = StrokeJoin.Round,+ )+ }+ return b.build()+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/InlineName.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/InlineName.ktnew file mode 100644index 0000000..a34521c--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/InlineName.kt@@ -0,0 +1,61 @@+package io.github.artcraftandroid.procraft.ui++import androidx.compose.foundation.text.BasicTextField+import androidx.compose.foundation.text.KeyboardActions+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.foundation.text.selection.LocalTextSelectionColors+import androidx.compose.foundation.text.selection.TextSelectionColors+import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.focus.onFocusChanged+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.text.TextRange+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.input.ImeAction+import androidx.compose.ui.text.input.TextFieldValue+import androidx.compose.ui.unit.TextUnit++/**+ * A name edited where it is shown: focused with all of it selected and the keyboard up; done on+ * the keyboard's return or when focus leaves, once. The selection is [color] at about a third, its+ * handles [color].+ */+@Composable+fun InlineName(name: String, color: Color, fontSize: TextUnit, modifier: Modifier = Modifier, onDone: (String) -> Unit) {+ var value by remember { mutableStateOf(TextFieldValue(name, TextRange(0, name.length))) }+ val focus = remember { FocusRequester() }+ var focused by remember { mutableStateOf(false) }+ var finished by remember { mutableStateOf(false) }+ val finish = {+ if (!finished) {+ finished = true+ onDone(value.text)+ }+ }+ LaunchedEffect(Unit) { focus.requestFocus() }+ val selection = TextSelectionColors(handleColor = color, backgroundColor = color.copy(alpha = 0.35f))+ CompositionLocalProvider(LocalTextSelectionColors provides selection) {+ BasicTextField(+ value,+ onValueChange = { value = it },+ modifier = modifier.focusRequester(focus).onFocusChanged {+ if (focused && !it.isFocused) finish()+ focused = it.isFocused+ },+ singleLine = true,+ textStyle = TextStyle(color = color, fontSize = fontSize),+ cursorBrush = SolidColor(color),+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),+ keyboardActions = KeyboardActions(onDone = { finish() }),+ )+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/LayersPanel.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/LayersPanel.ktnew file mode 100644index 0000000..3884217--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/LayersPanel.kt@@ -0,0 +1,813 @@+package io.github.artcraftandroid.procraft.ui++import androidx.compose.animation.core.Animatable+import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress+import androidx.compose.foundation.gestures.detectHorizontalDragGestures+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.foundation.lazy.itemsIndexed+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.clipToBounds+import androidx.compose.ui.draw.drawBehind+import androidx.compose.ui.draw.drawWithContent+import androidx.compose.ui.graphics.drawscope.translate+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.FilterQuality+import androidx.compose.ui.graphics.Shape+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.layout.boundsInWindow+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.IntRect+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.LayoutDirection+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.compose.ui.window.Popup+import androidx.compose.ui.window.PopupPositionProvider+import androidx.compose.ui.window.PopupProperties+import androidx.compose.ui.zIndex+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import io.github.artcraftandroid.procraft.core.LayerInfo+import io.github.artcraftandroid.procraft.core.LayerType+import kotlinx.coroutines.launch+import kotlin.math.abs+import kotlin.math.roundToInt++private val LayersWidth = 384.dp+private val RowHeight = 69.dp+/** A layer with a mask, and the mask, are a little shorter. */+private val MaskedRowHeight = 65.dp+private val RowGap = 1.dp+private val ListCorner = 8.dp+/** A group's row height, and how far in each level of group sits. */+private val GroupHeight = 44.dp+private val GroupIndent = 21.dp+private val GroupLine = Color(0xFF4E4E4E)+private val MaskOwnerRow = Color(0xFF2C5281)+/** Swiping a row left shows these buttons, each this wide, this far apart. */+private val SwipeButton = 82.dp+private val SwipeGap = 2.dp+private val SwipeFill = Color(0xFF3F3F3F)+private val SwipeInk = Color(0xFFC1C1C1)+private val SwipeDelete = Color(0xFFFF473D)+/** How far right a row slides to be picked. */+private val PickReach = 72.dp+/** A picked row (the current one stays blue). */+private val PickedRow = Color(0xFF2C5281)+private val LockedLetter = Color(0xFF808080)+/** The options never go higher than this from the window's top (the top bar and a gap). */+private val OptionsTop = 57.dp++/**+ * The layers panel: top layer first. Tap a layer to make it current, tap the current one for its+ * options, tap the blend letter for blend mode and opacity, hold and drag to reorder, swipe left+ * for lock, duplicate and delete, swipe right to pick it to act on with the current one (the+ * title's menu then groups, merges, shares, duplicates or deletes them).+ */+@Composable+fun LayersPanel(vm: CanvasViewModel, arrowX: Dp, modifier: Modifier = Modifier) {+ var options by remember { mutableStateOf<ULong?>(null) }+ var blendFor by remember { mutableStateOf<ULong?>(null) }+ // blend modes opening under a layer: the rows under it go at once and the panel grows over where+ // they were; closing, it shrinks back to them and they come back a moment later. [blendAt] is+ // the row they open under (-1 when nothing is moving), [belowShown] the rows under it.+ var blendAt by remember { mutableIntStateOf(-1) }+ var belowShown by remember { mutableFloatStateOf(1f) }+ val blendScope = rememberCoroutineScope()+ var blendSettled by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }+ fun changeBlend(id: ULong?) {+ if (id == blendFor) return+ val shown = vm.layers.filter { !vm.hidden(it) }+ val at = listOfNotNull(blendFor, id).map { b -> shown.indexOfFirst { it.id == b } }.filter { it >= 0 }.minOrNull() ?: -1+ val opening = id != null+ blendFor = id+ blendAt = at+ belowShown = 0f+ blendSettled?.cancel()+ blendSettled = blendScope.launch {+ kotlinx.coroutines.delay(if (opening) Motion.BLEND_OPEN_MS else Motion.BLEND_CLOSE_MS + Motion.BLEND_ROWS_WAIT_MS)+ androidx.compose.animation.core.animate(0f, 1f, animationSpec = Motion.blendRowsBack()) { v, _ -> belowShown = v }+ blendAt = -1+ }+ }+ var renaming by remember { mutableStateOf<ULong?>(null) }+ var swiped by remember { mutableStateOf<ULong?>(null) }+ var titleMenu by remember { mutableStateOf(false) }+ var deletingChosen by remember { mutableStateOf(false) }+ val context = androidx.compose.ui.platform.LocalContext.current+ val scope = rememberCoroutineScope()+ var dragId by remember { mutableStateOf<ULong?>(null) }+ var dragOffset by remember { mutableFloatStateOf(0f) }+ // where each row is in the window: for dropping a dragged row and placing the options+ val rows = remember { mutableMapOf<ULong, Rect>() }++ Popover(LayersWidth, arrowX, modifier) {+ // kept while they fade out+ val open = options?.let { id -> vm.layers.firstOrNull { it.id == id }?.let { l -> rows[id]?.let { l to it } } }+ val last = remember { arrayOfNulls<Pair<LayerInfo, Rect>>(1) }+ if (open != null) last[0] = open+ last[0]?.let { (l, row) -> LayerOptions(open != null, vm, l, row.center.y, onRename = { renaming = l.id }, onDone = { options = null }) }+ PanelHeader(+ "Layers",+ chevronOn = vm.anyPicked,+ onTitle = { titleMenu = !titleMenu },+ menu = {+ LayersTitleMenu(titleMenu, vm, onDismiss = { titleMenu = false }, onShare = {+ scope.launch {+ val files = vm.chosenLayerFiles()+ if (files.isNotEmpty()) shareFiles(context, files, "image/png")+ }+ }, onDelete = { deletingChosen = true })+ },+ ) {+ Box(Modifier.padding(top = 12.dp).size(40.dp, 41.dp).clickable { vm.addLayer() }, contentAlignment = Alignment.Center) {+ Icon(PcIcons.PlusMedium, contentDescription = "New layer", tint = Pc.PanelGlyph, modifier = Modifier.requiredSize(41.dp))+ }+ }+ // a layer added at the top of what shows comes in there, the rows under it sliding down,+ // rather than the list holding its place and leaving the new row out of sight above+ val list = rememberLazyListState()+ val ids = vm.layers.filter { !vm.hidden(it) }.map { it.id }+ val lastIds = remember { arrayOfNulls<List<ULong>>(1) }+ val before = lastIds[0]+ if (before != null && ids != before) {+ val added = ids.indices.firstOrNull { ids[it] !in before }+ if (added != null && added <= list.firstVisibleItemIndex) list.requestScrollToItem(added)+ }+ lastIds[0] = ids+ LazyColumn(+ Modifier.weight(1f, fill = false).padding(horizontal = 12.dp),+ state = list,+ verticalArrangement = Arrangement.spacedBy(RowGap),+ contentPadding = PaddingValues(bottom = 12.dp),+ ) {+ // a closed group's layers are left out+ val shown = vm.layers.filter { !vm.hidden(it) }+ itemsIndexed(shown, key = { _, l -> l.id.toLong() }) { index, l ->+ val dragging = dragId == l.id+ DisposableEffect(l.id) { onDispose { rows.remove(l.id) } }+ // the list's ends round; the rows between are square+ val shape = RoundedCornerShape(+ topStart = if (index == 0) ListCorner else 0.dp,+ topEnd = if (index == 0) ListCorner else 0.dp,+ bottomStart = if (index == shown.size - 1) ListCorner else 0.dp,+ bottomEnd = if (index == shown.size - 1) ListCorner else 0.dp,+ )+ Column(+ Modifier.animateItem(Motion.rowFade(), if (dragging || blendAt >= 0) null else Motion.rowMove(), Motion.rowFade())+ .onGloballyPositioned { rows[l.id] = it.boundsInWindow() }+ .zIndex(if (dragging) 1f else 0f).graphicsLayer {+ translationY = if (dragging) dragOffset else 0f+ alpha = if (blendAt in 0 until index) belowShown else 1f+ }+ .pointerInput(l.id) {+ if (l.kind == LayerType.MASK) return@pointerInput+ detectDragGesturesAfterLongPress(+ onDragStart = {+ dragId = l.id+ dragOffset = 0f+ swiped = null+ },+ onDrag = { change, amount ->+ change.consume()+ dragOffset += amount.y+ },+ onDragEnd = {+ rows[l.id]?.let { drop(vm, l, it.center.y + dragOffset, rows) }+ dragId = null+ dragOffset = 0f+ },+ onDragCancel = {+ dragId = null+ dragOffset = 0f+ },+ )+ },+ ) {+ val onTap = {+ swiped = null+ if (vm.anyPicked) {+ // picks give way to the layer tapped, the current one too+ vm.selectLayer(l.id)+ options = null+ } else if (l.current) {+ options = if (options == l.id) null else l.id+ changeBlend(null)+ } else {+ vm.selectLayer(l.id)+ options = null+ }+ }+ // renamed in place+ val name: @Composable (Color, Modifier) -> Unit = { ink, m ->+ if (renaming == l.id) {+ InlineName(l.name, ink, 17.sp, m) {+ vm.rename(l, it)+ renaming = null+ }+ } else {+ Text(l.name, color = ink, fontSize = 17.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = m)+ }+ }+ SwipeRow(vm, l, open = swiped == l.id, enabled = dragId == null, onOpen = { swiped = if (it) l.id else null }, onPick = { vm.pickLayer(l) }) {+ if (l.kind == LayerType.GROUP) {+ GroupRow(vm, l, shape, name, onTap) { vm.toggleCollapsed(l) }+ } else LayerRow(+ vm,+ l,+ shape,+ name,+ owner = vm.layers.any { it.current && it.kind == LayerType.MASK && it.parent == l.id },+ onTap = onTap,+ onBlend = {+ changeBlend(if (blendFor == l.id) null else l.id)+ options = null+ },+ )+ }+ // the blend modes open under the row, the panel growing as they fade in, and close back+ androidx.compose.animation.AnimatedVisibility(+ blendFor == l.id,+ // held at the top, uncovered as the panel grows and covered as it shrinks+ enter = androidx.compose.animation.expandVertically(Motion.blendOpenSize(), expandFrom = Alignment.Top) ++ androidx.compose.animation.fadeIn(Motion.blendOpen()),+ exit = androidx.compose.animation.shrinkVertically(Motion.blendCloseSize(), shrinkTowards = Alignment.Top) ++ androidx.compose.animation.fadeOut(Motion.blendClose()),+ ) { BlendEditor(vm, l) }+ }+ }+ // it moves down and up with the rows above it+ item(key = "background") {+ Box(+ Modifier.animateItem(null, if (dragId != null || blendAt >= 0) null else Motion.rowMove(), null)+ .padding(top = 10.dp).graphicsLayer { alpha = if (blendAt >= 0) belowShown else 1f },+ ) { BackgroundRow(vm) }+ }+ }+ }+ // the title menu's Delete asks first+ Alert(+ if (deletingChosen) Unit else null,+ title = { "Delete these layers?" },+ message = { "Undo brings them back." },+ action = "Delete",+ icon = PcIcons.Trash,+ onCancel = { deletingChosen = false },+ onAction = {+ vm.deletePicked()+ deletingChosen = false+ },+ )+}++/**+ * The title's menu, under it: Select All; Group and Merge (with layers picked); Share and+ * Duplicate; Delete.+ */+@Composable+private fun LayersTitleMenu(open: Boolean, vm: CanvasViewModel, onDismiss: () -> Unit, onShare: () -> Unit, onDelete: () -> Unit) {+ val picked = vm.anyPicked+ // mostly over the panel, whose rows the canvas's frosting doesn't blur: nearly solid+ LibraryMenu(+ open,+ androidx.compose.ui.graphics.TransformOrigin(0.5f, 0f),+ MenuPlace { a, size -> IntOffset(a.center.x - size.width / 2, a.bottom) },+ onDismiss,+ overPanel = true,+ ) {+ MenuItem(PcIcons.MenuSelectAll, "Select All") {+ onDismiss()+ vm.pickAllLayers()+ }+ MenuDivider()+ if (picked) {+ MenuItem(PcIcons.MenuGroup, "Group") {+ onDismiss()+ vm.groupPicked()+ }+ MenuItem(PcIcons.MenuMerge, "Merge") {+ onDismiss()+ vm.mergePicked()+ }+ MenuDivider()+ }+ MenuItem(PcIcons.MenuShare, "Share") {+ onDismiss()+ onShare()+ }+ MenuItem(PcIcons.MenuDuplicate, "Duplicate") {+ onDismiss()+ vm.duplicatePicked()+ }+ MenuDivider()+ MenuItem(PcIcons.MenuTrash, "Delete", Pc.MenuDanger) {+ onDismiss()+ onDelete()+ }+ }+}++/** Drops [l] where its row's middle came to rest: just above or below the row it is over. */+private fun drop(vm: CanvasViewModel, l: LayerInfo, y: Float, rows: Map<ULong, Rect>) {+ val unit = vm.unitOf(l)+ val others = vm.layers.filter { it.id !in unit && !vm.hidden(it) }.mapNotNull { o -> rows[o.id]?.let { o to it } }+ val (target, row) = others.firstOrNull { (_, r) -> y >= r.top && y < r.bottom }+ ?: others.minByOrNull { (_, r) -> abs(r.center.y - y) }+ ?: return+ vm.moveNextTo(l, target, above = y < row.center.y)+}++/**+ * A row that slides left to show Lock, Duplicate (not for a mask) and Delete, or a little right to+ * pick it ([onPick]), springing back.+ */+@Composable+private fun SwipeRow(+ vm: CanvasViewModel,+ l: LayerInfo,+ open: Boolean,+ enabled: Boolean,+ onOpen: (Boolean) -> Unit,+ onPick: () -> Unit,+ content: @Composable () -> Unit,+) {+ val buttons = if (l.kind == LayerType.MASK) 2 else 3+ // the row slides 6 past the buttons+ val reach = with(LocalDensity.current) { (SwipeButton * buttons + SwipeGap * (buttons - 1) + 6.dp).toPx() }+ val pickReach = with(LocalDensity.current) { PickReach.toPx() }+ val offset = remember { Animatable(0f) }+ val scope = rememberCoroutineScope()+ LaunchedEffect(open, reach) { offset.animateTo(if (open) -reach else 0f, Motion.swipeSettle()) }+ // the list only clips top and bottom; a slid row stops at its edge+ Box(Modifier.clipToBounds()) {+ if (offset.value < 0f) {+ Row(Modifier.matchParentSize(), horizontalArrangement = Arrangement.spacedBy(SwipeGap, Alignment.End)) {+ SwipeAction(if (l.locked) "Unlock" else "Lock", SwipeFill, SwipeInk) {+ vm.toggleLocked(l)+ onOpen(false)+ }+ if (l.kind != LayerType.MASK) SwipeAction("Duplicate", SwipeFill, SwipeInk) {+ vm.duplicate(l)+ onOpen(false)+ }+ // the only layer can't go: it is cleared instead+ val alone = vm.layers.count { it.kind != LayerType.MASK } == 1+ SwipeAction(if (alone) "Clear" else "Delete", SwipeDelete, Color.White) {+ if (alone) vm.clear(l) else vm.delete(l)+ onOpen(false)+ }+ }+ }+ Box(+ Modifier.offset { IntOffset(offset.value.roundToInt(), 0) }.pointerInput(l.id, open, enabled, reach) {+ if (!enabled) return@pointerInput+ detectHorizontalDragGestures(+ onHorizontalDrag = { change, amount ->+ change.consume()+ // closed, it goes right as far as picking takes+ scope.launch { offset.snapTo((offset.value + amount).coerceIn(-reach, if (open) 0f else pickReach)) }+ },+ onDragEnd = {+ if (offset.value > pickReach / 2f) {+ onPick()+ scope.launch { offset.animateTo(0f, Motion.swipeSettle()) }+ return@detectHorizontalDragGestures+ }+ val opened = offset.value < -reach / 2f+ if (opened == open) scope.launch { offset.animateTo(if (open) -reach else 0f, Motion.swipeSettle()) } else onOpen(opened)+ },+ onDragCancel = { scope.launch { offset.animateTo(if (open) -reach else 0f, Motion.swipeSettle()) } },+ )+ },+ ) { content() }+ }+}++@Composable+private fun SwipeAction(label: String, fill: Color, ink: Color, onClick: () -> Unit) {+ Box(+ Modifier.width(SwipeButton).fillMaxHeight().clip(RoundedCornerShape(8.dp)).background(fill).clickable(onClick = onClick),+ contentAlignment = Alignment.Center,+ ) {+ Text(label, color = ink, fontSize = 15.sp, fontWeight = FontWeight.Medium, maxLines = 1)+ }+}++/** A panel's title row, [height] tall: the title [start] in, its menu chevron, and [action] [end] from the right. */+@Composable+internal fun PanelHeader(+ title: String,+ start: Dp = 24.dp,+ end: Dp = 18.dp,+ height: Dp = 64.dp,+ chevron: Boolean = true,+ chevronOn: Boolean = false,+ onTitle: (() -> Unit)? = null,+ menu: @Composable () -> Unit = {},+ action: @Composable () -> Unit,+) {+ Box(Modifier.fillMaxWidth().height(height)) {+ Row(+ Modifier.align(Alignment.TopStart).padding(start = start, top = 19.dp)+ .then(if (onTitle != null) Modifier.clickable(interactionSource = null, indication = null, onClick = onTitle) else Modifier),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(title, color = Pc.PanelTitle, fontSize = 24.sp, fontWeight = FontWeight.Bold, maxLines = 1)+ menu()+ if (chevron) {+ Box(+ Modifier.padding(start = 10.dp).offset(y = (-1.5).dp).size(17.dp).clip(CircleShape)+ .background(if (chevronOn) Pc.RowSelected else Pc.ChevronDisc),+ contentAlignment = Alignment.Center,+ ) {+ Icon(PcIcons.ChevronDown, contentDescription = null, tint = Pc.ChevronGlyph, modifier = Modifier.size(13.dp))+ }+ }+ }+ Box(Modifier.align(Alignment.TopEnd).padding(end = end)) { action() }+ }+}++/** A row's name, where it always is; locked, a small padlock in the gap before it. */+@Composable+private fun LockedName(l: LayerInfo, ink: Color, name: @Composable (Color, Modifier) -> Unit, modifier: Modifier) {+ Box(modifier, contentAlignment = Alignment.CenterStart) {+ // the padlock's glyph ends 12 short of the name+ if (l.locked) Icon(PcIcons.LockRow, contentDescription = "Locked", tint = ink, modifier = Modifier.offset(x = 3.dp).size(17.dp))+ name(ink, Modifier.padding(start = 29.dp, end = 6.dp))+ }+}++/** A group's row: a line where a thumbnail would be, its name, its open or closed arrow and its box. */+@Composable+private fun GroupRow(vm: CanvasViewModel, l: LayerInfo, shape: Shape, name: @Composable (Color, Modifier) -> Unit, onTap: () -> Unit, onToggle: () -> Unit) {+ Row(+ Modifier.fillMaxWidth().height(GroupHeight).clip(shape)+ .background(if (l.current) Pc.RowSelected else if (l.picked) PickedRow else Pc.LayerRow)+ .clickable(onClick = onTap)+ .padding(start = GroupIndent * l.depth.toInt()),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ val ink = if (l.current || l.picked) Color.White else Pc.PanelTitle+ Box(Modifier.padding(start = 4.dp).size(93.dp, 4.dp).clip(RoundedCornerShape(2.dp)).background(GroupLine))+ LockedName(l, ink, name, Modifier.weight(1f))+ Box(Modifier.offset(x = 8.dp).size(44.dp, GroupHeight).clickable(onClick = onToggle), contentAlignment = Alignment.Center) {+ Icon(if (l.collapsed) PcIcons.ChevronRight else PcIcons.ChevronDown, contentDescription = if (l.collapsed) "Open" else "Close", tint = ink, modifier = Modifier.size(16.dp))+ }+ Box(Modifier.size(44.dp, GroupHeight).clickable { vm.toggleVisible(l) }, contentAlignment = Alignment.Center) {+ CheckBox(l.visible, if (l.current || l.picked) Color.White else Pc.CheckFill)+ }+ Spacer(Modifier.width(8.dp))+ }+}++@Composable+private fun LayerRow(+ vm: CanvasViewModel,+ l: LayerInfo,+ shape: Shape,+ name: @Composable (Color, Modifier) -> Unit,+ owner: Boolean,+ onTap: () -> Unit,+ onBlend: () -> Unit,+) {+ val mask = l.kind == LayerType.MASK+ val masked = vm.hasMask(l)+ Row(+ Modifier.fillMaxWidth().height(if (mask || masked) MaskedRowHeight else RowHeight).clip(shape)+ // the layer a selected mask belongs to shows a darker blue+ .background(if (l.current) Pc.RowSelected else if (l.picked) PickedRow else if (owner) MaskOwnerRow else Pc.LayerRow)+ .clickable(onClick = onTap)+ .padding(start = (if (l.clipped) 18.dp else 0.dp) + GroupIndent * l.depth.toInt()),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ val ink = if (l.current || l.picked) Color.White else Pc.PanelTitle+ if (l.clipped) Icon(PcIcons.Clip, contentDescription = "Clipped", tint = ink, modifier = Modifier.size(16.dp))+ // a mask's thumbnail and its layer's join into one, rounded only at the outer corners+ val corner = 4.dp+ val thumbShape = when {+ mask -> RoundedCornerShape(topStart = corner, topEnd = corner)+ masked -> RoundedCornerShape(bottomStart = corner, bottomEnd = corner)+ else -> RoundedCornerShape(corner)+ }+ val shift = when {+ mask -> 2.dp+ masked -> (-2).dp+ else -> 0.dp+ }+ Box(Modifier.padding(start = 4.dp).offset(y = shift)) { Thumb(vm, l, thumbShape) }+ LockedName(l, ink, name, Modifier.weight(1f))+ // the blend and visibility buttons overlap by 8, as on the reference; a mask has no blend+ if (mask) {+ Spacer(Modifier.width(36.dp))+ } else {+ Box(Modifier.offset(x = 8.dp).size(44.dp, 47.dp).clickable(onClick = onBlend), contentAlignment = Alignment.Center) {+ // a locked layer's mode is greyed+ val letter = if (l.locked && !l.current && !l.picked) LockedLetter else ink+ Text(blendCode(vm, l.blend), color = letter, fontSize = 14.sp, fontWeight = FontWeight.SemiBold)+ }+ }+ Box(Modifier.size(44.dp, 47.dp).clickable { vm.toggleVisible(l) }, contentAlignment = Alignment.Center) {+ CheckBox(l.visible, if (l.current || l.picked) Color.White else Pc.CheckFill)+ }+ Spacer(Modifier.width(8.dp))+ }+}++/** A layer's visibility box: filled with a check when shown, an outline when hidden. */+@Composable+private fun CheckBox(checked: Boolean, fill: Color) {+ val shape = RoundedCornerShape(5.dp)+ val tick = androidx.compose.ui.graphics.vector.rememberVectorPainter(PcIcons.Tick)+ Box(+ Modifier.size(18.dp)+ .graphicsLayer { compositingStrategy = androidx.compose.ui.graphics.CompositingStrategy.Offscreen }+ .clip(shape)+ .then(if (checked) Modifier.background(fill) else Modifier.border(1.5.dp, fill, shape))+ .drawWithContent {+ drawContent()+ if (!checked) return@drawWithContent+ // the tick is cut out of the box: the row shows through it+ val side = 14.dp.toPx()+ val inset = (size.width - side) / 2f+ val cut = androidx.compose.ui.graphics.Paint().apply { blendMode = androidx.compose.ui.graphics.BlendMode.DstOut }+ drawContext.canvas.saveLayer(Rect(Offset.Zero, size), cut)+ translate(inset, inset) { with(tick) { draw(Size(side, side)) } }+ drawContext.canvas.restore()+ },+ )+}++@Composable+private fun Thumb(vm: CanvasViewModel, l: LayerInfo, shape: Shape) {+ Box(+ Modifier.size(width = 93.dp, height = 61.dp).clip(shape)+ // a mask's thumbnail sits on white+ .then(+ when {+ l.alphaLock -> Modifier.drawBehind { checker() }+ l.kind == LayerType.MASK -> Modifier.background(Color.White)+ else -> Modifier.background(Pc.ThumbBackground)+ },+ ),+ contentAlignment = Alignment.Center,+ ) {+ // the thumbnail is what is drawn, fitted; small drawings show their pixels+ vm.thumbnails[l.id]?.let {+ Image(it, contentDescription = null, contentScale = ContentScale.Fit, filterQuality = FilterQuality.None, modifier = Modifier.fillMaxSize())+ }+ }+}++/** The transparency checkerboard behind thumbnails. */+private fun androidx.compose.ui.graphics.drawscope.DrawScope.checker() {+ val cell = 6.dp.toPx()+ drawRect(Color(0xFFFFFFFF))+ var y = 0+ while (y * cell < size.height) {+ var x = 0+ while (x * cell < size.width) {+ if ((x + y) % 2 == 1) drawRect(Color(0xFFD6D6D6), Offset(x * cell, y * cell), Size(cell, cell))+ x+++ }+ y+++ }+}++/**+ * The letters on a layer's row for its mode: a two-word name's initials (the second small), a+ * one-word name's first letter, or its first two where one letter is already taken.+ */+private fun blendCode(vm: CanvasViewModel, blend: UInt): String {+ val name = vm.blendModeList.firstOrNull { it.id == blend }?.name ?: return "N"+ if (name in TWO_LETTER_BLENDS) return name.take(2)+ val words = name.split(' ')+ return if (words.size == 1) name.take(1) else words[0].take(1) + words[1].take(1).lowercase()+}++private val TWO_LETTER_BLENDS = setOf("Darken", "Shade", "Lighten", "Subtract", "Divide", "Saturation")++@Composable+private fun BlendEditor(vm: CanvasViewModel, l: LayerInfo) {+ var opacity by remember(l.id) { mutableFloatStateOf(l.opacity) }+ Column(Modifier.fillMaxWidth().padding(top = 22.dp, bottom = 15.dp)) {+ Row(Modifier.padding(horizontal = 13.dp).fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {+ Text("Opacity", color = Pc.PanelTitle, fontSize = 17.sp, modifier = Modifier.weight(1f))+ Text(if (opacity >= 0.995f) "Max" else "${(opacity * 100).roundToInt()}%", color = Pc.PanelTitle, fontSize = 17.sp)+ }+ OpacitySlider(+ opacity,+ onChange = {+ opacity = it+ vm.setLayerOpacity(l, it, done = false)+ },+ onDone = { vm.setLayerOpacity(l, opacity, done = true) },+ )+ // the list opens with the layer's mode in its middle+ val list = rememberScrollState()+ val rowPx = with(LocalDensity.current) { 38.8.dp.toPx() }+ val listPx = with(LocalDensity.current) { 349.dp.toPx() }+ LaunchedEffect(l.id) {+ val i = vm.blendModeList.indexOfFirst { it.id == l.blend }.coerceAtLeast(0)+ list.scrollTo((i * rowPx - (listPx - rowPx) / 2f).roundToInt().coerceAtLeast(0))+ }+ Column(Modifier.padding(top = 11.dp).fillMaxWidth().height(349.dp).clip(RoundedCornerShape(12.dp)).background(Pc.LayerRow).verticalScroll(list)) {+ for (m in vm.blendModeList) {+ val chosen = m.id == l.blend+ val ink = if (chosen) Color.White else Pc.PanelTitle+ Row(+ Modifier.fillMaxWidth().height(38.8.dp).background(if (chosen) Pc.RowSelected else Color.Transparent)+ .clickable { vm.setBlend(l, m.id) }.padding(start = 21.dp, end = 20.5.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(m.name, color = ink, fontSize = 17.sp, maxLines = 1, modifier = Modifier.weight(1f))+ // drawn in a 22 frame: about 16 across, centred 31.5 in from the right+ PcIcons.BlendGlyphs[m.name]?.let { Icon(it, contentDescription = null, tint = ink, modifier = Modifier.size(22.dp)) }+ }+ }+ }+ }+}++/** A thin blue slider with a white knob, set by dragging anywhere along it. */+@Composable+internal fun OpacitySlider(value: Float, onChange: (Float) -> Unit, onDone: () -> Unit) {+ val change by rememberUpdatedState(onChange)+ val done by rememberUpdatedState(onDone)+ Box(+ Modifier.padding(horizontal = 13.dp, vertical = 2.dp).fillMaxWidth().height(16.dp)+ .pointerInput(Unit) {+ awaitEachGesture {+ val down = awaitFirstDown()+ down.consume()+ change((down.position.x / size.width).coerceIn(0f, 1f))+ while (true) {+ val c = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break+ if (!c.pressed) break+ change((c.position.x / size.width).coerceIn(0f, 1f))+ c.consume()+ }+ done()+ }+ }+ .drawBehind {+ val y = size.height / 2f+ val h = 3.dp.toPx()+ drawRoundRect(Pc.SliderRest, Offset(0f, y - h / 2f), Size(size.width, h), CornerRadius(h / 2f))+ drawRoundRect(Pc.Accent, Offset(0f, y - h / 2f), Size(size.width * value, h), CornerRadius(h / 2f))+ val knob = Size(26.dp.toPx(), 15.dp.toPx())+ val x = (size.width * value).coerceIn(knob.width / 2f, size.width - knob.width / 2f)+ drawRoundRect(Color.White, Offset(x - knob.width / 2f, y - knob.height / 2f), knob, CornerRadius(knob.height / 2f))+ },+ )+}+/**+ * The current layer's options, left of the panel and centred on its row. What doesn't apply to+ * it is left out; lock, duplicate and delete are on the row's swipe.+ */+@Composable+private fun LayerOptions(open: Boolean, vm: CanvasViewModel, l: LayerInfo, rowY: Float, onRename: () -> Unit, onDone: () -> Unit) {+ val density = LocalDensity.current+ val place = remember(rowY, density) {+ OptionsPlace(with(density) { (-183).dp.roundToPx() }, rowY, with(density) { OptionsTop.roundToPx() })+ }+ MenuPresence(open, androidx.compose.ui.graphics.TransformOrigin(1f, 0.5f)) { look ->+ Popup(popupPositionProvider = place, onDismissRequest = onDone, properties = PopupProperties(focusable = true)) {+ Column(look.width(194.dp).clip(RoundedCornerShape(24.dp)).background(Pc.MenuFill).padding(vertical = 7.dp)) {+ val then = { f: () -> Unit -> { f(); onDone() } }+ Option("Rename", onClick = then(onRename))+ when (l.kind) {+ LayerType.GROUP -> {+ Option("Ungroup", onClick = then { vm.ungroup(l) })+ Option("Flatten", onClick = then { vm.flattenGroup(l) })+ }+ LayerType.MASK -> {+ Option("Select", onClick = then { vm.selectLayerContents(l) })+ Option("Fill Layer", enabled = !l.locked, onClick = then { vm.fillLayer(l) })+ Option("Clear", enabled = !l.locked, onClick = then { vm.clear(l) })+ Option("Invert", enabled = !l.locked, onClick = then { vm.invertLayer(l) })+ }+ else -> {+ Option("Select", onClick = then { vm.selectLayerContents(l) })+ Option("Copy", onClick = then { vm.copyLayerContents(l) })+ // a text layer's pixels come from its text+ if (!l.text) {+ Option("Fill Layer", enabled = !l.locked, onClick = then { vm.fillLayer(l) })+ Option("Clear", enabled = !l.locked, onClick = then { vm.clear(l) })+ }+ Option("Alpha Lock", checked = l.alphaLock) { vm.toggleAlphaLock(l) }+ Option("Mask", enabled = !vm.hasMask(l), onClick = then { vm.addMask(l) })+ if (l.canClip) Option("Clipping Mask", checked = l.clipped) { vm.toggleClipped(l) }+ // only while the drawing guide is on+ if (vm.guide?.on == true) {+ Option("Drawing Assist", checked = vm.guide?.assisted == true) { vm.setGuideAssisted(vm.guide?.assisted != true) }+ }+ if (!l.text) Option("Invert", enabled = !l.locked, onClick = then { vm.invertLayer(l) })+ Option("Reference", checked = l.reference) { vm.toggleReference(l) }+ }+ }+ if (l.text) {+ Option("Edit Text", enabled = !l.locked, onClick = then { vm.editText(l) })+ Option("Rasterize", enabled = !l.locked, onClick = then { vm.rasterize(l) })+ }+ if (l.kind != LayerType.MASK) {+ if (l.canMerge) Option("Merge Down", enabled = !l.locked, onClick = then { vm.mergeDown(l) })+ if (l.canCombine) Option("Combine Down", onClick = then { vm.combineDown(l) })+ }+ }+ }+ }+}++/** Puts the options left of the panel, centred on the row tapped and kept below the top bar. */+private class OptionsPlace(private val left: Int, private val rowY: Float, private val top: Int) : PopupPositionProvider {+ override fun calculatePosition(anchorBounds: IntRect, windowSize: IntSize, layoutDirection: LayoutDirection, popupContentSize: IntSize): IntOffset {+ val bottom = (windowSize.height - popupContentSize.height).coerceAtLeast(top)+ val y = (rowY - popupContentSize.height / 2f).roundToInt().coerceIn(top, bottom)+ return IntOffset(anchorBounds.left + left, y)+ }+}++@Composable+private fun Option(label: String, checked: Boolean? = null, enabled: Boolean = true, destructive: Boolean = false, onClick: () -> Unit) {+ Row(+ Modifier.fillMaxWidth().height(38.dp).clickable(enabled = enabled, onClick = onClick).padding(start = 19.dp, end = 16.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ val color = when {+ !enabled -> Pc.MenuDisabled+ destructive -> Color(0xFFFF453A)+ else -> Color.White+ }+ Text(label, color = color, fontSize = 17.sp, modifier = Modifier.weight(1f))+ if (checked == true) Icon(PcIcons.Tick, contentDescription = null, tint = color, modifier = Modifier.size(18.dp))+ }+}+@Composable+private fun BackgroundRow(vm: CanvasViewModel) {+ val bg = vm.background+ Row(+ Modifier.fillMaxWidth().height(50.dp).clip(RoundedCornerShape(17.dp)).background(Pc.BackgroundRow),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Row(Modifier.weight(1f).fillMaxHeight().clickable { vm.pickBackground() }, verticalAlignment = Alignment.CenterVertically) {+ Box(Modifier.padding(start = 4.dp).size(92.dp, 42.dp).clip(RoundedCornerShape(14.dp)).background(Color(bg.r, bg.g, bg.b)))+ Text("Background color", color = Pc.PanelTitle, fontSize = 17.sp, maxLines = 1, modifier = Modifier.weight(1f).padding(start = 14.dp))+ }+ Box(Modifier.size(44.dp, 41.dp).clickable { vm.toggleBackground() }, contentAlignment = Alignment.Center) {+ CheckBox(bg.visible, Pc.CheckFill)+ }+ Spacer(Modifier.width(8.dp))+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Motion.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Motion.ktnew file mode 100644index 0000000..b1a625d--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Motion.kt@@ -0,0 +1,520 @@+package io.github.artcraftandroid.procraft.ui++import androidx.compose.animation.core.Animatable+import androidx.compose.animation.core.AnimationSpec+import androidx.compose.animation.core.CubicBezierEasing+import androidx.compose.animation.core.Easing+import androidx.compose.animation.core.LinearEasing+import androidx.compose.animation.core.tween+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.gestures.waitForUpOrCancellation+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.compositionLocalOf+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.composed+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.layout.positionOnScreen+import androidx.compose.ui.layout.positionInWindow+import androidx.compose.animation.core.VectorConverter+import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.launch+import kotlin.math.abs+import kotlin.math.cos+import kotlin.math.exp+import kotlin.math.sin+import kotlin.math.sqrt++/** How the interface moves: every animation's timing in one place, as measured on the reference. */+object Motion {+ /**+ * A menu opening: it grows out of the point it hangs from, from almost nothing, overshooting a+ * little; closing, it fades as it shrinks to [MENU_END_SCALE]. (The panels hanging from the top+ * bar don't move: they come and go at once.)+ */+ const val MENU_MS = 300+ const val MENU_START_SCALE = 0.001f+ const val MENU_END_SCALE = 0.8f+ val MenuOpen: Easing = CubicBezierEasing(0.26f, 1.22f, 0.39f, 1.01f)++ /** A menu closing, and the curve most timed changes take. */+ val Settle: Easing = CubicBezierEasing(0.2f, 0.8f, 0.5f, 1.0f)++ fun menuOpen(): AnimationSpec<Float> = tween(MENU_MS, easing = MenuOpen)+ fun menuClose(): AnimationSpec<Float> = tween(MENU_MS, easing = Settle)++ /** Buttons lighting up as they are pressed, and going back. */+ const val HIGHLIGHT_ON_MS = 67L+ fun highlightOn(): AnimationSpec<Float> = tween(HIGHLIGHT_ON_MS.toInt(), easing = LinearEasing)+ fun highlightOff(): AnimationSpec<Float> = tween(150, easing = LinearEasing)++ /** The ease in and out of most timed changes. */+ val EaseInOut: Easing = CubicBezierEasing(0.42f, 0f, 0.58f, 1f)++ /**+ * The band under the top bar telling what undo and redo did: down from behind the bar in 0.3 s+ * ease-in-out (fit rms 0.02), back up the same once 0.75 s have passed since it started down.+ */+ fun noticeIn(): AnimationSpec<Float> = tween(300, easing = EaseInOut)+ const val NOTICE_SHOWN_MS = 750L+ const val NOTICE_WARNING_SHOWN_MS = 1500L+ fun noticeOut(): AnimationSpec<Float> = tween(300, easing = EaseInOut)++ /** Messages coming and going. */+ fun message(): AnimationSpec<Float> = tween(300, easing = CubicBezierEasing(0.42f, 0f, 1f, 1f))++ /** The bars hidden and shown (the interface hidden). */+ fun bars(): AnimationSpec<Float> = tween(300, easing = EaseInOut)++ /**+ * A switch flipped: the knob slides across in about a third of a second as its track's colour+ * fades; it swells into a lens as it starts (to 1.35 by 1.4) and settles back once across.+ */+ fun switchKnob(): AnimationSpec<Float> = tween(330, easing = CubicBezierEasing(0.3f, 0f, 0.2f, 1f))+ fun switchSwell(): AnimationSpec<Float> = tween(70, easing = EaseInOut)+ fun switchSettle(): AnimationSpec<Float> = tween(120, easing = EaseInOut)+ const val SWITCH_HOLD_MS = 140L+ const val SWITCH_SWELL_X = 0.35f+ const val SWITCH_SWELL_Y = 0.4f++ /** A swatch pressed: it shrinks fast, then springs back with a bounce when let go. */+ const val SWATCH_PRESSED = 0.78f+ fun swatchPress(): AnimationSpec<Float> = tween(100, easing = Spring(0.1f, 0.8f, 2f))+ fun swatchRelease(): AnimationSpec<Float> = tween(300, easing = Spring(0.3f, 0.18f, 6f))++ /** The QuickMenu's buttons spreading from its middle as they fade in (0.15 s), and drawing back in (0.12 s). */+ fun quickMenuOpen(): AnimationSpec<Float> = tween(150, easing = Ease)+ fun quickMenuClose(): AnimationSpec<Float> = tween(120, easing = CubicBezierEasing(0.42f, 0f, 1f, 1f))++ /** The gallery zooming into an artwork as it opens (0.4 s), and out of it as it closes (0.5 s). */+ fun galleryOpen(): AnimationSpec<Float> = tween(400, easing = EaseInOut)+ fun galleryClose(): AnimationSpec<Float> = tween(500, easing = EaseInOut)++ /** The gallery going into and out of Select. */+ fun selectMode(): AnimationSpec<Float> = tween(150, easing = EaseInOut)++ /** An artwork in the gallery held: it shrinks under the finger, then lifts, and settles when let go. */+ const val ARTWORK_PRESSED = 0.87f+ const val ARTWORK_PRESS_DELAY_MS = 100L+ const val ARTWORK_LIFTED = 1.07f+ fun artworkPress(): AnimationSpec<Float> = tween(150, easing = EaseInOut)+ fun artworkLift(): AnimationSpec<Float> = tween(250, easing = EaseInOut)+ fun artworkDrop(): AnimationSpec<Float> = tween(250, easing = EaseInOut)++ /** Renaming an artwork: it rises to the top over the gallery blurring (0.3 s); done, it fades away (0.15 s). */+ fun renameRise(): AnimationSpec<Float> = tween(300, easing = EaseInOut)+ fun renameFade(): AnimationSpec<Float> = tween(150, easing = EaseInOut)++ /** An artwork's actions shown by a swipe growing in, and going. */+ fun swipeActions(): AnimationSpec<Float> = tween(300, easing = Spring(0.3f, 0.75f, 0f))++ /** A swiped row settling open or shut. */+ fun swipeSettle(): AnimationSpec<Float> = tween(300, easing = Spring(0.3f, 0.8f, 0.2f))++ /** A colour panel tab's icon held down (it shrinks as a highlight comes on, and back as one goes off). */+ const val TAB_PRESSED = 0.75f++ /** The Actions panel changing tabs: the old tab's rows fade out, then the new tab's fade in. */+ fun actionsTabOut(): AnimationSpec<Float> = tween(100, easing = EaseInOut)+ fun actionsTabIn(): AnimationSpec<Float> = tween(200, easing = EaseInOut)++ /** A panel's pages pushed in and back: 0.45 s on the ease curve. */+ const val PANEL_PAGE_MS = 450+ val Ease: Easing = CubicBezierEasing(0.25f, 0.1f, 0.25f, 1f)++ /**+ * A panel's page pushed in ([forward]): it slides in from the right as the page it covers+ * slides off to the left. Going back, the page goes at once as the one under it slides back in+ * from the left. The panel's size follows.+ */+ fun panelPage(forward: Boolean): androidx.compose.animation.ContentTransform {+ val move = tween<androidx.compose.ui.unit.IntOffset>(PANEL_PAGE_MS, easing = Ease)+ return androidx.compose.animation.ContentTransform(+ androidx.compose.animation.slideInHorizontally(move) { if (forward) it else -it },+ if (forward) androidx.compose.animation.slideOutHorizontally(move) { -it } else androidx.compose.animation.fadeOut(androidx.compose.animation.core.snap()),+ sizeTransform = androidx.compose.animation.SizeTransform(clip = true) { _, _ -> tween(PANEL_PAGE_MS, easing = Ease) },+ )+ }++ /**+ * The brush studio and the full-screen pages (canvas information, gesture controls) sliding up+ * (a spring settling in 0.5 s, not bouncing) and down (0.3 s).+ */+ fun studioIn(): androidx.compose.animation.core.FiniteAnimationSpec<androidx.compose.ui.unit.IntOffset> =+ tween(500, easing = Spring(0.5f, 1f, 0f))+ fun studioOut(): androidx.compose.animation.core.FiniteAnimationSpec<androidx.compose.ui.unit.IntOffset> =+ tween(300, easing = EaseInOut)++ /** A bottom toolbar (transform, selection) rising from below the screen on a spring settling in 0.4 s, and dropping away in 0.075 s. */+ fun toolbarIn(): androidx.compose.animation.EnterTransition =+ androidx.compose.animation.slideInVertically(tween(400, easing = Spring(0.4f, 0.9f, 0f))) { it * 3 / 2 }+ fun toolbarOut(): androidx.compose.animation.ExitTransition =+ androidx.compose.animation.slideOutVertically(tween(75, easing = CubicBezierEasing(0.42f, 0f, 1f, 1f))) { it * 3 / 2 }++ /** The side bar sliding off its edge as a mode takes the screen (0.13 s, speeding up), and back (0.2 s, slowing). */+ fun sideBarIn(right: Boolean): androidx.compose.animation.EnterTransition =+ androidx.compose.animation.slideInHorizontally(tween(200, easing = CubicBezierEasing(0f, 0f, 0.58f, 1f))) { if (right) it else -it }+ fun sideBarOut(right: Boolean): androidx.compose.animation.ExitTransition =+ androidx.compose.animation.slideOutHorizontally(tween(130, easing = CubicBezierEasing(0.42f, 0f, 1f, 1f))) { if (right) it else -it }++ /** A tool's header (crop, guides) fading in over the top bar as its mode begins. */+ fun toolHeaderIn(): AnimationSpec<Float> = tween(220, easing = EaseInOut)++ /** The reference window fading in where it is, and out when closed. */+ fun referenceFade(): androidx.compose.animation.core.FiniteAnimationSpec<Float> = tween(280, easing = EaseInOut)++ /** A panel fading away as something picked from it takes over (an adjustment): 0.25 s. */+ fun panelFade(): AnimationSpec<Float> = tween(250, easing = EaseInOut)++ /** The time-lapse replay fading in over the canvas as the panel fades away, and out on Done: 0.25 s. */+ fun replayFade(): androidx.compose.animation.core.FiniteAnimationSpec<Float> = tween(250, easing = EaseInOut)++ /**+ * A layer's blend modes: opening, the panel grows down over them and they fade in, 0.25 s;+ * closing, they fade as it shrinks back, 0.1 s, and 0.1 s later the rows under the layer come+ * back over 0.12 s (after opening, straight away).+ */+ const val BLEND_OPEN_MS = 250L+ const val BLEND_CLOSE_MS = 100L+ const val BLEND_ROWS_WAIT_MS = 100L+ fun blendOpen(): androidx.compose.animation.core.FiniteAnimationSpec<Float> = tween(BLEND_OPEN_MS.toInt(), easing = EaseInOut)+ fun blendOpenSize(): androidx.compose.animation.core.FiniteAnimationSpec<androidx.compose.ui.unit.IntSize> = tween(BLEND_OPEN_MS.toInt(), easing = EaseInOut)+ fun blendClose(): androidx.compose.animation.core.FiniteAnimationSpec<Float> = tween(BLEND_CLOSE_MS.toInt(), easing = EaseInOut)+ fun blendCloseSize(): androidx.compose.animation.core.FiniteAnimationSpec<androidx.compose.ui.unit.IntSize> = tween(BLEND_CLOSE_MS.toInt(), easing = EaseInOut)+ fun blendRowsBack(): AnimationSpec<Float> = tween(120, easing = EaseInOut)+++ /**+ * Into a stack of the gallery its artworks fly out of the stack's cell to their places; back out,+ * the gallery grows back into place, fading in.+ */+ fun stackPushMove(): AnimationSpec<Offset> = tween(450, easing = Spring(0.45f, 0.8f, 0f))+ fun stackPop(): androidx.compose.animation.core.FiniteAnimationSpec<Float> = tween(300, easing = Spring(0.3f, 0.8f, 0f))+ const val STACK_POP_SCALE = 0.8f++ /** The grown artwork lifting off a canvas that took a while to draw: 0.15 s. */+ fun coverFade(): AnimationSpec<Float> = tween(150, easing = EaseInOut)++ /** Leaving a stack, the gallery's title fading in (0.11 s) as the stack's fades out (0.07 s). */+ fun titleIn(): androidx.compose.animation.core.FiniteAnimationSpec<Float> = tween(110, easing = EaseInOut)+ fun titleOut(): androidx.compose.animation.core.FiniteAnimationSpec<Float> = tween(70, easing = EaseInOut)++ /**+ * Rows of a list arriving and going (a 0.3 s spring, damping 0.75), and moving to make room:+ * 0.35 s on the settling curve (measured as a layer was added: the spring is far too quick).+ */+ private val Rows = Spring(0.3f, 0.75f, 0f)+ fun rowMove(): androidx.compose.animation.core.FiniteAnimationSpec<androidx.compose.ui.unit.IntOffset> = tween(350, easing = Settle)+ fun rowFade(): androidx.compose.animation.core.FiniteAnimationSpec<Float> = tween(300, easing = Rows)+}++/**+ * A spring as a curve over a fixed time: the motion of a damped spring released from 0 towards 1+ * at [velocity] (in distances per second), with [damping] (1: critical; less bounces), stiff+ * enough to come to rest within [seconds].+ */+class Spring(private val seconds: Float, private val damping: Float, private val velocity: Float) : Easing {+ // the natural frequency, found once: the slowest at which the motion is within a thousandth of+ // its end by the time given+ private val omega: Double = run {+ var lo = 0.01+ var hi = 2000.0+ repeat(60) {+ val mid = (lo + hi) / 2+ if (envelope(mid, seconds.toDouble()) > 1e-3) lo = mid else hi = mid+ }+ hi+ }++ /** How far from its end the motion can still be at time [t], at frequency [w]. */+ private fun envelope(w: Double, t: Double): Double {+ val z = damping.toDouble().coerceAtLeast(0.01)+ val v = velocity.toDouble()+ return when {+ z < 1.0 -> {+ val wd = w * sqrt(1 - z * z)+ val c2 = (v - z * w) / wd+ sqrt(1 + c2 * c2) * exp(-z * w * t)+ }+ z == 1.0 -> (1 + abs(v - w) * t) * exp(-w * t)+ else -> {+ val s = sqrt(z * z - 1)+ val r1 = -w * (z - s)+ val r2 = -w * (z + s)+ val c1 = (v + r2) / (r1 - r2)+ abs(c1) * exp(r1 * t) + abs(-1 - c1) * exp(r2 * t)+ }+ }+ }++ override fun transform(fraction: Float): Float {+ if (fraction >= 1f) return 1f+ val t = fraction.toDouble() * seconds+ val z = damping.toDouble().coerceAtLeast(0.01)+ val v = velocity.toDouble()+ val w = omega+ val off = when {+ z < 1.0 -> {+ val wd = w * sqrt(1 - z * z)+ exp(-z * w * t) * (-cos(wd * t) + (v - z * w) / wd * sin(wd * t))+ }+ z == 1.0 -> (-1 + (v - w) * t) * exp(-w * t)+ else -> {+ val s = sqrt(z * z - 1)+ val r1 = -w * (z - s)+ val r2 = -w * (z + s)+ val c1 = (v + r2) / (r1 - r2)+ c1 * exp(r1 * t) + (-1 - c1) * exp(r2 * t)+ }+ }+ return (1 + off).toFloat()+ }++ companion object {+ /** A spring's curve run over its own time ([seconds]) as an animation. */+ fun spec(seconds: Float, damping: Float, velocity: Float = 0f, delaySeconds: Float = 0f): AnimationSpec<Float> =+ tween((seconds * 1000).toInt(), (delaySeconds * 1000).toInt(), Spring(seconds, damping, velocity))+ }+}++/**+ * Whether what [touch] is on is held down; after a quick tap it stays held long enough for a+ * highlight to come on.+ */+@Composable+fun heldOf(touch: androidx.compose.foundation.interaction.InteractionSource): Boolean {+ var held by remember { mutableStateOf(false) }+ LaunchedEffect(touch) {+ var since = 0L+ touch.interactions.collect { i ->+ when (i) {+ is androidx.compose.foundation.interaction.PressInteraction.Press -> {+ held = true+ since = System.nanoTime()+ }+ is androidx.compose.foundation.interaction.PressInteraction.Release,+ is androidx.compose.foundation.interaction.PressInteraction.Cancel -> {+ val left = Motion.HIGHLIGHT_ON_MS - (System.nanoTime() - since) / 1_000_000+ if (left > 0) kotlinx.coroutines.delay(left)+ held = false+ }+ }+ }+ }+ return held+}++/** How lit a button is (0..1): it lights up fast and goes back more slowly. */+@Composable+fun animateHighlight(on: Boolean): Float =+ androidx.compose.animation.core.animateFloatAsState(+ if (on) 1f else 0f,+ if (on) Motion.highlightOn() else Motion.highlightOff(),+ label = "highlight",+ ).value++/**+ * Shows [value] while there is one, fading in and out by [spec]: the last value stays while it+ * fades out. [content] gets the value and how opaque it is.+ */+@Composable+fun <T : Any> FadingValue(value: T?, spec: AnimationSpec<Float>, content: @Composable (T, Float) -> Unit) {+ val last = remember { arrayOfNulls<Any>(1) }+ if (value != null) last[0] = value+ val shown = androidx.compose.animation.core.animateFloatAsState(if (value != null) 1f else 0f, spec, label = "fade").value+ @Suppress("UNCHECKED_CAST")+ val kept = last[0] as T? ?: return+ if (shown > 0f) content(kept, shown)+}++/** How a panel looks as it opens or closes, for its frosted backdrop to follow: [pivot] in screen pixels. */+class PanelLook(val alpha: Float, val scale: Float, val pivot: Offset)++val LocalPanelLook = compositionLocalOf { PanelLook(1f, 1f, Offset.Zero) }++/**+ * Shows [content] for [target] unless it is [hidden]. The panels hanging from the top bar come and+ * go at once (as measured on the reference, within a frame); [content] still gets how opaque and+ * how big the panel is and where this host's top left is on screen (pixels), for its frosted+ * backdrop.+ */+@Composable+fun <T> PanelPresence(+ target: T,+ hidden: T,+ fading: Boolean = false,+ onFaded: () -> Unit = {},+ content: @Composable (shown: T, alpha: Float, scale: Float, origin: Offset) -> Unit,+) {+ var origin by remember { mutableStateOf(Offset.Zero) }+ // the last panel shown, which fades away when closed [fading] (then [onFaded])+ val last = remember { arrayOfNulls<Any>(1) }+ val fade = remember { Animatable(1f) }+ if (target != hidden) last[0] = target+ LaunchedEffect(target, fading) {+ if (target == hidden && fading) {+ fade.snapTo(1f)+ fade.animateTo(0f, Motion.panelFade())+ onFaded()+ } else {+ fade.snapTo(1f)+ }+ }+ @Suppress("UNCHECKED_CAST")+ val shown = if (target != hidden) target else if (fading) last[0] as T? ?: return else return+ Box(+ Modifier.fillMaxSize().onGloballyPositioned { origin = it.positionOnScreen() }+ .then(if (target == hidden) Modifier.pointerInput(Unit) { awaitEachGesture { awaitFirstDown().consume() } } else Modifier),+ ) {+ content(shown, if (target == hidden) fade.value else 1f, 1f, origin)+ }+}++/** Gives the panels inside [content] their look, for their frosted backdrops to follow. */+@Composable+fun ProvidePanelLook(look: PanelLook, content: @Composable () -> Unit) {+ CompositionLocalProvider(LocalPanelLook provides look, content = content)+}++/**+ * A menu (a popup) that grows out of [origin] (a point of the menu, in fractions of its size) as it+ * opens, and fades as it shrinks back towards it as it closes, staying up while it goes. [content] puts the+ * popup up and gives its menu the [Modifier] it gets, which carries how it looks now.+ */+@Composable+fun MenuPresence(open: Boolean, origin: androidx.compose.ui.graphics.TransformOrigin, content: @Composable (Modifier) -> Unit) {+ var showing by remember { mutableStateOf(open) }+ // a menu first put up open still opens from its origin+ val alpha = remember { Animatable(0f) }+ val scale = remember { Animatable(Motion.MENU_START_SCALE) }+ LaunchedEffect(open) {+ if (open) {+ if (!showing || alpha.value <= 0f) {+ showing = true+ alpha.snapTo(0f)+ scale.snapTo(Motion.MENU_START_SCALE)+ }+ coroutineScope {+ launch { alpha.animateTo(1f, Motion.menuOpen()) }+ launch { scale.animateTo(1f, Motion.menuOpen()) }+ }+ } else {+ coroutineScope {+ launch { scale.animateTo(Motion.MENU_END_SCALE, Motion.menuClose()) }+ launch { alpha.animateTo(0f, Motion.menuClose()) }+ }+ showing = false+ }+ }+ if (!showing) return+ var pivot by remember { mutableStateOf(Offset.Zero) }+ val a = alpha.value.coerceIn(0f, 1f)+ val k = scale.value+ val look = Modifier+ .onGloballyPositioned { c ->+ pivot = c.positionOnScreen() + Offset(origin.pivotFractionX * c.size.width, origin.pivotFractionY * c.size.height)+ }+ .graphicsLayer {+ this.alpha = a+ scaleX = k+ scaleY = k+ transformOrigin = origin+ }+ ProvidePanelLook(PanelLook(a, k, pivot)) { content(look) }+}++/**+ * How much presses on [touch]'s area shrink something ([value], 1 when let go): held, it goes to+ * [pressed] by [press]; let go, back by [release].+ */+class PressScale(+ private val pressed: Float,+ private val press: AnimationSpec<Float>,+ private val release: AnimationSpec<Float>,+ private val scope: kotlinx.coroutines.CoroutineScope,+) {+ private val scale = Animatable(1f)+ val value: Float get() = scale.value++ val touch: Modifier = Modifier.pointerInput(Unit) {+ awaitEachGesture {+ awaitFirstDown(requireUnconsumed = false)+ scope.launch { scale.animateTo(pressed, press) }+ waitForUpOrCancellation()+ scope.launch { scale.animateTo(1f, release) }+ }+ }+}++@Composable+fun rememberPressScale(pressed: Float, press: AnimationSpec<Float>, release: AnimationSpec<Float>): PressScale {+ val scope = androidx.compose.runtime.rememberCoroutineScope()+ return remember { PressScale(pressed, press, release, scope) }+}++/** Scales what it is on by [p]. */+fun Modifier.scaledBy(p: PressScale): Modifier = graphicsLayer {+ scaleX = p.value+ scaleY = p.value+}++/**+ * Flies what it is on in by [spec] from where [from] (window pixels) is, as its own bounds' top+ * left there; hidden until it is placed. Nothing moves without [from].+ */+fun Modifier.flyIn(from: androidx.compose.ui.geometry.Rect?, spec: AnimationSpec<Offset>): Modifier = composed {+ if (from == null) return@composed this+ val shift = remember { Animatable(Offset.Zero, Offset.VectorConverter) }+ var placed by remember { mutableStateOf(false) }+ val scope = androidx.compose.runtime.rememberCoroutineScope()+ this+ .onGloballyPositioned { c ->+ if (placed) return@onGloballyPositioned+ placed = true+ val at = c.positionInWindow()+ scope.launch {+ shift.snapTo(Offset(from.left - at.x, from.top - at.y))+ shift.animateTo(Offset.Zero, spec)+ }+ }+ .graphicsLayer {+ alpha = if (placed) 1f else 0f+ translationX = shift.value.x+ translationY = shift.value.y+ }+}++/**+ * Once [leaving], flies what it is on by [spec] to where [to] (window pixels) is, its top left+ * there, from where it was last placed. Nothing moves without [to].+ */+fun Modifier.flyOut(to: androidx.compose.ui.geometry.Rect?, leaving: Boolean, spec: AnimationSpec<Float>): Modifier = composed {+ if (to == null) return@composed this+ var from by remember { mutableStateOf<Offset?>(null) }+ val gone = remember { Animatable(0f) }+ LaunchedEffect(leaving) { if (leaving) gone.animateTo(1f, spec) }+ this+ .onGloballyPositioned { if (!leaving) from = it.positionInWindow() }+ .graphicsLayer {+ val f = from ?: return@graphicsLayer+ translationX = (to.left - f.x) * gone.value+ translationY = (to.top - f.y) * gone.value+ }+}++/** Shrinks what it is on while it is pressed and springs it back when let go, as swatches do. */+fun Modifier.pressScale(): Modifier = composed {+ val p = rememberPressScale(Motion.SWATCH_PRESSED, Motion.swatchPress(), Motion.swatchRelease())+ this.then(p.touch).scaledBy(p)+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Popover.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Popover.ktnew file mode 100644index 0000000..bdce76f--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Popover.kt@@ -0,0 +1,199 @@+package io.github.artcraftandroid.procraft.ui++import android.graphics.BlurMaskFilter+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ColumnScope+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.SideEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.runtime.staticCompositionLocalOf+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.drawBehind+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.RoundRect+import androidx.compose.ui.graphics.ClipOp+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Paint+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.drawscope.drawIntoCanvas+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.layout.positionInWindow+import androidx.compose.ui.layout.positionOnScreen+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp++/** Where frosted panels are told about: on the canvas screen only, which has a canvas behind them. */+val LocalBackdrops = staticCompositionLocalOf<Backdrops?> { null }++/** The rounded bodies of the frosted panels open now (window pixels), sent on whenever they change. */+class Backdrops(private val send: (List<Float>) -> Unit) {+ private val regions = LinkedHashMap<Any, FloatArray>()++ fun put(key: Any, region: FloatArray) {+ if (regions[key]?.contentEquals(region) == true) return+ regions[key] = region+ send(regions.values.flatMap { it.asList() })+ }++ fun remove(key: Any) {+ if (regions.remove(key) == null) return+ send(regions.values.flatMap { it.asList() })+ }+}++/**+ * Makes the node it is put on frosted glass over the canvas while it is shown: what is behind its+ * rounded box ([corner]) is blurred. Works from popups too (it goes by screen position).+ */+@Composable+fun rememberFrost(corner: Dp): Modifier {+ val backdrops = LocalBackdrops.current ?: return Modifier+ val key = remember { Any() }+ val density = LocalDensity.current+ // the blur grows and fades with the panel+ val look = LocalPanelLook.current+ var box by remember { mutableStateOf<FloatArray?>(null) }+ DisposableEffect(backdrops) { onDispose { backdrops.remove(key) } }+ SideEffect {+ box?.let { (x0, y0, x1, y1, corner) ->+ val (px, py, k) = Triple(look.pivot.x, look.pivot.y, look.scale)+ backdrops.put(key, floatArrayOf(px + (x0 - px) * k, py + (y0 - py) * k, px + (x1 - px) * k, py + (y1 - py) * k, corner * k, look.alpha))+ }+ }+ return Modifier.onGloballyPositioned { c ->+ val at = c.positionOnScreen()+ box = floatArrayOf(at.x, at.y, at.x + c.size.width, at.y + c.size.height, with(density) { corner.toPx() })+ }+}+++/** The side of a popover its arrow sticks out of, pointing at its button; or none. */+enum class ArrowSide { TOP, BOTTOM, LEFT, RIGHT, NONE }++/**+ * A panel hanging from the top bar, with an arrow pointing up at its button: [arrowX] is the tip's+ * distance from the panel's left edge (from its top, for an arrow on the [side]). [popoverPlace]+ * finds where it goes. Without a [fill] of its own it is frosted over the canvas: translucent,+ * with what is behind it blurred. [width] is the body's: a side arrow adds to it.+ */+@Composable+fun Popover(+ width: Dp,+ arrowX: Dp,+ modifier: Modifier = Modifier,+ fill: Color? = null,+ corner: Dp = Pc.PopoverCorner,+ side: ArrowSide = ArrowSide.TOP,+ content: @Composable ColumnScope.() -> Unit,+) {+ val backdrops = LocalBackdrops.current.takeIf { fill == null && Pc.PopoverFrost.alpha < 1f }+ val paint = fill ?: if (backdrops != null) Pc.PopoverFrost else Pc.PopoverFill+ val key = remember { Any() }+ val density = LocalDensity.current+ if (backdrops != null) DisposableEffect(backdrops) { onDispose { backdrops.remove(key) } }+ val frost = if (backdrops == null) {+ Modifier+ } else {+ Modifier.onGloballyPositioned { c ->+ val at = c.positionInWindow()+ val (arrowH, radius) = with(density) { Pc.ArrowHeight.toPx() to corner.toPx() }+ val (l, t, r) = Triple(if (side == ArrowSide.LEFT) arrowH else 0f, if (side == ArrowSide.TOP) arrowH else 0f, if (side == ArrowSide.RIGHT) arrowH else 0f)+ val b = if (side == ArrowSide.BOTTOM) arrowH else 0f+ backdrops.put(key, floatArrayOf(at.x + l, at.y + t, at.x + c.size.width - r, at.y + c.size.height - b, radius))+ }+ }+ val sideways = side == ArrowSide.LEFT || side == ArrowSide.RIGHT+ Box(+ modifier.width(if (sideways) width + Pc.ArrowHeight else width).then(frost).drawBehind {+ val arrowH = Pc.ArrowHeight.toPx()+ val at = arrowX.toPx()+ val half = arrowH+ val tip = 2.dp.toPx()+ val radius = CornerRadius(corner.toPx())+ val outline = Path().apply {+ when (side) {+ ArrowSide.TOP -> {+ addRoundRect(RoundRect(0f, arrowH, size.width, size.height, radius))+ moveTo(at - half - tip, arrowH + 0.5f)+ lineTo(at - tip, tip)+ quadraticTo(at, 0f, at + tip, tip)+ lineTo(at + half + tip, arrowH + 0.5f)+ close()+ }+ ArrowSide.BOTTOM -> {+ val h = size.height+ addRoundRect(RoundRect(0f, 0f, size.width, h - arrowH, radius))+ moveTo(at - half - tip, h - arrowH - 0.5f)+ lineTo(at - tip, h - tip)+ quadraticTo(at, h, at + tip, h - tip)+ lineTo(at + half + tip, h - arrowH - 0.5f)+ close()+ }+ ArrowSide.LEFT -> {+ addRoundRect(RoundRect(arrowH, 0f, size.width, size.height, radius))+ moveTo(arrowH + 0.5f, at - half - tip)+ lineTo(tip, at - tip)+ quadraticTo(0f, at, tip, at + tip)+ lineTo(arrowH + 0.5f, at + half + tip)+ close()+ }+ ArrowSide.RIGHT -> {+ val w = size.width+ addRoundRect(RoundRect(0f, 0f, w - arrowH, size.height, radius))+ moveTo(w - arrowH - 0.5f, at - half - tip)+ lineTo(w - tip, at - tip)+ quadraticTo(w, at, w - tip, at + tip)+ lineTo(w - arrowH - 0.5f, at + half + tip)+ close()+ }+ ArrowSide.NONE -> addRoundRect(RoundRect(0f, 0f, size.width, size.height, radius))+ }+ }+ drawIntoCanvas { canvas ->+ val shadow = Paint().apply {+ color = Pc.PopoverShadow+ asFrameworkPaint().maskFilter = BlurMaskFilter(Pc.PopoverShadowRadius.toPx(), BlurMaskFilter.Blur.NORMAL)+ }+ // only around the panel: none of it shows through+ canvas.save()+ canvas.clipPath(outline, ClipOp.Difference)+ canvas.drawPath(outline, shadow)+ canvas.restore()+ }+ drawPath(outline, paint)+ },+ ) {+ val inset = when (side) {+ ArrowSide.TOP -> Modifier.padding(top = Pc.ArrowHeight)+ ArrowSide.BOTTOM -> Modifier.padding(bottom = Pc.ArrowHeight)+ ArrowSide.LEFT -> Modifier.padding(start = Pc.ArrowHeight)+ ArrowSide.RIGHT -> Modifier.padding(end = Pc.ArrowHeight)+ ArrowSide.NONE -> Modifier+ }+ Column(inset.clip(RoundedCornerShape(corner)), content = content)+ }+}++/** Where a popover [width] wide goes on a screen [screenWidth] wide: its left edge and arrow tip. */+data class PopoverPlace(val left: Dp, val arrowX: Dp)++/**+ * A popover is centred on its button (the tip sits [Pc.ArrowShift] right of the button's centre)+ * and kept [Pc.PopoverGap] inside the screen, and at least [minLeft] from its left edge (clear of+ * the side bar).+ */+fun popoverPlace(width: Dp, buttonCentreX: Dp, screenWidth: Dp, minLeft: Dp = Pc.PopoverGap, minRight: Dp = Pc.PopoverGap): PopoverPlace {+ val tip = buttonCentreX + Pc.ArrowShift+ val left = (tip - width / 2).coerceIn(minLeft, (screenWidth - minRight - width).coerceAtLeast(minLeft))+ return PopoverPlace(left, tip - left)+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/QuickMenuUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/QuickMenuUi.ktnew file mode 100644index 0000000..c2e2d34--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/QuickMenuUi.kt@@ -0,0 +1,176 @@+package io.github.artcraftandroid.procraft.ui++import androidx.compose.foundation.ExperimentalFoundationApi+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.combinedClickable+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.material3.Icon+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import io.github.artcraftandroid.procraft.canvas.QuickAction+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxScope+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel++// glass: the buttons a dark tint over the canvas with a faint rim, the middle one a light tint+private val ButtonFill = Color(0x9C282828)+private val ButtonEdge = Color(0x40FFFFFF)+private val ButtonInk = Color(0xFFF7F7F7)+private val TitleFill = Color(0x94CFCFCF)+private val TitleInk = Color(0xFF0F0F0F)+private val RingButtonWidth = 171.dp+private val RingButtonHeight = 48.dp++/** Where the buttons' centres are from the middle, clockwise from the top. */+private val Slots = listOf(0 to -69, 191 to -39, 191 to 39, 0 to 69, -191 to 39, -191 to -39)+private val RingReachX = 191.dp+private val RingReachY = 69.dp++/**+ * The QuickMenu: its name in the middle of where it was opened, its six actions round it; an action+ * tapped runs and closes it, a tap anywhere else closes it, and a button held lists the actions it+ * can be set to.+ */+@OptIn(ExperimentalFoundationApi::class)+@Composable+fun BoxScope.QuickMenu(vm: CanvasViewModel) {+ // the buttons spread out from the point as it opens, and draw back in as it closes (the last+ // point kept while they go)+ val target = vm.quickMenuAt+ val last = remember { arrayOfNulls<Offset>(1) }+ if (target != null) last[0] = target+ val open = remember { androidx.compose.animation.core.Animatable(0f) }+ androidx.compose.runtime.LaunchedEffect(target) {+ if (target != null) {+ open.snapTo(0f)+ open.animateTo(1f, Motion.quickMenuOpen())+ } else {+ open.animateTo(0f, Motion.quickMenuClose())+ }+ }+ val at = last[0] ?: return+ if (target == null && open.value <= 0f) return+ val shown = open.value+ val density = LocalDensity.current+ // the button whose action is being chosen+ var choosing by remember { mutableStateOf<Int?>(null) }+ BoxWithConstraints(Modifier.fillMaxSize().pointerInput(Unit) { detectTapGestures { vm.quickMenuAt = null } }) {+ // kept on the screen+ val c = with(density) {+ val x = at.x.toDp().coerceIn(RingReachX + RingButtonWidth / 2, maxWidth - RingReachX - RingButtonWidth / 2)+ val y = at.y.toDp().coerceIn(RingReachY + RingButtonHeight, maxHeight - RingReachY - RingButtonHeight)+ x to y+ }+ Box(+ Modifier.offset(x = c.first - RingButtonWidth / 2, y = c.second - RingButtonHeight / 2).size(RingButtonWidth, RingButtonHeight)+ .graphicsLayer { alpha = shown.coerceIn(0f, 1f) }.clip(CircleShape).background(TitleFill),+ contentAlignment = Alignment.Center,+ ) {+ Text("QuickMenu 1", color = TitleInk, fontSize = 16.sp, fontWeight = FontWeight.SemiBold, maxLines = 1)+ }+ val slots = vm.quickMenuSlots+ slots.forEachIndexed { i, action ->+ val (dx, dy) = Slots.getOrNull(i) ?: return@forEachIndexed+ val x = c.first + dx.dp * shown - RingButtonWidth / 2+ val y = c.second + dy.dp * shown - RingButtonHeight / 2+ Box(+ Modifier.offset(x = x, y = y).size(RingButtonWidth, RingButtonHeight).graphicsLayer { alpha = shown.coerceIn(0f, 1f) }.clip(CircleShape)+ .background(if (choosing == i) Pc.Accent else ButtonFill).border(1.dp, ButtonEdge, CircleShape)+ .combinedClickable(+ onClick = {+ vm.quickMenuAt = null+ vm.runQuickAction(action, at)+ },+ onLongClick = { choosing = i },+ ),+ contentAlignment = Alignment.Center,+ ) {+ Text(action.button, color = if (choosing == i) Color.White else ButtonInk, fontSize = 16.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, textAlign = TextAlign.Center)+ }+ }+ // the actions a held button can be set to, beside the ring+ choosing?.let { i ->+ val right = c.first + RingReachX + RingButtonWidth / 2+ val left = (if (right + 236.dp < maxWidth) right + 16.dp else c.first - RingReachX - RingButtonWidth / 2 - 236.dp)+ .coerceIn(8.dp, (maxWidth - 228.dp).coerceAtLeast(8.dp))+ val top = (c.second - 220.dp).coerceIn(8.dp, (maxHeight - 448.dp).coerceAtLeast(8.dp))+ Column(+ Modifier.offset(x = left, y = top).width(220.dp).height(440.dp).clip(RoundedCornerShape(16.dp)).background(Pc.PopoverFill)+ .verticalScroll(rememberScrollState()).padding(vertical = 6.dp),+ ) {+ for (a in QuickAction.entries) {+ val chosen = a == slots.getOrNull(i)+ Box(+ Modifier.fillMaxWidth().height(40.dp).clickable {+ vm.setQuickSlot(i, a)+ choosing = null+ }.padding(horizontal = 16.dp),+ contentAlignment = Alignment.CenterStart,+ ) {+ Text(a.label, color = Pc.PanelTitle, fontSize = 16.sp, maxLines = 1)+ if (chosen) Icon(PcIcons.Tick, contentDescription = null, tint = Pc.Accent, modifier = Modifier.align(Alignment.CenterEnd).size(18.dp))+ }+ }+ }+ }+ }+}++/** Layer Select's list: the layers drawn under the point, top first, the current one blue. */+@Composable+fun BoxScope.LayerChoice(vm: CanvasViewModel) {+ val (at, ids) = vm.layerChoice ?: return+ val density = LocalDensity.current+ BoxWithConstraints(Modifier.fillMaxSize().pointerInput(Unit) { detectTapGestures { vm.layerChoice = null } }) {+ val x = with(density) { at.x.toDp() }.coerceIn(8.dp, maxWidth - 208.dp)+ val y = with(density) { at.y.toDp() + 24.dp }.coerceIn(8.dp, maxHeight - (ids.size * 44 + 16).dp)+ androidx.compose.foundation.layout.Column(+ Modifier.offset(x = x, y = y).size(200.dp, (ids.size * 44 + 16).dp).clip(androidx.compose.foundation.shape.RoundedCornerShape(16.dp))+ .background(Pc.PopoverFill).padding(vertical = 8.dp),+ ) {+ for (id in ids) {+ val l = vm.layers.firstOrNull { it.id == id } ?: continue+ Box(+ Modifier.fillMaxWidth().height(44.dp).background(if (l.current) Pc.Accent else Color.Transparent).clickable {+ vm.selectLayer(id)+ vm.layerChoice = null+ }.padding(start = 16.dp),+ contentAlignment = Alignment.CenterStart,+ ) {+ Text(l.name, color = if (l.current) Color.White else Pc.PanelTitle, fontSize = 16.sp, maxLines = 1)+ }+ }+ }+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ReferenceUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ReferenceUi.ktnew file mode 100644index 0000000..7199cc8--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ReferenceUi.kt@@ -0,0 +1,170 @@+package io.github.artcraftandroid.procraft.ui++import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.PickVisualMediaRequest+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.detectDragGestures+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxScope+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.SideEffect+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.shadow+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalConfiguration+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import kotlin.math.roundToInt++private val BarFill = Color(0xFF393939)+private val PictureFill = Color(0xFF262626)+private val GrabLine = Color(0xFF7C7C7C)+private val TitleInk = Color(0xFFC5C5C5)+private val CloseFill = Color(0xFF262626)+private val CloseEdge = Color(0xFF454545)+private val CloseInk = Color(0xFFA5A5A5)+private val SegmentTrack = Color(0xFF4D4D4D)+private val Muted = Color(0xFFAAAAAA)+private val TopBarHeight = 64.dp+private val BottomBarHeight = 45.dp+private val ReferenceCorner = 24.dp+private val HandleSide = 60.dp++/**+ * The reference window: the whole canvas as it is, or a picture to work from, floating over the+ * canvas. Its top bar drags it; the round button closes it (Reference off); handles over its+ * bottom corners size it.+ */+@Composable+fun BoxScope.ReferenceWindow(vm: CanvasViewModel) {+ // it fades in where it is, and out when closed; over the whole screen, since the fade draws+ // into a buffer its own size and the window sits away from the corner+ androidx.compose.animation.AnimatedVisibility(+ vm.referenceOn,+ Modifier.matchParentSize(),+ enter = androidx.compose.animation.fadeIn(Motion.referenceFade()),+ exit = androidx.compose.animation.fadeOut(Motion.referenceFade()),+ ) { ReferenceWindowContent(vm) }+}++@Composable+private fun ReferenceWindowContent(vm: CanvasViewModel) {+ val density = LocalDensity.current+ val config = LocalConfiguration.current+ val pick = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri -> uri?.let(vm::importReference) }+ val picture = vm.referenceSize+ val tall = TopBarHeight + picture.height + BottomBarHeight+ // the first time: in the middle near the bottom of the screen+ SideEffect {+ with(density) { vm.placeReference(config.screenWidthDp.dp.toPx(), config.screenHeightDp.dp.toPx(), tall.toPx()) }+ }+ val at = vm.referenceOffset.takeIf { it != Offset.Unspecified } ?: Offset.Zero+ // room around the window for the handles, which reach past its corners (touches outside a+ // layout's bounds don't reach it)+ val margin = HandleSide / 2 - 12.dp+ val below = HandleSide / 2 - 15.dp+ Box(Modifier.offset { IntOffset(at.x.roundToInt() - margin.roundToPx(), at.y.roundToInt()) }) {+ Column(Modifier.padding(start = margin, end = margin, bottom = below).width(picture.width).shadow(18.dp, RoundedCornerShape(ReferenceCorner)).clip(RoundedCornerShape(ReferenceCorner)).background(PictureFill)) {+ // the title bar: dragged to move the window+ Box(+ Modifier.fillMaxWidth().height(TopBarHeight).background(BarFill)+ .pointerInput(Unit) { detectDragGestures { change, amount -> change.consume(); vm.moveReference(amount) } },+ ) {+ Box(Modifier.align(Alignment.TopCenter).padding(top = 4.dp).size(40.dp, 4.dp).clip(CircleShape).background(GrabLine))+ Text("Reference", color = TitleInk, fontSize = 22.sp, fontWeight = FontWeight.Bold, maxLines = 1, modifier = Modifier.align(Alignment.CenterStart).padding(start = 20.dp))+ Row(Modifier.align(Alignment.CenterEnd).padding(end = 10.dp), verticalAlignment = Alignment.CenterVertically) {+ if (vm.referenceMode == CanvasViewModel.ReferenceMode.IMAGE && vm.referenceImage != null) {+ Text("Clear", color = Pc.Accent, fontSize = 15.sp, modifier = Modifier.clickable { vm.clearReference() }.padding(6.dp))+ Text("Import", color = Pc.Accent, fontSize = 15.sp, modifier = Modifier.clickable { pick.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) }.padding(6.dp))+ }+ Box(+ Modifier.size(43.dp).clip(CircleShape).background(CloseFill).border(1.dp, CloseEdge, CircleShape).clickable { vm.changeReferenceOn(false) },+ contentAlignment = Alignment.Center,+ ) {+ Icon(PcIcons.Cross, contentDescription = "Close", tint = CloseInk, modifier = Modifier.size(20.dp))+ }+ }+ }+ Box(Modifier.fillMaxWidth().height(picture.height), contentAlignment = Alignment.Center) {+ when (vm.referenceMode) {+ CanvasViewModel.ReferenceMode.CANVAS -> vm.referenceCanvas?.let {+ Image(it, contentDescription = "The canvas", contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize())+ }+ CanvasViewModel.ReferenceMode.IMAGE -> {+ val image = vm.referenceImage+ if (image != null) {+ Image(image, contentDescription = "Reference picture", contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize())+ } else {+ Box(+ Modifier.width(180.dp).height(60.dp).clip(RoundedCornerShape(30.dp)).background(SegmentTrack)+ .clickable { pick.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) },+ contentAlignment = Alignment.Center,+ ) {+ Text("Import Image", color = Muted, fontSize = 16.sp)+ }+ }+ }+ CanvasViewModel.ReferenceMode.FACE -> Text("Not available on this device", color = Muted, fontSize = 14.sp)+ }+ }+ Box(Modifier.fillMaxWidth().height(BottomBarHeight).background(BarFill), contentAlignment = Alignment.Center) {+ Row(+ Modifier.width(270.dp).height(35.dp).clip(CircleShape).background(SegmentTrack).padding(2.dp),+ horizontalArrangement = Arrangement.spacedBy(11.dp),+ ) {+ for ((mode, label) in listOf(CanvasViewModel.ReferenceMode.CANVAS to "Canvas", CanvasViewModel.ReferenceMode.IMAGE to "Image", CanvasViewModel.ReferenceMode.FACE to "Face")) {+ val on = vm.referenceMode == mode+ Box(+ Modifier.weight(1f).fillMaxHeight().clip(CircleShape).background(if (on) Pc.Accent else Color.Transparent)+ .clickable { vm.changeReferenceMode(mode) },+ contentAlignment = Alignment.Center,+ ) {+ Text(label, color = if (on) Color.White else TitleInk, fontSize = 15.sp, maxLines = 1)+ }+ }+ }+ }+ }+ // the size handles, unseen, centred 12 in from the window's bottom corners and 15 up+ for (left in listOf(true, false)) {+ val x = if (left) 0.dp else picture.width + margin * 2 - HandleSide+ Box(+ Modifier.offset(x = x, y = tall - 15.dp - HandleSide / 2).size(HandleSide)+ .pointerInput(left) {+ detectDragGestures { change, amount ->+ change.consume()+ vm.resizeReference(with(density) { amount.x.toDp() }, with(density) { amount.y.toDp() }, fromLeft = left)+ }+ },+ )+ }+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/SelectionUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/SelectionUi.ktnew file mode 100644index 0000000..6c1f4f5--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/SelectionUi.kt@@ -0,0 +1,195 @@+package io.github.artcraftandroid.procraft.ui++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.PathEffect+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.em+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import io.github.artcraftandroid.procraft.canvas.SelectionKind+import io.github.artcraftandroid.procraft.canvas.SelectionPopup+import kotlin.math.roundToInt++/** The selection toolbar's buttons: with room (landscape), and where the screen is narrow. */+private val SelectionButtonRoomy = 83.dp+private val SelectionButtonWidth = 70.dp+private val FeatherWidth = 250.dp+private val StartDot = Color(0xFFC7C7C7)+private val SavedThumb = Color(0xFF000000)++/** The selection tool's floating toolbar: its four ways, and what can be done with the selection. */+@Composable+fun SelectionToolbar(vm: CanvasViewModel, screenWidth: Dp, modifier: Modifier = Modifier) {+ val has = vm.hasSelection+ val drawing = vm.freehand.isNotEmpty()+ FloatingToolbar(+ toolbarLayout(screenWidth, 8, SelectionButtonRoomy, SelectionButtonWidth),+ onBackground = { vm.selectionPopup = SelectionPopup.NONE },+ modifier = modifier,+ segments = {+ for (kind in SelectionKind.entries) {+ val icon = when (kind) {+ SelectionKind.AUTOMATIC -> PcIcons.Automatic+ SelectionKind.FREEHAND -> PcIcons.Freehand+ SelectionKind.RECTANGLE -> PcIcons.RectangleShape+ SelectionKind.ELLIPSE -> PcIcons.EllipseShape+ }+ // drawn in a 44 frame, shown 41 across+ Segment(icon, kind.label, vm.selectionKind == kind, iconSize = 41.dp) { vm.chooseSelectionKind(kind) }+ }+ },+ ) { w ->+ // a long name smaller only where the buttons are narrow+ val long = if (w < SelectionButtonRoomy) 11.sp else 12.5.sp+ // selecting by colour always adds+ val joins = vm.selectionKind != SelectionKind.AUTOMATIC+ ToolbarButton(PcIcons.SelectAdd, "Add", active = joins && !vm.selectionRemoves, enabled = joins, width = w, iconSize = 44.dp) { vm.chooseSelectionRemoves(false) }+ ToolbarButton(PcIcons.SelectRemove, "Remove", active = joins && vm.selectionRemoves, enabled = joins, width = w, iconSize = 44.dp) { vm.chooseSelectionRemoves(true) }+ ToolbarButton(PcIcons.Invert, "Invert", enabled = has, width = w, iconSize = 44.dp) { vm.invertSelection() }+ ToolbarButton(PcIcons.SelectCopyPaste, "Copy & Paste", enabled = has || drawing, width = w, iconSize = 44.dp, labelSize = long) { vm.copySelectionToLayer() }+ ToolbarButton(PcIcons.Feather, "Feather", active = vm.selectionPopup == SelectionPopup.FEATHER, enabled = has || drawing, width = w, iconSize = 44.dp) {+ vm.openSelectionPopup(SelectionPopup.FEATHER)+ }+ ToolbarButton(PcIcons.SaveLoad, "Save & Load", active = vm.selectionPopup == SelectionPopup.SAVED, enabled = has || drawing, width = w, iconSize = 44.dp, labelSize = long) {+ vm.openSelectionPopup(SelectionPopup.SAVED)+ }+ ToolbarButton(PcIcons.ColorFill, "Color Fill", active = vm.colorFill, width = w, iconSize = 37.dp) { vm.toggleColorFill() }+ ToolbarButton(PcIcons.ClearSelection, "Clear", enabled = has || drawing, width = w, iconSize = 44.dp) { vm.clearSelection() }+ }+}++/** A popover over the selection toolbar: feathering the selection, or the selections kept. */+@Composable+fun SelectionPopover(vm: CanvasViewModel, screenWidth: Dp, screenHeight: Dp) {+ val popup = vm.selectionPopup+ if (popup == SelectionPopup.NONE) return+ val width = if (popup == SelectionPopup.FEATHER) FeatherWidth else MenuWidth+ val layout = toolbarLayout(screenWidth, 8, SelectionButtonRoomy, SelectionButtonWidth)+ val centre = toolbarButtonCentre(screenWidth, layout, if (popup == SelectionPopup.FEATHER) 4 else 5, 8)+ val left = (centre - width / 2).coerceIn(0.dp, screenWidth - width)+ MenuPopover(centre - left, left, toolbarButtonsTop(screenHeight), width) {+ when (popup) {+ SelectionPopup.FEATHER -> {+ MenuTitle("Feather")+ Spacer(Modifier.height(4.dp))+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(MenuGroupCorner)).background(MenuGroup).padding(vertical = 8.dp)) {+ val amount = vm.featherAmount+ SliderRow("Amount", amount, if (amount <= 0f) "None" else "${(amount * 100).roundToInt()}%") { vm.featherTo(it) }+ }+ }+ SelectionPopup.SAVED -> SavedSelections(vm)+ SelectionPopup.NONE -> Unit+ }+ }+}++@Composable+private fun SavedSelections(vm: CanvasViewModel) {+ Row(Modifier.fillMaxWidth().height(40.dp).padding(start = 14.dp), verticalAlignment = Alignment.CenterVertically) {+ Text("Selections", color = MenuText, fontSize = 24.sp, fontWeight = FontWeight.Bold, letterSpacing = (-0.015).em, maxLines = 1, modifier = Modifier.weight(1f))+ Box(Modifier.size(40.dp, 36.dp).tap { vm.saveSelection() }, contentAlignment = Alignment.Center) {+ Icon(PcIcons.Add, contentDescription = "Save new selection", tint = MenuText, modifier = Modifier.requiredSize(40.dp))+ }+ }+ Spacer(Modifier.height(8.dp))+ LazyColumn(Modifier.fillMaxWidth().height(172.dp), verticalArrangement = Arrangement.spacedBy(1.dp)) {+ items(vm.savedSelections) { i ->+ Row(+ Modifier.fillMaxWidth().height(51.dp).clip(RoundedCornerShape(MenuGroupCorner)).background(MenuGroup).tap { vm.loadSelection(i) },+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Box(Modifier.size(64.dp, 46.dp).clip(RoundedCornerShape(topStart = MenuGroupCorner, bottomStart = MenuGroupCorner)).background(SavedThumb), contentAlignment = Alignment.Center) {+ vm.savedThumbnails[i]?.let { Image(it, contentDescription = null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize()) }+ }+ Spacer(Modifier.width(14.dp))+ MenuLabel("Selection ${i + 1}", modifier = Modifier.weight(1f))+ }+ }+ }+}++/**+ * What the selection tool shows while a shape is made: the rectangle or ellipse being dragged and+ * the freehand path (dashed, its first point a dot to close it on), and the bar and crosshair while+ * a colour selection's threshold is dragged.+ */+@Composable+fun SelectionOverlay(vm: CanvasViewModel, barTop: Dp) {+ val drag = vm.shapeDrag+ val path = vm.freehand+ val threshold = vm.thresholdDrag+ if (drag == null && path.isEmpty() && threshold == null) return+ Canvas(Modifier.fillMaxSize()) {+ drag?.let { (a, b) ->+ val outline = Path().apply {+ val r = Rect(minOf(a.x, b.x), minOf(a.y, b.y), maxOf(a.x, b.x), maxOf(a.y, b.y))+ if (vm.selectionKind == SelectionKind.ELLIPSE) addOval(r) else addRect(r)+ }+ dashed(outline)+ }+ if (path.isNotEmpty()) {+ val points = path.map { vm.canvasToWindow(it) }+ val line = Path().apply {+ moveTo(points[0].x, points[0].y)+ for (p in points.drop(1)) lineTo(p.x, p.y)+ }+ dashed(line)+ drawCircle(StartDot, 5.5.dp.toPx(), points[0])+ }+ threshold?.let { (p, _) ->+ // a thin cross where the colour is picked+ val arm = 8.dp.toPx()+ val w = 1.dp.toPx()+ drawLine(Dash, Offset(p.x - arm, p.y), Offset(p.x + arm, p.y), w)+ drawLine(Dash, Offset(p.x, p.y - arm), Offset(p.x, p.y + arm), w)+ }+ }+ threshold?.let { (_, t) ->+ Box(Modifier.offset(y = barTop).fillMaxWidth().height(24.dp).background(Pc.MessageBar), contentAlignment = Alignment.Center) {+ Text("Selection Threshold ${formatPercent(t)}", color = Pc.MessageText, fontSize = 14.sp)+ }+ }+}++/** A path drawn as the selection's outline: thin dark dashes over light ones. */+private fun DrawScope.dashed(path: Path) {+ val dash = 5.dp.toPx()+ val width = 0.75.dp.toPx()+ drawPath(path, DashGap, style = Stroke(width, pathEffect = PathEffect.dashPathEffect(floatArrayOf(dash, dash), dash)))+ drawPath(path, Dash, style = Stroke(width, pathEffect = PathEffect.dashPathEffect(floatArrayOf(dash, dash), 0f)))+}++/** A threshold (0..1) as a percentage with one decimal. */+private fun formatPercent(t: Float): String = "${(t * 1000).roundToInt() / 10f}%"diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/SourceEditorUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/SourceEditorUi.ktnew file mode 100644index 0000000..ce600ff--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/SourceEditorUi.kt@@ -0,0 +1,367 @@+package io.github.artcraftandroid.procraft.ui++import android.content.res.Configuration+import androidx.activity.compose.BackHandler+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.PickVisualMediaRequest+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.grid.GridCells+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid+import androidx.compose.foundation.lazy.grid.itemsIndexed+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.graphics.ImageShader+import androidx.compose.ui.graphics.ShaderBrush+import androidx.compose.ui.graphics.TileMode+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalConfiguration+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.compose.ui.window.Popup+import androidx.compose.ui.window.PopupProperties+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import kotlin.math.roundToInt+import kotlinx.coroutines.launch++private val EditorPage = Color(0xFF2A2A2A)+private val EditorView = Color(0xFF262626)+private val EditorTitle = Color(0xFFEEEEEE)+private val CapsuleFill = Color(0xFF1C1C1C)+private val CapsuleEdge = Color(0xFF383838)+private val CapsuleInk = Color(0xFFAAAAAA)+private val DoneBlue = Color(0xFF0190FF)+private val RepeatLabel = Color(0xFF808080)+private val LibraryVeil = Color(0x80000000)+private val LibraryBar = Color(0xF21C1C1C)+private val MenuBlue = Color(0xFF0A84FF)++/**+ * The shape or grain editor of the brush studio (the one [CanvasViewModel.sourceEditing] says):+ * the image in a 600 square, changed by Import (a photo, a file, the source library or the+ * clipboard) or turned negative by a two-finger tap; the grain editor can also make it repeat+ * without seams. Cancel leaves the brush as it was, the tick keeps the change.+ */+@Composable+fun SourceEditor(vm: CanvasViewModel) {+ val grain = vm.sourceEditing ?: return+ val scope = rememberCoroutineScope()+ // the image as edited here (empty: the round tip), and the shipped one it is if it is one+ var image by remember(grain) { mutableStateOf(vm.studioSourcePixels(grain)) }+ var shipped by remember(grain) { mutableStateOf<Int?>(null) }+ var importing by remember { mutableStateOf(false) }+ var library by remember { mutableStateOf(false) }+ // Auto repeat and its settings+ var repeating by remember { mutableStateOf(false) }+ var scale by remember { mutableFloatStateOf(0f) }+ var rotate by remember { mutableFloatStateOf(0f) }+ var overlap by remember { mutableFloatStateOf(1f) }+ var hardness by remember { mutableFloatStateOf(0f) }+ var mirror by remember { mutableStateOf(false) }+ var pyramid by remember { mutableStateOf(true) }+ fun result(): ByteArray =+ if (repeating && image.isNotEmpty()) vm.repeatSource(image, 1f + scale * 3f, rotate * 360f, overlap, hardness, mirror, pyramid) else image+ val shown = remember(image, repeating, scale, rotate, overlap, hardness, mirror, pyramid) { vm.sourceBitmap(result(), shape = !grain) }+ fun take(pixels: ByteArray?) {+ if (pixels != null && pixels.isNotEmpty()) {+ image = pixels+ shipped = null+ }+ }+ val file = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> uri?.let { scope.launch { take(vm.decodeSource(it)) } } }+ val photo = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri -> uri?.let { scope.launch { take(vm.decodeSource(it)) } } }+ BackHandler { vm.sourceEditing = null }+ // landscape: a page sliding over the studio from the right, its pages' card still showing+ val landscape = LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE+ Box(Modifier.fillMaxSize().pointerInput(Unit) { awaitEachGesture { awaitFirstDown().consume() } }) {+ BoxWithConstraints(+ Modifier.fillMaxSize()+ .then(if (landscape) Modifier.padding(start = 246.dp).clip(RoundedCornerShape(topStart = 20.dp, bottomStart = 20.dp)) else Modifier)+ .background(EditorPage),+ ) {+ // the grain repeating over the whole page+ if (repeating && shown != null) {+ Box(Modifier.fillMaxSize().background(ShaderBrush(ImageShader(shown, TileMode.Repeated, TileMode.Repeated))))+ } else {+ Box(+ Modifier.align(Alignment.Center).offset(y = 32.dp).size(600.dp, 601.dp).clip(RoundedCornerShape(20.dp)).background(EditorView)+ .pointerInput(Unit) {+ // a two-finger tap turns the image negative+ awaitEachGesture {+ awaitFirstDown(requireUnconsumed = false)+ var most = 1+ while (true) {+ val event = awaitPointerEvent()+ most = maxOf(most, event.changes.count { it.pressed })+ if (event.changes.none { it.pressed }) break+ }+ if (most == 2 && image.isNotEmpty()) {+ image = ByteArray(image.size) { i -> (255 - (image[i].toInt() and 0xFF)).toByte() }+ shipped = null+ }+ }+ },+ ) {+ shown?.let { Image(it, contentDescription = null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize()) }+ // the round tip: a white disc+ ?: if (!grain) Box(Modifier.align(Alignment.Center).size(480.dp).clip(CircleShape).background(Color.White)) else Box(Modifier.fillMaxSize().background(Color.White))+ }+ }+ Text(+ if (grain) "Grain Editor" else "Shape Editor", color = EditorTitle, fontSize = 22.sp, fontWeight = FontWeight.Bold,+ modifier = Modifier.offset(24.dp, if (landscape) 16.dp else 26.dp),+ )+ Row(+ Modifier.align(Alignment.TopEnd).padding(top = if (landscape) 10.dp else 20.dp, end = if (landscape) 12.dp else 20.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Row(Modifier.height(43.dp).clip(CircleShape).background(CapsuleFill).border(1.dp, CapsuleEdge, CircleShape), verticalAlignment = Alignment.CenterVertically) {+ Box {+ CapsuleButton("Import", 71) { importing = true }+ ImportMenu(importing, onDismiss = { importing = false }) { choice ->+ importing = false+ when (choice) {+ 0 -> photo.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))+ 1 -> file.launch(arrayOf("image/*"))+ 2 -> library = true+ else -> scope.launch { take(vm.pastedSource()) }+ }+ }+ }+ if (grain) CapsuleButton("Auto repeat", 107, on = repeating) { repeating = !repeating }+ CapsuleButton("Cancel", 73) { vm.sourceEditing = null }+ }+ Spacer(Modifier.width(13.dp))+ Box(+ Modifier.size(44.dp, 45.dp).clip(CircleShape).background(DoneBlue).tap {+ vm.keepStudioSource(grain, result(), shipped.takeIf { !repeating })+ },+ contentAlignment = Alignment.Center,+ ) {+ Icon(PcIcons.DoneTick, contentDescription = "Done", tint = Color.White, modifier = Modifier.requiredSize(40.dp))+ }+ }+ if (repeating) RepeatPanel(+ Modifier.align(Alignment.BottomCenter).padding(bottom = 30.dp),+ scale, rotate, overlap, hardness, mirror, pyramid,+ onScale = { scale = it }, onRotate = { rotate = it }, onOverlap = { overlap = it }, onHardness = { hardness = it },+ onMirror = { mirror = it }, onPyramid = { pyramid = it },+ )+ if (library) SourceLibrary(vm, grain, onPick = { i ->+ image = vm.librarySource(grain, i)+ shipped = i+ library = false+ }) { library = false }+ }+ }+}++@Composable+private fun CapsuleButton(label: String, width: Int, on: Boolean = false, onClick: () -> Unit) {+ Box(+ Modifier.size(width.dp, 43.dp).clip(CircleShape).background(if (on) Pc.Accent else Color.Transparent).tap(onClick),+ contentAlignment = Alignment.Center,+ ) {+ Text(label, color = if (on) Color.White else CapsuleInk, fontSize = 17.sp, maxLines = 1)+ }+}++/** Where the image can come from, in a light popover under Import. */+@Composable+private fun ImportMenu(open: Boolean, onDismiss: () -> Unit, onPick: (Int) -> Unit) {+ val density = androidx.compose.ui.platform.LocalDensity.current+ MenuPresence(open, androidx.compose.ui.graphics.TransformOrigin(0.5f, 0f)) { look ->+ Popup(+ alignment = Alignment.TopCenter,+ offset = with(density) { androidx.compose.ui.unit.IntOffset(0, 48.dp.roundToPx()) },+ onDismissRequest = onDismiss,+ properties = PopupProperties(focusable = true),+ ) {+ Column(look.width(320.dp).clip(RoundedCornerShape(24.dp)).background(Pc.LightPanel).padding(start = 8.dp, end = 8.dp, bottom = 8.dp)) {+ Text("Image source", color = Pc.LightText, fontSize = 22.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 12.dp, top = 16.dp, bottom = 12.dp))+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(14.dp)).background(Pc.LightRow)) {+ MenuRow(PcIcons.SourcePhoto, "Import a photo") { onPick(0) }+ Box(Modifier.padding(start = 52.dp).fillMaxWidth().height(1.dp).background(Pc.LightSeparator))+ MenuRow(PcIcons.Folder, "Import a file") { onPick(1) }+ Box(Modifier.padding(start = 52.dp).fillMaxWidth().height(1.dp).background(Pc.LightSeparator))+ MenuRow(PcIcons.SourceBooks, "Source Library") { onPick(2) }+ }+ Spacer(Modifier.height(20.dp))+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(14.dp)).background(Pc.LightRow)) {+ MenuRow(PcIcons.TextPaste, "Paste", iconSize = 40.dp) { onPick(3) }+ }+ }+ }+ }+}++@Composable+private fun MenuRow(icon: ImageVector, label: String, iconSize: Dp = 24.dp, onClick: () -> Unit) {+ Row(Modifier.fillMaxWidth().height(44.dp).tap(onClick).padding(start = 18.dp), verticalAlignment = Alignment.CenterVertically) {+ // in a 24 slot; icons drawn in a padded frame are shown bigger+ Box(Modifier.size(24.dp), contentAlignment = Alignment.Center) {+ Icon(icon, contentDescription = null, tint = MenuBlue, modifier = Modifier.requiredSize(iconSize))+ }+ Text(label, color = Pc.LightText, fontSize = 17.sp, maxLines = 1, modifier = Modifier.padding(start = 22.dp))+ }+}++/** Auto repeat's settings: two columns of sliders and switches in a panel along the bottom. */+@Composable+private fun RepeatPanel(+ modifier: Modifier,+ scale: Float, rotate: Float, overlap: Float, hardness: Float, mirror: Boolean, pyramid: Boolean,+ onScale: (Float) -> Unit, onRotate: (Float) -> Unit, onOverlap: (Float) -> Unit, onHardness: (Float) -> Unit,+ onMirror: (Boolean) -> Unit, onPyramid: (Boolean) -> Unit,+) {+ Column(+ modifier.size(650.dp, 228.dp).clip(RoundedCornerShape(16.dp)).background(EditorPage).padding(16.dp),+ verticalArrangement = Arrangement.spacedBy(16.dp),+ ) {+ Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {+ RepeatSlider("Grain scale", "%.1f".format(1f + scale * 3f).trimEnd('0').trimEnd('.'), scale, onScale)+ RepeatSlider("Rotate", "${(rotate * 360f).roundToInt()}°", rotate, onRotate)+ }+ Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {+ RepeatSlider("Border overlap", if (overlap >= 1f) "Maximal" else if (overlap <= 0f) "None" else "${(overlap * 100).roundToInt()}%", overlap, onOverlap)+ RepeatSlider("Mask hardness", if (hardness <= 0f) "Soft" else if (hardness >= 1f) "Hard" else "${(hardness * 100).roundToInt()}%", hardness, onHardness)+ }+ Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {+ RepeatSwitch("Mirror overlap", mirror, onMirror)+ RepeatSwitch("Pyramid blending", pyramid, onPyramid)+ }+ }+}++@Composable+private fun RepeatSlider(label: String, value: String, at: Float, onChange: (Float) -> Unit) {+ Column(Modifier.width(301.dp).height(55.dp)) {+ Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp)) {+ Text(label, color = RepeatLabel, fontSize = 15.sp, maxLines = 1, modifier = Modifier.weight(1f))+ Text(value, color = RepeatLabel, fontSize = 15.sp, maxLines = 1)+ }+ SimpleSlider(at, onChange, Modifier.padding(horizontal = 16.dp))+ }+}++@Composable+private fun RepeatSwitch(label: String, on: Boolean, onChange: (Boolean) -> Unit) {+ Row(Modifier.width(301.dp).height(40.dp).tap { onChange(!on) }.padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {+ Text(label, color = RepeatLabel, fontSize = 15.sp, maxLines = 1, modifier = Modifier.weight(1f))+ Switch(on, enabled = true)+ }+}++/** A thin track with a white knob: the position follows the finger. */+@Composable+private fun SimpleSlider(value: Float, onChange: (Float) -> Unit, modifier: Modifier) {+ BoxWithConstraints(+ modifier.fillMaxWidth().height(20.dp).pointerInput(Unit) {+ awaitEachGesture {+ val down = awaitFirstDown()+ fun send(x: Float) = onChange((x / size.width).coerceIn(0f, 1f))+ send(down.position.x)+ while (true) {+ val event = awaitPointerEvent()+ val c = event.changes.firstOrNull { it.id == down.id } ?: break+ if (!c.pressed) break+ send(c.position.x)+ c.consume()+ }+ }+ },+ contentAlignment = Alignment.CenterStart,+ ) {+ val w = maxWidth+ Box(Modifier.fillMaxWidth().height(3.dp).clip(CircleShape).background(Color(0xFF3E3E3E)))+ Box(Modifier.width(w * value).height(3.dp).clip(CircleShape).background(Pc.Accent))+ Box(Modifier.offset(x = (w - 16.dp) * value).size(16.dp, 10.dp).clip(CircleShape).background(Color.White))+ }+}++/**+ * The source library: the shipped shape or grain images in 180 cells (the image 146 square, its+ * name under it) under a bar with the title, Cancel, and Shape Source and Grain Source.+ */+@Composable+private fun SourceLibrary(vm: CanvasViewModel, grain: Boolean, onPick: (Int) -> Unit, onCancel: () -> Unit) {+ var showGrains by remember { mutableStateOf(grain) }+ val images: List<Pair<String, ImageBitmap?>> = if (showGrains) vm.grainLibrary else vm.shapeLibrary+ BackHandler(onBack = onCancel)+ Box(Modifier.fillMaxSize().background(LibraryVeil)) {+ LazyVerticalGrid(+ columns = GridCells.Adaptive(180.dp),+ contentPadding = PaddingValues(top = 183.dp, start = 12.dp, end = 12.dp, bottom = 24.dp),+ modifier = Modifier.fillMaxSize(),+ ) {+ itemsIndexed(images) { i, (name, image) ->+ Column(+ Modifier.size(180.dp).tap {+ // each kind takes its own: a grain picked in the shape editor is not taken+ if (showGrains == grain) onPick(i)+ },+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ Box(Modifier.padding(top = 6.dp).size(146.dp).clip(RoundedCornerShape(8.dp)).background(Color.Black)) {+ image?.let { Image(it, contentDescription = name, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize()) }+ }+ Text(name, color = Color.White, fontSize = 17.sp, maxLines = 1, modifier = Modifier.padding(top = 5.dp))+ }+ }+ }+ Column(Modifier.fillMaxWidth().height(183.dp).background(LibraryBar)) {+ Row(Modifier.fillMaxWidth().height(128.dp).padding(start = 20.dp, end = 20.dp, bottom = 20.dp), verticalAlignment = Alignment.Bottom) {+ Text("Source Library", color = Color.White, fontSize = 27.sp, fontWeight = FontWeight.Bold, maxLines = 1, modifier = Modifier.weight(1f))+ Text("Cancel", color = Color.White, fontSize = 18.sp, maxLines = 1, modifier = Modifier.tap(onCancel))+ }+ Row(Modifier.fillMaxWidth().height(55.dp), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically) {+ for ((label, isGrain) in listOf("Shape Source" to false, "Grain Source" to true)) {+ Box(+ Modifier.padding(horizontal = 6.dp).size(114.dp, 40.dp).clip(RoundedCornerShape(8.dp))+ .background(if (showGrains == isGrain) Pc.Accent else Color.Transparent).tap { showGrains = isGrain },+ contentAlignment = Alignment.Center,+ ) {+ Text(label, color = Color.White, fontSize = 15.sp, maxLines = 1)+ }+ }+ }+ }+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/TextUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/TextUi.ktnew file mode 100644index 0000000..8a78919--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/TextUi.kt@@ -0,0 +1,468 @@+package io.github.artcraftandroid.procraft.ui++import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.Canvas+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.BoxScope+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ColumnScope+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.WindowInsets+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.ime+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.layout.windowInsetsPadding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.alpha+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.drawBehind+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.graphics.toArgb+import androidx.compose.ui.graphics.nativeCanvas+import androidx.compose.ui.graphics.drawscope.drawIntoCanvas+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.platform.LocalSoftwareKeyboardController+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material3.Icon+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import io.github.artcraftandroid.procraft.canvas.TextRenderer+import io.github.artcraftandroid.procraft.core.TextAlignment+import io.github.artcraftandroid.procraft.core.TextInfo+import kotlin.math.roundToInt++private val SheetFill = Color(0xFF535353)+private val SheetBar = Color(0xFF4F4F4F)+private val SheetCapsule = Color(0xFF3E3E3E)+private val CardFill = Color(0xFF373737)+private val ButtonFill = Color(0xFF474747)+private val SegmentTrack = Color(0xFF646464)+private val CapsuleInk = Color(0xFFC5C5C5)+private val KeyboardDisc = Color(0xFF393939)+private val KeyboardBar = Color(0xFF2B2B2B)+private val DoneBlue = Color(0xFF0190FF)+private val BoxLine = Color(0xFF0076FD)++/**+ * Text being edited: its box drawn over the canvas, a hidden field the keyboard types into, and a+ * bar above the keyboard with the style sheet's button and Done. Tapping outside the box keeps the+ * text.+ */+@Composable+fun BoxScope.TextEditor(vm: CanvasViewModel) {+ val info = vm.textInfo ?: return+ val focus = remember { FocusRequester() }+ val keyboard = LocalSoftwareKeyboardController.current+ val box by rememberUpdatedState(windowBox(vm, info))+ // a tap outside the box ends the edit, keeping it; dragging inside it moves the text+ Box(Modifier.fillMaxSize().pointerInput(Unit) {+ awaitEachGesture {+ val down = awaitFirstDown()+ if (!box.contains(down.position)) {+ vm.endText(true)+ return@awaitEachGesture+ }+ var last = down.position+ while (true) {+ val c = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break+ if (!c.pressed) break+ vm.moveText(last, c.position)+ last = c.position+ c.consume()+ }+ }+ })+ TextBox(vm, info)+ BasicTextField(vm.textField, vm::changeTextField, Modifier.size(1.dp).alpha(0f).focusRequester(focus))+ LaunchedEffect(vm.textStyleOpen) {+ if (vm.textStyleOpen) keyboard?.hide() else {+ focus.requestFocus()+ keyboard?.show()+ }+ }+ Column(Modifier.align(Alignment.BottomCenter).fillMaxWidth().windowInsetsPadding(WindowInsets.ime)) {+ if (vm.textStyleOpen) TextStyleSheet(vm, info) else TextBar(vm)+ }+}++/** A stroke on a text layer: it takes paint once rasterized. */+@Composable+fun RasterizePrompt(vm: CanvasViewModel) {+ Alert(+ if (vm.askRasterize) Unit else null,+ title = { "Rasterize this text layer?" },+ message = { "Its text can't be edited afterwards; you can paint on it." },+ action = "Rasterize",+ destructive = false,+ onCancel = { vm.askRasterize = false },+ onAction = {+ vm.askRasterize = false+ vm.layers.firstOrNull { it.current }?.let(vm::rasterize)+ },+ )+}++/** The text's box in the window, as the smallest upright rectangle around it. */+private fun windowBox(vm: CanvasViewModel, info: TextInfo): androidx.compose.ui.geometry.Rect {+ val b = TextRenderer.bounds(info)+ val corners = listOf(Offset(b.left, b.top), Offset(b.right, b.top), Offset(b.right, b.bottom), Offset(b.left, b.bottom)).map(vm::canvasToWindow)+ return androidx.compose.ui.geometry.Rect(corners.minOf { it.x }, corners.minOf { it.y }, corners.maxOf { it.x }, corners.maxOf { it.y })+}++/** The text's box: a thin blue line around where it is drawn, a dot at the middle of each side. */+@Composable+private fun TextBox(vm: CanvasViewModel, info: TextInfo) {+ val box = remember(info) { TextRenderer.bounds(info) }+ val layout = remember(info) { TextRenderer.layout(info) }+ val corners = listOf(Offset(box.left, box.top), Offset(box.right, box.top), Offset(box.right, box.bottom), Offset(box.left, box.bottom)).map(vm::canvasToWindow)+ val selection = vm.textField.selection+ Canvas(Modifier.fillMaxSize()) {+ val path = Path().apply {+ moveTo(corners[0].x, corners[0].y)+ corners.drop(1).forEach { lineTo(it.x, it.y) }+ close()+ }+ drawPath(path, BoxLine, style = Stroke(1.dp.toPx()))+ for (side in listOf(corners[0] + (corners[3] - corners[0]) / 2f, corners[1] + (corners[2] - corners[1]) / 2f)) {+ drawCircle(BoxLine, 3.dp.toPx(), side)+ }+ // the caret, or the selected letters ringed in blue with a handle at each end (the text as+ // laid out; vertical text spreads its letters apart, so it shows none)+ if (info.vertical) return@Canvas+ val length = layout.text.length+ val (start, end) = selection.min.coerceIn(0, length) to selection.max.coerceIn(0, length)+ val m = vm.viewMatrix+ val toWindow = android.graphics.Matrix().apply {+ setValues(floatArrayOf(m[0], m[2], m[4], m[1], m[3], m[5], 0f, 0f, 1f))+ preTranslate(info.x, info.y - info.baseline * info.size)+ }+ fun at(offset: Int, bottom: Boolean): Offset {+ val line = layout.getLineForOffset(offset)+ val p = floatArrayOf(layout.getPrimaryHorizontal(offset), (if (bottom) layout.getLineBottom(line) else layout.getLineTop(line)).toFloat())+ toWindow.mapPoints(p)+ return Offset(p[0], p[1])+ }+ if (start == end) {+ drawLine(BoxLine, at(start, false), at(start, true), 2.dp.toPx())+ return@Canvas+ }+ drawIntoCanvas { c ->+ val canvas = c.nativeCanvas+ val chosen = android.graphics.Path().also { layout.getSelectionPath(start, end, it) }+ val paint = layout.paint+ val (style, width, colour) = Triple(paint.style, paint.strokeWidth, paint.color)+ canvas.save()+ canvas.concat(toWindow)+ canvas.clipPath(chosen)+ paint.style = android.graphics.Paint.Style.STROKE+ paint.strokeWidth = info.size * SELECTED_RING+ paint.strokeJoin = android.graphics.Paint.Join.ROUND+ paint.color = BoxLine.toArgb()+ layout.draw(canvas)+ // the letters again in their own colour over their ring+ paint.style = style+ paint.strokeWidth = width+ paint.color = colour+ layout.draw(canvas)+ canvas.restore()+ }+ val (top, bottom) = at(start, false) to at(end, true)+ drawLine(BoxLine, top, at(start, true), 2.dp.toPx())+ drawLine(BoxLine, at(end, false), bottom, 2.dp.toPx())+ drawCircle(BoxLine, 6.dp.toPx(), top)+ drawCircle(BoxLine, 6.dp.toPx(), bottom)+ }+}++/** How wide the blue ring round selected letters is, as a fraction of the text's size. */+private const val SELECTED_RING = 0.08f++/** Above the keyboard: Edit style on the right. */+@Composable+private fun TextBar(vm: CanvasViewModel) {+ Row(Modifier.fillMaxWidth().height(44.dp).background(KeyboardBar).padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {+ Spacer(Modifier.weight(1f))+ Text("Edit style", color = Color.White, fontSize = 15.sp, modifier = Modifier.clickable { vm.openTextStyle() }.padding(8.dp))+ }+}++/**+ * The style sheet in the keyboard's place: a bar (the keyboard back, cut, copy and paste, import+ * a font, Cancel, Done); then Typeface (fonts and styles, each name in its own face) or Design+ * (size, spacing, opacity, and the attributes), switched at the bottom.+ */+@Composable+private fun TextStyleSheet(vm: CanvasViewModel, info: TextInfo) {+ var page by remember { mutableIntStateOf(0) }+ val sheetWide = androidx.compose.ui.platform.LocalConfiguration.current.screenWidthDp.dp >= WIDE_SHEET+ val importFont = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> uri?.let(vm::importFont) }+ Column(Modifier.fillMaxWidth().height(561.dp).background(SheetFill)) {+ Row(Modifier.fillMaxWidth().height(62.dp).background(SheetBar).padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically) {+ SheetIcon(PcIcons.Keyboard, "Keyboard", Modifier.size(44.dp).clip(CircleShape).background(KeyboardDisc), 40.dp) { vm.textStyleOpen = false }+ Spacer(Modifier.width(13.dp))+ Row(Modifier.height(40.dp).clip(RoundedCornerShape(12.dp)).background(SheetCapsule)) {+ SheetIcon(PcIcons.TextCut, "Cut", Modifier.size(41.dp, 40.dp), 40.dp) { vm.copyText(cut = true) }+ Spacer(Modifier.width(7.dp))+ SheetIcon(PcIcons.TextCopy, "Copy", Modifier.size(41.dp, 40.dp), 40.dp) { vm.copyText(cut = false) }+ Spacer(Modifier.width(7.dp))+ SheetIcon(PcIcons.TextPaste, "Paste", Modifier.size(41.dp, 40.dp), 40.dp) { vm.pasteText() }+ }+ Spacer(Modifier.weight(1f))+ Row(Modifier.height(43.dp).clip(CircleShape).background(SheetCapsule), verticalAlignment = Alignment.CenterVertically) {+ Text(+ "Import", color = CapsuleInk, fontSize = 15.sp,+ modifier = Modifier.clickable { importFont.launch(arrayOf("font/ttf", "font/otf", "font/sfnt", "application/x-font-ttf", "application/x-font-otf", "application/octet-stream")) }.padding(horizontal = 14.dp),+ )+ Text("Cancel", color = CapsuleInk, fontSize = 15.sp, modifier = Modifier.clickable { vm.cancelTextStyle() }.padding(horizontal = 14.dp))+ }+ Spacer(Modifier.width(13.dp))+ Box(Modifier.size(44.dp, 45.dp).clip(CircleShape).background(DoneBlue).clickable { vm.endText(true) }, contentAlignment = Alignment.Center) {+ Icon(PcIcons.DoneTick, contentDescription = "Done", tint = Color.White, modifier = Modifier.requiredSize(40.dp))+ }+ }+ // wide (landscape), the four cards side by side; narrow, Typeface or Design, switched below+ BoxWithConstraints(Modifier.fillMaxWidth().weight(1f)) {+ val wide = maxWidth >= WIDE_SHEET+ Row(Modifier.fillMaxSize().padding(horizontal = if (wide) 9.dp else 3.dp)) {+ if (wide) {+ FontCard(vm, info, Modifier.weight(264f))+ Spacer(Modifier.width(2.dp))+ StyleCard(vm, info, Modifier.weight(184f))+ Spacer(Modifier.width(8.dp))+ DesignCard(vm, info, Modifier.weight(326f))+ Spacer(Modifier.width(8.dp))+ AttributesCard(vm, info, Modifier.weight(325f), wide = true)+ } else if (page == 0) {+ FontCard(vm, info, Modifier.weight(417f))+ Spacer(Modifier.width(2.dp))+ StyleCard(vm, info, Modifier.weight(296f))+ } else {+ DesignCard(vm, info, Modifier.weight(598f))+ Spacer(Modifier.width(10.dp))+ AttributesCard(vm, info, Modifier.weight(130f), wide = false)+ }+ }+ }+ // Typeface | Design, when the cards don't all fit+ if (!sheetWide) Box(Modifier.fillMaxWidth().height(81.dp).background(SheetFill)) {+ Row(+ Modifier.align(Alignment.TopCenter).padding(top = 11.dp).height(34.dp).clip(CircleShape).background(SegmentTrack).padding(2.dp),+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ ) {+ for ((i, label) in listOf("Typeface", "Design").withIndex()) {+ Box(+ Modifier.width(156.dp).height(30.dp).clip(CircleShape).background(if (i == page) Pc.Accent else Color.Transparent).clickable { page = i },+ contentAlignment = Alignment.Center,+ ) {+ Text(label, color = if (i == page) Color.White else CapsuleInk, fontSize = 13.sp)+ }+ }+ }+ }+ }+}++/** Below this width the sheet shows its cards in two pages. */+private val WIDE_SHEET = 900.dp++@Composable+private fun FontCard(vm: CanvasViewModel, info: TextInfo, modifier: Modifier) {+ Card("Font", modifier) {+ LazyColumn(Modifier.padding(horizontal = 7.dp), verticalArrangement = Arrangement.spacedBy(9.dp)) {+ items(TextRenderer.families) { f ->+ Cell(f.name, f.family == info.font, TextRenderer.typeface(f.family, "Regular")) { vm.changeText { it.copy(font = f.family) } }+ }+ }+ }+}++@Composable+private fun StyleCard(vm: CanvasViewModel, info: TextInfo, modifier: Modifier) {+ Card("Style", modifier) {+ LazyColumn(Modifier.padding(horizontal = 7.dp), verticalArrangement = Arrangement.spacedBy(9.dp)) {+ items(TextRenderer.styles) { st ->+ Cell(st.name, st.name == info.style, TextRenderer.typeface(info.font, st.name)) { vm.changeText { it.copy(style = st.name) } }+ }+ }+ }+}++@Composable+private fun DesignCard(vm: CanvasViewModel, info: TextInfo, modifier: Modifier) {+ val dpi = vm.canvasDpi()+ val pt = { px: Float -> px * 72f / dpi }+ Card("Design", modifier) {+ Column(Modifier.padding(horizontal = 5.dp)) {+ DesignRow("Size", sizeToSlider(info.size), "%.1fpt".format(pt(info.size)), fromMiddle = false) { v -> vm.changeText { it.copy(size = sliderToSize(v)) } }+ DesignRow("Kerning", info.kerning / 2f + 0.5f, "%.1f%%".format(info.kerning * 100f)) { v -> vm.changeText { it.copy(kerning = v * 2f - 1f) } }+ DesignRow("Tracking", info.tracking / 2f + 0.5f, "%.1f%%".format(info.tracking * 100f)) { v -> vm.changeText { it.copy(tracking = v * 2f - 1f) } }+ DesignRow("Leading", info.leading / 2f + 0.5f, "${pt(info.leading * info.size).roundToInt()}pt") { v -> vm.changeText { it.copy(leading = v * 2f - 1f) } }+ DesignRow("Baseline", info.baseline / 2f + 0.5f, "${pt(info.baseline * info.size).roundToInt()}pt") { v -> vm.changeText { it.copy(baseline = v * 2f - 1f) } }+ DesignRow("Opacity", info.opacity, "%.1f%%".format(info.opacity * 100f), fromMiddle = false) { v -> vm.changeText { it.copy(opacity = v) } }+ }+ }+}++/**+ * Alignment, underline, outline, vertical and all caps: wide, the four alignments in a row and the+ * other three in a row under them; narrow, the alignments two by two and the others one a row.+ */+@Composable+private fun AttributesCard(vm: CanvasViewModel, info: TextInfo, modifier: Modifier, wide: Boolean) {+ val aligns = listOf(+ TextAlignment.LEFT to PcIcons.AlignLeft, TextAlignment.CENTER to PcIcons.AlignCenter,+ TextAlignment.RIGHT to PcIcons.AlignRight, TextAlignment.JUSTIFY to PcIcons.AlignJustify,+ )+ Card("Attributes", modifier) {+ Column(Modifier.padding(horizontal = if (wide) 9.dp else 4.dp), verticalArrangement = Arrangement.spacedBy(if (wide) 19.dp else 2.dp)) {+ for (row in aligns.chunked(if (wide) 4 else 2)) {+ Row(horizontalArrangement = Arrangement.spacedBy(3.dp)) {+ for ((a, icon) in row) Attribute(icon, a.name, info.align == a, Modifier.weight(1f), 32.dp) { vm.changeText { it.copy(align = a) } }+ }+ }+ if (!wide) Spacer(Modifier.height(14.dp))+ val looks: @Composable (Modifier, Modifier, Modifier) -> Unit = { u, o, v ->+ Attribute(PcIcons.TextUnderline, "Underline", info.underline, u, 38.dp) { vm.changeText { it.copy(underline = !it.underline) } }+ Attribute(PcIcons.TextOutline, "Outline", info.outline, o, 38.dp) { vm.changeText { it.copy(outline = !it.outline) } }+ Attribute(PcIcons.TextVertical, "Vertical", info.vertical, v, 41.dp) { vm.changeText { it.copy(vertical = !it.vertical) } }+ }+ if (wide) {+ Row(horizontalArrangement = Arrangement.spacedBy(3.dp)) { looks(Modifier.weight(94f), Modifier.weight(94f), Modifier.weight(111f)) }+ } else {+ looks(Modifier.fillMaxWidth(), Modifier.fillMaxWidth(), Modifier.fillMaxWidth())+ Spacer(Modifier.height(16.dp))+ }+ Row(Modifier.clickable { vm.changeText { it.copy(allCaps = !it.allCaps) } }, verticalAlignment = Alignment.CenterVertically) {+ Text("TT", color = Color.White, fontSize = 20.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 8.dp).width(48.dp))+ if (wide) Spacer(Modifier.weight(1f))+ Switch(info.allCaps, enabled = true)+ }+ }+ }+}++@Composable+private fun SheetIcon(icon: ImageVector, label: String, modifier: Modifier, iconSize: Dp, onClick: () -> Unit) {+ Box(modifier.clip(RoundedCornerShape(10.dp)).clickable(onClick = onClick), contentAlignment = Alignment.Center) {+ // drawn in a padded frame, shown [iconSize] across+ Icon(icon, contentDescription = label, tint = CapsuleInk, modifier = Modifier.requiredSize(iconSize))+ }+}++@Composable+private fun Card(title: String, modifier: Modifier, content: @Composable ColumnScope.() -> Unit) {+ Column(modifier.fillMaxHeight().clip(RoundedCornerShape(bottomStart = 12.dp, bottomEnd = 12.dp)).background(CardFill)) {+ Text(title, color = Color.White, fontSize = 17.sp, fontWeight = FontWeight.SemiBold, modifier = Modifier.padding(start = 17.dp, top = 14.dp, bottom = 9.dp))+ content()+ }+}++/** A font or style: its name drawn in that face, the chosen one a blue cell. */+@Composable+private fun Cell(name: String, selected: Boolean, face: android.graphics.Typeface, onClick: () -> Unit) {+ val family = remember(face) { FontFamily(face) }+ Box(+ Modifier.fillMaxWidth().height(33.dp).background(if (selected) Pc.Accent else Color.Transparent).clickable(onClick = onClick).padding(start = 12.dp),+ contentAlignment = Alignment.CenterStart,+ ) {+ Text(name, color = Color.White, fontSize = 15.sp, fontFamily = family, maxLines = 1)+ }+}++/** An attribute's button: its icon, blue when on. */+@Composable+private fun Attribute(icon: ImageVector, label: String, on: Boolean, modifier: Modifier, iconSize: Dp, onClick: () -> Unit) {+ Box(+ modifier.height(37.dp).clip(RoundedCornerShape(8.dp)).background(if (on) Pc.Accent else ButtonFill).clickable(onClick = onClick),+ contentAlignment = Alignment.Center,+ ) {+ Icon(icon, contentDescription = label, tint = Color.White, modifier = Modifier.requiredSize(iconSize))+ }+}++/** A design setting: its name, its value in a pill, and a thin bar under them (filled from the left, or a tick in the middle). */+@Composable+private fun DesignRow(label: String, value: Float, shown: String, fromMiddle: Boolean = true, onChange: (Float) -> Unit) {+ val change by rememberUpdatedState(onChange)+ Column(Modifier.fillMaxWidth().height(58.5.dp).padding(horizontal = 16.dp)) {+ Row(Modifier.fillMaxWidth().padding(top = 6.dp), verticalAlignment = Alignment.CenterVertically) {+ Text(label, color = Color.White, fontSize = 15.sp, modifier = Modifier.weight(1f))+ Box(Modifier.height(24.dp).clip(CircleShape).background(ButtonFill).padding(horizontal = 10.dp), contentAlignment = Alignment.Center) {+ Text(shown, color = Color.White, fontSize = 13.sp)+ }+ }+ Box(+ Modifier.fillMaxWidth().height(20.dp).pointerInput(Unit) {+ awaitEachGesture {+ val down = awaitFirstDown()+ down.consume()+ change((down.position.x / size.width).coerceIn(0f, 1f))+ while (true) {+ val c = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break+ if (!c.pressed) break+ change((c.position.x / size.width).coerceIn(0f, 1f))+ c.consume()+ }+ }+ }.drawBehind {+ val y = size.height / 2f+ val h = 2.dp.toPx()+ val v = value.coerceIn(0f, 1f)+ drawRoundRect(Color(0xFF5A5A5A), Offset(0f, y - h / 2f), Size(size.width, h), CornerRadius(h / 2f))+ if (fromMiddle) {+ drawLine(Color(0xFF8A8A8A), Offset(size.width / 2f, y - 5.dp.toPx()), Offset(size.width / 2f, y + 5.dp.toPx()), 1.dp.toPx())+ } else {+ drawRoundRect(Pc.Accent, Offset(0f, y - h / 2f), Size(size.width * v, h), CornerRadius(h / 2f))+ }+ val knob = Size(16.dp.toPx(), 10.dp.toPx())+ val x = (size.width * v).coerceIn(knob.width / 2f, size.width - knob.width / 2f)+ drawRoundRect(Color.White, Offset(x - knob.width / 2f, y - knob.height / 2f), knob, CornerRadius(knob.height / 2f))+ },+ )+ }+}++/** The size slider runs 1 to 2000 pixels, finer at the small end. */+private fun sliderToSize(v: Float) = 1f + 1999f * v * v++private fun sizeToSlider(size: Float) = kotlin.math.sqrt(((size - 1f) / 1999f).coerceIn(0f, 1f))diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Theme.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Theme.ktnew file mode 100644index 0000000..d2ad7b0--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Theme.kt@@ -0,0 +1,213 @@+package io.github.artcraftandroid.procraft.ui++import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp++/** Interface colours and sizes. Sizes in dp equal the reference's points. */+object Pc {+ /** The light interface (Prefs) is on: panels and bars go light grey with dark text. */+ var light by mutableStateOf(false)++ /** A colour for the interface as it is now: [dark], or [light] when the light interface is on. */+ private fun pick(dark: Long, light: Long) = Color(if (this.light) light else dark)++ val Panel: Color get() = pick(0xF7262626, 0xF7E6E6E6)+ val Row: Color get() = pick(0xFF303030, 0xFFD8D8D8)+ val RowSelected = Color(0xFF0076FD)+ val Accent = Color(0xFF0076FD)+ val Text: Color get() = pick(0xFFFFFFFF, 0xFF222222)+ val TextDim: Color get() = pick(0x99FFFFFF, 0x99000000)+ val Disabled: Color get() = pick(0x4DFFFFFF, 0x4D000000)+ val Divider: Color get() = pick(0x26FFFFFF, 0x1F000000)+ val Surround = Color(0xFF1C1C1C)++ // the bar across the top of the canvas+ /** Translucent: #333333 over white, as the reference's bar. */+ val Bar: Color get() = pick(0xE61C1C1C, 0xF2E7E7E7)+ val BarText: Color get() = pick(0xFFAAAAAA, 0xFF3B3B3B)+ val BarGlyph: Color get() = pick(0xFFC7C7C7, 0xFF373737)+ val BarGlyphSelected = Color(0xFF0076FD)+ val ActionDisc: Color get() = pick(0xFF141414, 0xFFEDEDED)+ val ActionGlyph: Color get() = pick(0xFF969696, 0xFF646464)+ val ColorRing: Color get() = pick(0xFF969696, 0xFF696969)+ val BarHeight = 44.dp+ val BarMargin = 40.dp+ val BarButtonWidth = 44.dp+ val BarButtonHeight = 38.dp+ val GalleryWidth = 58.dp+ val ActionDiscSize = 32.dp+ val ColorDot = 31.dp++ // the panels hanging from the top bar+ val PopoverFill: Color get() = pick(0xFF383838, 0xFFE6E6E6)+ /** A panel's own material over the canvas: what is behind it shows through, blurred. */+ val PopoverFrost: Color get() = pick(0xDE1E1E1E, 0xFFE6E6E6)+ /**+ * The gallery's popovers: their glass as it shows over the gallery's dark (nothing blurs what+ * is behind them there, and unblurred it shows through too sharply).+ */+ val GalleryPopover: Color get() = pick(0xFF212121, 0xFFE6E6E6)+ val PopoverShadow: Color get() = pick(0x38000000, 0x24000000)+ val PopoverShadowRadius = 51.dp+ val PopoverCorner = 35.dp+ val PopoverGap = 12.dp+ val ArrowHeight = 12.dp+ val ArrowShift = 2.dp+ val PanelTitle: Color get() = pick(0xFFC7C7C7, 0xFF393939)+ val PanelGlyph: Color get() = pick(0xFFC8C8C8, 0xFF393939)+ val ChevronDisc: Color get() = pick(0xFF4C4C4C, 0xFFCFCFCF)+ val ChevronGlyph: Color get() = pick(0xFF2E2E2E, 0xFFE6E6E6)+ // a little white over the panel, so they follow its frosting+ val LayerRow: Color get() = pick(0x0DFFFFFF, 0xFFD8D8D8)+ val BackgroundRow: Color get() = pick(0x0DFFFFFF, 0xFFD8D8D8)+ val CheckFill: Color get() = pick(0xFFC7C7C7, 0xFF575757)+ val ThumbBackground: Color get() = pick(0xFF4F4F4F, 0xFFC8C8C8)+ // the brush library is glass like the other panels: the sets on the panel's own frost, the+ // brushes a shade darker, the set cells a little lighter (measured over white and over the+ // dark surround: 58 / 31, 52 / 26, 64 / 42)+ val SetColumn: Color get() = pick(0x00000000, 0xFFE6E6E6)+ val SetCell: Color get() = pick(0x2E5B5B5B, 0xFFD7D7D7)+ val BrushColumn: Color get() = pick(0x26000000, 0xFFE0E0E0)+ val Grabber: Color get() = pick(0x7AC6C6C6, 0xFFB0B0B0)+ val SwatchEdge: Color get() = pick(0xFF5A5A5A, 0xFFC0C0C0)+ val SaturationGrey = Color(0xFF7F7F7F)+ val ClearText: Color get() = pick(0xFFB5B5B5, 0xFF4A4A4A)+ val EmptySwatch: Color get() = pick(0xFF2A2A2A, 0xFFD9D9D9)+ val ValueGroup: Color get() = pick(0xFF434343, 0xFFD5D5D5)+ val HexRow: Color get() = pick(0xFF414141, 0xFFD8D8D8)+ val HexField: Color get() = pick(0xFF4B4B4B, 0xFFCFCFCF)+ val MenuFill: Color get() = pick(0xFF5A5C5B, 0xFFF0F0F0)+ /** The small frosted menus: over the canvas what is behind shows through, blurred. */+ val GlassMenu: Color get() = pick(0xCF313135, 0xFAF0F0F0)+ /** A small menu over a panel: the panel can't show through blurred, so it is nearly solid. */+ val GlassMenuOverPanel: Color get() = pick(0xFA1F232A, 0xFAF0F0F0)+ val GlassMenuEdge: Color get() = pick(0x24FFFFFF, 0x14000000)+ val RadioRing: Color get() = pick(0xFF606060, 0xFFB0B0B0)+ val MenuDanger: Color get() = pick(0xFFE84F51, 0xFFD93A3D)+ val MenuLine: Color get() = pick(0x33FFFFFF, 0x26000000)+ val MenuDisabled: Color get() = pick(0x66FFFFFF, 0x66000000)+ val SliderRest: Color get() = pick(0xFF5A5A5A, 0xFFBEBEBE)+ val EmptySlot: Color get() = pick(0xFF555555, 0xFFC8C8C8)+ // a dark wash on the panel's glass (26 over the dark surround, 44 over white)+ val ActionsGroup: Color get() = pick(0x420C0C0C, 0xFFE8E8E8)+ val ActionsSeparator: Color get() = pick(0xFF373737, 0xFFE2E2E2)+ /** An Actions row's text: dimmer than the panel's title (#a8a8a8 against #c7c7c7). */+ val ActionsRow: Color get() = pick(0xFFA8A8A8, 0xFF393939)+ val ActionsDisabled: Color get() = pick(0xFF5E5E5E, 0xFFABABAB)+ val TabIdle: Color get() = pick(0xFFA3A3A3, 0xFF404040)+ val SwitchOff: Color get() = pick(0xFF747377, 0xFFA9A8AC)+ val MessageBar: Color get() = pick(0xFF606060, 0xFFD0D0D0)+ val MessageText: Color get() = pick(0xFFB5B5B5, 0xFF3B3B3B)+ val LoupeEdge = Color(0xFF808080)+ val SlideLabel: Color get() = pick(0xFFC1C1C1, 0xFF3D3D3D)+ val SlideValue: Color get() = pick(0xFFEDEDED, 0xFF3D3D3D)+ val SlideTrack: Color get() = pick(0xFF414141, 0xFFBEBEBE)+ val SwitchFixed: Color get() = pick(0xFF404040, 0xFFD2D2D2)+ val SwitchFixedKnob: Color get() = pick(0xFF525252, 0xFFE9E9E9)++ /** The centre of tool button [index] (0 is the colour button, counting leftwards), from the bar's right edge. */+ fun toolCentreFromRight(index: Int, barWidth: Dp): Dp = BarMargin + BarButtonWidth / 2 + (BarButtonWidth + barGaps(barWidth).first) * index++ /** The centre of action button [index] (0 is actions, counting rightwards), from the bar's left edge. */+ fun actionCentre(index: Int, barWidth: Dp): Dp {+ val gap = barGaps(barWidth).second+ return BarMargin + GalleryWidth + gap + BarButtonWidth / 2 + (BarButtonWidth + gap) * index+ }++ // the gallery+ val GalleryBackground = Color(0xFF212121)+ val GalleryTitle = Color(0xFFF0F0F0)+ val GalleryText = Color(0xFFAAAAAA)+ val GallerySize = Color(0xFF666666)+ val Capsule = Color(0xFF1C1C1C)+ val CapsuleEdge = Color(0xFF393939)+ val LightPanel = Color(0xFFD5D5D5)+ val LightText = Color(0xFF393939)+ val LightRowStrong = Color(0xFFE1E1E1)+ val LightRow = Color(0xFFDEDEDE)+ val LightSeparator = Color(0xFFD2D2D2)+ val LightChip = Color(0xFFD6D6D6)++ // the side bar+ // the bar and the tracks translucent, each straight over what is behind (#2d2d2d and #676767+ // over white); the thumbs opaque (#a6a6a6 over white and over the dark surround alike)+ val SideBar: Color get() = pick(0xE7171717, 0xF2E8E8E8)+ val SliderTrack: Color get() = pick(0xC93E3E3E, 0xFFEDEDED)+ val SliderThumb: Color get() = pick(0xFFA6A6A6, 0xFFF8F8F8)+ val SideGlyph: Color get() = pick(0xFF969696, 0xFF646464)+ val SideGlyphDisabled: Color get() = pick(0x1AFFFFFF, 0x33000000)+ val SideBarWidth = 51.dp+ val SideBarHeight = 519.dp+ val SideBarCorner = 20.dp+ /** Where the side bar's centre sits, as a fraction of the screen height. */+ const val SIDE_BAR_CENTRE = 0.5234f+ val SliderWidth = 40.dp+ val SliderHeight = 170.dp+ val SliderCorner = 13.dp+ val ThumbWidth = 32.dp+ val ThumbHeight = 18.dp+ val ThumbInset = 4.dp+ val ModifySize = 22.5.dp+ val ModifyStroke = 2.4.dp+ val ModifyCorner = 6.dp++ /**+ * The gaps between the tool buttons and between the action buttons for a bar [width] wide:+ * the room left after both margins picks one of five steps.+ */+ fun barGaps(width: Dp): Pair<Dp, Dp> {+ val room = width - BarMargin * 2+ return when {+ room < 435.dp -> 2.dp to 4.dp+ room < 530.dp -> 8.dp to 14.dp+ room < 625.dp -> 26.dp to 14.dp+ room < 730.dp -> 8.dp to 14.dp+ else -> 26.dp to 14.dp+ }+ }+}++/**+ * The open canvas's colour space: its colours (0xRRGGBB values) are Display P3 numbers or sRGB+ * ones. The window is in wide colour, so P3 colours show as they are.+ */+object CanvasSpace {+ var p3 by mutableStateOf(false)+ private set++ /**+ * How the canvas shows a colour of its own, when not as its numbers say: as a CMYK canvas's+ * press prints it, or an imported profile's colour in Display P3.+ */+ private var shown by mutableStateOf<((Int) -> Int)?>(null)+ private val seen = HashMap<Int, Int>()+ private val displayP3 by lazy { android.graphics.ColorSpace.get(android.graphics.ColorSpace.Named.DISPLAY_P3) }++ /** The canvas's colours are Display P3 numbers (else sRGB), shown through [shown] if given. */+ fun set(p3: Boolean, shown: ((Int) -> Int)? = null) {+ seen.clear()+ this.p3 = p3+ this.shown = shown+ }++ /** A canvas colour, in the canvas's space. */+ fun color(rgb: Int): Color {+ val f = shown+ val c = if (f == null) rgb else seen.getOrPut(rgb) { f(rgb) }+ return if (p3) {+ Color(((c shr 16) and 0xFF) / 255f, ((c shr 8) and 0xFF) / 255f, (c and 0xFF) / 255f, 1f, androidx.compose.ui.graphics.colorspace.ColorSpaces.DisplayP3)+ } else {+ Color(0xFF000000 or c.toLong())+ }+ }++ /** [bitmap], of the canvas's colours, marked with the canvas's space. */+ fun tag(bitmap: android.graphics.Bitmap): android.graphics.Bitmap {+ if (p3) bitmap.setColorSpace(displayP3)+ return bitmap+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/TimeLapseUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/TimeLapseUi.ktnew file mode 100644index 0000000..3e6b0f8--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/TimeLapseUi.kt@@ -0,0 +1,92 @@+package io.github.artcraftandroid.procraft.ui++import androidx.activity.compose.BackHandler+import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.gestures.detectHorizontalDragGestures+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import io.github.artcraftandroid.procraft.canvas.TimeLapse+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.delay+import kotlinx.coroutines.withContext++private val ReplayFill = Color(0xFF252525)++/**+ * The time-lapse replayed over everything at its frame rate; dragging across the screen scrubs+ * through it. A bar on top: Done, the title and the time into the replay.+ */+@Composable+fun TimeLapseReplay(vm: CanvasViewModel) {+ val count = remember { vm.timeLapseFrames() }+ var index by remember { mutableIntStateOf(0) }+ var scrubbing by remember { mutableStateOf(false) }+ var shown by remember { mutableStateOf<ImageBitmap?>(null) }+ BackHandler { vm.timeLapseReplaying = false }+ // play, frame by frame, until the end or a scrub+ LaunchedEffect(scrubbing) {+ while (!scrubbing && index < count - 1) {+ delay(1000L / TimeLapse.FPS)+ index+++ }+ }+ LaunchedEffect(index) {+ val i = index+ val image = withContext(Dispatchers.IO) { vm.timeLapseFrame(i)?.asImageBitmap() }+ if (image != null) shown = image+ }+ Box(+ Modifier.fillMaxSize().background(ReplayFill).pointerInput(count) {+ var start = 0f+ var from = 0+ detectHorizontalDragGestures(+ onDragStart = { start = it.x; from = index; scrubbing = true },+ onHorizontalDrag = { change, _ ->+ change.consume()+ val moved = (change.position.x - start) / size.width+ index = (from + (moved * count).toInt()).coerceIn(0, (count - 1).coerceAtLeast(0))+ },+ onDragEnd = { scrubbing = false },+ onDragCancel = { scrubbing = false },+ )+ },+ ) {+ shown?.let {+ // edge to edge, under the header+ Image(it, contentDescription = "Time-lapse", contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize())+ }+ if (count == 0) Text("Nothing recorded yet", color = Color(0xFF8E8E93), fontSize = 17.sp, modifier = Modifier.align(Alignment.Center))+ // the time into the replay, in frames past the second+ val frames = index+ val seconds = frames / TimeLapse.FPS+ val time = "%02d:%02d:%02d:%02d".format(seconds / 3600, seconds / 60 % 60, seconds % 60, frames % TimeLapse.FPS)+ ToolHeader("Time-lapse Replay", listOf(ToolButton(time)), onDone = { vm.timeLapseReplaying = false }, colors = LightToolHeader)+ // how far it has played+ Box(Modifier.padding(top = ToolHeaderHeight).fillMaxWidth().height(4.dp)) {+ val f = if (count > 1) index / (count - 1).toFloat() else 1f+ Box(Modifier.fillMaxWidth(f.coerceIn(0f, 1f)).height(4.dp).background(Color(0xFF0076FD)))+ }+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ToolHeader.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ToolHeader.ktnew file mode 100644index 0000000..ad29650--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ToolHeader.kt@@ -0,0 +1,81 @@+package io.github.artcraftandroid.procraft.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp++private val HeaderLabel = Color(0xFFC5C5C5)+private val ButtonLabel = Color(0xFFA5A5A5)+private val ChosenLabel = Color(0xFFC0C0C0)+private val CapsuleChosen = Color(0xFF464646)+private val DoneBlue = Color(0xFF0190FF)++/** A full-screen tool's header is this tall. */+val ToolHeaderHeight = 85.dp++/** A button in a tool header's capsule: text, shown chosen, and what it does (none: just shown). */+class ToolButton(val label: String, val chosen: Boolean = false, val onClick: (() -> Unit)? = null)++/** A tool header's colours: its band, and its capsule's fill and edge. */+class ToolHeaderColors(val band: Color, val capsule: Color, val edge: Color)++/** Over the dark surround of a tool that edits the canvas. */+val DarkToolHeader = ToolHeaderColors(Color(0xFF1D1D1D), Color(0xFF1A1A1A), Color(0xFF373737))++/** Over a picture shown edge to edge. */+val LightToolHeader = ToolHeaderColors(Color(0xFF333333), Color(0xFF232323), Color(0xFF424242))++/**+ * The header full-screen tools share: the title on the left; on the right a capsule of text+ * buttons and the round blue Done.+ */+@Composable+fun ToolHeader(title: String, buttons: List<ToolButton>, onDone: () -> Unit, modifier: Modifier = Modifier, colors: ToolHeaderColors = DarkToolHeader) {+ // it fades in over the top bar as its mode begins+ val shown = androidx.compose.runtime.remember { androidx.compose.animation.core.Animatable(0f) }+ androidx.compose.runtime.LaunchedEffect(Unit) { shown.animateTo(1f, Motion.toolHeaderIn()) }+ Box(modifier.fillMaxWidth().height(ToolHeaderHeight).graphicsLayer { alpha = shown.value }.background(colors.band)) {+ Text(title, color = HeaderLabel, fontSize = 22.sp, fontWeight = FontWeight.Bold, maxLines = 1, modifier = Modifier.padding(start = 32.dp, top = 27.dp))+ Row(Modifier.align(Alignment.TopEnd).padding(top = 20.dp, end = 20.dp), verticalAlignment = Alignment.CenterVertically) {+ if (buttons.isNotEmpty()) {+ Row(Modifier.height(43.dp).clip(CircleShape).background(colors.capsule).border(1.dp, colors.edge, CircleShape), verticalAlignment = Alignment.CenterVertically) {+ for (b in buttons) {+ Box(+ Modifier.height(43.dp).clip(CircleShape).background(if (b.chosen) CapsuleChosen else Color.Transparent)+ .then(if (b.onClick != null) Modifier.clickable(onClick = b.onClick) else Modifier)+ .padding(horizontal = 13.dp),+ contentAlignment = Alignment.Center,+ ) {+ Text(b.label, color = if (b.chosen) ChosenLabel else ButtonLabel, fontSize = 17.sp, maxLines = 1)+ }+ }+ }+ Spacer(Modifier.width(13.dp))+ }+ Box(Modifier.size(44.dp).clip(CircleShape).background(DoneBlue).clickable(onClick = onDone), contentAlignment = Alignment.Center) {+ Icon(PcIcons.DoneTick, contentDescription = "Done", tint = Color.White, modifier = Modifier.requiredSize(40.dp))+ }+ }+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/TransformNumericUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/TransformNumericUi.ktnew file mode 100644index 0000000..c9fe713--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/TransformNumericUi.kt@@ -0,0 +1,156 @@+package io.github.artcraftandroid.procraft.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import io.github.artcraftandroid.procraft.core.TransformKind+import kotlin.math.abs+import kotlin.math.roundToInt++private val FieldIdle = Color(0xFF383838)+private val TopKey = Color(0xFF2E2E2E)+private val DigitKey = Color(0xFF414141)+private val KeyInk = Color(0xFFDADADA)+private val LinkOn = Color(0xFF1F436B)+private const val NUMERIC_WIDTH = 248++/**+ * Numeric entry for an open transform, from a tap on a node: "Dimensions" (the box's width and+ * height, linked or not) or "Rotation" (its angle), typed on a keypad. Each key changes the box at+ * once; a tap outside closes it.+ */+@Composable+fun TransformNumeric(vm: CanvasViewModel) {+ val open = vm.transformNumeric ?: return+ val box = vm.transformBox ?: return+ val density = LocalDensity.current+ // which field is typed into (0 width or the angle, 1 height), what is typed so far, and the link+ var field by remember(open) { mutableStateOf(0) }+ var typed by remember(open) { mutableStateOf("") }+ var linked by remember(open) { mutableStateOf(vm.transformKind == TransformKind.UNIFORM) }+ fun value(i: Int): Float = if (open.angle) box.angle else if (i == 0) box.width else box.height+ fun shown(i: Int): String {+ if (field == i && typed.isNotEmpty()) return typed + if (open.angle) " º" else " px"+ val v = value(i)+ return if (open.angle) "${(((v % 360f) + 360f) % 360f).roundToInt()} º" else "${v.roundToInt()} px"+ }+ fun apply() {+ val v = typed.toFloatOrNull() ?: return+ if (open.angle) {+ vm.transformSetAngle(v)+ return+ }+ val (w, h) = box.width to box.height+ when {+ field == 0 && linked && w > 0f -> vm.transformSetSize(v, h * abs(v) / w)+ field == 0 -> vm.transformSetSize(v, h)+ linked && h > 0f -> vm.transformSetSize(w * abs(v) / h, v)+ else -> vm.transformSetSize(w, v)+ }+ }+ fun key(k: String) {+ typed = when (k) {+ "AC" -> ""+ "±" -> if (typed.startsWith("-")) typed.drop(1) else "-" + typed.ifEmpty { value(field).roundToInt().toString() }+ "⌫" -> typed.dropLast(1)+ "." -> if ('.' in typed) typed else typed.ifEmpty { "0" } + "."+ else -> if (typed.length < 7) typed + k else typed+ }+ apply()+ }+ BoxWithConstraints(Modifier.fillMaxSize().pointerInput(open) { detectTapGestures { vm.transformNumeric = null } }) {+ // under the node, its arrow pointing at it, kept on the screen+ val width = NUMERIC_WIDTH.dp+ val at = with(density) { open.at.x.toDp() to open.at.y.toDp() }+ val left = (at.first - width / 2).coerceIn(8.dp, maxWidth - width - 8.dp)+ val top = (at.second + 14.dp).coerceIn(8.dp, (maxHeight - 420.dp).coerceAtLeast(8.dp))+ Popover(width, at.first - left, Modifier.offset(left, top).pointerInput(Unit) { detectTapGestures { } }, corner = 20.dp) {+ Column(Modifier.padding(start = 10.dp, end = 10.dp, bottom = 10.dp)) {+ Text(if (open.angle) "Rotation" else "Dimensions", color = KeyInk, fontSize = 20.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 10.dp, top = 12.dp, bottom = 12.dp))+ if (open.angle) {+ Row(Modifier.fillMaxWidth().height(41.dp).clip(RoundedCornerShape(10.dp)).background(FieldIdle), verticalAlignment = Alignment.CenterVertically) {+ Text("Angle", color = KeyInk, fontSize = 15.sp, modifier = Modifier.weight(1f).padding(start = 12.dp))+ NumberField(shown(0), chosen = true) { field = 0 }+ }+ } else {+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {+ NumberField(shown(0), chosen = field == 0) {+ field = 0+ typed = ""+ }+ Box(+ Modifier.size(52.dp, 35.dp).clip(RoundedCornerShape(9.dp)).background(if (linked) LinkOn else FieldIdle).tap { linked = !linked },+ contentAlignment = Alignment.Center,+ ) {+ Icon(PcIcons.Link, contentDescription = "Link", tint = if (linked) Pc.Accent else KeyInk, modifier = Modifier.size(22.dp))+ }+ NumberField(shown(1), chosen = field == 1) {+ field = 1+ typed = ""+ }+ }+ }+ Column(Modifier.padding(top = 14.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ for (row in listOf(listOf("AC", "±", "⌫"), listOf("7", "8", "9"), listOf("4", "5", "6"), listOf("1", "2", "3"))) {+ Row(horizontalArrangement = Arrangement.spacedBy(7.dp)) {+ for (k in row) NumericKey(k, if (row.first() == "AC") TopKey else DigitKey, 71) { key(k) }+ }+ }+ Row(horizontalArrangement = Arrangement.spacedBy(7.dp)) {+ NumericKey("0", DigitKey, 150) { key("0") }+ NumericKey(".", DigitKey, 71) { key(".") }+ }+ }+ }+ }+ }+}++@Composable+private fun NumberField(text: String, chosen: Boolean, onClick: () -> Unit) {+ Box(+ Modifier.size(80.dp, 41.dp).clip(RoundedCornerShape(10.dp)).background(if (chosen) Pc.Accent else FieldIdle).tap(onClick),+ contentAlignment = Alignment.Center,+ ) {+ Text(text, color = Color.White, fontSize = 15.sp, maxLines = 1)+ }+}++@Composable+private fun NumericKey(label: String, fill: Color, width: Int, onClick: () -> Unit) {+ Box(Modifier.size(width.dp, 48.dp).clip(RoundedCornerShape(9.dp)).background(fill).tap(onClick), contentAlignment = Alignment.Center) {+ if (label == "⌫") {+ Icon(PcIcons.Backspace, contentDescription = "Back space", tint = KeyInk, modifier = Modifier.size(22.dp))+ } else {+ Text(label, color = KeyInk, fontSize = if (label.length > 1) 15.sp else 22.sp)+ }+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/TransformUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/TransformUi.ktnew file mode 100644index 0000000..cc73241--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/TransformUi.kt@@ -0,0 +1,582 @@+package io.github.artcraftandroid.procraft.ui++import android.graphics.BlurMaskFilter+import androidx.compose.animation.core.Animatable+import androidx.compose.animation.core.tween+import androidx.compose.foundation.Canvas+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.interaction.MutableInteractionSource+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ColumnScope+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.RowScope+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.layout.wrapContentWidth+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.composed+import androidx.compose.ui.draw.drawBehind+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.RoundRect+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.geometry.lerp+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Paint+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.PathEffect+import androidx.compose.ui.graphics.StrokeCap+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.graphics.drawscope.drawIntoCanvas+import androidx.compose.ui.graphics.drawscope.rotateRad+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.layout+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.TextUnit+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.em+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import io.github.artcraftandroid.procraft.canvas.TransformPopup+import io.github.artcraftandroid.procraft.canvas.boxOnScreen+import io.github.artcraftandroid.procraft.canvas.shownMeshPoints+import io.github.artcraftandroid.procraft.canvas.toScreen+import io.github.artcraftandroid.procraft.core.Interpolation+import io.github.artcraftandroid.procraft.core.TransformAction+import io.github.artcraftandroid.procraft.core.TransformBox+import io.github.artcraftandroid.procraft.core.TransformHandle+import io.github.artcraftandroid.procraft.core.TransformKind+import kotlin.math.atan2+import kotlin.math.roundToInt++private val NodeBlue = Color(0xFF0171EA)+private val RotateGreen = Color(0xFF00E607)+private val RotateLine = Color(0xFF00E400)+private val TurnOrange = Color(0xFFFEB800)+private val TurnLine = Color(0xFFFEBF00)+internal val Dash = Color(0xE6000000)+internal val DashGap = Color(0xE6FFFFFF)+private val NodeShadow = Color(0x1F000000)+private val MeshLine = Color(0xFF8B8B8B)++/** Where a capital's middle sits below the top of its line, as a fraction of the font size. */+private const val CAP_MIDDLE = 0.6056f++/** A held node is drawn this much larger. */+private const val HELD_SCALE = 1.5f++/** How long a let-go rotate or box-turning node takes to spring back (ms). */+private const val HANDLE_RETURN_MS = 500++private val ToolbarWidth = 728.dp+private val ToolbarHeight = 126.dp+private val ToolbarBottom = 25.dp+private val ToolbarCorner = 33.dp+// translucent: #282828 to #252525 over white, #212121 to #1e1e1e over the surround+private val ToolbarTop = Color(0xF7212121)+private val ToolbarFill = Color(0xF71E1E1E)+private val SegmentTrack = Color(0xFF535353)+private val SegmentEdge = Color(0xFF7E7E7E)+private val SegmentText = Color(0xFFC1C1C1)+private val ButtonText = Color(0xFFA3A3A3)+private val ButtonDimmed = Color(0xFF575757)+private val SegmentGap = 11.33.dp+/** The transform toolbar's buttons: with room (landscape), and where the screen is narrow. */+private val TransformButtonRoomy = 89.dp+internal val ButtonWidth = 83.dp+private val ButtonHeight = 60.dp+/** The space between a roomy toolbar's buttons. */+private val ButtonGap = 19.dp++internal val MenuWidth = 260.dp+private val MenuArrow = 15.dp+private val MenuCorner = 26.dp+private val MenuFill = Color(0xEB2A2A2A)+internal val MenuGroup = Color(0xFF313131)+internal val MenuLine = Color(0xFF373737)+internal val MenuText: Color get() = if (Pc.light) Color(0xFF393939) else Color(0xFFC5C5C5)+internal val MenuGroupCorner = 13.dp++/** The transform box over the canvas: dashed edges, its nodes, the rotate node and the box-turning node. */+@Composable+fun TransformOverlay(vm: CanvasViewModel) {+ val box = vm.transformBox ?: return+ if (vm.transformKind == TransformKind.WARP && box.mesh.size == 32) {+ WarpOverlay(vm, box)+ return+ }+ val density = LocalDensity.current.density+ val shown = boxOnScreen(box, vm.viewMatrix, density) ?: return+ // a rotate or box-turning node let go away from its place springs back+ val letGo = vm.transformLetGo+ val back = remember(letGo) { Animatable(0f) }+ LaunchedEffect(letGo) {+ if (letGo != null) {+ back.animateTo(1f, tween(HANDLE_RETURN_MS))+ vm.transformLetGo = null+ }+ }+ val held = vm.transformHeld+ // the rotate and box-turning nodes follow the touch while held+ fun placed(handle: TransformHandle, rest: Offset): Offset = when {+ held?.first == handle -> held.second+ letGo?.first == handle -> lerp(letGo.second, rest, back.value)+ else -> rest+ }+ val rotate = placed(TransformHandle.Rotate, shown.rotate)+ val turn = placed(TransformHandle.TurnBox, shown.turn)+ fun scale(handle: TransformHandle) = if (held?.first == handle) HELD_SCALE else 1f+ Canvas(Modifier.fillMaxSize()) {+ val c = shown.corners+ val edge = Path().apply {+ moveTo(c[0].x, c[0].y)+ for (i in 1..3) lineTo(c[i].x, c[i].y)+ close()+ }+ val dash = 5.dp.toPx()+ val width = 1.dp.toPx()+ drawPath(edge, DashGap, style = Stroke(width, pathEffect = PathEffect.dashPathEffect(floatArrayOf(dash, dash), dash)))+ drawPath(edge, Dash, style = Stroke(width, pathEffect = PathEffect.dashPathEffect(floatArrayOf(dash, dash), 0f)))+ drawLine(RotateLine, shown.edges[0], rotate, width)+ drawLine(TurnLine, shown.edges[2], turn, width)+ c.forEachIndexed { i, p -> node(p, NodeBlue, scale(TransformHandle.Corner(i.toUByte()))) }+ shown.edges.forEachIndexed { i, p -> node(p, NodeBlue, scale(TransformHandle.Edge(i.toUByte()))) }+ node(rotate, RotateGreen, scale(TransformHandle.Rotate))+ // the box-turning node is a square, turned with the box+ val k = scale(TransformHandle.TurnBox)+ rotateRad(atan2(shown.up.x, -shown.up.y), turn) {+ shadow(turn, 5.5.dp.toPx() * k)+ val outer = 11.dp.toPx() * k+ drawRoundRect(Color.White, turn - Offset(outer / 2, outer / 2), Size(outer, outer), CornerRadius(2.5.dp.toPx() * k))+ val inner = 8.dp.toPx() * k+ drawRoundRect(TurnOrange, turn - Offset(inner / 2, inner / 2), Size(inner, inner), CornerRadius(1.dp.toPx() * k))+ }+ }+}++/** A warp over the canvas: its lines at the thirds, its shown control points, and with the advanced mesh the lines joining them. */+@Composable+private fun WarpOverlay(vm: CanvasViewModel, box: TransformBox) {+ val m = vm.viewMatrix+ val held = vm.transformHeld?.first+ val advanced = vm.advancedMesh+ Canvas(Modifier.fillMaxSize()) {+ val mesh = List(16) { toScreen(box.mesh[2 * it], box.mesh[2 * it + 1], m) }+ if (advanced) {+ // the control points joined along each row, and down the two edges, dotted, under the+ // lines (which hide them where they agree)+ val dots = PathEffect.dashPathEffect(floatArrayOf(1.dp.toPx(), 2.dp.toPx()), 0f)+ for (k in 0 until 4) {+ for (j in 0 until 3) {+ drawLine(Dash, mesh[k * 4 + j], mesh[k * 4 + j + 1], 1.dp.toPx(), pathEffect = dots)+ if (k == 0 || k == 3) drawLine(Dash, mesh[j * 4 + k], mesh[(j + 1) * 4 + k], 1.dp.toPx(), pathEffect = dots)+ }+ }+ }+ val grid = box.grid+ val perLine = grid.size / 2 / 8+ if (perLine >= 2) {+ for (line in 0 until 8) {+ val path = Path()+ for (k in 0 until perLine) {+ val i = (line * perLine + k) * 2+ val p = toScreen(grid[i], grid[i + 1], m)+ if (k == 0) path.moveTo(p.x, p.y) else path.lineTo(p.x, p.y)+ }+ drawPath(path, MeshLine, style = Stroke(1.dp.toPx()))+ }+ }+ for (i in shownMeshPoints(advanced)) {+ val holding = held == TransformHandle.Mesh(i.toUByte()) || (held is TransformHandle.Corner && listOf(0, 3, 15, 12)[held.index.toInt() % 4] == i)+ node(mesh[i], NodeBlue, if (holding) HELD_SCALE else 1f)+ }+ }+}++/** A node: a coloured dot on a white disc with a faint shadow, [scale] times its size (larger while held). */+internal fun DrawScope.node(at: Offset, color: Color, scale: Float) {+ shadow(at, 5.5.dp.toPx() * scale)+ drawCircle(Color.White, 5.5.dp.toPx() * scale, at)+ drawCircle(color, 3.5.dp.toPx() * scale, at)+}++private fun DrawScope.shadow(at: Offset, radius: Float) {+ drawIntoCanvas { canvas ->+ val paint = Paint().apply {+ color = NodeShadow+ asFrameworkPaint().maskFilter = BlurMaskFilter(1.dp.toPx(), BlurMaskFilter.Blur.NORMAL)+ }+ canvas.drawCircle(at, radius + 0.5.dp.toPx(), paint)+ }+}++/** A tap target without a ripple. */+internal fun Modifier.tap(onClick: () -> Unit): Modifier = composed {+ clickable(remember { MutableInteractionSource() }, indication = null, onClick = onClick)+}++/** The floating toolbar at the foot of the screen while transforming. */+@Composable+fun TransformToolbar(vm: CanvasViewModel, screenWidth: Dp, modifier: Modifier = Modifier) {+ FloatingToolbar(+ toolbarLayout(screenWidth, 7, TransformButtonRoomy, ButtonWidth),+ onBackground = { vm.transformPopup = TransformPopup.NONE },+ modifier = modifier,+ segments = {+ Segment(PcIcons.Freeform, "Freeform", vm.transformKind == TransformKind.FREEFORM, iconSize = 43.dp) { vm.chooseTransformKind(TransformKind.FREEFORM) }+ Segment(PcIcons.Uniform, "Uniform", vm.transformKind == TransformKind.UNIFORM, iconSize = 43.dp) { vm.chooseTransformKind(TransformKind.UNIFORM) }+ Segment(PcIcons.Distort, "Distort", vm.transformKind == TransformKind.DISTORT, iconSize = 43.dp) { vm.chooseTransformKind(TransformKind.DISTORT) }+ Segment(PcIcons.Warp, "Warp", vm.transformKind == TransformKind.WARP, iconSize = 43.dp) { vm.chooseTransformKind(TransformKind.WARP) }+ },+ ) { w ->+ val popup = vm.transformPopup+ // a long name smaller only where the buttons are narrow+ val long = if (w < TransformButtonRoomy) 11.sp else 12.5.sp+ if (vm.transformKind == TransformKind.WARP) {+ ToolbarButton(PcIcons.AdvancedMesh, "Advanced Mesh", active = vm.advancedMesh, width = w, iconSize = 28.8.dp, labelSize = long) { vm.toggleAdvancedMesh() }+ } else {+ ToolbarButton(PcIcons.Snapping, "Snapping", active = popup == TransformPopup.SNAPPING, width = w, iconSize = 44.dp) {+ vm.transformPopup = if (popup == TransformPopup.SNAPPING) TransformPopup.NONE else TransformPopup.SNAPPING+ }+ }+ ToolbarButton(PcIcons.FlipHorizontal, "Flip Horizontal", width = w, iconSize = 50.dp) { vm.transformAction(TransformAction.FLIP_HORIZONTAL) }+ ToolbarButton(PcIcons.FlipVertical, "Flip Vertical", width = w, iconSize = 50.dp) { vm.transformAction(TransformAction.FLIP_VERTICAL) }+ ToolbarButton(PcIcons.Rotate45, "Rotate 45°", width = w, iconSize = 44.dp) { vm.transformAction(TransformAction.ROTATE45) }+ ToolbarButton(PcIcons.FitToCanvas, "Fit to Canvas", width = w, iconSize = 35.dp) { vm.transformAction(TransformAction.FIT_TO_CANVAS) }+ ToolbarButton(PcIcons.Interpolation, interpolationName(vm.interpolation, short = true), active = popup == TransformPopup.INTERPOLATION, width = w, iconSize = 44.dp) {+ vm.transformPopup = if (popup == TransformPopup.INTERPOLATION) TransformPopup.NONE else TransformPopup.INTERPOLATION+ }+ ToolbarButton(PcIcons.TransformReset, "Reset", width = w, iconSize = 44.dp) { vm.transformAction(TransformAction.RESET) }+ }+}++/** A floating toolbar's width and its buttons' width. */+internal data class ToolbarLayout(val width: Dp, val button: Dp)++/**+ * A floating toolbar of [count] buttons on a screen [screenWidth] wide: with room, [roomy]-wide+ * buttons 19 apart inside its padding (as measured in landscape); else across the screen (8 clear+ * of each side, at most 728) with [narrow]-wide buttons spread over it.+ */+internal fun toolbarLayout(screenWidth: Dp, count: Int, roomy: Dp, narrow: Dp): ToolbarLayout {+ val wide = roomy * count + ButtonGap * (count - 1) + 32.dp+ return if (wide <= screenWidth - 16.dp) ToolbarLayout(wide, roomy) else ToolbarLayout(minOf(ToolbarWidth, screenWidth - 16.dp), narrow)+}++/**+ * The floating toolbar at the foot of the screen (transform, selection): a row of [segments] in a+ * pill over a row of [buttons] (given their width) spread across it. A tap on its background calls+ * [onBackground].+ */+@Composable+internal fun FloatingToolbar(+ layout: ToolbarLayout,+ onBackground: () -> Unit,+ modifier: Modifier = Modifier,+ segments: @Composable RowScope.() -> Unit,+ buttons: @Composable RowScope.(Dp) -> Unit,+) {+ Column(+ modifier.offset(y = -ToolbarBottom).size(layout.width, ToolbarHeight)+ .clip(RoundedCornerShape(ToolbarCorner))+ .background(Brush.verticalGradient(0f to ToolbarTop, 0.12f to ToolbarFill))+ .tap(onBackground)+ .padding(16.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ Row(+ Modifier.height(34.dp).clip(CircleShape).background(SegmentTrack).border(0.5.dp, SegmentEdge, CircleShape).padding(2.dp),+ horizontalArrangement = Arrangement.spacedBy(SegmentGap),+ content = segments,+ )+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { buttons(layout.button) }+ }+}++/** Where button [index] of [count] is centred on a toolbar laid out as [layout], from the screen's left. */+internal fun toolbarButtonCentre(screenWidth: Dp, layout: ToolbarLayout, index: Int, count: Int): Dp {+ val left = (screenWidth - layout.width) / 2 + 16.dp+ val gap = (layout.width - 32.dp - layout.button * count) / (count - 1).coerceAtLeast(1)+ return left + (layout.button + gap) * index + layout.button / 2+}++/** The top of the toolbar's buttons, from the top of a screen [screenHeight] tall: where popovers point. */+internal fun toolbarButtonsTop(screenHeight: Dp): Dp = screenHeight - ToolbarBottom - ToolbarHeight + 16.dp + 34.dp++/** One of the four ways: its icon and name, filled blue when chosen. */+@Composable+internal fun Segment(icon: ImageVector, label: String, selected: Boolean, iconSize: Dp = 26.5.dp, onClick: () -> Unit) {+ val tint = if (selected) Color.White else SegmentText+ Row(+ Modifier.height(30.dp).clip(CircleShape).background(if (selected) Pc.Accent else Color.Transparent).tap(onClick)+ .padding(start = 14.dp, end = 20.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Box(Modifier.size(30.dp), contentAlignment = Alignment.Center) {+ Icon(icon, contentDescription = null, tint = tint, modifier = Modifier.requiredSize(iconSize))+ }+ Spacer(Modifier.width(2.dp))+ Text(label, color = tint, fontSize = 13.sp, letterSpacing = (-0.025).em, maxLines = 1, softWrap = false)+ }+}++/** A toolbar button: an icon over its name; blue while its popover is open. */+@Composable+internal fun ToolbarButton(+ icon: ImageVector,+ label: String,+ active: Boolean = false,+ enabled: Boolean = true,+ width: Dp = ButtonWidth,+ iconSize: Dp = 24.dp,+ labelSize: TextUnit = 12.5.sp,+ onClick: () -> Unit,+) {+ val tint = when {+ !enabled -> ButtonDimmed+ active -> Pc.Accent+ else -> ButtonText+ }+ Box(Modifier.size(width, ButtonHeight).then(if (enabled) Modifier.tap(onClick) else Modifier)) {+ // icons centred 30 below the top, labels' capitals 50 below it+ Icon(icon, contentDescription = null, tint = tint, modifier = Modifier.align(Alignment.TopCenter).offset(y = 30.dp - iconSize / 2).requiredSize(iconSize))+ Text(+ label,+ color = if (enabled) ButtonText else ButtonDimmed,+ fontSize = labelSize,+ letterSpacing = 0.em,+ maxLines = 1,+ softWrap = false,+ // a long name may run past the button, as the reference's do+ modifier = Modifier.align(Alignment.TopCenter).offset(y = 50.dp - labelSize.value.dp * CAP_MIDDLE).wrapContentWidth(unbounded = true),+ )+ }+}++private fun interpolationName(i: Interpolation, short: Boolean): String = when (i) {+ Interpolation.NEAREST -> if (short) "Nearest" else "Nearest Neighbor"+ Interpolation.BILINEAR -> "Bilinear"+ Interpolation.BICUBIC -> "Bicubic"+}++/**+ * The popover open over the transform toolbar, its arrow on its button. [screenWidth] and+ * [screenHeight] place it; the toolbar's buttons start 94 dp above its foot.+ */+@Composable+fun TransformPopover(vm: CanvasViewModel, screenWidth: Dp, screenHeight: Dp) {+ val popup = vm.transformPopup+ if (popup == TransformPopup.NONE) return+ val layout = toolbarLayout(screenWidth, 7, TransformButtonRoomy, ButtonWidth)+ val buttonCentre = toolbarButtonCentre(screenWidth, layout, if (popup == TransformPopup.SNAPPING) 0 else 5, 7)+ val left = (buttonCentre - MenuWidth / 2).coerceIn(0.dp, screenWidth - MenuWidth)+ MenuPopover(buttonCentre - left, left, bottom = toolbarButtonsTop(screenHeight)) {+ when (popup) {+ TransformPopup.INTERPOLATION -> InterpolationMenu(vm)+ TransformPopup.SNAPPING -> SnappingMenu(vm)+ TransformPopup.NONE -> Unit+ }+ }+}++/** A popover [left] from the screen's left whose arrow points down at its button, the tip at [bottom] from the top. */+@Composable+internal fun MenuPopover(arrowX: Dp, left: Dp, bottom: Dp, width: Dp = MenuWidth, content: @Composable ColumnScope.() -> Unit) {+ Box(Modifier.fillMaxSize()) {+ Column(+ Modifier+ .layoutAbove(left, bottom)+ .width(width)+ .drawBehind {+ val arrowH = MenuArrow.toPx()+ val tipX = arrowX.toPx()+ val bodyBottom = size.height - arrowH+ val tip = 2.dp.toPx()+ val outline = Path().apply {+ addRoundRect(RoundRect(0f, 0f, size.width, bodyBottom, CornerRadius(MenuCorner.toPx())))+ moveTo(tipX - arrowH - tip, bodyBottom - 0.5f)+ lineTo(tipX - tip, size.height - tip)+ quadraticTo(tipX, size.height, tipX + tip, size.height - tip)+ lineTo(tipX + arrowH + tip, bodyBottom - 0.5f)+ close()+ }+ drawIntoCanvas { canvas ->+ val shadow = Paint().apply {+ color = Pc.PopoverShadow+ asFrameworkPaint().maskFilter = BlurMaskFilter(Pc.PopoverShadowRadius.toPx(), BlurMaskFilter.Blur.NORMAL)+ }+ canvas.drawPath(outline, shadow)+ }+ drawPath(outline, MenuFill)+ }+ .tap {}+ .padding(start = 10.dp, end = 10.dp, top = 10.dp, bottom = 10.dp + MenuArrow),+ content = content,+ )+ }+}++/** Places a node [left] from its parent's left with its bottom edge [bottom] from the parent's top. */+private fun Modifier.layoutAbove(left: Dp, bottom: Dp): Modifier = layout { measurable, constraints ->+ val placeable = measurable.measure(constraints.copy(minWidth = 0, minHeight = 0))+ layout(placeable.width, placeable.height) {+ placeable.place(left.roundToPx(), bottom.roundToPx() - placeable.height)+ }+}++@Composable+internal fun MenuTitle(text: String) {+ Box(Modifier.fillMaxWidth().height(40.dp).padding(start = 12.dp), contentAlignment = Alignment.CenterStart) {+ Text(text, color = MenuText, fontSize = 24.sp, fontWeight = FontWeight.Bold, letterSpacing = (-0.015).em, maxLines = 1)+ }+}++/** A row's text in the toolbar's popovers. */+@Composable+internal fun MenuLabel(text: String, color: Color = MenuText, modifier: Modifier = Modifier) {+ Text(text, color = color, fontSize = 16.sp, letterSpacing = 0.em, maxLines = 1, modifier = modifier)+}++@Composable+private fun InterpolationMenu(vm: CanvasViewModel) {+ MenuTitle("Interpolation")+ Spacer(Modifier.height(10.dp))+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(MenuGroupCorner)).background(MenuGroup)) {+ val all = listOf(Interpolation.NEAREST, Interpolation.BILINEAR, Interpolation.BICUBIC)+ all.forEachIndexed { i, kind ->+ if (i > 0) Box(Modifier.fillMaxWidth().height(1.dp).background(MenuLine))+ val selected = vm.interpolation == kind+ Row(+ Modifier.fillMaxWidth().height(40.dp).background(if (selected) Pc.Accent else Color.Transparent)+ .tap {+ vm.chooseInterpolation(kind)+ vm.transformPopup = TransformPopup.NONE+ }+ .padding(start = 11.dp, end = 14.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ MenuLabel(interpolationName(kind, short = false), if (selected) Color.White else MenuText, Modifier.weight(1f))+ if (selected) Icon(PcIcons.MenuTick, contentDescription = null, tint = Color.White, modifier = Modifier.size(29.dp))+ }+ }+ }+}++@Composable+private fun SnappingMenu(vm: CanvasViewModel) {+ val g = vm.guides+ MenuTitle("Settings")+ Spacer(Modifier.height(4.dp))+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(MenuGroupCorner)).background(MenuGroup)) {+ SwitchRow("Magnetics", g.magnetics) { vm.changeGuides(g.copy(magnetics = !g.magnetics)) }+ Box(Modifier.fillMaxWidth().height(1.dp).background(MenuLine))+ SwitchRow("Snapping", g.snapping) { vm.changeGuides(g.copy(snapping = !g.snapping)) }+ }+ Spacer(Modifier.height(10.dp))+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(MenuGroupCorner)).background(MenuGroup)) {+ // distance runs 1..50 points; at its default and below it reads as none+ val distance = (g.distance - SNAP_DISTANCE_MIN) / (SNAP_DISTANCE_MAX - SNAP_DISTANCE_MIN)+ SliderRow("Distance", distance, if (g.distance <= SNAP_DISTANCE_DEFAULT) "None" else "${g.distance.roundToInt()}") {+ vm.changeGuides(g.copy(distance = (SNAP_DISTANCE_MIN + it * (SNAP_DISTANCE_MAX - SNAP_DISTANCE_MIN)).roundToInt().toFloat()))+ }+ Box(Modifier.fillMaxWidth().height(1.dp).background(MenuLine))+ SliderRow("Velocity", g.velocity / SNAP_VELOCITY_MAX, if (g.velocity >= SNAP_VELOCITY_MAX) "Max" else "${g.velocity.roundToInt()}") {+ vm.changeGuides(g.copy(velocity = (it * SNAP_VELOCITY_MAX).roundToInt().toFloat()))+ }+ }+}++private const val SNAP_DISTANCE_MIN = 1f+private const val SNAP_DISTANCE_MAX = 50f+private const val SNAP_DISTANCE_DEFAULT = 3f+private const val SNAP_VELOCITY_MAX = 10f++@Composable+private fun SwitchRow(label: String, checked: Boolean, onToggle: () -> Unit) {+ Row(Modifier.fillMaxWidth().height(49.dp).tap(onToggle).padding(start = 12.dp, end = 6.dp), verticalAlignment = Alignment.CenterVertically) {+ MenuLabel(label, modifier = Modifier.weight(1f))+ Switch(checked, enabled = true)+ }+}++@Composable+internal fun SliderRow(label: String, value: Float, shown: String, onChange: (Float) -> Unit) {+ Column(Modifier.fillMaxWidth().height(59.dp)) {+ Row(Modifier.fillMaxWidth().padding(start = 14.dp, end = 13.dp, top = 9.dp)) {+ MenuLabel(label, modifier = Modifier.weight(1f))+ MenuLabel(shown)+ }+ MenuSlider(value, onChange, Modifier.padding(top = 9.dp))+ }+}++/** A thin slider: blue up to a small white knob, grey after it. */+@Composable+private fun MenuSlider(value: Float, onChange: (Float) -> Unit, modifier: Modifier = Modifier) {+ val change by rememberUpdatedState(onChange)+ Box(+ modifier.fillMaxWidth().height(14.dp)+ .pointerInput(Unit) {+ val start = SliderStart.toPx()+ val end = SliderEnd.toPx()+ fun at(x: Float) = ((x - start) / (size.width - start - end)).coerceIn(0f, 1f)+ awaitEachGesture {+ val down = awaitFirstDown()+ down.consume()+ change(at(down.position.x))+ while (true) {+ val c = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break+ if (!c.pressed) break+ change(at(c.position.x))+ c.consume()+ }+ }+ }+ .drawBehind {+ val start = SliderStart.toPx()+ val end = size.width - SliderEnd.toPx()+ val y = size.height / 2f+ val x = start + (end - start) * value.coerceIn(0f, 1f)+ val track = 2.dp.toPx()+ drawLine(SliderRest, Offset(x, y), Offset(end, y), track, cap = StrokeCap.Round)+ drawLine(Pc.Accent, Offset(start, y), Offset(x, y), track, cap = StrokeCap.Round)+ val knob = Size(15.dp.toPx(), 11.dp.toPx())+ drawRoundRect(Color(0x33000000), Offset(x - knob.width / 2, y - knob.height / 2 + 0.5.dp.toPx()), knob, CornerRadius(knob.height / 2))+ drawRoundRect(Color.White, Offset(x - knob.width / 2, y - knob.height / 2), knob, CornerRadius(knob.height / 2))+ },+ )+}++/** Where the slider's knob centre runs, from the row's left edge and from its right. */+private val SliderStart = 21.5.dp+private val SliderEnd = 15.dp+private val SliderRest = Color(0xFF5A5A5A)diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Type.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Type.ktnew file mode 100644index 0000000..1271ecb--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Type.kt@@ -0,0 +1,79 @@+package io.github.artcraftandroid.procraft.ui++import androidx.compose.material3.LocalTextStyle+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Typography+import androidx.compose.material3.darkColorScheme+import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.remember+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.text.PlatformTextStyle+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.font.Font+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.Density+import androidx.compose.ui.unit.em++/** Touches leave no ripple: the reference's controls show presses in their own ways, or not at all. */+private object NoIndication : androidx.compose.foundation.IndicationNodeFactory {+ override fun create(interactionSource: androidx.compose.foundation.interaction.InteractionSource): androidx.compose.ui.node.DelegatableNode =+ object : androidx.compose.ui.Modifier.Node() {}++ override fun hashCode(): Int = -1++ override fun equals(other: Any?): Boolean = other === this+}++/** Letter spacing that brings the bundled face to the reference's text widths (measured over 18–24 pt labels). */+private const val TRACKING = -0.045f++/**+ * The app's theme: Inter (bundled in `assets/fonts`, OFL) for all text, with natural line heights+ * and no font padding, so text sits where the reference's labels do. Interface text keeps its size+ * whatever the system font scale, as the reference's does: sp equal dp inside the theme.+ */+@Composable+fun ProCraftTheme(content: @Composable () -> Unit) {+ val assets = LocalContext.current.assets+ val text = remember(assets) {+ val family = FontFamily(+ Font("fonts/Inter-Regular.ttf", assets, FontWeight.Normal),+ Font("fonts/Inter-Medium.ttf", assets, FontWeight.Medium),+ Font("fonts/Inter-SemiBold.ttf", assets, FontWeight.SemiBold),+ Font("fonts/Inter-Bold.ttf", assets, FontWeight.Bold),+ )+ TextStyle(fontFamily = family, letterSpacing = TRACKING.em, platformStyle = PlatformTextStyle(includeFontPadding = false))+ }+ val typography = remember(text) {+ val t = Typography()+ Typography(+ displayLarge = t.displayLarge.merge(text),+ displayMedium = t.displayMedium.merge(text),+ displaySmall = t.displaySmall.merge(text),+ headlineLarge = t.headlineLarge.merge(text),+ headlineMedium = t.headlineMedium.merge(text),+ headlineSmall = t.headlineSmall.merge(text),+ titleLarge = t.titleLarge.merge(text),+ titleMedium = t.titleMedium.merge(text),+ titleSmall = t.titleSmall.merge(text),+ bodyLarge = t.bodyLarge.merge(text),+ bodyMedium = t.bodyMedium.merge(text),+ bodySmall = t.bodySmall.merge(text),+ labelLarge = t.labelLarge.merge(text),+ labelMedium = t.labelMedium.merge(text),+ labelSmall = t.labelSmall.merge(text),+ )+ }+ MaterialTheme(colorScheme = darkColorScheme(primary = Pc.Accent), typography = typography) {+ val density = LocalDensity.current+ CompositionLocalProvider(+ LocalDensity provides Density(density.density, 1f),+ LocalTextStyle provides text,+ androidx.compose.foundation.LocalIndication provides NoIndication,+ content = content,+ )+ }+}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ZoomUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ZoomUi.ktnew file mode 100644index 0000000..bc0e968--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ZoomUi.kt@@ -0,0 +1,109 @@+package io.github.artcraftandroid.procraft.ui++import androidx.compose.animation.core.Animatable+import androidx.compose.foundation.Canvas+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.runtime.snapshotFlow+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.geometry.lerp+import androidx.compose.ui.graphics.TransformOrigin+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.IntSize+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import kotlin.math.roundToInt+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch++/**+ * The gallery zooming into an artwork as it opens, and out of it as it closes. Opening, it is drawn+ * over the canvas getting ready ([overlay]): the artwork's cell grows to where its canvas will+ * be, and the gallery fades over the last part, showing the canvas and its bars. A canvas not yet+ * drawn by then (a big artwork) stays covered by the grown artwork until it is, then that fades.+ * Closing, it is the gallery itself, starting with the cell where the canvas was and settling+ * back, as a picture of the canvas fades away over it.+ */+@Composable+fun ZoomingGallery(vm: CanvasViewModel, overlay: Boolean) {+ val z = vm.galleryZoom?.takeIf { it.opening == overlay }+ if (z == null) {+ if (!overlay) GalleryScreen(vm)+ return+ }+ val progress = remember(z) { Animatable(0f) }+ var drawn by remember(z) { mutableStateOf(!z.opening) }+ // whether the canvas was drawn when the fade was due; if not, the cover holds and fades later+ var fadesWithZoom by remember(z) { mutableStateOf(true) }+ val cover = remember(z) { Animatable(1f) }+ LaunchedEffect(z) {+ if (z.opening) {+ launch {+ vm.awaitCanvasDrawn()+ drawn = true+ }+ launch {+ snapshotFlow { progress.value >= 1f - OPEN_FADE }.first { it }+ fadesWithZoom = drawn+ }+ }+ progress.animateTo(1f, if (z.opening) Motion.galleryOpen() else Motion.galleryClose())+ if (!fadesWithZoom) {+ snapshotFlow { drawn }.first { it }+ cover.animateTo(0f, Motion.coverFade())+ }+ vm.galleryZoom = null+ }+ val e = progress.value+ val at = if (z.opening) lerp(z.cell, z.canvas, e) else lerp(z.canvas, z.cell, e)+ Box(Modifier.fillMaxSize()) {+ Box(+ Modifier.fillMaxSize()+ .zoomed(z.cell, at)+ .graphicsLayer {+ alpha = when {+ !z.opening -> 1f+ fadesWithZoom -> ((1f - e) / OPEN_FADE).coerceIn(0f, 1f)+ else -> cover.value+ }+ }+ // nothing in it is touched while it moves+ .then(if (overlay) Modifier.pointerInput(Unit) { awaitEachGesture { while (true) awaitPointerEvent().changes.forEach { it.consume() } } } else Modifier),+ ) { GalleryScreen(vm) }+ // closing, the canvas fades away over its cell+ val picture = z.picture+ if (!z.opening && picture != null) {+ Canvas(Modifier.fillMaxSize()) {+ drawImage(+ picture,+ dstOffset = IntOffset(at.left.roundToInt(), at.top.roundToInt()),+ dstSize = IntSize(at.width.roundToInt().coerceAtLeast(1), at.height.roundToInt().coerceAtLeast(1)),+ alpha = (1f - e / CLOSE_FADE).coerceIn(0f, 1f),+ )+ }+ }+ }+}++/** Draws what it is on so that [from] (window pixels) lands on [to]: scaled about the top left, then moved. */+private fun Modifier.zoomed(from: Rect, to: Rect): Modifier = graphicsLayer {+ val k = if (from.height > 0f) to.height / from.height else 1f+ transformOrigin = TransformOrigin(0f, 0f)+ scaleX = k+ scaleY = k+ translationX = to.left - from.left * k+ translationY = to.top - from.top * k+}++/** How much of the opening zoom's end the gallery fades over, and how much of the closing zoom's start the canvas does. */+private const val OPEN_FADE = 0.35f+private const val CLOSE_FADE = 0.3fdiff --git a/apps/procraft-android/android/app/src/main/res/drawable/ic_launcher_foreground.xml b/apps/procraft-android/android/app/src/main/res/drawable/ic_launcher_foreground.xmlnew file mode 100644index 0000000..8f9eca1--- /dev/null+++ b/apps/procraft-android/android/app/src/main/res/drawable/ic_launcher_foreground.xml@@ -0,0 +1,14 @@+<?xml version="1.0" encoding="utf-8"?>+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="108dp"+ android:height="108dp"+ android:viewportWidth="108"+ android:viewportHeight="108">+ <!-- a tapered stroke -->+ <path+ android:fillColor="#FFFFFFFF"+ android:pathData="M34,72 C42,58 54,46 72,36 C74,35 75,37 73,38 C58,49 47,61 39,74 C37,77 32,76 34,72 Z" />+ <path+ android:fillColor="#FF4F9DFF"+ android:pathData="M31,79 a4,4 0 1,0 8,0 a4,4 0 1,0 -8,0" />+</vector>diff --git a/apps/procraft-android/android/app/src/main/res/mipmap-anydpi/ic_launcher.xml b/apps/procraft-android/android/app/src/main/res/mipmap-anydpi/ic_launcher.xmlnew file mode 100644index 0000000..ff89aa7--- /dev/null+++ b/apps/procraft-android/android/app/src/main/res/mipmap-anydpi/ic_launcher.xml@@ -0,0 +1,6 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- A placeholder icon of our own (a brush stroke on a dark field) until ProCraft has its icon. -->+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">+ <background android:drawable="@color/ic_launcher_background" />+ <foreground android:drawable="@drawable/ic_launcher_foreground" />+</adaptive-icon>diff --git a/apps/procraft-android/android/app/src/main/res/values/strings.xml b/apps/procraft-android/android/app/src/main/res/values/strings.xmlnew file mode 100644index 0000000..6d915a4--- /dev/null+++ b/apps/procraft-android/android/app/src/main/res/values/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="app_name">ProCraft</string>+</resources>diff --git a/apps/procraft-android/android/app/src/main/res/values/themes.xml b/apps/procraft-android/android/app/src/main/res/values/themes.xmlnew file mode 100644index 0000000..4dec5be--- /dev/null+++ b/apps/procraft-android/android/app/src/main/res/values/themes.xml@@ -0,0 +1,13 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <!-- dark, so nothing flashes before the first frame -->+ <color name="window_background">#FF000000</color>+ <color name="ic_launcher_background">#FF1C1C1E</color>++ <style name="Theme.ProCraft" parent="android:Theme.Material.NoActionBar">+ <item name="android:windowBackground">@color/window_background</item>+ <item name="android:statusBarColor">@android:color/transparent</item>+ <item name="android:navigationBarColor">@android:color/transparent</item>+ <item name="android:windowLayoutInDisplayCutoutMode">always</item>+ </style>+</resources>diff --git a/apps/procraft-android/android/app/src/main/res/xml/shared_files.xml b/apps/procraft-android/android/app/src/main/res/xml/shared_files.xmlnew file mode 100644index 0000000..282e644--- /dev/null+++ b/apps/procraft-android/android/app/src/main/res/xml/shared_files.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<paths>+ <cache-path name="exports" path="exports/" />+</paths>diff --git a/apps/procraft-android/android/app/src/test/java/io/github/artcraftandroid/procraft/canvas/MainColoursTest.kt b/apps/procraft-android/android/app/src/test/java/io/github/artcraftandroid/procraft/canvas/MainColoursTest.ktnew file mode 100644index 0000000..1ef8fcc--- /dev/null+++ b/apps/procraft-android/android/app/src/test/java/io/github/artcraftandroid/procraft/canvas/MainColoursTest.kt@@ -0,0 +1,37 @@+package io.github.artcraftandroid.procraft.canvas++import io.github.artcraftandroid.procraft.ui.GradientPreset+import io.github.artcraftandroid.procraft.ui.gradientColorAt+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++class MainColoursTest {+ @Test+ fun aPictureOfTwoColoursGivesThoseTwoLightestFirst() {+ val pixels = List(100) { 0x102030 } + List(50) { 0xF0E0D0 }+ assertEquals(listOf(0xF0E0D0, 0x102030), mainColours(pixels, 30))+ }++ @Test+ fun aGradientGivesAsManyColoursAsAsked() {+ val pixels = (0 until 256).map { (it shl 16) or (it shl 8) or it }+ val colours = mainColours(pixels, 30)+ assertEquals(30, colours.size)+ // lightest first+ assertTrue(colours.zipWithNext().all { (a, b) -> (a and 0xFF) >= (b and 0xFF) })+ }++ @Test+ fun nothingGivesNothing() {+ assertEquals(emptyList<Int>(), mainColours(emptyList(), 30))+ }++ @Test+ fun aGradientsColourIsMixedBetweenItsStops() {+ val g = GradientPreset("Test", listOf(1f to 0xFFFFFFFF, 0f to 0xFF000000))+ assertEquals(0xFF000000, gradientColorAt(g, 0f))+ assertEquals(0xFFFFFFFF, gradientColorAt(g, 1f))+ assertEquals(0xFF7F7F7F, gradientColorAt(g, 0.5f))+ }+}diff --git a/apps/procraft-android/android/app/src/test/java/io/github/artcraftandroid/procraft/gallery/ColourSwatchesTest.kt b/apps/procraft-android/android/app/src/test/java/io/github/artcraftandroid/procraft/gallery/ColourSwatchesTest.ktnew file mode 100644index 0000000..82e9ea2--- /dev/null+++ b/apps/procraft-android/android/app/src/test/java/io/github/artcraftandroid/procraft/gallery/ColourSwatchesTest.kt@@ -0,0 +1,72 @@+package io.github.artcraftandroid.procraft.gallery++import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test+import java.io.ByteArrayOutputStream+import java.io.DataOutputStream++class ColourSwatchesTest {+ private fun bytes(write: DataOutputStream.() -> Unit): ByteArray =+ ByteArrayOutputStream().also { DataOutputStream(it).write() }.toByteArray()++ private fun DataOutputStream.name(s: String) {+ writeShort(s.length + 1)+ writeChars(s)+ writeShort(0)+ }++ @Test+ fun colourSwatchFilesReadEveryColourSpace() {+ val aco = bytes {+ writeShort(1)+ writeShort(5)+ // red in RGB; green as hue 120°; full cyan ink (0 is full); mid grey (0 is white); white in Lab+ writeShort(0); writeShort(65535); writeShort(0); writeShort(0); writeShort(0)+ writeShort(1); writeShort(65535 / 3); writeShort(65535); writeShort(65535); writeShort(0)+ writeShort(2); writeShort(0); writeShort(65535); writeShort(65535); writeShort(65535)+ writeShort(8); writeShort(5000); writeShort(0); writeShort(0); writeShort(0)+ writeShort(7); writeShort(10000); writeShort(0); writeShort(0); writeShort(0)+ }+ val p = ColourSwatches.read(aco, "Shop Colours.aco")!!+ assertEquals("Shop Colours", p.name)+ assertEquals(PALETTE_SLOTS, p.colors.size)+ assertEquals(listOf(0xFF0000, 0x00FF00, 0x00FFFF, 0x808080, 0xFFFFFF), p.colors.take(5))+ assertNull(p.colors[5])+ }++ @Test+ fun swatchExchangeFilesTakeTheirGroupsName() {+ val ase = bytes {+ writeBytes("ASEF")+ writeShort(1); writeShort(0)+ writeInt(4)+ val group = bytes { name("Sunset") }+ writeShort(0xC001); writeInt(group.size); write(group)+ val orange = bytes { name("Orange"); writeBytes("RGB "); writeFloat(1f); writeFloat(0.5f); writeFloat(0f); writeShort(2) }+ writeShort(0x0001); writeInt(orange.size); write(orange)+ val ink = bytes { name("Ink"); writeBytes("CMYK"); writeFloat(0f); writeFloat(0f); writeFloat(0f); writeFloat(1f); writeShort(2) }+ writeShort(0x0001); writeInt(ink.size); write(ink)+ writeShort(0xC002); writeInt(0)+ }+ assertTrue(ColourSwatches.isExchange(ase))+ val p = ColourSwatches.read(ase, "whatever.ase")!!+ assertEquals("Sunset", p.name)+ assertEquals(listOf(0xFF8000, 0x000000, null), p.colors.take(3))+ }++ @Test+ fun labGoesBothWays() {+ for (rgb in listOf(0x3366CC, 0xFFCC00, 0x123456)) {+ val (l, a, b) = ColourSwatches.labOf(rgb).toList()+ assertEquals(rgb, ColourSwatches.labToRgb(l, a, b))+ }+ }++ @Test+ fun otherFilesAreNotPalettes() {+ assertNull(ColourSwatches.read(byteArrayOf(1, 2, 3), "notes.txt"))+ assertNull(ColourSwatches.read(byteArrayOf(0, 1), "broken.aco"))+ }+}diff --git a/apps/procraft-android/android/app/src/test/java/io/github/artcraftandroid/procraft/ui/SpringTest.kt b/apps/procraft-android/android/app/src/test/java/io/github/artcraftandroid/procraft/ui/SpringTest.ktnew file mode 100644index 0000000..d950c04--- /dev/null+++ b/apps/procraft-android/android/app/src/test/java/io/github/artcraftandroid/procraft/ui/SpringTest.kt@@ -0,0 +1,42 @@+package io.github.artcraftandroid.procraft.ui++import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test+import kotlin.math.abs++class SpringTest {+ private fun samples(s: Spring) = (0..100).map { s.transform(it / 100f) }++ @Test+ fun startsAtNothingAndEndsAtTheEnd() {+ for (s in listOf(Spring(0.3f, 0.75f, 0f), Spring(0.3f, 0.18f, 6f), Spring(0.5f, 8f, 5f), Spring(0.3f, 1f, 0f))) {+ assertEquals(0f, s.transform(0f), 1e-4f)+ assertEquals(1f, s.transform(1f), 0f)+ }+ }++ @Test+ fun aLightlyDampedSpringOvershootsAndSettles() {+ val bouncy = samples(Spring(0.3f, 0.18f, 6f))+ assertTrue("overshoots", bouncy.any { it > 1.2f })+ // within a thousandth of the end by the time it is given+ assertTrue(abs(bouncy[99] - 1f) < 2e-3f)+ }++ @Test+ fun aDampedSpringBarelyOvershootsAndIsNearlyThereEarly() {+ val rows = samples(Spring(0.3f, 0.75f, 0f))+ assertTrue(rows.max() < 1.05f)+ assertTrue(abs(rows[60] - 1f) < 0.05f)+ }++ @Test+ fun anOverdampedSpringNeverGoesPastTheEnd() {+ val stiff = samples(Spring(0.5f, 8f, 5f))+ assertTrue(stiff.all { it <= 1f + 1e-3f })+ // it moves at once with its starting speed+ assertTrue(stiff[5] > 0.05f)+ assertTrue(stiff.zipWithNext().all { (a, b) -> b >= a - 1e-4f })+ }+}diff --git a/apps/procraft-android/android/build.gradle.kts b/apps/procraft-android/android/build.gradle.ktsnew file mode 100644index 0000000..020183f--- /dev/null+++ b/apps/procraft-android/android/build.gradle.kts@@ -0,0 +1,4 @@+plugins {+ alias(libs.plugins.android.application) apply false+ alias(libs.plugins.kotlin.compose) apply false+}diff --git a/apps/procraft-android/android/gradle.properties b/apps/procraft-android/android/gradle.propertiesnew file mode 100644index 0000000..2e9a635--- /dev/null+++ b/apps/procraft-android/android/gradle.properties@@ -0,0 +1,14 @@+org.gradle.jvmargs=-Xmx3072m -Dfile.encoding=UTF-8+org.gradle.parallel=true+org.gradle.caching=true+org.gradle.configuration-cache=true+android.useAndroidX=true+android.nonTransitiveRClass=true+kotlin.code.style=official++# The Rust library's ABIs: arm64-v8a for devices, x86_64 for the emulator. Build one to save time,+# e.g. `./gradlew assembleRelease -Pprocraft.abis=arm64-v8a`.+procraft.abis=arm64-v8a,x86_64++procraft.version=0.0.1+procraft.versionCode=1diff --git a/apps/procraft-android/android/gradle/libs.versions.toml b/apps/procraft-android/android/gradle/libs.versions.tomlnew file mode 100644index 0000000..12cdb1d--- /dev/null+++ b/apps/procraft-android/android/gradle/libs.versions.toml@@ -0,0 +1,27 @@+[versions]+agp = "9.2.1"+kotlin = "2.3.21"+composeBom = "2026.09.00"+coreKtx = "1.17.0"+lifecycle = "2.9.4"+activityCompose = "1.11.0"+# predicted pen positions, drawn ahead of the stroke to hide input latency+motionprediction = "1.0.0"+# UniFFI's Kotlin bindings call the Rust library through JNA (Apache-2.0)+jna = "5.19.1"+junit = "4.13.2"++[libraries]+androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }+androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" }+androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }+androidx-input-motionprediction = { group = "androidx.input", name = "input-motionprediction", version.ref = "motionprediction" }+androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }+androidx-compose-ui = { group = "androidx.compose.ui", name = "ui" }+androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" }+jna = { group = "net.java.dev.jna", name = "jna", version.ref = "jna" }+junit = { group = "junit", name = "junit", version.ref = "junit" }++[plugins]+android-application = { id = "com.android.application", version.ref = "agp" }+kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }diff --git a/apps/procraft-android/android/gradle/wrapper/gradle-wrapper.jar b/apps/procraft-android/android/gradle/wrapper/gradle-wrapper.jarnew file mode 100644index 0000000..1b33c55Binary files /dev/null and b/apps/procraft-android/android/gradle/wrapper/gradle-wrapper.jar differdiff --git a/apps/procraft-android/android/gradle/wrapper/gradle-wrapper.properties b/apps/procraft-android/android/gradle/wrapper/gradle-wrapper.propertiesnew file mode 100644index 0000000..b21b69e--- /dev/null+++ b/apps/procraft-android/android/gradle/wrapper/gradle-wrapper.properties@@ -0,0 +1,8 @@+distributionBase=GRADLE_USER_HOME+distributionPath=wrapper/dists+distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.1-bin.zip+distributionSha256Sum=bafc141b619ad6350fd975fc903156dd5c151998cc8b058e8c1044ab5f7b031f+networkTimeout=10000+validateDistributionUrl=true+zipStoreBase=GRADLE_USER_HOME+zipStorePath=wrapper/distsdiff --git a/apps/procraft-android/android/gradlew b/apps/procraft-android/android/gradlewnew file mode 100644index 0000000..23d15a9--- /dev/null+++ b/apps/procraft-android/android/gradlew@@ -0,0 +1,251 @@+#!/bin/sh++#+# Copyright © 2015-2021 the original authors.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# https://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#+# SPDX-License-Identifier: Apache-2.0+#++##############################################################################+#+# Gradle start up script for POSIX generated by Gradle.+#+# Important for running:+#+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is+# noncompliant, but you have some other compliant shell such as ksh or+# bash, then to run this script, type that shell name before the whole+# command line, like:+#+# ksh Gradle+#+# Busybox and similar reduced shells will NOT work, because this script+# requires all of these POSIX shell features:+# * functions;+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;+# * compound commands having a testable exit status, especially «case»;+# * various built-in commands including «command», «set», and «ulimit».+#+# Important for patching:+#+# (2) This script targets any POSIX shell, so it avoids extensions provided+# by Bash, Ksh, etc; in particular arrays are avoided.+#+# The "traditional" practice of packing multiple parameters into a+# space-separated string is a well documented source of bugs and security+# problems, so this is (mostly) avoided, by progressively accumulating+# options in "$@", and eventually passing that to Java.+#+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;+# see the in-line comments for details.+#+# There are tweaks for specific operating systems such as AIX, CygWin,+# Darwin, MinGW, and NonStop.+#+# (3) This script is generated from the Groovy template+# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt+# within the Gradle project.+#+# You can find Gradle at https://github.com/gradle/gradle/.+#+##############################################################################++# Attempt to set APP_HOME++# Resolve links: $0 may be a link+app_path=$0++# Need this for daisy-chained symlinks.+while+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path+ [ -h "$app_path" ]+do+ ls=$( ls -ld "$app_path" )+ link=${ls#*' -> '}+ case $link in #(+ /*) app_path=$link ;; #(+ *) app_path=$APP_HOME$link ;;+ esac+done++# This is normally unused+# shellcheck disable=SC2034+APP_BASE_NAME=${0##*/}+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit++# Use the maximum available, or set MAX_FD != -1 to use that value.+MAX_FD=maximum++warn () {+ echo "$*"+} >&2++die () {+ echo+ echo "$*"+ echo+ exit 1+} >&2++# OS specific support (must be 'true' or 'false').+cygwin=false+msys=false+darwin=false+nonstop=false+case "$( uname )" in #(+ CYGWIN* ) cygwin=true ;; #(+ Darwin* ) darwin=true ;; #(+ MSYS* | MINGW* ) msys=true ;; #(+ NONSTOP* ) nonstop=true ;;+esac++CLASSPATH="\\\"\\\""+++# Determine the Java command to use to start the JVM.+if [ -n "$JAVA_HOME" ] ; then+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then+ # IBM's JDK on AIX uses strange locations for the executables+ JAVACMD=$JAVA_HOME/jre/sh/java+ else+ JAVACMD=$JAVA_HOME/bin/java+ fi+ if [ ! -x "$JAVACMD" ] ; then+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME++Please set the JAVA_HOME variable in your environment to match the+location of your Java installation."+ fi+else+ JAVACMD=java+ if ! command -v java >/dev/null 2>&1+ then+ die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.++Please set the JAVA_HOME variable in your environment to match the+location of your Java installation."+ fi+fi++# Increase the maximum file descriptors if we can.+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then+ case $MAX_FD in #(+ max*)+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.+ # shellcheck disable=SC2039,SC3045+ MAX_FD=$( ulimit -H -n ) ||+ warn "Could not query maximum file descriptor limit"+ esac+ case $MAX_FD in #(+ '' | soft) :;; #(+ *)+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.+ # shellcheck disable=SC2039,SC3045+ ulimit -n "$MAX_FD" ||+ warn "Could not set maximum file descriptor limit to $MAX_FD"+ esac+fi++# Collect all arguments for the java command, stacking in reverse order:+# * args from the command line+# * the main class name+# * -classpath+# * -D...appname settings+# * --module-path (only if needed)+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.++# For Cygwin or MSYS, switch paths to Windows format before running java+if "$cygwin" || "$msys" ; then+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )++ JAVACMD=$( cygpath --unix "$JAVACMD" )++ # Now convert the arguments - kludge to limit ourselves to /bin/sh+ for arg do+ if+ case $arg in #(+ -*) false ;; # don't mess with options #(+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath+ [ -e "$t" ] ;; #(+ *) false ;;+ esac+ then+ arg=$( cygpath --path --ignore --mixed "$arg" )+ fi+ # Roll the args list around exactly as many times as the number of+ # args, so each arg winds up back in the position where it started, but+ # possibly modified.+ #+ # NB: a `for` loop captures its iteration list before it begins, so+ # changing the positional parameters here affects neither the number of+ # iterations, nor the values presented in `arg`.+ shift # remove old arg+ set -- "$@" "$arg" # push replacement arg+ done+fi+++# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'++# Collect all arguments for the java command:+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,+# and any embedded shellness will be escaped.+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be+# treated as '${Hostname}' itself on the command line.++set -- \+ "-Dorg.gradle.appname=$APP_BASE_NAME" \+ -classpath "$CLASSPATH" \+ -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \+ "$@"++# Stop when "xargs" is not available.+if ! command -v xargs >/dev/null 2>&1+then+ die "xargs is not available"+fi++# Use "xargs" to parse quoted args.+#+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.+#+# In Bash we could simply go:+#+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&+# set -- "${ARGS[@]}" "$@"+#+# but POSIX shell has neither arrays nor command substitution, so instead we+# post-process each arg (as a line of input to sed) to backslash-escape any+# character that might be a shell metacharacter, then use eval to reverse+# that process (while maintaining the separation between arguments), and wrap+# the whole thing up as a single "set" statement.+#+# This will of course break if any of these variables contains a newline or+# an unmatched quote.+#++eval "set -- $(+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |+ xargs -n1 |+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |+ tr '\n' ' '+ )" '"$@"'++exec "$JAVACMD" "$@"diff --git a/apps/procraft-android/android/gradlew.bat b/apps/procraft-android/android/gradlew.batnew file mode 100644index 0000000..db3a6ac--- /dev/null+++ b/apps/procraft-android/android/gradlew.bat@@ -0,0 +1,94 @@+@rem+@rem Copyright 2015 the original author or authors.+@rem+@rem Licensed under the Apache License, Version 2.0 (the "License");+@rem you may not use this file except in compliance with the License.+@rem You may obtain a copy of the License at+@rem+@rem https://www.apache.org/licenses/LICENSE-2.0+@rem+@rem Unless required by applicable law or agreed to in writing, software+@rem distributed under the License is distributed on an "AS IS" BASIS,+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+@rem See the License for the specific language governing permissions and+@rem limitations under the License.+@rem+@rem SPDX-License-Identifier: Apache-2.0+@rem++@if "%DEBUG%"=="" @echo off+@rem ##########################################################################+@rem+@rem Gradle startup script for Windows+@rem+@rem ##########################################################################++@rem Set local scope for the variables with windows NT shell+if "%OS%"=="Windows_NT" setlocal++set DIRNAME=%~dp0+if "%DIRNAME%"=="" set DIRNAME=.+@rem This is normally unused+set APP_BASE_NAME=%~n0+set APP_HOME=%DIRNAME%++@rem Resolve any "." and ".." in APP_HOME to make it shorter.+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi++@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"++@rem Find java.exe+if defined JAVA_HOME goto findJavaFromJavaHome++set JAVA_EXE=java.exe+%JAVA_EXE% -version >NUL 2>&1+if %ERRORLEVEL% equ 0 goto execute++echo. 1>&2+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2+echo. 1>&2+echo Please set the JAVA_HOME variable in your environment to match the 1>&2+echo location of your Java installation. 1>&2++goto fail++:findJavaFromJavaHome+set JAVA_HOME=%JAVA_HOME:"=%+set JAVA_EXE=%JAVA_HOME%/bin/java.exe++if exist "%JAVA_EXE%" goto execute++echo. 1>&2+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2+echo. 1>&2+echo Please set the JAVA_HOME variable in your environment to match the 1>&2+echo location of your Java installation. 1>&2++goto fail++:execute+@rem Setup the command line++set CLASSPATH=+++@rem Execute Gradle+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*++:end+@rem End local scope for the variables with windows NT shell+if %ERRORLEVEL% equ 0 goto mainEnd++:fail+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of+rem the _cmd.exe /c_ return code!+set EXIT_CODE=%ERRORLEVEL%+if %EXIT_CODE% equ 0 set EXIT_CODE=1+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%+exit /b %EXIT_CODE%++:mainEnd+if "%OS%"=="Windows_NT" endlocal++:omegadiff --git a/apps/procraft-android/android/settings.gradle.kts b/apps/procraft-android/android/settings.gradle.ktsnew file mode 100644index 0000000..d953541--- /dev/null+++ b/apps/procraft-android/android/settings.gradle.kts@@ -0,0 +1,25 @@+pluginManagement {+ repositories {+ google {+ content {+ includeGroupByRegex("com\\.android.*")+ includeGroupByRegex("com\\.google.*")+ includeGroupByRegex("androidx.*")+ }+ }+ mavenCentral()+ gradlePluginPortal()+ }+}++@Suppress("UnstableApiUsage")+dependencyResolutionManagement {+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)+ repositories {+ google()+ mavenCentral()+ }+}++rootProject.name = "ProCraft"+include(":app")diff --git a/apps/procraft-android/bindgen/Cargo.toml b/apps/procraft-android/bindgen/Cargo.tomlnew file mode 100644index 0000000..c8b19cb--- /dev/null+++ b/apps/procraft-android/bindgen/Cargo.toml@@ -0,0 +1,18 @@+[package]+name = "procraft-android-bindgen"+version.workspace = true+edition.workspace = true+rust-version.workspace = true+publish.workspace = true+description = "uniffi-bindgen for procraft-android: generates its Kotlin bindings from the built library (the Android build runs it)"++[[bin]]+name = "uniffi-bindgen"+path = "src/main.rs"++[lints]+workspace = true++[dependencies]+# The release procraft-android uses (same lock file): bindings only load against their own release.+uniffi = { version = "=0.32.2", features = ["cli"] }diff --git a/apps/procraft-android/bindgen/src/main.rs b/apps/procraft-android/bindgen/src/main.rsnew file mode 100644index 0000000..8b5f511--- /dev/null+++ b/apps/procraft-android/bindgen/src/main.rs@@ -0,0 +1,7 @@+//! `uniffi-bindgen` for `procraft-android`: generates its bindings from the built library, e.g.+//! `cargo run -p procraft-android-bindgen -- generate libprocraft_android.so --language kotlin --out-dir out`+//! (`android/app/build.gradle.kts` runs it).++fn main() {+ uniffi::uniffi_bindgen_main()+}diff --git a/apps/procraft-android/src/adjust.rs b/apps/procraft-android/src/adjust.rsnew file mode 100644index 0000000..d4c10f4--- /dev/null+++ b/apps/procraft-android/src/adjust.rs@@ -0,0 +1,700 @@+//! Adjustments: the current layer redrawn through a filter while its values are dragged, kept as+//! one undo step or put back; only what is selected changes.++use procraft_engine::geom::Vec2;+use procraft_engine::selection::feather_radius;+use procraft_engine::tone;+use procraft_gpu::{Filter, LiquifyMode, LiquifyStamp};++use procraft_engine::stroke::StrokeBuilder;+use procraft_gpu::{Canvas, StrokeStyle, StrokeTool};++use crate::{CanvasSession, PenSample, PointerKind, State, ToolKind};++/// The adjustments whose one amount (0..1) is dragged across the canvas.+#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]+pub enum SwipeAdjustment {+ GaussianBlur,+ Sharpen,+ Noise,+ PerspectiveBlur,+ ChromaticAberration,+ Halftone,+ Bloom,+}++/// The kinds of noise.+#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]+pub enum NoiseKind {+ Clouds,+ Billows,+ Ridges,+}++/// The kinds of halftone.+#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]+pub enum HalftoneKind {+ FullColor,+ ScreenPrint,+ Newspaper,+}++/// Chromatic aberration pulled from the middle, or moved one way everywhere.+#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]+pub enum ChromaticKind {+ Perspective,+ Displace,+}++/// Noise from its sliders (0..1): the amount reads three times as strong; the scale makes it+/// coarser, the octaves add finer layers (one to five), the turbulence keeps more of each.+fn noise(amount: f32, kind: NoiseKind, scale: f32, octaves: f32, turbulence: f32, multi: bool, added: bool) -> Filter {+ Filter::Noise {+ amount: amount * 3.0 * 0.6,+ frequency: 0.0000517 + 0.4564 * (scale - 1.0).powi(4),+ octaves: (octaves * 4.0) as u32 + 1,+ turbulence: turbulence * 0.32,+ kind: kind as u32,+ multi,+ added,+ }+}++/// Bloom from its sliders (0..1): the size through the blur's own curve, the burn from a little+/// weaker to much stronger.+fn bloom(amount: f32, transition: f32, size: f32, burn: f32) -> Filter {+ Filter::Bloom {+ sigma: feather_radius(size.powf(1.8)),+ amount,+ threshold: BLOOM_THRESHOLD,+ transition,+ burn: -0.3 + 1.3 * burn,+ }+}++/// Chromatic aberration from its sliders (0..1): perspective pulls from `centre` by the amount,+/// `a` smearing the fringes and `b` keeping them off the middle; displace moves them by `offset`+/// (canvas pixels), `a` smearing them and `b` making them transparent.+fn chromatic(centre: [f32; 2], kind: ChromaticKind, amount: f32, offset: [f32; 2], a: f32, b: f32) -> Filter {+ let displace = kind == ChromaticKind::Displace;+ Filter::Chromatic {+ centre,+ amount: amount * 0.05,+ displace,+ offset,+ blur: a,+ falloff: if displace { 0.0 } else { b },+ transparency: if displace { b } else { 0.0 },+ }+}++/// A halftone's cells (canvas pixels) for the amount.+fn halftone_pitch(amount: f32) -> f32 {+ amount * 96.0 + 2.0+}++/// A slider's value kept to 0..1 (0 if not a number).+fn unit(v: f32) -> f32 {+ if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }+}++/// The ways a glitch breaks the layer up.+#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]+pub enum GlitchKind {+ /// Blocks copied from a few blocks away.+ Artifact,+ /// Rows bent sideways.+ Wave,+ /// Bands ghosted sideways.+ Signal,+ /// The channels moved apart, block by block.+ Diverge,+}++/// How a liquify brush moves what is under it.+#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]+pub enum LiquifyKind {+ Push,+ TwirlRight,+ TwirlLeft,+ Pinch,+ Expand,+ Crystals,+ Edge,+ Reconstruct,+}++impl From<LiquifyKind> for LiquifyMode {+ fn from(k: LiquifyKind) -> LiquifyMode {+ match k {+ LiquifyKind::Push => LiquifyMode::Push,+ LiquifyKind::TwirlRight => LiquifyMode::TwirlRight,+ LiquifyKind::TwirlLeft => LiquifyMode::TwirlLeft,+ LiquifyKind::Pinch => LiquifyMode::Pinch,+ LiquifyKind::Expand => LiquifyMode::Expand,+ LiquifyKind::Crystals => LiquifyMode::Crystals,+ LiquifyKind::Edge => LiquifyMode::Edge,+ LiquifyKind::Reconstruct => LiquifyMode::Reconstruct,+ }+ }+}++/// The liquify brush: its way, and its size, pressure and distortion sliders (0..1).+#[derive(Clone, Copy, Debug, PartialEq, uniffi::Record)]+pub struct LiquifyBrush {+ pub kind: LiquifyKind,+ pub size: f32,+ pub pressure: f32,+ pub distortion: f32,+}++/// Noise's default fineness (per canvas pixel), octaves and turbulence.+/// Noise's turbulence slider as it starts.+const NOISE_TURBULENCE: f32 = 0.7;+/// Bloom's default size (as a blur amount) and where its light starts.+/// Bloom's size and burn sliders as they start.+const BLOOM_SIZE: f32 = 0.3;+const BLOOM_BURN: f32 = 0.35;+const BLOOM_THRESHOLD: f32 = 0.5;+/// How long (milliseconds) the liquify brush carries on at its lifting speed, at full momentum+/// (it covers that distance while slowing to a stop), and the most stamps it adds doing so.+const LIQUIFY_COAST_MS: f32 = 300.0;+const LIQUIFY_COAST_STAMPS: usize = 400;+/// The (set, brush) cloning paints with: the soft airbrush.+const CLONE_BRUSH: (usize, usize) = (3, 0);+/// How far (points) a motion blur's drag goes for its whole amount, and the blur that is (canvas+/// pixels).+const MOTION_DRAG_PT: f32 = 500.0;+const MOTION_LENGTH_PX: f32 = 256.0;++impl State {+ /// A stroke that paints the adjustment on, with the paint brush (white into the mask). Cloning,+ /// the first stroke fixes how far from the source it copies.+ pub(crate) fn pencil_stroke(&mut self, pointer: PointerKind, samples: &[PenSample]) {+ let current = self.doc.current();+ let sliders = self.shown_sliders();+ let brush = if self.cloning {+ self.shipped.get(CLONE_BRUSH.0).and_then(|s| s.brushes.get(CLONE_BRUSH.1)).unwrap_or(&self.fallback).clone()+ } else {+ self.brush(ToolKind::Paint).clone()+ };+ self.strokes = self.strokes.wrapping_add(1);+ let seed = self.strokes.wrapping_mul(0x9e37_79b9);+ let mut builder = StrokeBuilder::with_seed(brush.clone(), brush.diameter(sliders.size), pointer.into(), seed)+ .with_input(self.input.clone())+ .on_view_turned(self.view.map_or(0.0, |v| v.rotation()))+ .seen_at(self.view.map_or(1.0, |v| v.zoom()) / self.display_scale);+ let canvas_samples = self.to_canvas(samples);+ if let (Some(source), None, Some(first)) = (self.clone_source, self.clone_offset, canvas_samples.first()) {+ let offset = source - first.pos;+ self.clone_offset = Some(offset);+ self.last_filter = Some(Filter::Clone { offset: [offset.x, offset.y] });+ }+ let stamps = builder.add(&canvas_samples);+ let mut style =+ StrokeStyle::for_brush(&brush, StrokeTool::Paint, [1.0, 1.0, 1.0], brush.opacity(sliders.opacity), false);+ let Some(canvas) = self.canvas.as_mut() else { return };+ if let Some(gpu) = self.gpu.as_ref() {+ canvas.use_sources(gpu, &mut style, &brush);+ }+ canvas.begin_pencil_stroke(current, style);+ canvas.add_stamps(&stamps);+ self.stroke = Some(builder);+ self.redraw_painted_on();+ }++ /// Keeps the stroke just painted on as its own undo step, and goes on with the adjustment.+ pub(crate) fn bake_painted_on(&mut self) {+ if !(self.adjusting && self.pencil) {+ return;+ }+ let current = self.doc.current();+ if let Some(canvas) = self.canvas.as_mut() {+ canvas.end_transform(true);+ canvas.begin_transform(current);+ canvas.begin_pencil();+ if let Some(filter) = self.last_filter {+ canvas.set_filter(filter);+ }+ }+ }++ /// Drops what was painted on since the last stroke kept, runs `between` (an undo or redo),+ /// and goes on with the adjustment.+ pub(crate) fn restart_painted_on(&mut self, between: Option<fn(&mut Canvas)>) {+ if !(self.adjusting && self.pencil) {+ return;+ }+ let current = self.doc.current();+ if let Some(canvas) = self.canvas.as_mut() {+ canvas.end_transform(false);+ if let Some(f) = between {+ f(canvas);+ }+ canvas.begin_transform(current);+ canvas.begin_pencil();+ if let Some(filter) = self.last_filter {+ canvas.set_filter(filter);+ }+ }+ }++ /// Draws the adjustment again after more of it was painted on.+ pub(crate) fn redraw_painted_on(&mut self) {+ if self.pencil+ && let (Some(filter), Some(canvas)) = (self.last_filter, self.canvas.as_mut())+ {+ canvas.set_filter(filter);+ }+ }++ /// Ends an open adjustment: `commit` keeps it as one undo step, otherwise the layer goes back.+ pub(crate) fn end_adjustment(&mut self, commit: bool) {+ self.pencil = false;+ self.cloning = false;+ self.clone_source = None;+ self.clone_offset = None;+ if std::mem::take(&mut self.adjusting)+ && let Some(canvas) = self.canvas.as_mut()+ {+ if commit {+ canvas.name_next_step(match self.last_filter {+ Some(Filter::Hsb { .. }) => "adjust HSB",+ Some(Filter::Curves) => "adjust Curves",+ Some(Filter::ColorBalance { .. }) => "change Color Balance",+ Some(Filter::GradientMap { .. }) => "change Gradient Map",+ _ => "adjustment",+ });+ }+ canvas.end_transform(commit);+ if self.simplified_undos {+ canvas.collapse_steps();+ }+ }+ }++ fn adjust(&mut self, filter: Filter) {+ if self.adjusting+ && let Some(canvas) = self.canvas.as_mut()+ {+ self.last_filter = Some(filter);+ canvas.set_filter(filter);+ }+ }+}++#[uniffi::export]+impl CanvasSession {+ /// Starts adjusting the current layer; false when it cannot be (locked or hidden). An+ /// adjustment already open is kept first.+ pub fn adjust_begin(&self) -> bool {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.finish_stroke();+ st.settle();+ let current = st.doc.current();+ if st.doc.layer(current).is_none_or(|l| l.locked || !l.visible || l.text.is_some()) {+ return false;+ }+ let Some(canvas) = st.canvas.as_mut() else { return false };+ canvas.mark_steps();+ canvas.begin_transform(current);+ st.adjusting = true;+ st.last_filter = None;+ self.shared.frame(st);+ true+ }++ /// Hue, saturation and brightness, each 0..1 with 0.5 leaving the layer as it is: the hue turns+ /// the colour up to half a turn either way, saturation scales it from grey to twice as strong,+ /// brightness lightens or darkens it all the way.+ pub fn adjust_hsb(&self, hue: f32, saturation: f32, brightness: f32) {+ let [h, s, b] =+ [hue, saturation, brightness].map(|v| if v.is_finite() { (v.clamp(0.0, 1.0) - 0.5) * 2.0 } else { 0.0 });+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.adjust(Filter::Hsb { hue: h * std::f32::consts::PI, saturation: 1.0 + s, brightness: b });+ self.shared.frame(st);+ }++ /// One of the dragged adjustments at `amount` (0..1), with its other values at their defaults.+ pub fn adjust_swipe(&self, kind: SwipeAdjustment, amount: f32) {+ let a = if amount.is_finite() { amount.clamp(0.0, 1.0) } else { 0.0 };+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let centre = [st.doc.width() as f32 / 2.0, st.doc.height() as f32 / 2.0];+ let filter = match kind {+ SwipeAdjustment::GaussianBlur => Filter::Blur { sigma: feather_radius(a) },+ SwipeAdjustment::Sharpen => Filter::Sharpen { amount: a },+ // the amount reads three times as strong+ SwipeAdjustment::Noise => noise(a, NoiseKind::Clouds, 0.0, 0.0, NOISE_TURBULENCE, false, true),+ SwipeAdjustment::PerspectiveBlur => Filter::Zoom { centre, amount: a * 0.25 },+ SwipeAdjustment::ChromaticAberration => {+ chromatic(centre, ChromaticKind::Perspective, a, [0.0; 2], 0.0, 0.0)+ }+ SwipeAdjustment::Halftone => Filter::Halftone { pitch: halftone_pitch(a), kind: 0 },+ SwipeAdjustment::Bloom => bloom(a, 1.0, BLOOM_SIZE, BLOOM_BURN),+ };+ st.adjust(filter);+ self.shared.frame(st);+ }++ /// A motion blur along the drag from its start to window point offset (`dx`, `dy`): longer the+ /// further the drag goes. Returns the amount (0..1).+ pub fn adjust_motion(&self, dx: f32, dy: f32) -> f32 {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let points = Vec2::new(dx, dy) * (1.0 / st.display_scale.max(1e-6));+ let amount = (points.length() / MOTION_DRAG_PT).clamp(0.0, 1.0);+ // the drag's direction on the canvas, through the view's turn+ let turn = st.view.map_or(0.0, |v| v.to_screen().rotation());+ let angle = dy.atan2(dx) - turn;+ let length = amount * MOTION_LENGTH_PX;+ if length.is_finite() {+ st.adjust(Filter::Motion { along: [length * angle.cos(), length * angle.sin()] });+ self.shared.frame(st);+ }+ amount+ }++ /// Curves: the points (x, y pairs in 0..1) of the curve for all three channels and of the red,+ /// green and blue curves; each runs through its points as a smooth spline.+ pub fn adjust_curves(&self, all: Vec<f32>, red: Vec<f32>, green: Vec<f32>, blue: Vec<f32>) {+ let points = |v: &[f32]| v.as_chunks::<2>().0.iter().map(|&[x, y]| (x, y)).collect::<Vec<_>>();+ let [a, r, g, b] = [&all, &red, &green, &blue].map(|v| tone::curve_table(&points(v)));+ let entries: Vec<u8> = r.iter().zip(&g).zip(&b).zip(&a).flat_map(|(((&r, &g), &b), &a)| [r, g, b, a]).collect();+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ if let (Some(canvas), Some(gpu)) = (st.canvas.as_mut(), st.gpu.as_ref()) {+ canvas.set_table(gpu, &entries);+ }+ st.adjust(Filter::Curves);+ self.shared.frame(st);+ }++ /// The curve through `points` (x, y pairs in 0..1) as 256 heights (0..1), for drawing.+ pub fn curve_shape(&self, points: Vec<f32>) -> Vec<f32> {+ let pts: Vec<(f32, f32)> = points.as_chunks::<2>().0.iter().map(|&[x, y]| (x, y)).collect();+ tone::curve_table(&pts).iter().map(|&v| f32::from(v) / 255.0).collect()+ }++ /// Noise of `kind`, `amount` (0..1) of it, with its sliders (0..1); each channel its own when+ /// `multi`; added to the colour, or else mixed in.+ #[allow(clippy::too_many_arguments)]+ pub fn adjust_noise(+ &self,+ kind: NoiseKind,+ amount: f32,+ scale: f32,+ octaves: f32,+ turbulence: f32,+ multi: bool,+ added: bool,+ ) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.adjust(noise(unit(amount), kind, unit(scale), unit(octaves), unit(turbulence), multi, added));+ self.shared.frame(st);+ }++ /// Bloom, `amount` (0..1) of it, with its transition, size and burn sliders (0..1).+ pub fn adjust_bloom(&self, amount: f32, transition: f32, size: f32, burn: f32) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.adjust(bloom(unit(amount), unit(transition), unit(size), unit(burn)));+ self.shared.frame(st);+ }++ /// A halftone of `kind`, its cells growing with `amount` (0..1).+ pub fn adjust_halftone(&self, kind: HalftoneKind, amount: f32) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.adjust(Filter::Halftone { pitch: halftone_pitch(unit(amount)), kind: kind as u32 });+ self.shared.frame(st);+ }++ /// Chromatic aberration of `kind`: perspective by `amount` (0..1) from the middle; displace by+ /// the drag (`dx`, `dy`, window pixels). `a` and `b` are its two sliders (0..1): perspective's+ /// transition and fall off, displace's blur and transparency.+ pub fn adjust_chromatic(&self, kind: ChromaticKind, amount: f32, dx: f32, dy: f32, a: f32, b: f32) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let centre = [st.doc.width() as f32 / 2.0, st.doc.height() as f32 / 2.0];+ // the drag on the canvas, through the view's scale and turn+ let offset = st+ .view+ .and_then(|v| v.to_screen().inverse())+ .map(|inv| inv.apply(Vec2::new(dx, dy)) - inv.apply(Vec2::new(0.0, 0.0)))+ .filter(|o| o.is_finite())+ .map_or([0.0; 2], |o| [o.x, o.y]);+ st.adjust(chromatic(centre, kind, unit(amount), offset, unit(a), unit(b)));+ self.shared.frame(st);+ }++ /// A glitch of `kind`, `amount` (0..1) of it. `values` are the kind's own sliders: artifact and+ /// signal amount and block size, wave amplitude and frequency (each 0..1), diverge the red,+ /// green and blue shifts (−1..1); `zoom` (0..1) scales the pattern.+ pub fn adjust_glitch(&self, kind: GlitchKind, amount: f32, values: Vec<f32>, zoom: f32) {+ let finite = |v: f32, lo: f32| if v.is_finite() { v.clamp(lo, 1.0) } else { 0.0 };+ let lo = if kind == GlitchKind::Diverge { -1.0 } else { 0.0 };+ let v = |k: usize| finite(values.get(k).copied().unwrap_or(0.0), lo);+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ // the same pattern for the whole adjustment, another for the next+ let seed = (st.revision % 97) as f32 * 0.731;+ st.adjust(Filter::Glitch {+ kind: kind as u32,+ amount: finite(amount, 0.0),+ values: [v(0), v(1), v(2)],+ zoom: finite(zoom, 0.0),+ seed,+ });+ self.shared.frame(st);+ }++ /// Colour balance: for the shadows, midtones and highlights, how far each of red (against+ /// cyan), green (against magenta) and blue (against yellow) moves, each −1..1.+ pub fn adjust_color_balance(&self, shadows: Vec<f32>, midtones: Vec<f32>, highlights: Vec<f32>) {+ let three = |v: &[f32]| -> [f32; 3] {+ std::array::from_fn(|i| v.get(i).copied().filter(|x| x.is_finite()).unwrap_or(0.0).clamp(-1.0, 1.0))+ };+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.adjust(Filter::ColorBalance {+ shadows: three(&shadows),+ midtones: three(&midtones),+ highlights: three(&highlights),+ });+ self.shared.frame(st);+ }++ /// A gradient map: the gradient through `stops` (position and red, green, blue, all 0..1, four+ /// numbers a stop) by brightness, `amount` (0..1) of the way.+ pub fn adjust_gradient_map(&self, stops: Vec<f32>, amount: f32) {+ let stops: Vec<(f32, [f32; 3])> = stops.as_chunks::<4>().0.iter().map(|&[p, r, g, b]| (p, [r, g, b])).collect();+ let table = tone::gradient_table(&stops);+ let entries: Vec<u8> = table.iter().flat_map(|&[r, g, b]| [r, g, b, 255]).collect();+ let a = if amount.is_finite() { amount.clamp(0.0, 1.0) } else { 1.0 };+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ if let (Some(canvas), Some(gpu)) = (st.canvas.as_mut(), st.gpu.as_ref()) {+ canvas.set_table(gpu, &entries);+ }+ st.adjust(Filter::GradientMap { amount: a });+ self.shared.frame(st);+ }++ /// Starts liquifying the current layer; false when it cannot be.+ pub fn liquify_begin(&self) -> bool {+ if !self.adjust_begin() {+ return false;+ }+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ if let Some(canvas) = st.canvas.as_mut() {+ canvas.begin_liquify();+ }+ st.adjust(Filter::Liquify { amount: 1.0 });+ true+ }++ /// The liquify brush along window points `points` (x, y, pressure 0..1 each); `start` begins a+ /// new stroke. Stamps fall a tenth of the brush apart.+ pub fn liquify_stroke(&self, points: Vec<f32>, start: bool, brush: LiquifyBrush) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let Some(view) = st.view else { return };+ let size = brush.size.clamp(0.0, 1.0);+ let radius = 4.0 + 1596.0 * size.powf(2.2);+ let strength = 0.01 + 0.99 * brush.pressure.clamp(0.0, 1.0);+ let step = (radius * 0.1).max(1.0);+ if start {+ st.liquify_last = None;+ }+ let mut stamps = Vec::new();+ for &[x, y, pen] in points.as_chunks::<3>().0 {+ let Some(p) = view.screen_to_canvas(Vec2::new(x, y)).filter(|p| p.is_finite()) else { continue };+ let pressure = strength * if pen.is_finite() && pen > 0.0 { pen.min(1.0) } else { 1.0 };+ let Some(last) = st.liquify_last else {+ st.liquify_last = Some(p);+ continue;+ };+ let gap = p.distance(last);+ let count = (gap / step).floor() as usize;+ if count == 0 {+ continue;+ }+ let dir = (p - last) * (1.0 / gap);+ let mut at = last;+ for _ in 0..count {+ let next = at + dir * step;+ st.strokes = st.strokes.wrapping_add(1);+ stamps.push(LiquifyStamp {+ centre: [next.x, next.y],+ moved: [dir.x * step, dir.y * step],+ radius,+ pressure,+ distortion: brush.distortion.clamp(0.0, 1.0),+ seed: (st.strokes % 997) as f32,+ mode: brush.kind.into(),+ });+ at = next;+ }+ st.liquify_last = Some(at);+ }+ if let (false, Some(canvas)) = (stamps.is_empty(), st.canvas.as_mut()) {+ canvas.liquify_stamps(&stamps);+ if let Some(f) = st.last_filter {+ canvas.set_filter(f);+ }+ self.shared.frame(st);+ }+ }++ /// The liquify brush carries on after it lifts: from its last stamp along the window velocity+ /// (`vx`, `vy`, pixels a millisecond), slowing to a stop and fading as it goes, for as long as+ /// `momentum` (0..1) lets it.+ pub fn liquify_coast(&self, vx: f32, vy: f32, momentum: f32, brush: LiquifyBrush) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let (Some(view), Some(last)) = (st.view, st.liquify_last.take()) else { return };+ let Some(inv) = view.to_screen().inverse() else { return };+ let velocity = inv.apply(Vec2::new(vx, vy)) - inv.apply(Vec2::new(0.0, 0.0));+ let momentum = if momentum.is_finite() { momentum.clamp(0.0, 1.0) } else { 0.0 };+ let reach = velocity.length() * momentum * LIQUIFY_COAST_MS;+ let radius = 4.0 + 1596.0 * brush.size.clamp(0.0, 1.0).powf(2.2);+ let step = (radius * 0.1).max(1.0);+ if !reach.is_finite() || reach < step {+ return;+ }+ let dir = velocity * (1.0 / velocity.length());+ let strength = 0.01 + 0.99 * brush.pressure.clamp(0.0, 1.0);+ let count = ((reach / step) as usize).min(LIQUIFY_COAST_STAMPS);+ let mut stamps = Vec::with_capacity(count);+ let mut at = last;+ for k in 0..count {+ // the speed falls off evenly, so the stamps fade as the brush slows+ let left = 1.0 - k as f32 / count as f32;+ at = at + dir * step;+ st.strokes = st.strokes.wrapping_add(1);+ stamps.push(LiquifyStamp {+ centre: [at.x, at.y],+ moved: [dir.x * step, dir.y * step],+ radius,+ pressure: strength * left,+ distortion: brush.distortion.clamp(0.0, 1.0),+ seed: (st.strokes % 997) as f32,+ mode: brush.kind.into(),+ });+ }+ if let Some(canvas) = st.canvas.as_mut() {+ canvas.liquify_stamps(&stamps);+ if let Some(f) = st.last_filter {+ canvas.set_filter(f);+ }+ self.shared.frame(st);+ }+ }++ /// How much of the liquify shows (0..1): the adjust slider.+ pub fn liquify_amount(&self, amount: f32) {+ let a = if amount.is_finite() { amount.clamp(0.0, 1.0) } else { 1.0 };+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.adjust(Filter::Liquify { amount: a });+ self.shared.frame(st);+ }++ /// Everything liquified goes back to where it was.+ pub fn liquify_reset(&self) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ if let Some(canvas) = st.canvas.as_mut() {+ canvas.liquify_clear();+ if let Some(f) = st.last_filter {+ canvas.set_filter(f);+ }+ self.shared.frame(st);+ }+ }++ /// Ends the adjustment: `commit` keeps it as one undo step, otherwise the layer goes back.+ pub fn adjust_end(&self, commit: bool) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ if st.adjusting {+ st.end_adjustment(commit);+ st.flush();+ st.revision += 1;+ self.shared.frame(st);+ }+ }++ /// From now on the adjustment shows only where it is painted on with the paint brush.+ pub fn adjust_pencil(&self) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ if !st.adjusting || st.pencil {+ return;+ }+ st.pencil = true;+ if let Some(canvas) = st.canvas.as_mut() {+ canvas.begin_pencil();+ if let Some(filter) = st.last_filter {+ canvas.set_filter(filter);+ }+ }+ self.shared.frame(st);+ }++ /// Starts cloning the current layer: painting copies from the source (see+ /// [`Self::clone_source`]); false when the layer cannot take it.+ /// Whether leaving an adjustment makes the steps made in it one undo step (on at first).+ pub fn set_simplified_undos(&self, on: bool) {+ self.shared.lock().simplified_undos = on;+ }++ pub fn clone_begin(&self) -> bool {+ if !self.adjust_begin() {+ return false;+ }+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.pencil = true;+ st.cloning = true;+ if let Some(canvas) = st.canvas.as_mut() {+ canvas.begin_pencil();+ }+ st.adjust(Filter::Clone { offset: [0.0, 0.0] });+ self.shared.frame(st);+ true+ }++ /// The clone source moved to window point (`x`, `y`): the next stroke copies from there.+ pub fn clone_source(&self, x: f32, y: f32) {+ let mut st = self.shared.lock();+ if let Some(p) = st.view.and_then(|v| v.screen_to_canvas(Vec2::new(x, y))).filter(|p| p.is_finite()) {+ st.clone_source = Some(p);+ st.clone_offset = None;+ }+ }++ /// While `original`, the layer shows as it was before the adjustment; then the adjustment again.+ pub fn adjust_preview(&self, original: bool) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ if !st.adjusting {+ return;+ }+ // nothing sharpened is the layer as it was+ let filter = if original { Some(Filter::Sharpen { amount: 0.0 }) } else { st.last_filter };+ if let (Some(f), Some(canvas)) = (filter, st.canvas.as_mut()) {+ canvas.set_filter(f);+ self.shared.frame(st);+ }+ }++ pub fn is_adjusting(&self) -> bool {+ self.shared.lock().adjusting+ }+}diff --git a/apps/procraft-android/src/animation.rs b/apps/procraft-android/src/animation.rsnew file mode 100644index 0000000..9d88c07--- /dev/null+++ b/apps/procraft-android/src/animation.rs@@ -0,0 +1,323 @@+//! The layers as an animation: each visible top-level layer or group a frame, bottom first, as+//! an animated GIF or PNG, or a frame at a time for a video or a preview.++use std::fs;+use std::io::BufWriter;+use std::path::Path;++use procraft_engine::animation::{self, Animation, Playback};+use procraft_engine::document::{Document, LayerId};+use procraft_engine::formats::GifWriter;++use crate::layers::ThumbnailImage;+use crate::project::{file_error, thumbnail, write_atomically};+use crate::{CanvasSession, MobileError};++/// The frames: the visible top-level layers and groups, bottom first.+fn frames(doc: &Document) -> Vec<LayerId> {+ animation::frames(doc)+}++/// The frames as they play: each as often as Animation Assist holds it.+fn sequence(doc: &Document) -> Vec<LayerId> {+ let holds = |id: LayerId| doc.animation.as_ref().map_or(0, |a| a.hold(id)) as usize;+ frames(doc).into_iter().flat_map(|id| std::iter::repeat_n(id, 1 + holds(id))).collect()+}++#[uniffi::export]+impl CanvasSession {+ /// The frames in playing order (indices into the frames), each as often as it is held.+ pub fn animation_sequence(&self) -> Vec<u32> {+ let doc = &self.shared.lock().doc;+ let all = frames(doc);+ sequence(doc)+ .iter()+ .filter_map(|id| all.iter().position(|f| f == id))+ .filter_map(|i| u32::try_from(i).ok())+ .collect()+ }++ /// How many frames the animation has.+ pub fn animation_frame_count(&self) -> u32 {+ u32::try_from(frames(&self.shared.lock().doc).len()).unwrap_or(u32::MAX)+ }++ /// Frame `index` (bottom first), straight alpha, scaled to fit `max_side` (0: full size),+ /// over the background unless `transparent`; none if there is no such frame.+ pub fn animation_frame(&self, index: u32, transparent: bool, max_side: u32) -> Option<ThumbnailImage> {+ let unit = frames(&self.shared.lock().doc).get(usize::try_from(index).ok()?).copied()?;+ match self.render_frame(unit, transparent, max_side) {+ Ok((width, height, rgba)) => Some(ThumbnailImage { width, height, rgba }),+ Err(e) => {+ log::warn!("animation frame: {e}");+ None+ }+ }+ }++ /// The animation as a looping GIF at `path`, `fps` frames a second, scaled to fit+ /// `max_side` (0: full size); `dither` spreads the palette's error, `transparent` leaves+ /// the background out.+ pub fn export_gif(+ &self,+ path: String,+ max_side: u32,+ fps: f32,+ dither: bool,+ transparent: bool,+ ) -> Result<(), MobileError> {+ let units = sequence(&self.shared.lock().doc);+ let delay = (100.0 / fps.clamp(0.1, 100.0)).round() as u16;+ let mut gif: Option<GifWriter> = None;+ for unit in units {+ let (w, h, rgba) = self.render_frame(unit, transparent, max_side)?;+ gif.get_or_insert_with(|| GifWriter::new(w, h)).frame(&rgba, delay.max(1), dither);+ }+ let bytes = gif.ok_or_else(|| file_error("saving", "there are no frames"))?.finish();+ write_atomically(Path::new(&path), |f| fs::write(f, &bytes).map_err(|e| file_error("saving", e)))+ }++ /// The animation as a looping animated PNG at `path`, `fps` frames a second, scaled to fit+ /// `max_side` (0: full size), `transparent` leaving the background out.+ pub fn export_apng(&self, path: String, max_side: u32, fps: f32, transparent: bool) -> Result<(), MobileError> {+ let units = sequence(&self.shared.lock().doc);+ let count = u32::try_from(units.len()).unwrap_or(u32::MAX);+ let Some((&first, rest)) = units.split_first() else {+ return Err(file_error("saving", "there are no frames"));+ };+ let (w, h, rgba) = self.render_frame(first, transparent, max_side)?;+ // a frame lasts 1/fps seconds, in thousandths+ let delay = (1000.0 / fps.clamp(0.1, 1000.0)).round().clamp(1.0, 65535.0) as u16;+ write_atomically(Path::new(&path), |f| {+ let out = fs::File::create(f).map_err(|e| file_error("saving", e))?;+ let mut encoder = png::Encoder::new(BufWriter::new(out), w, h);+ encoder.set_color(png::ColorType::Rgba);+ encoder.set_depth(png::BitDepth::Eight);+ encoder.set_compression(png::Compression::Fast);+ encoder.set_animated(count, 0).map_err(|e| file_error("saving", e))?;+ encoder.set_frame_delay(delay, 1000).map_err(|e| file_error("saving", e))?;+ let mut writer = encoder.write_header().map_err(|e| file_error("saving", e))?;+ writer.write_image_data(&rgba).map_err(|e| file_error("saving", e))?;+ for &unit in rest {+ let (fw, fh, frame) = self.render_frame(unit, transparent, max_side)?;+ if (fw, fh) != (w, h) {+ return Err(file_error("saving", "the frames differ in size"));+ }+ writer.write_image_data(&frame).map_err(|e| file_error("saving", e))?;+ }+ writer.finish().map_err(|e| file_error("saving", e))+ })+ }+}++impl CanvasSession {+ /// `unit` alone (the background too unless `transparent`), straight alpha, scaled to fit+ /// `max_side` (0: full size). The canvas shows the whole picture again afterwards.+ fn render_frame(+ &self,+ unit: LayerId,+ transparent: bool,+ max_side: u32,+ ) -> Result<(u32, u32, Vec<u8>), MobileError> {+ let (w, h, rgba) = {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.finish_stroke();+ st.settle();+ let mut doc = st.doc.clone();+ for id in doc.members(None) {+ if id != unit {+ doc.set_visible(id, false);+ }+ }+ if transparent {+ doc.background_visible = false;+ }+ let (w, h) = (doc.width(), doc.height());+ let (Some(canvas), Some(gpu)) = (st.canvas.as_mut(), st.gpu.as_ref()) else {+ return Err(file_error("reading the picture", "the canvas is not shown yet"));+ };+ canvas.invalidate();+ canvas.render(gpu, &mut doc, None);+ let rgba = canvas.read_composite(gpu);+ canvas.invalidate();+ canvas.render(gpu, &mut st.doc, None);+ self.shared.frame(st);+ (w, h, rgba.map_err(|e| file_error("reading the picture", e))?)+ };+ let side = if max_side == 0 { w.max(h) } else { max_side.min(w.max(h)) };+ Ok(thumbnail(&rgba, w, h, side))+ }+}++/// How playing goes on after the last frame.+#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]+pub enum AnimationPlayback {+ Loop,+ PingPong,+ OneShot,+}++/// Animation Assist's settings, as the panel shows them.+#[derive(Clone, Debug, PartialEq, uniffi::Record)]+pub struct AnimationSettings {+ pub fps: u32,+ pub onion_frames: u32,+ pub onion_opacity: f32,+ pub playback: AnimationPlayback,+ pub blend_primary: bool,+ /// The onion skins' colours before and after the current frame, sRGB 0..1.+ pub before: Vec<f32>,+ pub after: Vec<f32>,+ pub background: bool,+ pub foreground: bool,+ /// Page Assist rather than Animation Assist.+ pub pages: bool,+}++impl From<&Animation> for AnimationSettings {+ fn from(a: &Animation) -> AnimationSettings {+ AnimationSettings {+ fps: a.fps,+ onion_frames: a.onion_frames,+ onion_opacity: a.onion_opacity,+ playback: match a.playback {+ Playback::Loop => AnimationPlayback::Loop,+ Playback::PingPong => AnimationPlayback::PingPong,+ Playback::OneShot => AnimationPlayback::OneShot,+ },+ blend_primary: a.blend_primary,+ before: a.before.to_vec(),+ after: a.after.to_vec(),+ background: a.background,+ foreground: a.foreground,+ pages: a.pages,+ }+ }+}++#[uniffi::export]+impl CanvasSession {+ /// Turns Animation Assist on (its settings as they start) or off, as an undo step.+ pub fn set_animation_assist(&self, on: bool) -> bool {+ self.set_assist(on, false)+ }++ /// Turns Page Assist on or off, as an undo step.+ pub fn set_page_assist(&self, on: bool) -> bool {+ self.set_assist(on, true)+ }+}++impl CanvasSession {+ /// Animation or Page Assist on (the other off), or that one off.+ fn set_assist(&self, on: bool, pages: bool) -> bool {+ let changed = self+ .change(+ match (on, pages) {+ (true, false) => "show Animation Assist",+ (false, false) => "hide Animation Assist",+ (true, true) => "show Page Assist",+ (false, true) => "hide Page Assist",+ },+ |d| {+ let now = d.animation.as_ref().is_some_and(|a| a.pages == pages);+ (now != on).then(|| d.animation = on.then(|| Animation { pages, ..Animation::default() }))+ },+ )+ .is_some();+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ if let Some(c) = st.canvas.as_mut() {+ c.set_play_frame(None);+ c.invalidate();+ }+ self.shared.frame(st);+ changed+ }+}++#[uniffi::export]+impl CanvasSession {+ /// Animation Assist's settings while it is on.+ pub fn animation_settings(&self) -> Option<AnimationSettings> {+ self.shared.lock().doc.animation.as_ref().map(AnimationSettings::from)+ }++ /// Changes the settings (live, as sliders move).+ pub fn set_animation_settings(&self, s: AnimationSettings) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let Some(a) = st.doc.animation.as_mut() else { return };+ let color = |v: &[f32], or: [f32; 3]| match v {+ [r, g, b] => [*r, *g, *b],+ _ => or,+ };+ *a = Animation {+ fps: s.fps,+ onion_frames: s.onion_frames,+ onion_opacity: s.onion_opacity,+ playback: match s.playback {+ AnimationPlayback::Loop => Playback::Loop,+ AnimationPlayback::PingPong => Playback::PingPong,+ AnimationPlayback::OneShot => Playback::OneShot,+ },+ blend_primary: s.blend_primary,+ before: color(&s.before, a.before),+ after: color(&s.after, a.after),+ background: s.background,+ foreground: s.foreground,+ holds: std::mem::take(&mut a.holds),+ pages: a.pages,+ }+ .repaired();+ if let Some(c) = st.canvas.as_mut() {+ c.invalidate();+ }+ self.shared.frame(st);+ }++ /// The frames' layers (top-level layers and groups), bottom first.+ pub fn animation_frames(&self) -> Vec<u64> {+ animation::frames(&self.shared.lock().doc).into_iter().map(|id| id.0).collect()+ }++ /// The frame holding the current layer.+ pub fn current_frame(&self) -> Option<u32> {+ animation::current_frame(&self.shared.lock().doc).and_then(|i| u32::try_from(i).ok())+ }++ /// Playing: frame `frame` shows alone; none goes back to drawing with onion skins.+ pub fn set_play_frame(&self, frame: Option<u32>) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ if let Some(c) = st.canvas.as_mut() {+ c.set_play_frame(frame.and_then(|f| usize::try_from(f).ok()));+ }+ self.shared.frame(st);+ }++ /// Frame `id`'s picture over the whole canvas, fitted to `max_side` (premultiplied), for the+ /// timeline; none for a group or before the canvas exists.+ pub fn frame_thumbnail(&self, id: u64, max_side: u32) -> Option<ThumbnailImage> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ if st.doc.layer(LayerId(id)).is_none_or(|l| l.kind == procraft_engine::document::LayerKind::Group) {+ return None;+ }+ let (Some(canvas), Some(gpu)) = (st.canvas.as_mut(), st.gpu.as_ref()) else { return None };+ let t = canvas.layer_picture(gpu, &mut st.doc, LayerId(id), max_side).ok()?;+ Some(ThumbnailImage { width: t.width, height: t.height, rgba: t.rgba })+ }++ /// How many more frames the frame of layer `id` is held.+ pub fn frame_hold(&self, id: u64) -> u32 {+ self.shared.lock().doc.animation.as_ref().map_or(0, |a| a.hold(LayerId(id)))+ }++ pub fn set_frame_hold(&self, id: u64, frames: u32) {+ if let Some(a) = self.shared.lock().doc.animation.as_mut() {+ a.set_hold(LayerId(id), frames);+ }+ }+}diff --git a/apps/procraft-android/src/brush_files.rs b/apps/procraft-android/src/brush_files.rsnew file mode 100644index 0000000..f593f20--- /dev/null+++ b/apps/procraft-android/src/brush_files.rs@@ -0,0 +1,583 @@+//! Brush and set files as other painting apps share them (`.brush`, `.brushset`): read into the+//! library, and written from it. A brush's shape and grain images go with it; an image a file only+//! names (one that came with the app that made it) is stood in for by the nearest of ours.++use procraft_engine::brush::{Author, Brush, Source, StockImage, StockImages};+use procraft_engine::brushfile::{self, BrushFile, Pictures, Texture};+use procraft_engine::curve::Curve;+use procraft_engine::textures::{self, TEXTURE_SIZE, grain, shape};++use crate::CanvasSession;+use crate::brush_library::LibrarySet;++/// The set brushes from single brush files go into.+const IMPORTED: &str = "Imported";++/// The size of the preview a brush file carries.+const THUMBNAIL: (u32, u32) = (327, 100);++/// A brush file's pictures, made: the shape, the grain if any and the preview (PNGs).+struct Made {+ shape: Vec<u8>,+ grain: Option<Vec<u8>>,+ thumbnail: Vec<u8>,+ author: Option<std::sync::Arc<[u8]>>,+ signature: Option<std::sync::Arc<[u8]>>,+}++impl Made {+ fn pictures(&self) -> Pictures<'_> {+ Pictures {+ shape_png: &self.shape,+ grain_png: self.grain.as_deref(),+ thumbnail_png: &self.thumbnail,+ author_png: self.author.as_deref(),+ signature_png: self.signature.as_deref(),+ }+ }+}++/// Who made `brush`, as its file is to say ("" for ProCraft's own).+fn author_name(brush: &Brush) -> &str {+ brush.author.as_ref().map_or("", |a| a.name.as_str())+}++impl CanvasSession {+ fn brush_pictures(&self, brush: &Brush, set: u32, index: u32) -> Made {+ // the preview it came with, else one drawn+ let thumbnail = brush.thumbnail.as_deref().map(<[u8]>::to_vec).unwrap_or_else(|| {+ self.brush_preview(set, index, THUMBNAIL.0, THUMBNAIL.1)+ .map(|t| crate::project::rgba_png(t.width, t.height, &t.rgba))+ .unwrap_or_else(|| crate::project::rgba_png(1, 1, &[0, 0, 0, 0]))+ });+ let author = brush.author.as_ref();+ Made {+ shape: gray_png(&shape_pixels(brush)),+ grain: grain_pixels(brush).map(|p| gray_png(&p)),+ thumbnail,+ author: author.and_then(|a| a.picture.clone()),+ signature: author.and_then(|a| a.signature.clone()),+ }+ }+}++#[uniffi::export]+impl CanvasSession {+ /// Adds the brushes in `bytes`: a brush file's (to the top of the "Imported" set, made at the+ /// top of the library if there isn't one) or a set file's (a set of their own at the top).+ /// Returns the set they went into, or none if the file is neither.+ pub fn import_brushes(&self, bytes: Vec<u8>) -> Option<u32> {+ if let Some((name, files)) = brushfile::read_set(&bytes) {+ let brushes: Vec<Brush> = files.iter().map(brush_from).collect();+ let mut st = self.shared.lock();+ let name = if name.trim().is_empty() { IMPORTED.to_owned() } else { name.trim().to_owned() };+ let origins = vec![None; brushes.len()];+ st.library.insert(0, LibrarySet { name, brushes, origins, icon: crate::brush_library::IMPORTED_ICON });+ st.move_brush_refs(|(rs, ri)| Some((rs + 1, ri)));+ return Some(0);+ }+ let brush = brush_from(&brushfile::read(&bytes)?);+ let mut st = self.shared.lock();+ let at = match st.library.iter().position(|s| s.name == IMPORTED) {+ Some(at) => at,+ None => {+ st.library.insert(+ 0,+ LibrarySet {+ name: IMPORTED.to_owned(),+ brushes: Vec::new(),+ origins: Vec::new(),+ icon: crate::brush_library::IMPORTED_ICON,+ },+ );+ st.move_brush_refs(|(rs, ri)| Some((rs + 1, ri)));+ 0+ }+ };+ let entry = st.library.get_mut(at)?;+ entry.brushes.insert(0, brush);+ entry.origins.insert(0, None);+ st.move_brush_refs(|(rs, ri)| Some(if rs == at { (rs, ri + 1) } else { (rs, ri) }));+ Some(at as u32)+ }++ /// Brush `index` of `set` as a brush file.+ pub fn brush_as_file(&self, set: u32, index: u32) -> Option<Vec<u8>> {+ let brush = self.shared.lock().library.get(set as usize)?.brushes.get(index as usize)?.clone();+ let made = self.brush_pictures(&brush, set, index);+ Some(brushfile::write(&brush, author_name(&brush), &made.pictures()))+ }++ /// Set `set` as a set file.+ pub fn brush_set_as_file(&self, set: u32) -> Option<Vec<u8>> {+ let (name, brushes) = {+ let st = self.shared.lock();+ let entry = st.library.get(set as usize)?;+ (entry.name.clone(), entry.brushes.clone())+ };+ let made: Vec<Made> = brushes.iter().enumerate().map(|(i, b)| self.brush_pictures(b, set, i as u32)).collect();+ let list: Vec<(&Brush, &str, Pictures<'_>)> =+ brushes.iter().zip(&made).map(|(b, m)| (b, author_name(b), m.pictures())).collect();+ let seed =+ std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos() as u64);+ Some(brushfile::write_set(&name, &list, |i| folder_id(seed, i)))+ }+}++/// A folder name like the files' own (a UUID's form), from `seed` and the brush's place.+fn folder_id(seed: u64, i: usize) -> String {+ let mix = |k: u64| {+ let mut h = seed ^ (i as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ k.wrapping_mul(0xC2B2_AE3D_27D4_EB4F);+ h ^= h >> 31;+ h = h.wrapping_mul(0xBF58_476D_1CE4_E5B9);+ h ^ (h >> 29)+ };+ let (a, b) = (mix(1), mix(2));+ format!(+ "{:08X}-{:04X}-4{:03X}-{:04X}-{:012X}",+ a >> 32,+ (a >> 16) & 0xFFFF,+ a & 0xFFF,+ 0x8000 | ((b >> 48) & 0x3FFF),+ b & 0xFFFF_FFFF_FFFF+ )+}++/// A brush from a brush file: the studio's controls on a fresh brush, its images found or stood in+/// for.+fn brush_from(file: &BrushFile) -> Brush {+ let mut b = Brush { name: file.name.clone(), ..Brush::round_pen() };+ let (image, source, hardness) = shape_for(&file.shape);+ b.shape.image = image;+ b.shape.source = source;+ if let Some(h) = hardness {+ b.hardness = h;+ }+ for (key, value) in &file.settings {+ b.set_setting(key, *value);+ }+ brushfile::set_sizes(&mut b, file.max_size, file.min_size);+ b.shape.rotation = file.shape_angle;+ for (points, curve) in [(&file.size_curve, &mut b.size_curve), (&file.opacity_curve, &mut b.opacity_curve)] {+ if let Some(points) = points {+ *curve = Curve::new(points);+ }+ }+ if let Some(points) = &file.pressure_curve {+ b.pressure_curve = Curve::new(points);+ }+ b.notches = file.notches.clone();+ let (image, source) = grain_for(&file.grain, file.thumbnail.as_deref());+ b.grain.image = image;+ b.grain.source = source;+ // the stock images it names, to name again when it is written out+ let stock = |t: &Texture| match t {+ Texture::Stock { name, inverted } => Some(StockImage { name: name.clone(), inverted: *inverted }),+ _ => None,+ };+ b.stock = StockImages { shape: stock(&file.shape), grain: stock(&file.grain) };+ // its own preview, if it can be shown+ b.thumbnail = file.thumbnail.as_deref().filter(|t| thumbnail_pixels(t).is_some()).map(Into::into);+ // who made it, if the file says+ let png = |bytes: &Option<Vec<u8>>| bytes.as_deref().filter(|p| decode_png(p).is_some()).map(Into::into);+ let (picture, signature) = (png(&file.author_picture), png(&file.signature));+ let name = file.author.trim();+ if !name.is_empty() || picture.is_some() || signature.is_some() {+ b.author = Some(Author { name: name.chars().take(256).collect(), picture, signature });+ }+ b+}++/// A preview image (PNG) as premultiplied RGBA8, with its width and height; none if it can't be+/// read.+pub(crate) fn thumbnail_pixels(bytes: &[u8]) -> Option<(u32, u32, Vec<u8>)> {+ let (w, h, channels, buf) = decode_png(bytes)?;+ let mut rgba = Vec::with_capacity(w * h * 4);+ for px in buf.chunks_exact(channels.max(1)).take(w * h) {+ let get = |k: usize| px.get(k).copied().unwrap_or(0);+ let (rgb, alpha) = match channels {+ 1 => ([get(0); 3], 255),+ 2 => ([get(0); 3], get(1)),+ 3 => ([get(0), get(1), get(2)], 255),+ _ => ([get(0), get(1), get(2)], get(3)),+ };+ let times = |v: u8| ((u16::from(v) * u16::from(alpha) + 127) / 255) as u8;+ rgba.extend([times(rgb[0]), times(rgb[1]), times(rgb[2]), alpha]);+ }+ (rgba.len() == w * h * 4).then_some((w as u32, h as u32, rgba))+}++/// A PNG's pixels at 8 bits a sample: width, height, samples a pixel and the samples.+fn decode_png(bytes: &[u8]) -> Option<(usize, usize, usize, Vec<u8>)> {+ let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes));+ decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);+ let mut reader = decoder.read_info().ok()?;+ let mut buf = vec![0; reader.output_buffer_size()?];+ let info = reader.next_frame(&mut buf).ok()?;+ let (w, h) = (info.width as usize, info.height as usize);+ (w > 0 && h > 0).then_some((w, h, info.color_type.samples(), buf))+}++/// The shape for a file's: its image, or our nearest, or the round tip at a hardness.+pub(crate) fn shape_for(t: &Texture) -> (Option<u32>, Option<Source>, Option<f32>) {+ match t {+ Texture::None => (None, None, None),+ Texture::Image { bytes, inverted } => match gray_texture(bytes, *inverted) {+ Some(s) => (None, Some(s), None),+ None => (Some(shape::GRAINY_DISC), None, None),+ },+ Texture::Stock { name, inverted } => {+ let n = name.to_lowercase();+ let has = |words: &[&str]| words.iter().any(|w| n.contains(w));+ if has(&["blank"]) {+ // a plain image: the stamp's whole square (nothing, inverted)+ let fill = if *inverted { 0 } else { 255 };+ (None, Source::new(vec![fill; TEXTURE_SIZE * TEXTURE_SIZE]), None)+ } else if has(&["medium-hard", "medium hard", "mediumhard"]) {+ (None, None, Some(0.75))+ } else if has(&["hard", "pen", "solid", "oval", "round"]) && !has(&["soft", "ink"]) {+ (None, None, Some(0.95))+ } else if has(&["medium"]) {+ (None, None, Some(0.5))+ } else if has(&["soft", "air", "blur", "glow"]) {+ (Some(shape::SOFT_ROUND), None, None)+ } else {+ (Some(stock_shape(&n)), None, None)+ }+ }+ }+}++/// Our shape nearest a stock shape's name.+fn stock_shape(n: &str) -> u32 {+ let table: &[(&[&str], u32)] = &[+ (&["brick"], shape::BLOCK),+ (&["spray", "mist", "aero", "speckle"], shape::SPRAY),+ (&["splat", "flick", "spatter", "drip"], shape::SPLATTER),+ (&["bristle", "fan", "hair", "fur"], shape::BRISTLES),+ (&["flat", "chisel", "square brush"], shape::FLAT),+ (&["dry", "streak", "scrape"], shape::DRY),+ (&["chalk", "pastel", "crayon", "charcoal", "conte", "graphite", "pencil"], shape::STOCK_PASTEL),+ (&["stamp", "dash", "impress"], shape::STOCK_DAB),+ (&["dab", "paint", "acrylic", "oil", "gouache", "chunk", "rough"], shape::STOCK_CHUNK),+ (&["blot", "blob", "water", "wash", "stain", "bleed", "ink", "mess", "sponge"], shape::BLOT),+ (&["leaf", "foliage", "tree"], shape::LEAF),+ (&["grass", "reed"], shape::GRASS),+ (&["cloud", "fog", "smoke"], shape::CLOUD),+ (&["wisp", "wind"], shape::WISP),+ (&["star", "sparkle", "glint", "flare", "twinkle"], shape::SPARKLE),+ (&["ring", "bokeh", "circle", "bubble"], shape::RING),+ (&["square", "pixel", "block", "box"], shape::SQUARE),+ (&["hatch", "line", "stripe"], shape::HATCH),+ (&["noise", "grain", "grit", "sand", "texture"], shape::STOCK_GRAINY_DISC),+ ];+ table.iter().find(|(words, _)| words.iter().any(|w| n.contains(w))).map_or(shape::STOCK_GRAINY_DISC, |(_, s)| *s)+}++/// What a brush's own preview (PNG) says of a stock grain we don't have.+#[derive(Clone, Copy, PartialEq, Eq, Debug)]+enum PreviewLook {+ /// The stroke drawn faintly: its pixels on average under [`FAINT_PREVIEW`] of the way to+ /// full, as a stroke worn through by a dark grain is.+ Faint,+ /// The stroke's middle even, its pixels on average within [`EVEN_PREVIEW`] of its fullest+ /// (the preview not wholly opaque): the grain about white.+ Even,+ Plain,+}++fn preview_look(png: &[u8]) -> Option<PreviewLook> {+ let (w, h, rgba) = thumbnail_pixels(png)?;+ let (w, h) = (w as usize, h as usize);+ let (pixels, _) = rgba.as_chunks::<4>();+ let alpha: Vec<f32> = pixels.iter().map(|&[_, _, _, a]| f32::from(a) / 255.0).collect();+ let inked: Vec<f32> = alpha.iter().copied().filter(|&a| a > 13.0 / 255.0).collect();+ if inked.len() < 100 {+ return None;+ }+ let mean = inked.iter().sum::<f32>() / inked.len() as f32;+ if mean < FAINT_PREVIEW {+ return Some(PreviewLook::Faint);+ }+ if mean >= OPAQUE_PREVIEW {+ return Some(PreviewLook::Plain);+ }+ // the stroke's middle: pixels with ink at every pixel up to 3 steps away+ let inked_at = |x: isize, y: isize| {+ x >= 0+ && y >= 0+ && (x as usize) < w+ && (y as usize) < h+ && alpha.get(y as usize * w + x as usize).is_some_and(|&a| a > 0.05)+ };+ let mut middle = Vec::new();+ for y in 0..h as isize {+ for x in 0..w as isize {+ let all = (-3..=3isize).all(|dy| {+ let reach = 3 - dy.abs();+ (-reach..=reach).all(|dx| inked_at(x + dx, y + dy))+ });+ if all && let Some(&a) = alpha.get(y as usize * w + x as usize) {+ middle.push(a);+ }+ }+ }+ if middle.len() < 200 {+ return Some(PreviewLook::Plain);+ }+ middle.sort_by(f32::total_cmp);+ let fullest = middle.get(middle.len() * 95 / 100).copied().unwrap_or(1.0).max(1e-3);+ let even = middle.iter().sum::<f32>() / middle.len() as f32 / fullest >= EVEN_PREVIEW;+ Some(if even { PreviewLook::Even } else { PreviewLook::Plain })+}++/// The share of full under which a preview's stroke is faint (see [`preview_look`]): measured,+/// a brush on a dark speckled grain draws its preview at 0.26 on average, those on lighter grains+/// at 0.40 and up (soft brushes with no grain at all at 0.65).+const FAINT_PREVIEW: f32 = 0.35;++/// How even a preview's middle is, its mean over its 95th percentile, at and above which the+/// grain is taken as about white: the stock brushes' previews this even are mostly on grains of+/// 0.84-0.91 (ink and cloud textures), those less even on 0.06-0.84.+const EVEN_PREVIEW: f32 = 0.95;++/// The share of full at and above which a preview is wholly opaque (drawn as a flat stamp), which+/// says nothing of its grain.+const OPAQUE_PREVIEW: f32 = 0.99;++/// The grain for a file's: its image, or our nearest, or none. A stock grain whose name says nothing+/// we know stands in as a dark speckle if the brush's own preview (`preview`, a PNG) draws faintly,+/// as none if its middle draws evenly, else as a light mottle, as most stock grains are.+pub(crate) fn grain_for(t: &Texture, preview: Option<&[u8]>) -> (Option<u32>, Option<Source>) {+ match t {+ Texture::None => (None, None),+ Texture::Image { bytes, inverted } => match gray_texture(bytes, *inverted) {+ Some(s) => (None, Some(s)),+ None => (Some(grain::PAPER), None),+ },+ Texture::Stock { name, .. } => {+ let n = name.to_lowercase();+ if n.contains("blank") {+ return (None, None);+ }+ let table: &[(&[&str], u32)] = &[+ (&["recycled"], grain::RECYCLED),+ (&["canvas", "weave", "burlap", "cloth", "fabric"], grain::WEAVE),+ (&["linen"], grain::LINEN),+ (&["denim", "twill"], grain::TWILL),+ (&["wood"], grain::WOOD),+ (&["brick"], grain::BRICK),+ (&["concrete", "stone", "rock", "wall", "asphalt"], grain::CONCRETE),+ (&["halftone", "dot"], grain::HALFTONE),+ (&["hatch"], grain::HATCHING),+ (&["crumple", "crease", "fold"], grain::CRUMPLED),+ (&["stipple"], grain::STIPPLE),+ (&["wash", "water", "wet"], grain::WASH),+ (&["marble"], grain::MARBLE),+ (&["cell", "organic"], grain::CELLS),+ (&["scale"], grain::SCALES),+ (&["hex", "honeycomb"], grain::HEXAGONS),+ (&["leather", "skin"], grain::LEATHER),+ (&["bark"], grain::BARK),+ (&["rust"], grain::RUST),+ (&["scratch"], grain::SCRATCHES),+ // a sheet of paper: a worn, light one, or crumpled+ (&["dirty-paper", "dirty paper", "worn-paper", "worn paper"], grain::WORN),+ (&["paper"], grain::SHEET),+ (&["grunge", "dirt", "dust", "dirty"], grain::GRUNGE),+ (&["fibre", "fiber", "hair", "straw"], grain::FIBRE),+ (&["sand", "grit"], grain::SAND),+ (&["noise", "static"], grain::FINE_NOISE),+ (&["charcoal", "willow", "chalk", "pastel", "rough", "coarse", "corse"], grain::CHARCOAL),+ ];+ let unknown = || match preview.and_then(preview_look) {+ Some(PreviewLook::Faint) => Some(grain::SPECKLED),+ // about white: as good as none+ Some(PreviewLook::Even) => None,+ _ => Some(grain::MOTTLED),+ };+ let g = table+ .iter()+ .find(|(words, _)| words.iter().any(|w| n.contains(w)))+ .map_or_else(unknown, |(_, g)| Some(*g));+ (g, None)+ }+ }+}++/// An image (PNG) as a shape or grain: grey (its alpha taken in), [`TEXTURE_SIZE`] square, white+/// for paint; none if it can't be read.+fn gray_texture(bytes: &[u8], inverted: bool) -> Option<Source> {+ let (w, h, channels, buf) = decode_png(bytes)?;+ let value = |x: usize, y: usize| -> f32 {+ let at = (y * w + x) * channels;+ let px = buf.get(at..at + channels).unwrap_or(&[]);+ let get = |k: usize| f32::from(px.get(k).copied().unwrap_or(0));+ let (lum, alpha) = match channels {+ 1 => (get(0), 255.0),+ 2 => (get(0), get(1)),+ 3 => (0.299 * get(0) + 0.587 * get(1) + 0.114 * get(2), 255.0),+ _ => (0.299 * get(0) + 0.587 * get(1) + 0.114 * get(2), get(3)),+ };+ lum * alpha / 255.0+ };+ let n = TEXTURE_SIZE;+ // a smaller image is blown up smoothly, between its pixels' centres+ let between = |fx: f32, fy: f32| -> f32 {+ let (fx, fy) = (fx.clamp(0.0, (w - 1) as f32), fy.clamp(0.0, (h - 1) as f32));+ let (x0, y0) = (fx.floor() as usize, fy.floor() as usize);+ let (x1, y1) = ((x0 + 1).min(w - 1), (y0 + 1).min(h - 1));+ let (u, v) = (fx - x0 as f32, fy - y0 as f32);+ let top = value(x0, y0) * (1.0 - u) + value(x1, y0) * u;+ let bottom = value(x0, y1) * (1.0 - u) + value(x1, y1) * u;+ top * (1.0 - v) + bottom * v+ };+ let mut pixels = Vec::with_capacity(n * n);+ for ty in 0..n {+ let (y0, y1) = (ty * h / n, ((ty + 1) * h / n).max(ty * h / n + 1).min(h));+ for tx in 0..n {+ let v = if w < n || h < n {+ let at = |t: usize, size: usize| (t as f32 + 0.5) * size as f32 / n as f32 - 0.5;+ between(at(tx, w), at(ty, h))+ } else {+ // each texture pixel the average of the image's pixels it covers+ let (x0, x1) = (tx * w / n, ((tx + 1) * w / n).max(tx * w / n + 1).min(w));+ let mut sum = 0.0;+ for y in y0..y1 {+ for x in x0..x1 {+ sum += value(x, y);+ }+ }+ sum / ((y1 - y0) * (x1 - x0)).max(1) as f32+ };+ let v = if inverted { 255.0 - v } else { v };+ pixels.push(v.round().clamp(0.0, 255.0) as u8);+ }+ }+ Source::new(pixels)+}++/// The brush's shape as an image: its own, one of ours, or its round tip drawn.+fn shape_pixels(b: &Brush) -> Vec<u8> {+ if let Some(s) = &b.shape.source {+ return s.pixels.to_vec();+ }+ if let Some(img) = b.shape.image.and_then(|i| textures::shapes().into_iter().nth(i as usize)) {+ return img.pixels;+ }+ // the round tip filling the image, its edge as soft as the brush's hardness says+ let n = TEXTURE_SIZE;+ let soft = (1.0 - b.hardness.clamp(0.0, 1.0)).max(0.02);+ (0..n * n)+ .map(|i| {+ let (x, y) = ((i % n) as f32 + 0.5, (i / n) as f32 + 0.5);+ let r = ((x / n as f32 - 0.5).powi(2) + (y / n as f32 - 0.5).powi(2)).sqrt() * 2.0;+ let v = ((1.0 - r) / soft).clamp(0.0, 1.0);+ (v * v * (3.0 - 2.0 * v) * 255.0).round() as u8+ })+ .collect()+}++/// The brush's grain as an image, if it has one.+fn grain_pixels(b: &Brush) -> Option<Vec<u8>> {+ if let Some(s) = &b.grain.source {+ return Some(s.pixels.to_vec());+ }+ b.grain.image.and_then(|i| textures::grains().into_iter().nth(i as usize)).map(|g| g.pixels)+}++/// A square grey PNG of `pixels`.+fn gray_png(pixels: &[u8]) -> Vec<u8> {+ let n = TEXTURE_SIZE as u32;+ let mut out = Vec::new();+ let mut encoder = png::Encoder::new(&mut out, n, n);+ encoder.set_color(png::ColorType::Grayscale);+ encoder.set_depth(png::BitDepth::Eight);+ if let Ok(mut writer) = encoder.write_header() {+ let _ = writer.write_image_data(pixels);+ let _ = writer.finish();+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn stock_names_find_our_nearest() {+ assert_eq!(+ shape_for(&Texture::Stock { name: "Brush-Hard.png".into(), inverted: false }),+ (None, None, Some(0.95))+ );+ assert_eq!(shape_for(&Texture::Stock { name: "Soft.png".into(), inverted: false }).0, Some(shape::SOFT_ROUND));+ assert_eq!(shape_for(&Texture::Stock { name: "Spray-Fine.jpg".into(), inverted: false }).0, Some(shape::SPRAY));+ assert_eq!(grain_for(&Texture::Stock { name: "Blank.png".into(), inverted: false }, None), (None, None));+ assert_eq!(+ grain_for(&Texture::Stock { name: "Old-Canvas.jpg".into(), inverted: false }, None).0,+ Some(grain::WEAVE)+ );+ // a name we don't know: a light mottle, a dark speckle if the brush's preview is faint, or+ // none if its middle is even+ let mystery = Texture::Stock { name: "Mystery.png".into(), inverted: false };+ let preview = |alpha: u8| crate::project::rgba_png(40, 10, &[alpha, alpha, alpha, alpha].repeat(400));+ assert_eq!(grain_for(&mystery, None).0, Some(grain::MOTTLED));+ assert_eq!(grain_for(&mystery, Some(&preview(60))).0, Some(grain::SPECKLED));+ assert_eq!(grain_for(&mystery, Some(&preview(200))).0, Some(grain::MOTTLED));+ let stroke = |alpha: &dyn Fn(usize) -> u8| {+ let px: Vec<u8> = (0..60 * 30).flat_map(|i| [alpha(i); 4]).collect();+ crate::project::rgba_png(60, 30, &px)+ };+ assert_eq!(grain_for(&mystery, Some(&stroke(&|_| 220))).0, None);+ assert_eq!(grain_for(&mystery, Some(&stroke(&|i| if i % 3 == 0 { 120 } else { 240 }))).0, Some(grain::MOTTLED));+ assert_eq!(+ grain_for(&Texture::Stock { name: "Munched-Paper.png".into(), inverted: false }, None).0,+ Some(grain::SHEET)+ );+ assert_eq!(+ grain_for(&Texture::Stock { name: "Dirty-Paper.jpg".into(), inverted: false }, None).0,+ Some(grain::WORN)+ );+ assert_eq!(+ grain_for(&Texture::Stock { name: "Charcoal-Corse.jpg".into(), inverted: false }, None).0,+ Some(grain::CHARCOAL)+ );+ // willow charcoal's grain is a charcoal's+ assert_eq!(+ grain_for(&Texture::Stock { name: "Willow-Grain.jpg".into(), inverted: false }, None).0,+ Some(grain::CHARCOAL)+ );+ }++ #[test]+ fn an_image_becomes_a_texture() {+ // a 4 × 4 grey PNG: white on the left half+ let px: Vec<u8> = (0..16).map(|i| if i % 4 < 2 { 255 } else { 0 }).collect();+ let mut png_bytes = Vec::new();+ let mut e = png::Encoder::new(&mut png_bytes, 4, 4);+ e.set_color(png::ColorType::Grayscale);+ let mut w = e.write_header().unwrap();+ w.write_image_data(&px).unwrap();+ w.finish().unwrap();+ let s = gray_texture(&png_bytes, false).unwrap();+ let n = TEXTURE_SIZE;+ assert_eq!((s.pixels[n / 2 * n + 10], s.pixels[n / 2 * n + n - 10]), (255, 0));+ // blown up smoothly: the edge between the halves fades across+ assert!((100..156).contains(&s.pixels[n / 2 * n + n / 2]), "{}", s.pixels[n / 2 * n + n / 2]);+ assert!(s.pixels[n / 2 * n + n / 2 - n / 16] > s.pixels[n / 2 * n + n / 2]);+ let inv = gray_texture(&png_bytes, true).unwrap();+ assert_eq!(inv.pixels[n / 2 * n + 10], 0);+ assert!(gray_texture(b"not an image", false).is_none());+ // our own textures go out and come back the same+ let back = gray_texture(&gray_png(&textures::grains()[3].pixels), false).unwrap();+ assert_eq!(*back.pixels, textures::grains()[3].pixels);+ }++ #[test]+ fn folder_ids_look_like_the_files_own() {+ let id = folder_id(42, 3);+ assert_eq!(id.len(), 36);+ assert_eq!(id.matches('-').count(), 4);+ assert_ne!(id, folder_id(42, 4));+ }+}diff --git a/apps/procraft-android/src/brush_library.rs b/apps/procraft-android/src/brush_library.rsnew file mode 100644index 0000000..4142ce0--- /dev/null+++ b/apps/procraft-android/src/brush_library.rs@@ -0,0 +1,722 @@+//! Editing the brush library: brushes duplicated, deleted and made new, sets made, renamed and+//! deleted, and the whole library kept between sessions as each brush's origin and changes.++use std::collections::BTreeMap;++use procraft_engine::brush::{Author, Brush, Notches, ResetPoint, Source, StockImage, StockImages};+use procraft_engine::brushfile::Texture;+use procraft_engine::curve::Curve;+use procraft_engine::geom::Vec2;+use procraft_engine::library::{BrushSet, SHELF};++use crate::{CanvasSession, State};++/// A set in the library as it is now: the shipped sets as edited, and the user's own.+pub(crate) struct LibrarySet {+ pub(crate) name: String,+ pub(crate) brushes: Vec<Brush>,+ /// Where each brush came from: a shipped (set, index), or none for a new brush.+ pub(crate) origins: Vec<Option<(usize, usize)>>,+ /// Which of the set icons it shows.+ pub(crate) icon: u32,+}++/// How many set icons there are: the 42 to choose from, then the six shipped sets' own.+pub const SET_ICONS: u32 = 48;++/// The brush icon, which a new set starts with.+const BRUSH_ICON: u32 = 5;++/// The icon a set of imported brushes starts with.+pub(crate) const IMPORTED_ICON: u32 = BRUSH_ICON;++/// The set icons' numbering as kept. Sets kept under an earlier one have their icon worked out+/// again (their shipped icon, else the brush).+const ICON_NUMBERING: u32 = 2;++/// The icon a shipped set starts with, by its name (the brush icon for the rest).+fn shipped_icon(name: &str) -> u32 {+ match name {+ "Sketching" => 42,+ "Inking" => 43,+ "Painting" => 44,+ "Airbrushing" => 45,+ "Charcoals" => 46,+ "Textures" => 47,+ // later sets show glyphs from the shared choice+ "Drawing" => 1,+ "Watercolour" => 13,+ "Calligraphy" => 27,+ "Spray Paint" => 35,+ "Nature" => 38,+ "Effects" => 32,+ "Pixel" => 9,+ "Elements" => 18,+ "Industrial" => 21,+ "Organic" => 16,+ "Abstract" => 11,+ "Touchups" => 40,+ "Retro" => 15,+ "Vintage" => 37,+ "Luminance" => 34,+ _ => BRUSH_ICON,+ }+}++impl LibrarySet {+ /// The library as it ships, its sets in shelf order.+ pub(crate) fn shipped(sets: &[BrushSet]) -> Vec<LibrarySet> {+ SHELF+ .iter()+ .filter_map(|&s| sets.get(s).map(|set| (s, set)))+ .map(|(s, set)| LibrarySet {+ name: set.name.to_owned(),+ brushes: set.brushes.clone(),+ origins: (0..set.brushes.len()).map(|i| Some((s, i))).collect(),+ icon: shipped_icon(set.name),+ })+ .collect()+ }+}++impl CanvasSession {+ fn shipped_counts(shipped: &[BrushSet]) -> Vec<u32> {+ shipped.iter().map(|set| set.brushes.len() as u32).collect()+ }+}++/// Where the brush that started as shipped `origin` is in `library`, else the first place.+pub(crate) fn place_of(library: &[LibrarySet], origin: (usize, usize)) -> (usize, usize) {+ library+ .iter()+ .enumerate()+ .find_map(|(s, set)| set.origins.iter().position(|o| *o == Some(origin)).map(|i| (s, i)))+ .unwrap_or((0, 0))+}++/// What a new brush starts as.+fn blank_brush() -> Brush {+ Brush { name: "Untitled Brush".to_owned(), ..Brush::round_pen() }+}++/// A brush as kept: where it came from, its name, the controls that differ from there and, if it+/// differs, its pressure curve.+#[derive(serde::Serialize, serde::Deserialize)]+struct SavedBrush {+ #[serde(default)]+ from: Option<(usize, usize)>,+ name: String,+ #[serde(default)]+ settings: BTreeMap<String, f32>,+ #[serde(default)]+ curve: Vec<[f32; 2]>,+ /// The pressure's own curves for the size and the opacity, if they differ.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ size_curve: Vec<[f32; 2]>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ opacity_curve: Vec<[f32; 2]>,+ /// The brush's own shape and grain images, as text.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ shape_source: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ grain_source: Option<String>,+ /// The shipped shape and grain images it uses, where they differ from its origin's (-1: none).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ shape_image: Option<i64>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ grain_image: Option<i64>,+ /// The preview its file brought, while it is as it came (PNG, as text).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ thumbnail: Option<String>,+ /// The values saved on the side sliders while using it.+ #[serde(default, skip_serializing_if = "SavedNotches::is_empty")]+ notches: SavedNotches,+ /// Who made it, if its file said.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ author: Option<SavedAuthor>,+ /// What resetting it puts back, and when that was set aside.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ reset: Option<SavedReset>,+ /// The stock shape and grain images its file named (and whether inverted): drawn with ours+ /// standing in, found again by name when it is loaded.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ shape_stock: Option<(String, bool)>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ grain_stock: Option<(String, bool)>,+}++/// A brush's maker as kept: their name, and their picture and signature (PNG, as text).+#[derive(serde::Serialize, serde::Deserialize)]+struct SavedAuthor {+ name: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ picture: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ signature: Option<String>,+}++/// A reset point as kept: the brush set aside (from the same origin) and when.+#[derive(serde::Serialize, serde::Deserialize)]+struct SavedReset {+ made: i64,+ brush: Box<SavedBrush>,+}++/// A brush's slider notches as kept: sizes and opacities for painting, smudging and erasing.+#[derive(serde::Serialize, serde::Deserialize, Default)]+struct SavedNotches {+ #[serde(default)]+ sizes: [Vec<f32>; 3],+ #[serde(default)]+ opacities: [Vec<f32>; 3],+}++impl SavedNotches {+ fn is_empty(&self) -> bool {+ self.sizes.iter().chain(&self.opacities).all(Vec::is_empty)+ }++ fn of(n: &Notches) -> SavedNotches {+ SavedNotches { sizes: n.sizes.clone(), opacities: n.opacities.clone() }+ }++ /// As notches again: only slider positions, and no more than a slider takes.+ fn notches(&self) -> Notches {+ let clean = |l: &Vec<f32>| -> Vec<f32> {+ l.iter().copied().filter(|v| (0.0..=1.0).contains(v)).take(Notches::MOST).collect()+ };+ Notches { sizes: self.sizes.each_ref().map(clean), opacities: self.opacities.each_ref().map(clean) }+ }+}++#[derive(serde::Serialize, serde::Deserialize)]+struct SavedSet {+ name: String,+ brushes: Vec<SavedBrush>,+ /// The set's icon; kept libraries from before have none.+ #[serde(default)]+ icon: Option<u32>,+ /// Which numbering [`Self::icon`] is in (none before the first change of it).+ #[serde(default)]+ icons: u32,+}++impl SavedSet {+ /// Its icon, in today's numbering.+ fn icon_now(&self) -> u32 {+ match self.icon {+ Some(icon) if self.icons == ICON_NUMBERING => icon.min(SET_ICONS - 1),+ _ => shipped_icon(&self.name),+ }+ }+}++/// The brushes in use, as kept between sessions (by place in the library).+#[derive(serde::Serialize, serde::Deserialize)]+struct SavedChoices {+ /// The paint, erase and smudge tools' brushes.+ tools: [(usize, usize); 3],+ /// Each set's last chosen brush, the latest choice last.+ #[serde(default)]+ sets: Vec<(usize, usize)>,+ /// The side sliders' size and opacity per brush and tool (0 paint, 1 erase, 2 smudge).+ #[serde(default)]+ sliders: Vec<(u8, usize, usize, f32, f32)>,+}++/// The tools in the order [`SavedChoices`] keeps them.+const TOOLS: [crate::ToolKind; 3] = [crate::ToolKind::Paint, crate::ToolKind::Erase, crate::ToolKind::Smudge];++/// One brush as a file to share.+#[derive(serde::Serialize, serde::Deserialize)]+struct BrushFile {+ procraft_brush: u32,+ brush: SavedBrush,+}++/// A set as a file to share.+#[derive(serde::Serialize, serde::Deserialize)]+struct SetFile {+ procraft_brush_set: u32,+ set: SavedSet,+}++impl State {+ /// What brush `origin` started as.+ pub(crate) fn origin_brush(&self, origin: Option<(usize, usize)>) -> Brush {+ origin+ .and_then(|(s, i)| self.shipped.get(s).and_then(|set| set.brushes.get(i)))+ .cloned()+ .unwrap_or_else(blank_brush)+ }++ /// Brush `i` of `set` as kept: its origin and its changes from there.+ fn saved(&self, set: &LibrarySet, i: usize) -> Option<SavedBrush> {+ let brush = set.brushes.get(i)?;+ Some(self.saved_brush(brush, set.origins.get(i).copied().flatten()))+ }++ /// `brush` as kept, as changed from what it started as (`from`).+ fn saved_brush(&self, brush: &Brush, from: Option<(usize, usize)>) -> SavedBrush {+ let base = self.origin_brush(from);+ let kept = |c: &Curve, b: &Curve| -> Vec<[f32; 2]> {+ if c == b { Vec::new() } else { c.points().iter().map(|p| [p.x, p.y]).collect() }+ };+ let image = |mine: Option<u32>, theirs: Option<u32>| (mine != theirs).then(|| mine.map_or(-1, i64::from));+ let text = |png: &Option<std::sync::Arc<[u8]>>| png.as_deref().map(procraft_engine::base64::encode);+ SavedBrush {+ from,+ name: brush.name.clone(),+ settings: brush.changes_from(&base).into_iter().collect(),+ curve: kept(&brush.pressure_curve, &base.pressure_curve),+ size_curve: kept(&brush.size_curve, &base.size_curve),+ opacity_curve: kept(&brush.opacity_curve, &base.opacity_curve),+ shape_source: brush.shape.source.as_ref().map(Source::to_text),+ grain_source: brush.grain.source.as_ref().map(Source::to_text),+ shape_image: image(brush.shape.image, base.shape.image),+ grain_image: image(brush.grain.image, base.grain.image),+ thumbnail: brush.thumbnail.as_deref().map(procraft_engine::base64::encode),+ notches: SavedNotches::of(&brush.notches),+ author: brush.author.as_ref().map(|a| SavedAuthor {+ name: a.name.clone(),+ picture: text(&a.picture),+ signature: text(&a.signature),+ }),+ reset: brush+ .reset_point+ .as_ref()+ .map(|r| SavedReset { made: r.made, brush: Box::new(self.saved_brush(&r.brush, from)) }),+ shape_stock: brush.stock.shape.as_ref().map(|s| (s.name.clone(), s.inverted)),+ grain_stock: brush.stock.grain.as_ref().map(|s| (s.name.clone(), s.inverted)),+ }+ }++ /// A kept brush made again.+ fn restored(&self, b: SavedBrush) -> Brush {+ let mut brush = self.origin_brush(b.from);+ if !b.name.trim().is_empty() {+ brush.name = b.name.chars().take(256).collect();+ }+ // the images first: a brush's own shape sets the unit its sizes are kept in+ for (kept, image) in [(b.shape_image, &mut brush.shape.image), (b.grain_image, &mut brush.grain.image)] {+ if let Some(k) = kept {+ *image = u32::try_from(k).ok();+ }+ }+ if let Some(text) = &b.shape_source {+ brush.shape.source = Source::from_text(text);+ }+ if let Some(text) = &b.grain_source {+ brush.grain.source = Source::from_text(text);+ }+ // the stock images its file named, stood in for by our nearest as they are now+ let stock = |kept: &Option<(String, bool)>| {+ kept.as_ref().map(|(name, inverted)| StockImage { name: name.clone(), inverted: *inverted })+ };+ brush.stock = StockImages { shape: stock(&b.shape_stock), grain: stock(&b.grain_stock) };+ let png = |text: &Option<String>| text.as_deref().and_then(procraft_engine::base64::decode).map(Into::into);+ brush.thumbnail = png(&b.thumbnail);+ if let Some(s) = &brush.stock.shape {+ let texture = Texture::Stock { name: s.name.clone(), inverted: s.inverted };+ brush.shape.image = crate::brush_files::shape_for(&texture).0;+ }+ if let Some(s) = &brush.stock.grain {+ let texture = Texture::Stock { name: s.name.clone(), inverted: s.inverted };+ brush.grain.image = crate::brush_files::grain_for(&texture, brush.thumbnail.as_deref()).0;+ }+ brush.set_settings(b.settings.iter().map(|(k, v)| (k.as_str(), *v)));+ for (points, curve) in [+ (&b.curve, &mut brush.pressure_curve),+ (&b.size_curve, &mut brush.size_curve),+ (&b.opacity_curve, &mut brush.opacity_curve),+ ] {+ if points.len() >= 2 {+ let pts: Vec<Vec2> = points.iter().map(|&[x, y]| Vec2::new(x, y)).collect();+ *curve = Curve::new(&pts);+ }+ }+ brush.notches = b.notches.notches();+ brush.author = b.author.as_ref().map(|a| Author {+ name: a.name.clone(),+ picture: png(&a.picture),+ signature: png(&a.signature),+ });+ brush.reset_point = b.reset.map(|r| ResetPoint::of(&self.restored(*r.brush), r.made));+ brush+ }++ /// Whether the library has a brush at `(set, index)`.+ fn holds(&self, (set, index): (usize, usize)) -> bool {+ self.library.get(set).is_some_and(|s| index < s.brushes.len())+ }++ /// The brush last chosen in `set`, if one has been.+ pub(crate) fn set_choice(&self, set: usize) -> Option<usize> {+ self.set_choices.iter().find(|c| c.0 == set).map(|c| c.1)+ }++ /// Notes `place` as its set's last chosen brush.+ pub(crate) fn note_choice(&mut self, place: (usize, usize)) {+ self.set_choices.retain(|c| c.0 != place.0);+ self.set_choices.push(place);+ }++ /// The first brush in the library, for a tool whose brush is gone.+ fn first_brush(&self) -> (usize, usize) {+ (self.library.iter().position(|s| !s.brushes.is_empty()).unwrap_or(0), 0)+ }++ /// Every place that names a brush by its position: the tools' brushes and the kept sliders.+ pub(crate) fn move_brush_refs(&mut self, f: impl Fn((usize, usize)) -> Option<(usize, usize)>) {+ let first = self.first_brush();+ for r in [&mut self.paint_brush, &mut self.erase_brush, &mut self.smudge_brush] {+ *r = f(*r).unwrap_or(first);+ }+ self.sliders = std::mem::take(&mut self.sliders)+ .into_iter()+ .filter_map(|((tool, s, i), v)| f((s, i)).map(|(s, i)| ((tool, s, i), v)))+ .collect();+ // a set's choice follows its brush: a set it leaves has none, and a set it joins keeps the+ // later choice+ for place in std::mem::take(&mut self.set_choices).into_iter().filter_map(&f) {+ if self.holds(place) {+ self.note_choice(place);+ }+ }+ // a tool left on a set with no brushes takes the first brush there is+ let first = self.first_brush();+ let library = &self.library;+ for r in [&mut self.paint_brush, &mut self.erase_brush, &mut self.smudge_brush] {+ if library.get(r.0).is_none_or(|s| r.1 >= s.brushes.len()) {+ *r = first;+ }+ }+ }+}++#[uniffi::export]+impl CanvasSession {+ /// A copy of a brush just above it in its set; returns the copy's index.+ pub fn duplicate_brush(&self, set: u32, index: u32) -> Option<u32> {+ let mut st = self.shared.lock();+ let (s, i) = (set as usize, index as usize);+ let entry = st.library.get_mut(s)?;+ let brush = entry.brushes.get(i)?.clone();+ let origin = entry.origins.get(i).copied().flatten();+ entry.brushes.insert(i, brush);+ entry.origins.insert(i, origin);+ st.move_brush_refs(|(rs, ri)| Some(if rs == s && ri >= i { (rs, ri + 1) } else { (rs, ri) }));+ Some(index)+ }++ /// Moves a brush to place `to_index` of set `to_set` (counted without it there); a tool that+ /// used it keeps it, wherever it goes.+ pub fn move_brush(&self, set: u32, index: u32, to_set: u32, to_index: u32) -> bool {+ let mut st = self.shared.lock();+ let (s, i, ts) = (set as usize, index as usize, to_set as usize);+ if ts >= st.library.len() {+ return false;+ }+ let Some(entry) = st.library.get_mut(s) else { return false };+ if i >= entry.brushes.len() {+ return false;+ }+ let brush = entry.brushes.remove(i);+ let origin = if i < entry.origins.len() { entry.origins.remove(i) } else { None };+ let Some(target) = st.library.get_mut(ts) else { return false };+ let ti = (to_index as usize).min(target.brushes.len());+ target.brushes.insert(ti, brush);+ if ti <= target.origins.len() {+ target.origins.insert(ti, origin);+ } else {+ target.origins.push(origin);+ }+ st.move_brush_refs(|(rs, ri)| {+ if (rs, ri) == (s, i) {+ return Some((ts, ti));+ }+ // out of its old place, then into the new one+ let ri = if rs == s && ri > i { ri - 1 } else { ri };+ Some((rs, if rs == ts && ri >= ti { ri + 1 } else { ri }))+ });+ true+ }++ /// Removes a brush; a tool that used it takes the one now in its place.+ pub fn delete_brush(&self, set: u32, index: u32) -> bool {+ let mut st = self.shared.lock();+ let (s, i) = (set as usize, index as usize);+ let Some(entry) = st.library.get_mut(s) else { return false };+ if i >= entry.brushes.len() {+ return false;+ }+ entry.brushes.remove(i);+ if i < entry.origins.len() {+ entry.origins.remove(i);+ }+ let left = entry.brushes.len();+ st.move_brush_refs(|(rs, ri)| match (rs == s, ri.cmp(&i)) {+ (true, std::cmp::Ordering::Greater) => Some((rs, ri - 1)),+ // the brush below moves up into its place, or the one above when it was last+ (true, std::cmp::Ordering::Equal) => (left > 0).then(|| (rs, ri.min(left - 1))),+ _ => Some((rs, ri)),+ });+ true+ }++ /// A new plain round brush at the top of `set`, chosen for the current tool; returns its+ /// index.+ pub fn new_brush(&self, set: u32) -> Option<u32> {+ let mut st = self.shared.lock();+ let s = set as usize;+ let entry = st.library.get_mut(s)?;+ entry.brushes.insert(0, blank_brush());+ entry.origins.insert(0, None);+ st.move_brush_refs(|(rs, ri)| Some(if rs == s { (rs, ri + 1) } else { (rs, ri) }));+ let before = st.brush_ref(st.tool);+ st.note_choice(before);+ match st.tool {+ crate::ToolKind::Paint => st.paint_brush = (s, 0),+ crate::ToolKind::Erase => st.erase_brush = (s, 0),+ crate::ToolKind::Smudge => st.smudge_brush = (s, 0),+ }+ st.note_choice((s, 0));+ Some(0)+ }++ /// A new empty set at the top of the library; returns its index.+ pub fn new_brush_set(&self) -> u32 {+ let mut st = self.shared.lock();+ st.library.insert(+ 0,+ LibrarySet { name: "Untitled Set".to_owned(), brushes: Vec::new(), origins: Vec::new(), icon: BRUSH_ICON },+ );+ st.move_brush_refs(|(s, i)| Some((s + 1, i)));+ 0+ }++ pub fn rename_brush_set(&self, set: u32, name: String) -> bool {+ let name = name.trim();+ let mut st = self.shared.lock();+ match st.library.get_mut(set as usize) {+ Some(entry) if !name.is_empty() => {+ entry.name = name.chars().take(256).collect();+ true+ }+ _ => false,+ }+ }++ /// Removes a set and its brushes (not the last set).+ pub fn delete_brush_set(&self, set: u32) -> bool {+ let mut st = self.shared.lock();+ let s = set as usize;+ if s >= st.library.len() || st.library.len() <= 1 {+ return false;+ }+ st.library.remove(s);+ st.move_brush_refs(|(rs, ri)| match rs.cmp(&s) {+ std::cmp::Ordering::Less => Some((rs, ri)),+ std::cmp::Ordering::Equal => None,+ std::cmp::Ordering::Greater => Some((rs - 1, ri)),+ });+ true+ }++ /// The library as kept between sessions (JSON).+ pub fn saved_brush_library(&self) -> String {+ let st = self.shared.lock();+ let sets: Vec<SavedSet> = st+ .library+ .iter()+ .map(|set| SavedSet {+ name: set.name.clone(),+ brushes: (0..set.brushes.len()).filter_map(|i| st.saved(set, i)).collect(),+ icon: Some(set.icon),+ icons: ICON_NUMBERING,+ })+ .collect();+ serde_json::to_string(&sets).unwrap_or_default()+ }++ /// Puts back a library kept with [`Self::saved_brush_library`]; false, changing nothing, if it+ /// can't be read.+ pub fn load_brush_library(&self, json: String) -> bool {+ let Ok(saved) = serde_json::from_str::<Vec<SavedSet>>(&json) else { return false };+ if saved.is_empty() {+ return false;+ }+ let mut st = self.shared.lock();+ let library: Vec<LibrarySet> = saved+ .into_iter()+ .map(|set| {+ let icon = set.icon_now();+ let origins = set.brushes.iter().map(|b| b.from).collect();+ let brushes = set.brushes.into_iter().map(|b| st.restored(b)).collect();+ LibrarySet { name: set.name, brushes, origins, icon }+ })+ .collect();+ st.library = library;+ st.sliders.clear();+ st.move_brush_refs(Some);+ true+ }++ /// The tools' brushes, the sets' last choices and each brush's sliders, as kept between+ /// sessions (JSON); kept with the library as it is now.+ pub fn saved_brush_choices(&self) -> String {+ let st = self.shared.lock();+ let tool_index = |tool| TOOLS.iter().position(|&t| t == tool).unwrap_or(0) as u8;+ let mut sliders: Vec<_> =+ st.sliders.iter().map(|(&(tool, s, i), v)| (tool_index(tool), s, i, v.size, v.opacity)).collect();+ sliders.sort_by_key(|&(t, s, i, ..)| (t, s, i));+ let choices =+ SavedChoices { tools: TOOLS.map(|tool| st.brush_ref(tool)), sets: st.set_choices.clone(), sliders };+ serde_json::to_string(&choices).unwrap_or_default()+ }++ /// Puts back what [`Self::saved_brush_choices`] kept, after the library it was kept with;+ /// places the library no longer has are left as they are. False if it can't be read.+ pub fn load_brush_choices(&self, json: String) -> bool {+ let Ok(saved) = serde_json::from_str::<SavedChoices>(&json) else { return false };+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ for (tool, place) in TOOLS.into_iter().zip(saved.tools) {+ if !st.holds(place) {+ continue;+ }+ match tool {+ crate::ToolKind::Paint => st.paint_brush = place,+ crate::ToolKind::Erase => st.erase_brush = place,+ crate::ToolKind::Smudge => st.smudge_brush = place,+ }+ }+ st.set_choices.clear();+ for place in saved.sets {+ if st.holds(place) {+ st.note_choice(place);+ }+ }+ for (tool, s, i, size, opacity) in saved.sliders {+ let Some(&tool) = TOOLS.get(usize::from(tool)) else { continue };+ if st.holds((s, i)) && size.is_finite() && opacity.is_finite() {+ let v = crate::Sliders { size: size.clamp(0.0, 1.0), opacity: opacity.clamp(0.0, 1.0) };+ st.sliders.insert((tool, s, i), v);+ }+ }+ true+ }++ /// Adds to the library what shipped since it was kept. `seen` is how many brushes of each+ /// shipped set it has had the chance to hold (sets past its end hadn't shipped). A set's new+ /// brushes go at the end of the set holding its others (not at all if that set is gone); new+ /// sets go at the end, in shelf order. Nothing the library holds already is added again.+ /// Returns how many brushes each set ships with now.+ pub fn add_shipped_brushes(&self, seen: Vec<u32>) -> Vec<u32> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let holds = |library: &[LibrarySet], origin: (usize, usize)| {+ library.iter().any(|set| set.origins.contains(&Some(origin)))+ };+ // new brushes of sets it had+ for (s, set) in st.shipped.iter().enumerate() {+ let Some(&had) = seen.get(s) else { continue };+ let home = st.library.iter().position(|l| l.origins.iter().flatten().any(|&(from, _)| from == s));+ let Some(home) = home else { continue };+ for (i, brush) in set.brushes.iter().enumerate().skip(had as usize) {+ if holds(&st.library, (s, i)) {+ continue;+ }+ if let Some(entry) = st.library.get_mut(home) {+ entry.brushes.push(brush.clone());+ entry.origins.push(Some((s, i)));+ }+ }+ }+ // sets it never had+ let new: Vec<LibrarySet> = LibrarySet::shipped(&st.shipped)+ .into_iter()+ .filter(|set| {+ set.origins.first().copied().flatten().is_some_and(|(s, _)| {+ s >= seen.len()+ && !st.library.iter().any(|l| l.origins.iter().flatten().any(|&(from, _)| from == s))+ })+ })+ .collect();+ st.library.extend(new);+ Self::shipped_counts(&st.shipped)+ }++ /// How many brushes each set ships with.+ pub fn shipped_brush_counts(&self) -> Vec<u32> {+ Self::shipped_counts(&self.shared.lock().shipped)+ }++ /// One brush as a file to share (JSON).+ pub fn brush_file(&self, set: u32, index: u32) -> Option<String> {+ let st = self.shared.lock();+ let brush = st.saved(st.library.get(set as usize)?, index as usize)?;+ serde_json::to_string(&BrushFile { procraft_brush: 1, brush }).ok()+ }++ /// A set as a file to share (JSON).+ pub fn brush_set_file(&self, set: u32) -> Option<String> {+ let st = self.shared.lock();+ let entry = st.library.get(set as usize)?;+ let brushes = (0..entry.brushes.len()).filter_map(|i| st.saved(entry, i)).collect();+ serde_json::to_string(&SetFile {+ procraft_brush_set: 1,+ set: SavedSet { name: entry.name.clone(), brushes, icon: Some(entry.icon), icons: ICON_NUMBERING },+ })+ .ok()+ }++ /// The set's icon (0 to [`SET_ICONS`] − 1).+ pub fn set_brush_set_icon(&self, set: u32, icon: u32) -> bool {+ let mut st = self.shared.lock();+ let Some(entry) = st.library.get_mut(set as usize) else { return false };+ entry.icon = icon.min(SET_ICONS - 1);+ true+ }++ /// A copy of a set (its brushes as they are) just above it; returns the copy's index.+ pub fn duplicate_brush_set(&self, set: u32) -> Option<u32> {+ let mut st = self.shared.lock();+ let s = set as usize;+ let entry = st.library.get(s)?;+ let copy = LibrarySet {+ name: entry.name.clone(),+ brushes: entry.brushes.clone(),+ origins: entry.origins.clone(),+ icon: entry.icon,+ };+ st.library.insert(s, copy);+ st.move_brush_refs(|(rs, ri)| Some(if rs >= s { (rs + 1, ri) } else { (rs, ri) }));+ Some(set)+ }++ /// A shared file of a brush (put at the top of `set`) or of a set (put at the top of the+ /// library); returns the set it went into, or none if the file can't be read.+ pub fn import_brush_file(&self, set: u32, file: String) -> Option<u32> {+ if let Ok(saved) = serde_json::from_str::<SetFile>(&file) {+ let mut st = self.shared.lock();+ let icon = saved.set.icon_now();+ let origins = saved.set.brushes.iter().map(|b| b.from).collect();+ let brushes = saved.set.brushes.into_iter().map(|b| st.restored(b)).collect();+ let name = if saved.set.name.trim().is_empty() { "Untitled Set".to_owned() } else { saved.set.name };+ st.library.insert(0, LibrarySet { name, brushes, origins, icon });+ st.move_brush_refs(|(rs, ri)| Some((rs + 1, ri)));+ return Some(0);+ }+ let saved = serde_json::from_str::<BrushFile>(&file).ok()?;+ let mut st = self.shared.lock();+ let s = set as usize;+ let from = saved.brush.from;+ let brush = st.restored(saved.brush);+ let entry = st.library.get_mut(s)?;+ entry.brushes.insert(0, brush);+ entry.origins.insert(0, from);+ st.move_brush_refs(|(rs, ri)| Some(if rs == s { (rs, ri + 1) } else { (rs, ri) }));+ Some(set)+ }+}diff --git a/apps/procraft-android/src/brushes.rs b/apps/procraft-android/src/brushes.rsnew file mode 100644index 0000000..d6b3866--- /dev/null+++ b/apps/procraft-android/src/brushes.rs@@ -0,0 +1,151 @@+//! The brush library: its sets and brushes, choosing the brush for the current tool, and preview+//! strokes for the library panel.++use procraft_engine::document::Document;+use procraft_engine::geom::Vec2;+use procraft_engine::input::Pointer;+use procraft_engine::preview;+use procraft_engine::stroke::{Stamp, StrokeBuilder};+use procraft_gpu::{Canvas, StrokeStyle, StrokeTool};++use crate::CanvasSession;+use crate::layers::ThumbnailImage;++#[derive(Clone, Debug, PartialEq, uniffi::Record)]+pub struct BrushInfo {+ pub set: u32,+ pub index: u32,+ pub name: String,+}++#[derive(Clone, Debug, PartialEq, uniffi::Record)]+pub struct BrushSetInfo {+ pub name: String,+ pub brushes: Vec<BrushInfo>,+ /// Which of the set icons it shows.+ pub icon: u32,+ /// The brush last chosen in it, if one has been.+ pub chosen: Option<u32>,+}++#[uniffi::export]+impl CanvasSession {+ pub fn brush_library(&self) -> Vec<BrushSetInfo> {+ let st = self.shared.lock();+ st.library+ .iter()+ .enumerate()+ .map(|(s, set)| BrushSetInfo {+ name: set.name.to_owned(),+ icon: set.icon,+ chosen: st.set_choice(s).map(|i| i as u32),+ brushes: set+ .brushes+ .iter()+ .enumerate()+ .map(|(i, b)| BrushInfo { set: s as u32, index: i as u32, name: b.name.clone() })+ .collect(),+ })+ .collect()+ }++ /// The brush the current tool uses.+ pub fn current_brush(&self) -> BrushInfo {+ let st = self.shared.lock();+ let (set, index) = st.brush_ref(st.tool);+ BrushInfo { set: set as u32, index: index as u32, name: st.brush(st.tool).name.clone() }+ }++ /// The current tool's brush's control `key`, as the studio shows it.+ pub fn current_brush_setting(&self, key: String) -> f32 {+ let st = self.shared.lock();+ st.brush(st.tool).setting(&key)+ }++ /// The current tool's brush's saved sizes (`size`) or opacities: its slider's notches.+ pub fn slider_notches(&self, size: bool) -> Vec<f32> {+ let st = self.shared.lock();+ st.brush(st.tool).notches.list(notch_tool(st.tool), size).to_vec()+ }++ /// Saves `value` on the current tool's size or opacity slider (its brush keeps it); false if+ /// the slider is full or a notch is there already.+ pub fn add_slider_notch(&self, size: bool, value: f32) -> bool {+ let mut st = self.shared.lock();+ let tool = st.tool;+ st.brush_mut(tool).is_some_and(|b| b.notches.add(notch_tool(tool), size, value))+ }++ /// Takes away the notch `value` is on, on the current tool's size or opacity slider.+ pub fn remove_slider_notch(&self, size: bool, value: f32) -> bool {+ let mut st = self.shared.lock();+ let tool = st.tool;+ st.brush_mut(tool).is_some_and(|b| b.notches.remove(notch_tool(tool), size, value))+ }++ /// Chooses the brush the current tool uses.+ pub fn select_brush(&self, set: u32, index: u32) -> bool {+ let mut st = self.shared.lock();+ let (set, index) = (set as usize, index as usize);+ if st.library.get(set).and_then(|s| s.brushes.get(index)).is_none() {+ return false;+ }+ // the set left keeps showing the brush it had, the new one this+ let before = st.brush_ref(st.tool);+ st.note_choice(before);+ match st.tool {+ crate::ToolKind::Paint => st.paint_brush = (set, index),+ crate::ToolKind::Erase => st.erase_brush = (set, index),+ crate::ToolKind::Smudge => st.smudge_brush = (set, index),+ }+ st.note_choice((set, index));+ true+ }++ /// A sample stroke drawn with the brush, white on transparent, fitted into `width` × `height`+ /// pixels.+ pub fn brush_preview(&self, set: u32, index: u32, width: u32, height: u32) -> Option<ThumbnailImage> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let brush = st.library.get(set as usize)?.brushes.get(index as usize)?.clone();+ let (w, h) = (width.clamp(16, 2048), height.clamp(16, 1024));+ // the preview it came with, while it is as it came+ if let Some((tw, th, rgba)) = brush.thumbnail.as_deref().and_then(crate::brush_files::thumbnail_pixels) {+ return Some(ThumbnailImage { width: w, height: h, rgba: preview::fit_image(&rgba, (tw, th), w, h) });+ }+ let gpu = st.gpu.as_ref()?;+ // drawn on a canvas of the sample stroke's own, then fitted into the preview+ let (cw, ch) = (preview::CANVAS.0 as u32, preview::CANVAS.1 as u32);+ if st.preview.is_none() {+ let mut doc = Document::new(cw, ch);+ doc.background_visible = false;+ let canvas = Canvas::new(gpu, &doc).ok()?;+ st.preview = Some((canvas, doc));+ }+ let (canvas, doc) = st.preview.as_mut()?;+ let layer = doc.current();+ canvas.wipe_layer(layer);+ let mut style = StrokeStyle::for_brush(&brush, StrokeTool::Paint, [1.0, 1.0, 1.0], 1.0, false);+ style.preview = true;+ canvas.use_sources(gpu, &mut style, &brush);+ canvas.begin_stroke(layer, style);+ if brush.setting("preview_stamp") >= 0.5 {+ // the brush's stamp on its own, filling the preview's height+ canvas.add_stamps(&[Stamp::round(Vec2::new(cw as f32 / 2.0, ch as f32 / 2.0), ch as f32 * 0.4, 1.0)]);+ } else {+ let mut stroke = StrokeBuilder::new(brush.clone(), preview::diameter(&brush), Pointer::Stylus).steady();+ canvas.add_stamps(&stroke.add(&preview::samples(&brush)));+ canvas.replace_stamps(&stroke.finish());+ }+ canvas.end_stroke();+ canvas.render(gpu, doc, None);+ canvas.forget_history();+ let rgba = canvas.read_composite(gpu).ok()?;+ Some(ThumbnailImage { width: w, height: h, rgba: preview::fit(&rgba, w, h) })+ }+}++/// Where a tool's notches are kept on a brush.+fn notch_tool(tool: crate::ToolKind) -> usize {+ procraft_engine::brush::Notches::tool(tool == crate::ToolKind::Paint, tool == crate::ToolKind::Smudge)+}diff --git a/apps/procraft-android/src/clipboard.rs b/apps/procraft-android/src/clipboard.rsnew file mode 100644index 0000000..f61aab1--- /dev/null+++ b/apps/procraft-android/src/clipboard.rs@@ -0,0 +1,191 @@+//! Copy, cut and paste, the canvas flipped, and pictures brought in as layers.++use procraft_engine::document::LayerId;++use crate::layers::ThumbnailImage;+use crate::{CanvasSession, State};++impl State {+ /// The current layer's pixels within the selection (all of it without one).+ fn selected_pixels(&mut self) -> Option<Vec<u8>> {+ let mask = self.selection.clone();+ let mut pixels = self.current_pixels()?;+ if let Some(mask) = mask {+ for (px, &m) in pixels.as_chunks_mut::<4>().0.iter_mut().zip(&mask.data) {+ let k = u16::from(m);+ for c in px.iter_mut() {+ *c = ((u16::from(*c) * k + 127) / 255) as u8;+ }+ }+ }+ Some(pixels)+ }+}++/// `image` placed on a `width` × `height` canvas: centred, and scaled down to fit when `fit` and+/// it is larger (premultiplied RGBA8; anything outside is cut off).+fn placed(image: &ThumbnailImage, width: u32, height: u32, fit: bool) -> Option<Vec<u8>> {+ let (iw, ih) = (image.width as usize, image.height as usize);+ if iw == 0 || ih == 0 || image.rgba.len() != iw * ih * 4 {+ return None;+ }+ let (w, h) = (width as usize, height as usize);+ let scale = if fit { (w as f32 / iw as f32).min(h as f32 / ih as f32).min(1.0) } else { 1.0 };+ let (sw, sh) = ((iw as f32 * scale).round().max(1.0) as usize, (ih as f32 * scale).round().max(1.0) as usize);+ let (ox, oy) = ((w as i64 - sw as i64) / 2, (h as i64 - sh as i64) / 2);+ let mut out = vec![0u8; w * h * 4];+ for y in 0..sh {+ let ty = oy + y as i64;+ if ty < 0 || ty >= h as i64 {+ continue;+ }+ // nearest source row and column (scaling only ever shrinks)+ let sy = ((y as f32 + 0.5) / scale) as usize;+ for x in 0..sw {+ let tx = ox + x as i64;+ if tx < 0 || tx >= w as i64 {+ continue;+ }+ let sx = ((x as f32 + 0.5) / scale) as usize;+ let (src, dst) = ((sy.min(ih - 1) * iw + sx.min(iw - 1)) * 4, (ty as usize * w + tx as usize) * 4);+ if let (Some(from), Some(to)) = (image.rgba.get(src..src + 4), out.get_mut(dst..dst + 4)) {+ to.copy_from_slice(from);+ }+ }+ }+ Some(out)+}++/// `pixels` (premultiplied RGBA8, `width` wide) mirrored left to right, or top to bottom.+fn flipped(pixels: &[u8], width: usize, horizontal: bool) -> Vec<u8> {+ let rows: Vec<&[[u8; 4]]> = pixels.as_chunks::<4>().0.chunks(width.max(1)).collect();+ if horizontal {+ rows.iter().flat_map(|r| r.iter().rev()).flatten().copied().collect()+ } else {+ rows.iter().rev().flat_map(|r| r.iter()).flatten().copied().collect()+ }+}++#[uniffi::export]+impl CanvasSession {+ /// The current layer within the selection, to paste later.+ pub fn copy_layer(&self) -> Option<ThumbnailImage> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let rgba = st.selected_pixels()?;+ Some(ThumbnailImage { width: st.doc.width(), height: st.doc.height(), rgba })+ }++ /// The whole canvas as it shows, to paste later.+ pub fn copy_canvas(&self) -> Option<ThumbnailImage> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.finish_stroke();+ st.settle();+ st.flush();+ let (Some(canvas), Some(gpu)) = (st.canvas.as_ref(), st.gpu.as_ref()) else { return None };+ let rgba = canvas.read_composite(gpu).ok()?;+ Some(ThumbnailImage { width: st.doc.width(), height: st.doc.height(), rgba })+ }++ /// Copies the current layer within the selection, then clears that.+ pub fn cut_layer(&self) -> Option<ThumbnailImage> {+ let copied = self.copy_layer()?;+ self.clear_layer();+ Some(copied)+ }++ /// A new layer above the current one holding `image` where it was copied from (centred when+ /// it is another size); returns its id.+ pub fn paste(&self, image: ThumbnailImage) -> Option<u64> {+ self.add_picture(&image, false)+ }++ /// A new layer above the current one holding `image` (a photo or file, straight RGBA8),+ /// centred and scaled down to fit; returns its id.+ pub fn insert_image(&self, image: ThumbnailImage) -> Option<u64> {+ let mut premultiplied = image;+ for px in premultiplied.rgba.as_chunks_mut::<4>().0 {+ let a = u16::from(px[3]);+ for c in px.iter_mut().take(3) {+ *c = ((u16::from(*c) * a + 127) / 255) as u8;+ }+ }+ self.add_picture(&premultiplied, true)+ }++ /// Mirrors every layer of the canvas, left to right or (not `horizontal`) top to bottom, as+ /// one undo step.+ pub fn flip_canvas(&self, horizontal: bool) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.finish_stroke();+ st.settle();+ st.flush();+ let width = st.doc.width() as usize;+ let ids: Vec<LayerId> = st.doc.layer_ids().collect();+ let (Some(canvas), Some(gpu)) = (st.canvas.as_mut(), st.gpu.as_ref()) else { return };+ let layers: Vec<(LayerId, Vec<u8>)> = ids+ .into_iter()+ .filter_map(|id| canvas.read_layer(gpu, id).ok().map(|p| (id, flipped(&p, width, horizontal))))+ .collect();+ canvas.name_next_step(if horizontal { "flip canvas horizontally" } else { "flip canvas vertically" });+ canvas.write_layers(layers);+ st.revision += 1;+ self.shared.frame(st);+ }+}++impl CanvasSession {+ fn add_picture(&self, image: &ThumbnailImage, fit: bool) -> Option<u64> {+ let (w, h) = {+ let st = self.shared.lock();+ (st.doc.width(), st.doc.height())+ };+ let pixels = placed(image, w, h, fit)?;+ let id = self.add_layer();+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ if !st.doc.has_room(1) {+ return None;+ }+ if let (Some(canvas), Some(gpu)) = (st.canvas.as_mut(), st.gpu.as_ref()) {+ canvas.upload_layer(gpu, LayerId(id), &pixels).ok()?;+ }+ st.revision += 1;+ self.shared.frame(st);+ Some(id)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn flips_mirror_rows_and_columns() {+ // two by two: red green / blue white+ let px: Vec<u8> = [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255, 255, 255, 255]].concat();+ assert_eq!(+ flipped(&px, 2, true),+ [[0, 255, 0, 255], [255, 0, 0, 255], [255, 255, 255, 255], [0, 0, 255, 255]].concat()+ );+ assert_eq!(+ flipped(&px, 2, false),+ [[0, 0, 255, 255], [255, 255, 255, 255], [255, 0, 0, 255], [0, 255, 0, 255]].concat()+ );+ }++ #[test]+ fn pictures_are_centred_and_fitted() {+ let image = ThumbnailImage { width: 4, height: 2, rgba: vec![200; 4 * 2 * 4] };+ let on = placed(&image, 8, 8, true).unwrap();+ // centred: rows 3 and 4, columns 2 to 5+ assert_eq!(on[(3 * 8 + 2) * 4], 200);+ assert_eq!(on[(3 * 8 + 1) * 4], 0);+ let big = ThumbnailImage { width: 16, height: 16, rgba: vec![9; 16 * 16 * 4] };+ let fitted = placed(&big, 8, 8, true).unwrap();+ assert!(fitted.iter().all(|&v| v == 9));+ assert!(placed(&ThumbnailImage { width: 3, height: 3, rgba: vec![] }, 8, 8, true).is_none());+ }+}diff --git a/apps/procraft-android/src/colour.rs b/apps/procraft-android/src/colour.rsnew file mode 100644index 0000000..1b1eeda--- /dev/null+++ b/apps/procraft-android/src/colour.rs@@ -0,0 +1,250 @@+//! Colour profiles by name: the built-in RGB ones, ProCraft's own CMYK profile and those the user+//! imported (kept as .icc files in a folder the app names), and colours moved between them for+//! the colour panel.++use std::path::PathBuf;+use std::sync::{Arc, Mutex};++use procraft_engine::cms::{CanvasIcc, IccProfile, Space};+use procraft_engine::document::Document;+use procraft_engine::profile::Profile;++use crate::CanvasSession;++/// The profiles the user imported, and the folder they are kept in.+struct Imported {+ folder: Option<PathBuf>,+ profiles: Vec<Arc<IccProfile>>,+}++static IMPORTED: Mutex<Imported> = Mutex::new(Imported { folder: None, profiles: Vec::new() });++fn imported() -> Vec<Arc<IccProfile>> {+ IMPORTED.lock().map(|i| i.profiles.clone()).unwrap_or_default()+}++/// ProCraft's own CMYK profile, read once.+fn generic_cmyk() -> Option<Arc<IccProfile>> {+ static READ: std::sync::OnceLock<Option<Arc<IccProfile>>> = std::sync::OnceLock::new();+ READ.get_or_init(|| IccProfile::parse(&procraft_engine::cmyk::profile()).map(Arc::new)).clone()+}++/// What a profile name puts a canvas in: a built-in profile, and a profile of its own if any.+pub(crate) fn resolve(name: &str) -> Option<(Profile, Option<CanvasIcc>)> {+ if let Some(p) = Profile::from_name(name) {+ return Some((p, None));+ }+ let icc = std::iter::once(generic_cmyk()).flatten().chain(imported()).find(|p| p.name == name)?;+ Some(placed(icc))+}++/// The built-in profile beside `icc`: Display P3 for a CMYK profile (its canvas's pixels are in+/// it), else the one nearest an RGB profile's name.+fn placed(icc: Arc<IccProfile>) -> (Profile, Option<CanvasIcc>) {+ let near = if icc.space == Space::Cmyk || icc.name.contains("P3") { Profile::DisplayP3 } else { Profile::Srgb };+ (near, Some(CanvasIcc(icc)))+}++/// The RGB profile named `name` (a canvas's own when it is the one named), if any.+fn rgb_named(name: &str, doc: Option<&Document>) -> Option<Arc<IccProfile>> {+ if let Some(d) = doc.filter(|d| d.profile_name() == name) {+ return Some(d.rgb_profile());+ }+ let (profile, icc) = resolve(name)?;+ let mut probe = Document::new(1, 1);+ probe.change_to(profile, icc);+ Some(probe.rgb_profile())+}++/// The table taking a canvas's colours to the screen's (as a press would print them, for a CMYK+/// canvas), for a canvas with a profile of its own; none for the built-in profiles, which the+/// display moves by matrix.+#[cfg(any(target_os = "android", test))]+pub(crate) fn display_table(doc: &Document, screen: Profile) -> Option<procraft_engine::cms::Lut> {+ doc.icc.as_ref()?;+ use procraft_engine::cms;+ Some(cms::Lut::build(&doc.rgb_profile(), &cms::builtin(screen), doc.press().as_deref(), 33))+}++/// What [`display_table`] depends on, to know when to make it again.+#[cfg(any(target_os = "android", test))]+pub(crate) fn table_key(doc: &Document, screen: Profile) -> Option<(usize, Profile)> {+ doc.icc.as_ref().map(|i| (Arc::as_ptr(&i.0) as usize, screen))+}++/// 0xRRGGBB as 0..1 values.+fn unpack(rgb: u32) -> [f64; 3] {+ [16, 8, 0].map(|s| f64::from((rgb >> s) & 0xFF) / 255.0)+}++/// 0..1 values as 0xRRGGBB.+fn pack(v: &[f64]) -> u32 {+ let byte = |k: usize| (v.get(k).copied().unwrap_or(0.0).clamp(0.0, 1.0) * 255.0).round() as u32;+ (byte(0) << 16) | (byte(1) << 8) | byte(2)+}++/// Tells where imported profiles are kept, and reads those already there.+#[uniffi::export]+pub fn set_profile_folder(dir: String) {+ let folder = PathBuf::from(dir);+ let mut profiles = Vec::new();+ if let Ok(entries) = std::fs::read_dir(&folder) {+ let mut paths: Vec<PathBuf> = entries.flatten().map(|e| e.path()).collect();+ paths.sort();+ for path in paths {+ if let Some(p) = std::fs::read(&path).ok().and_then(|b| IccProfile::parse(&b)).filter(|p| p.can_receive()) {+ profiles.push(Arc::new(p));+ }+ }+ }+ if let Ok(mut i) = IMPORTED.lock() {+ *i = Imported { folder: Some(folder), profiles };+ }+}++/// Adds the profile in `bytes` (an .icc file) to those a canvas can be in, keeping a copy; its+/// name, or none if it isn't an RGB or CMYK profile colours can be turned into. A profile with the+/// name of one there already takes its place.+#[uniffi::export]+pub fn import_profile(bytes: Vec<u8>) -> Option<String> {+ let p = IccProfile::parse(&bytes).filter(|p| p.can_receive() && p.space != Space::Gray && !p.name.is_empty())?;+ if Profile::from_name(&p.name).is_some() || generic_cmyk().is_some_and(|g| g.name == p.name) {+ return Some(p.name);+ }+ let mut i = IMPORTED.lock().ok()?;+ if let Some(folder) = &i.folder {+ let safe: String =+ p.name.chars().map(|c| if c.is_alphanumeric() || " -_.".contains(c) { c } else { '_' }).collect();+ let _ = std::fs::create_dir_all(folder);+ if let Err(e) = std::fs::write(folder.join(format!("{}.icc", safe.trim())), &bytes) {+ log::error!("keeping an imported profile: {e}");+ }+ }+ let name = p.name.clone();+ i.profiles.retain(|q| q.name != name);+ i.profiles.push(Arc::new(p));+ Some(name)+}++/// The CMYK profiles a canvas can print to, by name, in the order lists show them.+#[uniffi::export]+pub fn cmyk_profiles() -> Vec<String> {+ let ours = generic_cmyk().map(|p| p.name.clone());+ ours.into_iter().chain(imported().iter().filter(|p| p.space == Space::Cmyk).map(|p| p.name.clone())).collect()+}++/// The RGB profiles a canvas can be in, by name, in the order lists show them: the built-in ones,+/// then those imported.+#[uniffi::export]+pub fn color_profiles() -> Vec<String> {+ Profile::ALL+ .iter()+ .map(|p| p.name().to_owned())+ .chain(imported().iter().filter(|p| p.space == Space::Rgb).map(|p| p.name.clone()))+ .collect()+}++/// Whether `name` is one of the built-in RGB profiles (whose colours the screen shows by matrix).+#[uniffi::export]+pub fn profile_is_built_in(name: String) -> bool {+ Profile::from_name(&name).is_some()+}++/// Whether the profile named `name` is a CMYK one.+#[uniffi::export]+pub fn is_cmyk_profile(name: String) -> bool {+ resolve(&name).is_some_and(|(_, icc)| icc.is_some_and(|i| i.0.space == Space::Cmyk))+}++/// An 8-bit colour (0xRRGGBB) in the RGB profile named `from` (a CMYK profile's: Display P3), as it+/// is in `to`; unchanged if either name isn't a profile.+#[uniffi::export]+pub fn convert_color(rgb: u32, from: String, to: String) -> u32 {+ match (Profile::from_name(&from), Profile::from_name(&to)) {+ (Some(from), Some(to)) => from.convert_rgb(rgb & 0xFF_FFFF, to),+ _ => match (rgb_named(&from, None), rgb_named(&to, None)) {+ (Some(a), Some(b)) => pack(&a.convert(&unpack(rgb), &b)),+ _ => rgb,+ },+ }+}++#[uniffi::export]+impl CanvasSession {+ /// Whether the canvas prints to a CMYK profile.+ pub fn is_cmyk(&self) -> bool {+ self.shared.lock().doc.press().is_some()+ }++ /// The canvas colour `rgb` (0xRRGGBB) as the canvas shows it: as its press would print it on a+ /// CMYK canvas, else unchanged.+ pub fn proof_color(&self, rgb: u32) -> u32 {+ let st = self.shared.lock();+ let Some(press) = st.doc.press() else { return rgb & 0xFF_FFFF };+ let rgb_profile = st.doc.rgb_profile();+ pack(&press.convert(&rgb_profile.convert(&unpack(rgb), &press), &rgb_profile))+ }++ /// The inks (cyan, magenta, yellow, black; 0..1) a CMYK canvas prints canvas colour `rgb` with;+ /// empty on an RGB canvas.+ pub fn cmyk_of(&self, rgb: u32) -> Vec<f32> {+ let st = self.shared.lock();+ let Some(press) = st.doc.press() else { return Vec::new() };+ // white is the paper+ if rgb & 0xFF_FFFF == 0xFF_FFFF {+ return vec![0.0; 4];+ }+ st.doc.rgb_profile().convert(&unpack(rgb), &press).iter().map(|&v| v as f32).collect()+ }++ /// The canvas colour (0xRRGGBB) inks `cmyk` (0..1 each) print as on a CMYK canvas; black on an+ /// RGB canvas.+ pub fn rgb_of_cmyk(&self, cmyk: Vec<f32>) -> u32 {+ let st = self.shared.lock();+ let Some(press) = st.doc.press() else { return 0 };+ let inks: Vec<f64> = (0..4).map(|k| f64::from(cmyk.get(k).copied().unwrap_or(0.0)).clamp(0.0, 1.0)).collect();+ pack(&press.convert(&inks, &st.doc.rgb_profile()))+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn our_cmyk_profile_is_offered_and_resolves() {+ assert_eq!(cmyk_profiles().first().map(String::as_str), Some(procraft_engine::cmyk::NAME));+ let (profile, icc) = resolve(procraft_engine::cmyk::NAME).unwrap();+ assert_eq!(profile, Profile::DisplayP3);+ assert_eq!(icc.unwrap().0.space, Space::Cmyk);+ assert!(is_cmyk_profile(procraft_engine::cmyk::NAME.to_owned()));+ assert!(!is_cmyk_profile("Display P3".to_owned()));+ assert_eq!(resolve("sRGB IEC61966-2.1"), Some((Profile::Srgb, None)));+ assert!(resolve("no such profile").is_none());+ }++ #[test]+ fn a_cmyk_canvas_shows_through_a_table() {+ let mut doc = Document::new(4, 4);+ assert!(display_table(&doc, Profile::Srgb).is_none() && table_key(&doc, Profile::Srgb).is_none());+ let (profile, icc) = resolve(procraft_engine::cmyk::NAME).unwrap();+ doc.change_to(profile, icc);+ let table = display_table(&doc, Profile::DisplayP3).unwrap();+ // the press dulls a pure green; white stays white+ let green = table.apply([0.0, 1.0, 0.0]);+ assert!(green[0] > 0.2 && green[1] < 0.9, "{green:?}");+ assert_eq!(table.apply([1.0, 1.0, 1.0]), vec![1.0, 1.0, 1.0]);+ assert_eq!(table_key(&doc, Profile::DisplayP3), table_key(&doc.clone(), Profile::DisplayP3));+ }++ #[test]+ fn colours_move_between_profiles_by_name() {+ // built in: the matrices+ let p3_red = convert_color(0xFF0000, "sRGB IEC61966-2.1".to_owned(), "Display P3".to_owned());+ assert_eq!(p3_red, Profile::Srgb.convert_rgb(0xFF0000, Profile::DisplayP3));+ // a CMYK profile's colours are Display P3's+ let same = convert_color(0x12AB34, "Display P3".to_owned(), procraft_engine::cmyk::NAME.to_owned());+ assert!((same >> 16).abs_diff(0x12) <= 1 && ((same >> 8) & 0xFF).abs_diff(0xAB) <= 1, "{same:06x}");+ assert_eq!(convert_color(0x123456, "nothing".to_owned(), "Display P3".to_owned()), 0x123456);+ }+}diff --git a/apps/procraft-android/src/crop.rs b/apps/procraft-android/src/crop.rsnew file mode 100644index 0000000..5987925--- /dev/null+++ b/apps/procraft-android/src/crop.rs@@ -0,0 +1,244 @@+//! Cropping and resizing the canvas. The canvas is made again at its new size with every layer+//! resampled; the canvas from before is kept, history and all, and undoing past the new canvas's+//! first step puts it back.++use procraft_engine::crop::{crop, resample};+use procraft_engine::view::View;+use procraft_gpu::Canvas;++use crate::{CanvasSession, State};++/// How long the canvas takes to shrink into place as crop begins.+const CROP_SHRINK_SECONDS: f32 = 0.3;++impl State {+ /// Whether redoing would put an undone crop back: only while nothing new was done since.+ pub(crate) fn crop_redo_ready(&self) -> bool {+ match (&self.crop_redo, &self.canvas) {+ (Some((_, _, steps)), Some(c)) => !c.can_redo() && c.steps_made() == *steps,+ _ => false,+ }+ }+}++#[uniffi::export]+impl CanvasSession {+ /// Crops and resizes the canvas, as one undo step: keeps the rectangle `x, y, width, height`+ /// (canvas pixels; it may reach past the edges) turned by `angle` radians about its middle.+ /// With `resample`, what is kept is scaled to `new_width` × `new_height` pixels; otherwise the+ /// canvas is the rectangle's size. False if the canvas isn't shown yet.+ #[allow(clippy::too_many_arguments)]+ pub fn crop_canvas(+ &self,+ x: f32,+ y: f32,+ width: f32,+ height: f32,+ angle: f32,+ resample_to: bool,+ new_width: u32,+ new_height: u32,+ ) -> bool {+ self.text_end(true);+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.finish_stroke();+ st.settle();+ let (Some(old), Some(gpu)) = (st.canvas.as_mut(), st.gpu.as_ref()) else { return false };+ old.render(gpu, &mut st.doc, None);+ let (sw, sh) = (st.doc.width(), st.doc.height());+ let c = crop([x, y, width, height], angle, resample_to.then_some((new_width, new_height)));+ let doc = st.doc.resized(c.width, c.height);+ let mut layers = Vec::new();+ for id in st.doc.pixel_layer_ids() {+ match old.read_layer(gpu, id) {+ Ok(pixels) => layers.push((id, resample(&pixels, sw, sh, &c))),+ Err(e) => {+ log::error!("cropping: {e}");+ return false;+ }+ }+ }+ let mut canvas = match Canvas::new(gpu, &doc) {+ Ok(c) => c,+ Err(e) => {+ log::error!("cropping: {e}");+ return false;+ }+ };+ for (id, pixels) in &layers {+ let _ = canvas.upload_layer(gpu, *id, pixels);+ }+ let old_canvas = st.canvas.replace(canvas);+ let old_doc = std::mem::replace(&mut st.doc, doc);+ if let Some(old_canvas) = old_canvas {+ st.crop_undo = Some((old_canvas, old_doc));+ }+ st.crop_redo = None;+ st.selection = None;+ st.view = Some(st.fitted_view());+ st.reconfigure = true;+ st.revision += 1;+ self.shared.frame(st);+ true+ }+}++#[uniffi::export]+impl CanvasSession {+ /// The canvas's colour profile, by name.+ pub fn profile(&self) -> String {+ self.shared.lock().doc.profile_name()+ }++ /// Puts a canvas just made in the colour profile named `name` (nothing on it is moved). False+ /// if no profile has that name.+ pub fn set_new_profile(&self, name: String) -> bool {+ let Some((profile, icc)) = crate::colour::resolve(&name) else { return false };+ let mut st = self.shared.lock();+ st.doc.profile = profile;+ st.doc.icc = icc;+ self.shared.frame(&mut st);+ true+ }++ /// Puts the canvas in the colour profile named `name`, as one undo step: every layer's colours+ /// and the background are turned into it, so they look the same where it can show them. False+ /// if no profile has that name, the canvas is in it already or isn't shown yet.+ pub fn change_profile(&self, name: String) -> bool {+ let Some((to, icc)) = crate::colour::resolve(&name) else { return false };+ self.text_end(true);+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let from = st.doc.profile;+ if st.doc.profile_name() == name {+ return false;+ }+ // the pixels move between the RGB profiles they are in (a CMYK canvas's: Display P3)+ let mut next = procraft_engine::document::Document::new(1, 1);+ next.change_to(to, icc.clone());+ let (old_rgb, new_rgb) = (st.doc.rgb_profile(), next.rgb_profile());+ let table = (st.doc.icc.is_some() || icc.is_some())+ .then(|| (old_rgb != new_rgb).then(|| procraft_engine::cms::Lut::build(&old_rgb, &new_rgb, None, 33)))+ .flatten();+ st.finish_stroke();+ st.settle();+ st.flush();+ let ids: Vec<_> = st.doc.colour_layer_ids().collect();+ let (Some(canvas), Some(gpu)) = (st.canvas.as_mut(), st.gpu.as_ref()) else { return false };+ let mut layers = Vec::new();+ for id in ids {+ match canvas.read_layer(gpu, id) {+ Ok(mut pixels) => {+ match &table {+ Some(t) => t.apply_rgba(&mut pixels, true),+ None if icc.is_none() && st.doc.icc.is_none() => from.convert_pixels(&mut pixels, to),+ None => {}+ }+ layers.push((id, pixels));+ }+ Err(e) => {+ log::error!("changing the colour profile: {e}");+ return false;+ }+ }+ }+ let before = st.doc.clone();+ st.doc.change_to(to, icc);+ canvas.name_next_step(&format!("Set color profile \"{name}\""));+ canvas.write_layers_and_document(layers, before);+ st.revision += 1;+ self.shared.frame(st);+ true+ }++ /// The canvas's dots per inch (1 to 9999), as an undo step.+ pub fn set_dpi(&self, dpi: f32) -> bool {+ if !dpi.is_finite() {+ return false;+ }+ let dpi = dpi.clamp(1.0, 9999.0);+ self.change("DPI", |d| ((d.dpi - dpi).abs() > f32::EPSILON).then(|| d.dpi = dpi)).is_some()+ }++ /// Fits the whole canvas in the window, then shrinks it by `scale` (0.05 to 1) about the+ /// window's middle, as crop does so its frame's handles can be reached. The canvas shrinks+ /// into place over [`CROP_SHRINK_SECONDS`], slowing to a stop.+ pub fn fit_canvas_scaled(&self, scale: f32) {+ use procraft_engine::geom::{Affine, Vec2};+ let scale = if scale.is_finite() { scale.clamp(0.05, 1.0) } else { 1.0 };+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let (ww, wh) = st.window_size;+ let fit = View::fit((st.doc.width(), st.doc.height()), (ww, wh)).to_screen();+ let (cx, cy) = (ww as f32 / 2.0, wh as f32 / 2.0);+ let shrunk = fit+ .then(Affine::translate(Vec2::new(-cx, -cy)))+ .then(Affine::scale(scale))+ .then(Affine::translate(Vec2::new(cx, cy)));+ // shrinking into place, slowing to a stop+ let to = View::from_affine(shrunk);+ st.view_motion = st.view.map(|from| crate::ViewMotion {+ from,+ to,+ start: std::time::Instant::now(),+ curve: crate::ViewCurve::EaseOut(CROP_SHRINK_SECONDS),+ });+ if st.view_motion.is_none() {+ st.view = Some(to);+ }+ if let Some(c) = st.canvas.as_mut() {+ c.invalidate();+ }+ self.shared.frame(st);+ }+}++impl CanvasSession {+ /// Undo past the first step of a cropped canvas puts the canvas from before back; redo, while+ /// nothing new was done, crops again. False when there is no such step (the canvas's own+ /// history comes first).+ pub(crate) fn swap_crop(&self, undo: bool) -> bool {+ {+ // nothing to swap (or an adjustment open, whose undo is its own): leave it all be+ let st = self.shared.lock();+ if st.adjusting || (st.crop_undo.is_none() && st.crop_redo.is_none()) {+ return false;+ }+ }+ self.text_end(true);+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.finish_stroke();+ // queued work becomes steps first, so the counts are current+ st.settle();+ st.flush();+ if undo {+ if st.canvas.as_ref().is_none_or(Canvas::can_undo) {+ return false;+ }+ let Some((canvas, doc)) = st.crop_undo.take() else { return false };+ let cropped = st.canvas.replace(canvas);+ let cropped_doc = std::mem::replace(&mut st.doc, doc);+ let steps = st.canvas.as_ref().map_or(0, Canvas::steps_made);+ st.crop_redo = cropped.map(|c| (c, cropped_doc, steps));+ } else {+ if !st.crop_redo_ready() {+ return false;+ }+ let Some((canvas, doc, _)) = st.crop_redo.take() else { return false };+ let before = st.canvas.replace(canvas);+ let before_doc = std::mem::replace(&mut st.doc, doc);+ st.crop_undo = before.map(|c| (c, before_doc));+ }+ st.selection = None;+ st.view = Some(st.fitted_view());+ st.reconfigure = true;+ if let Some(c) = st.canvas.as_mut() {+ c.invalidate();+ }+ st.revision += 1;+ self.shared.frame(st);+ true+ }+}diff --git a/apps/procraft-android/src/guide.rs b/apps/procraft-android/src/guide.rsnew file mode 100644index 0000000..ede100c--- /dev/null+++ b/apps/procraft-android/src/guide.rs@@ -0,0 +1,311 @@+//! The drawing guide: set from the guide editor, drawn over the canvas as lines, and followed by+//! strokes with assisted drawing on (kept to the guide's directions, or mirrored by symmetry).++use procraft_engine::geom::{Affine, Vec2};+use procraft_engine::guide::{Guide, GuideKind, SymmetryKind, bar_color};+use procraft_engine::input::Sample;+use procraft_engine::stroke::Stamp;+use procraft_engine::view::View;++use crate::{CanvasSession, State};++#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]+pub enum GuideType {+ Grid,+ Isometric,+ Perspective,+ Symmetry,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]+pub enum SymmetryType {+ Vertical,+ Horizontal,+ Quadrant,+ Radial,+}++/// The guide as the editor and the overlay show it. Points are window pixels, x and y in turn;+/// `lines` are segments (two points each); `color` is sRGB 0..1.+#[derive(Clone, Debug, PartialEq, uniffi::Record)]+pub struct GuideInfo {+ pub on: bool,+ pub kind: GuideType,+ pub opacity: f32,+ pub thickness: f32,+ /// The grid's size, canvas pixels.+ pub size: f32,+ /// Where the colour sits on the colour bar (0..1), and the colour.+ pub hue: f32,+ pub color: Vec<f32>,+ pub symmetry: SymmetryType,+ pub rotational: bool,+ pub assisted: bool,+ pub centre: Vec<f32>,+ pub handle: Vec<f32>,+ pub vanishing: Vec<f32>,+ pub lines: Vec<f32>,+}++fn kind_of(t: GuideType) -> GuideKind {+ match t {+ GuideType::Grid => GuideKind::Grid,+ GuideType::Isometric => GuideKind::Isometric,+ GuideType::Perspective => GuideKind::Perspective,+ GuideType::Symmetry => GuideKind::Symmetry,+ }+}++fn type_of(k: GuideKind) -> GuideType {+ match k {+ GuideKind::Grid => GuideType::Grid,+ GuideKind::Isometric => GuideType::Isometric,+ GuideKind::Perspective => GuideType::Perspective,+ GuideKind::Symmetry => GuideType::Symmetry,+ }+}++/// `stamps` and the copies the guide's symmetry draws of them.+pub(crate) fn mirrored(guide: &Guide, stamps: &[Stamp]) -> Vec<Stamp> {+ let mut out = stamps.to_vec();+ for s in stamps {+ for (at, turn, mirror) in guide.copies(s.center) {+ let mut copy = *s;+ copy.center = at;+ if mirror {+ copy.angle = turn - s.angle;+ copy.flip = [!s.flip[0], s.flip[1]];+ } else {+ copy.angle = s.angle + turn;+ }+ out.push(copy);+ }+ }+ out+}++/// Vanishing points closer than this to the input (window pixels) are taken, not added.+const VANISHING_REACH: f32 = 30.0;++impl State {+ /// Stroke input kept to the guide when assisted drawing is on.+ pub(crate) fn assisted(&self, mut samples: Vec<Sample>) -> Vec<Sample> {+ if let Some(start) = self.assist_from {+ let forced = self.force_assist.then(|| {+ let mut g = self.doc.guide.clone();+ g.assisted = true;+ g+ });+ let guide = forced.as_ref().unwrap_or(&self.doc.guide);+ for s in &mut samples {+ s.pos = guide.assist(start, s.pos);+ }+ }+ samples+ }++ fn guide_info(&self) -> GuideInfo {+ let g = &self.doc.guide;+ let look = g.look();+ let to_screen = self.view.map_or(Affine::scale(1.0), |v| v.to_screen());+ let point = |p: Vec2| {+ let w = to_screen.apply(p);+ [w.x, w.y]+ };+ let c = Vec2::new(g.centre[0], g.centre[1]);+ // the turn handle sits up from the centre, at the canvas's top edge when level+ let up = Vec2::new(g.angle.sin(), -g.angle.cos()) * c.y.max(1.0);+ GuideInfo {+ on: g.on,+ kind: type_of(g.kind),+ opacity: look.opacity,+ thickness: look.thickness,+ size: look.size,+ hue: look.color,+ color: bar_color(look.color).to_vec(),+ symmetry: match g.symmetry {+ SymmetryKind::Vertical => SymmetryType::Vertical,+ SymmetryKind::Horizontal => SymmetryType::Horizontal,+ SymmetryKind::Quadrant => SymmetryType::Quadrant,+ SymmetryKind::Radial => SymmetryType::Radial,+ },+ rotational: g.rotational,+ assisted: g.assisted,+ centre: point(c).to_vec(),+ handle: point(c + up).to_vec(),+ vanishing: g.vanishing.iter().flat_map(|v| point(Vec2::new(v[0], v[1]))).collect(),+ lines: g+ .lines(self.doc.width(), self.doc.height())+ .into_iter()+ .flat_map(|(a, b)| point(a).into_iter().chain(point(b)))+ .collect(),+ }+ }++ fn to_canvas_point(&self, x: f32, y: f32) -> Option<Vec2> {+ self.view?.screen_to_canvas(Vec2::new(x, y)).filter(|p| p.is_finite())+ }+}++#[uniffi::export]+impl CanvasSession {+ pub fn guide(&self) -> GuideInfo {+ self.shared.lock().guide_info()+ }++ pub fn set_guide_on(&self, on: bool) -> GuideInfo {+ self.change_guide(|g| g.on = on)+ }++ pub fn set_guide_kind(&self, kind: GuideType) -> GuideInfo {+ self.change_guide(|g| g.kind = kind_of(kind))+ }++ /// The shown kind's opacity and thickness (0..1), grid size (canvas pixels) and colour (0..1+ /// along the colour bar).+ pub fn set_guide_look(&self, opacity: f32, thickness: f32, size: f32, hue: f32) -> GuideInfo {+ self.change_guide(|g| {+ let k = g.kind as usize;+ if let Some(look) = g.looks.get_mut(k) {+ let unit = |v: f32, old: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { old };+ look.opacity = unit(opacity, look.opacity);+ look.thickness = unit(thickness, look.thickness);+ look.color = unit(hue, look.color);+ if size.is_finite() {+ look.size = size.clamp(4.0, 1000.0);+ }+ }+ })+ }++ pub fn set_guide_symmetry(&self, kind: SymmetryType, rotational: bool) -> GuideInfo {+ self.change_guide(|g| {+ g.symmetry = match kind {+ SymmetryType::Vertical => SymmetryKind::Vertical,+ SymmetryType::Horizontal => SymmetryKind::Horizontal,+ SymmetryType::Quadrant => SymmetryKind::Quadrant,+ SymmetryType::Radial => SymmetryKind::Radial,+ };+ g.rotational = rotational;+ })+ }++ /// Strokes from now on follow the drawing guide (if it is on) even where drawing assist is+ /// off, until this is turned off again: □ + Touch or □ + Pen set to assisted drawing.+ pub fn set_stroke_assist(&self, on: bool) {+ self.shared.lock().force_assist = on;+ }++ pub fn set_guide_assisted(&self, assisted: bool) -> GuideInfo {+ self.change_guide(|g| g.assisted = assisted)+ }++ /// The guide's centre dragged to window point (`x`, `y`).+ pub fn move_guide_centre(&self, x: f32, y: f32) -> GuideInfo {+ let to = self.shared.lock().to_canvas_point(x, y);+ self.change_guide(|g| {+ if let Some(p) = to {+ g.centre = [p.x, p.y];+ }+ })+ }++ /// The guide's turn handle dragged to window point (`x`, `y`): it turns about its centre.+ pub fn turn_guide(&self, x: f32, y: f32) -> GuideInfo {+ let to = self.shared.lock().to_canvas_point(x, y);+ self.change_guide(|g| {+ if let Some(p) = to {+ let d = p - Vec2::new(g.centre[0], g.centre[1]);+ if d.length() > 1.0 {+ g.angle = d.x.atan2(-d.y);+ }+ }+ })+ }++ /// Perspective: a tap at window point (`x`, `y`) adds a vanishing point (up to three); returns+ /// the index of the point there, to drag.+ pub fn touch_vanishing_point(&self, x: f32, y: f32) -> Option<u32> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let p = st.to_canvas_point(x, y)?;+ let to_screen = st.view?.to_screen();+ let near = st+ .doc+ .guide+ .vanishing+ .iter()+ .position(|v| to_screen.apply(Vec2::new(v[0], v[1])).distance(Vec2::new(x, y)) <= VANISHING_REACH);+ if let Some(i) = near {+ return Some(i as u32);+ }+ if st.doc.guide.vanishing.len() >= 3 {+ return None;+ }+ st.doc.guide.vanishing.push([p.x, p.y]);+ st.revision += 1;+ self.shared.frame(st);+ Some(st.doc.guide.vanishing.len() as u32 - 1)+ }++ pub fn move_vanishing_point(&self, index: u32, x: f32, y: f32) -> GuideInfo {+ let to = self.shared.lock().to_canvas_point(x, y);+ self.change_guide(|g| {+ if let (Some(p), Some(v)) = (to, g.vanishing.get_mut(index as usize)) {+ *v = [p.x, p.y];+ }+ })+ }++ pub fn remove_vanishing_point(&self, index: u32) -> GuideInfo {+ self.change_guide(|g| {+ if (index as usize) < g.vanishing.len() {+ g.vanishing.remove(index as usize);+ }+ })+ }++ /// Opens the guide editor: the guide as it was is kept to go back to, and the canvas fits+ /// inside the window rectangle `left`..`right` × `top`..`bottom`.+ pub fn guide_edit_begin(&self, left: f32, top: f32, right: f32, bottom: f32) -> GuideInfo {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.finish_stroke();+ st.guide_before = Some((st.doc.guide.clone(), st.view));+ if st.doc.guide.centre == [0.0, 0.0] {+ st.doc.guide.centre = [st.doc.width() as f32 / 2.0, st.doc.height() as f32 / 2.0];+ }+ let size = ((right - left).max(1.0) as u32, (bottom - top).max(1.0) as u32);+ let fitted = View::fit((st.doc.width(), st.doc.height()), size);+ st.view = Some(View::from_affine(fitted.to_screen().then(Affine::translate(Vec2::new(left, top)))));+ self.shared.frame(st);+ st.guide_info()+ }++ /// Closes the guide editor: `keep` keeps the changes, otherwise the guide goes back. The view+ /// goes back as it was either way.+ pub fn guide_edit_end(&self, keep: bool) -> GuideInfo {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ if let Some((guide, view)) = st.guide_before.take() {+ if !keep {+ st.doc.guide = guide;+ }+ st.view = view;+ }+ st.revision += 1;+ self.shared.frame(st);+ st.guide_info()+ }+}++impl CanvasSession {+ fn change_guide(&self, f: impl FnOnce(&mut Guide)) -> GuideInfo {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ f(&mut st.doc.guide);+ st.revision += 1;+ self.shared.frame(st);+ st.guide_info()+ }+}diff --git a/apps/procraft-android/src/layer_ops.rs b/apps/procraft-android/src/layer_ops.rsnew file mode 100644index 0000000..ace7d3e--- /dev/null+++ b/apps/procraft-android/src/layer_ops.rs@@ -0,0 +1,118 @@+//! A layer's own actions from its options: selecting what is on it, copying it, filling it with the+//! colour, inverting it, and making it the reference layer.++use procraft_engine::document::LayerId;+use procraft_engine::selection::Mask;++use crate::layers::ThumbnailImage;+use crate::{CanvasSession, State};++impl State {+ /// A layer's pixels, everything queued drawn first.+ fn layer_pixels(&mut self, id: LayerId) -> Option<Vec<u8>> {+ self.finish_stroke();+ self.settle();+ self.flush();+ let (Some(canvas), Some(gpu)) = (self.canvas.as_mut(), self.gpu.as_ref()) else { return None };+ canvas.read_layer(gpu, id).ok()+ }++ /// Replaces an unlocked layer's pixels as one undo step.+ fn rewrite_layer(&mut self, id: LayerId, pixels: Vec<u8>) {+ if let Some(canvas) = self.canvas.as_mut() {+ canvas.write_layer(id, pixels);+ }+ self.revision += 1;+ }+}++#[uniffi::export]+impl CanvasSession {+ /// Selects what is on layer `id` (by its coverage), as one undo step.+ pub fn select_layer_contents(&self, id: u64) -> bool {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let Some(pixels) = st.layer_pixels(LayerId(id)) else { return false };+ let (w, h) = (st.doc.width(), st.doc.height());+ let mut mask = Mask::empty(w, h);+ for (m, px) in mask.data.iter_mut().zip(pixels.as_chunks::<4>().0) {+ *m = px[3];+ }+ let before = st.selection.take();+ st.selection = Some(mask);+ st.record_selection(before, "select layer contents");+ self.shared.frame(st);+ true+ }++ /// Layer `id`'s pixels, to paste later.+ pub fn copy_layer_contents(&self, id: u64) -> Option<ThumbnailImage> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let rgba = st.layer_pixels(LayerId(id))?;+ Some(ThumbnailImage { width: st.doc.width(), height: st.doc.height(), rgba })+ }++ /// Fills layer `id` with the colour, within the selection if there is one (only where it+ /// already has paint when alpha-locked), as one undo step.+ pub fn fill_layer(&self, id: u64) -> bool {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let id = LayerId(id);+ let Some(layer) = st.doc.layer(id).cloned() else { return false };+ if layer.locked || layer.text.is_some() {+ return false;+ }+ let Some(mut pixels) = st.layer_pixels(id) else { return false };+ let [r, g, b] = st.color.map(|c| (c.clamp(0.0, 1.0) * 255.0).round());+ let mask = st.selection.clone();+ for (i, px) in pixels.as_chunks_mut::<4>().0.iter_mut().enumerate() {+ let k = mask.as_ref().map_or(1.0, |m| f32::from(m.data.get(i).copied().unwrap_or(0)) / 255.0);+ // the colour over what is there, as much as the selection takes; alpha-locked, only+ // as much as is there+ let a = if layer.alpha_lock { f32::from(px[3]) / 255.0 } else { 1.0 };+ let fill = [r * a, g * a, b * a, a * 255.0];+ for (c, f) in px.iter_mut().zip(fill) {+ *c = (f32::from(*c) + (f - f32::from(*c)) * k).round().clamp(0.0, 255.0) as u8;+ }+ }+ st.rewrite_layer(id, pixels);+ self.shared.frame(st);+ true+ }++ /// Inverts layer `id`'s colours (its coverage kept), as one undo step.+ pub fn invert_layer(&self, id: u64) -> bool {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let id = LayerId(id);+ if st.doc.layer(id).is_none_or(|l| l.locked || l.text.is_some()) {+ return false;+ }+ let Some(mut pixels) = st.layer_pixels(id) else { return false };+ for px in pixels.as_chunks_mut::<4>().0 {+ let a = px[3];+ for c in px.iter_mut().take(3) {+ *c = a.saturating_sub(*c);+ }+ }+ st.rewrite_layer(id, pixels);+ self.shared.frame(st);+ true+ }++ /// Makes layer `id` the reference layer, or (not `on`) leaves none.+ pub fn set_layer_reference(&self, id: u64, on: bool) -> bool {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let before = st.doc.clone();+ if !st.doc.set_reference(LayerId(id), on) {+ return false;+ }+ if let Some(canvas) = st.canvas.as_mut() {+ canvas.record_document(before);+ }+ st.revision += 1;+ true+ }+}diff --git a/apps/procraft-android/src/layers.rs b/apps/procraft-android/src/layers.rsnew file mode 100644index 0000000..6a66526--- /dev/null+++ b/apps/procraft-android/src/layers.rs@@ -0,0 +1,566 @@+//! Layers: the list the layers panel shows and every change to it, each one undoable. A slider+//! drag (opacity, background colour) is one undo step from where it began to `done`.++use procraft_engine::document::{BlendMode, Document, LayerId, LayerKind};++use crate::CanvasSession;++#[derive(Clone, Debug, PartialEq, uniffi::Record)]+pub struct LayerInfo {+ pub id: u64,+ pub name: String,+ pub visible: bool,+ pub opacity: f32,+ /// A blend mode id (see [`blend_modes`]).+ pub blend: u32,+ pub alpha_lock: bool,+ pub clipped: bool,+ pub locked: bool,+ pub current: bool,+ /// Picked to act on together with the current layer.+ pub picked: bool,+ pub reference: bool,+ pub kind: LayerType,+ /// A mask's layer, or the group a layer is in.+ pub parent: Option<u64>,+ /// A group shown closed.+ pub collapsed: bool,+ /// A text layer, its text still editable.+ pub text: bool,+ /// How many groups it is inside.+ pub depth: u32,+ /// Whether Merge Down, Combine Down and Clipping Mask apply to it.+ pub can_merge: bool,+ pub can_combine: bool,+ pub can_clip: bool,+}++/// What a layer in the list is.+#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]+pub enum LayerType {+ Paint,+ Group,+ Mask,+}++#[derive(Clone, Debug, PartialEq, uniffi::Record)]+pub struct BlendModeInfo {+ pub id: u32,+ pub name: String,+}++#[derive(Clone, Debug, PartialEq, uniffi::Record)]+pub struct BackgroundInfo {+ pub r: f32,+ pub g: f32,+ pub b: f32,+ pub visible: bool,+}++/// A small premultiplied RGBA image, rows top to bottom.+#[derive(Clone, Debug, PartialEq, uniffi::Record)]+pub struct ThumbnailImage {+ pub width: u32,+ pub height: u32,+ pub rgba: Vec<u8>,+}++/// The memory layers may take on this device, bytes: it sets how many layers a canvas holds.+#[uniffi::export]+pub fn set_layer_budget(bytes: u64) {+ procraft_engine::document::set_layer_budget(bytes);+}++/// How many layers a canvas holds, has, and of which kinds.+#[derive(uniffi::Record)]+pub struct LayerStats {+ /// Layers with pixels (paint layers and masks) the canvas can hold.+ pub maximum: u32,+ /// Layers with pixels it has.+ pub used: u32,+ pub clipping: u32,+ pub masks: u32,+ pub groups: u32,+}++/// The sRGB colour profile (ICC), as palette files carry it with their colours.+#[uniffi::export]+pub fn srgb_profile() -> Vec<u8> {+ procraft_engine::icc::icc(procraft_engine::profile::Profile::Srgb)+}++/// The layer blend modes in the order the panel lists them.+#[uniffi::export]+pub fn blend_modes() -> Vec<BlendModeInfo> {+ BlendMode::ALL.iter().map(|m| BlendModeInfo { id: m.id(), name: m.name().to_owned() }).collect()+}++#[uniffi::export]+impl CanvasSession {+ /// The visible paint layers with something drawn under window point (`x`, `y`), top first.+ pub fn layers_at(&self, x: f32, y: f32) -> Vec<u64> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let Some(p) = st.view.and_then(|v| v.screen_to_canvas(procraft_engine::geom::Vec2::new(x, y))) else {+ return Vec::new();+ };+ if p.x < 0.0 || p.y < 0.0 {+ return Vec::new();+ }+ let (Some(canvas), Some(gpu)) = (st.canvas.as_mut(), st.gpu.as_ref()) else { return Vec::new() };+ let Ok(alphas) = canvas.alphas_at(gpu, &mut st.doc, p.x as u32, p.y as u32) else { return Vec::new() };+ let doc = &st.doc;+ alphas+ .into_iter()+ .rev()+ .filter(|(id, a)| *a >= 26 && doc.layer(*id).is_some_and(|l| l.visible))+ .map(|(id, _)| id.0)+ .collect()+ }++ pub fn layer_stats(&self) -> LayerStats {+ let st = self.shared.lock();+ let d = &st.doc;+ let count = |n: usize| u32::try_from(n).unwrap_or(u32::MAX);+ let kind = |k: LayerKind| count(d.layers().iter().filter(|l| l.kind == k).count());+ LayerStats {+ maximum: count(d.layer_cap()),+ used: count(d.pixel_layer_ids().count()),+ clipping: count(d.layers().iter().filter(|l| l.clipped).count()),+ masks: kind(LayerKind::Mask),+ groups: kind(LayerKind::Group),+ }+ }++ /// Top layer first, as the panel lists them.+ pub fn layers(&self) -> Vec<LayerInfo> {+ let st = self.shared.lock();+ let current = st.doc.current();+ st.doc+ .layers()+ .iter()+ .rev()+ .map(|l| LayerInfo {+ id: l.id.0,+ name: l.name.clone(),+ visible: l.visible,+ opacity: l.opacity,+ blend: l.blend.id(),+ alpha_lock: l.alpha_lock,+ clipped: l.clipped,+ locked: l.locked,+ current: l.id == current,+ picked: st.doc.is_picked(l.id),+ reference: l.reference,+ kind: match l.kind {+ LayerKind::Paint => LayerType::Paint,+ LayerKind::Group => LayerType::Group,+ LayerKind::Mask => LayerType::Mask,+ },+ parent: match l.kind {+ LayerKind::Mask => l.parent.map(|p| p.0),+ _ => st.doc.group_of(l.id).map(|g| g.0),+ },+ collapsed: l.collapsed,+ text: l.text.is_some(),+ depth: u32::try_from(st.doc.depth(l.id)).unwrap_or(u32::MAX),+ can_merge: st.doc.merge_target(l.id).is_some(),+ can_combine: l.kind != LayerKind::Mask && st.doc.below(l.id).is_some(),+ can_clip: st.doc.can_clip(l.id),+ })+ .collect()+ }++ pub fn background(&self) -> BackgroundInfo {+ let st = self.shared.lock();+ let [r, g, b] = st.doc.background;+ BackgroundInfo { r, g, b, visible: st.doc.background_visible }+ }++ /// A new empty layer above the current one; it becomes current.+ /// A new empty layer above the current one, made current; 0 when the canvas has no room for+ /// another (see [`Document::layer_cap`]).+ pub fn add_layer(&self) -> u64 {+ self.change("new layer", |d| d.has_room(1).then(|| d.add_layer().0)).unwrap_or(0)+ }++ /// Makes `id` the layer painting goes to, and the only one chosen (no picks): an undo step,+ /// unless nothing changes.+ pub fn select_layer(&self, id: u64) -> bool {+ let id = LayerId(id);+ {+ let st = self.shared.lock();+ if st.doc.current() == id && st.doc.picked().is_empty() {+ return st.doc.layer(id).is_some();+ }+ }+ let ok = self+ .change("select layer", |d| {+ d.clear_picks();+ d.set_current(id).then_some(())+ })+ .is_some();+ // the onion skins follow the current frame+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ if ok+ && st.doc.animation.is_some()+ && let Some(c) = st.canvas.as_mut()+ {+ c.invalidate();+ self.shared.frame(st);+ }+ ok+ }++ /// Picks layer `id` to act on with the current one, or unpicks it: an undo step.+ pub fn pick_layer(&self, id: u64) -> bool {+ self.change("pick layer", |d| d.toggle_pick(LayerId(id)).then_some(())).is_some()+ }++ /// Picks every layer: an undo step.+ pub fn pick_all_layers(&self) -> bool {+ self.change("select all layers", |d| d.pick_all().then_some(())).is_some()+ }++ /// The current and picked layers, bottom first.+ pub fn chosen_layers(&self) -> Vec<u64> {+ self.shared.lock().doc.chosen().iter().map(|l| l.0).collect()+ }++ /// Puts the current and picked layers in a new group where the top of them was; returns the+ /// group, or 0.+ pub fn group_picked(&self) -> u64 {+ self.change("group layers", |d| d.group_chosen().map(|g| g.0)).unwrap_or(0)+ }++ /// Copies of the current and picked layers, together above the top of them; the copies are+ /// what is chosen then. False if there is no room for them.+ pub fn duplicate_picked(&self) -> bool {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.finish_stroke();+ st.settle();+ let before = st.doc.clone();+ let mut trial = st.doc.clone();+ let Some(pairs) = trial.duplicate_chosen() else { return false };+ if !st.doc.has_room(pairs.len()) {+ return false;+ }+ st.doc = trial;+ if let Some(canvas) = st.canvas.as_mut() {+ canvas.name_next_step("duplicate layers");+ canvas.duplicate_layers(pairs, before);+ }+ st.revision += 1;+ self.shared.frame(st);+ true+ }++ /// Removes the current and picked layers that aren't locked (the last layer stays).+ pub fn delete_picked(&self) -> bool {+ self.change("delete layers", |d| d.delete_chosen().then_some(())).is_some()+ }++ /// Merges the picked layers above the bottom one of what is chosen into it.+ pub fn merge_picked(&self) -> bool {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.finish_stroke();+ st.settle();+ let Some((lower, uppers)) = st.doc.merge_chosen_plan() else { return false };+ let before = st.doc.clone();+ if let Some(canvas) = st.canvas.as_mut() {+ canvas.name_next_step("merge layers");+ canvas.merge_layers(uppers.clone(), lower, before);+ }+ st.doc.finish_merge_chosen(lower, &uppers);+ st.revision += 1;+ self.shared.frame(st);+ true+ }++ pub fn delete_layer(&self, id: u64) -> bool {+ self.change("delete layer", |d| {+ let unlocked = d.layer(LayerId(id)).is_some_and(|l| !l.locked);+ (unlocked && d.delete_layer(LayerId(id))).then_some(())+ })+ .is_some()+ }++ /// A copy just above `id` (a layer with its mask, a group with everything in it), made+ /// current; returns its id.+ pub fn duplicate_layer(&self, id: u64) -> Option<u64> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.finish_stroke();+ st.settle();+ let before = st.doc.clone();+ let unit = st.doc.layer(LayerId(id)).map_or(0, |_| {+ st.doc+ .pixel_layer_ids()+ .filter(|&l| {+ l == LayerId(id) || st.doc.is_inside(l, LayerId(id)) || st.doc.mask_of(LayerId(id)) == Some(l)+ })+ .count()+ });+ if !st.doc.has_room(unit) {+ return None;+ }+ let (copy, pairs) = st.doc.duplicate(LayerId(id))?;+ if let Some(canvas) = st.canvas.as_mut() {+ canvas.name_next_step("duplicate layer");+ canvas.duplicate_layers(pairs, before);+ }+ st.revision += 1;+ self.shared.frame(st);+ Some(copy.0)+ }++ /// Gives paint layer `id` a mask (white: showing all of it), made current; returns its id.+ pub fn add_mask(&self, id: u64) -> Option<u64> {+ let mask = self.change("mask", |d| if d.has_room(1) { d.add_mask(LayerId(id)) } else { None })?;+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let white = vec![255u8; st.doc.width() as usize * st.doc.height() as usize * 4];+ if let (Some(canvas), Some(gpu)) = (st.canvas.as_mut(), st.gpu.as_ref()) {+ let _ = canvas.upload_layer(gpu, mask, &white);+ }+ self.shared.frame(st);+ Some(mask.0)+ }++ /// Puts layer or group `id` and what is below it in a new group, or into the group below;+ /// returns the group's id.+ pub fn combine_down(&self, id: u64) -> Option<u64> {+ self.change("combine down", |d| d.combine_down(LayerId(id))).map(|g| g.0)+ }++ /// Takes the layers out of group `id` and removes it.+ pub fn ungroup(&self, id: u64) -> bool {+ self.change("ungroup", |d| d.ungroup(LayerId(id)).then_some(())).is_some()+ }++ /// Replaces group `id` with one layer showing the same; returns the layer's id.+ pub fn flatten_group(&self, id: u64) -> Option<u64> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.finish_stroke();+ st.settle();+ let before = st.doc.clone();+ let layer = st.doc.flatten(LayerId(id))?;+ if let Some(canvas) = st.canvas.as_mut() {+ canvas.flatten_group(LayerId(id), layer, false, before);+ }+ st.revision += 1;+ self.shared.frame(st);+ Some(layer.0)+ }++ /// Opens or closes a group in the list (not an undo step).+ pub fn set_group_collapsed(&self, id: u64, collapsed: bool) -> bool {+ let mut st = self.shared.lock();+ let ok = st.doc.set_collapsed(LayerId(id), collapsed);+ if ok {+ st.revision += 1;+ }+ ok+ }++ /// Moves layer or group `id` (with its mask, or everything in it) to `position`, counted from+ /// the bottom without them. Landing in a group, it joins it.+ pub fn move_layer(&self, id: u64, position: u32) -> bool {+ self.change("move layer", |d| {+ let to = usize::try_from(position).unwrap_or(usize::MAX);+ let before = d.layers().to_vec();+ (d.move_layer(LayerId(id), to) && d.layers() != before.as_slice()).then_some(())+ })+ .is_some()+ }++ /// Moves the current and picked layers together to `position` of the stack without them+ /// (0 = bottom), as [`CanvasSession::move_layer`] moves one.+ pub fn move_chosen(&self, position: u32) -> bool {+ self.change("move layers", |d| {+ let to = usize::try_from(position).unwrap_or(usize::MAX);+ let before = d.layers().to_vec();+ (d.move_chosen(to) && d.layers() != before.as_slice()).then_some(())+ })+ .is_some()+ }++ /// Blends layer or group `id` into the layer below and removes it.+ pub fn merge_down(&self, id: u64) -> bool {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.finish_stroke();+ st.settle();+ let upper = LayerId(id);+ let Some(lower) = st.doc.merge_target(upper) else { return false };+ if [upper, lower].iter().any(|l| st.doc.layer(*l).is_none_or(|l| l.locked)) {+ return false;+ }+ let before = st.doc.clone();+ let group = st.doc.layer(upper).is_some_and(|l| l.kind == LayerKind::Group);+ if let Some(canvas) = st.canvas.as_mut() {+ if group {+ canvas.flatten_group(upper, lower, true, before);+ } else {+ canvas.name_next_step("merge down");+ canvas.merge_down(upper, lower, before);+ }+ }+ st.doc.finish_merge_down(upper);+ st.revision += 1;+ self.shared.frame(st);+ true+ }++ pub fn set_layer_visible(&self, id: u64, visible: bool) -> bool {+ self.change(if visible { "show layer" } else { "hide layer" }, |d| {+ changed(d, id, |l| l.visible != visible)+ .then(|| d.set_visible(LayerId(id), visible))+ .filter(|ok| *ok)+ .map(|_| ())+ })+ .is_some()+ }++ /// Opacity 0..1; `done` ends the drag (one undo step for the whole drag).+ pub fn set_layer_opacity(&self, id: u64, opacity: f32, done: bool) -> bool {+ self.change_live("layer opacity", done, |d| d.set_opacity(LayerId(id), opacity))+ }++ /// `blend` is a blend mode id (see [`blend_modes`]).+ pub fn set_layer_blend(&self, id: u64, blend: u32) -> bool {+ let Some(mode) = BlendMode::from_id(blend) else { return false };+ self.change("blend mode", |d| {+ changed(d, id, |l| l.blend != mode).then(|| d.set_blend(LayerId(id), mode)).filter(|ok| *ok).map(|_| ())+ })+ .is_some()+ }++ pub fn set_layer_alpha_lock(&self, id: u64, on: bool) -> bool {+ self.change("alpha lock", |d| {+ changed(d, id, |l| l.alpha_lock != on)+ .then(|| d.set_alpha_lock(LayerId(id), on))+ .filter(|ok| *ok)+ .map(|_| ())+ })+ .is_some()+ }++ pub fn set_layer_clipped(&self, id: u64, on: bool) -> bool {+ self.change(if on { "clip layer" } else { "unclip layer" }, |d| {+ changed(d, id, |l| l.clipped != on).then(|| d.set_clipped(LayerId(id), on)).filter(|ok| *ok).map(|_| ())+ })+ .is_some()+ }++ pub fn set_layer_locked(&self, id: u64, on: bool) -> bool {+ self.change(if on { "lock layer" } else { "unlock layer" }, |d| {+ changed(d, id, |l| l.locked != on).then(|| d.set_locked(LayerId(id), on)).filter(|ok| *ok).map(|_| ())+ })+ .is_some()+ }++ pub fn rename_layer(&self, id: u64, name: String) -> bool {+ self.change("rename layer", |d| {+ changed(d, id, |l| l.name != name.trim()).then(|| d.rename(LayerId(id), &name)).filter(|ok| *ok).map(|_| ())+ })+ .is_some()+ }++ /// Background colour, sRGB 0..1; `done` ends the drag.+ pub fn set_background_color(&self, r: f32, g: f32, b: f32, done: bool) -> bool {+ let c = [r, g, b];+ if c.iter().any(|v| !v.is_finite()) {+ return false;+ }+ self.change_live("change background color", done, |d| {+ d.background = c.map(|v| v.clamp(0.0, 1.0));+ true+ })+ }++ pub fn set_background_visible(&self, visible: bool) -> bool {+ self.change(if visible { "show background" } else { "hide background" }, |d| {+ (d.background_visible != visible).then(|| {+ d.background_visible = visible;+ })+ })+ .is_some()+ }++ /// The whole picture scaled to fit `max_side` pixels (premultiplied), for the reference+ /// window; none before the canvas exists.+ pub fn canvas_thumbnail(&self, max_side: u32) -> Option<ThumbnailImage> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let (Some(canvas), Some(gpu)) = (st.canvas.as_mut(), st.gpu.as_ref()) else { return None };+ let t = canvas.composite_thumbnail(gpu, &mut st.doc, max_side).ok()?;+ Some(ThumbnailImage { width: t.width, height: t.height, rgba: t.rgba })+ }++ /// The layer scaled to fit `max_side` pixels, or none before the canvas exists.+ pub fn layer_thumbnail(&self, id: u64, max_side: u32) -> Option<ThumbnailImage> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let (Some(canvas), Some(gpu)) = (st.canvas.as_mut(), st.gpu.as_ref()) else { return None };+ match canvas.layer_thumbnail(gpu, &mut st.doc, LayerId(id), max_side) {+ Ok(t) => Some(ThumbnailImage { width: t.width, height: t.height, rgba: t.rgba }),+ Err(e) => {+ log::warn!("thumbnail: {e}");+ None+ }+ }+ }+}++/// Whether layer `id` exists and `differs` holds for it.+fn changed(d: &Document, id: u64, differs: impl FnOnce(&procraft_engine::document::Layer) -> bool) -> bool {+ d.layer(LayerId(id)).is_some_and(differs)+}++impl CanvasSession {+ /// An undoable change to the document, called `name` by undo and redo; `f` returns `Some`+ /// when it changed something (and must leave the document alone otherwise).+ pub(crate) fn change<T>(&self, name: &str, f: impl FnOnce(&mut Document) -> Option<T>) -> Option<T> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.finish_stroke();+ st.settle();+ let before = st.doc.clone();+ let out = f(&mut st.doc)?;+ if let Some(canvas) = st.canvas.as_mut() {+ canvas.name_next_step(name);+ canvas.record_document(before);+ }+ st.revision += 1;+ self.shared.frame(st);+ Some(out)+ }++ /// A change made continuously, called `name` by undo and redo: shown at once, recorded as one+ /// step when `done`.+ fn change_live(&self, name: &str, done: bool, f: impl FnOnce(&mut Document) -> bool) -> bool {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.finish_stroke();+ let before = st.doc.clone();+ if !f(&mut st.doc) {+ return false;+ }+ st.pending_doc.get_or_insert(before);+ st.pending_name = Some(name.to_owned());+ if let Some(canvas) = st.canvas.as_mut() {+ canvas.invalidate();+ }+ if done {+ st.settle();+ }+ st.revision += 1;+ self.shared.frame(st);+ true+ }+}diff --git a/apps/procraft-android/src/lib.rs b/apps/procraft-android/src/lib.rsnew file mode 100644index 0000000..deb2703--- /dev/null+++ b/apps/procraft-android/src/lib.rs@@ -0,0 +1,1126 @@+//! ProCraft's native library for Android: a [`CanvasSession`] (UniFFI) that takes input from the+//! Kotlin UI, builds strokes with the engine and draws them with the GPU renderer on its own+//! render thread, straight into the app's `SurfaceView`.+//!+//! The window crosses over through two small JNI functions (`window.rs`, the crate's only unsafe+//! code): Kotlin hands its `Surface` to `NativeWindows.acquire` and passes the id it returns to+//! [`CanvasSession::attach_window`].++uniffi::setup_scaffolding!();++mod adjust;+mod animation;+mod brush_files;+mod brush_library;+mod brushes;+mod clipboard;+mod colour;+mod crop;+mod guide;+mod layer_ops;+mod layers;+mod pick;+mod project;+mod projection;+mod quickshape;+#[cfg(target_os = "android")]+mod render;+mod selection;+mod studio;+#[cfg(test)]+mod tests;+mod text;+mod transform;+#[cfg(target_os = "android")]+mod window;++use std::collections::HashMap;+use std::sync::{Arc, Condvar, Mutex, MutexGuard};+use std::thread::JoinHandle;++use procraft_engine::brush::Brush;+use procraft_engine::document::Document;+use procraft_engine::geom::Vec2;+use procraft_engine::input::{Pointer, Sample};+use procraft_engine::library::{BrushSet, library};+use procraft_engine::stroke::StrokeBuilder;+use procraft_engine::view::View;+use procraft_gpu::{Canvas, Gpu, StrokeStyle, StrokeTool};++/// Colour around the canvas, sRGB.+#[cfg_attr(not(target_os = "android"), allow(dead_code))]+pub(crate) const SURROUND: [f32; 3] = [37.0 / 255.0, 37.0 / 255.0, 37.0 / 255.0];++/// The grid over the surround: its line colour (sRGB), and its spacing, line width and top (the+/// bar's height), in interface points.+#[cfg_attr(not(target_os = "android"), allow(dead_code))]+pub(crate) const GRID_LINE: [f32; 3] = [40.0 / 255.0, 40.0 / 255.0, 40.0 / 255.0];+#[cfg_attr(not(target_os = "android"), allow(dead_code))]+pub(crate) const GRID_SPACING_PT: f32 = 16.0;+#[cfg_attr(not(target_os = "android"), allow(dead_code))]+pub(crate) const GRID_TOP_PT: f32 = 44.0;++/// The bands over what is not selected: their period across the window and drift (points, points+/// a second, so a period a second), and their coverage.+#[cfg_attr(not(target_os = "android"), allow(dead_code))]+pub(crate) const STRIPE_PERIOD_PT: f32 = 10.0;+#[cfg_attr(not(target_os = "android"), allow(dead_code))]+pub(crate) const STRIPE_SPEED_PT: f32 = 10.0;+#[cfg_attr(not(target_os = "android"), allow(dead_code))]+/// How far what is behind a frosted panel is blurred (Gaussian sigma, points).+pub(crate) const BACKDROP_SIGMA_PT: f32 = 23.5;+#[cfg_attr(not(target_os = "android"), allow(dead_code))]+/// How dark the bands over what is not selected are, at full selection mask visibility.+pub(crate) const STRIPE_COVERAGE: f32 = 0.25;+/// What is selected is multiplied by this while selecting by colour, and covered by the other+/// while the threshold is dragged (sRGB).+#[cfg_attr(not(target_os = "android"), allow(dead_code))]+pub(crate) const SELECTION_TINT: [f32; 3] = [1.0 / 255.0, 120.0 / 255.0, 1.0];+#[cfg_attr(not(target_os = "android"), allow(dead_code))]+pub(crate) const SELECTION_FILL: [f32; 3] = [50.0 / 255.0, 117.0 / 255.0, 247.0 / 255.0];++/// One input sample in window pixels.+#[derive(Clone, Copy, Debug, uniffi::Record)]+pub struct PenSample {+ pub x: f32,+ pub y: f32,+ /// 0..1 (ignored for fingers).+ pub pressure: f32,+ /// Radians from upright.+ pub tilt: f32,+ /// Radians, the direction the pen leans.+ pub orientation: f32,+ /// Milliseconds, the platform's event clock.+ pub time_ms: f64,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]+pub enum PointerKind {+ Finger,+ Stylus,+ StylusEraser,+ Mouse,+}++impl From<PointerKind> for Pointer {+ fn from(p: PointerKind) -> Pointer {+ match p {+ PointerKind::Finger => Pointer::Finger,+ PointerKind::Stylus => Pointer::Stylus,+ PointerKind::StylusEraser => Pointer::StylusEraser,+ PointerKind::Mouse => Pointer::Mouse,+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, uniffi::Enum)]+pub enum ToolKind {+ Paint,+ Erase,+ Smudge,+}++impl ToolKind {+ fn stroke_tool(self) -> StrokeTool {+ match self {+ ToolKind::Paint => StrokeTool::Paint,+ ToolKind::Erase => StrokeTool::Erase,+ ToolKind::Smudge => StrokeTool::Smudge,+ }+ }+}++#[derive(Clone, Debug, uniffi::Record)]+pub struct CanvasInfo {+ pub width: u32,+ pub height: u32,+ /// Dots per inch.+ pub dpi: f32,+ pub tool: ToolKind,+ /// The current tool's sliders, 0..1.+ pub size: f32,+ pub opacity: f32,+ /// The current tool's brush across at that size, canvas pixels.+ pub brush_diameter: f32,+ pub can_undo: bool,+ pub can_redo: bool,+ pub zoom: f32,+ /// Frames shown with the canvas drawn on them.+ pub frames: u64,+ /// Time between the last two frames, milliseconds.+ pub frame_interval_ms: f32,+ /// Why the canvas can't draw, if it can't.+ pub error: Option<String>,+ /// Changes whenever the layers or their settings change (also by undo and redo).+ pub revision: u64,+}++#[derive(Debug, thiserror::Error, uniffi::Error)]+pub enum MobileError {+ #[error("window: {reason}")]+ Window { reason: String },+ #[error("file: {reason}")]+ File { reason: String },+}++#[derive(Clone, Copy, Debug)]+struct Sliders {+ size: f32,+ opacity: f32,+}++/// A brush's sliders before they are first moved.+const DEFAULT_SLIDERS: Sliders = Sliders { size: 0.3, opacity: 1.0 };++/// How long the view takes to settle into place, and how much it gives on the way.+const VIEW_SETTLE_SECONDS: f32 = 0.5;+#[cfg_attr(not(target_os = "android"), allow(dead_code))]+const VIEW_SETTLE_DAMPING: f32 = 0.8;+/// How long the view takes to grow back to fit, slowing to a stop.+const VIEW_EASE_SECONDS: f32 = 0.3;++/// The view settling from `from` to `to`, begun at `start`, along `curve`.+#[derive(Clone, Copy)]+#[cfg_attr(not(target_os = "android"), allow(dead_code))]+pub(crate) struct ViewMotion {+ pub(crate) from: View,+ pub(crate) to: View,+ pub(crate) start: std::time::Instant,+ pub(crate) curve: ViewCurve,+}++/// How a view moves into place: settling on a spring (fitting), or slowing to a stop (crop).+#[derive(Clone, Copy)]+pub(crate) enum ViewCurve {+ Settle,+ EaseOut(f32),+}++impl ViewCurve {+ /// How far along it is `t` seconds in, and how long it takes.+ fn at(self, t: f32) -> (f32, f32) {+ match self {+ ViewCurve::Settle => {+ let spring = procraft_engine::motion::Spring::new(VIEW_SETTLE_SECONDS, VIEW_SETTLE_DAMPING);+ (spring.at(t), spring.seconds())+ }+ ViewCurve::EaseOut(seconds) => (procraft_engine::motion::Bezier::ease_out(seconds).at(t), seconds),+ }+ }+}++impl State {+ /// Moves the view on to where its settling has got by now; true while it is still moving.+ #[cfg_attr(not(target_os = "android"), allow(dead_code))]+ pub(crate) fn step_view_motion(&mut self) -> bool {+ let Some(m) = self.view_motion else { return false };+ let t = m.start.elapsed().as_secs_f32();+ let (along, seconds) = m.curve.at(t);+ let centre = Vec2::new(self.doc.width() as f32 / 2.0, self.doc.height() as f32 / 2.0);+ self.view = Some(View::between(&m.from, &m.to, centre, along));+ if t >= seconds {+ self.view_motion = None;+ return false;+ }+ true+ }+}++pub(crate) struct State {+ pub(crate) doc: Document,+ /// Fitted once the window's size is known.+ pub(crate) view: Option<View>,+ /// The view settling from one place to another (fitting the canvas), stepped each frame.+ pub(crate) view_motion: Option<ViewMotion>,+ pub(crate) window_size: (u32, u32),+ pub(crate) reconfigure: bool,+ tool: ToolKind,+ /// The app's own smoothing and pressure, on top of every brush's.+ pub(crate) input: procraft_engine::stroke::InputSettings,+ /// Selection mask visibility, 0..1: how strongly what is not selected is banded.+ pub(crate) selection_visibility: f32,+ /// Brush scaling relative to the screen: the brush keeps its size on the screen as the canvas+ /// zooms (else it keeps its size on the canvas).+ pub(crate) brush_on_screen: bool,+ /// Crops kept for undo: the canvas and document from before; and one undone, for redo, with+ /// the steps the canvas then put back had made (redo only while that hasn't changed).+ crop_undo: Option<(Canvas, Document)>,+ crop_redo: Option<(Canvas, Document, u64)>,+ /// The text layer being edited, and the document as the edit began.+ text_edit: Option<(procraft_engine::document::LayerId, Document)>,+ /// The library as the user has it, and as it ships.+ library: Vec<brush_library::LibrarySet>,+ shipped: Vec<BrushSet>,+ /// When the library is empty (never, but never panic).+ fallback: Brush,+ /// The brush each tool uses: (set, brush) in the library.+ paint_brush: (usize, usize),+ erase_brush: (usize, usize),+ smudge_brush: (usize, usize),+ /// Each set's last chosen brush, (set, brush) in the library, the latest choice last.+ set_choices: Vec<(usize, usize)>,+ /// Each brush's sliders, per tool.+ sliders: HashMap<(ToolKind, usize, usize), Sliders>,+ /// Strokes started, to seed each one's randomness.+ strokes: u32,+ /// The small canvas brush previews are drawn on.+ preview: Option<(Canvas, Document)>,+ color: [f32; 3],+ /// The secondary colour, for secondary colour dynamics.+ secondary: [f32; 3],+ stroke: Option<StrokeBuilder>,+ #[cfg_attr(not(any(target_os = "android", test)), allow(dead_code))]+ pub(crate) gpu: Option<Gpu>,+ pub(crate) canvas: Option<Canvas>,+ pub(crate) needs_frame: bool,+ pub(crate) stop: bool,+ /// Project canvas: the second display's size, and that its thread should end.+ #[cfg_attr(not(target_os = "android"), allow(dead_code))]+ pub(crate) projection_size: (u32, u32),+ pub(crate) projection_stop: bool,+ pub(crate) frames: u64,+ /// The drawing pad's strokes as drawn (pointer and input), drawn again when the brush changes;+ /// `None` on a canvas that keeps none.+ pub(crate) pad_strokes: Option<Vec<(PointerKind, Vec<PenSample>)>>,+ /// The pad shows only its sample scribble: a stroke of one's own takes it away.+ pub(crate) pad_sample: bool,+ pub(crate) frame_interval_ms: f32,+ pub(crate) error: Option<String>,+ /// Window pixels per interface point.+ pub(crate) display_scale: f32,+ /// The document before a continuous change (a slider drag) began.+ pending_doc: Option<Document>,+ /// What undo calls that change.+ pending_name: Option<String>,+ /// The artwork's title.+ pub(crate) name: String,+ /// What the artwork keeps about itself: when it was made, strokes, time spent, its author.+ pub(crate) info: project::ArtworkInfo,+ /// Saved layer pixels waiting for the canvas (an opened artwork before it is shown).+ pub(crate) pending_pixels: Vec<(procraft_engine::document::LayerId, Vec<u8>)>,+ /// What fitting the canvas keeps clear of (left, top, right, bottom, window pixels).+ fit_insets: [f32; 4],+ /// Frosted panels open over the canvas: left, top, right, bottom and corner radius (window+ /// pixels).+ #[cfg_attr(not(target_os = "android"), allow(dead_code))]+ pub(crate) backdrops: Vec<[f32; 6]>,+ /// The view kept with the artwork, shown when the window first comes.+ pub(crate) saved_view: Option<project::SavedView>,+ pub(crate) revision: u64,+ /// The open transform, how its handles act and how it resamples.+ transform: Option<procraft_engine::transform::Transform>,+ transform_mode: procraft_engine::transform::TransformMode,+ interpolation: transform::Interpolation,+ transform_guides: transform::GuideSettings,+ /// What is selected, if anything, and selections kept to load again.+ selection: Option<procraft_engine::selection::Mask>,+ saved_selections: Vec<procraft_engine::selection::Mask>,+ pub(crate) selection_display: selection::SelectionDisplay,+ /// The table showing a canvas with a profile of its own on the screen, and what it was made for.+ #[cfg(target_os = "android")]+ pub(crate) display_lut: Option<((usize, procraft_engine::profile::Profile), procraft_gpu::DisplayLut)>,+ /// While a colour selection's threshold is dragged: the selection before it, and the layer read once.+ selection_before: Option<Option<procraft_engine::selection::Mask>>,+ colour_source: Option<Vec<u8>>,+ /// An adjustment is open on the current layer, and what it last drew.+ adjusting: bool,+ last_filter: Option<procraft_gpu::Filter>,+ /// The liquify brush's last stamp (canvas pixels).+ liquify_last: Option<Vec2>,+ /// The brush studio is open on this (set, brush), and the brush as it opened.+ studio: Option<((usize, usize), Brush)>,+ /// The adjustment is painted on (Pencil); cloning, from where, and by how far once it starts.+ pencil: bool,+ cloning: bool,+ /// Leaving an adjustment makes the steps made in it (Pencil and clone strokes) one.+ simplified_undos: bool,+ /// The clone brush's sliders (it is the soft airbrush).+ clone_sliders: Sliders,+ clone_source: Option<Vec2>,+ clone_offset: Option<Vec2>,+ /// The selection before the feather popover softened it.+ feather_base: Option<procraft_engine::selection::Mask>,+ /// The last drag step on the box (window point, when), for its speed.+ last_drag: Option<(Vec2, std::time::Instant)>,+ /// The stroke being drawn as input (canvas points) and its pressures summed, for QuickShape,+ /// and the shape it snapped to while that is shown.+ drawn: Vec<Vec2>,+ drawn_pressure: f32,+ shape: Option<quickshape::ShapeEdit>,+ /// The open stroke as it began, and the last stroke kept, for QuickShape afterwards.+ began: Option<quickshape::LastStroke>,+ last_stroke: Option<quickshape::LastStroke>,+ /// Strokes follow the drawing guide even where drawing assist is off (□ held down).+ force_assist: bool,+ /// Where the stroke began (canvas pixels), for assisted drawing; the guide and view as the+ /// guide editor opened.+ assist_from: Option<Vec2>,+ guide_before: Option<(procraft_engine::guide::Guide, Option<View>)>,+}++impl State {+ /// The whole canvas fitted in the window, clear of the insets, turned by the right angle the+ /// view is nearest (fitting straightens a turned canvas, but keeps it on its side if it is).+ pub(crate) fn fitted_view(&self) -> View {+ let turns = self.view.map_or(0, |v| v.quarter_turns());+ View::fit_turned((self.doc.width(), self.doc.height()), self.window_size, self.fit_insets, turns)+ }++ /// Finishes an open stroke.+ fn finish_stroke(&mut self) {+ self.shape = None;+ if let (Some(open), Some(canvas)) = (self.stroke.take(), self.canvas.as_mut()) {+ close_stroke(canvas, open, &self.doc.guide);+ self.bake_painted_on();+ }+ }++ /// Ends a continuous change still open (a slider drag, a transform): it becomes one undo step.+ fn settle(&mut self) {+ self.end_transform(true);+ self.end_adjustment(true);+ let name = self.pending_name.take();+ if let (Some(before), Some(canvas)) = (self.pending_doc.take(), self.canvas.as_mut()) {+ if let Some(name) = name {+ canvas.name_next_step(&name);+ }+ canvas.record_document(before);+ }+ }++ /// Runs the queued canvas work now (without drawing), so the document already reflects an+ /// undo or redo when the call returns.+ fn flush(&mut self) {+ if let (Some(canvas), Some(gpu)) = (self.canvas.as_mut(), self.gpu.as_ref()) {+ canvas.render(gpu, &mut self.doc, None);+ }+ }++ /// The (set, brush) `tool` uses.+ fn brush_ref(&self, tool: ToolKind) -> (usize, usize) {+ match tool {+ ToolKind::Paint => self.paint_brush,+ ToolKind::Erase => self.erase_brush,+ ToolKind::Smudge => self.smudge_brush,+ }+ }++ /// What brush sizes are multiplied by: 1 relative to the canvas; relative to the screen, the+ /// canvas fitted to the window over the zoom now, so a brush looks the same size at any zoom.+ fn brush_scale(&self) -> f32 {+ if !self.brush_on_screen {+ return 1.0;+ }+ let fit = View::fit((self.doc.width(), self.doc.height()), self.window_size).zoom();+ let zoom = self.view.map_or(fit, |v| v.zoom());+ if zoom > 0.0 && fit.is_finite() { (fit / zoom).clamp(0.01, 100.0) } else { 1.0 }+ }++ fn brush(&self, tool: ToolKind) -> &Brush {+ let (set, index) = self.brush_ref(tool);+ self.library.get(set).and_then(|s| s.brushes.get(index)).unwrap_or(&self.fallback)+ }++ /// More input for the pad's last kept stroke, if it keeps them.+ fn keep_pad_input(&mut self, samples: &[PenSample]) {+ if let Some((_, input)) = self.pad_strokes.as_mut().and_then(|k| k.last_mut()) {+ input.extend_from_slice(samples);+ }+ }++ /// The tool's brush in the library, to change it (none if the tool has fallen back).+ fn brush_mut(&mut self, tool: ToolKind) -> Option<&mut Brush> {+ let (set, index) = self.brush_ref(tool);+ self.library.get_mut(set).and_then(|s| s.brushes.get_mut(index))+ }++ fn sliders(&self, tool: ToolKind) -> Sliders {+ let (set, index) = self.brush_ref(tool);+ self.sliders.get(&(tool, set, index)).copied().unwrap_or_else(|| self.starting_sliders(tool))+ }++ /// Where a brush's sliders start: at the size its preview shows it, full opacity.+ fn starting_sliders(&self, tool: ToolKind) -> Sliders {+ let curve = procraft_engine::brush::SIZE_CURVE;+ let size = self.brush(tool).setting("preview_size").clamp(0.0, 1.0).powf(1.0 / curve);+ Sliders { size, ..DEFAULT_SLIDERS }+ }++ /// The sliders the side bar shows: the clone brush's while cloning, the paint brush's while+ /// an adjustment is painted on, else the tool's.+ fn shown_sliders(&self) -> Sliders {+ if self.cloning {+ self.clone_sliders+ } else {+ self.sliders(if self.pencil { ToolKind::Paint } else { self.tool })+ }+ }++ fn sliders_mut(&mut self) -> &mut Sliders {+ if self.cloning {+ return &mut self.clone_sliders;+ }+ let tool = if self.pencil { ToolKind::Paint } else { self.tool };+ let (set, index) = self.brush_ref(tool);+ let start = self.starting_sliders(tool);+ self.sliders.entry((tool, set, index)).or_insert(start)+ }++ /// Creates the canvas once there is a GPU.+ #[cfg_attr(not(any(target_os = "android", test)), allow(dead_code))]+ pub(crate) fn ensure_canvas(&mut self) {+ if self.canvas.is_some() {+ return;+ }+ let Some(gpu) = self.gpu.as_ref() else { return };+ match Canvas::new(gpu, &self.doc) {+ Ok(mut c) => {+ for (id, pixels) in std::mem::take(&mut self.pending_pixels) {+ if let Err(e) = c.upload_layer(gpu, id, &pixels) {+ log::error!("opening a layer: {e}");+ }+ }+ self.canvas = Some(c);+ }+ Err(e) => {+ log::error!("canvas: {e}");+ self.error = Some(e.to_string());+ }+ }+ }++ /// Samples in canvas pixels.+ fn to_canvas(&self, samples: &[PenSample]) -> Vec<Sample> {+ let Some(inv) = self.view.and_then(|v| v.to_screen().inverse()) else { return Vec::new() };+ samples+ .iter()+ .map(|s| Sample {+ pos: inv.apply(Vec2::new(s.x, s.y)),+ pressure: s.pressure,+ tilt: s.tilt,+ azimuth: s.orientation,+ time_ms: s.time_ms,+ })+ .collect()+ }+}++/// Ends the canvas's open stroke with `builder`'s final stamps: a painted or erased stroke is+/// redrawn once in its final form (end taper); a smudge, which has already changed the layer, and+/// an adjustment painted on, which adds to its mask, only get the stamps not drawn yet.+fn close_stroke(canvas: &mut Canvas, mut builder: StrokeBuilder, guide: &procraft_engine::guide::Guide) {+ let drawn = builder.stamp_count();+ let all = builder.finish();+ // what undo calls it+ canvas.name_next_step(match canvas.stroke_tool() {+ Some(StrokeTool::Erase) => "Erase stroke",+ Some(StrokeTool::Smudge) => "Smudge stroke",+ _ if canvas.is_pencil() => "Filter stroke",+ _ => "Paint stroke",+ });+ if canvas.stroke_tool() == Some(StrokeTool::Smudge) || canvas.is_pencil() {+ canvas.add_stamps(&guide::mirrored(guide, all.get(drawn..).unwrap_or(&[])));+ } else {+ canvas.replace_stamps(&guide::mirrored(guide, &all));+ }+ canvas.end_stroke();+}++pub(crate) struct Shared {+ state: Mutex<State>,+ pub(crate) wake: Condvar,+ thread: Mutex<Option<JoinHandle<()>>>,+ /// Project canvas's render thread.+ projection: Mutex<Option<JoinHandle<()>>>,+ /// Held while the artwork is saved: one save at a time, so two never write the same files.+ pub(crate) saving: Mutex<project::Saved>,+}++impl Shared {+ pub(crate) fn lock(&self) -> MutexGuard<'_, State> {+ self.state.lock().unwrap_or_else(|e| e.into_inner())+ }++ fn frame(&self, st: &mut State) {+ st.needs_frame = true;+ self.wake.notify_all();+ }+}++/// A canvas being painted: the document, the brush, the input and the renderer.+#[derive(uniffi::Object)]+pub struct CanvasSession {+ pub(crate) shared: Arc<Shared>,+}++#[uniffi::export]+impl CanvasSession {+ /// A new artwork of `width` × `height` pixels.+ #[uniffi::constructor]+ pub fn new(width: u32, height: u32) -> Arc<CanvasSession> {+ CanvasSession::with_document(Document::new(width, height), DEFAULT_NAME.to_owned(), Vec::new())+ }+}++/// What a new artwork is called.+pub(crate) const DEFAULT_NAME: &str = "Untitled Artwork";++impl CanvasSession {+ /// A session on `doc`, with saved pixels for its layers.+ pub(crate) fn with_document(+ doc: Document,+ name: String,+ pixels: Vec<(procraft_engine::document::LayerId, Vec<u8>)>,+ ) -> Arc<CanvasSession> {+ #[cfg(target_os = "android")]+ android_logger::init_once(+ android_logger::Config::default().with_max_level(log::LevelFilter::Info).with_tag("procraft"),+ );+ let shipped = library();+ let shelf = brush_library::LibrarySet::shipped(&shipped);+ // the round pen to paint, the soft airbrush to erase, the round brush to smudge+ let [paint_brush, erase_brush, smudge_brush] =+ [(1, 0), (3, 0), (2, 0)].map(|origin| brush_library::place_of(&shelf, origin));+ let state = State {+ doc,+ view: None,+ view_motion: None,+ window_size: (1, 1),+ reconfigure: false,+ tool: ToolKind::Paint,+ text_edit: None,+ crop_undo: None,+ selection_visibility: 0.25,+ brush_on_screen: false,+ input: procraft_engine::stroke::InputSettings::default(),+ crop_redo: None,+ library: shelf,+ shipped,+ fallback: Brush::round_pen(),+ paint_brush,+ erase_brush,+ smudge_brush,+ set_choices: Vec::new(),+ sliders: HashMap::new(),+ strokes: 0,+ preview: None,+ color: [0.0, 0.0, 0.0],+ secondary: [1.0, 1.0, 1.0],+ stroke: None,+ gpu: None,+ canvas: None,+ needs_frame: false,+ stop: false,+ projection_size: (1, 1),+ projection_stop: false,+ frames: 0,+ pad_strokes: None,+ pad_sample: false,+ frame_interval_ms: 0.0,+ error: None,+ display_scale: 2.0,+ pending_doc: None,+ pending_name: None,+ info: project::ArtworkInfo {+ created_ms: std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_or(0, |d| u64::try_from(d.as_millis()).unwrap_or(0)),+ ..project::ArtworkInfo::default()+ },+ revision: 0,+ transform: None,+ transform_mode: procraft_engine::transform::TransformMode::Freeform,+ interpolation: transform::Interpolation::Bilinear,+ transform_guides: transform::GuideSettings::default(),+ selection: None,+ saved_selections: Vec::new(),+ selection_display: selection::SelectionDisplay::Stripes,+ #[cfg(target_os = "android")]+ display_lut: None,+ selection_before: None,+ colour_source: None,+ feather_base: None,+ adjusting: false,+ last_filter: None,+ liquify_last: None,+ studio: None,+ pencil: false,+ cloning: false,+ simplified_undos: true,+ clone_sliders: DEFAULT_SLIDERS,+ clone_source: None,+ clone_offset: None,+ last_drag: None,+ drawn: Vec::new(),+ drawn_pressure: 0.0,+ shape: None,+ began: None,+ last_stroke: None,+ force_assist: false,+ assist_from: None,+ guide_before: None,+ name,+ pending_pixels: pixels,+ fit_insets: [0.0; 4],+ backdrops: Vec::new(),+ saved_view: None,+ };+ Arc::new(CanvasSession {+ shared: Arc::new(Shared {+ state: Mutex::new(state),+ wake: Condvar::new(),+ thread: Mutex::new(None),+ projection: Mutex::new(None),+ saving: Mutex::new(project::Saved::default()),+ }),+ })+ }+}++#[uniffi::export]+impl CanvasSession {+ /// Starts drawing into the window `window` (an id from `NativeWindows.acquire`), `width` ×+ /// `height` pixels. The session owns the window from here on.+ pub fn attach_window(&self, window: u64, width: u32, height: u32) -> Result<(), MobileError> {+ self.detach_window();+ #[cfg(target_os = "android")]+ {+ let native =+ window::take(window).ok_or_else(|| MobileError::Window { reason: format!("no window {window}") })?;+ {+ let mut st = self.shared.lock();+ st.window_size = (width.max(1), height.max(1));+ if st.view.is_none() {+ let kept = st.saved_view.take().and_then(|v| v.view(st.window_size));+ st.view = Some(kept.unwrap_or_else(|| st.fitted_view()));+ }+ st.stop = false;+ st.reconfigure = true;+ self.shared.frame(&mut st);+ }+ let shared = Arc::clone(&self.shared);+ let handle = std::thread::Builder::new()+ .name("procraft-render".to_owned())+ .spawn(move || render::run(shared, native))+ .map_err(|e| MobileError::Window { reason: e.to_string() })?;+ *self.shared.thread.lock().unwrap_or_else(|e| e.into_inner()) = Some(handle);+ Ok(())+ }+ #[cfg(not(target_os = "android"))]+ {+ let _ = (width, height);+ Err(MobileError::Window { reason: format!("windows are Android-only (asked for {window})") })+ }+ }++ pub fn resize_window(&self, width: u32, height: u32) {+ let mut st = self.shared.lock();+ let size = (width.max(1), height.max(1));+ if st.window_size != size {+ st.window_size = size;+ st.reconfigure = true;+ self.shared.frame(&mut st);+ }+ }++ /// Stops drawing and lets go of the window (call before the platform destroys it). Returns+ /// once the render thread has finished.+ pub fn detach_window(&self) {+ let handle = self.shared.thread.lock().unwrap_or_else(|e| e.into_inner()).take();+ if let Some(handle) = handle {+ {+ let mut st = self.shared.lock();+ st.stop = true;+ self.shared.wake.notify_all();+ }+ let _ = handle.join();+ self.shared.lock().stop = false;+ }+ }++ /// A stroke starts: `samples` are its first input.+ pub fn stroke_begin(&self, pointer: PointerKind, samples: Vec<PenSample>) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ if let Some(kept) = st.pad_strokes.as_mut() {+ kept.push((pointer, samples.clone()));+ }+ // a layer being transformed or adjusted takes no paint, unless the adjustment is painted on+ if st.transform.is_some() || (st.adjusting && !st.pencil) {+ return;+ }+ if st.adjusting {+ st.pencil_stroke(pointer, &samples);+ self.shared.frame(st);+ return;+ }+ let current = st.doc.current();+ st.finish_stroke();+ st.settle();+ // locked and hidden layers, groups and text layers take no paint+ if st.doc.layer(current).is_none_or(|l| {+ l.locked || !l.visible || l.kind == procraft_engine::document::LayerKind::Group || l.text.is_some()+ }) {+ return;+ }+ let tool = if pointer == PointerKind::StylusEraser { ToolKind::Erase } else { st.tool };+ let sliders = st.sliders(tool);+ let mut brush = st.brush(tool).clone();+ // a blending brush's opacity lightens each stamp, as its flow does, so its strokes still+ // build up to full; a glaze's caps the stroke+ let opacity = if brush.blends() && matches!(tool.stroke_tool(), StrokeTool::Paint | StrokeTool::Erase) {+ brush.flow *= sliders.opacity.clamp(0.0, 1.0).powf(procraft_engine::brush::FLOW_POWER);+ 1.0+ } else {+ brush.opacity(sliders.opacity)+ };+ st.strokes = st.strokes.wrapping_add(1);+ st.info.strokes = st.info.strokes.saturating_add(1);+ let seed = st.strokes.wrapping_mul(0x9e37_79b9);+ let diameter = brush.diameter(sliders.size) * st.brush_scale();+ let mut builder = StrokeBuilder::with_seed(brush.clone(), diameter, pointer.into(), seed)+ .scaled(st.brush_scale())+ .with_input(st.input.clone())+ .on_view_turned(st.view.map_or(0.0, |v| v.rotation()))+ .seen_at(st.view.map_or(1.0, |v| v.zoom()) / st.display_scale);+ if st.pad_sample {+ // the pad's sample scribble is drawn as given: its path whatever the brush's+ // streamline, its pressure as it comes (its pace still counts)+ builder = builder.exact_path();+ }+ let canvas_samples = st.to_canvas(&samples);+ st.assist_from = canvas_samples.first().map(|s| s.pos);+ let canvas_samples = st.assisted(canvas_samples);+ st.drawn.clear();+ st.drawn_pressure = 0.0;+ st.remember_input(&canvas_samples);+ let stamps = guide::mirrored(&st.doc.guide, &builder.add(&canvas_samples));+ let mut style = StrokeStyle::for_brush(+ &brush,+ tool.stroke_tool(),+ st.color,+ opacity,+ st.doc.layer(current).is_some_and(|l| l.alpha_lock),+ );+ style.secondary = st.secondary;+ style.preview = st.pad_strokes.is_some();+ if let (Some(canvas), Some(gpu)) = (st.canvas.as_mut(), st.gpu.as_ref()) {+ canvas.use_sources(gpu, &mut style, &brush);+ }+ // painted and erased strokes can be made shapes once they end+ st.last_stroke = None;+ st.began =+ matches!(tool.stroke_tool(), StrokeTool::Paint | StrokeTool::Erase).then(|| quickshape::LastStroke {+ layer: current,+ style,+ brush: brush.clone(),+ diameter,+ pointer,+ drawn: Vec::new(),+ pressure: 1.0,+ steps: 0,+ });+ let Some(canvas) = st.canvas.as_mut() else { return };+ canvas.begin_stroke(current, style);+ canvas.add_stamps(&stamps);+ st.stroke = Some(builder);+ self.shared.frame(st);+ }++ /// More input for the stroke (including the samples batched in between).+ pub fn stroke_add(&self, samples: Vec<PenSample>) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.keep_pad_input(&samples);+ let canvas_samples = st.assisted(st.to_canvas(&samples));+ // a snapped shape follows the held finger no further+ if st.shape.is_some() {+ return;+ }+ st.remember_input(&canvas_samples);+ let (Some(builder), Some(canvas)) = (st.stroke.as_mut(), st.canvas.as_mut()) else { return };+ let stamps = guide::mirrored(&st.doc.guide, &builder.add(&canvas_samples));+ if !stamps.is_empty() {+ canvas.add_stamps(&stamps);+ st.redraw_painted_on();+ self.shared.frame(st);+ }+ }++ /// Where the input is predicted to go next: drawn ahead of the stroke until the next input,+ /// never kept.+ pub fn stroke_predict(&self, samples: Vec<PenSample>) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let canvas_samples = st.to_canvas(&samples);+ let (Some(builder), Some(canvas)) = (st.stroke.as_ref(), st.canvas.as_mut()) else { return };+ canvas.set_prediction(&builder.preview(&canvas_samples));+ self.shared.frame(st);+ }++ /// The stroke ends (the pen or finger lifted) after `samples`.+ pub fn stroke_end(&self, samples: Vec<PenSample>) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.keep_pad_input(&samples);+ let canvas_samples = st.assisted(st.to_canvas(&samples));+ // a snapped shape stays open to be edited, until the next thing done keeps it+ if st.shape.is_some() {+ self.shared.frame(st);+ return;+ }+ let (Some(mut builder), Some(canvas)) = (st.stroke.take(), st.canvas.as_mut()) else { return };+ let stamps = builder.add(&canvas_samples);+ canvas.add_stamps(&guide::mirrored(&st.doc.guide, &stamps));+ close_stroke(canvas, builder, &st.doc.guide);+ st.redraw_painted_on();+ st.bake_painted_on();+ st.remember_last_stroke();+ self.shared.frame(st);+ }++ /// Drops the stroke (a second finger turned it into a gesture).+ pub fn stroke_cancel(&self) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ if let Some(kept) = st.pad_strokes.as_mut() {+ kept.pop();+ }+ st.stroke = None;+ st.shape = None;+ st.began = None;+ if let Some(canvas) = st.canvas.as_mut() {+ canvas.cancel_stroke();+ // what it painted on is in the adjustment's mask: start that again+ st.restart_painted_on(None);+ self.shared.frame(st);+ }+ }++ /// A step of a two-finger gesture (see `View::gesture`).+ pub fn view_gesture(&self, pivot_x: f32, pivot_y: f32, pan_x: f32, pan_y: f32, scale: f32, rotation: f32) {+ let mut st = self.shared.lock();+ // the fingers take the canvas from wherever it was settling to+ st.view_motion = None;+ if let Some(view) = st.view.as_mut() {+ view.gesture(Vec2::new(pivot_x, pivot_y), Vec2::new(pan_x, pan_y), scale, rotation);+ self.shared.frame(&mut st);+ }+ }++ /// How many window pixels make one interface point (the screen's density).+ pub fn set_display_scale(&self, pixels_per_point: f32) {+ if pixels_per_point.is_finite() && pixels_per_point > 0.0 {+ let mut st = self.shared.lock();+ st.display_scale = pixels_per_point;+ self.shared.frame(&mut st);+ }+ }++ /// Fits the whole canvas in the window again, at once.+ pub fn fit_view(&self) {+ let mut st = self.shared.lock();+ st.view_motion = None;+ st.view = Some(st.fitted_view());+ self.shared.frame(&mut st);+ }++ /// Fits the whole canvas in the window again, settling into place on a spring over+ /// [`CanvasSession::view_settle_seconds`] (the view read meanwhile is where it has got to).+ pub fn settle_to_fit(&self) {+ let mut st = self.shared.lock();+ let to = st.fitted_view();+ st.view_motion =+ st.view.map(|from| ViewMotion { from, to, start: std::time::Instant::now(), curve: ViewCurve::Settle });+ if st.view_motion.is_none() {+ st.view = Some(to);+ }+ self.shared.frame(&mut st);+ }++ /// Fits the whole canvas in the window again, growing back into place over 0.3 s, slowing to+ /// a stop (as leaving crop without cropping does).+ pub fn ease_to_fit(&self) {+ let mut st = self.shared.lock();+ let to = st.fitted_view();+ st.view_motion = st.view.map(|from| ViewMotion {+ from,+ to,+ start: std::time::Instant::now(),+ curve: ViewCurve::EaseOut(VIEW_EASE_SECONDS),+ });+ if st.view_motion.is_none() {+ st.view = Some(to);+ }+ self.shared.frame(&mut st);+ }++ /// How long the view takes to settle into place.+ pub fn view_settle_seconds(&self) -> f32 {+ VIEW_SETTLE_SECONDS+ }++ /// Whether the view is still moving into place (what is drawn over the canvas follows it).+ pub fn view_moving(&self) -> bool {+ self.shared.lock().view_motion.is_some()+ }++ /// The frosted panels open over the canvas, five numbers each (left, top, right, bottom and+ /// corner radius, window pixels): what is behind them is drawn blurred.+ pub fn set_backdrops(&self, regions: Vec<f32>) {+ let (regions, _) = regions.as_chunks::<6>();+ let mut st = self.shared.lock();+ if st.backdrops != regions {+ st.backdrops = regions.to_vec();+ self.shared.frame(&mut st);+ }+ }++ /// What fitting the canvas keeps clear of from now on (left, top, right, bottom, window+ /// pixels): the interface, with Fit Canvas Inside Interface on.+ pub fn set_fit_insets(&self, left: f32, top: f32, right: f32, bottom: f32) {+ self.shared.lock().fit_insets = [left, top, right, bottom];+ }++ /// The artwork opens fitted, not as it was left (Canvas Orientation Memory off).+ pub fn forget_saved_view(&self) {+ self.shared.lock().saved_view = None;+ }++ pub fn set_tool(&self, tool: ToolKind) {+ self.shared.lock().tool = tool;+ }++ /// The current tool's size slider, 0..1.+ pub fn set_brush_size(&self, slider: f32) {+ if slider.is_finite() {+ self.shared.lock().sliders_mut().size = slider.clamp(0.0, 1.0);+ }+ }++ /// The current tool's opacity slider, 0..1.+ pub fn set_brush_opacity(&self, slider: f32) {+ if slider.is_finite() {+ self.shared.lock().sliders_mut().opacity = slider.clamp(0.0, 1.0);+ }+ }++ /// The paint colour, sRGB 0..1.+ pub fn set_color(&self, r: f32, g: f32, b: f32) {+ let c = [r, g, b].map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 });+ self.shared.lock().color = c;+ }++ /// The secondary colour, which brushes with secondary colour dynamics mix in.+ pub fn set_secondary_color(&self, r: f32, g: f32, b: f32) {+ let c = [r, g, b].map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 1.0 });+ self.shared.lock().secondary = c;+ }++ /// Undoes the last step; returns what it was called, if it was named.+ pub fn undo(&self) -> Option<String> {+ if self.swap_crop(true) {+ return Some("Crop canvas".to_owned());+ }+ self.edit(Canvas::undo);+ self.shared.lock().canvas.as_ref().and_then(Canvas::redo_name)+ }++ /// Redoes the last step undone; returns what it was called, if it was named.+ pub fn redo(&self) -> Option<String> {+ if self.swap_crop(false) {+ return Some("Crop canvas".to_owned());+ }+ self.edit(Canvas::redo);+ self.shared.lock().canvas.as_ref().and_then(Canvas::undo_name)+ }++ pub fn clear_layer(&self) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let current = st.doc.current();+ st.finish_stroke();+ st.settle();+ if st.doc.layer(current).is_none_or(|l| l.locked || l.text.is_some()) {+ return;+ }+ // with a selection, only what is selected is cleared+ if let Some(mask) = st.selection.clone() {+ st.flush();+ let pixels = match (st.canvas.as_mut(), st.gpu.as_ref()) {+ (Some(canvas), Some(gpu)) => canvas.read_layer(gpu, current).ok(),+ _ => None,+ };+ if let (Some(mut pixels), Some(canvas)) = (pixels, st.canvas.as_mut()) {+ for (px, &m) in pixels.as_chunks_mut::<4>().0.iter_mut().zip(&mask.data) {+ let keep = 255 - u16::from(m);+ px.iter_mut().for_each(|c| *c = ((u16::from(*c) * keep + 127) / 255) as u8);+ }+ canvas.write_layer(current, pixels);+ self.shared.frame(st);+ }+ return;+ }+ if let Some(canvas) = st.canvas.as_mut() {+ canvas.name_next_step("clear layer");+ canvas.clear_layer(current);+ self.shared.frame(st);+ }+ }++ pub fn info(&self) -> CanvasInfo {+ let st = self.shared.lock();+ let sliders = st.shown_sliders();+ CanvasInfo {+ width: st.doc.width(),+ dpi: st.doc.dpi,+ height: st.doc.height(),+ tool: st.tool,+ size: sliders.size,+ opacity: sliders.opacity,+ brush_diameter: st.brush(st.tool).diameter(sliders.size) * st.brush_scale(),+ can_undo: st.canvas.as_ref().is_some_and(Canvas::can_undo) || st.crop_undo.is_some(),+ // keeping an open shape drops what could be redone+ can_redo: st.shape.is_none() && (st.canvas.as_ref().is_some_and(Canvas::can_redo) || st.crop_redo_ready()),+ zoom: st.view.map_or(1.0, |v| v.zoom()),+ frames: st.frames,+ frame_interval_ms: st.frame_interval_ms,+ error: st.error.clone(),+ revision: st.revision,+ }+ }+}++impl CanvasSession {+ /// Undo or redo, after finishing any open stroke; done at once, so the document is current+ /// when this returns.+ fn edit(&self, f: fn(&mut Canvas)) {+ // text being edited is kept first: it is the step undone+ self.text_end(true);+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.finish_stroke();+ // painting an adjustment on, undo and redo step through the strokes and it stays open+ if st.adjusting && st.pencil {+ st.restart_painted_on(Some(f));+ st.flush();+ st.revision += 1;+ self.shared.frame(st);+ return;+ }+ st.settle();+ if let Some(canvas) = st.canvas.as_mut() {+ f(canvas);+ st.flush();+ st.sync_selection();+ st.revision += 1;+ self.shared.frame(st);+ }+ }+}++impl Drop for CanvasSession {+ fn drop(&mut self) {+ self.detach_window();+ }+}diff --git a/apps/procraft-android/src/pick.rs b/apps/procraft-android/src/pick.rsnew file mode 100644index 0000000..4c2c78f--- /dev/null+++ b/apps/procraft-android/src/pick.rs@@ -0,0 +1,78 @@+//! The eyedropper: what is shown around a window point, and the canvas colour under it.++use procraft_engine::geom::{Affine, Vec2};+use procraft_gpu::{SurroundGrid, Target, read_texture, wgpu};++use crate::{CanvasSession, GRID_LINE, GRID_SPACING_PT, GRID_TOP_PT, SURROUND};++/// What the eyedropper sees.+#[derive(Clone, Debug, uniffi::Record)]+pub struct Pick {+ /// The canvas colour under the point (0xRRGGBB), or none when the point is off the canvas.+ pub rgb: Option<u32>,+ /// The window around the point as it is shown, `side` × `side` RGBA8, rows top to bottom.+ pub side: u32,+ pub pixels: Vec<u8>,+}++#[uniffi::export]+impl CanvasSession {+ /// The `side` × `side` window pixels centred on window point (`x`, `y`) as they are shown+ /// (canvas through the view, surround and grid), and the colour under the point. None before+ /// the canvas is shown.+ pub fn pick(&self, x: f32, y: f32, side: u32) -> Option<Pick> {+ let side = side.clamp(1, 1024);+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let view = st.view?;+ let (Some(canvas), Some(gpu)) = (st.canvas.as_mut(), st.gpu.as_ref()) else { return None };+ let format = wgpu::TextureFormat::Rgba8Unorm;+ let texture = gpu.device.create_texture(&wgpu::TextureDescriptor {+ label: Some("eyedropper"),+ size: wgpu::Extent3d { width: side, height: side, depth_or_array_layers: 1 },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format,+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,+ view_formats: &[],+ });+ let target_view = texture.create_view(&Default::default());+ // the window shifted so that the point lands in the middle of the small target+ let corner = Vec2::new(x - side as f32 / 2.0, y - side as f32 / 2.0);+ let to_screen = view.to_screen().then(Affine::translate(Vec2::ZERO - corner));+ let s = st.display_scale;+ let grid = SurroundGrid {+ spacing: GRID_SPACING_PT * s,+ origin: [-corner.x, GRID_TOP_PT * s - corner.y],+ width: s,+ color: GRID_LINE,+ };+ canvas.render(+ gpu,+ &mut st.doc,+ Some(Target {+ view: &target_view,+ format,+ size: (side, side),+ to_screen,+ surround: SURROUND,+ grid: Some(grid),+ selection: None,+ backdrop: None,+ convert: None,+ lut: None,+ }),+ );+ let pixels = read_texture(gpu, &texture, side, side).ok()?;+ let on_canvas = view+ .screen_to_canvas(Vec2::new(x, y))+ .is_some_and(|p| p.x >= 0.0 && p.y >= 0.0 && p.x < st.doc.width() as f32 && p.y < st.doc.height() as f32);+ let middle = ((side / 2 * side + side / 2) * 4) as usize;+ let rgb = pixels+ .get(middle..middle + 3)+ .filter(|_| on_canvas)+ .map(|c| c.iter().fold(0u32, |acc, v| (acc << 8) | u32::from(*v)));+ Some(Pick { rgb, side, pixels })+ }+}diff --git a/apps/procraft-android/src/project.rs b/apps/procraft-android/src/project.rsnew file mode 100644index 0000000..45e7ea5--- /dev/null+++ b/apps/procraft-android/src/project.rs@@ -0,0 +1,773 @@+//! Saving and opening artworks. An artwork is a folder:+//!+//! - `artwork.json`: the format, the title and the document (layers and their settings).+//! - `layers/<id>.png`: each layer's pixels, premultiplied RGBA8 stored losslessly in a PNG (an+//! internal store, not for other apps).+//! - `thumbnail.png`: the picture at up to [`THUMBNAIL_SIDE`] pixels, for the gallery.+//!+//! Files are written beside their final name and renamed into place, so an interrupted save+//! leaves the previous version whole.++use std::fs;+use std::io::BufReader;+use std::path::{Path, PathBuf};+use std::sync::Arc;++use procraft_engine::document::{BlendMode, Document, LayerId, LayerKind};+use procraft_engine::formats::{self, PsdKind, PsdLayer};+use procraft_engine::geom::Vec2;+use procraft_engine::view::View;++use crate::{CanvasSession, MobileError};++/// The gallery thumbnail's longest side, pixels.+pub const THUMBNAIL_SIDE: u32 = 512;+/// A package's preview's longest side, pixels.+const PACKAGE_PREVIEW_SIDE: u32 = 1024;+const FORMAT: &str = "procraft-artwork";+const VERSION: u32 = 1;++#[derive(serde::Serialize, serde::Deserialize)]+struct ArtworkFile {+ format: String,+ version: u32,+ name: String,+ document: Document,+ #[serde(default)]+ info: ArtworkInfo,+ /// How it was last shown, if it was.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ view: Option<SavedView>,+}++/// A view kept with an artwork: the canvas point in the middle of the window, the zoom and the+/// rotation (radians).+#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]+pub(crate) struct SavedView {+ centre: [f32; 2],+ zoom: f32,+ rotation: f32,+}++impl SavedView {+ /// The view `view` makes in a window `window` pixels.+ pub(crate) fn of(view: &View, window: (u32, u32)) -> Option<SavedView> {+ let middle = Vec2::new(window.0 as f32 / 2.0, window.1 as f32 / 2.0);+ let centre = view.screen_to_canvas(middle)?;+ Some(SavedView { centre: [centre.x, centre.y], zoom: view.zoom(), rotation: view.to_screen().rotation() })+ }++ /// It again, in a window `window` pixels.+ #[cfg_attr(not(target_os = "android"), allow(dead_code))]+ pub(crate) fn view(&self, window: (u32, u32)) -> Option<View> {+ View::centred(Vec2::new(self.centre[0], self.centre[1]), self.zoom, self.rotation, window)+ }+}++/// What an artwork keeps about itself besides the picture.+#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize, uniffi::Record)]+pub struct ArtworkInfo {+ /// When it was made, milliseconds since 1970 (0: not known).+ #[serde(default)]+ pub created_ms: u64,+ /// Strokes made on it.+ #[serde(default)]+ pub strokes: u64,+ /// Time spent on it, milliseconds.+ #[serde(default)]+ pub tracked_ms: u64,+ /// Who made it.+ #[serde(default)]+ pub author: String,+}++pub(crate) fn file_error(context: &str, e: impl std::fmt::Display) -> MobileError {+ MobileError::File { reason: format!("{context}: {e}") }+}++/// What a save writes, read under the lock: the artwork's file, every layer and the picture (if+/// shown).+pub(crate) struct SaveSnapshot {+ file: ArtworkFile,+ layers: Vec<(LayerId, Vec<u8>)>,+ composite: Option<Vec<u8>>,+}++/// What the last saves wrote: the folder, and a hash of each layer's pixels, so layers that+/// haven't changed aren't written again.+#[derive(Default)]+pub(crate) struct Saved {+ dir: PathBuf,+ layers: std::collections::HashMap<LayerId, u64>,+}++/// A quick hash of pixels, to tell a changed layer from one saved already.+fn pixels_hash(rgba: &[u8]) -> u64 {+ const PRIME: u64 = 0x0000_0100_0000_01B3;+ let (words, rest) = rgba.as_chunks::<8>();+ let mut h: u64 = 0xCBF2_9CE4_8422_2325;+ for w in words {+ h = (h ^ u64::from_le_bytes(*w)).wrapping_mul(PRIME).rotate_left(29);+ }+ for &b in rest {+ h = (h ^ u64::from(b)).wrapping_mul(PRIME);+ }+ h+}++impl crate::State {+ /// Nothing under way that saving would end or cut short.+ pub(crate) fn idle(&self) -> bool {+ self.stroke.is_none()+ && self.transform.is_none()+ && !self.adjusting+ && self.text_edit.is_none()+ && self.shape.is_none()+ && self.pending_doc.is_none()+ && self.feather_base.is_none()+ && self.selection_before.is_none()+ }++ /// The artwork as it is now, for saving.+ pub(crate) fn save_snapshot(&mut self) -> Result<SaveSnapshot, MobileError> {+ let file = ArtworkFile {+ format: FORMAT.to_owned(),+ version: VERSION,+ name: self.name.clone(),+ document: self.doc.clone(),+ info: self.info.clone(),+ // as shown, or as it opened if it hasn't been shown+ view: self.view.as_ref().and_then(|v| SavedView::of(v, self.window_size)).or(self.saved_view),+ };+ let mut layers = Vec::new();+ let mut composite = None;+ if let (Some(canvas), Some(gpu)) = (self.canvas.as_mut(), self.gpu.as_ref()) {+ canvas.render(gpu, &mut self.doc, None);+ for layer in self.doc.layers() {+ let rgba = canvas.read_layer(gpu, layer.id).map_err(|e| file_error("reading a layer", e))?;+ layers.push((layer.id, rgba));+ }+ composite = Some(canvas.read_composite(gpu).map_err(|e| file_error("reading the picture", e))?);+ } else {+ // not shown yet: what was opened is still what there is+ layers = self.pending_pixels.clone();+ }+ Ok(SaveSnapshot { file, layers, composite })+ }+}++/// Writes a save into `dir` (made if missing): the layers that changed since the last save there,+/// the thumbnail and the document.+fn write_artwork(saved: &mut Saved, dir: &Path, snapshot: SaveSnapshot) -> Result<(), MobileError> {+ let SaveSnapshot { file, layers, composite } = snapshot;+ if saved.dir != dir {+ saved.dir = dir.to_path_buf();+ saved.layers.clear();+ }+ let (w, h) = (file.document.width(), file.document.height());+ fs::create_dir_all(dir.join("layers")).map_err(|e| file_error("making the folder", e))?;+ for (id, rgba) in &layers {+ let hash = pixels_hash(rgba);+ let path = layer_path(dir, *id);+ if saved.layers.get(id) == Some(&hash) && path.exists() {+ continue;+ }+ write_atomically(&path, |p| write_png(p, w, h, rgba, &[]))?;+ saved.layers.insert(*id, hash);+ }+ // layer files the document no longer has+ saved.layers.retain(|id, _| file.document.layer(*id).is_some());+ if let Ok(entries) = fs::read_dir(dir.join("layers")) {+ let keep: Vec<PathBuf> = file.document.layer_ids().map(|id| layer_path(dir, id)).collect();+ for entry in entries.flatten() {+ let path = entry.path();+ if !keep.contains(&path) {+ let _ = fs::remove_file(path);+ }+ }+ }+ if let Some(rgba) = composite {+ let (tw, th, mut thumb) = thumbnail(&rgba, w, h, THUMBNAIL_SIDE);+ // the gallery shows it in the artwork's colours (a CMYK canvas's: as its press prints them)+ if let Some(table) = proof_table(&file.document) {+ table.apply_rgba(&mut thumb, false);+ }+ let icc = file.document.picture_icc();+ write_atomically(&dir.join("thumbnail.png"), |p| write_png(p, tw, th, &thumb, &icc))?;+ }+ let json = serde_json::to_string(&file).map_err(|e| file_error("writing the artwork", e))?;+ write_atomically(&dir.join("artwork.json"), |p| {+ fs::write(p, json.as_bytes()).map_err(|e| file_error("writing the artwork", e))+ })+}++#[uniffi::export]+impl CanvasSession {+ /// A new artwork `width` × `height` at `dpi`, its background colour (sRGB 0..1, three values)+ /// and whether it shows, and its name: a custom canvas.+ #[uniffi::constructor]+ pub fn new_custom(+ width: u32,+ height: u32,+ dpi: f32,+ background: Vec<f32>,+ background_visible: bool,+ name: String,+ ) -> Arc<CanvasSession> {+ let mut doc = Document::new(width.max(1), height.max(1));+ doc.dpi = dpi;+ if let [r, g, b] = background[..] {+ doc.background = [r, g, b];+ }+ doc.background_visible = background_visible;+ let name = if name.trim().is_empty() {+ "Untitled Artwork".to_owned()+ } else {+ name.trim().chars().take(256).collect()+ };+ CanvasSession::with_document(doc.repaired(), name, Vec::new())+ }++ /// A new artwork the size of `image` (straight RGBA8), the picture as its one layer.+ #[uniffi::constructor]+ pub fn from_image(image: crate::layers::ThumbnailImage, name: String) -> Arc<CanvasSession> {+ let (w, h) = (image.width.max(1), image.height.max(1));+ let doc = Document::new(w, h);+ let layer = doc.current();+ let mut pixels = image.rgba;+ pixels.resize(w as usize * h as usize * 4, 0);+ for px in pixels.as_chunks_mut::<4>().0 {+ let a = u16::from(px[3]);+ for c in px.iter_mut().take(3) {+ *c = ((u16::from(*c) * a + 127) / 255) as u8;+ }+ }+ let name = if name.trim().is_empty() {+ "Untitled Artwork".to_owned()+ } else {+ name.trim().chars().take(256).collect()+ };+ CanvasSession::with_document(doc, name, vec![(layer, pixels)])+ }++ /// Opens an artwork saved with [`CanvasSession::save`].+ #[uniffi::constructor]+ pub fn open(dir: String) -> Result<Arc<CanvasSession>, MobileError> {+ let dir = PathBuf::from(dir);+ let text = fs::read_to_string(dir.join("artwork.json")).map_err(|e| file_error("reading the artwork", e))?;+ let file: ArtworkFile = serde_json::from_str(&text).map_err(|e| file_error("reading the artwork", e))?;+ if file.format != FORMAT || file.version > VERSION {+ return Err(MobileError::File {+ reason: format!("not an artwork this version can open ({} {})", file.format, file.version),+ });+ }+ let doc = file.document.repaired();+ let mut pixels = Vec::new();+ for layer in doc.layers() {+ let path = layer_path(&dir, layer.id);+ // a layer with no file is empty+ if !path.exists() {+ continue;+ }+ match read_png(&path, doc.width(), doc.height()) {+ Ok(rgba) => pixels.push((layer.id, rgba)),+ Err(e) => log::error!("layer {:?}: {e}", layer.id),+ }+ }+ let session = CanvasSession::with_document(doc, file.name, pixels);+ {+ let mut st = session.shared.lock();+ st.info = file.info;+ st.saved_view = file.view;+ }+ Ok(session)+ }++ /// Saves the artwork into `dir` (made if missing): its document, every layer and a thumbnail.+ /// Saves started together run one after the other.+ pub fn save(&self, dir: String) -> Result<(), MobileError> {+ let mut saved = self.shared.saving.lock().unwrap_or_else(|e| e.into_inner());+ let snapshot = {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.finish_stroke();+ st.settle();+ st.save_snapshot()?+ };+ write_artwork(&mut saved, Path::new(&dir), snapshot)+ }++ /// Saves as [`CanvasSession::save`] does, but only when nothing is under way that saving+ /// would end (a stroke, a transform, an adjustment, text being edited...); false if it didn't.+ pub fn save_if_idle(&self, dir: String) -> Result<bool, MobileError> {+ let mut saved = self.shared.saving.lock().unwrap_or_else(|e| e.into_inner());+ let snapshot = {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ if !st.idle() {+ return Ok(false);+ }+ st.save_snapshot()?+ };+ write_artwork(&mut saved, Path::new(&dir), snapshot).map(|()| true)+ }++ /// A number that changes whenever the artwork does (new steps, undo and redo, layer+ /// settings): unchanged, there is nothing new to save.+ pub fn edits(&self) -> u64 {+ let st = self.shared.lock();+ st.revision.wrapping_add(st.canvas.as_ref().map_or(0, procraft_gpu::Canvas::steps_made))+ }++ /// Gives an artwork opened only to be exported (never shown) a GPU device of its own, so its+ /// exports work; false if there is none.+ pub fn prepare_offscreen(&self) -> bool {+ let mut st = self.shared.lock();+ if st.gpu.is_none() {+ match procraft_gpu::Gpu::headless() {+ Ok(gpu) => st.gpu = Some(gpu),+ Err(e) => {+ log::error!("exporting offscreen: {e}");+ return false;+ }+ }+ }+ st.ensure_canvas();+ st.canvas.is_some()+ }++ /// Writes the flattened picture, full size and with straight alpha, to `path` as a PNG.+ pub fn export_png(&self, path: String) -> Result<(), MobileError> {+ let (w, h, rgba, icc) = {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.finish_stroke();+ st.settle();+ let (w, h) = (st.doc.width(), st.doc.height());+ let icc = st.doc.picture_icc();+ let proof = proof_table(&st.doc);+ let (Some(canvas), Some(gpu)) = (st.canvas.as_mut(), st.gpu.as_ref()) else {+ return Err(file_error("reading the picture", "the canvas is not shown yet"));+ };+ canvas.render(gpu, &mut st.doc, None);+ let rgba = canvas.read_composite(gpu).map_err(|e| file_error("reading the picture", e))?;+ (w, h, rgba, (icc, proof))+ };+ let (icc, proof) = icc;+ let mut straight = straight_alpha(&rgba);+ if let Some(table) = proof {+ table.apply_rgba(&mut straight, false);+ }+ write_atomically(Path::new(&path), |p| write_png(p, w, h, &straight, &icc))+ }++ /// Opens a layered artwork package (as the Share menu's first row writes) from `path`.+ #[uniffi::constructor]+ pub fn open_package(path: String) -> Result<Arc<CanvasSession>, MobileError> {+ let bytes = fs::read(&path).map_err(|e| file_error("opening the file", e))?;+ let imported =+ procraft_engine::native::read(&bytes).map_err(|e| file_error("opening the file", format!("{e:?}")))?;+ let session = CanvasSession::with_document(imported.document, imported.name, imported.pixels);+ {+ let mut st = session.shared.lock();+ st.info.strokes = imported.strokes;+ st.info.tracked_ms = (imported.tracked_seconds * 1000.0) as u64;+ st.info.author = imported.author;+ }+ Ok(session)+ }++ /// The artwork as a layered package at `path`; `seed` makes its layers' ids.+ pub fn export_package(&self, path: String, seed: u64) -> Result<(), MobileError> {+ let (doc, pixels, composite, name, info) = {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.finish_stroke();+ st.settle();+ let (Some(canvas), Some(gpu)) = (st.canvas.as_mut(), st.gpu.as_ref()) else {+ return Err(file_error("reading the picture", "the canvas is not shown yet"));+ };+ canvas.render(gpu, &mut st.doc, None);+ let composite = canvas.read_composite(gpu).map_err(|e| file_error("reading the picture", e))?;+ let mut pixels = std::collections::HashMap::new();+ for l in st.doc.layers() {+ if l.kind != LayerKind::Group {+ pixels.insert(l.id, canvas.read_layer(gpu, l.id).map_err(|e| file_error("reading a layer", e))?);+ }+ }+ (st.doc.clone(), pixels, composite, st.name.clone(), st.info.clone())+ };+ let (w, h) = (doc.width(), doc.height());+ let (tw, th, mut thumb) = thumbnail(&straight_alpha(&composite), w, h, PACKAGE_PREVIEW_SIDE);+ if let Some(table) = proof_table(&doc) {+ table.apply_rgba(&mut thumb, false);+ }+ let preview = png_bytes(tw, th, &thumb, &doc.picture_icc())?;+ let bytes = procraft_engine::native::write(&procraft_engine::native::Export {+ document: &doc,+ pixels: &pixels,+ composite: &composite,+ thumbnail_png: &preview,+ name: &name,+ author: &info.author,+ strokes: info.strokes,+ tracked_seconds: info.tracked_ms as f64 / 1000.0,+ seed,+ });+ write_atomically(Path::new(&path), |f| fs::write(f, &bytes).map_err(|e| file_error("saving", e)))+ }++ /// The artwork as a layered PSD (groups, masks, clipping, blend modes kept) at `path`.+ pub fn export_psd(&self, path: String) -> Result<(), MobileError> {+ let p = self.pictures(true)?;+ let layers = psd_layers(&p);+ let (icc, inks) = file_colours(&p.doc);+ let bytes = formats::psd(p.width, p.height, p.doc.dpi, &icc, &layers, &p.composite, inks.as_ref());+ write_atomically(Path::new(&path), |f| fs::write(f, &bytes).map_err(|e| file_error("saving", e)))+ }++ /// The flattened picture as a TIFF at `path`.+ pub fn export_tiff(&self, path: String) -> Result<(), MobileError> {+ let p = self.pictures(false)?;+ let bytes = match file_colours(&p.doc) {+ (icc, Some(inks)) => formats::tiff_cmyk(p.width, p.height, p.doc.dpi, &icc, &p.composite, &inks),+ (icc, None) => formats::tiff(p.width, p.height, p.doc.dpi, &icc, &p.composite),+ };+ write_atomically(Path::new(&path), |f| fs::write(f, &bytes).map_err(|e| file_error("saving", e)))+ }++ /// The picture as a one-page PDF, or (`layers`) a page for each layer, bottom first, at `path`.+ /// The flattened picture, or each layer (`layers`), as a page of a PDF at `path`: exact at+ /// `quality` 100, JPEG below it.+ pub fn export_pdf(&self, path: String, layers: bool, quality: u8) -> Result<(), MobileError> {+ let p = self.pictures(layers)?;+ let pages: Vec<&[u8]> = if layers {+ p.doc.layers().iter().filter_map(|l| p.layers.get(&l.id)).map(Vec::as_slice).collect()+ } else {+ vec![p.composite.as_slice()]+ };+ let (icc, inks) = file_colours(&p.doc);+ let bytes = formats::pdf(p.width, p.height, p.doc.dpi, &icc, &pages, quality.min(100), inks.as_ref());+ write_atomically(Path::new(&path), |f| fs::write(f, &bytes).map_err(|e| file_error("saving", e)))+ }++ /// Each layer as a PNG in `dir` (made if missing), bottom first, named after it; returns+ /// their paths.+ pub fn export_layer_pngs(&self, dir: String) -> Result<Vec<String>, MobileError> {+ self.write_layer_pngs(dir, |_, _| true)+ }++ /// The current and picked layers (a group: the layers in it) each as a PNG in folder `dir`;+ /// returns the files' paths.+ pub fn export_chosen_pngs(&self, dir: String) -> Result<Vec<String>, MobileError> {+ self.write_layer_pngs(dir, |doc, id| doc.chosen().iter().any(|c| *c == id || doc.is_inside(id, *c)))+ }++ pub fn name(&self) -> String {+ self.shared.lock().name.clone()+ }++ /// When the artwork was made, its strokes, the time spent on it and its author.+ pub fn artwork_info(&self) -> ArtworkInfo {+ self.shared.lock().info.clone()+ }++ pub fn set_author(&self, name: String) {+ self.shared.lock().info.author = name.trim().chars().take(256).collect();+ }++ /// Adds time spent on the artwork (at most a day at once), milliseconds.+ pub fn add_tracked_time(&self, ms: u64) {+ let mut st = self.shared.lock();+ st.info.tracked_ms = st.info.tracked_ms.saturating_add(ms.min(24 * 3600 * 1000));+ }++ pub fn set_name(&self, name: String) -> bool {+ let name = name.trim();+ if name.is_empty() {+ return false;+ }+ self.shared.lock().name = name.chars().take(256).collect();+ true+ }+}++/// The table showing a CMYK canvas's colours as its press prints them (in Display P3, as its+/// pictures carry), if it is one.+fn proof_table(doc: &Document) -> Option<procraft_engine::cms::Lut> {+ use procraft_engine::cms::{Lut, builtin};+ let press = doc.press()?;+ Some(Lut::build(&doc.rgb_profile(), &builtin(procraft_engine::profile::Profile::DisplayP3), Some(&press), 33))+}++/// What a layered or print file of the canvas carries: the profile, and for a CMYK canvas the+/// table to its press's inks.+fn file_colours(doc: &Document) -> (Vec<u8>, Option<procraft_engine::cms::Lut>) {+ match doc.press() {+ Some(press) => {+ let inks = procraft_engine::cms::Lut::build(&doc.rgb_profile(), &press, None, 33);+ (press.bytes.to_vec(), Some(inks))+ }+ None => (doc.picture_icc(), None),+ }+}++/// What an export reads from the canvas, straight alpha: the flattened picture, and (if asked+/// for) every paint layer's pixels, every mask's grey and the background colour as a layer.+struct Pictures {+ width: u32,+ height: u32,+ doc: Document,+ composite: Vec<u8>,+ layers: std::collections::HashMap<LayerId, Vec<u8>>,+ masks: std::collections::HashMap<LayerId, Vec<u8>>,+ background: Vec<u8>,+}++impl CanvasSession {+ /// The layers `wanted` picks out each as a PNG in folder `dir`; returns the files' paths.+ fn write_layer_pngs(+ &self,+ dir: String,+ wanted: impl Fn(&Document, LayerId) -> bool,+ ) -> Result<Vec<String>, MobileError> {+ let p = self.pictures(true)?;+ let icc = p.doc.picture_icc();+ let proof = proof_table(&p.doc);+ let dir = PathBuf::from(dir);+ fs::create_dir_all(&dir).map_err(|e| file_error("making the folder", e))?;+ let mut paths = Vec::new();+ let mut used = std::collections::HashSet::new();+ for l in p.doc.layers() {+ if !wanted(&p.doc, l.id) {+ continue;+ }+ let Some(rgba) = p.layers.get(&l.id) else { continue };+ let base: String =+ l.name.chars().map(|c| if c.is_alphanumeric() || " _-".contains(c) { c } else { '_' }).collect();+ let base = if base.trim().is_empty() { "Layer".to_owned() } else { base.trim().to_owned() };+ let mut name = base.clone();+ let mut n = 2;+ while !used.insert(name.clone()) {+ name = format!("{base} {n}");+ n += 1;+ }+ let path = dir.join(format!("{name}.png"));+ let proofed = proof.as_ref().map(|table| {+ let mut px = rgba.clone();+ table.apply_rgba(&mut px, false);+ px+ });+ write_atomically(&path, |f| write_png(f, p.width, p.height, proofed.as_ref().unwrap_or(rgba), &icc))?;+ paths.push(path.to_string_lossy().into_owned());+ }+ Ok(paths)+ }++ fn pictures(&self, with_layers: bool) -> Result<Pictures, MobileError> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.finish_stroke();+ st.settle();+ let (Some(canvas), Some(gpu)) = (st.canvas.as_mut(), st.gpu.as_ref()) else {+ return Err(file_error("reading the picture", "the canvas is not shown yet"));+ };+ canvas.render(gpu, &mut st.doc, None);+ let composite = straight_alpha(&canvas.read_composite(gpu).map_err(|e| file_error("reading the picture", e))?);+ let mut layers = std::collections::HashMap::new();+ let mut masks = std::collections::HashMap::new();+ if with_layers {+ for l in st.doc.layers() {+ match l.kind {+ LayerKind::Paint => {+ let rgba = canvas.read_layer(gpu, l.id).map_err(|e| file_error("reading a layer", e))?;+ layers.insert(l.id, straight_alpha(&rgba));+ }+ LayerKind::Mask => {+ let rgba = canvas.read_layer(gpu, l.id).map_err(|e| file_error("reading a mask", e))?;+ masks.insert(l.id, rgba.as_chunks::<4>().0.iter().map(|&[r, ..]| r).collect());+ }+ LayerKind::Group => {}+ }+ }+ }+ let [r, g, b] = st.doc.background.map(|c| (c.clamp(0.0, 1.0) * 255.0).round() as u8);+ let (w, h) = (st.doc.width(), st.doc.height());+ let background = if with_layers { [r, g, b, 255].repeat(w as usize * h as usize) } else { Vec::new() };+ Ok(Pictures { width: w, height: h, doc: st.doc.clone(), composite, layers, masks, background })+ }+}++/// The PSD's layers, top first: groups as a start, their layers and an end; masks with their+/// layers; the background colour, when shown, at the bottom.+fn psd_layers(p: &Pictures) -> Vec<PsdLayer<'_>> {+ let doc = &p.doc;+ let end = || PsdLayer {+ name: "",+ kind: PsdKind::GroupEnd,+ opacity: 1.0,+ visible: true,+ blend: BlendMode::Normal,+ clipped: false,+ };+ let mut out = Vec::new();+ let mut open: Vec<LayerId> = Vec::new();+ for l in doc.layers().iter().rev() {+ if l.kind == LayerKind::Mask {+ continue;+ }+ while let Some(&g) = open.last() {+ if doc.is_inside(l.id, g) {+ break;+ }+ open.pop();+ out.push(end());+ }+ let kind = match l.kind {+ LayerKind::Group => {+ open.push(l.id);+ PsdKind::GroupStart { open: !l.collapsed }+ }+ _ => {+ let Some(rgba) = p.layers.get(&l.id) else { continue };+ let mask = doc+ .mask_of(l.id)+ .filter(|m| doc.layer(*m).is_some_and(|m| m.visible))+ .and_then(|m| p.masks.get(&m));+ PsdKind::Pixels { rgba, mask: mask.map(Vec::as_slice) }+ }+ };+ out.push(PsdLayer {+ name: &l.name,+ kind,+ opacity: l.opacity,+ visible: l.visible,+ blend: l.blend,+ clipped: l.clipped,+ });+ }+ for _ in open {+ out.push(end());+ }+ if doc.background_visible {+ out.push(PsdLayer {+ name: "Background",+ kind: PsdKind::Pixels { rgba: &p.background, mask: None },+ opacity: 1.0,+ visible: true,+ blend: BlendMode::Normal,+ clipped: false,+ });+ }+ out+}++fn layer_path(dir: &Path, id: LayerId) -> PathBuf {+ dir.join("layers").join(format!("{}.png", id.0))+}++/// Writes `path` by writing a temporary file beside it and renaming it into place.+pub(crate) fn write_atomically(+ path: &Path,+ write: impl FnOnce(&Path) -> Result<(), MobileError>,+) -> Result<(), MobileError> {+ // a name of its own, so that no other write of the same file can touch it+ static WRITES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);+ let n = WRITES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);+ let tmp = path.with_extension(format!("{}.tmp", n));+ write(&tmp)?;+ fs::rename(&tmp, path).map_err(|e| file_error("saving", e))+}++/// A PNG of RGBA8 pixels, carrying the colour profile `icc` (none if empty).+fn write_png(path: &Path, width: u32, height: u32, rgba: &[u8], icc: &[u8]) -> Result<(), MobileError> {+ let bytes = png_bytes(width, height, rgba, icc)?;+ fs::write(path, bytes).map_err(|e| file_error("saving", e))+}++/// A PNG of premultiplied RGBA8 pixels (as the GPU gives them), none on failure but empty.+pub(crate) fn rgba_png(width: u32, height: u32, premultiplied: &[u8]) -> Vec<u8> {+ png_bytes(width, height, &straight_alpha(premultiplied), &[]).unwrap_or_default()+}++/// A PNG of straight RGBA8 pixels, carrying `icc` if it isn't empty.+fn png_bytes(width: u32, height: u32, rgba: &[u8], icc: &[u8]) -> Result<Vec<u8>, MobileError> {+ let mut out = Vec::new();+ let mut info = png::Info::with_size(width, height);+ info.color_type = png::ColorType::Rgba;+ info.bit_depth = png::BitDepth::Eight;+ if !icc.is_empty() {+ info.icc_profile = Some(std::borrow::Cow::Borrowed(icc));+ }+ {+ let mut encoder = png::Encoder::with_info(&mut out, info).map_err(|e| file_error("saving", e))?;+ encoder.set_compression(png::Compression::Fast);+ let mut writer = encoder.write_header().map_err(|e| file_error("saving", e))?;+ writer.write_image_data(rgba).map_err(|e| file_error("saving", e))?;+ writer.finish().map_err(|e| file_error("saving", e))?;+ }+ Ok(out)+}++/// A PNG's RGBA8 pixels, which must be `width` × `height`.+fn read_png(path: &Path, width: u32, height: u32) -> Result<Vec<u8>, MobileError> {+ let file = fs::File::open(path).map_err(|e| file_error("opening a layer", e))?;+ let decoder = png::Decoder::new(BufReader::new(file));+ let mut reader = decoder.read_info().map_err(|e| file_error("opening a layer", e))?;+ let size = reader.output_buffer_size().ok_or_else(|| file_error("opening a layer", "too large"))?;+ let mut buf = vec![0; size];+ let info = reader.next_frame(&mut buf).map_err(|e| file_error("opening a layer", e))?;+ if info.width != width+ || info.height != height+ || info.color_type != png::ColorType::Rgba+ || info.bit_depth != png::BitDepth::Eight+ {+ return Err(file_error("opening a layer", format!("{}×{} {:?}", info.width, info.height, info.color_type)));+ }+ buf.truncate(info.buffer_size());+ Ok(buf)+}++/// Premultiplied RGBA8 pixels with straight alpha instead.+pub(crate) fn straight_alpha(rgba: &[u8]) -> Vec<u8> {+ let (pixels, _) = rgba.as_chunks::<4>();+ let mut out = Vec::with_capacity(rgba.len());+ for &[r, g, b, a] in pixels {+ let alpha = u32::from(a);+ let un = |c: u8| (u32::from(c) * 255 + alpha / 2).checked_div(alpha).map_or(0, |v| v.min(255) as u8);+ out.extend_from_slice(&[un(r), un(g), un(b), a]);+ }+ out+}++/// The picture scaled down (box filter) to fit `side`, straight alpha, for viewing elsewhere.+pub(crate) fn thumbnail(rgba: &[u8], width: u32, height: u32, side: u32) -> (u32, u32, Vec<u8>) {+ let scale = (side as f32 / width.max(height).max(1) as f32).min(1.0);+ let (tw, th) = (((width as f32 * scale).round() as u32).max(1), ((height as f32 * scale).round() as u32).max(1));+ let mut out = Vec::with_capacity((tw * th * 4) as usize);+ for ty in 0..th {+ let (y0, y1) = (ty * height / th, ((ty + 1) * height / th).max(ty * height / th + 1));+ for tx in 0..tw {+ let (x0, x1) = (tx * width / tw, ((tx + 1) * width / tw).max(tx * width / tw + 1));+ let mut sum = [0u32; 4];+ let mut n = 0u32;+ for y in y0..y1.min(height) {+ for x in x0..x1.min(width) {+ let i = ((y * width + x) * 4) as usize;+ if let Some(px) = rgba.get(i..i + 4) {+ for (s, v) in sum.iter_mut().zip(px) {+ *s += u32::from(*v);+ }+ n += 1;+ }+ }+ }+ let n = n.max(1);+ let [r, g, b, a] = sum.map(|s| s / n);+ // premultiplied to straight+ let un = |c: u32| (c * 255 + a / 2).checked_div(a).map_or(0, |v| v.min(255) as u8);+ out.extend_from_slice(&[un(r), un(g), un(b), a as u8]);+ }+ }+ (tw, th, out)+}diff --git a/apps/procraft-android/src/projection.rs b/apps/procraft-android/src/projection.rsnew file mode 100644index 0000000..74c3c67--- /dev/null+++ b/apps/procraft-android/src/projection.rs@@ -0,0 +1,49 @@+//! Project canvas: the whole picture, without the interface, on a second display.++use crate::{CanvasSession, MobileError};++#[uniffi::export]+impl CanvasSession {+ /// Shows the canvas fitted and centred on black in the window `window` (an id from+ /// `NativeWindows.acquire`), `width` × `height` pixels, on a second display. The session+ /// owns the window from here on.+ pub fn attach_projection(&self, window: u64, width: u32, height: u32) -> Result<(), MobileError> {+ self.detach_projection();+ #[cfg(target_os = "android")]+ {+ let native = crate::window::take(window)+ .ok_or_else(|| MobileError::Window { reason: format!("no window {window}") })?;+ {+ let mut st = self.shared.lock();+ st.projection_size = (width.max(1), height.max(1));+ st.projection_stop = false;+ }+ let shared = std::sync::Arc::clone(&self.shared);+ let handle = std::thread::Builder::new()+ .name("procraft-projection".to_owned())+ .spawn(move || crate::render::project(shared, native))+ .map_err(|e| MobileError::Window { reason: e.to_string() })?;+ *self.shared.projection.lock().unwrap_or_else(|e| e.into_inner()) = Some(handle);+ Ok(())+ }+ #[cfg(not(target_os = "android"))]+ {+ let _ = (width, height);+ Err(MobileError::Window { reason: format!("windows are Android-only (asked for {window})") })+ }+ }++ pub fn resize_projection(&self, width: u32, height: u32) {+ self.shared.lock().projection_size = (width.max(1), height.max(1));+ }++ /// Lets go of the second display's window; returns once its thread has finished.+ pub fn detach_projection(&self) {+ let handle = self.shared.projection.lock().unwrap_or_else(|e| e.into_inner()).take();+ if let Some(handle) = handle {+ self.shared.lock().projection_stop = true;+ let _ = handle.join();+ self.shared.lock().projection_stop = false;+ }+ }+}diff --git a/apps/procraft-android/src/quickshape.rs b/apps/procraft-android/src/quickshape.rsnew file mode 100644index 0000000..5c48a43--- /dev/null+++ b/apps/procraft-android/src/quickshape.rs@@ -0,0 +1,280 @@+//! QuickShape: a stroke drawn and held snaps to the shape it looks like, redrawn with the same+//! brush along the shape's outline. It stays open while it is edited (its kind changed, its+//! handles dragged) and is kept as drawn with the next thing done.++use procraft_engine::brush::Brush;+use procraft_engine::document::LayerId;+use procraft_engine::geom::Vec2;+use procraft_engine::input::Sample;+use procraft_engine::quickshape::{Shape, ShapeKind, recognise};+use procraft_engine::stroke::StrokeBuilder;+use procraft_gpu::StrokeStyle;++use crate::{CanvasSession, PointerKind, State};++#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]+pub enum QuickShapeKind {+ Line,+ Polyline,+ Arc,+ Ellipse,+ Circle,+ Triangle,+ EquilateralTriangle,+ Quadrilateral,+ Rectangle,+ Square,+}++impl From<ShapeKind> for QuickShapeKind {+ fn from(k: ShapeKind) -> QuickShapeKind {+ match k {+ ShapeKind::Line => QuickShapeKind::Line,+ ShapeKind::Polyline => QuickShapeKind::Polyline,+ ShapeKind::Arc => QuickShapeKind::Arc,+ ShapeKind::Ellipse => QuickShapeKind::Ellipse,+ ShapeKind::Circle => QuickShapeKind::Circle,+ ShapeKind::Triangle => QuickShapeKind::Triangle,+ ShapeKind::EquilateralTriangle => QuickShapeKind::EquilateralTriangle,+ ShapeKind::Quadrilateral => QuickShapeKind::Quadrilateral,+ ShapeKind::Rectangle => QuickShapeKind::Rectangle,+ ShapeKind::Square => QuickShapeKind::Square,+ }+ }+}++impl From<QuickShapeKind> for ShapeKind {+ fn from(k: QuickShapeKind) -> ShapeKind {+ match k {+ QuickShapeKind::Line => ShapeKind::Line,+ QuickShapeKind::Polyline => ShapeKind::Polyline,+ QuickShapeKind::Arc => ShapeKind::Arc,+ QuickShapeKind::Ellipse => ShapeKind::Ellipse,+ QuickShapeKind::Circle => ShapeKind::Circle,+ QuickShapeKind::Triangle => ShapeKind::Triangle,+ QuickShapeKind::EquilateralTriangle => ShapeKind::EquilateralTriangle,+ QuickShapeKind::Quadrilateral => ShapeKind::Quadrilateral,+ QuickShapeKind::Rectangle => ShapeKind::Rectangle,+ QuickShapeKind::Square => ShapeKind::Square,+ }+ }+}++/// The shape a stroke snapped to: its kind, the kinds it can be shown as instead (its own first),+/// and its editing handles (window points, x and y in turn).+#[derive(Clone, Debug, PartialEq, uniffi::Record)]+pub struct QuickShapeInfo {+ pub kind: QuickShapeKind,+ pub choices: Vec<QuickShapeKind>,+ pub handles: Vec<f32>,+}++/// A snapped stroke being shown and edited.+pub(crate) struct ShapeEdit {+ shape: Shape,+ choices: Vec<ShapeKind>,+ /// The stroke as drawn (canvas points), which other kinds are fitted to.+ drawn: Vec<Vec2>,+ pressure: f32,+}++/// A stroke as it began (and, once kept, what it drew), so that QuickShape can redraw it as a+/// shape after it has ended.+pub(crate) struct LastStroke {+ pub(crate) layer: LayerId,+ pub(crate) style: StrokeStyle,+ pub(crate) brush: Brush,+ pub(crate) diameter: f32,+ pub(crate) pointer: PointerKind,+ /// What it drew (canvas points) and its mean pressure.+ pub(crate) drawn: Vec<Vec2>,+ pub(crate) pressure: f32,+ /// The canvas's undo steps once it was kept: anything done since changes them.+ pub(crate) steps: u64,+}++/// The outline is redrawn with samples this far apart (canvas pixels) and this many milliseconds+/// apart.+const SAMPLE_STEP: f32 = 2.0;+const SAMPLE_MS: f64 = 2.0;++impl State {+ /// Notes a stroke's input, for QuickShape.+ pub(crate) fn remember_input(&mut self, samples: &[Sample]) {+ for s in samples.iter().filter(|s| s.is_finite()) {+ self.drawn.push(s.pos);+ self.drawn_pressure += s.pressure.clamp(0.0, 1.0);+ }+ }++ /// Redraws the open stroke along the shape's outline.+ fn draw_shape(&mut self) {+ let (Some(edit), Some(old)) = (self.shape.as_ref(), self.stroke.as_ref()) else { return };+ let mut brush = old.brush().clone();+ // the outline is already smooth: nothing should round its corners+ brush.streamline = 0.0;+ brush.set_setting("stabilization", 0.0);+ let mut builder = StrokeBuilder::with_seed(brush, old.diameter(), old.pointer(), 0x5eed_1234);+ let samples = resample(&edit.shape.outline(), edit.pressure);+ builder.add(&samples);+ let stamps = builder.finish();+ if let Some(canvas) = self.canvas.as_mut() {+ canvas.replace_stamps(&stamps);+ }+ self.stroke = Some(builder);+ }++ /// The stroke just kept is remembered, for QuickShape on the last stroke.+ pub(crate) fn remember_last_stroke(&mut self) {+ let Some(mut last) = self.began.take() else { return };+ // its step is made now, so that a later change shows against it+ self.flush();+ let Some(canvas) = self.canvas.as_ref() else { return };+ last.drawn = self.drawn.clone();+ last.pressure = self.mean_pressure();+ last.steps = canvas.steps_made();+ self.last_stroke = Some(last);+ }++ fn mean_pressure(&self) -> f32 {+ let p = if self.drawn.is_empty() { 1.0 } else { self.drawn_pressure / self.drawn.len() as f32 };+ p.max(0.05)+ }++ fn shape_info(&self) -> Option<QuickShapeInfo> {+ let edit = self.shape.as_ref()?;+ let view = self.view?;+ let to_screen = view.to_screen();+ Some(QuickShapeInfo {+ kind: edit.shape.kind.into(),+ choices: edit.choices.iter().map(|&k| k.into()).collect(),+ handles: edit+ .shape+ .handles()+ .into_iter()+ .flat_map(|p| {+ let w = to_screen.apply(p);+ [w.x, w.y]+ })+ .collect(),+ })+ }+}++/// Points `step` apart along `outline`, as stroke samples at `pressure`.+fn resample(outline: &[Vec2], pressure: f32) -> Vec<Sample> {+ let mut out = Vec::new();+ let mut t = 0.0f64;+ let mut push = |p: Vec2| {+ out.push(Sample::at(p, pressure, t));+ t += SAMPLE_MS;+ };+ let Some(&first) = outline.first() else { return Vec::new() };+ push(first);+ for w in outline.windows(2) {+ let [a, b] = w else { continue };+ let n = (a.distance(*b) / SAMPLE_STEP).ceil().max(1.0) as usize;+ for k in 1..=n {+ push(a.lerp(*b, k as f32 / n as f32));+ }+ }+ out+}++/// The outline (x and y in turn) of the shape a path of points (x and y in turn) looks like, if+/// any: a freehand selection held still snaps to it.+#[uniffi::export]+pub fn quickshape_outline(points: Vec<f32>) -> Option<Vec<f32>> {+ let path: Vec<Vec2> = points.as_chunks::<2>().0.iter().map(|&[x, y]| Vec2::new(x, y)).collect();+ let shape = recognise(&path).into_iter().next()?;+ Some(shape.outline().into_iter().flat_map(|p| [p.x, p.y]).collect())+}++#[uniffi::export]+impl CanvasSession {+ /// The stroke being drawn has been held still: it snaps to the shape it looks like, if any.+ pub fn quickshape_hold(&self) -> Option<QuickShapeInfo> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ if st.stroke.is_none() || st.shape.is_some() {+ return None;+ }+ let found = recognise(&st.drawn);+ let first = found.first()?.clone();+ let choices = found.iter().map(|s| s.kind).collect();+ st.shape = Some(ShapeEdit { shape: first, choices, drawn: st.drawn.clone(), pressure: st.mean_pressure() });+ st.began = None;+ st.draw_shape();+ self.shared.frame(st);+ st.shape_info()+ }++ /// The last stroke, if nothing has been done since it was kept, snaps to the shape it looks+ /// like: it comes off its layer and is redrawn along the shape, open to be edited as a held+ /// stroke is.+ pub fn quickshape_last(&self) -> Option<QuickShapeInfo> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ if st.stroke.is_some() || st.shape.is_some() {+ return None;+ }+ st.flush();+ let last = st.last_stroke.take()?;+ let canvas = st.canvas.as_mut()?;+ if canvas.steps_made() != last.steps || canvas.can_redo() {+ return None;+ }+ let found = recognise(&last.drawn);+ let first = found.first()?.clone();+ let choices = found.iter().map(|s| s.kind).collect();+ canvas.undo();+ canvas.begin_stroke(last.layer, last.style);+ st.stroke = Some(StrokeBuilder::with_seed(last.brush, last.diameter, last.pointer.into(), 0x5eed_1234));+ st.shape = Some(ShapeEdit { shape: first, choices, drawn: last.drawn, pressure: last.pressure });+ st.draw_shape();+ self.shared.frame(st);+ st.shape_info()+ }++ /// The snapped shape, while there is one.+ pub fn quickshape_info(&self) -> Option<QuickShapeInfo> {+ self.shared.lock().shape_info()+ }++ /// Shows the snapped shape as `kind` instead.+ pub fn quickshape_choose(&self, kind: QuickShapeKind) -> Option<QuickShapeInfo> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let edit = st.shape.as_mut()?;+ let current = edit.shape.kind;+ // a kind already shown keeps its edits; another is fitted to the stroke as drawn+ edit.shape = edit.shape.as_kind(kind.into(), &edit.drawn);+ if edit.shape.kind == current && ShapeKind::from(kind) != current {+ return st.shape_info();+ }+ st.draw_shape();+ self.shared.frame(st);+ st.shape_info()+ }++ /// Drags handle `index` of the snapped shape to window point (`x`, `y`).+ pub fn quickshape_move_handle(&self, index: u32, x: f32, y: f32) -> Option<QuickShapeInfo> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let to = st.view?.screen_to_canvas(Vec2::new(x, y))?;+ st.shape.as_mut()?.shape.move_handle(index as usize, to);+ st.draw_shape();+ self.shared.frame(st);+ st.shape_info()+ }++ /// Keeps the snapped shape as drawn.+ pub fn quickshape_done(&self) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ if st.shape.is_some() {+ st.finish_stroke();+ self.shared.frame(st);+ }+ }+}diff --git a/apps/procraft-android/src/render.rs b/apps/procraft-android/src/render.rsnew file mode 100644index 0000000..d186d70--- /dev/null+++ b/apps/procraft-android/src/render.rs@@ -0,0 +1,352 @@+//! The render thread: owns the window's surface and draws a frame whenever something changed.++use std::sync::Arc;+use std::time::{Duration, Instant};++use ndk::native_window::NativeWindow;+use procraft_engine::profile::Profile;+use procraft_engine::view::View;+use procraft_gpu::{Backdrop, Gpu, SelectionLook, Stripes, SurroundGrid, Target, wgpu};++use crate::selection::SelectionDisplay;+use crate::{+ BACKDROP_SIGMA_PT, GRID_LINE, GRID_SPACING_PT, GRID_TOP_PT, SELECTION_FILL, SELECTION_TINT, STRIPE_COVERAGE,+ STRIPE_PERIOD_PT, STRIPE_SPEED_PT, SURROUND, Shared,+};++pub(crate) fn run(shared: Arc<Shared>, window: NativeWindow) {+ let instance = shared.lock().gpu.as_ref().map_or_else(Gpu::instance, |g| g.instance.clone());+ let surface = match crate::window::create_surface(&instance, &window) {+ Ok(s) => s,+ Err(e) => return fail(&shared, e),+ };+ if shared.lock().gpu.is_none() {+ // the device is made once, for the first window, and kept with the layers it holds+ match Gpu::for_surface(instance, &surface) {+ Ok(gpu) => shared.lock().gpu = Some(gpu),+ Err(e) => return fail(&shared, e.to_string()),+ }+ }+ let queue = {+ let mut st = shared.lock();+ st.ensure_canvas();+ st.reconfigure = true;+ st.needs_frame = true;+ st.gpu.as_ref().map(|g| g.queue.clone())+ };+ let Some(queue) = queue else { return };++ let mut config: Option<wgpu::SurfaceConfiguration> = None;+ let mut last_present: Option<Instant> = None;+ let started = Instant::now();+ loop {+ let (size, reconfigure) = {+ let mut st = shared.lock();+ while !st.stop && !st.needs_frame {+ st = shared.wake.wait(st).unwrap_or_else(|e| e.into_inner());+ }+ if st.stop {+ break;+ }+ (st.window_size, std::mem::replace(&mut st.reconfigure, false))+ };+ if reconfigure || config.is_none() {+ let st = shared.lock();+ let Some(gpu) = st.gpu.as_ref() else { break };+ config = configure(gpu, &surface, size);+ }+ let Some(format) = config.as_ref().map(|c| c.format) else {+ std::thread::sleep(Duration::from_millis(16));+ continue;+ };+ let screen = config.as_ref().map_or(Profile::Srgb, screen_profile);+ // wait for the next image before looking at the input, so the frame shows the latest+ let frame = match surface.get_current_texture() {+ wgpu::CurrentSurfaceTexture::Success(f) => f,+ wgpu::CurrentSurfaceTexture::Suboptimal(f) => {+ shared.lock().reconfigure = true;+ f+ }+ wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {+ shared.lock().reconfigure = true;+ std::thread::sleep(Duration::from_millis(4));+ continue;+ }+ wgpu::CurrentSurfaceTexture::Timeout+ | wgpu::CurrentSurfaceTexture::Occluded+ | wgpu::CurrentSurfaceTexture::Validation => {+ std::thread::sleep(Duration::from_millis(4));+ continue;+ }+ };+ let view = frame.texture.create_view(&wgpu::TextureViewDescriptor::default());+ {+ let mut guard = shared.lock();+ let st = &mut *guard;+ // the window changed size while the image was awaited (the device turned): the view is+ // already for the new size, so this image is let go and the surface configured again+ if st.window_size != size {+ continue;+ }+ st.needs_frame = false;+ // the view settling into place keeps drawing until it is there+ if st.step_view_motion() {+ st.needs_frame = true;+ }+ let to_screen = st.view.map(|v| v.to_screen());+ if let (Some(canvas), Some(gpu), Some(to_screen)) = (st.canvas.as_mut(), st.gpu.as_ref(), to_screen) {+ let s = st.display_scale;+ let grid = SurroundGrid {+ spacing: GRID_SPACING_PT * s,+ origin: [0.0, GRID_TOP_PT * s],+ width: s,+ color: GRID_LINE,+ };+ // the bands over what is not selected drift, so they keep drawing+ let look = canvas.has_selection().then(|| match st.selection_display {+ SelectionDisplay::Stripes => {+ let period = STRIPE_PERIOD_PT * s;+ let drift = (started.elapsed().as_secs_f32() * STRIPE_SPEED_PT * s) % period;+ SelectionLook::Stripes(Stripes {+ period,+ drift,+ coverage: STRIPE_COVERAGE * st.selection_visibility,+ })+ }+ SelectionDisplay::Tint => SelectionLook::Tint(Profile::Srgb.convert(SELECTION_TINT, screen)),+ SelectionDisplay::Fill => SelectionLook::Fill(Profile::Srgb.convert(SELECTION_FILL, screen)),+ });+ let animating = matches!(look, Some(SelectionLook::Stripes(_)));+ let convert = colours_to(st.doc.profile, screen);+ // a canvas with a profile of its own shows through a table, made when that changes+ let key = crate::colour::table_key(&st.doc, screen);+ if st.display_lut.as_ref().map(|(k, _)| *k) != key {+ st.display_lut = key+ .zip(crate::colour::display_table(&st.doc, screen))+ .map(|(k, table)| (k, canvas.display_lut(gpu, &table)));+ }+ let lut = st.display_lut.as_ref().map(|(_, l)| l);+ let backdrop = (!st.backdrops.is_empty())+ .then(|| Backdrop { regions: &st.backdrops, sigma: BACKDROP_SIGMA_PT * s });+ canvas.render(+ gpu,+ &mut st.doc,+ Some(Target {+ view: &view,+ format,+ size,+ to_screen,+ surround: SURROUND,+ grid: Some(grid),+ selection: look,+ backdrop,+ convert,+ lut,+ }),+ );+ if animating {+ st.needs_frame = true;+ }+ // counted only when the canvas was drawn, so a first frame means the artwork shows+ st.frames += 1;+ }+ let now = Instant::now();+ if let Some(prev) = last_present {+ st.frame_interval_ms = now.duration_since(prev).as_secs_f32() * 1000.0;+ }+ last_present = Some(now);+ }+ queue.present(frame);+ }+ drop(surface);+ drop(window);+}++/// How often the second display looks for a new frame of the main window.+const PROJECTION_POLL: Duration = Duration::from_millis(8);++/// Project canvas's thread: the whole canvas fitted and centred on black on a second display,+/// drawn again after each frame of the main window.+pub(crate) fn project(shared: Arc<Shared>, window: NativeWindow) {+ // the device comes with the main window+ let instance = loop {+ {+ let st = shared.lock();+ if st.projection_stop {+ return;+ }+ if let Some(gpu) = st.gpu.as_ref() {+ break gpu.instance.clone();+ }+ }+ std::thread::sleep(Duration::from_millis(50));+ };+ let surface = match crate::window::create_surface(&instance, &window) {+ Ok(s) => s,+ Err(e) => return fail(&shared, e),+ };+ let Some(queue) = shared.lock().gpu.as_ref().map(|g| g.queue.clone()) else { return };+ let mut config: Option<wgpu::SurfaceConfiguration> = None;+ let mut size = (0, 0);+ let mut drawn: Option<u64> = None;+ loop {+ let (wanted, frames) = {+ let st = shared.lock();+ if st.projection_stop {+ break;+ }+ (st.projection_size, st.frames)+ };+ if wanted != size || config.is_none() {+ size = wanted;+ let st = shared.lock();+ let Some(gpu) = st.gpu.as_ref() else { break };+ config = configure(gpu, &surface, size);+ drawn = None;+ }+ let Some(format) = config.as_ref().map(|c| c.format) else {+ std::thread::sleep(Duration::from_millis(16));+ continue;+ };+ if drawn == Some(frames) {+ std::thread::sleep(PROJECTION_POLL);+ continue;+ }+ let frame = match surface.get_current_texture() {+ wgpu::CurrentSurfaceTexture::Success(f) | wgpu::CurrentSurfaceTexture::Suboptimal(f) => f,+ wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {+ config = None;+ std::thread::sleep(Duration::from_millis(4));+ continue;+ }+ wgpu::CurrentSurfaceTexture::Timeout+ | wgpu::CurrentSurfaceTexture::Occluded+ | wgpu::CurrentSurfaceTexture::Validation => {+ std::thread::sleep(Duration::from_millis(4));+ continue;+ }+ };+ let view = frame.texture.create_view(&wgpu::TextureViewDescriptor::default());+ {+ let mut guard = shared.lock();+ let st = &mut *guard;+ if st.projection_size != size {+ continue;+ }+ if let (Some(canvas), Some(gpu)) = (st.canvas.as_mut(), st.gpu.as_ref()) {+ let to_screen = View::fit((st.doc.width(), st.doc.height()), size).to_screen();+ let screen = config.as_ref().map_or(Profile::Srgb, screen_profile);+ let convert = colours_to(st.doc.profile, screen);+ let key = crate::colour::table_key(&st.doc, screen);+ if st.display_lut.as_ref().map(|(k, _)| *k) != key {+ st.display_lut = key+ .zip(crate::colour::display_table(&st.doc, screen))+ .map(|(k, table)| (k, canvas.display_lut(gpu, &table)));+ }+ let lut = st.display_lut.as_ref().map(|(_, l)| l);+ canvas.render(+ gpu,+ &mut st.doc,+ Some(Target {+ view: &view,+ format,+ size,+ to_screen,+ surround: [0.0; 3],+ grid: None,+ selection: None,+ backdrop: None,+ convert,+ lut,+ }),+ );+ }+ }+ drawn = Some(frames);+ queue.present(frame);+ }+ // the picture goes with the canvas: the display is left black+ if config.is_some()+ && let wgpu::CurrentSurfaceTexture::Success(frame) | wgpu::CurrentSurfaceTexture::Suboptimal(frame) =+ surface.get_current_texture()+ {+ let view = frame.texture.create_view(&wgpu::TextureViewDescriptor::default());+ if let Some(gpu) = shared.lock().gpu.as_ref() {+ let mut encoder =+ gpu.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("projection clear") });+ drop(encoder.begin_render_pass(&wgpu::RenderPassDescriptor {+ label: Some("projection clear"),+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {+ view: &view,+ depth_slice: None,+ resolve_target: None,+ ops: wgpu::Operations {+ load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),+ store: wgpu::StoreOp::Store,+ },+ })],+ depth_stencil_attachment: None,+ timestamp_writes: None,+ occlusion_query_set: None,+ multiview_mask: None,+ }));+ gpu.queue.submit([encoder.finish()]);+ }+ queue.present(frame);+ }+ drop(surface);+ drop(window);+}++fn fail(shared: &Shared, reason: String) {+ log::error!("render thread: {reason}");+ shared.lock().error = Some(reason);+}++/// Configures the surface for `size`: a format that doesn't re-encode sRGB, the lowest-latency+/// present mode on offer, and one frame in flight.+/// The profile a configured surface shows colours in.+fn screen_profile(config: &wgpu::SurfaceConfiguration) -> Profile {+ if config.color_space == wgpu::SurfaceColorSpace::DisplayP3 { Profile::DisplayP3 } else { Profile::Srgb }+}++/// The matrix moving a canvas's colours in `from` to `to`, if they differ.+fn colours_to(from: Profile, to: Profile) -> Option<[[f32; 3]; 3]> {+ (from.is_p3() != to.is_p3()).then(|| from.matrix_to(to))+}++fn configure(gpu: &Gpu, surface: &wgpu::Surface<'_>, size: (u32, u32)) -> Option<wgpu::SurfaceConfiguration> {+ let caps = surface.get_capabilities(&gpu.adapter);+ let format = caps.formats.iter().copied().find(|f| !f.is_srgb()).or_else(|| caps.formats.first().copied())?;++ let mut config = surface.get_default_config(&gpu.adapter, size.0.max(1), size.1.max(1))?;+ config.format = format;+ config.view_formats = Vec::new();+ config.present_mode = if caps.present_modes.contains(&wgpu::PresentMode::Mailbox) {+ wgpu::PresentMode::Mailbox+ } else {+ wgpu::PresentMode::Fifo+ };+ if caps.alpha_modes.contains(&wgpu::CompositeAlphaMode::Opaque) {+ config.alpha_mode = wgpu::CompositeAlphaMode::Opaque;+ }+ // wide colour where the screen takes it: the canvas is shown in Display P3+ let p3 = caps+ .format_capabilities+ .iter()+ .any(|f| f.format == format && f.color_spaces.contains(wgpu::SurfaceColorSpaces::DISPLAY_P3));+ if p3 {+ config.color_space = wgpu::SurfaceColorSpace::DisplayP3;+ }+ config.desired_maximum_frame_latency = 1;+ surface.configure(&gpu.device, &config);+ log::info!(+ "surface {}×{} {:?} {:?} {:?}",+ config.width,+ config.height,+ config.format,+ config.present_mode,+ config.color_space+ );+ Some(config)+}diff --git a/apps/procraft-android/src/selection.rs b/apps/procraft-android/src/selection.rsnew file mode 100644index 0000000..826ad9a--- /dev/null+++ b/apps/procraft-android/src/selection.rs@@ -0,0 +1,386 @@+//! Selections: shapes drawn on the window become a selection on the canvas, which painting keeps+//! inside, and which can be inverted, feathered, saved, filled or copied to a layer of its own.++use procraft_engine::geom::Vec2;+use procraft_engine::selection::{Combine, Mask, feather_radius};++use crate::{CanvasSession, State};++/// How a new shape joins the selection there is.+#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]+pub enum SelectionJoin {+ Add,+ Remove,+}++impl From<SelectionJoin> for Combine {+ fn from(j: SelectionJoin) -> Combine {+ match j {+ SelectionJoin::Add => Combine::Add,+ SelectionJoin::Remove => Combine::Remove,+ }+ }+}++/// How the selection shows: bands over what is not selected, or what is selected tinted (while+/// selecting by colour) or covered (while its threshold is being dragged).+#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]+pub enum SelectionDisplay {+ Stripes,+ Tint,+ Fill,+}++/// Points around an ellipse drawn as a polygon.+const ELLIPSE_POINTS: usize = 128;++impl State {+ /// Shows the selection on the canvas (or none when nothing is selected).+ fn show_selection(&mut self) {+ let mask = self.selection.as_ref().filter(|m| !m.is_empty());+ if let (Some(canvas), Some(gpu)) = (self.canvas.as_mut(), self.gpu.as_ref()) {+ canvas.set_selection(gpu, mask.map(|m| m.data.as_slice()));+ }+ if mask.is_none() {+ self.selection = None;+ }+ }++ /// The selection as it is now becomes one undo step, called `name`, that puts `before` back.+ pub(crate) fn record_selection(&mut self, before: Option<Mask>, name: &str) {+ self.finish_stroke();+ self.settle();+ if self.selection.as_ref().is_some_and(Mask::is_empty) {+ self.selection = None;+ }+ if self.selection == before {+ return;+ }+ let coverage = self.selection.as_ref().map(|m| m.data.as_slice());+ if let (Some(canvas), Some(gpu)) = (self.canvas.as_mut(), self.gpu.as_ref()) {+ canvas.name_next_step(name);+ canvas.change_selection(gpu, &mut self.doc, coverage, before.map(|m| m.data));+ self.revision += 1;+ }+ }++ /// Joins `shape` to the selection; `record` makes it an undo step (otherwise it is only shown,+ /// as while a colour threshold is dragged).+ fn join(&mut self, shape: Mask, how: SelectionJoin, record: bool) {+ self.feather_base = None;+ let before = self.selection.clone();+ match (self.selection.as_mut(), how) {+ (Some(m), _) => m.combine(&shape, how.into()),+ (None, SelectionJoin::Add) => self.selection = Some(shape),+ (None, SelectionJoin::Remove) => {}+ }+ if record {+ let name = match (how, before.is_some()) {+ (SelectionJoin::Remove, _) => "subtract from selection",+ (SelectionJoin::Add, true) => "add to selection",+ (SelectionJoin::Add, false) => "draw selection",+ };+ self.record_selection(before, name);+ } else {+ self.show_selection();+ }+ }++ /// Takes the selection back from the canvas (after an undo or redo).+ pub(crate) fn sync_selection(&mut self) {+ let (w, h) = (self.doc.width(), self.doc.height());+ self.selection =+ self.canvas.as_ref().and_then(|c| c.selection()).map(|c| Mask { width: w, height: h, data: c.to_vec() });+ self.feather_base = None;+ }++ /// Window points to canvas points.+ fn to_canvas_points(&self, window: &[Vec2]) -> Option<Vec<Vec2>> {+ let view = self.view?;+ window.iter().map(|&p| view.screen_to_canvas(p).filter(|c| c.is_finite())).collect()+ }++ /// The current layer's pixels, after any queued work.+ pub(crate) fn current_pixels(&mut self) -> Option<Vec<u8>> {+ self.finish_stroke();+ self.settle();+ self.flush();+ let current = self.doc.current();+ let (Some(canvas), Some(gpu)) = (self.canvas.as_mut(), self.gpu.as_ref()) else { return None };+ canvas.read_layer(gpu, current).ok()+ }+}++#[uniffi::export]+impl CanvasSession {+ /// A rectangle (or with `ellipse`, the ellipse in it) between window points (`x0`, `y0`) and+ /// (`x1`, `y1`) joins the selection. Drawn on the window, so it turns with the view.+ pub fn select_shape(&self, ellipse: bool, x0: f32, y0: f32, x1: f32, y1: f32, join: SelectionJoin) {+ let (a, b) = (Vec2::new(x0, y0), Vec2::new(x1, y1));+ let window: Vec<Vec2> = if ellipse {+ let (c, r) = (a.lerp(b, 0.5), (b - a) * 0.5);+ (0..ELLIPSE_POINTS)+ .map(|i| {+ let t = i as f32 / ELLIPSE_POINTS as f32 * std::f32::consts::TAU;+ Vec2::new(c.x + r.x * t.cos(), c.y + r.y * t.sin())+ })+ .collect()+ } else {+ vec![a, Vec2::new(b.x, a.y), b, Vec2::new(a.x, b.y)]+ };+ self.select_window_polygon(&window, join);+ }++ /// The polygon through window points `points` (x, y pairs) joins the selection.+ pub fn select_polygon(&self, points: Vec<f32>, join: SelectionJoin) {+ let window: Vec<Vec2> = points.as_chunks::<2>().0.iter().map(|&[x, y]| Vec2::new(x, y)).collect();+ self.select_window_polygon(&window, join);+ }++ /// Selects by colour: the pixels of the current layer joined to window point (`x`, `y`) whose+ /// colour is within `threshold` (0..1) of its colour join the selection. While `live` (the+ /// threshold being dragged) each call replaces the last one's shape; the last call is not live.+ pub fn select_by_colour(&self, x: f32, y: f32, threshold: f32, join: SelectionJoin, live: bool) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let Some(p) = st.view.and_then(|v| v.screen_to_canvas(Vec2::new(x, y))) else { return };+ let (w, h) = (st.doc.width(), st.doc.height());+ if !(p.x >= 0.0 && p.y >= 0.0 && p.x < w as f32 && p.y < h as f32) {+ return;+ }+ // the layer is read once for the whole drag+ let pixels = match st.colour_source.take() {+ Some(px) => px,+ None => {+ let Some(px) = st.current_pixels() else { return };+ st.selection_before = Some(st.selection.clone());+ px+ }+ };+ let shape = Mask::by_colour(w, h, &pixels, (p.x as u32, p.y as u32), threshold);+ let before = st.selection_before.clone().flatten();+ st.selection = before.clone();+ if live {+ st.join(shape, join, false);+ st.colour_source = Some(pixels);+ } else {+ // the drag ends: one step from before it+ st.join(shape, join, false);+ st.selection_before = None;+ st.record_selection(before, "Automatic Selection");+ }+ self.shared.frame(st);+ }++ /// Selection mask visibility, 0..1 (a quarter by default).+ pub fn set_selection_visibility(&self, visibility: f32) {+ let mut st = self.shared.lock();+ st.selection_visibility = if visibility.is_finite() { visibility.clamp(0.0, 1.0) } else { 0.25 };+ self.shared.frame(&mut st);+ }++ /// Brush scaling: relative to the screen (true) or to the canvas.+ pub fn set_brush_scaling(&self, on_screen: bool) {+ self.shared.lock().brush_on_screen = on_screen;+ }++ pub fn set_selection_display(&self, display: SelectionDisplay) {+ let mut st = self.shared.lock();+ st.selection_display = display;+ self.shared.frame(&mut st);+ }++ /// Selects what was not selected, and the other way round.+ pub fn select_invert(&self) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let (w, h) = (st.doc.width(), st.doc.height());+ let before = st.selection.clone();+ let mut m = st.selection.take().unwrap_or_else(|| Mask::empty(w, h));+ st.feather_base = None;+ m.invert();+ st.selection = Some(m);+ st.record_selection(before, "invert");+ self.shared.frame(st);+ }++ /// Softens the selection's edges by `amount` (0..1, the feather popover's): each call feathers+ /// the selection as it was before the first, until the selection is changed some other way.+ pub fn select_feather(&self, amount: f32) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let Some(current) = st.selection.clone() else { return };+ let mut m = st.feather_base.get_or_insert(current).clone();+ m.feather(feather_radius(amount));+ st.selection = Some(m);+ st.show_selection();+ self.shared.frame(st);+ }++ /// The feather popover closed: its feathering becomes one undo step.+ pub fn select_feather_done(&self) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ if let Some(base) = st.feather_base.take() {+ st.record_selection(Some(base), "feather");+ self.shared.frame(st);+ }+ }++ /// Selects nothing (painting goes anywhere again).+ pub fn select_none(&self) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let before = st.selection.take();+ st.feather_base = None;+ st.record_selection(before, "clear selection");+ self.shared.frame(st);+ }++ pub fn has_selection(&self) -> bool {+ self.shared.lock().selection.is_some()+ }++ /// Keeps the selection to load again later; returns how many are kept.+ pub fn save_selection(&self) -> u32 {+ let mut st = self.shared.lock();+ if let Some(m) = st.selection.clone() {+ st.saved_selections.push(m);+ }+ u32::try_from(st.saved_selections.len()).unwrap_or(u32::MAX)+ }++ /// Makes a kept selection the selection again.+ pub fn load_selection(&self, index: u32) -> bool {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let Some(m) = st.saved_selections.get(index as usize).cloned() else { return false };+ let before = st.selection.replace(m);+ st.feather_base = None;+ st.record_selection(before, "load selection");+ self.shared.frame(st);+ true+ }++ pub fn delete_saved_selection(&self, index: u32) {+ let mut st = self.shared.lock();+ if (index as usize) < st.saved_selections.len() {+ st.saved_selections.remove(index as usize);+ }+ }++ /// A kept selection as a small picture fitting `max_width` × `max_height`: white where it+ /// selects, black where it does not.+ pub fn saved_selection_thumbnail(+ &self,+ index: u32,+ max_width: u32,+ max_height: u32,+ ) -> Option<crate::layers::ThumbnailImage> {+ let st = self.shared.lock();+ let m = st.saved_selections.get(index as usize)?;+ let (w, h) = (m.width.max(1) as f32, m.height.max(1) as f32);+ let scale = (max_width.max(1) as f32 / w).min(max_height.max(1) as f32 / h);+ let (tw, th) = (((w * scale).round() as u32).max(1), ((h * scale).round() as u32).max(1));+ let mut rgba = Vec::with_capacity((tw * th * 4) as usize);+ for y in 0..th {+ for x in 0..tw {+ // the mean of the mask pixels this one covers, sampled on a small grid+ let mut sum = 0u32;+ for sy in 0..3 {+ for sx in 0..3 {+ let mx = ((x as f32 + (sx as f32 + 0.5) / 3.0) / scale) as u32;+ let my = ((y as f32 + (sy as f32 + 0.5) / 3.0) / scale) as u32;+ let i =+ (my.min(m.height.saturating_sub(1)) * m.width + mx.min(m.width.saturating_sub(1))) as usize;+ sum += u32::from(m.data.get(i).copied().unwrap_or(0));+ }+ }+ let v = (sum / 9) as u8;+ rgba.extend([v, v, v, 255]);+ }+ }+ Some(crate::layers::ThumbnailImage { width: tw, height: th, rgba })+ }++ pub fn saved_selection_count(&self) -> u32 {+ u32::try_from(self.shared.lock().saved_selections.len()).unwrap_or(u32::MAX)+ }++ /// Fills the selection on the current layer with the paint colour, as one undo step.+ pub fn fill_selection(&self) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let current = st.doc.current();+ if st.doc.layer(current).is_none_or(|l| l.locked) {+ return;+ }+ let Some(mask) = st.selection.clone() else { return };+ let Some(mut pixels) = st.current_pixels() else { return };+ let [r, g, b] = st.color.map(|c| c.clamp(0.0, 1.0));+ let alpha_lock = st.doc.layer(current).is_some_and(|l| l.alpha_lock);+ for (px, &m) in pixels.as_chunks_mut::<4>().0.iter_mut().zip(&mask.data) {+ let [pr, pg, pb, pa] = px;+ if m == 0 {+ continue;+ }+ // the colour over what is there, as much as is selected (only where there is paint,+ // with the alpha locked)+ let k = f32::from(m) / 255.0;+ let a = f32::from(*pa) / 255.0;+ let (cover, out_a) = if alpha_lock { (k * a, a) } else { (k, k + a * (1.0 - k)) };+ for (dst, src) in [(&mut *pr, r), (&mut *pg, g), (&mut *pb, b)] {+ *dst = to_byte(src * cover + f32::from(*dst) / 255.0 * (1.0 - k));+ }+ *pa = to_byte(out_a);+ }+ if let Some(canvas) = st.canvas.as_mut() {+ canvas.write_layer(current, pixels);+ st.flush();+ st.revision += 1;+ self.shared.frame(st);+ }+ }++ /// Copies what is selected on the current layer to a new layer above it, made current;+ /// returns its id.+ pub fn copy_selection_to_layer(&self) -> Option<u64> {+ let pixels = {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let mask = st.selection.clone()?;+ let mut pixels = st.current_pixels()?;+ for (px, &m) in pixels.as_chunks_mut::<4>().0.iter_mut().zip(&mask.data) {+ let k = u16::from(m);+ for c in px.iter_mut() {+ *c = ((u16::from(*c) * k + 127) / 255) as u8;+ }+ }+ pixels+ };+ let id = self.add_layer();+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ if let (Some(canvas), Some(gpu)) = (st.canvas.as_mut(), st.gpu.as_ref()) {+ let _ = canvas.upload_layer(gpu, procraft_engine::document::LayerId(id), &pixels);+ }+ st.revision += 1;+ self.shared.frame(st);+ Some(id)+ }+}++impl CanvasSession {+ fn select_window_polygon(&self, window: &[Vec2], join: SelectionJoin) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let Some(points) = st.to_canvas_points(window) else { return };+ let shape = Mask::polygon(st.doc.width(), st.doc.height(), &points);+ st.join(shape, join, true);+ self.shared.frame(st);+ }+}++fn to_byte(v: f32) -> u8 {+ (v.clamp(0.0, 1.0) * 255.0).round() as u8+}diff --git a/apps/procraft-android/src/studio.rs b/apps/procraft-android/src/studio.rsnew file mode 100644index 0000000..75e75fd--- /dev/null+++ b/apps/procraft-android/src/studio.rs@@ -0,0 +1,612 @@+//! The brush studio: the brush the current tool uses, edited control by control while the studio+//! is open (strokes and previews use it as it is), kept or put back when it closes.++use procraft_engine::brush::{Brush, ResetPoint, Source};+use procraft_engine::curve::Curve;+use procraft_engine::geom::Vec2;+use procraft_engine::textures;++use crate::{CanvasSession, State};++/// The curve through `points` (x, y pairs on the unit square) at `count` (2 to 1024) evenly+/// spaced x from 0 to 1: the curve as strokes apply it, for drawing.+#[uniffi::export]+pub fn curve_samples(points: Vec<f32>, count: u32) -> Vec<f32> {+ let pts: Vec<Vec2> = points.as_chunks::<2>().0.iter().map(|&[x, y]| Vec2::new(x, y)).collect();+ let curve = Curve::new(&pts);+ let n = count.clamp(2, 1024);+ (0..n).map(|i| curve.eval(i as f32 / (n - 1) as f32)).collect()+}++/// A shipped shape or grain image: its name and its pixels (`TEXTURE_SIZE` square greyscale,+/// white = paint).+#[derive(Clone, Debug, PartialEq, uniffi::Record)]+pub struct SourceImage {+ pub name: String,+ pub pixels: Vec<u8>,+}++/// The shipped shape images (or, `grain`, grain images), in order: the source library.+#[uniffi::export]+pub fn source_library(grain: bool) -> Vec<SourceImage> {+ let images = if grain { textures::grains() } else { textures::shapes() };+ images.into_iter().map(|i| SourceImage { name: i.name.to_owned(), pixels: i.pixels }).collect()+}++/// `pixels` (a `source_size` square greyscale image) made to repeat without seams: the grain+/// editor's Auto repeat, the image `scale` times across (1 to 4), turned `rotation_degrees`,+/// faded at its edges over `overlap` of the way in (0..1) as sharply as `hardness` (0..1), into+/// its shifted copy, turned round with `mirror`, fine detail apart with `pyramid`.+#[uniffi::export]+pub fn repeatable_source(+ pixels: Vec<u8>,+ scale: f32,+ rotation_degrees: f32,+ overlap: f32,+ hardness: f32,+ mirror: bool,+ pyramid: bool,+) -> Vec<u8> {+ let repeat =+ textures::Repeat { scale, rotation: rotation_degrees.to_radians(), overlap, hardness, mirror, pyramid };+ textures::repeatable(&pixels, repeat)+}++/// The edge of a shape or grain image, pixels.+#[uniffi::export]+pub fn source_size() -> u32 {+ textures::TEXTURE_SIZE as u32+}++/// One brush's changes from how it ships, as earlier versions kept them: where it is in the+/// library, its name, the controls that differ and, if it differs, its pressure curve.+#[derive(serde::Serialize, serde::Deserialize)]+struct BrushChange {+ set: usize,+ index: usize,+ name: String,+ settings: std::collections::BTreeMap<String, f32>,+ #[serde(default)]+ curve: Vec<[f32; 2]>,+}++impl State {+ /// The brush being edited.+ fn studio_brush(&mut self) -> Option<&mut Brush> {+ let ((set, index), _) = self.studio.as_ref()?;+ let (set, index) = (*set, *index);+ self.library.get_mut(set)?.brushes.get_mut(index)+ }++ /// The brush being edited, about to change: its preview is drawn afresh from now on.+ fn studio_change(&mut self) -> Option<&mut Brush> {+ let brush = self.studio_brush()?;+ brush.thumbnail = None;+ Some(brush)+ }+}++#[uniffi::export]+impl CanvasSession {+ /// Opens the studio on the brush the current tool uses (a studio already open is kept);+ /// returns the brush's name.+ pub fn studio_begin(&self) -> String {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.finish_stroke();+ let at = st.brush_ref(st.tool);+ if st.studio.is_none() {+ // the first time in the studio sets the brush aside, to go back to+ if let Some(brush) = st.library.get_mut(at.0).and_then(|s| s.brushes.get_mut(at.1))+ && brush.reset_point.is_none()+ {+ brush.reset_point = Some(ResetPoint::of(brush, now()));+ }+ st.studio = Some((at, st.brush(st.tool).clone()));+ }+ st.brush(st.tool).name.clone()+ }++ /// Who made the brush being edited, and when its reset point was made.+ pub fn studio_about(&self) -> StudioAbout {+ let mut st = self.shared.lock();+ let Some(brush) = st.studio_brush() else {+ return StudioAbout { author: String::new(), picture: None, signature: None, reset_made: None };+ };+ let author = brush.author.as_ref();+ StudioAbout {+ author: author.map_or_else(String::new, |a| a.name.clone()),+ picture: author.and_then(|a| a.picture.as_deref()).map(<[u8]>::to_vec),+ signature: author.and_then(|a| a.signature.as_deref()).map(<[u8]>::to_vec),+ reset_made: brush.reset_point.as_ref().map(|r| r.made),+ }+ }++ /// Sets the brush being edited aside as it is now, for resetting it to go back to.+ pub fn studio_new_reset_point(&self) {+ let mut st = self.shared.lock();+ if let Some(brush) = st.studio_brush() {+ brush.reset_point = Some(ResetPoint::of(brush, now()));+ }+ }++ /// The values the controls `keys` show (see `procraft_engine::studio`).+ pub fn studio_settings(&self, keys: Vec<String>) -> Vec<f32> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let Some(brush) = st.studio_brush() else { return vec![0.0; keys.len()] };+ keys.iter().map(|k| brush.setting(k)).collect()+ }++ /// Moves the control `key` to `value`.+ pub fn set_studio_setting(&self, key: String, value: f32) {+ let mut st = self.shared.lock();+ if let Some(brush) = st.studio_change() {+ brush.set_setting(&key, value);+ }+ }++ /// The image the brush's shape (or, `grain`, its grain) uses now: its own, else the shipped+ /// one (`source_size` square greyscale, white = paint); empty for the round tip, or no grain.+ pub fn studio_source(&self, grain: bool) -> Vec<u8> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let Some(brush) = st.studio_brush() else { return Vec::new() };+ let (own, shipped) =+ if grain { (&brush.grain.source, brush.grain.image) } else { (&brush.shape.source, brush.shape.image) };+ if let Some(source) = own {+ return source.pixels.to_vec();+ }+ let images = if grain { textures::grains() } else { textures::shapes() };+ shipped.and_then(|i| images.into_iter().nth(i as usize)).map_or_else(Vec::new, |i| i.pixels)+ }++ /// The brush's shape (or, `grain`, grain) becomes an image of the user's own (`source_size`+ /// square greyscale, white = paint). False if the pixels aren't that size.+ pub fn set_studio_source(&self, grain: bool, pixels: Vec<u8>) -> bool {+ let Some(source) = Source::new(pixels) else { return false };+ let mut st = self.shared.lock();+ let Some(brush) = st.studio_change() else { return false };+ // an image of the user's own: no longer the stock one its file named+ if grain {+ brush.grain.source = Some(source);+ brush.stock.grain = None;+ } else {+ brush.shape.source = Some(source);+ brush.stock.shape = None;+ }+ true+ }++ /// The brush's shape (or, `grain`, grain) becomes shipped image `index` of the source library.+ pub fn set_studio_shipped_source(&self, grain: bool, index: u32) -> bool {+ let count = if grain { textures::grains().len() } else { textures::shapes().len() };+ if index as usize >= count {+ return false;+ }+ let mut st = self.shared.lock();+ let Some(brush) = st.studio_change() else { return false };+ if grain {+ brush.grain.source = None;+ brush.grain.image = Some(index);+ brush.stock.grain = None;+ } else {+ brush.shape.source = None;+ brush.shape.image = Some(index);+ brush.stock.shape = None;+ }+ true+ }++ /// The pressure curve's points, as x, y pairs (0..1).+ pub fn studio_curve(&self) -> Vec<f32> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.studio_brush().map_or_else(Vec::new, |b| b.pressure_curve.points().iter().flat_map(|p| [p.x, p.y]).collect())+ }++ /// The pressure curve through `points` (x, y pairs, 0..1).+ pub fn set_studio_curve(&self, points: Vec<f32>) {+ let pts: Vec<Vec2> = points.as_chunks::<2>().0.iter().map(|&[x, y]| Vec2::new(x, y)).collect();+ let mut st = self.shared.lock();+ if pts.len() >= 2+ && let Some(brush) = st.studio_change()+ {+ brush.pressure_curve = Curve::new(&pts);+ }+ }++ /// The app's own smoothing and pressure for every stroke, each 0..1, and its pressure curve+ /// (x, y pairs, 0..1; fewer than two points keep it straight).+ pub fn set_input_settings(+ &self,+ stabilization: f32,+ motion_filtering: f32,+ motion_expression: f32,+ pressure_smoothing: f32,+ curve: Vec<f32>,+ ) {+ let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };+ let pts: Vec<Vec2> = curve.as_chunks::<2>().0.iter().map(|&[x, y]| Vec2::new(unit(x), unit(y))).collect();+ let mut st = self.shared.lock();+ st.input = procraft_engine::stroke::InputSettings {+ stabilization: unit(stabilization),+ motion_filtering: unit(motion_filtering),+ motion_expression: unit(motion_expression),+ pressure_smoothing: unit(pressure_smoothing),+ pressure_curve: if pts.len() >= 2 { Curve::new(&pts) } else { Curve::linear() },+ speed_distance: st.input.speed_distance,+ };+ }++ /// How far input must move for the speed dynamics to count it as fast, as a part of the usual+ /// distance (0.25 to 1).+ pub fn set_speed_distance(&self, part: f32) {+ self.shared.lock().input.speed_distance = if part.is_finite() { part.clamp(0.25, 1.0) } else { 1.0 };+ }++ /// The brush back to how it started: as it ships, or as a new brush is (its name kept).+ pub fn studio_reset(&self) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let Some(((set, index), _)) = st.studio.as_ref() else { return };+ let (set, index) = (*set, *index);+ let origin = st.library.get(set).and_then(|s| s.origins.get(index)).copied().flatten();+ let start = st.origin_brush(origin);+ if let Some(brush) = st.studio_brush() {+ let name = std::mem::take(&mut brush.name);+ let reset = brush.reset_point.take();+ // back to its reset point, else to how it started+ let back = reset.as_ref().map_or(start, |r| (*r.brush).clone());+ *brush = Brush { name, reset_point: reset, ..back };+ }+ }++ /// Paints with the brush `other` has open in its studio (else its current tool's brush), as+ /// big as its preview size and in `color` (sRGB 0..1): for a drawing pad.+ pub fn paint_like(&self, other: std::sync::Arc<CanvasSession>, r: f32, g: f32, b: f32) {+ let brush = {+ let st = other.shared.lock();+ let (set, index) = st.studio.as_ref().map_or_else(|| st.brush_ref(st.tool), |(at, _)| *at);+ st.library.get(set).and_then(|s| s.brushes.get(index)).cloned()+ };+ let Some(brush) = brush else { return };+ let mut st = self.shared.lock();+ st.finish_stroke();+ st.tool = crate::ToolKind::Paint;+ // the size slider's place for the size the pad draws at+ let size = procraft_engine::preview::pad_size_share(&brush).powf(1.0 / procraft_engine::brush::SIZE_CURVE);+ let (set, index) = st.paint_brush;+ if let Some(slot) = st.library.get_mut(set).and_then(|s| s.brushes.get_mut(index)) {+ *slot = brush;+ }+ let sliders = st.sliders_mut();+ sliders.size = size;+ sliders.opacity = 1.0;+ st.color = [r, g, b].map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 1.0 });+ }++ /// Starts keeping this canvas's strokes, to draw them again as the brush changes (the brush+ /// studio's drawing pad).+ pub fn keep_strokes(&self) {+ let mut st = self.shared.lock();+ if st.pad_strokes.is_none() {+ st.pad_strokes = Some(Vec::new());+ }+ }++ /// Draws the kept strokes again on a cleared layer, with the brush as it is now.+ pub fn replay_strokes(&self) {+ let strokes = {+ let mut st = self.shared.lock();+ match st.pad_strokes.as_mut() {+ Some(kept) => std::mem::take(kept),+ None => return,+ }+ };+ self.clear_layer();+ // drawn as they were, they are kept again as they go+ for (pointer, input) in strokes {+ if input.is_empty() {+ continue;+ }+ self.stroke_begin(pointer, input);+ self.stroke_end(Vec::new());+ }+ }++ /// Forgets the kept strokes (the pad cleared).+ pub fn forget_strokes(&self) {+ let mut st = self.shared.lock();+ if let Some(kept) = st.pad_strokes.as_mut() {+ kept.clear();+ }+ st.pad_sample = false;+ }++ /// Draws the pad's sample scribble across it, kept like a stroke until one's own replaces it.+ pub fn draw_sample_scribble(&self) {+ {+ let mut st = self.shared.lock();+ let (w, h) = (st.doc.width() as f32, st.doc.height() as f32);+ let scale = st.display_scale;+ st.pad_strokes = Some(vec![(crate::PointerKind::Stylus, pad_scribble(w, h, scale))]);+ st.pad_sample = true;+ }+ self.replay_strokes();+ }++ /// A stroke of one's own starts on the pad: its sample scribble goes, if it is still there.+ pub fn begin_own_stroke(&self) {+ let sample = std::mem::replace(&mut self.shared.lock().pad_sample, false);+ if sample {+ self.forget_strokes();+ self.clear_layer();+ }+ }++ /// Applies brush changes kept by earlier versions (to the library as it ships); anything it+ /// cannot read is skipped.+ pub fn apply_brush_changes(&self, json: String) {+ let Ok(changes) = serde_json::from_str::<Vec<BrushChange>>(&json) else { return };+ let mut st = self.shared.lock();+ for c in changes {+ let Some(brush) = st.library.get_mut(c.set).and_then(|s| s.brushes.get_mut(c.index)) else { continue };+ if !c.name.is_empty() {+ brush.name = c.name;+ }+ brush.set_settings(c.settings.iter().map(|(k, v)| (k.as_str(), *v)));+ if c.curve.len() >= 2 {+ let pts: Vec<Vec2> = c.curve.iter().map(|&[x, y]| Vec2::new(x, y)).collect();+ brush.pressure_curve = Curve::new(&pts);+ }+ }+ }++ /// Closes the studio: `keep` keeps the edits, otherwise the brush goes back to how it opened.+ pub fn studio_end(&self, keep: bool) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let Some(((set, index), before)) = st.studio.take() else { return };+ if !keep && let Some(brush) = st.library.get_mut(set).and_then(|s| s.brushes.get_mut(index)) {+ // a reset point made meanwhile stays+ let reset = brush.reset_point.take();+ *brush = Brush { reset_point: reset, ..before };+ }+ }+}++/// The studio's About page: who made the brush ("" for ProCraft's own) with their picture and+/// signature (PNG) if it has them, and when its reset point was made (seconds since 1970).+#[derive(uniffi::Record)]+pub struct StudioAbout {+ pub author: String,+ pub picture: Option<Vec<u8>>,+ pub signature: Option<Vec<u8>>,+ pub reset_made: Option<i64>,+}++/// Now, in seconds since 1970.+fn now() -> i64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX))+}++/// The drawing pad's sample scribble, in points from the pad's middle: a light lead-in up to the+/// top, then a steep zigzag down the pad whose swings shrink as it goes, ending in a small hook to+/// the right. The path runs smoothly through these points. It is the same size whatever the pad's+/// (as the reference's, which runs off a portrait pad's top and fits a landscape one).+const SCRIBBLE: [(f32, f32); 41] = [+ (-147.0, -7.5),+ (-104.0, -66.5),+ (-44.0, -140.5),+ (15.5, -206.0),+ (88.5, -264.0),+ (112.0, -269.5),+ (116.0, -259.0),+ (97.0, -220.0),+ (55.5, -162.5),+ (-16.0, -61.5),+ (-57.0, 5.0),+ (-91.0, 83.5),+ (-81.0, 82.0),+ (-67.0, 66.5),+ (-10.0, -7.0),+ (42.5, -67.0),+ (113.0, -124.0),+ (133.5, -129.5),+ (136.0, -120.5),+ (97.0, -56.0),+ (78.5, -28.5),+ (38.0, 33.5),+ (-7.5, 110.0),+ (-36.0, 180.5),+ (-27.0, 180.0),+ (-6.5, 158.0),+ (30.5, 111.0),+ (68.0, 65.5),+ (117.5, 27.0),+ (125.0, 31.5),+ (86.0, 109.5),+ (70.0, 135.5),+ (27.0, 216.5),+ (77.5, 164.5),+ (113.5, 128.5),+ (130.0, 121.5),+ (133.5, 132.0),+ (117.0, 179.0),+ (100.0, 239.0),+ (109.0, 255.0),+ (130.5, 264.5),+];++/// How hard the sample scribble is pressed along its length (the share of the way, the pressure):+/// the pen's own pressure doubled (a preview's pressure is the pen's times 2.04, past any pressure+/// curve), so lightly through the lead-in, about 0.8 on the strokes back up, nearly full on those+/// down to the left, lighter through the sharpest turn, letting go over the end.+const SCRIBBLE_PRESSURE: [(f32, f32); 41] = [+ (0.0, 0.093),+ (0.025, 0.115),+ (0.05, 0.122),+ (0.075, 0.15),+ (0.1, 0.202),+ (0.125, 0.28),+ (0.15, 0.373),+ (0.175, 0.365),+ (0.2, 0.504),+ (0.225, 0.637),+ (0.25, 0.735),+ (0.275, 0.827),+ (0.3, 0.889),+ (0.325, 0.904),+ (0.35, 0.875),+ (0.375, 0.776),+ (0.4, 0.785),+ (0.425, 0.797),+ (0.45, 0.798),+ (0.475, 0.792),+ (0.5, 0.691),+ (0.525, 0.688),+ (0.55, 0.822),+ (0.575, 0.913),+ (0.6, 0.969),+ (0.625, 0.99),+ (0.65, 0.943),+ (0.675, 0.789),+ (0.7, 0.789),+ (0.725, 0.841),+ (0.75, 0.883),+ (0.775, 0.798),+ (0.8, 0.802),+ (0.825, 0.808),+ (0.85, 0.836),+ (0.875, 0.656),+ (0.9, 0.601),+ (0.925, 0.568),+ (0.95, 0.587),+ (0.975, 0.414),+ (1.0, 0.0),+];++/// How far through its time the sample scribble is along its length (the share of the way, the+/// share of the time): quick through the middle, slower into its first turns and out of its last,+/// over [`SCRIBBLE_SECONDS`].+const SCRIBBLE_PACE: [(f32, f32); 21] = [+ (0.0, 0.0),+ (0.05, 0.0845),+ (0.1, 0.1242),+ (0.15, 0.1636),+ (0.2, 0.2329),+ (0.25, 0.2603),+ (0.3, 0.2834),+ (0.35, 0.3212),+ (0.4, 0.3899),+ (0.45, 0.4197),+ (0.5, 0.4606),+ (0.55, 0.5162),+ (0.6, 0.5415),+ (0.65, 0.572),+ (0.7, 0.6403),+ (0.75, 0.6728),+ (0.8, 0.7349),+ (0.85, 0.7673),+ (0.9, 0.8363),+ (0.95, 0.907),+ (1.0, 1.0),+];++/// How long the sample scribble takes to draw.+const SCRIBBLE_SECONDS: f64 = 1.013;++/// `table`'s value `t` of the way along the sample scribble, in a straight line between its points.+fn along(table: &[(f32, f32)], t: f32) -> f32 {+ let mut before = (0.0, 0.0);+ for &(at, p) in table {+ if t <= at {+ let (b, q) = before;+ return if at > b { q + (p - q) * (t - b) / (at - b) } else { p };+ }+ before = (at, p);+ }+ before.1+}++/// The sample scribble's pressure `t` of the way along it.+fn scribble_pressure(t: f32) -> f32 {+ along(&SCRIBBLE_PRESSURE, t)+}++/// The drawing pad's sample scribble on a pad `w` x `h` (canvas pixels, the pad's window, `scale`+/// pixels a point): a smooth path through [`SCRIBBLE`] drawn at [`SCRIBBLE_PACE`], pressed as+/// [`SCRIBBLE_PRESSURE`] says.+fn pad_scribble(w: f32, h: f32, scale: f32) -> Vec<crate::PenSample> {+ const STEPS: usize = 1200;+ let turns: Vec<Vec2> = SCRIBBLE.iter().map(|&(x, y)| Vec2::new(w / 2.0 + x * scale, h / 2.0 + y * scale)).collect();+ let path = evenly(&through(&turns, 24), STEPS);+ path.iter()+ .enumerate()+ .map(|(i, p)| {+ let t = i as f32 / STEPS as f32;+ crate::PenSample {+ x: p.x,+ y: p.y,+ pressure: scribble_pressure(t),+ tilt: 0.0,+ orientation: 0.0,+ time_ms: f64::from(along(&SCRIBBLE_PACE, t)) * SCRIBBLE_SECONDS * 1000.0,+ }+ })+ .collect()+}++/// A smooth path through `points` (centripetal Catmull-Rom, so no loops or overshoots at sharp+/// turns), `per` points to each span.+fn through(points: &[Vec2], per: usize) -> Vec<Vec2> {+ let (Some(&first), Some(&last)) = (points.first(), points.last()) else { return Vec::new() };+ // the ends carried on straight, to lead in and out+ let lead = |end: Vec2, next: Option<&Vec2>| next.map_or(end, |&n| end + (end - n));+ let mut all = vec![lead(first, points.get(1))];+ all.extend_from_slice(points);+ all.push(lead(last, points.len().checked_sub(2).and_then(|i| points.get(i))));+ let mut out = vec![first];+ for w in all.windows(4) {+ let &[p0, p1, p2, p3] = w else { continue };+ // knots spaced by the root of each span's length+ let knot = |a: Vec2, b: Vec2| a.distance(b).sqrt().max(1e-3);+ let (t1, t2, t3) = (knot(p0, p1), knot(p0, p1) + knot(p1, p2), knot(p0, p1) + knot(p1, p2) + knot(p2, p3));+ for k in 1..=per {+ let t = t1 + (t2 - t1) * k as f32 / per as f32;+ let a1 = p0.lerp(p1, t / t1);+ let a2 = p1.lerp(p2, (t - t1) / (t2 - t1));+ let a3 = p2.lerp(p3, (t - t2) / (t3 - t2));+ let b1 = a1.lerp(a2, t / t2);+ let b2 = a2.lerp(a3, (t - t1) / (t3 - t1));+ out.push(b1.lerp(b2, (t - t1) / (t2 - t1)));+ }+ }+ out+}++/// `steps` + 1 points evenly spaced along `path`.+fn evenly(path: &[Vec2], steps: usize) -> Vec<Vec2> {+ let mut lengths = vec![0.0f32];+ for w in path.windows(2) {+ let &[a, b] = w else { continue };+ let so_far = lengths.last().copied().unwrap_or(0.0);+ lengths.push(so_far + a.distance(b));+ }+ let total = lengths.last().copied().unwrap_or(0.0);+ let mut at = 0;+ (0..=steps)+ .filter_map(|i| {+ let want = total * i as f32 / steps.max(1) as f32;+ while at + 2 < lengths.len() && lengths.get(at + 1).is_some_and(|&l| l < want) {+ at += 1;+ }+ let (&a, &b) = (path.get(at)?, path.get(at + 1).or(path.get(at))?);+ let (la, lb) = (lengths.get(at).copied()?, lengths.get(at + 1).copied().unwrap_or(total));+ Some(a.lerp(b, if lb > la { (want - la) / (lb - la) } else { 0.0 }))+ })+ .collect()+}diff --git a/apps/procraft-android/src/tests.rs b/apps/procraft-android/src/tests.rsnew file mode 100644index 0000000..cd90af0--- /dev/null+++ b/apps/procraft-android/src/tests.rs@@ -0,0 +1,2369 @@+//! The session on the host: input in window pixels → strokes → pixels, on a headless GPU.++use procraft_engine::view::View;+use procraft_gpu::Gpu;++use crate::{CanvasSession, PenSample, PointerKind, ToolKind};++fn sample(x: f32, y: f32, t: f64) -> PenSample {+ PenSample { x, y, pressure: 1.0, tilt: 0.0, orientation: 0.0, time_ms: t }+}++/// A session on a headless GPU with a `window` × `window` "screen", or `None` without a GPU.+fn session(canvas: u32, window: u32) -> Option<std::sync::Arc<CanvasSession>> {+ let gpu = match Gpu::headless() {+ Ok(g) => g,+ Err(e) => {+ eprintln!("skipped: {e}");+ return None;+ }+ };+ let s = CanvasSession::new(canvas, canvas);+ {+ let mut st = s.shared.lock();+ st.window_size = (window, window);+ st.view = Some(View::fit((canvas, canvas), (window, window)));+ st.gpu = Some(gpu);+ st.ensure_canvas();+ }+ Some(s)+}++/// Renders what is queued and returns the composite's pixel at canvas (x, y).+fn pixel(s: &CanvasSession, x: u32, y: u32) -> [u8; 4] {+ let mut guard = s.shared.lock();+ let st = &mut *guard;+ let (canvas, gpu) = (st.canvas.as_mut().unwrap(), st.gpu.as_ref().unwrap());+ canvas.render(gpu, &mut st.doc, None);+ assert_eq!(gpu.errors(), 0, "GPU validation errors");+ let px = canvas.read_composite(gpu).unwrap();+ let i = ((y * st.doc.width() + x) * 4) as usize;+ [px[i], px[i + 1], px[i + 2], px[i + 3]]+}++#[test]+fn a_pen_stroke_paints_and_undoes() {+ let Some(s) = session(100, 200) else { return };+ // the 100 px canvas is shown at 2×: window (100, 100) is canvas (50, 50)+ s.stroke_begin(PointerKind::Stylus, vec![sample(60.0, 100.0, 0.0)]);+ s.stroke_add((1..20).map(|i| sample(60.0 + i as f32 * 4.0, 100.0, i as f64 * 8.0)).collect());+ s.stroke_end(vec![sample(140.0, 100.0, 170.0)]);+ assert_eq!(pixel(&s, 50, 50), [0, 0, 0, 255]);+ assert_eq!(pixel(&s, 50, 90), [255, 255, 255, 255]);+ assert!(s.info().can_undo);+ s.undo();+ assert_eq!(pixel(&s, 50, 50), [255, 255, 255, 255]);+ s.redo();+ assert_eq!(pixel(&s, 50, 50), [0, 0, 0, 255]);+}++#[test]+fn eraser_end_and_erase_tool_erase() {+ let Some(s) = session(100, 100) else { return };+ // the eraser starts on a soft airbrush; give it the hard round pen, as large as it goes+ s.set_tool(ToolKind::Erase);+ assert_eq!(s.current_brush().name, "Soft Airbrush");+ assert!(s.select_brush(1, 0));+ assert!(!s.select_brush(99, 0));+ s.set_brush_size(1.0);+ s.set_tool(ToolKind::Paint);+ s.set_brush_size(1.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(50.0, 50.0, 0.0)]);+ s.stroke_end(vec![]);+ assert_eq!(pixel(&s, 50, 50), [0, 0, 0, 255]);+ s.stroke_begin(PointerKind::StylusEraser, vec![sample(50.0, 50.0, 0.0)]);+ s.stroke_end(vec![]);+ assert_eq!(pixel(&s, 50, 50), [255, 255, 255, 255]);++ s.stroke_begin(PointerKind::Finger, vec![sample(20.0, 20.0, 0.0)]);+ s.stroke_end(vec![]);+ s.set_tool(ToolKind::Erase);+ assert_eq!(s.info().tool, ToolKind::Erase);+ s.stroke_begin(PointerKind::Finger, vec![sample(20.0, 20.0, 0.0)]);+ s.stroke_end(vec![]);+ assert_eq!(pixel(&s, 20, 20), [255, 255, 255, 255]);+}++#[test]+fn cancel_colour_opacity_and_clear() {+ let Some(s) = session(100, 100) else { return };+ s.stroke_begin(PointerKind::Finger, vec![sample(30.0, 30.0, 0.0)]);+ s.stroke_cancel();+ assert_eq!(pixel(&s, 30, 30), [255, 255, 255, 255]);++ s.set_color(1.0, 0.0, 0.0);+ s.set_brush_opacity(0.5);+ s.stroke_begin(PointerKind::Finger, vec![sample(30.0, 30.0, 0.0)]);+ s.stroke_end(vec![]);+ let [r, g, b, _] = pixel(&s, 30, 30);+ assert!(r == 255 && (126..=129).contains(&g) && g == b, "{r} {g} {b}");++ s.clear_layer();+ assert_eq!(pixel(&s, 30, 30), [255, 255, 255, 255]);+ s.undo();+ assert_eq!(pixel(&s, 30, 30)[1], pixel(&s, 30, 30)[2]);+}++#[test]+fn a_blending_brush_builds_up_past_its_opacity_and_a_glaze_stops_at_it() {+ let Some(s) = session(100, 100) else { return };+ s.set_color(1.0, 0.0, 0.0);+ s.set_brush_opacity(0.5);+ let line = |y: f32| {+ s.stroke_begin(+ PointerKind::Finger,+ (0..40).map(|i| sample(10.0 + i as f32 * 2.0, y, f64::from(i) * 8.0)).collect(),+ );+ s.stroke_end(vec![]);+ };+ // a glaze (the round pen): the stroke at half+ line(30.0);+ let glaze = pixel(&s, 50, 30)[1];+ assert!((120..=136).contains(&glaze), "{glaze}");+ // blending, each stamp is lighter but they build up well past it+ s.studio_begin();+ s.set_studio_setting("rendering_mode".to_owned(), 5.0);+ s.studio_end(true);+ line(70.0);+ let blend = pixel(&s, 50, 70)[1];+ assert!(blend + 50 < glaze, "{blend} {glaze}");+}++#[test]+fn gestures_move_the_view_and_bad_values_are_ignored() {+ let Some(s) = session(100, 100) else { return };+ s.view_gesture(50.0, 50.0, 0.0, 0.0, 2.0, 0.0);+ assert!((s.info().zoom - 2.0).abs() < 1e-4);+ s.view_gesture(f32::NAN, 0.0, 0.0, 0.0, 1.0, 0.0);+ s.set_brush_size(f32::NAN);+ s.set_color(f32::NAN, 2.0, -1.0);+ assert!((s.info().zoom - 2.0).abs() < 1e-4);+ s.fit_view();+ assert!((s.info().zoom - 1.0).abs() < 1e-4);+ // settling to fit gets there over its time, frame by frame+ s.view_gesture(50.0, 50.0, 0.0, 0.0, 2.0, 0.0);+ s.settle_to_fit();+ std::thread::sleep(std::time::Duration::from_secs_f32(s.view_settle_seconds()));+ s.shared.lock().step_view_motion();+ assert!((s.info().zoom - 1.0).abs() < 1e-4);+ // no window on the host+ assert!(s.attach_window(1, 10, 10).is_err());+}++#[test]+fn layers_change_undoably() {+ let Some(s) = session(100, 100) else { return };+ let first = s.layers()[0].id;+ let second = s.add_layer();+ assert_eq!(s.layers().iter().map(|l| l.id).collect::<Vec<_>>(), vec![second, first], "top first");+ assert!(s.layers()[0].current);+ let r0 = s.info().revision;+ // an opacity drag is one undo step+ for v in [0.9, 0.6, 0.3] {+ s.set_layer_opacity(second, v, false);+ }+ s.set_layer_opacity(second, 0.2, true);+ assert!(s.info().revision > r0);+ assert!((s.layers()[0].opacity - 0.2).abs() < 1e-6);+ s.undo();+ assert!((s.layers()[0].opacity - 1.0).abs() < 1e-6, "back to before the drag");+ s.undo();+ assert_eq!(s.layers().len(), 1, "the add is undone");+ s.redo();+ assert_eq!(s.layers().len(), 2);+}++#[test]+fn merge_duplicate_blend_and_locks() {+ let Some(s) = session(100, 100) else { return };+ let bottom = s.layers()[0].id;+ s.set_color(1.0, 0.0, 0.0);+ s.set_brush_size(1.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(50.0, 50.0, 0.0)]);+ s.stroke_end(vec![]);+ let copy = s.duplicate_layer(bottom).unwrap();+ assert_eq!(s.layers().len(), 2);+ assert!(s.set_layer_blend(copy, procraft_engine::document::BlendMode::Multiply.id()));+ assert!(!s.set_layer_blend(copy, 999));+ assert_eq!(crate::layers::blend_modes().len(), 27);+ assert!(s.merge_down(copy));+ assert_eq!(s.layers().len(), 1);+ // red multiplied by red is still red+ assert_eq!(pixel(&s, 50, 50), [255, 0, 0, 255]);+ // a locked layer takes no paint and can't be cleared+ assert!(s.set_layer_locked(bottom, true));+ s.set_color(0.0, 0.0, 1.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(50.0, 50.0, 0.0)]);+ s.stroke_end(vec![]);+ s.clear_layer();+ assert_eq!(pixel(&s, 50, 50), [255, 0, 0, 255]);+ let thumb = s.layer_thumbnail(bottom, 10).unwrap();+ assert_eq!(thumb.width.max(thumb.height), 10);+ assert!(!s.delete_layer(bottom), "locked, and the last layer");+}++#[test]+fn background_settings() {+ let Some(s) = session(100, 100) else { return };+ assert!(s.set_background_color(0.0, 0.0, 0.0, true));+ assert_eq!(pixel(&s, 10, 10), [0, 0, 0, 255]);+ assert!(s.set_background_visible(false));+ assert!(!s.set_background_visible(false), "no change, no step");+ assert_eq!(pixel(&s, 10, 10), [0, 0, 0, 0]);+ s.undo();+ assert!(s.background().visible);+}++#[test]+fn every_brush_draws_a_preview() {+ let Some(s) = session(100, 100) else { return };+ let library = s.brush_library();+ assert!(library.len() >= 6);+ for set in &library {+ for b in &set.brushes {+ let p = s.brush_preview(b.set, b.index, 240, 60).unwrap();+ assert_eq!((p.width, p.height, p.rgba.len()), (240, 60, 240 * 60 * 4));+ let painted = p.rgba.chunks(4).filter(|px| px[3] > 0).count();+ assert!(painted > 100, "{} drew {painted} pixels", b.name);+ assert!(p.rgba.chunks(4).all(|px| px[3] == 0 || px[0] <= px[3]), "{} premultiplied", b.name);+ }+ }+ // the preview canvas leaves the artwork alone+ assert!(!s.info().can_undo);+}++#[test]+fn brushes_keep_their_own_sliders() {+ let Some(s) = session(100, 100) else { return };+ s.set_brush_size(0.9);+ assert!(s.select_brush(0, 0));+ // at the size its preview shows (0.09 of its range: the slider's place for it)+ let start = 0.09f32.powf(1.0 / procraft_engine::brush::SIZE_CURVE);+ assert!((s.info().size - start).abs() < 1e-6, "a fresh brush starts at its default");+ s.set_brush_size(0.1);+ assert!(s.select_brush(1, 0));+ assert!((s.info().size - 0.9).abs() < 1e-6, "back to the pen's own size");+ // a textured brush paints through the renderer without trouble+ assert!(s.select_brush(4, 0));+ s.stroke_begin(PointerKind::Stylus, (0..20).map(|i| sample(20.0 + i as f32 * 3.0, 50.0, i as f64 * 8.0)).collect());+ s.stroke_end(vec![]);+ let [_, _, _, a] = pixel(&s, 50, 50);+ assert_eq!(a, 255, "background stays opaque under the stroke");+}++/// Writes every brush preview as raw RGBA (`<set>-<index>.rgba`, 480×120) into the directory in+/// `PROCRAFT_DUMP`, for looking at the brushes: `cargo test -p procraft-android dump -- --ignored`.+#[test]+#[ignore]+fn dump_brush_previews() {+ let Ok(dir) = std::env::var("PROCRAFT_DUMP") else { return };+ let Some(s) = session(100, 100) else { return };+ let mut names = String::new();+ for set in s.brush_library() {+ for b in &set.brushes {+ let p = s.brush_preview(b.set, b.index, 480, 120).unwrap();+ std::fs::write(format!("{dir}/{}-{}.rgba", b.set, b.index), &p.rgba).unwrap();+ names += &format!(+ "{}-{} {}: {}+",+ b.set, b.index, set.name, b.name+ );+ }+ }+ std::fs::write(format!("{dir}/names.txt"), names).unwrap();+}++#[test]+fn smudge_tool_moves_paint_and_is_one_undo_step() {+ let Some(s) = session(100, 100) else { return };+ s.set_color(1.0, 0.0, 0.0);+ s.set_brush_size(0.4);+ s.stroke_begin(PointerKind::Finger, vec![sample(30.0, 50.0, 0.0)]);+ s.stroke_end(vec![]);+ assert_eq!(pixel(&s, 30, 50), [255, 0, 0, 255]);+ let outside = pixel(&s, 70, 50);+ assert_eq!(outside, [255, 255, 255, 255]);+ s.set_tool(ToolKind::Smudge);+ assert_eq!(s.current_brush().name, "Round Brush");+ s.set_brush_size(0.6);+ s.stroke_begin(PointerKind::Finger, vec![sample(30.0, 50.0, 0.0)]);+ s.stroke_add((1..30).map(|i| sample(30.0 + i as f32 * 1.5, 50.0, i as f64 * 8.0)).collect());+ s.stroke_end(vec![sample(75.0, 50.0, 250.0)]);+ let [r, g, _, _] = pixel(&s, 60, 50);+ assert!(r > g, "red dragged right: {r} {g}");+ s.undo();+ assert_eq!(pixel(&s, 60, 50), [255, 255, 255, 255]);+ assert_eq!(pixel(&s, 30, 50), [255, 0, 0, 255], "the paint itself stays");+}++#[test]+fn prediction_is_drawn_but_never_kept() {+ let Some(s) = session(100, 100) else { return };+ s.stroke_begin(PointerKind::Stylus, vec![sample(10.0, 50.0, 0.0)]);+ s.stroke_predict(vec![sample(90.0, 50.0, 16.0)]);+ s.stroke_end(vec![]);+ assert_eq!(pixel(&s, 90, 50), [255, 255, 255, 255]);+ // without an open stroke a prediction does nothing+ s.stroke_predict(vec![sample(50.0, 50.0, 0.0)]);+}++#[test]+fn artworks_save_and_open() {+ let Some(s) = session(100, 100) else { return };+ s.set_color(0.0, 1.0, 0.0);+ s.set_brush_size(0.3);+ s.stroke_begin(PointerKind::Finger, vec![sample(30.0, 30.0, 0.0)]);+ s.stroke_end(vec![]);+ let top = s.add_layer();+ s.set_color(0.0, 0.0, 1.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(70.0, 70.0, 0.0)]);+ s.stroke_end(vec![]);+ assert!(s.set_layer_opacity(top, 0.5, true));+ assert!(s.set_name("Test Piece".to_owned()));+ s.set_author(" A. Painter ".to_owned());+ s.add_tracked_time(90_000);+ let info = s.artwork_info();+ assert_eq!((info.strokes, info.tracked_ms, info.author.as_str()), (2, 90_000, "A. Painter"));+ assert!(info.created_ms > 0);+ let stats = s.layer_stats();+ assert_eq!((stats.used, stats.masks, stats.groups), (2, 0, 0));+ assert!(stats.maximum >= stats.used);+ let dir = std::env::temp_dir().join(format!("procraft-save-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ s.save(dir.to_string_lossy().into_owned()).unwrap();+ assert!(dir.join("artwork.json").exists() && dir.join("thumbnail.png").exists());++ let opened = CanvasSession::open(dir.to_string_lossy().into_owned()).unwrap();+ {+ let gpu = Gpu::headless().unwrap();+ let mut st = opened.shared.lock();+ st.window_size = (100, 100);+ st.view = Some(View::fit((100, 100), (100, 100)));+ st.gpu = Some(gpu);+ st.ensure_canvas();+ }+ assert_eq!(opened.name(), "Test Piece");+ assert_eq!(opened.artwork_info().author, "A. Painter");+ assert_eq!(opened.artwork_info().created_ms, info.created_ms);+ assert_eq!(opened.layers(), s.layers());+ assert_eq!(pixel(&opened, 30, 30), pixel(&s, 30, 30));+ assert_eq!(pixel(&opened, 70, 70), pixel(&s, 70, 70));+ // saving again over the same folder works, and a deleted layer's file goes away+ assert!(opened.delete_layer(top));+ opened.save(dir.to_string_lossy().into_owned()).unwrap();+ assert_eq!(std::fs::read_dir(dir.join("layers")).unwrap().count(), 1);+ assert!(CanvasSession::open(dir.join("missing").to_string_lossy().into_owned()).is_err());+ let _ = std::fs::remove_dir_all(&dir);+}++#[test]+fn straight_alpha_undoes_premultiplying() {+ let px = crate::project::straight_alpha(&[64, 32, 0, 128, 0, 0, 0, 0, 255, 255, 255, 255]);+ assert_eq!(px, vec![128, 64, 0, 128, 0, 0, 0, 0, 255, 255, 255, 255]);+}++#[test]+fn the_eyedropper_sees_the_window_and_the_colour_under_the_point() {+ let Some(s) = session(100, 200) else { return };+ // a black line across window y = 100 (canvas y = 50), shown at 2×+ s.stroke_begin(PointerKind::Stylus, vec![sample(20.0, 100.0, 0.0)]);+ s.stroke_add((1..40).map(|i| sample(20.0 + i as f32 * 4.0, 100.0, i as f64 * 8.0)).collect());+ s.stroke_end(vec![sample(180.0, 100.0, 330.0)]);+ let on_line = s.pick(100.0, 100.0, 81).unwrap();+ assert_eq!(on_line.rgb, Some(0x000000));+ assert_eq!(on_line.pixels.len(), 81 * 81 * 4);+ // the window's middle is the line, its top row (40 px above) the white canvas+ assert_eq!(&on_line.pixels[(40 * 81 + 40) * 4..(40 * 81 + 40) * 4 + 3], &[0, 0, 0]);+ assert_eq!(&on_line.pixels[40 * 4..40 * 4 + 3], &[255, 255, 255]);+ assert_eq!(s.pick(100.0, 40.0, 21).unwrap().rgb, Some(0xFFFFFF));+ // the window is 200 wide and the canvas fills it: nothing is off the canvas inside it, but+ // outside the window is+ assert_eq!(s.pick(250.0, 100.0, 21).unwrap().rgb, None);+}++#[test]+fn content_shape_holds_every_painted_pixel() {+ use crate::transform::content_shape;+ let mut px = vec![0u8; 4 * 5 * 4];+ assert_eq!(content_shape(&px, 5), None);+ px[(5 + 1) * 4 + 3] = 1; // (1, 1)+ px[(3 * 5 + 3) * 4 + 3] = 255; // (3, 3)+ let (bounds, hull) = content_shape(&px, 5).unwrap();+ assert_eq!(bounds, [1.0, 1.0, 3.0, 3.0]);+ // the two pixels' outer corners+ assert_eq!(hull.len(), 6, "{hull:?}");+ assert_eq!(content_shape(&px, 0), None);+}++#[test]+fn a_transform_moves_the_layer_as_one_undo_step() {+ use crate::transform::{Interpolation, TransformAction, TransformHandle, TransformKind};+ let Some(s) = session(100, 100) else { return };+ s.set_brush_size(0.4);+ assert_eq!(s.transform_begin(), None, "nothing to transform yet");+ s.stroke_begin(PointerKind::Finger, vec![sample(30.0, 30.0, 0.0)]);+ s.stroke_end(vec![]);+ let b = s.transform_begin().unwrap();+ let [x0, y0, x1, _, _, y1, ..] = b.corners[..] else { panic!() };+ assert!(x1 - x0 < 30.0 && y1 - y0 < 30.0, "{b:?}");+ assert!(x0 < 30.0 && x1 > 30.0 && y0 < 30.0 && y1 > 30.0);+ assert!(!b.can_undo);+ // painting waits while the transform is open+ s.stroke_begin(PointerKind::Finger, vec![sample(80.0, 20.0, 0.0)]);+ s.stroke_end(vec![]);+ s.transform_grab(TransformHandle::Move, 30.0, 30.0);+ s.transform_drag(50.0, 50.0);+ let moved = s.transform_drag(70.0, 70.0).unwrap();+ assert!((moved.corners[0] - (x0 + 40.0)).abs() < 1e-3);+ let released = s.transform_release().unwrap();+ assert!(released.can_undo);+ assert_eq!(pixel(&s, 70, 70), [0, 0, 0, 255]);+ assert_eq!(pixel(&s, 30, 30), [255, 255, 255, 255]);+ assert_eq!(pixel(&s, 80, 20), [255, 255, 255, 255]);+ // undone inside the transform, then again+ s.transform_apply(TransformAction::Undo);+ assert_eq!(pixel(&s, 30, 30), [0, 0, 0, 255]);+ s.transform_grab(TransformHandle::Move, 30.0, 30.0);+ s.transform_drag(70.0, 70.0);+ // a second finger: put back+ s.transform_cancel_drag();+ assert_eq!(pixel(&s, 30, 30), [0, 0, 0, 255]);+ s.transform_grab(TransformHandle::Move, 30.0, 30.0);+ s.transform_drag(70.0, 70.0);+ s.transform_release();+ let nudged = s.transform_nudge(99.0, 70.0).unwrap();+ assert!((nudged.corners[0] - released.corners[0] - 1.0).abs() < 1e-3);+ s.transform_apply(TransformAction::Undo);+ s.transform_set_guides(crate::transform::GuideSettings {+ magnetics: true,+ snapping: true,+ distance: 3.0,+ velocity: 10.0,+ });+ let warped = s.transform_set_kind(TransformKind::Warp).unwrap();+ assert_eq!(warped.mesh.len(), 32);+ assert_eq!(warped.grid.len(), 8 * 25 * 2);+ s.transform_grab(TransformHandle::Mesh { index: 15 }, 0.0, 0.0);+ s.transform_drag(5.0, 5.0);+ s.transform_release();+ s.transform_apply(TransformAction::Undo);+ s.transform_set_kind(TransformKind::Distort);+ s.transform_set_interpolation(Interpolation::Nearest);+ s.transform_end(true);+ assert_eq!(pixel(&s, 70, 70), [0, 0, 0, 255]);+ s.undo();+ assert_eq!(pixel(&s, 30, 30), [0, 0, 0, 255]);+ assert_eq!(pixel(&s, 70, 70), [255, 255, 255, 255]);+ // cancelled, and kept by another change+ s.transform_begin().unwrap();+ s.transform_apply(TransformAction::FlipVertical);+ s.transform_apply(TransformAction::FitToCanvas);+ s.transform_end(false);+ assert_eq!(pixel(&s, 30, 30), [0, 0, 0, 255]);+ s.transform_begin().unwrap();+ s.transform_grab(TransformHandle::Move, 30.0, 30.0);+ s.transform_drag(70.0, 70.0);+ s.add_layer();+ assert_eq!(pixel(&s, 70, 70), [0, 0, 0, 255]);+ assert_eq!(s.transform_drag(10.0, 10.0), None);+ assert_eq!(s.view_matrix(), vec![1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);+}++#[test]+fn a_selection_limits_painting_and_its_tools_work() {+ use crate::selection::SelectionJoin;+ let Some(s) = session(100, 100) else { return };+ s.set_brush_size(0.4);+ // the left half, drawn on the window (1:1)+ s.select_shape(false, 0.0, 0.0, 50.0, 100.0, SelectionJoin::Add);+ assert!(s.has_selection());+ s.stroke_begin(PointerKind::Finger, vec![sample(50.0, 50.0, 0.0)]);+ s.stroke_end(vec![]);+ assert_eq!(pixel(&s, 47, 50), [0, 0, 0, 255]);+ assert_eq!(pixel(&s, 53, 50), [255, 255, 255, 255]);+ // inverted: the right half; filled with red there+ s.select_invert();+ s.set_color(1.0, 0.0, 0.0);+ s.fill_selection();+ assert_eq!(pixel(&s, 90, 10), [255, 0, 0, 255]);+ assert_eq!(pixel(&s, 10, 10), [255, 255, 255, 255]);+ s.undo();+ assert_eq!(pixel(&s, 90, 10), [255, 255, 255, 255]);+ // a circle taken away, then saved, cleared and loaded+ s.select_shape(true, 60.0, 0.0, 100.0, 40.0, SelectionJoin::Remove);+ assert_eq!(s.save_selection(), 1);+ s.select_none();+ assert!(!s.has_selection());+ assert!(s.load_selection(0));+ assert!(!s.load_selection(5));+ // each change to the selection is an undo step+ s.select_none();+ s.undo();+ assert!(s.has_selection());+ s.redo();+ assert!(!s.has_selection());+ s.undo();+ // copied to a layer of its own: the left half's paint is not selected, so the copy is empty+ let id = s.copy_selection_to_layer().unwrap();+ assert!(s.info().revision > 0);+ s.select_none();+ s.select_polygon(vec![0.0, 0.0, 50.0, 0.0, 50.0, 100.0, 0.0, 100.0], SelectionJoin::Add);+ s.select_feather(0.02);+ s.select_feather(0.0);+ s.select_feather(0.05);+ s.select_feather_done();+ s.select_by_colour(10.0, 10.0, 0.1, SelectionJoin::Add, true);+ s.select_by_colour(10.0, 10.0, 0.3, SelectionJoin::Add, false);+ s.set_selection_display(crate::selection::SelectionDisplay::Tint);+ assert!(s.has_selection());+ let _ = id;+ // clearing with a selection clears only what is selected+ s.select_none();+ let paint = s.layers().iter().map(|l| l.id).rfind(|&l| l != id).unwrap();+ assert!(s.select_layer(paint));+ s.select_shape(false, 0.0, 0.0, 45.0, 100.0, SelectionJoin::Add);+ s.clear_layer();+ assert_eq!(pixel(&s, 44, 50), [255, 255, 255, 255]);+ assert_eq!(pixel(&s, 48, 50), [0, 0, 0, 255]);+}++#[test]+fn a_transform_with_a_selection_moves_only_what_it_takes() {+ use crate::selection::SelectionJoin;+ use crate::transform::{TransformAction, TransformHandle};+ let Some(s) = session(100, 100) else { return };+ s.set_brush_size(0.4);+ s.stroke_begin(PointerKind::Finger, vec![sample(20.0, 50.0, 0.0)]);+ s.stroke_add((1..30).map(|i| sample(20.0 + i as f32 * 2.0, 50.0, i as f64 * 8.0)).collect());+ s.stroke_end(vec![sample(80.0, 50.0, 250.0)]);+ // the left half selected: the box holds only its part of the stroke+ s.select_shape(false, 0.0, 0.0, 50.0, 100.0, SelectionJoin::Add);+ let b = s.transform_begin().unwrap();+ assert!(b.corners[2] <= 50.5, "{b:?}");+ s.transform_grab(TransformHandle::Move, 30.0, 50.0);+ s.transform_drag(30.0, 80.0);+ s.transform_release();+ s.transform_end(true);+ // the left part moved down, the right part stayed+ assert_eq!(pixel(&s, 30, 80), [0, 0, 0, 255]);+ assert_eq!(pixel(&s, 30, 50), [255, 255, 255, 255]);+ assert_eq!(pixel(&s, 70, 50), [0, 0, 0, 255]);+ // and the selection went with it+ s.stroke_begin(PointerKind::Finger, vec![sample(30.0, 20.0, 0.0)]);+ s.stroke_end(vec![]);+ assert_eq!(pixel(&s, 30, 20), [255, 255, 255, 255]);+ let _ = TransformAction::Reset;+}++#[test]+fn adjustments_change_the_layer_as_one_undo_step() {+ let Some(s) = session(100, 100) else { return };+ s.set_brush_size(0.4);+ s.set_color(1.0, 0.0, 0.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(50.0, 50.0, 0.0)]);+ s.stroke_end(vec![]);+ assert!(s.adjust_begin());+ assert!(s.is_adjusting());+ // brightness to none: black; then back to as it was+ s.adjust_hsb(0.5, 0.5, 0.0);+ assert_eq!(pixel(&s, 50, 50), [0, 0, 0, 255]);+ s.adjust_hsb(0.5, 0.5, 0.5);+ assert_eq!(pixel(&s, 50, 50), [255, 0, 0, 255]);+ s.adjust_swipe(crate::adjust::SwipeAdjustment::GaussianBlur, 0.2);+ for kind in [+ crate::adjust::SwipeAdjustment::Sharpen,+ crate::adjust::SwipeAdjustment::Noise,+ crate::adjust::SwipeAdjustment::PerspectiveBlur,+ crate::adjust::SwipeAdjustment::ChromaticAberration,+ crate::adjust::SwipeAdjustment::Halftone,+ crate::adjust::SwipeAdjustment::Bloom,+ ] {+ s.adjust_swipe(kind, 0.5);+ }+ assert!((s.adjust_motion(100.0, 0.0) - 0.1).abs() < 1e-3);+ s.adjust_curves(vec![0.0, 0.0, 0.5, 0.8, 1.0, 1.0], vec![], vec![], vec![]);+ s.adjust_color_balance(vec![0.5, 0.0, 0.0], vec![], vec![0.0, 0.0, -0.5]);+ s.adjust_gradient_map(vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0], 1.0);+ s.adjust_noise(crate::adjust::NoiseKind::Ridges, 0.5, 0.3, 0.5, 0.7, true, false);+ s.adjust_bloom(0.5, 1.0, 0.3, 0.35);+ s.adjust_halftone(crate::adjust::HalftoneKind::Newspaper, 0.3);+ s.adjust_chromatic(crate::adjust::ChromaticKind::Displace, 0.0, 12.0, -4.0, 0.2, f32::NAN);+ for kind in [crate::adjust::GlitchKind::Artifact, crate::adjust::GlitchKind::Diverge] {+ s.adjust_glitch(kind, 0.5, vec![0.9, -0.5, f32::NAN], 0.5);+ }+ s.adjust_swipe(crate::adjust::SwipeAdjustment::GaussianBlur, 0.2);+ s.adjust_end(true);+ assert!(!s.is_adjusting());+ assert_ne!(pixel(&s, 50, 50), [255, 0, 0, 255]);+ s.undo();+ assert_eq!(pixel(&s, 50, 50), [255, 0, 0, 255]);+ // put back+ assert!(s.adjust_begin());+ s.adjust_hsb(0.5, 0.5, 0.0);+ s.adjust_end(false);+ assert_eq!(pixel(&s, 50, 50), [255, 0, 0, 255]);+}++#[test]+fn liquify_moves_paint_as_one_undo_step() {+ use crate::adjust::{LiquifyBrush, LiquifyKind};+ let Some(s) = session(100, 100) else { return };+ s.set_brush_size(0.4);+ s.stroke_begin(PointerKind::Finger, vec![sample(30.0, 50.0, 0.0)]);+ s.stroke_end(vec![]);+ assert!(s.liquify_begin());+ let brush = LiquifyBrush { kind: LiquifyKind::Push, size: 0.15, pressure: 1.0, distortion: 0.0 };+ let path: Vec<f32> = (0..=20).flat_map(|i| [30.0 + i as f32, 50.0, 1.0]).collect();+ s.liquify_stroke(path, true, brush);+ assert!(pixel(&s, 45, 50)[0] < 128, "{:?}", pixel(&s, 45, 50));+ s.liquify_amount(0.5);+ s.liquify_reset();+ assert_eq!(pixel(&s, 45, 50), [255, 255, 255, 255]);+ s.liquify_stroke((0..=20).flat_map(|i| [30.0 + i as f32, 50.0, 1.0]).collect(), true, brush);+ // lifted while moving, it carries on further right+ let row = |s: &CanvasSession| (40..90).map(|x| pixel(s, x, 50)).collect::<Vec<_>>();+ let before = row(&s);+ s.liquify_coast(0.1, 0.0, 1.0, brush);+ assert_ne!(row(&s), before);+ s.liquify_coast(f32::NAN, 0.0, 1.0, brush);+ s.adjust_end(true);+ s.undo();+ assert_eq!(pixel(&s, 30, 50), [0, 0, 0, 255]);+}++#[test]+fn an_adjustment_painted_on_and_clone() {+ let Some(s) = session(100, 100) else { return };+ s.set_brush_size(0.4);+ s.set_color(1.0, 0.0, 0.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(30.0, 50.0, 0.0)]);+ s.stroke_end(vec![]);+ assert!(s.adjust_begin());+ s.adjust_hsb(0.5, 0.5, 0.0);+ s.adjust_pencil();+ // nothing painted on yet: as it was+ assert_eq!(pixel(&s, 30, 50), [255, 0, 0, 255]);+ s.stroke_begin(PointerKind::Finger, vec![sample(30.0, 50.0, 0.0)]);+ s.stroke_end(vec![]);+ assert_eq!(pixel(&s, 30, 50), [0, 0, 0, 255]);+ s.adjust_end(true);+ assert_eq!(pixel(&s, 30, 50), [0, 0, 0, 255]);+ s.undo();+ assert_eq!(pixel(&s, 30, 50), [255, 0, 0, 255]);+ // clone the red 40 to the right+ assert!(s.clone_begin());+ s.clone_source(30.0, 50.0);+ assert_eq!(pixel(&s, 70, 50), [255, 255, 255, 255]);+ // the clone brush is the soft airbrush: a dab copies some of it+ s.stroke_begin(PointerKind::Finger, vec![sample(70.0, 50.0, 0.0)]);+ s.stroke_end(vec![]);+ let cloned = pixel(&s, 70, 50);+ assert!(cloned[0] == 255 && cloned[1] < 250 && cloned[1] == cloned[2], "{cloned:?}");+ // each stroke is its own step, undone and redone while cloning goes on+ s.stroke_begin(PointerKind::Finger, vec![sample(70.0, 50.0, 0.0)]);+ s.stroke_end(vec![]);+ let twice = pixel(&s, 70, 50);+ assert!(twice[1] < cloned[1], "{twice:?}");+ s.undo();+ assert_eq!(pixel(&s, 70, 50), cloned);+ assert!(s.is_adjusting());+ s.redo();+ assert_eq!(pixel(&s, 70, 50), twice);+ s.adjust_end(true);+ assert_eq!(pixel(&s, 70, 50), twice);+ // left, its strokes are one step (simplified undos)+ s.undo();+ assert_eq!(pixel(&s, 70, 50), [255, 255, 255, 255]);+ assert_eq!(pixel(&s, 30, 50), [255, 0, 0, 255]);+ s.redo();+ assert_eq!(pixel(&s, 70, 50), twice);+ // without simplified undos they stay apart+ s.set_simplified_undos(false);+ assert!(s.clone_begin());+ s.clone_source(30.0, 50.0);+ for _ in 0..2 {+ s.stroke_begin(PointerKind::Finger, vec![sample(70.0, 60.0, 0.0)]);+ s.stroke_end(vec![]);+ }+ let both = pixel(&s, 70, 60);+ s.adjust_end(true);+ s.undo();+ assert!(pixel(&s, 70, 60)[1] > both[1] && pixel(&s, 70, 60)[1] < 255, "{:?}", pixel(&s, 70, 60));+}++#[test]+fn newspaper_halftone_is_grey() {+ let Some(s) = session(100, 100) else { return };+ s.set_brush_size(0.6);+ s.set_color(1.0, 0.0, 0.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(50.0, 50.0, 0.0)]);+ s.stroke_end(vec![]);+ assert!(s.adjust_begin());+ s.adjust_halftone(crate::adjust::HalftoneKind::Newspaper, 0.1);+ for (x, y) in [(50, 50), (48, 52), (53, 47)] {+ let [r, g, b, _] = pixel(&s, x, y);+ assert!(r == g && g == b, "{:?}", pixel(&s, x, y));+ }+}++#[test]+fn an_imported_brush_shows_its_own_preview_until_changed() {+ use procraft_engine::brush::Brush;+ use procraft_engine::brushfile::{self, Pictures};+ let Some(s) = session(100, 100) else { return };+ // a file whose preview is a solid white band across its middle+ let (w, h) = (327u32, 100u32);+ let band: Vec<u8> =+ (0..w * h).flat_map(|i| if (40..60).contains(&(i / w)) { [255u8; 4] } else { [0u8; 4] }).collect();+ let thumbnail = crate::project::rgba_png(w, h, &band);+ let shape = crate::project::rgba_png(1, 1, &[255; 4]);+ let file = brushfile::write(+ &Brush { name: "Band".to_owned(), ..Brush::round_pen() },+ "",+ &Pictures {+ shape_png: &shape,+ grain_png: None,+ thumbnail_png: &thumbnail,+ author_png: None,+ signature_png: None,+ },+ );+ let set = s.import_brushes(file.clone()).unwrap();+ let alpha = |s: &CanvasSession| {+ let p = s.brush_preview(set, 0, w, h).unwrap();+ (p.rgba[((50 * w + 5) * 4 + 3) as usize], p.rgba[((10 * w + 160) * 4 + 3) as usize])+ };+ assert_eq!(alpha(&s), (255, 0));+ // kept with the library, and written back out as it came+ let Some(other) = session(100, 100) else { return };+ assert!(other.load_brush_library(s.saved_brush_library()));+ assert_eq!(alpha(&other), (255, 0));+ let out = brushfile::read(&s.brush_as_file(set, 0).unwrap()).unwrap();+ assert_eq!(out.thumbnail.as_deref(), Some(thumbnail.as_slice()));+ // changed, it is drawn: nothing at the band's far left+ assert!(s.select_brush(set, 0));+ s.studio_begin();+ s.set_studio_setting("spacing".to_owned(), 0.3);+ assert_eq!(alpha(&s).0, 0);+}++#[test]+fn a_closely_spaced_brush_keeps_its_size_controls() {+ let Some(s) = session(100, 100) else { return };+ s.studio_begin();+ s.set_studio_setting("spacing".to_owned(), 0.05);+ s.set_studio_setting("max_size".to_owned(), 0.8);+ s.set_studio_setting("min_size".to_owned(), 0.3);+ s.studio_end(true);+ let Some(other) = session(100, 100) else { return };+ assert!(other.load_brush_library(s.saved_brush_library()));+ other.studio_begin();+ let sizes = other.studio_settings(vec!["max_size".to_owned(), "min_size".to_owned()]);+ assert!((sizes[0] - 0.8).abs() < 1e-3 && (sizes[1] - 0.3).abs() < 1e-3, "{sizes:?}");+}++#[test]+fn a_brush_keeps_its_images_and_their_sizes() {+ let Some(s) = session(100, 100) else { return };+ let size = crate::studio::source_size() as usize;+ let sizes = vec!["max_size".to_owned()];+ // its own shape (sizes kept in that shape's unit), a shipped grain+ s.studio_begin();+ assert!(s.set_studio_source(false, vec![200; size * size]));+ assert!(s.set_studio_shipped_source(true, 2));+ s.set_studio_setting("max_size".to_owned(), 0.6);+ let grain = s.studio_source(true);+ s.studio_end(true);+ let Some(other) = session(100, 100) else { return };+ assert!(other.load_brush_library(s.saved_brush_library()));+ other.studio_begin();+ assert!((other.studio_settings(sizes.clone())[0] - 0.6).abs() < 1e-3);+ assert_eq!(other.studio_source(false), vec![200; size * size]);+ assert_eq!(other.studio_source(true), grain);+ other.studio_end(false);+ // a shipped shape in place of the round tip+ s.studio_begin();+ s.studio_reset();+ assert!(s.set_studio_shipped_source(false, 1));+ let shape = s.studio_source(false);+ s.studio_end(true);+ let Some(third) = session(100, 100) else { return };+ assert!(third.load_brush_library(s.saved_brush_library()));+ third.studio_begin();+ assert_eq!(third.studio_source(false), shape);+}++#[test]+fn the_brush_studio_edits_keeps_and_puts_back() {+ let Some(s) = session(100, 100) else { return };+ let name = s.studio_begin();+ assert!(!name.is_empty());+ let keys = vec!["spacing".to_owned(), "wet_pull".to_owned()];+ let start = s.studio_settings(keys.clone());+ s.set_studio_setting("spacing".to_owned(), 0.5);+ s.set_studio_setting("wet_pull".to_owned(), 0.2);+ assert_eq!(s.studio_settings(keys.clone()), vec![0.5, 0.2]);+ s.set_studio_curve(vec![0.0, 0.0, 0.5, 0.2, 1.0, 1.0]);+ assert_eq!(s.studio_curve().len(), 6);+ // cancelled, it opens as it was+ s.studio_end(false);+ s.studio_begin();+ assert_eq!(s.studio_settings(keys.clone()), start);+ assert_eq!(s.studio_curve().len(), 4);+ // kept, it stays; reset, it is as it ships+ s.set_studio_setting("spacing".to_owned(), 0.5);+ s.studio_end(true);+ s.studio_begin();+ assert_eq!(s.studio_settings(keys.clone())[0], 0.5);+ s.studio_reset();+ assert_eq!(s.studio_settings(keys.clone()), start);+ s.studio_end(true);+ // a stroke still draws with the edited brush+ s.stroke_begin(PointerKind::Finger, vec![sample(50.0, 50.0, 0.0)]);+ s.stroke_end(vec![]);+ // changes carry to another session+ s.studio_begin();+ s.set_studio_setting("spacing".to_owned(), 0.33);+ s.set_studio_setting("wet_attack".to_owned(), 0.25);+ s.studio_end(true);+ let kept = s.saved_brush_library();+ let Some(other) = session(100, 100) else { return };+ assert!(other.load_brush_library(kept));+ other.studio_begin();+ assert_eq!(other.studio_settings(vec!["spacing".to_owned(), "wet_attack".to_owned()]), vec![0.33, 0.25]);+ other.studio_end(false);+ other.apply_brush_changes("not json".to_owned());+ assert!(!other.load_brush_library("not json".to_owned()));+ // a pad paints like it, in its own colour, at the preview size+ let Some(pad) = session(100, 100) else { return };+ s.studio_begin();+ s.set_studio_setting("preview_size".to_owned(), 0.5);+ pad.paint_like(s.clone(), 1.0, 0.0, 0.0);+ pad.stroke_begin(PointerKind::Finger, vec![sample(50.0, 50.0, 0.0)]);+ pad.stroke_end(vec![]);+ assert_eq!(pixel(&pad, 50, 50), [255, 0, 0, 255]);+ s.studio_end(false);+}++#[test]+fn a_held_stroke_snaps_to_a_shape_and_is_edited() {+ use crate::quickshape::QuickShapeKind;+ let Some(s) = session(200, 200) else { return };+ s.set_brush_size(0.2);+ // a rough circle, held+ let pts: Vec<PenSample> = (0..=60)+ .map(|i| {+ let t = i as f32 / 60.0 * std::f32::consts::TAU;+ sample(100.0 + 60.0 * t.cos() + 2.0 * (7.0 * t).sin(), 100.0 + 40.0 * t.sin(), f64::from(i) * 8.0)+ })+ .collect();+ s.stroke_begin(PointerKind::Finger, pts[..1].to_vec());+ s.stroke_add(pts[1..].to_vec());+ let info = s.quickshape_hold().expect("a shape");+ assert_eq!(info.kind, QuickShapeKind::Ellipse);+ assert_eq!(info.handles.len(), 8);+ s.stroke_end(vec![]);+ // still open: shown as a circle, then a handle dragged+ let circle = s.quickshape_choose(QuickShapeKind::Circle).unwrap();+ assert_eq!(circle.kind, QuickShapeKind::Circle);+ let moved = s.quickshape_move_handle(0, 190.0, 100.0).unwrap();+ assert!((moved.handles[0] - 190.0).abs() < 1.0, "{:?}", moved.handles);+ s.quickshape_done();+ assert!(s.quickshape_info().is_none());+ // the circle's edge is painted, its middle is not+ assert_eq!(pixel(&s, 10, 100)[0], 0);+ assert_eq!(pixel(&s, 100, 100), [255, 255, 255, 255]);+ s.undo();+ assert_eq!(pixel(&s, 10, 100), [255, 255, 255, 255]);+ // a scribble too short to be anything does not snap+ s.stroke_begin(PointerKind::Finger, vec![sample(10.0, 10.0, 0.0)]);+ assert!(s.quickshape_hold().is_none());+ s.stroke_end(vec![]);+}++#[test]+fn copy_cut_paste_and_flip() {+ let Some(s) = session(100, 100) else { return };+ s.set_brush_size(0.4);+ s.set_color(1.0, 0.0, 0.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(20.0, 50.0, 0.0)]);+ s.stroke_end(vec![]);+ let copied = s.copy_layer().unwrap();+ let layers = s.layers().len();+ let pasted = s.paste(copied.clone()).unwrap();+ assert_eq!(s.layers().len(), layers + 1);+ assert_eq!(s.layers().iter().find(|l| l.current).map(|l| l.id), Some(pasted));+ // flipped left to right, both layers' red is now on the right, as one undo step+ s.flip_canvas(true);+ assert_eq!(pixel(&s, 79, 50), [255, 0, 0, 255]);+ assert_eq!(pixel(&s, 20, 50), [255, 255, 255, 255]);+ s.undo();+ assert_eq!(pixel(&s, 20, 50), [255, 0, 0, 255]);+ // cut takes it off the layer+ let cut = s.cut_layer().unwrap();+ assert_eq!(cut.rgba, copied.rgba);+ s.delete_layer(pasted);+ s.cut_layer().unwrap();+ assert_eq!(pixel(&s, 20, 50), [255, 255, 255, 255]);+ // a photo comes in as straight colour, premultiplied+ let photo = crate::layers::ThumbnailImage { width: 2, height: 2, rgba: [255, 0, 0, 128].repeat(4) };+ assert!(s.insert_image(photo).is_some());+ let canvas = s.copy_canvas().unwrap();+ assert_eq!(canvas.rgba.len(), 100 * 100 * 4);+}++#[test]+fn the_drawing_guide_mirrors_and_assists_strokes() {+ use crate::guide::{GuideType, SymmetryType};+ let Some(s) = session(100, 100) else { return };+ s.set_brush_size(0.3);+ // symmetry: a dot on the left is drawn on the right too+ s.set_guide_on(true);+ s.set_guide_kind(GuideType::Symmetry);+ s.set_guide_symmetry(SymmetryType::Vertical, false);+ s.set_guide_assisted(true);+ s.stroke_begin(PointerKind::Finger, vec![sample(20.0, 30.0, 0.0)]);+ s.stroke_end(vec![]);+ assert_eq!(pixel(&s, 80, 30)[0], 0);+ // the grid keeps a slanting stroke level+ s.set_guide_kind(GuideType::Grid);+ s.stroke_begin(PointerKind::Finger, vec![sample(10.0, 70.0, 0.0)]);+ s.stroke_add((1..=20).map(|i| sample(10.0 + i as f32 * 3.0, 70.0 + i as f32 * 0.6, f64::from(i) * 8.0)).collect());+ s.stroke_end(vec![]);+ assert_eq!(pixel(&s, 60, 70)[0], 0);+ assert_eq!(pixel(&s, 60, 80), [255, 255, 255, 255]);+ let info = s.guide();+ assert!(info.on && info.assisted && !info.lines.is_empty());+ // the editor fits the canvas inside a rectangle, and cancelling puts the guide back+ let before = s.view_matrix();+ s.guide_edit_begin(10.0, 10.0, 60.0, 60.0);+ s.set_guide_look(0.5, 0.5, 30.0, 0.7);+ assert_eq!(s.guide().size, 30.0);+ s.guide_edit_end(false);+ assert_eq!(s.guide().size, 71.0);+ assert_eq!(s.view_matrix(), before);+ // perspective points are added by tapping, three at most+ s.set_guide_kind(GuideType::Perspective);+ assert_eq!(s.touch_vanishing_point(5.0, 50.0), Some(0));+ assert_eq!(s.touch_vanishing_point(6.0, 50.0), Some(0));+ assert_eq!(s.touch_vanishing_point(95.0, 50.0), Some(1));+ s.remove_vanishing_point(1);+ assert_eq!(s.guide().vanishing.len(), 2);+}++#[test]+fn a_layers_own_actions() {+ let Some(s) = session(100, 100) else { return };+ s.set_brush_size(0.4);+ s.set_color(1.0, 0.0, 0.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(30.0, 30.0, 0.0)]);+ s.stroke_end(vec![]);+ let id = s.layers()[0].id;+ // invert: red to cyan, the coverage kept+ assert!(s.invert_layer(id));+ assert_eq!(pixel(&s, 30, 30), [0, 255, 255, 255]);+ s.undo();+ // select what is on it+ assert!(s.select_layer_contents(id));+ assert!(s.has_selection());+ // fill within that selection with blue+ s.set_color(0.0, 0.0, 1.0);+ assert!(s.fill_layer(id));+ assert_eq!(pixel(&s, 30, 30), [0, 0, 255, 255]);+ assert_eq!(pixel(&s, 80, 80), [255, 255, 255, 255]);+ s.select_none();+ assert!(s.fill_layer(id));+ assert_eq!(pixel(&s, 80, 80), [0, 0, 255, 255]);+ assert_eq!(s.copy_layer_contents(id).unwrap().rgba.len(), 100 * 100 * 4);+ // one reference layer at a time+ let other = s.add_layer();+ assert!(s.set_layer_reference(id, true));+ assert!(s.set_layer_reference(other, true));+ let refs: Vec<bool> = s.layers().iter().map(|l| l.reference).collect();+ assert_eq!(refs.iter().filter(|&&r| r).count(), 1);+ assert!(s.layers().iter().any(|l| l.id == other && l.reference));+}++#[test]+fn masks_hide_and_groups_composite_together() {+ use crate::layers::LayerType;+ let Some(s) = session(100, 100) else { return };+ s.set_brush_size(0.6);+ s.set_color(1.0, 0.0, 0.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(50.0, 50.0, 0.0)]);+ s.stroke_end(vec![]);+ let red = s.layers()[0].id;+ // a white mask shows everything; black painted on it hides the layer there+ let mask = s.add_mask(red).unwrap();+ assert_eq!(pixel(&s, 50, 50), [255, 0, 0, 255]);+ s.set_color(0.0, 0.0, 0.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(50.0, 50.0, 0.0)]);+ s.stroke_end(vec![]);+ assert_eq!(pixel(&s, 50, 50), [255, 255, 255, 255]);+ let list = s.layers();+ assert_eq!(list.iter().find(|l| l.id == mask).map(|l| (l.kind, l.parent)), Some((LayerType::Mask, Some(red))));+ s.undo();+ assert_eq!(pixel(&s, 50, 50), [255, 0, 0, 255]);+ // a blue layer above, combined down with the red one: a group at half opacity shows both+ // composited first, then halved+ let blue = s.add_layer();+ s.set_color(0.0, 0.0, 1.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(20.0, 20.0, 0.0)]);+ s.stroke_end(vec![]);+ let group = s.combine_down(blue).unwrap();+ assert!(s.layers().iter().any(|l| l.id == group && l.kind == LayerType::Group));+ assert!(s.layers().iter().filter(|l| l.parent == Some(group)).count() >= 2);+ s.set_layer_opacity(group, 0.5, true);+ let [r, g, b, _] = pixel(&s, 50, 50);+ assert!(r == 255 && (125..=130).contains(&g) && (125..=130).contains(&b), "{:?}", [r, g, b]);+ let [r, g, b, _] = pixel(&s, 20, 20);+ assert!((125..=130).contains(&r) && b == 255 && (125..=130).contains(&g), "{:?}", [r, g, b]);+ // hidden, the group hides all of it+ s.set_layer_visible(group, false);+ assert_eq!(pixel(&s, 50, 50), [255, 255, 255, 255]);+ s.set_layer_visible(group, true);+ // a group takes no paint+ s.select_layer(group);+ s.stroke_begin(PointerKind::Finger, vec![sample(80.0, 80.0, 0.0)]);+ s.stroke_end(vec![]);+ assert_eq!(pixel(&s, 80, 80), [255, 255, 255, 255]);+ assert!(s.set_group_collapsed(group, true));+ assert!(s.layers().iter().any(|l| l.id == group && l.collapsed));+}++#[test]+fn groups_nest_flatten_and_merge_down() {+ let Some(s) = session(100, 100) else { return };+ let dot = |x: f32, y: f32, rgb: [f32; 3]| {+ s.set_color(rgb[0], rgb[1], rgb[2]);+ s.stroke_begin(PointerKind::Finger, vec![sample(x, y, 0.0)]);+ s.stroke_end(vec![]);+ };+ s.set_brush_size(0.6);+ dot(30.0, 30.0, [1.0, 0.0, 0.0]);+ let red = s.layers()[0].id;+ let blue = s.add_layer();+ dot(70.0, 70.0, [0.0, 0.0, 1.0]);+ let green = s.add_layer();+ dot(50.0, 50.0, [0.0, 1.0, 0.0]);+ // green and blue in a group above red, then a group in the group+ let outer = s.combine_down(green).unwrap();+ let inner = s.combine_down(green).unwrap();+ let info = |id: u64| s.layers().into_iter().find(|l| l.id == id).unwrap();+ assert_eq!((info(green).depth, info(inner).depth, info(outer).depth), (2, 1, 0));+ assert!(info(outer).can_merge && info(outer).can_combine && !info(outer).can_clip);+ assert!(!info(blue).can_merge && !info(blue).can_combine && info(green).can_clip);+ // the inner group at half opacity: its layers composited first, then halved+ s.set_layer_opacity(inner, 0.5, true);+ let near = |p: [u8; 4], q: [u8; 3]| (0..3).all(|i| p[i].abs_diff(q[i]) <= 2);+ assert!(near(pixel(&s, 50, 50), [128, 255, 128]), "{:?}", pixel(&s, 50, 50));+ assert!(near(pixel(&s, 70, 70), [128, 128, 255]), "{:?}", pixel(&s, 70, 70));+ assert_eq!(pixel(&s, 30, 30), [255, 0, 0, 255]);+ // flattened, it looks the same: one layer named after its bottom one, at the group's opacity+ let flat = s.flatten_group(inner).unwrap();+ assert!(near(pixel(&s, 50, 50), [128, 255, 128]), "{:?}", pixel(&s, 50, 50));+ assert!(near(pixel(&s, 70, 70), [128, 128, 255]));+ assert_eq!((info(flat).name.as_str(), info(flat).opacity, info(flat).parent), ("Layer 2", 0.5, Some(outer)));+ s.undo();+ assert!(s.layers().iter().any(|l| l.id == inner));+ s.redo();+ assert!(s.layers().iter().all(|l| l.id != inner));+ // the outer group merged into red: one layer, still looking the same+ assert!(s.merge_down(outer));+ assert_eq!(s.layers().len(), 1);+ assert_eq!(s.layers()[0].id, red);+ assert!(near(pixel(&s, 50, 50), [128, 255, 128]), "{:?}", pixel(&s, 50, 50));+ assert_eq!(pixel(&s, 30, 30), [255, 0, 0, 255]);+ s.undo();+ assert!(s.layers().iter().any(|l| l.id == outer));+ // ungrouped, its layers come out+ assert!(s.ungroup(outer));+ assert!(s.layers().iter().all(|l| l.depth == 0));+ // a duplicate keeps the layer's mask+ let mask = s.add_mask(red).unwrap();+ let copy = s.duplicate_layer(red).unwrap();+ assert!(s.layers().iter().any(|l| l.parent == Some(copy) && l.id != mask));+}++#[test]+fn brushes_and_sets_are_made_copied_and_deleted() {+ let Some(s) = session(100, 100) else { return };+ let names = |set: usize| s.brush_library()[set].brushes.iter().map(|b| b.name.clone()).collect::<Vec<_>>();+ let start = s.current_brush();+ let set_name = s.brush_library()[start.set as usize].name.clone();+ let first = names(start.set as usize);+ // a copy goes just above; the tool keeps its brush, now one down+ assert_eq!(s.duplicate_brush(start.set, start.index), Some(start.index));+ assert_eq!(names(start.set as usize).len(), first.len() + 1);+ assert_eq!(s.current_brush().index, start.index + 1);+ // the copy is edited, and the original deleted: the copy stays current+ assert!(s.select_brush(start.set, start.index));+ s.studio_begin();+ s.set_studio_setting("spacing".to_owned(), 0.4);+ s.studio_end(true);+ assert!(s.delete_brush(start.set, start.index + 1));+ assert_eq!((s.current_brush().index, names(start.set as usize).len()), (start.index, first.len()));+ // a new brush at the top of the set is chosen; deleting the current brush moves the tool to+ // the one in its place+ assert_eq!(s.new_brush(start.set), Some(0));+ assert_eq!((s.current_brush().index, s.current_brush().name.as_str()), (0, "Untitled Brush"));+ assert!(s.delete_brush(start.set, 0));+ assert_eq!(s.current_brush().name, first[start.index as usize]);+ assert_eq!(s.new_brush(start.set), Some(0));+ // a new set at the top of the library moves the others down+ let sets = s.brush_library().len();+ assert_eq!(s.new_brush_set(), 0);+ assert_eq!(s.brush_library().len(), sets + 1);+ assert_eq!(s.current_brush().set, start.set + 1);+ assert!(s.rename_brush_set(0, " Mine ".to_owned()) && !s.rename_brush_set(0, " ".to_owned()));+ assert_eq!(s.brush_library()[0].name, "Mine");+ // everything carries to another session+ let kept = s.saved_brush_library();+ let Some(other) = session(100, 100) else { return };+ assert!(other.load_brush_library(kept));+ let lib = other.brush_library();+ assert_eq!(lib.len(), sets + 1);+ assert_eq!(lib[0].name, "Mine");+ assert_eq!(lib[start.set as usize + 1].brushes[0].name, "Untitled Brush");+ assert!(other.select_brush(start.set + 1, start.index + 1));+ other.studio_begin();+ assert_eq!(other.studio_settings(vec!["spacing".to_owned()]), vec![0.4]);+ other.studio_end(false);+ // a brush shared as a file comes in at the top of a set, edits and all+ let file = s.brush_file(start.set + 1, start.index + 1).unwrap();+ assert_eq!(other.import_brush_file(0, file), Some(0));+ assert!(other.select_brush(0, 0));+ other.studio_begin();+ assert_eq!(other.studio_settings(vec!["spacing".to_owned()]), vec![0.4]);+ other.studio_end(false);+ assert_eq!(other.import_brush_file(0, "{}".to_owned()), None);+ // a set shared as a file comes in at the top of the library; a copy goes just above+ let file = s.brush_set_file(start.set + 1).unwrap();+ let count = other.brush_library().len();+ assert_eq!(other.import_brush_file(3, file), Some(0));+ assert_eq!(other.brush_library().len(), count + 1);+ assert_eq!(other.brush_library()[0].brushes.len(), s.brush_library()[start.set as usize + 1].brushes.len());+ assert_eq!(other.duplicate_brush_set(0), Some(0));+ assert_eq!(other.brush_library()[1].name, other.brush_library()[0].name);+ // deleting a set takes its brushes; the last set stays+ assert!(s.delete_brush_set(start.set + 1));+ assert!(s.brush_library().iter().all(|set| set.name != set_name));+ while s.brush_library().len() > 1 {+ assert!(s.delete_brush_set(0));+ }+ assert!(!s.delete_brush_set(0));+ // a tool still draws with something+ s.stroke_begin(PointerKind::Finger, vec![sample(50.0, 50.0, 0.0)]);+ s.stroke_end(vec![]);+}++#[test]+fn exports_psd_tiff_pdf_and_layer_pngs() {+ let Some(s) = session(40, 30) else { return };+ s.set_brush_size(0.6);+ s.set_color(1.0, 0.0, 0.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(20.0, 15.0, 0.0)]);+ s.stroke_end(vec![]);+ let top = s.add_layer();+ s.set_color(0.0, 0.0, 1.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(10.0, 10.0, 0.0)]);+ s.stroke_end(vec![]);+ s.combine_down(top).unwrap();+ s.add_mask(top).unwrap();+ let dir = std::env::temp_dir().join(format!("procraft-export-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let path = |name: &str| dir.join(name).to_string_lossy().into_owned();+ s.export_psd(path("a.psd")).unwrap();+ let psd = std::fs::read(dir.join("a.psd")).unwrap();+ assert_eq!(&psd[..4], b"8BPS");+ // a group's end marker, the background, and the mask (channel -2) are there+ assert!(psd.windows(14).any(|w| w == b"</Layer group>") && psd.windows(10).any(|w| w == b"Background"));+ assert!(psd.windows(2).any(|w| w == [0xFF, 0xFE]));+ s.export_tiff(path("a.tif")).unwrap();+ assert_eq!(&std::fs::read(dir.join("a.tif")).unwrap()[..4], b"II*\0");+ s.export_pdf(path("a.pdf"), true, 100).unwrap();+ let pdf = String::from_utf8_lossy(&std::fs::read(dir.join("a.pdf")).unwrap()).into_owned();+ assert!(pdf.contains("/Count 2"));+ s.export_pdf(path("b.pdf"), false, 60).unwrap();+ let pngs = s.export_layer_pngs(path("pngs")).unwrap();+ assert_eq!(pngs.len(), 2);+ assert!(pngs.iter().all(|p| std::path::Path::new(p).exists()));+ std::fs::remove_dir_all(&dir).unwrap();+}++#[test]+fn text_is_edited_as_one_step_and_rasterized() {+ use crate::text::{TextAlignment, TextInfo};+ let Some(s) = session(40, 40) else { return };+ let info = TextInfo {+ text: "Hi".to_owned(),+ font: "sans-serif".to_owned(),+ style: "Regular".to_owned(),+ size: 20.0,+ kerning: 0.0,+ tracking: 0.0,+ leading: 0.0,+ baseline: 0.0,+ opacity: 1.0,+ align: TextAlignment::Left,+ underline: false,+ outline: false,+ vertical: false,+ all_caps: false,+ r: 1.0,+ g: 0.0,+ b: 0.0,+ x: 2.0,+ y: 2.0,+ width: 0.0,+ };+ let red = [255u8, 0, 0, 255].repeat(40 * 40);+ let id = s.text_begin(None, info.clone()).unwrap();+ assert_eq!(s.editing_text(), Some(id));+ s.put_text_pixels(red.clone());+ assert!(s.set_text(TextInfo { text: "Hello".to_owned(), ..info.clone() }));+ s.put_text_pixels(red.clone());+ assert_eq!(pixel(&s, 5, 5), [255, 0, 0, 255]);+ s.text_end(true);+ let layer = s.layers().into_iter().find(|l| l.id == id).unwrap();+ assert!(layer.text && layer.name == "Hello");+ assert_eq!(s.layer_text(id).unwrap().text, "Hello");+ // a text layer takes no paint+ s.set_color(0.0, 0.0, 1.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(5.0, 5.0, 0.0)]);+ s.stroke_end(vec![]);+ assert_eq!(pixel(&s, 5, 5), [255, 0, 0, 255]);+ // one undo takes the new text layer away; redo brings it back+ s.undo();+ assert_eq!((s.layers().len(), pixel(&s, 5, 5)), (1, [255, 255, 255, 255]));+ s.redo();+ assert_eq!(s.layer_text(id).unwrap().text, "Hello");+ assert_eq!(pixel(&s, 5, 5), [255, 0, 0, 255]);+ // edited again and cancelled, it is as it was+ assert_eq!(s.text_begin(Some(id), info.clone()), Some(id));+ s.set_text(TextInfo { text: "Changed".to_owned(), ..info.clone() });+ s.put_text_pixels([0u8, 255, 0, 255].repeat(40 * 40));+ s.text_end(false);+ assert_eq!(s.layer_text(id).unwrap().text, "Hello");+ assert_eq!(pixel(&s, 5, 5), [255, 0, 0, 255]);+ // new text left empty goes away+ let count = s.layers().len();+ s.text_begin(None, TextInfo { text: String::new(), ..info.clone() }).unwrap();+ s.text_end(true);+ assert_eq!(s.layers().len(), count);+ // rasterized, it takes paint+ assert!(s.rasterize_layer(id) && s.layer_text(id).is_none());+ assert!(s.select_layer(id));+ s.stroke_begin(PointerKind::Finger, vec![sample(5.0, 5.0, 0.0)]);+ s.stroke_end(vec![]);+ assert_ne!(pixel(&s, 5, 5), [255, 0, 0, 255]);+}++#[test]+fn the_canvas_thumbnail_is_the_picture() {+ let Some(s) = session(64, 64) else { return };+ s.set_background_color(0.0, 1.0, 0.0, true);+ let t = s.canvas_thumbnail(16).unwrap();+ assert_eq!((t.width, t.height), (16, 16));+ assert_eq!(&t.rgba[..4], &[0, 255, 0, 255]);+}++#[test]+fn a_crop_resizes_and_undoes_and_redoes() {+ let Some(s) = session(64, 64) else { return };+ s.set_brush_size(0.3);+ s.set_color(1.0, 0.0, 0.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(40.0, 40.0, 0.0)]);+ s.stroke_end(vec![]);+ assert_eq!(pixel(&s, 40, 40), [255, 0, 0, 255]);+ // keep the 32 x 32 square from (24, 24): the dot lands at (16, 16)+ assert!(s.crop_canvas(24.0, 24.0, 32.0, 32.0, 0.0, false, 0, 0));+ assert_eq!((s.info().width, s.info().height), (32, 32));+ assert_eq!(pixel(&s, 16, 16), [255, 0, 0, 255]);+ assert!(s.info().can_undo);+ // painting after, then undoing that and the crop+ s.set_color(0.0, 0.0, 1.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(5.0, 5.0, 0.0)]);+ s.stroke_end(vec![]);+ s.undo();+ s.undo();+ assert_eq!((s.info().width, s.info().height), (64, 64));+ assert_eq!(pixel(&s, 40, 40), [255, 0, 0, 255]);+ assert!(s.info().can_redo);+ s.redo();+ assert_eq!((s.info().width, s.info().height), (32, 32));+ assert_eq!(pixel(&s, 16, 16), [255, 0, 0, 255]);+ // resampled to twice the size+ assert!(s.crop_canvas(0.0, 0.0, 32.0, 32.0, 0.0, true, 64, 48));+ assert_eq!((s.info().width, s.info().height), (64, 48));+ assert_eq!(pixel(&s, 32, 24), [255, 0, 0, 255]);+ // undone, then something new: the crop can't be redone+ s.undo();+ s.set_color(0.0, 1.0, 0.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(2.0, 2.0, 0.0)]);+ s.stroke_end(vec![]);+ s.redo();+ assert_eq!((s.info().width, s.info().height), (32, 32));+}++#[test]+fn an_artwork_from_a_picture() {+ use crate::layers::ThumbnailImage;+ let rgba = [255u8, 0, 0, 128].repeat(6 * 4);+ let s = CanvasSession::from_image(ThumbnailImage { width: 6, height: 4, rgba }, " Photo ".to_owned());+ assert_eq!((s.info().width, s.info().height), (6, 4));+ assert_eq!(s.name(), "Photo");+ let st = s.shared.lock();+ let (_, pixels) = st.pending_pixels.first().unwrap();+ assert_eq!(&pixels[..4], &[128, 0, 0, 128]);+}++#[test]+fn curve_samples_follow_the_curve() {+ let straight = crate::studio::curve_samples(vec![0.0, 0.0, 1.0, 1.0], 5);+ assert_eq!(straight.len(), 5);+ for (i, v) in straight.iter().enumerate() {+ assert!((v - i as f32 / 4.0).abs() < 1e-5);+ }+ // through a raised middle point, never above the top+ let bent = crate::studio::curve_samples(vec![0.0, 0.0, 0.5, 0.8, 1.0, 1.0], 101);+ assert!((bent[50] - 0.8).abs() < 1e-4);+ assert!(bent.iter().all(|v| (0.0..=1.0).contains(v)));+}++#[test]+fn layers_export_as_animations() {+ let Some(s) = session(40, 40) else { return };+ s.set_brush_size(0.6);+ s.set_color(1.0, 0.0, 0.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(20.0, 15.0, 0.0)]);+ s.stroke_end(vec![]);+ s.add_layer();+ s.set_color(0.0, 0.0, 1.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(10.0, 10.0, 0.0)]);+ s.stroke_end(vec![]);+ assert_eq!(s.animation_frame_count(), 2);+ // each frame shows its own layer alone: red over white, then blue with nothing behind+ let first = s.animation_frame(0, false, 0).unwrap();+ assert_eq!((first.width, first.height), (40, 40));+ let px = |f: &crate::layers::ThumbnailImage| f.rgba.chunks(4).map(|p| p.to_vec()).collect::<Vec<_>>();+ assert!(px(&first).iter().all(|p| p[3] == 255 && p[0] >= p[2]));+ assert!(px(&first).iter().any(|p| p[0] > 200 && p[2] < 50));+ let second = s.animation_frame(1, true, 20).unwrap();+ assert_eq!((second.width, second.height), (20, 20));+ assert!(px(&second).iter().all(|p| p[3] == 0 || p[2] >= p[0]));+ assert!(px(&second).iter().any(|p| p[3] == 0), "no background when transparent");+ assert!(s.animation_frame(2, false, 0).is_none());+ let dir = std::env::temp_dir().join(format!("procraft-animation-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let path = |name: &str| dir.join(name).to_string_lossy().into_owned();+ s.export_gif(path("a.gif"), 0, 15.0, true, false).unwrap();+ let gif = std::fs::read(dir.join("a.gif")).unwrap();+ assert_eq!(&gif[..6], b"GIF89a");+ assert_eq!(gif.windows(3).filter(|w| w == &[0x21, 0xF9, 4]).count(), 2);+ s.export_apng(path("a.png"), 0, 15.0, false).unwrap();+ let png = std::fs::read(dir.join("a.png")).unwrap();+ assert!(png.windows(4).any(|w| w == b"acTL") && png.windows(4).any(|w| w == b"fdAT"));+ std::fs::remove_dir_all(&dir).ok();+}++#[test]+fn animation_assist_shows_onion_skins_and_plays() {+ let Some(s) = session(40, 40) else { return };+ s.set_brush_size(0.6);+ s.set_color(1.0, 0.0, 0.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(20.0, 20.0, 0.0)]);+ s.stroke_end(vec![]);+ let second = s.add_layer();+ s.set_color(0.0, 0.0, 1.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(20.0, 20.0, 0.0)]);+ s.stroke_end(vec![]);+ assert!(s.animation_settings().is_none());+ assert!(s.set_animation_assist(true));+ assert_eq!(s.animation_settings().unwrap().fps, 15);+ assert_eq!(s.animation_frames().len(), 2);+ assert_eq!(s.current_frame(), Some(1));+ // drawing on the second frame, the first shows under it as an onion skin; playing the first,+ // only it shows+ s.set_play_frame(Some(0));+ {+ let mut st = s.shared.lock();+ let st = &mut *st;+ let (canvas, gpu) = (st.canvas.as_mut().unwrap(), st.gpu.as_ref().unwrap());+ canvas.render(gpu, &mut st.doc, None);+ let rgba = canvas.read_composite(gpu).unwrap();+ let i = (20 * 40 + 20) * 4;+ assert!(rgba[i] > 200 && rgba[i + 2] < 60, "the first frame alone: red");+ }+ s.set_play_frame(None);+ let mut settings = s.animation_settings().unwrap();+ settings.fps = 99;+ s.set_animation_settings(settings);+ assert_eq!(s.animation_settings().unwrap().fps, 60);+ s.set_frame_hold(second, 2);+ assert_eq!(s.frame_hold(second), 2);+ assert!(s.set_animation_assist(false));+ assert!(s.animation_settings().is_none());+}++#[test]+fn layers_at_a_point_are_listed_top_first() {+ let Some(s) = session(40, 40) else { return };+ let bottom = s.layers().last().unwrap().id;+ s.set_brush_size(0.3);+ s.stroke_begin(PointerKind::Finger, vec![sample(10.0, 10.0, 0.0)]);+ s.stroke_end(vec![]);+ let top = s.add_layer();+ s.stroke_begin(PointerKind::Finger, vec![sample(10.0, 10.0, 0.0)]);+ s.stroke_end(vec![]);+ s.stroke_begin(PointerKind::Finger, vec![sample(32.0, 32.0, 0.0)]);+ s.stroke_end(vec![]);+ assert_eq!(s.layers_at(10.0, 10.0), vec![top, bottom]);+ assert_eq!(s.layers_at(32.0, 32.0), vec![top]);+ assert!(s.layers_at(36.0, 4.0).is_empty());+ // hidden layers aren't picked+ s.set_layer_visible(top, false);+ assert_eq!(s.layers_at(10.0, 10.0), vec![bottom]);+}++#[test]+fn brushes_can_keep_their_size_on_the_screen() {+ let Some(s) = session(100, 100) else { return };+ let on_canvas = s.info().brush_diameter;+ // zoomed in twice: relative to the canvas the brush stays; relative to the screen it halves+ s.view_gesture(50.0, 50.0, 0.0, 0.0, 2.0, 0.0);+ assert!((s.info().brush_diameter - on_canvas).abs() < 1e-3);+ s.set_brush_scaling(true);+ assert!((s.info().brush_diameter - on_canvas / 2.0).abs() < 1e-2, "{} vs {}", s.info().brush_diameter, on_canvas);+ s.set_brush_scaling(false);+ assert!((s.info().brush_diameter - on_canvas).abs() < 1e-3);+}++#[test]+fn a_custom_canvas_keeps_its_size_dpi_background_and_name() {+ let s = CanvasSession::new_custom(1200, 800, 300.0, vec![0.25, 0.5, 0.75], false, " Sketch ".into());+ let info = s.info();+ assert_eq!((info.width, info.height, info.dpi), (1200, 800, 300.0));+ let bg = s.background();+ assert_eq!((bg.r, bg.g, bg.b, bg.visible), (0.25, 0.5, 0.75, false));+ assert_eq!(s.name(), "Sketch");+ // bad values are repaired, not kept+ let s = CanvasSession::new_custom(0, 5, f32::NAN, vec![2.0], true, " ".into());+ let info = s.info();+ assert_eq!((info.width, info.height), (1, 5));+ assert!(info.dpi.is_finite() && info.dpi >= 1.0);+ assert!(s.background().visible);+ assert_eq!(s.name(), "Untitled Artwork");+}++#[test]+fn the_last_stroke_snaps_to_a_shape_until_something_else_is_done() {+ use crate::quickshape::QuickShapeKind;+ let Some(s) = session(200, 200) else { return };+ s.set_brush_size(0.02);+ // a wavy line, drawn and lifted: it dips to y 64 at x 40 and rises to y 54 at x 76+ let line: Vec<PenSample> = (0..=40)+ .map(|i| sample(20.0 + 4.0 * i as f32, 60.0 + 5.0 * (i as f32 / 3.0).sin(), f64::from(i) * 8.0))+ .collect();+ s.stroke_begin(PointerKind::Finger, line[..1].to_vec());+ s.stroke_add(line[1..].to_vec());+ s.stroke_end(vec![]);+ // painted at (or a pixel beside) the dip and the rise+ let near = |x: u32, y: u32| (y - 1..=y + 1).any(|y| (x - 1..=x + 1).any(|x| pixel(&s, x, y)[0] < 128));+ assert!(near(40, 64) && near(76, 54));+ let info = s.quickshape_last().expect("a shape");+ assert_eq!(info.kind, QuickShapeKind::Line);+ s.quickshape_done();+ // straight now: neither the dip nor the rise is painted+ assert_eq!(pixel(&s, 40, 64), [255, 255, 255, 255]);+ assert_eq!(pixel(&s, 76, 54), [255, 255, 255, 255]);+ assert!((50..70).any(|y| pixel(&s, 100, y)[0] < 128));+ // one step: undone, nothing is left+ s.undo();+ assert!((50..70).all(|y| pixel(&s, 100, y) == [255, 255, 255, 255]));+ // once something else is done (an undo here), there is no last stroke to snap+ s.stroke_begin(PointerKind::Finger, line[..1].to_vec());+ s.stroke_add(line[1..].to_vec());+ s.stroke_end(vec![]);+ s.undo();+ assert!(s.quickshape_last().is_none());+}++#[test]+fn a_brush_moves_to_another_set_and_the_tool_keeps_it() {+ let s = CanvasSession::new(64, 64);+ let before = s.brush_library();+ let moved = before[0].brushes[1].name.clone();+ assert!(s.select_brush(0, 1));+ assert!(s.move_brush(0, 1, 1, 0));+ let after = s.brush_library();+ assert_eq!(after[1].brushes[0].name, moved);+ assert_eq!(after[0].brushes.len(), before[0].brushes.len() - 1);+ assert_eq!(after[1].brushes.len(), before[1].brushes.len() + 1);+ let c = s.current_brush();+ assert_eq!((c.set, c.index), (1, 0));+ // along its own set, the last to the top: the chosen brush moves down one+ let n = after[1].brushes.len();+ let last = after[1].brushes[n - 1].name.clone();+ assert!(s.move_brush(1, n as u32 - 1, 1, 0));+ assert_eq!(s.brush_library()[1].brushes[0].name, last);+ assert_eq!(s.current_brush().index, 1);+ // nowhere to go, or nothing there: refused+ assert!(!s.move_brush(99, 0, 0, 0));+ assert!(!s.move_brush(0, 0, 99, 0));+}++#[test]+fn a_moved_layer_snaps_onto_another_layers_bounds() {+ use crate::transform::{GuideSettings, TransformHandle};+ let Some(s) = session(100, 100) else { return };+ s.set_brush_size(0.4);+ // a dot on the first layer: where its box's middle is+ s.stroke_begin(PointerKind::Finger, vec![sample(70.0, 30.0, 0.0)]);+ s.stroke_end(vec![]);+ let first = s.transform_begin().unwrap();+ let middle = (first.corners[0] + first.corners[2]) / 2.0;+ s.transform_end(false);+ // a dot on a new layer, moved to 2.5 from the first dot's middle: it lands on it+ s.add_layer();+ s.stroke_begin(PointerKind::Finger, vec![sample(30.0, 80.0, 0.0)]);+ s.stroke_end(vec![]);+ s.transform_begin().unwrap();+ s.transform_set_guides(GuideSettings { magnetics: false, snapping: true, distance: 3.0, velocity: 10.0 });+ s.transform_grab(TransformHandle::Move, 30.0, 80.0);+ let moved = s.transform_drag(30.0 + (middle - 30.0) + 2.5, 80.0).unwrap();+ let now = (moved.corners[0] + moved.corners[2]) / 2.0;+ assert!((now - middle).abs() < 0.01, "{now} vs {middle}");+ s.transform_end(false);+}++#[test]+fn a_held_lasso_snaps_to_the_shape_it_looks_like() {+ // a rough circle, as x and y in turn+ let pts: Vec<f32> = (0..=60)+ .flat_map(|i| {+ let t = i as f32 / 60.0 * std::f32::consts::TAU;+ [100.0 + 60.0 * t.cos() + 2.0 * (7.0 * t).sin(), 100.0 + 60.0 * t.sin()]+ })+ .collect();+ let outline = crate::quickshape::quickshape_outline(pts).expect("a shape");+ assert!(outline.len() >= 6 && outline.len().is_multiple_of(2));+ // every point of it near the circle+ for p in outline.chunks(2) {+ let r = ((p[0] - 100.0).powi(2) + (p[1] - 100.0).powi(2)).sqrt();+ assert!((r - 60.0).abs() < 8.0, "{r}");+ }+ assert!(crate::quickshape::quickshape_outline(vec![1.0, 1.0]).is_none());+}++#[test]+fn a_brush_paints_with_a_shape_of_the_users_own_and_keeps_it() {+ let Some(s) = session(100, 100) else { return };+ s.set_brush_size(0.3);+ let n = crate::studio::source_size() as usize;+ // a filled square: square stamps where the round pen's are round+ s.studio_begin();+ assert!(!s.set_studio_source(false, vec![255; 10]), "the wrong size is refused");+ assert!(s.set_studio_source(false, vec![255; n * n]));+ assert_eq!(s.studio_source(false).len(), n * n);+ s.studio_end(true);+ s.stroke_begin(PointerKind::Finger, vec![sample(50.0, 50.0, 0.0)]);+ s.stroke_end(vec![]);+ let corner = (40..50).find(|&d| pixel(&s, d, d)[0] < 128);+ let edge = (40..50).find(|&d| pixel(&s, d, 50)[0] < 128);+ // the square reaches as far along the diagonal as across+ let (Some(c), Some(e)) = (corner, edge) else { panic!("{corner:?} {edge:?}") };+ assert!(c <= e + 1, "{c} vs {e}");+ // kept with the library and back+ let saved = s.saved_brush_library();+ let t = CanvasSession::new(64, 64);+ assert!(t.load_brush_library(saved));+ t.studio_begin();+ assert_eq!(t.studio_source(false), vec![255; n * n]);+ // a shipped shape again+ assert!(t.set_studio_shipped_source(false, 0));+ assert_ne!(t.studio_source(false), vec![255; n * n]);+ assert_eq!(crate::studio::source_library(true).len(), procraft_engine::textures::grains().len());+}++#[test]+fn an_artwork_opens_as_it_was_shown() {+ let Some(s) = session(100, 100) else { return };+ s.view_gesture(50.0, 50.0, 5.0, -3.0, 2.0, 0.4);+ let shown = s.shared.lock().view.unwrap();+ let dir = std::env::temp_dir().join(format!("procraft-view-{}", std::process::id()));+ s.save(dir.to_string_lossy().into_owned()).unwrap();+ let t = CanvasSession::open(dir.to_string_lossy().into_owned()).unwrap();+ let back = t.shared.lock().saved_view.and_then(|v| v.view((100, 100))).unwrap();+ let (a, b) = (shown.to_screen(), back.to_screen());+ for (x, y) in [(a.a, b.a), (a.b, b.b), (a.c, b.c), (a.d, b.d), (a.e, b.e), (a.f, b.f)] {+ assert!((x - y).abs() < 1e-2, "{a:?} vs {b:?}");+ }+ // without the memory it opens fitted+ t.forget_saved_view();+ assert!(t.shared.lock().saved_view.is_none());+ let _ = std::fs::remove_dir_all(&dir);+}++#[test]+fn saves_at_the_same_time_keep_the_layers_whole() {+ let Some(s) = session(300, 300) else { return };+ s.set_brush_size(0.5);+ for i in 0..10 {+ let y = 20.0 + 25.0 * i as f32;+ s.stroke_begin(PointerKind::Finger, vec![sample(10.0, y, 0.0)]);+ s.stroke_add((1..30).map(|k| sample(10.0 + 9.0 * k as f32, y + 3.0, f64::from(k) * 8.0)).collect());+ s.stroke_end(vec![]);+ }+ let dir = std::env::temp_dir().join(format!("procraft-twice-{}", std::process::id()));+ let path = dir.to_string_lossy().into_owned();+ // the open's save and the close's save, together, a few times over+ for _ in 0..4 {+ std::thread::scope(|scope| {+ let a = scope.spawn(|| s.save(path.clone()));+ let b = scope.spawn(|| s.save(path.clone()));+ assert!(a.join().unwrap().is_ok() && b.join().unwrap().is_ok());+ });+ }+ let back = CanvasSession::open(path).unwrap();+ let pending = back.shared.lock().pending_pixels.clone();+ let painted = pending.iter().map(|(_, px)| px.chunks(4).filter(|p| p[3] > 0).count()).sum::<usize>();+ assert!(painted > 5000, "{painted}");+ // nothing left over from the writes+ let left: Vec<_> = std::fs::read_dir(dir.join("layers"))+ .unwrap()+ .flatten()+ .filter(|e| e.path().extension().is_some_and(|x| x == "tmp"))+ .collect();+ assert!(left.is_empty(), "{left:?}");+ let _ = std::fs::remove_dir_all(&dir);+}++#[test]+fn frosted_panels_come_six_numbers_each() {+ let Some(s) = session(100, 100) else { return };+ s.set_backdrops(vec![10.0, 20.0, 60.0, 80.0, 12.0, 0.5, 1.0, 2.0]);+ assert_eq!(s.shared.lock().backdrops, vec![[10.0, 20.0, 60.0, 80.0, 12.0, 0.5]]);+ s.set_backdrops(Vec::new());+ assert!(s.shared.lock().backdrops.is_empty());+}++#[test]+fn sets_kept_under_the_old_icon_numbering_get_their_icons_back() {+ let Some(s) = session(100, 100) else { return };+ let old = r#"[{"name":"Inking","brushes":[],"icon":1},{"name":"Mine","brushes":[],"icon":7}]"#;+ assert!(s.load_brush_library(old.to_owned()));+ let icons: Vec<u32> = s.shared.lock().library.iter().map(|set| set.icon).collect();+ // the shipped set its own icon, the other the brush+ assert_eq!(icons, vec![43, 5]);+ // kept again, they stay+ let kept = s.saved_brush_library();+ assert!(s.load_brush_library(kept));+ assert_eq!(s.shared.lock().library.iter().map(|set| set.icon).collect::<Vec<_>>(), vec![43, 5]);+}++#[test]+fn a_canvas_keeps_its_colour_profile() {+ let Some(s) = session(40, 30) else { return };+ assert_eq!(s.profile(), "sRGB IEC61966-2.1");+ assert!(!s.set_new_profile("Adobe RGB".to_owned()));+ assert!(s.set_new_profile("Display P3".to_owned()));+ let dir = std::env::temp_dir().join(format!("procraft-profile-{}", std::process::id()));+ s.save(dir.to_string_lossy().into_owned()).unwrap();+ let t = CanvasSession::open(dir.to_string_lossy().into_owned()).unwrap();+ assert_eq!(t.profile(), "Display P3");+ assert_eq!(crate::colour::color_profiles().first().map(String::as_str), Some("Display P3"));+ let _ = std::fs::remove_dir_all(dir);+}++#[test]+fn a_p3_canvas_exports_with_its_profile() {+ let Some(s) = session(20, 10) else { return };+ assert!(s.set_new_profile("Display P3".to_owned()));+ let path = std::env::temp_dir().join(format!("procraft-p3-{}.png", std::process::id()));+ s.export_png(path.to_string_lossy().into_owned()).unwrap();+ let reader = png::Decoder::new(std::io::BufReader::new(std::fs::File::open(&path).unwrap())).read_info().unwrap();+ let icc = reader.info().icc_profile.as_ref().expect("an embedded profile").to_vec();+ assert_eq!(icc, procraft_engine::icc::icc(procraft_engine::profile::Profile::DisplayP3));+ let _ = std::fs::remove_file(path);+}++#[test]+fn a_cmyk_canvas_keeps_rgb_pixels_and_prints_its_inks() {+ let Some(s) = session(20, 10) else { return };+ let cmyk = procraft_engine::cmyk::NAME.to_owned();+ assert!(s.set_new_profile(cmyk.clone()));+ assert!(s.is_cmyk());+ assert_eq!(s.profile(), cmyk);+ // the colour panel's numbers: green takes cyan and yellow; white is the paper+ let inks = s.cmyk_of(0x00FF00);+ assert!(inks[0] > 0.3 && inks[1] < 0.05 && inks[2] > 0.5 && inks[3] < 0.05, "{inks:?}");+ assert_eq!(s.cmyk_of(0xFFFFFF), vec![0.0; 4]);+ let proofed = s.proof_color(0x00FF00);+ assert_ne!(proofed, 0x00FF00, "pure green can't be printed");+ assert_eq!(s.rgb_of_cmyk(vec![0.0; 4]) & 0xF0F0F0, 0xF0F0F0, "no ink shows the paper");+ // a green layer: the layer keeps green; the PNG shows the press's green, the TIFF its inks+ s.set_brush_size(1.0);+ s.set_color(0.0, 1.0, 0.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(2.0, 5.0, 0.0), sample(18.0, 5.0, 10.0)]);+ s.stroke_end(vec![]);+ assert_eq!(pixel(&s, 10, 5), [0, 255, 0, 255]);+ let dir = std::env::temp_dir().join(format!("procraft-cmyk-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let png_path = dir.join("a.png");+ s.export_png(png_path.to_string_lossy().into_owned()).unwrap();+ let mut reader =+ png::Decoder::new(std::io::BufReader::new(std::fs::File::open(&png_path).unwrap())).read_info().unwrap();+ let icc = reader.info().icc_profile.as_ref().unwrap().to_vec();+ assert_eq!(icc, procraft_engine::icc::icc(procraft_engine::profile::Profile::DisplayP3));+ let mut buf = vec![0; reader.output_buffer_size().unwrap()];+ reader.next_frame(&mut buf).unwrap();+ let at = (5 * 20 + 10) * 4;+ let shown = (u32::from(buf[at]) << 16) | (u32::from(buf[at + 1]) << 8) | u32::from(buf[at + 2]);+ assert!(shown != 0x00FF00 && buf[at] > 40, "{shown:06x}");+ s.export_tiff(dir.join("a.tif").to_string_lossy().into_owned()).unwrap();+ let tiff = std::fs::read(dir.join("a.tif")).unwrap();+ // photometric 5: separated inks+ assert!(tiff.windows(4).any(|w| w == [6, 1, 3, 0]) && tiff.windows(8).any(|w| w == [6, 1, 3, 0, 1, 0, 0, 0]));+ // saved and opened again, it is still CMYK+ s.save(dir.join("art").to_string_lossy().into_owned()).unwrap();+ let t = CanvasSession::open(dir.join("art").to_string_lossy().into_owned()).unwrap();+ assert!(t.is_cmyk());+ assert_eq!(t.profile(), cmyk);+ let _ = std::fs::remove_dir_all(dir);+}++#[test]+fn changing_the_profile_turns_the_colours_and_undoes() {+ let Some(s) = session(100, 100) else { return };+ s.set_brush_size(0.4);+ s.set_color(1.0, 0.0, 0.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(20.0, 50.0, 0.0)]);+ s.stroke_end(vec![]);+ assert!(!s.change_profile("sRGB IEC61966-2.1".to_owned()));+ assert!(!s.change_profile("Adobe RGB".to_owned()));+ assert!(s.change_profile("Display P3".to_owned()));+ assert_eq!(s.profile(), "Display P3");+ // the red in P3's numbers; white stays white+ assert_eq!(pixel(&s, 20, 50), [0xEA, 0x33, 0x23, 255]);+ assert_eq!(pixel(&s, 80, 80), [255, 255, 255, 255]);+ // one undo step puts the numbers and the profile back+ s.undo();+ assert_eq!(s.profile(), "sRGB IEC61966-2.1");+ assert_eq!(pixel(&s, 20, 50), [255, 0, 0, 255]);+ s.redo();+ assert_eq!(s.profile(), "Display P3");+ assert_eq!(pixel(&s, 20, 50), [0xEA, 0x33, 0x23, 255]);+}++#[test]+fn an_artwork_never_shown_exports_offscreen() {+ let Some(s) = session(40, 40) else { return };+ s.set_brush_size(0.4);+ s.set_color(1.0, 0.0, 0.0);+ s.stroke_begin(PointerKind::Finger, vec![sample(20.0, 20.0, 0.0)]);+ s.stroke_end(vec![]);+ let dir = std::env::temp_dir().join(format!("procraft-offscreen-{}", std::process::id()));+ s.save(dir.to_string_lossy().into_owned()).unwrap();+ let t = CanvasSession::open(dir.to_string_lossy().into_owned()).unwrap();+ let png = dir.join("out.png");+ // not shown: no picture until it has a device of its own+ assert!(t.export_png(png.to_string_lossy().into_owned()).is_err());+ assert!(t.prepare_offscreen());+ t.export_png(png.to_string_lossy().into_owned()).unwrap();+ let mut reader =+ png::Decoder::new(std::io::BufReader::new(std::fs::File::open(&png).unwrap())).read_info().unwrap();+ let mut buf = vec![0; reader.output_buffer_size().unwrap()];+ let info = reader.next_frame(&mut buf).unwrap();+ let at = (20 * info.width as usize + 20) * 4;+ assert_eq!(&buf[at..at + 4], &[255, 0, 0, 255]);+ let _ = std::fs::remove_dir_all(dir);+}++#[test]+fn saving_while_idle_writes_only_what_changed() {+ let Some(s) = session(40, 40) else { return };+ let dir = std::env::temp_dir().join(format!("procraft-autosave-{}", std::process::id()));+ let path = dir.to_string_lossy().into_owned();+ s.save(path.clone()).unwrap();+ let edits = s.edits();+ // a stroke under way isn't cut short+ s.stroke_begin(PointerKind::Finger, vec![sample(20.0, 20.0, 0.0)]);+ assert!(!s.save_if_idle(path.clone()).unwrap());+ s.stroke_end(vec![]);+ assert_ne!(s.edits(), edits);+ assert!(s.save_if_idle(path.clone()).unwrap());+ // a new layer: the first one's file isn't written again+ let first = s.layers()[0].id;+ let file = dir.join("layers").read_dir().unwrap().flatten().next().unwrap().path();+ let written = std::fs::metadata(&file).unwrap().modified().unwrap();+ std::thread::sleep(std::time::Duration::from_millis(20));+ s.add_layer();+ assert!(s.save_if_idle(path.clone()).unwrap());+ assert_eq!(std::fs::metadata(&file).unwrap().modified().unwrap(), written);+ assert_eq!(dir.join("layers").read_dir().unwrap().count(), 2);+ let t = CanvasSession::open(path).unwrap();+ assert_eq!(t.layers().len(), 2);+ assert!(t.layers().iter().any(|l| l.id == first));+ let _ = std::fs::remove_dir_all(dir);+}++#[test]+fn what_shipped_later_joins_a_kept_library_once() {+ let s = CanvasSession::new(64, 64);+ let names = |s: &CanvasSession| s.brush_library().into_iter().map(|set| set.name).collect::<Vec<_>>();+ // a new library: every set, in shelf order, with the tools on their brushes+ let all = names(&s);+ assert_eq!(&all[..3], ["Sketching", "Inking", "Drawing"]);+ assert_eq!(s.current_brush().name, "Round Pen");+ let counts = s.shipped_brush_counts();+ // a library kept when the first six sets shipped with three, three, three, two, two and two+ let old = CanvasSession::new(64, 64);+ let first = ["Sketching", "Inking", "Painting", "Airbrushing", "Charcoals", "Textures"];+ while let Some(i) = names(&old).iter().position(|n| !first.contains(&n.as_str())) {+ assert!(old.delete_brush_set(i as u32));+ }+ let inking = names(&old).iter().position(|n| n == "Inking").unwrap() as u32;+ while old.brush_library()[inking as usize].brushes.len() > 3 {+ assert!(old.delete_brush(inking, 3));+ }+ let kept = old.saved_brush_library();+ let t = CanvasSession::new(64, 64);+ assert!(t.load_brush_library(kept));+ assert_eq!(t.brush_library().len(), 6);+ assert_eq!(t.add_shipped_brushes(vec![3, 3, 3, 2, 2, 2]), counts);+ // the new sets at the end, the new inking brushes after the old ones+ assert_eq!(t.brush_library().len(), all.len());+ let ink = &t.brush_library()[inking as usize];+ assert_eq!(ink.brushes.len() as u32, counts[1]);+ assert_eq!(ink.brushes[3].name, "Dip Pen");+ // and only once, whatever it is told+ assert_eq!(t.add_shipped_brushes(vec![0; 6]), counts);+ assert_eq!(t.brush_library().len(), all.len());+ assert_eq!(t.brush_library()[inking as usize].brushes.len() as u32, counts[1]);+}++#[test]+fn a_canvas_tells_the_view_it_will_open_with() {+ let s = CanvasSession::new(200, 100);+ // fitted: 400 × 400 shows it 400 wide, 200 tall, in the middle+ assert_eq!(s.opening_view_matrix(400, 400), vec![2.0, 0.0, 0.0, 2.0, 0.0, 100.0]);+}++#[test]+fn undo_and_redo_tell_what_they_undid() {+ let Some(s) = session(100, 100) else { return };+ s.stroke_begin(PointerKind::Finger, vec![sample(20.0, 50.0, 0.0)]);+ s.stroke_end(vec![]);+ s.flip_canvas(true);+ assert_eq!(s.undo().as_deref(), Some("flip canvas horizontally"));+ assert_eq!(s.undo().as_deref(), Some("Paint stroke"));+ assert_eq!(s.redo().as_deref(), Some("Paint stroke"));+ s.set_tool(ToolKind::Erase);+ s.stroke_begin(PointerKind::Finger, vec![sample(20.0, 50.0, 0.0)]);+ s.stroke_end(vec![]);+ assert_eq!(s.undo().as_deref(), Some("Erase stroke"));+ // layer changes, made at once or by a slider+ let id = s.add_layer();+ assert_eq!(s.undo().as_deref(), Some("new layer"));+ s.redo();+ s.set_layer_opacity(id, 0.5, false);+ s.set_layer_opacity(id, 0.4, true);+ assert_eq!(s.undo().as_deref(), Some("layer opacity"));+ s.set_layer_visible(id, false);+ assert_eq!(s.undo().as_deref(), Some("hide layer"));+ // selections+ use crate::selection::SelectionJoin;+ s.select_shape(false, 10.0, 10.0, 40.0, 40.0, SelectionJoin::Add);+ s.select_shape(false, 50.0, 50.0, 60.0, 60.0, SelectionJoin::Add);+ s.select_invert();+ s.select_none();+ assert_eq!(s.undo().as_deref(), Some("clear selection"));+ assert_eq!(s.undo().as_deref(), Some("invert"));+ assert_eq!(s.undo().as_deref(), Some("add to selection"));+ assert_eq!(s.undo().as_deref(), Some("draw selection"));+}++#[test]+fn a_stamp_preview_shows_the_stamp_alone() {+ let Some(s) = session(100, 100) else { return };+ let b = s.current_brush();+ // painted columns: a stroke reaches across the preview, a stamp keeps to its middle+ let reach = |s: &CanvasSession| {+ let p = s.brush_preview(b.set, b.index, 327, 100).unwrap();+ let cols: Vec<usize> = (0..327).filter(|&x| (0..100).any(|y| p.rgba[(y * 327 + x) * 4 + 3] > 0)).collect();+ (cols.first().copied().unwrap_or(0), cols.last().copied().unwrap_or(0))+ };+ let (left, right) = reach(&s);+ assert!(left < 50 && right > 270, "stroke {left}..{right}");+ s.studio_begin();+ s.set_studio_setting("preview_stamp".into(), 1.0);+ s.studio_end(true);+ let (left, right) = reach(&s);+ assert!(left > 110 && right < 220, "stamp {left}..{right}");+}++#[test]+fn slider_notches_are_kept_with_the_library() {+ let s = CanvasSession::new(64, 64);+ assert!(s.add_slider_notch(true, 0.3));+ assert!(s.add_slider_notch(false, 0.5));+ assert!(!s.add_slider_notch(true, 0.31));+ assert_eq!(s.slider_notches(true), vec![0.3]);+ let t = CanvasSession::new(64, 64);+ assert!(t.load_brush_library(s.saved_brush_library()));+ assert_eq!(t.slider_notches(true), vec![0.3]);+ assert_eq!(t.slider_notches(false), vec![0.5]);+ assert!(t.remove_slider_notch(true, 0.32));+ assert!(t.slider_notches(true).is_empty());+ assert!(!t.remove_slider_notch(true, 0.3));+}++#[test]+fn a_pad_keeps_its_strokes_and_its_sample_gives_way() {+ let pad = CanvasSession::new(200, 120);+ let kept = |p: &CanvasSession| {+ p.shared.lock().pad_strokes.as_ref().map(|k| k.iter().map(|(_, s)| s.len()).collect::<Vec<_>>())+ };+ // a canvas keeps nothing unless asked+ assert_eq!(kept(&pad), None);+ pad.keep_strokes();+ pad.draw_sample_scribble();+ assert_eq!(kept(&pad).map(|k| k.len()), Some(1));+ // one's own stroke takes the sample's place+ pad.begin_own_stroke();+ assert_eq!(kept(&pad), Some(vec![]));+ pad.stroke_begin(PointerKind::Finger, vec![sample(10.0, 10.0, 0.0)]);+ pad.stroke_add(vec![sample(50.0, 40.0, 16.0)]);+ pad.stroke_end(vec![sample(90.0, 60.0, 32.0)]);+ assert_eq!(kept(&pad), Some(vec![3]));+ // a second one isn't the sample: nothing goes+ pad.begin_own_stroke();+ pad.stroke_begin(PointerKind::Finger, vec![sample(10.0, 90.0, 0.0)]);+ pad.stroke_cancel();+ assert_eq!(kept(&pad), Some(vec![3]));+ // drawn again, it is kept as it was+ pad.replay_strokes();+ assert_eq!(kept(&pad), Some(vec![3]));+ pad.forget_strokes();+ assert_eq!(kept(&pad), Some(vec![]));+}++#[test]+fn choosing_a_layer_is_an_undo_step() {+ let Some(s) = session(32, 32) else { return };+ let current = |s: &CanvasSession| s.layers().iter().find(|l| l.current).map(|l| l.id);+ let first = current(&s).unwrap();+ let second = s.add_layer();+ // choosing the one already current makes no step+ assert!(s.select_layer(second));+ assert!(s.select_layer(first));+ assert_eq!(s.undo().as_deref(), Some("select layer"));+ assert_eq!(current(&s), Some(second));+ assert!(s.redo().is_some());+ assert_eq!(current(&s), Some(first));+}++#[test]+fn picked_layers_merge_duplicate_and_group_as_one_step_each() {+ let Some(s) = session(100, 100) else { return };+ let dot = |x: f32, y: f32, rgb: [f32; 3]| {+ s.set_color(rgb[0], rgb[1], rgb[2]);+ s.stroke_begin(PointerKind::Finger, vec![sample(x, y, 0.0)]);+ s.stroke_end(vec![]);+ };+ s.set_brush_size(0.6);+ dot(30.0, 30.0, [1.0, 0.0, 0.0]);+ let red = s.layers()[0].id;+ let middle = s.add_layer();+ let blue = s.add_layer();+ dot(70.0, 70.0, [0.0, 0.0, 1.0]);+ // blue current, red picked: the middle layer is left alone+ assert!(s.pick_layer(red));+ assert_eq!(s.chosen_layers(), [red, blue]);+ assert!(s.layers().iter().any(|l| l.id == red && l.picked));+ assert!(s.merge_picked());+ let ids: Vec<u64> = s.layers().iter().map(|l| l.id).collect();+ // top first+ assert_eq!(ids, [middle, red]);+ assert_eq!(pixel(&s, 70, 70), [0, 0, 255, 255]);+ assert_eq!(pixel(&s, 30, 30), [255, 0, 0, 255]);+ // one step undoes it all, the picks too+ assert_eq!(s.undo().as_deref(), Some("merge layers"));+ assert_eq!(s.layers().len(), 3);+ assert_eq!(s.chosen_layers(), [red, blue]);+ // the copies come out together above blue and are what is chosen+ assert!(s.duplicate_picked());+ assert_eq!(s.layers().len(), 5);+ let chosen = s.chosen_layers();+ assert!(chosen.iter().all(|c| ![red, middle, blue].contains(c)));+ assert_eq!(pixel(&s, 30, 30), [255, 0, 0, 255]);+ s.undo();+ let group = s.group_picked();+ assert_ne!(group, 0);+ let inside: Vec<u64> = s.layers().iter().filter(|l| l.parent == Some(group)).map(|l| l.id).collect();+ assert_eq!(inside, [blue, red]);+ assert!(s.layers().iter().all(|l| !l.picked));+ // choosing a layer clears the picks, as an undo step+ s.undo();+ assert!(s.select_layer(blue));+ assert!(s.chosen_layers() == [blue]);+ s.undo();+ assert_eq!(s.chosen_layers(), [red, blue]);+}++#[test]+fn picked_layers_transform_together() {+ use crate::transform::TransformHandle;+ let Some(s) = session(100, 100) else { return };+ let dot = |x: f32, y: f32| {+ s.stroke_begin(PointerKind::Finger, vec![sample(x, y, 0.0)]);+ s.stroke_end(vec![]);+ };+ dot(20.0, 20.0);+ let below = s.layers()[0].id;+ s.add_layer();+ dot(40.0, 40.0);+ // the box holds both dots+ assert!(s.pick_layer(below));+ let b = s.transform_begin().unwrap();+ let [x0, y0, x1, _, _, y1, ..] = b.corners[..] else { panic!() };+ assert!(x0 < 20.0 && y0 < 20.0 && x1 > 40.0 && y1 > 40.0, "{b:?}");+ s.transform_grab(TransformHandle::Move, 30.0, 30.0);+ s.transform_drag(60.0, 30.0);+ s.transform_release();+ s.transform_end(true);+ assert_eq!(pixel(&s, 50, 20), [0, 0, 0, 255]);+ assert_eq!(pixel(&s, 70, 40), [0, 0, 0, 255]);+ assert_eq!(pixel(&s, 20, 20), [255, 255, 255, 255]);+ // one step puts both back+ s.undo();+ assert_eq!(pixel(&s, 20, 20), [0, 0, 0, 255]);+ assert_eq!(pixel(&s, 40, 40), [0, 0, 0, 255]);+}++/// On request (`BRUSH_SHEET=path.png`): every library brush's sample stroke, three to a row on+/// dark grey, with their names listed beside it (`path.txt`), to look the library over.+#[test]+fn brush_sheet() {+ let Ok(out) = std::env::var("BRUSH_SHEET") else { return };+ let Some(s) = session(64, 64) else { return };+ let (cw, ch, cols) = (347u32, 110u32, 4u32);+ let brushes: Vec<(u32, u32, String)> = s+ .brush_library()+ .iter()+ .enumerate()+ .flat_map(|(i, set)| {+ set.brushes.iter().enumerate().map(move |(j, b)| (i as u32, j as u32, format!("{} / {}", set.name, b.name)))+ })+ .collect();+ let rows = (brushes.len() as u32).div_ceil(cols);+ let (w, h) = (cw * cols, ch * rows);+ let mut sheet: Vec<u8> = (0..w * h).flat_map(|_| [30u8, 30, 30, 255]).collect();+ let mut names = String::new();+ for (k, (set, index, name)) in brushes.iter().enumerate() {+ let (cx, cy) = ((k as u32 % cols) * cw, (k as u32 / cols) * ch);+ names.push_str(&format!("{} {}: {name}\n", k as u32 / cols, k as u32 % cols));+ let Some(p) = s.brush_preview(*set, *index, cw - 20, ch - 10) else { continue };+ for y in 0..p.height {+ for x in 0..p.width {+ let a = u32::from(p.rgba[((y * p.width + x) * 4 + 3) as usize]);+ let at = (((cy + 5 + y) * w + cx + 10 + x) * 4) as usize;+ for c in 0..3 {+ sheet[at + c] = ((30 * (255 - a) + 255 * a) / 255) as u8;+ }+ }+ }+ }+ let file = std::fs::File::create(&out).unwrap();+ let mut encoder = png::Encoder::new(std::io::BufWriter::new(file), w, h);+ encoder.set_color(png::ColorType::Rgba);+ encoder.write_header().unwrap().write_image_data(&sheet).unwrap();+ std::fs::write(format!("{out}.txt"), names).unwrap();+}++/// On request (`SET_SHEET=path.png`, `SET_FILE=set file`): the set file's brushes imported and+/// their previews drawn at the size brush files carry them, one to a row on dark grey.+#[test]+fn set_sheet() {+ let (Ok(out), Ok(file)) = (std::env::var("SET_SHEET"), std::env::var("SET_FILE")) else { return };+ let Some(s) = session(64, 64) else { return };+ let set = s.import_brushes(std::fs::read(file).unwrap()).unwrap();+ let count = s.brush_library().get(set as usize).unwrap().brushes.len() as u32;+ let (w, ch) = (327u32, 100u32);+ let h = ch * count;+ let mut sheet: Vec<u8> = (0..w * h).flat_map(|_| [30u8, 30, 30, 255]).collect();+ for k in 0..count {+ let Some(p) = s.brush_preview(set, k, w, ch) else { continue };+ for y in 0..p.height {+ for x in 0..p.width {+ let a = u32::from(p.rgba[((y * p.width + x) * 4 + 3) as usize]);+ let at = (((k * ch + y) * w + x) * 4) as usize;+ for c in 0..3 {+ sheet[at + c] = ((30 * (255 - a) + 255 * a) / 255) as u8;+ }+ }+ }+ }+ let file = std::fs::File::create(&out).unwrap();+ let mut encoder = png::Encoder::new(std::io::BufWriter::new(file), w, h);+ encoder.set_color(png::ColorType::Rgba);+ encoder.write_header().unwrap().write_image_data(&sheet).unwrap();+}++/// The rendering modes build up within a stroke as measured on the reference's drawing pad: a hard+/// round brush 22 px across, spaced as its file keeps 0.042, at 49% flow, one pass along a line.+#[test]+fn rendering_modes_build_up_as_measured() {+ use procraft_engine::brush::{Brush, Taper};+ use procraft_engine::document::Document;+ use procraft_engine::geom::Vec2;+ use procraft_engine::input::{Pointer, Sample};+ use procraft_engine::stroke::StrokeBuilder;+ use procraft_gpu::{Canvas, StrokeStyle, StrokeTool};+ let Ok(gpu) = Gpu::headless() else { return };+ let pass = |mode: f32| -> f32 {+ let mut b = Brush {+ streamline: 0.0,+ pressure_size: 0.0,+ pressure_opacity: 0.0,+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ hardness: 1.0,+ ..Brush::round_pen()+ };+ b.set_setting("spacing", (0.042f32 / 2.0).powf(1.0 / 2.2));+ b.set_setting("flow", 0.49);+ b.set_setting("rendering_mode", mode);+ let mut doc = Document::new(200, 60);+ doc.background_visible = false;+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ let layer = doc.current();+ let mut style = StrokeStyle::for_brush(&b, StrokeTool::Paint, [1.0, 1.0, 1.0], 1.0, false);+ canvas.use_sources(&gpu, &mut style, &b);+ canvas.begin_stroke(layer, style);+ let mut stroke = StrokeBuilder::new(b, 22.0, Pointer::Stylus);+ let samples: Vec<Sample> =+ (0..=40).map(|i| Sample::at(Vec2::new(20.0 + i as f32 * 4.0, 30.0), 1.0, f64::from(i) * 8.0)).collect();+ canvas.add_stamps(&stroke.add(&samples));+ canvas.replace_stamps(&stroke.finish());+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);+ let px = canvas.read_composite(&gpu).unwrap();+ f32::from(px[((30 * 200 + 100) * 4 + 3) as usize]) / 255.0+ };+ // Light Glaze keeps the strongest stamp: 0.49 to the power 2.5+ assert!((pass(0.0) - 0.170).abs() < 0.02, "light glaze {}", pass(0.0));+ // Intense Glaze (as Uniformed Glaze and Intense Blending) builds up over+ assert!((pass(2.0) - 0.826).abs() < 0.04, "intense glaze {}", pass(2.0));+ // Heavy Glaze (as Uniform Blending) builds up gradually+ assert!((pass(3.0) - 0.638).abs() < 0.04, "heavy glaze {}", pass(3.0));+}++#[test]+fn the_brushes_in_use_are_kept_between_sessions() {+ let s = CanvasSession::new(64, 64);+ let chosen = |s: &CanvasSession, set: usize| s.brush_library()[set].chosen;+ // a brush chosen in set 1 at a size of its own, then one in set 0: set 1 keeps showing its own+ assert!(s.select_brush(1, 2));+ s.set_brush_size(0.7);+ assert!(s.select_brush(0, 3));+ assert_eq!((chosen(&s, 0), chosen(&s, 1)), (Some(3), Some(2)));+ // set 1's choice moved into set 0: set 1 has none, set 0 keeps its later choice+ assert!(s.move_brush(1, 2, 0, 0));+ assert_eq!((chosen(&s, 0), chosen(&s, 1)), (Some(4), None));+ // kept with the library, they come back in a new session, sliders and all+ let (library, choices) = (s.saved_brush_library(), s.saved_brush_choices());+ let t = CanvasSession::new(64, 64);+ assert!(t.load_brush_library(library));+ assert!(t.load_brush_choices(choices));+ assert_eq!((t.current_brush().set, t.current_brush().index), (0, 4));+ assert_eq!((chosen(&t, 0), chosen(&t, 1)), (Some(4), None));+ assert!(t.select_brush(0, 0));+ assert!((t.info().size - 0.7).abs() < 1e-6);+ // what can't be read changes nothing; places no longer there are passed over+ assert!(!t.load_brush_choices("{".to_owned()));+ assert!(t.load_brush_choices(r#"{"tools":[[99,0],[0,99],[0,0]],"sets":[[7,900]]}"#.to_owned()));+ assert_eq!((t.current_brush().set, t.current_brush().index), (0, 0));+ assert_eq!(chosen(&t, 0), None);+}++#[test]+fn a_brush_keeps_its_maker_and_a_reset_point() {+ use procraft_engine::brush::Brush;+ use procraft_engine::brushfile::{self, Pictures};+ let s = CanvasSession::new(64, 64);+ // a file by someone, with their picture (and a signature that isn't a picture)+ let face = crate::project::rgba_png(2, 2, &[200; 16]);+ let shape = crate::project::rgba_png(1, 1, &[255; 4]);+ let file = brushfile::write(+ &Brush { name: "Theirs".to_owned(), spacing: 0.2, ..Brush::round_pen() },+ "Someone",+ &Pictures {+ shape_png: &shape,+ grain_png: None,+ thumbnail_png: &shape,+ author_png: Some(&face),+ signature_png: Some(b"not a png"),+ },+ );+ let set = s.import_brushes(file).unwrap();+ assert!(s.select_brush(set, 0));+ // opened in the studio the first time, it is set aside to go back to+ s.studio_begin();+ let about = s.studio_about();+ assert_eq!(+ (about.author.as_str(), about.picture.as_deref(), about.signature),+ ("Someone", Some(face.as_slice()), None)+ );+ let first = about.reset_made.unwrap();+ assert!(first > 0);+ let spacing = s.studio_settings(vec!["spacing".to_owned()])[0];+ s.set_studio_setting("spacing".to_owned(), 0.9);+ s.studio_end(true);+ // opened again, the reset point stays as it was; resetting goes back to it+ s.studio_begin();+ assert_eq!(s.studio_about().reset_made, Some(first));+ s.studio_reset();+ assert_eq!(s.studio_settings(vec!["spacing".to_owned()])[0], spacing);+ // a new one, kept even when the edits are cancelled; and kept with the library+ s.set_studio_setting("spacing".to_owned(), 0.6);+ s.studio_new_reset_point();+ s.studio_end(false);+ let t = CanvasSession::new(64, 64);+ assert!(t.load_brush_library(s.saved_brush_library()));+ assert!(t.select_brush(0, 0));+ t.studio_begin();+ assert_eq!(t.studio_about().author, "Someone");+ t.studio_reset();+ assert!((t.studio_settings(vec!["spacing".to_owned()])[0] - 0.6).abs() < 1e-6);+ // and the maker goes back out with the brush+ let out = brushfile::read(&s.brush_as_file(set, 0).unwrap()).unwrap();+ assert_eq!((out.author.as_str(), out.author_picture), ("Someone", Some(face)));+}++#[test]+fn a_rolling_grain_stays_put_when_painting_wet() {+ use procraft_engine::brush::{Brush, Grain, GrainMode};+ let Some(s) = session(200, 200) else { return };+ // a wet brush whose fine grain rolls along with the stroke, light enough for the grain to+ // show (built up in full, it fills in)+ let mut b = Brush {+ grain: Grain {+ image: Some(procraft_engine::textures::grain::NOISE),+ mode: GrainMode::Moving,+ scale: 256.0,+ depth: 1.0,+ source: None,+ },+ ..Brush::round_pen()+ };+ b.set_setting("rendering_mode", 5.0);+ b.set_setting("wet_pull", 0.5);+ b.set_setting("grain_movement", 1.0);+ b.set_setting("grain_offset_jitter", 0.0);+ b.set_setting("flow", 0.35);+ {+ let mut st = s.shared.lock();+ let (set, index) = st.paint_brush;+ st.library[set].brushes[index] = b;+ }+ s.set_brush_size(0.6);+ s.set_color(0.0, 0.0, 0.0);+ s.stroke_begin(+ PointerKind::Stylus,+ (0..60).map(|i| sample(20.0 + i as f32 * 3.0, 100.0, i as f64 * 8.0)).collect(),+ );+ s.stroke_end(vec![]);+ // along the stroke the grain shows, as it does across it, rather than smeared into streaks+ let row: Vec<f32> = (60..140).map(|x| f32::from(pixel(&s, x, 100)[0])).collect();+ let mean = row.iter().sum::<f32>() / row.len() as f32;+ let spread = (row.iter().map(|v| (v - mean).powi(2)).sum::<f32>() / row.len() as f32).sqrt();+ assert!(spread > 6.0, "{spread}");+}++#[test]+fn a_moving_grain_streaks_along_the_stroke_however_the_stamps_turn() {+ use procraft_engine::brush::{Brush, Grain, GrainMode};+ let Some(s) = session(200, 200) else { return };+ // a wet brush turning each stamp at random, its fine grain moving a tenth of the way along+ let mut b = Brush {+ grain: Grain {+ image: Some(procraft_engine::textures::grain::SPECKLED),+ mode: GrainMode::Moving,+ scale: 256.0,+ depth: 1.0,+ source: None,+ },+ ..Brush::round_pen()+ };+ b.shape.randomise = true;+ b.set_setting("rendering_mode", 5.0);+ b.set_setting("grain_movement", 0.9);+ b.set_setting("grain_offset_jitter", 0.0);+ b.set_setting("flow", 0.35);+ {+ let mut st = s.shared.lock();+ let (set, index) = st.paint_brush;+ st.library[set].brushes[index] = b;+ }+ s.set_brush_size(1.0);+ s.set_color(0.0, 0.0, 0.0);+ s.stroke_begin(+ PointerKind::Stylus,+ (0..60).map(|i| sample(20.0 + i as f32 * 3.0, 100.0, i as f64 * 8.0)).collect(),+ );+ s.stroke_end(vec![]);+ // the grain keeps its way up, so each stamp lays it a little further on: streaks along the+ // stroke, neighbours alike along it and not across it+ let at = |x: u32, y: u32| f32::from(pixel(&s, x, y)[0]);+ let (mut along, mut across) = (0.0, 0.0);+ for y in 96..104 {+ for x in 80..120 {+ along += (at(x + 1, y) - at(x, y)).abs();+ across += (at(x, y + 1) - at(x, y)).abs();+ }+ }+ assert!(across > 1.0 && along < across * 0.6, "along {along}, across {across}");+}++#[test]+fn stock_images_a_file_names_are_kept_and_named_again() {+ use procraft_engine::brush::{Brush, StockImage, StockImages};+ use procraft_engine::brushfile::{self, Pictures, Texture};+ use procraft_engine::textures::grain;+ let s = CanvasSession::new(64, 64);+ let png = crate::project::rgba_png(1, 1, &[255; 4]);+ let named = |name: &str| Some(StockImage { name: name.to_owned(), inverted: true });+ let file = brushfile::write(+ &Brush {+ name: "Stocked".to_owned(),+ stock: StockImages { shape: named("Hard-Round.png"), grain: named("Old-Recycled-Paper.png") },+ ..Brush::round_pen()+ },+ "",+ &Pictures { shape_png: &png, grain_png: None, thumbnail_png: &png, author_png: None, signature_png: None },+ );+ let set = s.import_brushes(file).unwrap();+ {+ let st = s.shared.lock();+ let b = &st.library[set as usize].brushes[0];+ assert_eq!(b.stock.grain.as_ref().map(|g| g.name.as_str()), Some("Old-Recycled-Paper.png"));+ assert_eq!(b.grain.image, Some(grain::RECYCLED));+ }+ // kept with the library, and our stand-in found again by name+ let t = CanvasSession::new(64, 64);+ assert!(t.load_brush_library(s.saved_brush_library()));+ let set = {+ let st = t.shared.lock();+ let set = st.library.iter().position(|x| x.brushes.iter().any(|b| b.name == "Stocked")).unwrap();+ let b = &st.library[set].brushes[0];+ assert_eq!(b.stock.shape.as_ref().map(|g| (g.name.as_str(), g.inverted)), Some(("Hard-Round.png", true)));+ assert_eq!(b.grain.image, Some(grain::RECYCLED));+ set as u32+ };+ // written out, it names them again+ let out = brushfile::read(&t.brush_as_file(set, 0).unwrap()).unwrap();+ assert_eq!(out.grain, Texture::Stock { name: "Old-Recycled-Paper.png".to_owned(), inverted: true });+ assert_eq!(out.shape, Texture::Stock { name: "Hard-Round.png".to_owned(), inverted: true });+}diff --git a/apps/procraft-android/src/text.rs b/apps/procraft-android/src/text.rsnew file mode 100644index 0000000..0ce5ce8--- /dev/null+++ b/apps/procraft-android/src/text.rs@@ -0,0 +1,196 @@+//! Text layers: text added and edited where it sits. The app lays the text out and draws it into+//! the layer's pixels; the layer keeps the text so it can be edited again, until it is rasterized.+//! An edit is one undo step, back to the text and the pixels as it began.++use procraft_engine::document::{LayerId, LayerText, TextAlign};++use crate::CanvasSession;++#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]+pub enum TextAlignment {+ Left,+ Center,+ Right,+ Justify,+}++/// A text layer's text and how it looks.+#[derive(Clone, Debug, PartialEq, uniffi::Record)]+pub struct TextInfo {+ pub text: String,+ /// The typeface's family and style names.+ pub font: String,+ pub style: String,+ /// Letter height, canvas pixels.+ pub size: f32,+ /// Fractions of the size, -1..1.+ pub kerning: f32,+ pub tracking: f32,+ pub leading: f32,+ pub baseline: f32,+ pub opacity: f32,+ pub align: TextAlignment,+ pub underline: bool,+ pub outline: bool,+ pub vertical: bool,+ pub all_caps: bool,+ /// sRGB 0..1.+ pub r: f32,+ pub g: f32,+ pub b: f32,+ /// The box's top left corner, canvas pixels, and the width it wraps at (0: no wrapping).+ pub x: f32,+ pub y: f32,+ pub width: f32,+}++impl From<&LayerText> for TextInfo {+ fn from(t: &LayerText) -> Self {+ TextInfo {+ text: t.text.clone(),+ font: t.font.clone(),+ style: t.style.clone(),+ size: t.size,+ kerning: t.kerning,+ tracking: t.tracking,+ leading: t.leading,+ baseline: t.baseline,+ opacity: t.opacity,+ align: match t.align {+ TextAlign::Left => TextAlignment::Left,+ TextAlign::Center => TextAlignment::Center,+ TextAlign::Right => TextAlignment::Right,+ TextAlign::Justify => TextAlignment::Justify,+ },+ underline: t.underline,+ outline: t.outline,+ vertical: t.vertical,+ all_caps: t.all_caps,+ r: t.color[0],+ g: t.color[1],+ b: t.color[2],+ x: t.origin[0],+ y: t.origin[1],+ width: t.width,+ }+ }+}++impl From<TextInfo> for LayerText {+ fn from(t: TextInfo) -> Self {+ LayerText {+ text: t.text,+ font: t.font,+ style: t.style,+ size: t.size,+ kerning: t.kerning,+ tracking: t.tracking,+ leading: t.leading,+ baseline: t.baseline,+ opacity: t.opacity,+ align: match t.align {+ TextAlignment::Left => TextAlign::Left,+ TextAlignment::Center => TextAlign::Center,+ TextAlignment::Right => TextAlign::Right,+ TextAlignment::Justify => TextAlign::Justify,+ },+ underline: t.underline,+ outline: t.outline,+ vertical: t.vertical,+ all_caps: t.all_caps,+ color: [t.r, t.g, t.b],+ origin: [t.x, t.y],+ width: t.width,+ }+ }+}++#[uniffi::export]+impl CanvasSession {+ /// Starts editing text: a new text layer above the current one with `info` (`id` none), or+ /// text layer `id`. Returns the layer being edited, or none if `id` isn't a text layer.+ pub fn text_begin(&self, id: Option<u64>, info: TextInfo) -> Option<u64> {+ self.text_end(true);+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.finish_stroke();+ st.settle();+ let before = st.doc.clone();+ let layer = match id {+ Some(id) => {+ let id = LayerId(id);+ st.doc.layer(id).filter(|l| l.text.is_some() && !l.locked)?;+ st.doc.set_current(id);+ id+ }+ None if st.doc.has_room(1) => st.doc.add_text_layer(info.into()),+ None => return None,+ };+ if let Some(canvas) = st.canvas.as_mut() {+ canvas.hold_layer(layer);+ }+ st.text_edit = Some((layer, before));+ st.revision += 1;+ self.shared.frame(st);+ Some(layer.0)+ }++ /// Changes the text being edited (one undo step when the edit ends).+ pub fn set_text(&self, info: TextInfo) -> bool {+ let mut st = self.shared.lock();+ let Some((layer, _)) = st.text_edit.as_ref() else { return false };+ let layer = *layer;+ let ok = st.doc.set_text(layer, info.into());+ if ok {+ st.revision += 1;+ }+ ok+ }++ /// The text being edited, drawn into its layer: premultiplied RGBA8, the canvas's size.+ pub fn put_text_pixels(&self, rgba: Vec<u8>) -> bool {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let Some((layer, _)) = st.text_edit.as_ref() else { return false };+ let layer = *layer;+ let Some(canvas) = st.canvas.as_mut() else { return false };+ canvas.put_layer(layer, rgba);+ self.shared.frame(st);+ true+ }++ /// Ends editing text: `keep` makes the edit one undo step; otherwise the layer goes back to+ /// how it was (a new one goes away). New text left empty goes away too.+ pub fn text_end(&self, keep: bool) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let Some((layer, before)) = st.text_edit.take() else { return };+ let new = before.layer(layer).is_none();+ let empty = st.doc.layer(layer).and_then(|l| l.text.as_ref()).is_none_or(|t| t.text.trim().is_empty());+ let keep = keep && !(new && empty);+ if let Some(canvas) = st.canvas.as_mut() {+ canvas.release_layer(keep, keep.then(|| before.clone()));+ }+ if !keep {+ st.doc = before;+ }+ st.revision += 1;+ self.shared.frame(st);+ }++ /// The text layer being edited, if any.+ pub fn editing_text(&self) -> Option<u64> {+ self.shared.lock().text_edit.as_ref().map(|(l, _)| l.0)+ }++ /// A text layer's text, or none for another layer.+ pub fn layer_text(&self, id: u64) -> Option<TextInfo> {+ let st = self.shared.lock();+ st.doc.layer(LayerId(id))?.text.as_ref().map(TextInfo::from)+ }++ /// Makes text layer `id` an ordinary layer, its pixels kept, as one undo step.+ pub fn rasterize_layer(&self, id: u64) -> bool {+ self.change("rasterize", |d| d.rasterize(LayerId(id)).then_some(())).is_some()+ }+}diff --git a/apps/procraft-android/src/transform.rs b/apps/procraft-android/src/transform.rsnew file mode 100644index 0000000..c951442--- /dev/null+++ b/apps/procraft-android/src/transform.rs@@ -0,0 +1,504 @@+//! Transform: the current layer's content moved, scaled, rotated or distorted as a whole through+//! the box around it, shown live and kept as one undo step.++use procraft_engine::document::{Document, Layer, LayerId, LayerKind};+use procraft_engine::geom::{Affine, Homography, Vec2};+use procraft_engine::transform::{Guides, Handle, Transform, TransformMode, convex_hull};+use procraft_engine::warp;+use procraft_gpu::Resample;++use crate::{CanvasSession, State};++/// How transformed pixels are resampled.+#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]+pub enum Interpolation {+ Nearest,+ Bilinear,+ Bicubic,+}++impl From<Interpolation> for Resample {+ fn from(i: Interpolation) -> Resample {+ match i {+ Interpolation::Nearest => Resample::Nearest,+ Interpolation::Bilinear => Resample::Bilinear,+ Interpolation::Bicubic => Resample::Bicubic,+ }+ }+}++/// How the box's handles change the content.+#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]+pub enum TransformKind {+ Freeform,+ Uniform,+ Distort,+ Warp,+}++impl From<TransformKind> for TransformMode {+ fn from(k: TransformKind) -> TransformMode {+ match k {+ TransformKind::Freeform => TransformMode::Freeform,+ TransformKind::Uniform => TransformMode::Uniform,+ TransformKind::Distort => TransformMode::Distort,+ TransformKind::Warp => TransformMode::Warp,+ }+ }+}++/// What a drag on the box holds.+#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]+pub enum TransformHandle {+ /// 0 top left, 1 top right, 2 bottom right, 3 bottom left.+ Corner {+ index: u8,+ },+ /// The middle of an edge: 0 top, 1 right, 2 bottom, 3 left.+ Edge {+ index: u8,+ },+ /// The node above the box.+ Rotate,+ /// The node below the box.+ TurnBox,+ Move,+ /// One of a warp's 16 control points, row by row.+ Mesh {+ index: u8,+ },+}++impl From<TransformHandle> for Handle {+ fn from(h: TransformHandle) -> Handle {+ match h {+ TransformHandle::Corner { index } => Handle::Corner(index),+ TransformHandle::Edge { index } => Handle::Edge(index),+ TransformHandle::Rotate => Handle::Rotate,+ TransformHandle::TurnBox => Handle::TurnBox,+ TransformHandle::Move => Handle::Move,+ TransformHandle::Mesh { index } => Handle::Mesh(index),+ }+ }+}++/// The transform toolbar's one-tap changes.+#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]+pub enum TransformAction {+ FlipHorizontal,+ FlipVertical,+ Rotate45,+ FitToCanvas,+ Reset,+ /// Takes back the last change made in this transform.+ Undo,+}++/// What pulls a moved or turned box: magnetics (15° steps), and snapping onto the canvas's+/// edges and centre within `distance` points while the drag is no faster than `velocity` points+/// a frame.+#[derive(Clone, Copy, Debug, PartialEq, uniffi::Record)]+pub struct GuideSettings {+ pub magnetics: bool,+ pub snapping: bool,+ pub distance: f32,+ pub velocity: f32,+}++impl Default for GuideSettings {+ fn default() -> GuideSettings {+ GuideSettings { magnetics: false, snapping: false, distance: 3.0, velocity: 10.0 }+ }+}++/// How far (points) a move goes before magnetics locks its direction.+const LOCK_AFTER_PT: f32 = 2.0;++/// The box to draw: its corners (top left, top right, bottom right, bottom left) as eight numbers+/// in canvas pixels, and whether there is a change to take back. With a warp, also its 16 control+/// points (32 numbers, row by row) and its lines at the thirds (eight lines of+/// [`GRID_SAMPLES`] + 1 points each: four across, then four down); empty otherwise.+#[derive(Clone, Debug, PartialEq, uniffi::Record)]+pub struct TransformBox {+ pub corners: Vec<f32>,+ pub can_undo: bool,+ pub mesh: Vec<f32>,+ pub grid: Vec<f32>,+ /// The box's width and height (canvas pixels) and its turn from upright (degrees,+ /// clockwise), as numeric entry shows them.+ pub width: f32,+ pub height: f32,+ pub angle: f32,+}++/// How finely a warp's lines are sampled for drawing, and its triangles for rendering.+const GRID_SAMPLES: usize = 24;+const MESH_STEPS: usize = 48;++/// The smallest rectangle (x, y, width, height) holding every pixel with any alpha in+/// premultiplied RGBA8 `pixels` (`width` wide), and the convex hull of those pixels' corners;+/// none when all are clear.+pub(crate) fn content_shape(pixels: &[u8], width: u32) -> Option<([f32; 4], Vec<Vec2>)> {+ let row_len = width as usize * 4;+ if row_len == 0 {+ return None;+ }+ let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0, 0);+ // each row's outermost pixels are all the hull can need+ let mut ends: Vec<Vec2> = Vec::new();+ for (y, row) in pixels.chunks_exact(row_len).enumerate() {+ let (px, _) = row.as_chunks::<4>();+ let Some(first) = px.iter().position(|&[.., a]| a != 0) else { continue };+ let last = px.iter().rposition(|&[.., a]| a != 0).unwrap_or(first) + 1;+ x0 = x0.min(first);+ x1 = x1.max(last);+ y0 = y0.min(y);+ y1 = y + 1;+ let (yt, yb) = (y as f32, (y + 1) as f32);+ ends.extend([(first, yt), (first, yb), (last, yt), (last, yb)].map(|(x, y)| Vec2::new(x as f32, y)));+ }+ (x0 < x1).then(|| ([x0 as f32, y0 as f32, (x1 - x0) as f32, (y1 - y0) as f32], convex_hull(&ends)))+}++/// The box around the pixels that aren't clear (`x`, `y`, `width`, `height`), if any.+fn content_bounds(pixels: &[u8], width: u32) -> Option<[f32; 4]> {+ let row_len = width as usize * 4;+ if row_len == 0 {+ return None;+ }+ let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0, 0);+ for (y, row) in pixels.chunks_exact(row_len).enumerate() {+ let (px, _) = row.as_chunks::<4>();+ let Some(first) = px.iter().position(|&[.., a]| a != 0) else { continue };+ let last = px.iter().rposition(|&[.., a]| a != 0).unwrap_or(first) + 1;+ x0 = x0.min(first);+ x1 = x1.max(last);+ y0 = y0.min(y);+ y1 = y + 1;+ }+ (x0 < x1).then(|| [x0 as f32, y0 as f32, (x1 - x0) as f32, (y1 - y0) as f32])+}++/// Whether `l` shows: it and every group it is in visible.+fn shown(doc: &Document, l: &Layer) -> bool {+ l.visible && l.parent.and_then(|p| doc.layer(p)).is_none_or(|p| shown(doc, p))+}++/// How many other layers a moved box snaps onto at most (each is read back once, at the start).+const MAX_SNAP_LAYERS: usize = 16;++impl State {+ /// Ends an open transform: `commit` keeps it as one undo step, otherwise the layer is put back.+ pub(crate) fn end_transform(&mut self, commit: bool) {+ if self.transform.take().is_some()+ && let Some(canvas) = self.canvas.as_mut()+ {+ if commit {+ canvas.name_next_step(match self.transform_mode {+ procraft_engine::transform::TransformMode::Freeform => "non-uniform transform",+ procraft_engine::transform::TransformMode::Uniform => "uniform transform",+ procraft_engine::transform::TransformMode::Distort => "distort transform",+ procraft_engine::transform::TransformMode::Warp => "warp transform",+ });+ }+ canvas.end_transform(commit);+ }+ }++ /// Redraws the layer with the content where the transform has it now.+ fn show_transform(&mut self) {+ let (Some(t), Some(canvas)) = (self.transform.as_ref(), self.canvas.as_mut()) else { return };+ if let Some(mesh) = t.warp() {+ canvas.set_transform_mesh(&warp::triangles(&mesh, t.source(), MESH_STEPS), self.interpolation.into());+ } else if let Some(to_source) = Homography::quad_to_quad(t.content(), t.source()) {+ // each layer pixel looks up where it came from+ canvas.set_transform(to_source.to_f32(), self.interpolation.into());+ }+ }++ fn transform_box(&self) -> Option<TransformBox> {+ let t = self.transform.as_ref()?;+ let flat = |points: &mut dyn Iterator<Item = &Vec2>| points.flat_map(|p| [p.x, p.y]).collect::<Vec<f32>>();+ let mesh = t.warp();+ Some(TransformBox {+ corners: flat(&mut t.frame().iter()),+ can_undo: t.can_undo(),+ mesh: mesh.map(|m| flat(&mut m.iter())).unwrap_or_default(),+ grid: mesh.map(|m| flat(&mut warp::grid_lines(&m, GRID_SAMPLES).iter().flatten())).unwrap_or_default(),+ width: t.size().0,+ height: t.size().1,+ angle: t.angle().to_degrees(),+ })+ }++ /// What pulls the drag now that it reached window point `to`.+ fn guides(&mut self, to: Vec2) -> Guides {+ let now = std::time::Instant::now();+ let zoom = self.view.map_or(1.0, |v| v.zoom()).max(1e-6);+ let points = |px: f32| px / self.display_scale.max(1e-6);+ // the speed in points per 60 Hz frame since the last step+ let speed = self.last_drag.map_or(0.0, |(at, when)| {+ let ms = now.duration_since(when).as_secs_f32() * 1000.0;+ points((to.x - at.x).abs() + (to.y - at.y).abs()) * 16.7 / ms.max(1.0)+ });+ self.last_drag = Some((to, now));+ let g = self.transform_guides;+ Guides {+ magnetics: g.magnetics,+ lock_after: LOCK_AFTER_PT * self.display_scale / zoom,+ snap: (g.snapping && speed <= g.velocity).then(|| g.distance * self.display_scale / zoom),+ canvas: Vec2::new(self.doc.width() as f32, self.doc.height() as f32),+ }+ }++ /// Window pixels to canvas pixels.+ fn window_to_canvas(&self, x: f32, y: f32) -> Option<Vec2> {+ self.view?.screen_to_canvas(Vec2::new(x, y)).filter(|p| p.is_finite())+ }+}++#[uniffi::export]+impl CanvasSession {+ /// Starts transforming the current layer and returns the box around what it holds; none when+ /// there is nothing to transform (the layer is empty, locked or hidden). A transform already+ /// open is kept first.+ ///+ /// Other changes to the artwork keep an open transform first; strokes are ignored while one is+ /// open.+ pub fn transform_begin(&self) -> Option<TransformBox> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.finish_stroke();+ st.settle();+ let current = st.doc.current();+ let movable = |l: &Layer| !l.locked && l.visible && l.text.is_none();+ // with layers picked, every paint layer chosen (those in a chosen group too) moves+ let chosen = st.doc.chosen();+ let targets: Vec<LayerId> = if chosen.len() > 1 {+ st.doc+ .layers()+ .iter()+ .filter(|l| l.kind == LayerKind::Paint && movable(l))+ .filter(|l| chosen.iter().any(|c| *c == l.id || st.doc.is_inside(l.id, *c)))+ .map(|l| l.id)+ .collect()+ } else {+ st.doc.layer(current).filter(|l| movable(l)).map(|_| current).into_iter().collect()+ };+ if targets.is_empty() {+ return None;+ }+ st.flush();+ let width = st.doc.width();+ let (Some(canvas), Some(gpu)) = (st.canvas.as_mut(), st.gpu.as_ref()) else { return None };+ // what all of them hold together+ let mut pixels: Vec<u8> = Vec::new();+ for id in &targets {+ let layer = canvas.read_layer(gpu, *id).ok()?;+ if pixels.is_empty() {+ pixels = layer;+ } else {+ for (p, q) in pixels.as_chunks_mut::<4>().0.iter_mut().zip(layer.as_chunks::<4>().0) {+ p[3] = p[3].max(q[3]);+ }+ }+ }+ // with a selection, only what it takes moves+ if let Some(mask) = st.selection.as_ref() {+ for (px, &m) in pixels.as_chunks_mut::<4>().0.iter_mut().zip(&mask.data) {+ px[3] = ((u16::from(px[3]) * u16::from(m) + 127) / 255) as u8;+ }+ }+ let ([x, y, w, h], hull) = content_shape(&pixels, width)?;+ // the other layers shown, nearest the top first, are snapped onto by their bounds+ let others: Vec<_> = st+ .doc+ .layers()+ .iter()+ .rev()+ .filter(|l| !targets.contains(&l.id) && l.kind == LayerKind::Paint && shown(&st.doc, l))+ .take(MAX_SNAP_LAYERS)+ .map(|l| l.id)+ .collect();+ let bounds: Vec<[f32; 4]> =+ others.into_iter().filter_map(|id| content_bounds(&canvas.read_layer(gpu, id).ok()?, width)).collect();+ canvas.begin_transform_layers(&targets);+ let mut t = Transform::new(x, y, w, h, hull);+ t.set_snap_targets(&bounds);+ st.transform = Some(t);+ self.shared.frame(st);+ st.transform_box()+ }++ /// A drag of `handle` starts at window point (`x`, `y`).+ pub fn transform_grab(&self, handle: TransformHandle, x: f32, y: f32) {+ let mut st = self.shared.lock();+ let Some(at) = st.window_to_canvas(x, y) else { return };+ st.last_drag = None;+ if let Some(t) = st.transform.as_mut() {+ t.grab(handle.into(), at);+ }+ }++ /// The drag reached window point (`x`, `y`): the content follows. Returns the box.+ pub fn transform_drag(&self, x: f32, y: f32) -> Option<TransformBox> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let to = st.window_to_canvas(x, y)?;+ let mode = st.transform_mode;+ let guides = st.guides(Vec2::new(x, y));+ if st.transform.as_mut()?.drag(mode, to, &guides) {+ st.show_transform();+ self.shared.frame(st);+ }+ st.transform_box()+ }++ /// The drag ends: its change becomes a step the transform's undo takes back.+ pub fn transform_release(&self) -> Option<TransformBox> {+ let mut st = self.shared.lock();+ st.transform.as_mut()?.release();+ st.transform_box()+ }++ /// The drag is abandoned (a second finger came down): the content goes back.+ pub fn transform_cancel_drag(&self) -> Option<TransformBox> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.transform.as_mut()?.cancel_drag();+ st.show_transform();+ self.shared.frame(st);+ st.transform_box()+ }++ /// One of the toolbar's changes. Returns the box.+ pub fn transform_apply(&self, action: TransformAction) -> Option<TransformBox> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let (width, height) = (st.doc.width() as f32, st.doc.height() as f32);+ let t = st.transform.as_mut()?;+ match action {+ TransformAction::FlipHorizontal => t.flip_horizontal(),+ TransformAction::FlipVertical => t.flip_vertical(),+ TransformAction::Rotate45 => t.rotate(std::f32::consts::FRAC_PI_4),+ TransformAction::FitToCanvas => t.fit(width, height),+ TransformAction::Reset => t.reset(),+ TransformAction::Undo => {+ t.undo();+ }+ }+ st.show_transform();+ self.shared.frame(st);+ st.transform_box()+ }++ /// A tap on the canvas away from the box's nodes, at window point (`x`, `y`): the content+ /// moves one canvas pixel towards it. Returns the box.+ pub fn transform_nudge(&self, x: f32, y: f32) -> Option<TransformBox> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let at = st.window_to_canvas(x, y)?;+ st.transform.as_mut()?.nudge(at);+ st.show_transform();+ self.shared.frame(st);+ st.transform_box()+ }++ /// Makes the box `width` × `height` canvas pixels (numeric entry; negative mirrors). Returns+ /// the box.+ pub fn transform_set_size(&self, width: f32, height: f32) -> Option<TransformBox> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.transform.as_mut()?.set_size(width, height);+ st.show_transform();+ self.shared.frame(st);+ st.transform_box()+ }++ /// Turns the box to `degrees` from upright, clockwise (numeric entry). Returns the box.+ pub fn transform_set_angle(&self, degrees: f32) -> Option<TransformBox> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.transform.as_mut()?.set_angle(degrees.to_radians());+ st.show_transform();+ self.shared.frame(st);+ st.transform_box()+ }++ /// Magnetics and snapping from now on.+ pub fn transform_set_guides(&self, guides: GuideSettings) {+ self.shared.lock().transform_guides = guides;+ }++ /// How the handles act from now on; a warp lays its mesh over the content. Returns the box.+ pub fn transform_set_kind(&self, kind: TransformKind) -> Option<TransformBox> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.transform_mode = kind.into();+ if kind == TransformKind::Warp+ && let Some(t) = st.transform.as_mut()+ {+ t.start_warp();+ st.show_transform();+ self.shared.frame(st);+ }+ st.transform_box()+ }++ /// How the transformed pixels are resampled; redrawn at once.+ pub fn transform_set_interpolation(&self, interpolation: Interpolation) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ st.interpolation = interpolation;+ if st.transform.is_some() {+ st.show_transform();+ self.shared.frame(st);+ }+ }++ /// Ends the transform: `commit` keeps it as one undo step, otherwise the layer is put back.+ pub fn transform_end(&self, commit: bool) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ if let Some(t) = st.transform.as_ref() {+ // a selection moves with what it took+ let moved = match (commit, st.selection.as_ref()) {+ (true, Some(mask)) => match t.warp() {+ Some(mesh) => Some(mask.warped(&warp::triangles(&mesh, t.source(), MESH_STEPS))),+ None => Homography::quad_to_quad(t.content(), t.source()).map(|h| mask.moved(|p| h.apply(p))),+ },+ _ => None,+ };+ st.end_transform(commit);+ st.flush();+ if let Some(moved) = moved {+ let before = st.selection.replace(moved);+ st.record_selection(before, "move");+ }+ st.revision += 1;+ self.shared.frame(st);+ }+ }++ /// The view as six numbers `[a, b, c, d, e, f]`: canvas pixel (x, y) is shown at window pixel+ /// (a·x + c·y + e, b·x + d·y + f). The identity before the canvas is shown.+ pub fn view_matrix(&self) -> Vec<f32> {+ let st = self.shared.lock();+ let m = st.view.map_or(Affine::IDENTITY, |v| v.to_screen());+ vec![m.a, m.b, m.c, m.d, m.e, m.f]+ }++ /// The view the canvas opens with in a window of `width` × `height` pixels (as it was left,+ /// else fitted), as [`CanvasSession::view_matrix`] gives it; once shown, the view it has.+ pub fn opening_view_matrix(&self, width: u32, height: u32) -> Vec<f32> {+ let st = self.shared.lock();+ let window = (width.max(1), height.max(1));+ let view = st.view.unwrap_or_else(|| {+ st.saved_view.and_then(|v| v.view(window)).unwrap_or_else(|| {+ procraft_engine::view::View::fit_inside((st.doc.width(), st.doc.height()), window, st.fit_insets)+ })+ });+ let m = view.to_screen();+ vec![m.a, m.b, m.c, m.d, m.e, m.f]+ }+}diff --git a/apps/procraft-android/src/window.rs b/apps/procraft-android/src/window.rsnew file mode 100644index 0000000..3741000--- /dev/null+++ b/apps/procraft-android/src/window.rs@@ -0,0 +1,67 @@+//! The window handed over from Kotlin, and the wgpu surface on it: the crate's only unsafe code.+#![allow(unsafe_code)]++use std::ffi::c_void;+use std::sync::Mutex;+use std::sync::atomic::{AtomicU64, Ordering};++use jni_sys::{JNIEnv, jclass, jlong, jobject};+use ndk::native_window::NativeWindow;+use procraft_gpu::wgpu;+use raw_window_handle::{AndroidDisplayHandle, AndroidNdkWindowHandle, RawDisplayHandle, RawWindowHandle};++/// Windows acquired from Kotlin and not yet attached, by id.+static WINDOWS: Mutex<Vec<(u64, NativeWindow)>> = Mutex::new(Vec::new());+static NEXT_ID: AtomicU64 = AtomicU64::new(1);++/// Takes the window registered as `id`.+pub(crate) fn take(id: u64) -> Option<NativeWindow> {+ let mut windows = WINDOWS.lock().unwrap_or_else(|e| e.into_inner());+ let at = windows.iter().position(|(i, _)| *i == id)?;+ Some(windows.swap_remove(at).1)+}++/// `NativeWindows.acquire(surface: Surface): Long`: registers the surface's native window and+/// returns its id (0 if there is none).+#[unsafe(no_mangle)]+pub extern "system" fn Java_io_github_artcraftandroid_procraft_canvas_NativeWindows_acquire(+ env: *mut JNIEnv,+ _class: jclass,+ surface: jobject,+) -> jlong {+ if env.is_null() || surface.is_null() {+ return 0;+ }+ // SAFETY: the JVM calls this with its own valid `env`, and the Kotlin declaration only takes an+ // `android.view.Surface`.+ let Some(window) = (unsafe { NativeWindow::from_surface(env, surface) }) else { return 0 };+ let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);+ WINDOWS.lock().unwrap_or_else(|e| e.into_inner()).push((id, window));+ jlong::try_from(id).unwrap_or(0)+}++/// `NativeWindows.release(id: Long)`: lets go of a window that was never attached.+#[unsafe(no_mangle)]+pub extern "system" fn Java_io_github_artcraftandroid_procraft_canvas_NativeWindows_release(+ _env: *mut JNIEnv,+ _class: jclass,+ id: jlong,+) {+ if let Ok(id) = u64::try_from(id) {+ drop(take(id));+ }+}++/// A wgpu surface on `window`. The caller keeps `window` alive until the surface is dropped.+pub(crate) fn create_surface(+ instance: &wgpu::Instance,+ window: &NativeWindow,+) -> Result<wgpu::Surface<'static>, String> {+ let target = wgpu::SurfaceTargetUnsafe::RawHandle {+ raw_display_handle: Some(RawDisplayHandle::Android(AndroidDisplayHandle::new())),+ raw_window_handle: RawWindowHandle::AndroidNdk(AndroidNdkWindowHandle::new(window.ptr().cast::<c_void>())),+ };+ // SAFETY: the handle is a live ANativeWindow, and the render thread, which owns both, drops+ // the surface before the window.+ unsafe { instance.create_surface_unsafe(target) }.map_err(|e| e.to_string())+}diff --git a/apps/procraft-android/uniffi.toml b/apps/procraft-android/uniffi.tomlnew file mode 100644index 0000000..69933b5--- /dev/null+++ b/apps/procraft-android/uniffi.toml@@ -0,0 +1,5 @@+# UniFFI bindings of the `procraft_android` library.++[bindings.kotlin]+package_name = "io.github.artcraftandroid.procraft.core"+cdylib_name = "procraft_android"diff --git a/clippy.toml b/clippy.tomlnew file mode 100644index 0000000..4b6c79f--- /dev/null+++ b/clippy.toml@@ -0,0 +1,4 @@+allow-unwrap-in-tests = true+allow-expect-in-tests = true+allow-panic-in-tests = true+allow-indexing-slicing-in-tests = truediff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.tomlnew file mode 100644index 0000000..a7a951a--- /dev/null+++ b/crates/engine/Cargo.toml@@ -0,0 +1,17 @@+[package]+name = "procraft-engine"+version.workspace = true+edition.workspace = true+rust-version.workspace = true+publish.workspace = true+description = "ProCraft's painting engine: document model, brushes, stroke geometry and the canvas view (no GPU, no platform code)"++[lints]+workspace = true++[dependencies]+serde = { workspace = true }+miniz_oxide = { workspace = true }++[dev-dependencies]+serde_json = { workspace = true }diff --git a/crates/engine/src/animation.rs b/crates/engine/src/animation.rsnew file mode 100644index 0000000..4e024cf--- /dev/null+++ b/crates/engine/src/animation.rs@@ -0,0 +1,187 @@+//! Animation Assist: the canvas's top-level layers and groups as the frames of an animation, how+//! it plays, and how the frames around the current one show while drawing (onion skins).++use crate::document::{Document, LayerId};++/// How playing goes on after the last frame.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+pub enum Playback {+ /// From the first frame again.+ #[default]+ Loop,+ /// Back to the first and forth again.+ PingPong,+ /// Once, stopping on the last.+ OneShot,+}++/// The most onion skin frames shown on each side ("Max").+pub const MAX_ONION_FRAMES: u32 = 12;++/// Animation Assist's settings for a canvas.+#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]+#[serde(default)]+pub struct Animation {+ /// Frames a second, 1 to 60.+ pub fps: u32,+ /// Frames shown faintly on each side of the current one, 0 to [`MAX_ONION_FRAMES`].+ pub onion_frames: u32,+ /// The nearest onion skin frames' opacity, 0 to 1 (further ones fade).+ pub onion_opacity: f32,+ pub playback: Playback,+ /// The current frame shows blended with the onion skins instead of over them.+ pub blend_primary: bool,+ /// The colours onion skin frames take: before the current frame and after it (sRGB 0..1).+ pub before: [f32; 3],+ pub after: [f32; 3],+ /// The first frame always shows, behind every other.+ pub background: bool,+ /// The last frame always shows, in front of every other.+ pub foreground: bool,+ /// Frames held for longer: (the frame's layer, how many more frames it shows).+ pub holds: Vec<(LayerId, u32)>,+ /// Page Assist: the frames are pages, one shown at a time (no onion skins, no playing).+ pub pages: bool,+}++impl Default for Animation {+ fn default() -> Animation {+ Animation {+ fps: 15,+ onion_frames: MAX_ONION_FRAMES,+ onion_opacity: 0.6,+ playback: Playback::Loop,+ blend_primary: false,+ before: [0.9, 0.12, 0.12],+ after: [0.12, 0.7, 0.2],+ background: false,+ foreground: false,+ holds: Vec::new(),+ pages: false,+ }+ }+}++impl Animation {+ /// The settings with every value in range.+ pub fn repaired(mut self) -> Animation {+ self.fps = self.fps.clamp(1, 60);+ self.onion_frames = self.onion_frames.min(MAX_ONION_FRAMES);+ self.onion_opacity = if self.onion_opacity.is_finite() { self.onion_opacity.clamp(0.0, 1.0) } else { 0.6 };+ let unit = |c: [f32; 3]| c.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 });+ self.before = unit(self.before);+ self.after = unit(self.after);+ self.holds.retain(|(_, n)| *n > 0);+ self+ }++ /// How many more frames the frame of `id` is held.+ pub fn hold(&self, id: LayerId) -> u32 {+ self.holds.iter().find(|(l, _)| *l == id).map_or(0, |(_, n)| *n)+ }++ pub fn set_hold(&mut self, id: LayerId, frames: u32) {+ self.holds.retain(|(l, _)| *l != id);+ if frames > 0 {+ self.holds.push((id, frames.min(60)));+ }+ }+}++/// How a frame shows while drawing: normally, faintly in a colour, or not at all.+#[derive(Clone, Copy, Debug, PartialEq)]+pub enum FrameLook {+ Shown,+ /// An onion skin: tinted towards `color` and at `opacity`.+ Onion {+ color: [f32; 3],+ opacity: f32,+ },+ Hidden,+}++/// The frames: the visible top-level layers and groups, bottom first.+pub fn frames(doc: &Document) -> Vec<LayerId> {+ doc.members(None).into_iter().filter(|id| doc.layer(*id).is_some_and(|l| l.visible)).collect()+}++/// The frame holding the current layer.+pub fn current_frame(doc: &Document) -> Option<usize> {+ let mut id = doc.current();+ // up to the top level+ for _ in 0..64 {+ match doc.group_of(id) {+ Some(g) => id = g,+ None => break,+ }+ }+ frames(doc).iter().position(|f| *f == id)+}++/// How frame `index` of `count` shows with frame `current` the one drawn on (or, `playing`, the+/// one played: no onion skins then).+pub fn look(a: &Animation, index: usize, count: usize, current: usize, playing: bool) -> FrameLook {+ if a.pages {+ return if index == current { FrameLook::Shown } else { FrameLook::Hidden };+ }+ let last = count.saturating_sub(1);+ if index == current || (a.background && index == 0) || (a.foreground && index == last && count > 1) {+ return FrameLook::Shown;+ }+ if playing {+ return FrameLook::Hidden;+ }+ let distance = index.abs_diff(current);+ let n = a.onion_frames as usize;+ if distance == 0 || distance > n {+ return FrameLook::Hidden;+ }+ // the nearest at the set opacity, fading to nothing past the furthest+ let fade = 1.0 - (distance - 1) as f32 / n as f32;+ let color = if index < current { a.before } else { a.after };+ FrameLook::Onion { color, opacity: a.onion_opacity * fade }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn onion_skins_fade_and_take_their_side_colour() {+ let a = Animation { onion_frames: 2, ..Animation::default() };+ assert_eq!(look(&a, 3, 6, 3, false), FrameLook::Shown);+ let FrameLook::Onion { color, opacity } = look(&a, 2, 6, 3, false) else { panic!() };+ assert_eq!(color, a.before);+ assert!((opacity - 0.6).abs() < 1e-6);+ let FrameLook::Onion { color, opacity } = look(&a, 5, 6, 3, false) else { panic!() };+ assert_eq!(color, a.after);+ assert!((opacity - 0.3).abs() < 1e-6);+ assert_eq!(look(&a, 0, 6, 3, false), FrameLook::Hidden);+ // playing, only the played frame (and a background) shows+ assert_eq!(look(&a, 2, 6, 3, true), FrameLook::Hidden);+ let b = Animation { background: true, foreground: true, ..a };+ assert_eq!(look(&b, 0, 6, 3, true), FrameLook::Shown);+ assert_eq!(look(&b, 5, 6, 3, true), FrameLook::Shown);+ // pages: only the current one+ let p = Animation { pages: true, ..b };+ assert_eq!(look(&p, 3, 6, 3, false), FrameLook::Shown);+ assert_eq!(look(&p, 0, 6, 3, false), FrameLook::Hidden);+ assert_eq!(look(&p, 2, 6, 3, false), FrameLook::Hidden);+ }++ #[test]+ fn frames_are_the_top_level_units() {+ let mut d = Document::new(10, 10);+ let a = d.current();+ let b = LayerId(d.add_layer().0);+ assert_eq!(frames(&d), vec![a, b]);+ assert_eq!(current_frame(&d), Some(1));+ d.set_current(a);+ assert_eq!(current_frame(&d), Some(0));+ let mut s = Animation::default();+ s.set_hold(b, 3);+ assert_eq!(s.hold(b), 3);+ s.set_hold(b, 0);+ assert_eq!(s.hold(b), 0);+ }+}diff --git a/crates/engine/src/applz4.rs b/crates/engine/src/applz4.rsnew file mode 100644index 0000000..f297ef2--- /dev/null+++ b/crates/engine/src/applz4.rs@@ -0,0 +1,229 @@+//! LZ4 in a block framing: blocks of up to 64 KiB, each `bv41`+//! (compressed: raw size, compressed size, LZ4 data that may refer back into earlier blocks) or+//! `bv4-` (stored: raw size, bytes), ended by `bv4$`.++/// Raw bytes per block written.+const BLOCK: usize = 64 * 1024;++/// Decodes a framed stream; `None` if it is damaged or would come out longer than `limit`.+pub fn decode(data: &[u8], limit: usize) -> Option<Vec<u8>> {+ let mut out = Vec::new();+ let mut at = 0;+ loop {+ match data.get(at..at + 4)? {+ b"bv4$" => return Some(out),+ b"bv41" => {+ let raw = le(data, at + 4)?;+ let comp = le(data, at + 8)?;+ if out.len().checked_add(raw)? > limit {+ return None;+ }+ let block = data.get(at + 12..at.checked_add(12)?.checked_add(comp)?)?;+ let goal = out.len() + raw;+ block_into(block, &mut out, goal)?;+ at += 12 + comp;+ }+ b"bv4-" => {+ let raw = le(data, at + 4)?;+ if out.len().checked_add(raw)? > limit {+ return None;+ }+ out.extend_from_slice(data.get(at + 8..at.checked_add(8)?.checked_add(raw)?)?);+ at += 8 + raw;+ }+ _ => return None,+ }+ }+}++fn le(b: &[u8], at: usize) -> Option<usize> {+ usize::try_from(u32::from_le_bytes(b.get(at..at.checked_add(4)?)?.try_into().ok()?)).ok()+}++/// Decodes one LZ4 block onto `out` until it holds `goal` bytes; matches may reach back into what+/// `out` held before.+fn block_into(src: &[u8], out: &mut Vec<u8>, goal: usize) -> Option<()> {+ let mut i = 0;+ while i < src.len() {+ let token = *src.get(i)?;+ i += 1;+ let mut literals = usize::from(token >> 4);+ if literals == 15 {+ loop {+ let b = *src.get(i)?;+ i += 1;+ literals += usize::from(b);+ if b != 255 {+ break;+ }+ }+ }+ out.extend_from_slice(src.get(i..i.checked_add(literals)?)?);+ i += literals;+ if i >= src.len() || out.len() >= goal {+ break;+ }+ let offset = usize::from(u16::from_le_bytes(src.get(i..i + 2)?.try_into().ok()?));+ i += 2;+ let mut length = usize::from(token & 15);+ if length == 15 {+ loop {+ let b = *src.get(i)?;+ i += 1;+ length += usize::from(b);+ if b != 255 {+ break;+ }+ }+ }+ length += 4;+ let start = out.len().checked_sub(offset)?;+ if offset == 0 || out.len().checked_add(length)? > goal {+ return None;+ }+ // byte by byte: the match may overlap what it writes+ for k in 0..length {+ let b = *out.get(start + k)?;+ out.push(b);+ }+ }+ (out.len() == goal).then_some(())+}++/// Encodes `data` in the framing, each block compressed (or stored, when that is smaller).+pub fn encode(data: &[u8]) -> Vec<u8> {+ let mut out = Vec::with_capacity(data.len() / 4 + 16);+ for block in data.chunks(BLOCK) {+ let packed = compress_block(block);+ if packed.len() < block.len() {+ out.extend_from_slice(b"bv41");+ out.extend_from_slice(&(block.len() as u32).to_le_bytes());+ out.extend_from_slice(&(packed.len() as u32).to_le_bytes());+ out.extend_from_slice(&packed);+ } else {+ out.extend_from_slice(b"bv4-");+ out.extend_from_slice(&(block.len() as u32).to_le_bytes());+ out.extend_from_slice(block);+ }+ }+ out.extend_from_slice(b"bv4$");+ out+}++/// One LZ4 block, matches found greedily through a hash of 4-byte sequences.+fn compress_block(src: &[u8]) -> Vec<u8> {+ const HASH_BITS: u32 = 14;+ // the format's rules: the last 5 bytes are literals, and no match starts in the last 12+ const LAST_LITERALS: usize = 5;+ const MATCH_LIMIT: usize = 12;+ let mut out = Vec::with_capacity(src.len() / 2 + 16);+ let mut table = vec![0usize; 1 << HASH_BITS];+ let read4 = |at: usize| src.get(at..at + 4).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(u32::from_le_bytes);+ let hash = |v: u32| (v.wrapping_mul(2_654_435_761) >> (32 - HASH_BITS)) as usize;+ let mut anchor = 0;+ let mut i = 0;+ let end = src.len().saturating_sub(MATCH_LIMIT);+ while i < end {+ let Some(v) = read4(i) else { break };+ let h = hash(v);+ let candidate = table.get(h).copied().unwrap_or(0);+ if let Some(slot) = table.get_mut(h) {+ *slot = i;+ }+ if candidate < i && i - candidate <= 0xFFFF && read4(candidate) == Some(v) {+ // extend the match, stopping short of the block's literal tail+ let max = src.len() - LAST_LITERALS;+ let mut len = 4;+ while i + len < max && src.get(candidate + len) == src.get(i + len) {+ len += 1;+ }+ emit(&mut out, src.get(anchor..i).unwrap_or(&[]), Some(((i - candidate) as u16, len)));+ i += len;+ anchor = i;+ } else {+ i += 1;+ }+ }+ emit(&mut out, src.get(anchor..).unwrap_or(&[]), None);+ out+}++/// A sequence: `literals`, then a match (offset, length) if any.+fn emit(out: &mut Vec<u8>, literals: &[u8], m: Option<(u16, usize)>) {+ let lit = literals.len();+ let ml = m.map_or(0, |(_, l)| l - 4);+ let token = ((lit.min(15) as u8) << 4) | ml.min(15) as u8;+ out.push(token);+ if lit >= 15 {+ let mut rest = lit - 15;+ while rest >= 255 {+ out.push(255);+ rest -= 255;+ }+ out.push(rest as u8);+ }+ out.extend_from_slice(literals);+ if let Some((offset, _)) = m {+ out.extend_from_slice(&offset.to_le_bytes());+ if ml >= 15 {+ let mut rest = ml - 15;+ while rest >= 255 {+ out.push(255);+ rest -= 255;+ }+ out.push(rest as u8);+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn data_round_trips() {+ let empty: Vec<u8> = vec![0; 256 * 256 * 4];+ let mut stroke = empty.clone();+ for (i, b) in stroke.iter_mut().enumerate() {+ if (i / 4) % 997 < 30 {+ *b = (i % 251) as u8;+ }+ }+ let noise: Vec<u8> = (0..70_000u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 24) as u8).collect();+ for data in [&empty, &stroke, &noise, &vec![7u8; 3], &Vec::new()] {+ let packed = encode(data);+ assert_eq!(decode(&packed, data.len()).as_deref(), Some(data.as_slice()));+ }+ // an empty tile packs small+ assert!(encode(&empty).len() < 2_000, "{}", encode(&empty).len());+ }++ #[test]+ fn blocks_may_refer_back_into_earlier_ones() {+ // two blocks: 8 literals, then a block that is one match into the first+ let mut s = b"bv41".to_vec();+ s.extend_from_slice(&8u32.to_le_bytes());+ s.extend_from_slice(&9u32.to_le_bytes());+ s.push(0x80);+ s.extend_from_slice(b"ABCDEFGH");+ s.extend_from_slice(b"bv41");+ s.extend_from_slice(&8u32.to_le_bytes());+ s.extend_from_slice(&4u32.to_le_bytes());+ s.push(0x04);+ s.extend_from_slice(&8u16.to_le_bytes());+ s.push(0x00);+ s.extend_from_slice(b"bv4$");+ // the second block's sequence: no literals, a match 8 back, length 8 (4 + 4); then the+ // block ends with an empty literal run+ assert_eq!(decode(&s, 100).as_deref(), Some(&b"ABCDEFGHABCDEFGH"[..]));+ }++ #[test]+ fn damaged_streams_are_refused() {+ assert_eq!(decode(b"nope", 10), None);+ assert_eq!(decode(b"bv41\x10\x00\x00\x00\xff\x00\x00\x00", 100), None);+ let packed = encode(&[1u8; 1000]);+ assert_eq!(decode(&packed, 10), None, "over the limit");+ assert_eq!(decode(packed.get(..packed.len() - 4).unwrap(), 1000), None, "no end");+ }+}diff --git a/crates/engine/src/base64.rs b/crates/engine/src/base64.rsnew file mode 100644index 0000000..a716bcd--- /dev/null+++ b/crates/engine/src/base64.rs@@ -0,0 +1,50 @@+//! Bytes as base64 text (the standard alphabet, padded), for keeping binary data in text files.++const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";++/// `bytes` as base64.+pub fn encode(bytes: &[u8]) -> String {+ let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);+ for chunk in bytes.chunks(3) {+ let b = [0, 1, 2].map(|i| chunk.get(i).copied().unwrap_or(0));+ let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);+ for k in 0..4 {+ let c = if k <= chunk.len() { ALPHABET.get(((n >> (18 - 6 * k)) & 63) as usize).copied() } else { None };+ out.push(char::from(c.unwrap_or(b'=')));+ }+ }+ out+}++/// The bytes in base64 `text` (spaces at either end ignored); none if it isn't base64.+pub fn decode(text: &str) -> Option<Vec<u8>> {+ let mut out = Vec::with_capacity(text.len() / 4 * 3);+ for quad in text.trim().as_bytes().chunks(4) {+ let mut n = 0u32;+ let mut real = 0;+ for (k, &c) in quad.iter().enumerate() {+ if c == b'=' {+ break;+ }+ n |= (ALPHABET.iter().position(|&x| x == c)? as u32) << (18 - 6 * k);+ real += 1;+ }+ out.extend([(n >> 16) as u8, (n >> 8) as u8, n as u8].into_iter().take(real.max(1) - 1));+ }+ Some(out)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn bytes_go_both_ways() {+ for bytes in [&b""[..], b"f", b"fo", b"foo", b"foob", b"fooba", b"foobar", &[0, 255, 128, 7]] {+ assert_eq!(decode(&encode(bytes)).unwrap(), bytes);+ }+ assert_eq!(encode(b"foobar"), "Zm9vYmFy");+ assert_eq!(encode(b"fo"), "Zm8=");+ assert!(decode("no!").is_none());+ }+}diff --git a/crates/engine/src/brush.rs b/crates/engine/src/brush.rsnew file mode 100644index 0000000..973c0dc--- /dev/null+++ b/crates/engine/src/brush.rs@@ -0,0 +1,694 @@+//! Brush settings: what a stroke's stamps look like and how input drives them.+//!+//! Only the parameters the stroke builder uses so far are here; the full set (shape and grain+//! images, rendering modes, wet mix, colour dynamics, tilt and roll) is added as it is drawn.++use std::collections::BTreeMap;+use std::sync::Arc;++use crate::curve::Curve;+use crate::textures::TEXTURE_SIZE;++/// An image of the user's own for a brush's shape or grain: square greyscale, `TEXTURE_SIZE` on a+/// side, rows top to bottom, white = paint; known by a hash of its pixels.+#[derive(Clone, Debug)]+pub struct Source {+ pub id: u64,+ pub pixels: Arc<Vec<u8>>,+}++impl PartialEq for Source {+ fn eq(&self, other: &Source) -> bool {+ self.id == other.id+ }+}++impl Source {+ /// The image, or none if it isn't `TEXTURE_SIZE` square.+ pub fn new(pixels: Vec<u8>) -> Option<Source> {+ if pixels.len() != TEXTURE_SIZE * TEXTURE_SIZE {+ return None;+ }+ // FNV-1a+ let id =+ pixels.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3));+ Some(Source { id, pixels: Arc::new(pixels) })+ }++ /// The pixels as text (base64), to keep with a brush.+ pub fn to_text(&self) -> String {+ crate::base64::encode(&self.pixels)+ }++ /// An image kept as text by [`Source::to_text`]; none if it isn't one.+ pub fn from_text(text: &str) -> Option<Source> {+ Source::new(crate::base64::decode(text)?)+ }+}++/// Size and opacity at the ends of a stroke.+#[derive(Clone, Debug, PartialEq)]+pub struct Taper {+ /// Length of the start taper, 0..1 of [`TAPER_SPAN`] stamp diameters.+ pub start: f32,+ /// Length of the end taper, 0..1 of [`TAPER_SPAN`] stamp diameters.+ pub end: f32,+ /// How thin the tips get: 0 = no change, 1 = down to nothing.+ pub size: f32,+ /// How transparent the tips get: 0 = no change, 1 = fully transparent.+ pub opacity: f32,+}++/// A taper length of 1 spans this many stamp diameters.+pub const TAPER_SPAN: f32 = 24.0;++/// A classic taper of length 1 spans this many canvas pixels, whatever the brush's size (as+/// measured: the width grows evenly to full over it).+pub const CLASSIC_TAPER_SPAN: f32 = 520.0;+/// A classic end taper comes to its tip over at most the last this many milliseconds of the+/// stroke, however long it is set (as measured, at any speed: a quarter of the width 11 ms before+/// the pen lifts, half 24 ms, nine tenths 51 ms).+pub const CLASSIC_END_MS: f32 = 58.0;+/// The newer taper's ends on touch run over at most the first and the last this many milliseconds+/// of the stroke, whatever the brush's size or the stroke's length (as measured: a quarter of the+/// width 16 ms before the finger lifts, half 37 ms, nine tenths 73 ms).+pub const TIMED_START_MS: f32 = 6.0;+pub const TIMED_END_MS: f32 = 82.5;+/// A newer taper of length 1 on touch lasts this long, up to those (as measured: a length of+/// 0.0225 ends in a short tip, 0.0625 already in the whole, 0 in none).+pub const TIMED_TAPER_SPAN_MS: f32 = 1300.0;+/// How the width comes to an end taper's tip: the share of the end still to go, to this power.+const CLASSIC_END_EASE: f32 = 0.83;+const TIMED_END_EASE: f32 = 0.855;++/// How far a taper of `len` canvas pixels has grown `d` pixels in, eased by `power`.+fn grown(len: f32, d: f32, power: f32) -> f32 {+ if len <= 0.0 { 1.0 } else { (d / len).clamp(0.0, 1.0).powf(power) }+}++impl Taper {+ pub const NONE: Taper = Taper { start: 0.0, end: 0.0, size: 0.0, opacity: 0.0 };++ /// The multipliers (size, opacity) at `distance` px from the start of a stroke of `length` px+ /// drawn with a `diameter` px brush; `length` is `None` while the stroke is still being drawn.+ pub fn factors(&self, distance: f32, length: Option<f32>, diameter: f32) -> (f32, f32) {+ let span = TAPER_SPAN * diameter.max(0.5);+ let (mut start, mut end) = (self.start.max(0.0) * span, self.end.max(0.0) * span);+ if let Some(total) = length {+ // a stroke shorter than its tapers tapers in proportion; a tap not at all+ let sum = start + end;+ if sum > total.max(0.0) && sum > 0.0 {+ let k = total.max(0.0) / sum;+ start *= k;+ end *= k;+ }+ }+ let ramp = |len: f32, d: f32| -> f32 {+ if len <= 0.0 {+ return 1.0;+ }+ let u = (d / len).clamp(0.0, 1.0);+ 1.0 - (1.0 - u) * (1.0 - u)+ };+ let mut t = ramp(start, distance);+ if let Some(total) = length {+ t = t.min(ramp(end, (total - distance).max(0.0)));+ }+ (1.0 - self.size.clamp(0.0, 1.0) * (1.0 - t), 1.0 - self.opacity.clamp(0.0, 1.0) * (1.0 - t))+ }++ /// As [`Taper::factors`] for a classic taper, as measured: the start grows evenly over its+ /// length in canvas pixels whatever the brush's size; the end comes to its tip over its length+ /// or over the last [`CLASSIC_END_MS`] of the stroke, whichever is shorter (`pace`: how fast+ /// the stroke ended, canvas pixels a millisecond); a stroke shorter than its tapers just+ /// doesn't reach full.+ pub fn classic_factors(&self, distance: f32, length: Option<f32>, pace: f32) -> (f32, f32) {+ // a tap keeps its full size+ if length.is_some_and(|l| l <= 0.0) {+ return (1.0, 1.0);+ }+ let start = self.start.max(0.0) * CLASSIC_TAPER_SPAN;+ let end = (self.end.max(0.0) * CLASSIC_TAPER_SPAN).min(CLASSIC_END_MS * pace.max(0.0));+ let mut t = grown(start, distance, 1.0);+ if let Some(total) = length {+ t = t.min(grown(end, (total - distance).max(0.0), CLASSIC_END_EASE));+ }+ self.applied(t)+ }++ /// As [`Taper::factors`] for the newer taper on touch, as measured: each end lasts its length+ /// in time ([`TIMED_TAPER_SPAN_MS`] for 1) up to [`TIMED_START_MS`] and [`TIMED_END_MS`],+ /// over as much of the stroke as the finger covered in that time (`paces`: how fast the+ /// stroke started and ended, canvas pixels a millisecond).+ pub fn timed_factors(&self, distance: f32, length: Option<f32>, paces: (f32, f32)) -> (f32, f32) {+ if length.is_some_and(|l| l <= 0.0) {+ return (1.0, 1.0);+ }+ let lasts = |share: f32, most: f32| (share.max(0.0) * TIMED_TAPER_SPAN_MS).min(most);+ let start = lasts(self.start, TIMED_START_MS) * paces.0.max(0.0);+ let end = lasts(self.end, TIMED_END_MS) * paces.1.max(0.0);+ let mut t = grown(start, distance, 1.0);+ if let Some(total) = length {+ t = t.min(grown(end, (total - distance).max(0.0), TIMED_END_EASE));+ }+ self.applied(t)+ }++ /// The multipliers (size, opacity) where the taper has grown `t` of the way to full.+ fn applied(&self, t: f32) -> (f32, f32) {+ (1.0 - self.size.clamp(0.0, 1.0) * (1.0 - t), 1.0 - self.opacity.clamp(0.0, 1.0) * (1.0 - t))+ }+}++/// How a stroke's stamps build up within the stroke (the studio's rendering modes: Light Glaze+/// keeps the strongest; Uniformed Glaze, Intense Glaze and Intense Blending build up; Heavy Glaze+/// and Uniform Blending build up gradually).+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub enum Rendering {+ /// Each stamp adds to what is there ("over"), up to the stroke's opacity.+ #[default]+ BuildUp,+ /// Overlapping stamps don't build up: the stroke keeps the strongest stamp at each pixel.+ Strongest,+ /// Each stamp adds less the more is there (by what is left, squared).+ Gradual,+ /// Each stamp adds towards its transfer (what light pressure lets through), never past it.+ Capped,+}++/// What the pen's pressure drives, each taking it through a curve of its own and following it at+/// a speed of its own (see [`Brush::pressures`]).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum PressureUse {+ Size = 0,+ Opacity = 1,+ Bleed = 2,+ Roundness = 3,+}++/// The size slider's curve: the size it sets is its place to this power.+pub const SIZE_CURVE: f32 = 2.2;++/// A stamp's opacity is its flow, pressure, tilt and speed together, through the brush's opacity+/// range, to this power: light touches fall away fast.+pub const FLOW_POWER: f32 = 2.5;++/// Where a grain sits.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub enum GrainMode {+ /// Fixed to the canvas, like paper: applied to the whole stroke.+ #[default]+ Texturized,+ /// Travels with each stamp.+ Moving,+}++/// The stamp's shape and how it is placed.+#[derive(Clone, Debug, PartialEq)]+pub struct Shape {+ /// A shape image (see `textures::shape`), or none for the round tip drawn with `hardness`.+ pub image: Option<u32>,+ /// An image of the user's own, in place of `image`.+ pub source: Option<Source>,+ /// Fixed rotation, radians.+ pub rotation: f32,+ /// How far the stamp turns with the stroke's direction: 1 follows it, 0 holds still, −1+ /// turns against it.+ pub follow: f32,+ /// Turn with the direction the pen leans.+ pub follow_azimuth: bool,+ /// A random rotation per stamp.+ pub randomise: bool,+ /// 1 = as drawn; lower squashes the stamp across its rotation.+ pub roundness: f32,+ /// How far each stamp turns at random, up to this many half turns either way (the Scatter+ /// control, 0..2).+ pub scatter: f32,+ /// Random offset from the path, in stamp diameters (some brushes of our own throw their+ /// stamps about; files keep such randomness as jitter).+ pub throw: f32,+ /// Stamps placed at each step.+ pub count: u32,+ /// Random reduction of each stamp's size and opacity, 0..1.+ pub size_jitter: f32,+ pub opacity_jitter: f32,+}++impl Default for Shape {+ fn default() -> Shape {+ Shape {+ image: None,+ source: None,+ rotation: 0.0,+ follow: 0.0,+ follow_azimuth: false,+ randomise: false,+ roundness: 1.0,+ scatter: 0.0,+ throw: 0.0,+ count: 1,+ size_jitter: 0.0,+ opacity_jitter: 0.0,+ }+ }+}++/// The texture inside the stroke.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct Grain {+ /// A grain image (see `textures::grain`), or none.+ pub image: Option<u32>,+ /// An image of the user's own, in place of `image`.+ pub source: Option<Source>,+ pub mode: GrainMode,+ /// Size of one grain tile on the canvas, pixels.+ pub scale: f32,+ /// How strongly the grain shows, 0..1.+ pub depth: f32,+}++/// What leaning the pen does.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct Tilt {+ /// The tilt angle control's dial (radians, a quarter turn at most): each tilt control starts+ /// to act from its own angle, this one unless it has its own (see [`Tilt::reach`]).+ pub angle: f32,+ /// What leaning adds to the stamp's size, in the size's units ([`Brush::size_unit`]) at the+ /// most lean, before it is taken as far as the lean has gone.+ pub size: f32,+ /// Fading of the stamp as the pen leans, 0..1.+ pub opacity: f32,+}++/// A lean (radians from upright) about as flat as pens go.+pub const FLAT_TILT: f32 = 1.2;++impl Tilt {+ /// How far a pen leaning `lean` radians from upright has gone for a tilt control whose angle+ /// is `theta` (its dial's share of a quarter turn): nothing until it is down to 34° above the+ /// surface (at 0; at 1, from upright), rising as it goes down to 26°, the most it counts,+ /// where it reaches 0.5 (at 0) to 0.88 (at 1).+ pub fn reach(lean: f32, theta: f32) -> f32 {+ if !lean.is_finite() {+ return 0.0;+ }+ let altitude = (1.0 - lean / std::f32::consts::FRAC_PI_2).clamp(0.0, 1.0);+ let theta = if theta.is_finite() { theta.clamp(0.0, 1.0) } else { 0.0 };+ let span = TILT_SPAN_LOW + (TILT_SPAN_HIGH - TILT_SPAN_LOW) * theta;+ (1.0 - (altitude.max(TILT_LOWEST) - TILT_SPAN_LOW) / span).clamp(1.0 / 1024.0, 1.0)+ }+}++/// The ramp of [`Tilt::reach`], as shares of a quarter turn of altitude: the lowest it counts+/// (25.8°), and its span at a tilt angle of 0 and of 1.+const TILT_LOWEST: f32 = 0.28648;+const TILT_SPAN_LOW: f32 = 0.19099;+const TILT_SPAN_HIGH: f32 = 0.80901;++#[derive(Clone, Debug, PartialEq)]+pub struct Brush {+ pub name: String,+ /// Distance between stamps, as a fraction of the stamp diameter.+ pub spacing: f32,+ /// Smoothing of the stroke's path, 0..1.+ pub streamline: f32,+ /// Smoothing of pen pressure, 0..1.+ pub pressure_smoothing: f32,+ /// Edge of the round tip: 0 = soft all the way to the centre, 1 = hard.+ pub hardness: f32,+ /// Stamp diameter in canvas pixels at the size slider's minimum and maximum.+ pub min_size: f32,+ pub max_size: f32,+ /// Stroke opacity at the opacity slider's minimum and maximum.+ pub min_opacity: f32,+ pub max_opacity: f32,+ /// How much each stamp adds at full pressure, 0..1 (the studio's flow control to the power+ /// [`FLOW_POWER`]).+ pub flow: f32,+ /// How much pen pressure shrinks the stamp (0 = not at all, 1 = to nothing at no pressure).+ pub pressure_size: f32,+ /// How much pen pressure lowers the stamp's opacity.+ pub pressure_opacity: f32,+ pub pressure_curve: Curve,+ /// What the pressure (after [`Brush::pressure_curve`]) becomes for the size and for the+ /// opacity.+ pub size_curve: Curve,+ pub opacity_curve: Curve,+ /// Taper for pens and for fingers.+ pub pen_taper: Taper,+ pub touch_taper: Taper,+ pub shape: Shape,+ pub grain: Grain,+ pub tilt: Tilt,+ pub rendering: Rendering,+ /// Brush studio controls the engine does not draw yet, by key (see `studio`).+ pub extra: BTreeMap<String, f32>,+ /// Values saved on the side sliders while this brush is in use, shown there as notches.+ pub notches: Notches,+ /// Its preview as its file brought it (PNG), shown in place of a drawn one until the brush is+ /// changed.+ pub thumbnail: Option<std::sync::Arc<[u8]>>,+ /// Who made it, as its file says; none for ProCraft's own.+ pub author: Option<Author>,+ /// What resetting the brush puts back: set the first time it is opened in the studio.+ pub reset_point: Option<ResetPoint>,+ /// The stock images its file named for its shape and grain, which our own stand in for.+ pub stock: StockImages,+}++/// The stock images a brush's file names for its shape and grain (drawn with ours standing in),+/// kept so that they are named again when the brush is written out.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct StockImages {+ pub shape: Option<StockImage>,+ pub grain: Option<StockImage>,+}++/// A stock image as a brush file names it, and whether the file has it inverted.+#[derive(Clone, Debug, PartialEq)]+pub struct StockImage {+ pub name: String,+ pub inverted: bool,+}++/// A brush's maker as its file names them, with their picture and signature (PNG) if it has them.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct Author {+ pub name: String,+ pub picture: Option<std::sync::Arc<[u8]>>,+ pub signature: Option<std::sync::Arc<[u8]>>,+}++/// A brush set aside to go back to (without a reset point of its own), and when: seconds since+/// 1970.+#[derive(Clone, Debug, PartialEq)]+pub struct ResetPoint {+ pub brush: Box<Brush>,+ pub made: i64,+}++impl ResetPoint {+ /// `brush` as it is, set aside at `made`.+ pub fn of(brush: &Brush, made: i64) -> ResetPoint {+ ResetPoint { brush: Box::new(Brush { reset_point: None, ..brush.clone() }), made }+ }+}++/// A brush's saved side-slider values (its notches): sizes and opacities, slider positions 0..1,+/// kept apart for each tool that uses the brush (painting, smudging, erasing; see [`Notches::tool`]).+#[derive(Clone, Debug, Default, PartialEq)]+pub struct Notches {+ pub sizes: [Vec<f32>; 3],+ pub opacities: [Vec<f32>; 3],+}++impl Notches {+ /// The most notches a slider takes.+ pub const MOST: usize = 4;+ /// How near a value (of the slider's length) is on a notch, and is pulled onto it.+ pub const NEAR: f32 = 0.04;++ /// Where a tool's notches are kept: 0 painting, 1 smudging, 2 erasing.+ pub fn tool(painting: bool, smudging: bool) -> usize {+ if painting {+ 0+ } else if smudging {+ 1+ } else {+ 2+ }+ }++ /// A tool's (0..3) size or opacity notches.+ pub fn list(&self, tool: usize, size: bool) -> &[f32] {+ let lists = if size { &self.sizes } else { &self.opacities };+ lists.get(tool).map_or(&[], Vec::as_slice)+ }++ fn list_mut(&mut self, tool: usize, size: bool) -> Option<&mut Vec<f32>> {+ if size { self.sizes.get_mut(tool) } else { self.opacities.get_mut(tool) }+ }++ /// The notch `value` is on (the nearest, within [`Notches::NEAR`]), if any.+ pub fn at(&self, tool: usize, size: bool, value: f32) -> Option<f32> {+ self.list(tool, size)+ .iter()+ .copied()+ .filter(|n| (n - value).abs() < Self::NEAR)+ .min_by(|a, b| (a - value).abs().total_cmp(&(b - value).abs()))+ }++ /// Saves `value` as a notch, unless the slider is full, one is there already, or it isn't a+ /// slider position; whether it did.+ pub fn add(&mut self, tool: usize, size: bool, value: f32) -> bool {+ if !(0.0..=1.0).contains(&value) || self.at(tool, size, value).is_some() {+ return false;+ }+ match self.list_mut(tool, size) {+ Some(list) if list.len() < Self::MOST => {+ list.push(value);+ true+ }+ _ => false,+ }+ }++ /// Takes away the notch `value` is on; whether there was one.+ pub fn remove(&mut self, tool: usize, size: bool, value: f32) -> bool {+ let Some(n) = self.at(tool, size, value) else { return false };+ let Some(list) = self.list_mut(tool, size) else { return false };+ list.retain(|&v| v != n);+ true+ }+}++impl Brush {+ /// A plain round inking pen: ProCraft's own starting brush until the library exists.+ pub fn round_pen() -> Brush {+ Brush {+ name: "Round Pen".to_owned(),+ spacing: 0.08,+ streamline: 0.35,+ pressure_smoothing: 0.2,+ hardness: 0.92,+ min_size: 1.0,+ max_size: 120.0,+ min_opacity: 0.0,+ max_opacity: 1.0,+ flow: 1.0,+ pressure_size: 0.85,+ pressure_opacity: 0.0,+ pressure_curve: Curve::linear(),+ size_curve: Curve::linear(),+ opacity_curve: Curve::linear(),+ pen_taper: Taper { start: 0.15, end: 0.2, size: 0.8, opacity: 0.0 },+ touch_taper: Taper { start: 0.1, end: 0.1, size: 0.6, opacity: 0.0 },+ shape: Shape::default(),+ grain: Grain::default(),+ tilt: Tilt::default(),+ rendering: Rendering::BuildUp,+ extra: BTreeMap::new(),+ notches: Notches::default(),+ thumbnail: None,+ author: None,+ reset_point: None,+ stock: StockImages::default(),+ }+ }++ /// Canvas pixels a stamp is across for each unit of size as brush files keep it: the+ /// stamp's square, of which a round tip of ours covers [`crate::brushfile::ROUND_TIP_SHARE`].+ pub fn size_unit(&self) -> f32 {+ let round_tip = self.shape.image.is_none() && self.shape.source.is_none();+ crate::brushfile::PIXELS_PER_SIZE * if round_tip { crate::brushfile::ROUND_TIP_SHARE } else { 1.0 }+ }++ /// Stamp diameter (canvas px) for a size slider at 0..1: the slider to the power+ /// [`SIZE_CURVE`] (so small sizes get most of it), from the least size to the most.+ pub fn diameter(&self, slider: f32) -> f32 {+ let s = if slider.is_finite() { slider.clamp(0.0, 1.0) } else { 0.5 };+ let most = self.biggest();+ let least = self.min_size.min(most);+ (least + (most - least) * s.powf(SIZE_CURVE)).max(0.5)+ }++ /// The most size drawn (canvas pixels): the brush's own, held to what its spacing allows.+ pub fn biggest(&self) -> f32 {+ self.max_size.min(self.most_size() * self.size_unit())+ }++ /// Stroke opacity for an opacity slider at 0..1.+ pub fn opacity(&self, slider: f32) -> f32 {+ let s = if slider.is_finite() { slider.clamp(0.0, 1.0) } else { 1.0 };+ (self.min_opacity + (self.max_opacity - self.min_opacity) * s).clamp(0.0, 1.0)+ }++ /// The (size, opacity) multipliers for a pressure of 0..1.+ pub fn pressure_factors(&self, pressure: f32) -> (f32, f32) {+ let [size, opacity, ..] = self.pressures(pressure);+ self.factors(size, opacity)+ }++ /// The pressure as each of its uses takes it, through the pressure curve and their own:+ /// [`PressureUse`] order.+ pub fn pressures(&self, pressure: f32) -> [f32; 4] {+ let p = self.pressure_curve.eval(pressure);+ [self.size_curve.eval(p), self.opacity_curve.eval(p), p, p]+ }++ /// The (size, opacity) multipliers for the size's and the opacity's own pressures: an amount+ /// above 0 takes away as the pressure lightens, one below 0 as it presses.+ pub fn factors(&self, size: f32, opacity: f32) -> (f32, f32) {+ let factor = |amount: f32, p: f32| {+ let amount = amount.clamp(-1.0, 1.0);+ if amount >= 0.0 { 1.0 - amount * (1.0 - p) } else { 1.0 + amount * p }+ };+ (factor(self.pressure_size, size), factor(self.pressure_opacity, opacity))+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn taper_ramps_in_and_out() {+ let t = Taper { start: 0.5, end: 0.5, size: 1.0, opacity: 0.5 };+ let d = 10.0;+ let span = 0.5 * TAPER_SPAN * d;+ assert_eq!(t.factors(0.0, None, d), (0.0, 0.5));+ assert_eq!(t.factors(span, None, d), (1.0, 1.0));+ let (mid, _) = t.factors(span * 4.0, Some(span * 8.0), d);+ assert_eq!(mid, 1.0);+ let (end, _) = t.factors(span * 8.0, Some(span * 8.0), d);+ assert_eq!(end, 0.0);+ assert_eq!(Taper::NONE.factors(0.0, Some(0.0), d), (1.0, 1.0));+ // a tap keeps its full size; a short stroke still thins at both ends+ assert_eq!(t.factors(0.0, Some(0.0), d), (1.0, 1.0));+ let (short_tip, _) = t.factors(0.0, Some(span), d);+ let (short_mid, _) = t.factors(span / 2.0, Some(span), d);+ assert!(short_tip < 0.1 && short_mid > 0.99);+ }++ #[test]+ fn a_classic_taper_spans_canvas_pixels_whatever_the_size() {+ let t = Taper { start: 0.5, end: 1.0, size: 1.0, opacity: 0.0 };+ // the start grows evenly over half of the span+ let half = 0.5 * CLASSIC_TAPER_SPAN;+ assert_eq!(t.classic_factors(0.0, None, 1.0).0, 0.0);+ assert!((t.classic_factors(half / 2.0, None, 1.0).0 - 0.5).abs() < 1e-5);+ assert_eq!(t.classic_factors(half, None, 1.0).0, 1.0);+ // the end is a short tip however long it is set, as long as the pen takes to lift: the+ // faster the stroke ends, the longer the tip+ let total = 2000.0;+ for pace in [0.5, 1.0, 3.0] {+ let tip = CLASSIC_END_MS * pace;+ assert_eq!(t.classic_factors(total - tip, Some(total), pace).0, 1.0);+ let half_way = t.classic_factors(total - tip / 2.0, Some(total), pace).0;+ assert!((half_way - 0.5f32.powf(CLASSIC_END_EASE)).abs() < 1e-5);+ }+ // set short, the end is shorter still+ let short = Taper { end: 0.02, ..t };+ assert_eq!(short.classic_factors(total - 0.02 * CLASSIC_TAPER_SPAN, Some(total), 1.0).0, 1.0);+ // a short stroke doesn't reach full; a tap keeps its size+ assert!(t.classic_factors(100.0, Some(150.0), 1.0).0 < 0.5);+ assert_eq!(t.classic_factors(0.0, Some(0.0), 1.0), (1.0, 1.0));+ }++ #[test]+ fn the_newer_taper_on_touch_lasts_a_time() {+ let t = Taper { start: 0.5, end: 0.5, size: 1.0, opacity: 0.0 };+ let total = 2000.0;+ // its ends cover what the finger moves over in their time, however long they are set+ for pace in [0.5, 1.0, 3.0] {+ let (start, end) = (TIMED_START_MS * pace, TIMED_END_MS * pace);+ let at = |d: f32, t: &Taper| t.timed_factors(d, Some(total), (pace, pace)).0;+ assert_eq!(at(0.0, &t), 0.0);+ assert!((at(start / 2.0, &t) - 0.5).abs() < 1e-5);+ assert_eq!(at(start, &t), 1.0);+ assert_eq!(at(total - end, &t), 1.0);+ assert!(at(total - end / 2.0, &t) < 0.6);+ assert_eq!(at(total - end, &Taper { end: 1.0, ..t }), 1.0);+ }+ // set very short, an end is shorter; set to none, there is none+ let short = Taper { end: 0.02, ..t };+ assert_eq!(short.timed_factors(total - 0.02 * TIMED_TAPER_SPAN_MS, Some(total), (1.0, 1.0)).0, 1.0);+ assert_eq!(Taper { end: 0.0, ..t }.timed_factors(total, Some(total), (1.0, 1.0)).0, 1.0);+ assert_eq!(t.timed_factors(0.0, Some(0.0), (1.0, 1.0)), (1.0, 1.0));+ }++ #[test]+ fn tilt_reaches_past_its_angle() {+ let deg = |d: f32| d.to_radians();+ // upright, next to nothing; down to 26 degrees above the surface, the most+ assert!(Tilt::reach(0.0, 0.1) < 0.001);+ assert!((Tilt::reach(FLAT_TILT, 0.0) - 0.5).abs() < 1e-3);+ assert!((Tilt::reach(FLAT_TILT, 0.1) - 0.622).abs() < 1e-3);+ assert!((Tilt::reach(FLAT_TILT, 1.0) - 0.882).abs() < 1e-3);+ // at 0.1 it starts about 50 degrees from upright+ assert!(Tilt::reach(deg(48.0), 0.1) < 0.001);+ assert!(Tilt::reach(deg(52.0), 0.1) > 0.02);+ // at 1 it starts at once+ assert!(Tilt::reach(deg(10.0), 1.0) > 0.05);+ assert_eq!(Tilt::reach(f32::NAN, 0.5), 0.0);+ }++ #[test]+ fn sliders_map_into_range() {+ let b = Brush::round_pen();+ assert_eq!(b.diameter(0.0), b.min_size);+ assert_eq!(b.diameter(1.0), b.max_size);+ assert!(b.diameter(0.5) < (b.min_size + b.max_size) / 2.0);+ assert_eq!(b.diameter(f32::NAN), b.diameter(0.5));+ assert_eq!(b.opacity(1.0), 1.0);+ let (s, o) = b.pressure_factors(1.0);+ assert_eq!((s, o), (1.0, 1.0));+ let (s0, _) = b.pressure_factors(0.0);+ assert!((s0 - 0.15).abs() < 1e-5);+ }++ #[test]+ fn a_source_image_keeps_as_text() {+ let n = TEXTURE_SIZE * TEXTURE_SIZE;+ let pixels: Vec<u8> = (0..n).map(|i| (i * 7 % 251) as u8).collect();+ let a = Source::new(pixels.clone()).unwrap();+ let back = Source::from_text(&a.to_text()).unwrap();+ assert_eq!(*back.pixels, pixels);+ assert_eq!(back, a);+ // another image is another source; the wrong size or text is none+ assert_ne!(Source::new(vec![0; n]).unwrap(), a);+ assert!(Source::new(vec![0; 10]).is_none());+ assert!(Source::from_text("not an image!").is_none());+ }++ #[test]+ fn notches_are_saved_per_tool_and_slider_and_found_nearby() {+ let mut n = Notches::default();+ assert!(n.add(0, true, 0.3));+ // already there (within reach), or not a slider position+ assert!(!n.add(0, true, 0.32));+ assert!(!n.add(0, true, 1.5));+ assert!(!n.add(0, true, f32::NAN));+ // another tool's or the other slider's are their own+ assert!(n.add(2, true, 0.3));+ assert!(n.add(0, false, 0.3));+ assert_eq!(n.list(0, true), &[0.3]);+ assert_eq!(n.list(1, true), &[] as &[f32]);+ assert_eq!(n.list(9, true), &[] as &[f32]);+ // the nearest within reach+ assert!(n.add(0, true, 0.37));+ assert_eq!(n.at(0, true, 0.335), Some(0.3));+ assert_eq!(n.at(0, true, 0.345), Some(0.37));+ assert_eq!(n.at(0, true, 0.5), None);+ // full at four+ assert!(n.add(0, true, 0.6));+ assert!(n.add(0, true, 0.9));+ assert!(!n.add(0, true, 0.1));+ assert!(n.remove(0, true, 0.61));+ assert!(!n.remove(0, true, 0.61));+ assert_eq!(n.list(0, true), &[0.3, 0.37, 0.9]);+ assert_eq!(Notches::tool(true, false), 0);+ assert_eq!(Notches::tool(false, true), 1);+ assert_eq!(Notches::tool(false, false), 2);+ }+}diff --git a/crates/engine/src/brushfile.rs b/crates/engine/src/brushfile.rsnew file mode 100644index 0000000..af390b9--- /dev/null+++ b/crates/engine/src/brushfile.rs@@ -0,0 +1,805 @@+//! Brush files: a zip holding a brush's settings as a keyed archive (`Brush.archive`), a preview+//! (`QuickLook/Thumbnail.png`) and any shape and grain images of its own (`Shape.png`,+//! `Grain.png`). Read into the brush studio's controls (the keys and values+//! [`Brush::set_setting`] takes) and written back from a brush, the controls turned into the+//! file's own numbers. A set file is a zip of brushes, each in a folder of its own, with+//! `brushset.plist` giving the set's name and the folders in order.++use crate::brush::{Brush, Notches, SIZE_CURVE};+use crate::document::BlendMode;+use crate::geom::Vec2;+use crate::keyed::{Archive, Builder, Object};+use crate::plist::Value;+use crate::zip::{ZipReader, ZipWriter};++/// A brush as a brush file holds it.+#[derive(Clone, Debug, PartialEq)]+pub struct BrushFile {+ pub name: String,+ pub author: String,+ /// The studio's controls, in the order to set them (the sizes apart: see [`set_sizes`]).+ pub settings: Vec<(String, f32)>,+ /// The file's maximum size (its stamps' squares, in [`PIXELS_PER_SIZE`]).+ pub max_size: f32,+ /// The file's least size, in the same units, if it has one.+ pub min_size: Option<f32>,+ /// The shape's own fixed angle, radians.+ pub shape_angle: f32,+ /// The pressure response (points 0..1 from the left), if it isn't straight.+ pub pressure_curve: Option<Vec<Vec2>>,+ /// The pressure's own curves for the size and the opacity, if not straight.+ pub size_curve: Option<Vec<Vec2>>,+ pub opacity_curve: Option<Vec<Vec2>>,+ pub shape: Texture,+ pub grain: Texture,+ /// Where the size and opacity sliders start when it is picked, 0..1.+ pub paint_size: f32,+ pub paint_opacity: f32,+ /// The sliders' notches for painting, smudging and erasing.+ pub notches: Notches,+ /// Its preview (`QuickLook/Thumbnail.png`), if it has one.+ pub thumbnail: Option<Vec<u8>>,+ /// Its author's picture and signature (PNG), if it has them.+ pub author_picture: Option<Vec<u8>>,+ pub signature: Option<Vec<u8>>,+}++/// A shape or grain image as a brush file names it.+#[derive(Clone, Debug, PartialEq)]+pub enum Texture {+ /// No image: the round tip, or no grain.+ None,+ /// An image that comes with the app that made the file, by its file name (not in the file).+ Stock { name: String, inverted: bool },+ /// An image in the file (PNG or JPEG bytes).+ Image { bytes: Vec<u8>, inverted: bool },+}++/// Canvas pixels a stamp's square is across at the most size, for each 1 of the file's `maxSize`.+pub const PIXELS_PER_SIZE: f32 = 262.0;++/// How much of a stamp's square a hard round tip drawn as an image covers: a round tip of ours+/// (which fills its stamp) stands in for one at this share of the size.+pub const ROUND_TIP_SHARE: f32 = 0.797;++/// Sets `brush`'s sizes from a file's (`maxSize`, `minSize`, in units of its+/// [`Brush::size_unit`], so its shape first), the least kept no larger than the most.+pub fn set_sizes(brush: &mut Brush, max_size: f32, min_size: Option<f32>) {+ let unit = brush.size_unit();+ if max_size.is_finite() {+ brush.max_size = (max_size.max(0.0) * unit).max(0.5);+ }+ if let Some(min) = min_size.filter(|m| m.is_finite()) {+ brush.min_size = (min.max(0.0) * unit).min(brush.max_size);+ }+}++/// How a control's value is kept in the file.+#[derive(Clone, Copy, Debug, PartialEq)]+enum Kept {+ /// As it is.+ Same,+ /// As it is, as a whole number.+ Whole,+ /// The control to the power 2.2, times this (spacing and jitter).+ Curve(f32),+ /// Times this.+ Times(f32),+ /// The control squared, times 16 (grain scale).+ Squared16,+ /// 1 less the control.+ Complement,+ /// A switch.+ Switch,+ /// A choice of three whose last two the file keeps the other way round (the hover fill:+ /// none, shape, all in the list; none, all, shape in the file).+ LastTwoSwapped,+}++/// The list's place for the file's number, or the other way (the same swap both ways).+fn swap_last_two(v: f64) -> f64 {+ match v.round() as i64 {+ 1 => 2.0,+ 2 => 1.0,+ _ => v,+ }+}++/// The file's number for control value `c`.+fn to_file(kept: Kept, c: f32) -> Value {+ let c = f64::from(c);+ match kept {+ Kept::Same => Value::Real(c),+ Kept::Whole => Value::Int(c.round() as i64),+ Kept::Curve(scale) => Value::Real(f64::from(scale) * c.max(0.0).powf(2.2)),+ Kept::Times(k) => Value::Real(c * f64::from(k)),+ Kept::Squared16 => Value::Real(16.0 * c * c),+ Kept::Complement => Value::Real(1.0 - c),+ Kept::Switch => Value::Bool(c >= 0.5),+ Kept::LastTwoSwapped => Value::Int(swap_last_two(c) as i64),+ }+}++/// The control value for the file's number `v`.+fn to_control(kept: Kept, v: f64) -> f32 {+ let c = match kept {+ Kept::Same | Kept::Whole | Kept::Switch => v,+ Kept::Curve(scale) => (v / f64::from(scale)).max(0.0).powf(1.0 / 2.2),+ Kept::Times(k) => v / f64::from(k),+ Kept::Squared16 => (v / 16.0).max(0.0).sqrt(),+ Kept::Complement => 1.0 - v,+ Kept::LastTwoSwapped => swap_last_two(v),+ };+ c as f32+}++/// The controls kept one to one: the studio's key, the file's, and how.+const PLAIN: &[(&str, &str, Kept)] = &[+ // stroke path and stabilization+ ("spacing", "plotSpacing", Kept::Curve(2.0)),+ ("spacing_jitter", "plotSpacingJitter", Kept::Times(10.0)),+ ("spacing_version", "plotSpacingVersion", Kept::Whole),+ ("jitter_lateral", "plotJitter", Kept::Curve(3.0)),+ ("jitter_linear", "plotJitterLongitudinal", Kept::Curve(3.0)),+ ("falloff", "dynamicsFalloff", Kept::Same),+ ("streamline", "plotSmoothing", Kept::Same),+ ("streamline_pressure", "dynamicsPressureSmoothing", Kept::Same),+ ("stabilization", "plotMovingAverageStabilization", Kept::Same),+ ("motion_filtering", "plotFFTSmoothingAmount", Kept::Same),+ ("motion_expression", "plotFFTSmoothingBias", Kept::Same),+ // taper: the pen's, then touch's+ ("pen_taper_start", "pencilTaperStartLength", Kept::Same),+ ("pen_taper_end", "pencilTaperEndLength", Kept::Same),+ ("pen_taper_size", "pencilTaperSize", Kept::Same),+ ("pen_taper_opacity", "pencilTaperOpacity", Kept::Same),+ ("pen_taper_pressure", "taperPressure", Kept::Same),+ ("pen_taper_tip", "pencilTaperShape", Kept::Same),+ ("pen_taper_link", "pencilTaperSizeLinked", Kept::Switch),+ ("pen_tip_animation", "pencilTipAnimation", Kept::Switch),+ ("touch_taper_start", "taperStartLength", Kept::Same),+ ("touch_taper_end", "taperEndLength", Kept::Same),+ ("touch_taper_size", "taperSize", Kept::Same),+ ("touch_taper_opacity", "taperOpacity", Kept::Same),+ ("touch_taper_tip", "taperShape", Kept::Same),+ ("touch_taper_link", "taperSizeLinked", Kept::Switch),+ // shape+ ("relative_to_stroke", "shapeRollMode", Kept::Whole),+ ("shape_rotation", "shapeRotation", Kept::Same),+ ("scatter", "shapeScatter", Kept::Times(2.0)),+ ("count_jitter", "shapeCountJitter", Kept::Same),+ ("randomized", "shapeRandomise", Kept::Switch),+ ("flip_x", "shapeFlipXJitter", Kept::Switch),+ ("flip_y", "shapeFlipYJitter", Kept::Switch),+ ("roundness", "shapeRoundness", Kept::Same),+ ("pressure_roundness", "dynamicsPressureShapeRoundnessMinimum", Kept::Complement),+ ("tilt_roundness", "dynamicsTiltShapeRoundnessMinimum", Kept::Complement),+ ("roundness_jitter_y", "jitterShapeRoundness", Kept::Same),+ ("roundness_jitter_x", "jitterShapeRoundnessX", Kept::Same),+ // grain+ ("grain_behavior", "textureApplication", Kept::Whole),+ ("grain_movement", "textureMovement", Kept::Same),+ ("grain_scale", "textureScale", Kept::Squared16),+ ("grain_zoom", "textureZoom", Kept::Same),+ ("grain_rotation", "textureRotation", Kept::Same),+ ("grain_depth", "grainDepth", Kept::Same),+ ("grain_depth_min", "grainDepthMinimum", Kept::Same),+ ("grain_depth_jitter", "grainDepthJitter", Kept::Same),+ ("grain_offset_jitter", "textureOffsetJitter", Kept::Switch),+ ("grain_brightness", "textureBrightness", Kept::Same),+ ("grain_contrast", "textureContrast", Kept::Same),+ ("grain_follows_camera", "texturizedGrainFollowsCamera", Kept::Switch),+ // rendering+ ("flow", "dynamicsGlazedFlow", Kept::Same),+ ("wet_edges", "wetEdgesAmount", Kept::Same),+ ("burnt_edges", "burntEdgesAmount", Kept::Same),+ ("luminance_blending", "blendGammaCorrect", Kept::Switch),+ ("alpha_threshold", "alphaThreshold", Kept::Switch),+ ("alpha_threshold_amount", "alphaThresholdAmount", Kept::Same),+ ("classic_combine", "legacyNormalDual", Kept::Switch),+ // wet mix+ ("wet_dilution", "dynamicsMix", Kept::Same),+ ("wet_charge", "dynamicsLoad", Kept::Same),+ ("wet_attack", "dynamicsPressureMix", Kept::Same),+ ("wet_pull", "dynamicsWetAccumulation", Kept::Same),+ ("wet_grade", "dynamicsMixSoftening", Kept::Same),+ ("wet_blur", "dynamicsBlur", Kept::Same),+ ("wet_blur_jitter", "dynamicsBlurJitter", Kept::Same),+ ("wet_jitter", "dynamicsWetnessJitter", Kept::Same),+ // colour dynamics+ ("stamp_hue", "dynamicsJitterHue", Kept::Same),+ ("stamp_saturation", "dynamicsJitterSaturation", Kept::Same),+ ("stamp_lightness", "dynamicsJitterLightness", Kept::Same),+ ("stamp_darkness", "dynamicsJitterDarkness", Kept::Same),+ ("stamp_secondary", "jitterSecondary", Kept::Same),+ ("stroke_hue", "dynamicsJitterStrokeHue", Kept::Same),+ ("stroke_saturation", "dynamicsJitterStrokeSaturation", Kept::Same),+ ("stroke_lightness", "dynamicsJitterStrokeLightness", Kept::Same),+ ("stroke_darkness", "dynamicsJitterStrokeDarkness", Kept::Same),+ ("stroke_secondary", "jitterStrokeSecondary", Kept::Same),+ ("pressure_hue", "dynamicsPressureHue", Kept::Same),+ ("pressure_saturation", "dynamicsPressureSaturation", Kept::Same),+ ("pressure_brightness", "dynamicsPressureBrightness", Kept::Same),+ ("pressure_secondary", "dynamicsPressureSecondaryColor", Kept::Same),+ ("tilt_hue", "dynamicsTiltHue", Kept::Same),+ ("tilt_saturation", "dynamicsTiltSaturation", Kept::Same),+ ("tilt_brightness", "dynamicsTiltBrightness", Kept::Same),+ ("tilt_secondary", "dynamicsTiltSecondaryColor", Kept::Same),+ ("roll_hue", "dynamicsRollHue", Kept::Same),+ ("roll_saturation", "dynamicsRollSaturation", Kept::Same),+ ("roll_brightness", "dynamicsRollBrightness", Kept::Same),+ ("roll_secondary", "dynamicsRollSecondaryColor", Kept::Same),+ // dynamics+ ("speed_size", "dynamicsSpeedSize", Kept::Same),+ ("speed_opacity", "dynamicsSpeedOpacity", Kept::Same),+ ("speed_spacing", "plotSpacingSpeed", Kept::Times(10.0)),+ ("jitter_size", "dynamicsJitterSize", Kept::Same),+ ("jitter_opacity", "dynamicsJitterOpacity", Kept::Same),+ // the pen+ ("pressure_size", "dynamicsPressureSize", Kept::Same),+ ("pressure_opacity", "dynamicsPressureOpacity", Kept::Same),+ ("pressure_flow", "dynamicsPressureOpacityTransfer", Kept::Same),+ ("pressure_bleed", "dynamicsPressureBleed", Kept::Curve(1.0)),+ ("tilt_angle", "dynamicsTiltAngle", Kept::Same),+ ("opacity_tilt_angle", "opacityTiltAngle", Kept::Same),+ ("size_tilt_angle", "sizeTiltAngle", Kept::Same),+ ("gradation_tilt_angle", "gradationTiltAngle", Kept::Same),+ ("bleed_tilt_angle", "bleedTiltAngle", Kept::Same),+ ("roundness_tilt_angle", "shapeRoundnessTiltAngle", Kept::Same),+ ("hue_tilt_angle", "hueTiltAngle", Kept::Same),+ ("saturation_tilt_angle", "saturationTiltAngle", Kept::Same),+ ("brightness_tilt_angle", "brightnessTiltAngle", Kept::Same),+ ("secondary_tilt_angle", "secondaryColorTiltAngle", Kept::Same),+ ("tilt_roundness_max", "dynamicsTiltShapeRoundness", Kept::Same),+ ("tilt_opacity", "dynamicsTiltOpacity", Kept::Same),+ ("tilt_gradation", "dynamicsTiltGradation", Kept::Same),+ ("tilt_bleed", "dynamicsTiltBleed", Kept::Curve(1.0)),+ ("tilt_size", "dynamicsTiltSize", Kept::Same),+ ("tilt_size_compression", "dynamicsTiltCompression", Kept::Same),+ ("roll_size", "dynamicsRollSize", Kept::Same),+ ("roll_opacity", "dynamicsRollOpacity", Kept::Same),+ ("roll_bleed", "dynamicsRollBleed", Kept::Same),+ ("cursor_outline", "hoverOutline", Kept::Whole),+ ("hover_pressure", "hoverPressure", Kept::Same),+ ("hover_fill", "hoverFill", Kept::LastTwoSwapped),+ // properties and preview+ ("orient_to_screen", "oriented", Kept::Switch),+ ("smudge_pull", "dynamicsSmudgeAccumulation", Kept::Same),+ ("max_opacity", "maxOpacity", Kept::Same),+ ("min_opacity", "minOpacity", Kept::Same),+ ("preview_stamp", "stamp", Kept::Switch),+ ("preview_size", "previewSize", Kept::Same),+ ("preview_pressure_min", "previewPressureMinimum", Kept::Same),+ ("preview_pressure_scale", "previewPressureScale", Kept::Times(2.0)),+ ("preview_wet_mix", "previewWetMixEnabled", Kept::Switch),+ ("preview_tilt", "previewTiltEnabled", Kept::Switch),+ ("pressure_size_response", "dynamicsPressureSizeSpeed", Kept::Same),+ ("pressure_opacity_response", "dynamicsPressureOpacitySpeed", Kept::Same),+ ("pressure_bleed_response", "dynamicsPressureBleedSpeed", Kept::Same),+ ("pressure_roundness_response", "dynamicsPressureResponse", Kept::Same),+ ("preview_tilt_offset", "previewTiltAngleOffset", Kept::Same),+];++/// Rendering modes as the studio lists them, by the file's three switches (recursive mixing, the+/// most transfer, modulated transfer).+const RENDERING: [(bool, bool, bool); 6] = [+ (false, true, false),+ (false, true, true),+ (false, false, false),+ (false, false, true),+ (true, false, true),+ (true, false, false),+];++/// The number of stamps a place for the count a file stores: one more than fifteen times it,+/// whole (so a sixteenth for each stamp, as files are written, reads back the same).+fn stamp_count(stored: f64) -> f32 {+ ((stored * 15.0).floor() + 1.0).clamp(1.0, 16.0) as f32+}++/// A brush file's root object's values, read through.+struct Fields<'a>(Object<'a>);++impl Fields<'_> {+ fn num(&self, key: &str) -> Option<f64> {+ self.0.real(key).or_else(|| self.0.bool(key).map(|b| if b { 1.0 } else { 0.0 }))+ }+ fn flag(&self, key: &str) -> bool {+ self.num(key).is_some_and(|v| v >= 0.5)+ }+ /// A string, none for the archive's null.+ fn text(&self, key: &str) -> Option<String> {+ self.0.string(key).filter(|s| s != "$null" && !s.is_empty())+ }+ /// A curve's points ("{x, y}" strings).+ fn curve(&self, key: &str) -> Option<Vec<Vec2>> {+ let points: Vec<Vec2> = self+ .0+ .object(key)?+ .values("points")+ .iter()+ .filter_map(|v| {+ let s = v.as_str()?;+ let (x, y) = s.trim_matches(|c| c == '{' || c == '}').split_once(',')?;+ Some(Vec2::new(x.trim().parse().ok()?, y.trim().parse().ok()?))+ })+ .collect();+ (points.len() >= 2).then_some(points)+ }+ fn reals(&self, key: &str) -> Vec<f32> {+ self.0.values(key).iter().filter_map(|v| v.as_real()).map(|v| v as f32).collect()+ }+}++/// Reads a brush file; none if it isn't one.+pub fn read(bytes: &[u8]) -> Option<BrushFile> {+ read_in(&ZipReader::new(bytes)?, "")+}++/// Reads a set file: the set's name and its brushes in order; none if it isn't one.+pub fn read_set(bytes: &[u8]) -> Option<(String, Vec<BrushFile>)> {+ let zip = ZipReader::new(bytes)?;+ let (name, folders) = set_list(&zip.read("brushset.plist")?)?;+ let brushes: Vec<BrushFile> = folders.iter().filter_map(|f| read_in(&zip, &format!("{f}/"))).collect();+ (!brushes.is_empty()).then_some((name, brushes))+}++/// The set's name and its brushes' folders from `brushset.plist` (XML or binary).+fn set_list(bytes: &[u8]) -> Option<(String, Vec<String>)> {+ if bytes.starts_with(b"bplist") {+ let root = crate::plist::read(bytes)?;+ let Value::Dict(fields) = root else { return None };+ let get = |k: &str| fields.iter().find(|(key, _)| key == k).map(|(_, v)| v);+ let name = get("name").and_then(|v| v.as_str()).unwrap_or("Imported").to_owned();+ let folders = get("brushes")?.as_array()?.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect();+ return Some((name, folders));+ }+ let text = std::str::from_utf8(bytes).ok()?;+ // the string after `<key>name</key>`, and the strings in the array after `<key>brushes</key>`+ let after = |key: &str| text.split_once(&format!("<key>{key}</key>")).map(|(_, rest)| rest);+ let strings = |part: &str| -> Vec<String> {+ part.split("<string>").skip(1).filter_map(|s| s.split_once("</string>").map(|(v, _)| unescape(v))).collect()+ };+ let name = after("name").and_then(|rest| strings(rest).into_iter().next()).unwrap_or_else(|| "Imported".to_owned());+ let array = after("brushes")?.split_once("</array>")?.0;+ Some((name, strings(array)))+}++fn unescape(s: &str) -> String {+ s.replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'").replace("&", "&")+}++fn escape(s: &str) -> String {+ s.replace('&', "&").replace('<', "<").replace('>', ">")+}++/// Reads the brush whose files are under `prefix` in `zip`.+fn read_in(zip: &ZipReader<'_>, prefix: &str) -> Option<BrushFile> {+ let archive = Archive::read(&zip.read(&format!("{prefix}Brush.archive"))?)?;+ let root = archive.root()?;+ let f = Fields(root);+ let mut settings: Vec<(String, f32)> = Vec::new();+ let mut set = |key: &str, v: f32| {+ if v.is_finite() {+ settings.push((key.to_owned(), v));+ }+ };+ for &(control, key, kept) in PLAIN {+ if let Some(v) = f.num(key) {+ set(control, to_control(kept, v));+ }+ }+ if let Some(v) = f.num("shapeCount") {+ let count = stamp_count(v);+ set("count", (count - 1.0) / (crate::studio::MAX_COUNT as f32 - 1.0));+ }+ let style = if f.flag("shapeRoll") {+ 2.0+ } else if f.flag("shapeAzimuth") {+ 1.0+ } else {+ 0.0+ };+ set("input_style", style);+ // older files without a spacing version: the older spacing if they have a dual brush's blend+ if f.num("plotSpacingVersion").is_none() {+ set("spacing_version", if f.num("dualBlendMode").is_some() { 0.0 } else { 1.0 });+ }+ let switches =+ (f.flag("renderingRecursiveMixing"), f.flag("renderingMaxTransfer"), f.flag("renderingModulatedTransfer"));+ if let Some(mode) = RENDERING.iter().position(|&r| r == switches) {+ set("rendering_mode", mode as f32);+ }+ // the classic taper is the old one+ if let Some(v) = f.num("taperVersion") {+ set("classic_taper", if v < 0.5 { 1.0 } else { 0.0 });+ }+ for (control, on, mode) in [+ ("shape_filtering", "shapeFilter", "shapeFilterMode"),+ ("grain_filtering", "textureFilter", "textureFilterMode"),+ ] {+ if f.num(on).is_some() {+ // none, classic, improved+ set(+ control,+ if !f.flag(on) {+ 0.0+ } else if f.flag(mode) {+ 1.0+ } else {+ 2.0+ },+ );+ }+ }+ // blend modes by the layers' numbering, the newest key first+ let blend = |keys: &[&str]| keys.iter().find_map(|k| f.num(k)).map(|n| crate::native::blend_from(n.round() as i64));+ if let Some(m) = blend(&["extendedBlend2", "extendedBlend", "blendMode"]) {+ set("blend_mode", m.id() as f32);+ }+ if let Some(m) = blend(&["grainBlendModeExtended", "grainBlendMode"]) {+ set("grain_blend", m.id() as f32);+ }+ if let Some(m) = blend(&["burntEdgesBlendModeExtended", "burntEdgesBlendMode"]) {+ set("burnt_blend", m.id() as f32);+ }+ // an image of the brush's own is in the file by a name of its own (its path then null), or+ // by the name its path gives; else the path names a stock image+ let texture = |path: &str, own: &str, inverted: &str| {+ let inverted = f.flag(inverted);+ match f.text(path) {+ None => match zip.read(&format!("{prefix}{own}")) {+ Some(bytes) => Texture::Image { bytes, inverted },+ None => Texture::None,+ },+ Some(name) => {+ let file = name.rsplit('/').next().unwrap_or(&name);+ match zip.read(&format!("{prefix}{name}")).or_else(|| zip.read(&format!("{prefix}{file}"))) {+ Some(bytes) => Texture::Image { bytes, inverted },+ None => Texture::Stock { name, inverted },+ }+ }+ }+ };+ // sizes are kept as the size the slider sets (its place to the power of its curve)+ let place = |v: Vec<f32>| v.into_iter().map(|s| s.max(0.0).powf(1.0 / SIZE_CURVE)).collect::<Vec<f32>>();+ let notches = Notches {+ sizes: ["savedPaintSizes", "savedSmudgeSizes", "savedEraseSizes"].map(|k| place(f.reals(k))),+ opacities: ["savedPaintOpacities", "savedSmudgeOpacities", "savedEraseOpacities"].map(|k| f.reals(k)),+ };+ Some(BrushFile {+ name: f.text("name").unwrap_or_else(|| "Imported Brush".to_owned()),+ author: f.text("authorName").unwrap_or_default(),+ settings,+ max_size: f.num("maxSize").unwrap_or(1.0) as f32,+ min_size: f.num("minSize").map(|v| v as f32),+ shape_angle: f.num("shapeAngle").unwrap_or(0.0) as f32,+ pressure_curve: f.curve("dynamicsPressureOverall").filter(|c| !is_straight(c)),+ size_curve: f.curve("dynamicsPressureSizeCurve").filter(|c| !is_straight(c)),+ opacity_curve: f.curve("dynamicsPressureOpacityCurve").filter(|c| !is_straight(c)),+ shape: texture("bundledShapePath", "Shape.png", "shapeInverted"),+ grain: texture("bundledGrainPath", "Grain.png", "textureInverted"),+ paint_size: f.num("paintSize").unwrap_or(0.5) as f32,+ paint_opacity: f.num("paintOpacity").unwrap_or(1.0) as f32,+ notches,+ thumbnail: zip.read(&format!("{prefix}QuickLook/Thumbnail.png")),+ author_picture: zip.read(&format!("{prefix}{AUTHOR_PICTURE}")),+ signature: zip.read(&format!("{prefix}{SIGNATURE}")),+ })+}++fn is_straight(points: &[Vec2]) -> bool {+ points.iter().all(|p| (p.x - p.y).abs() < 1e-3)+}++/// The images and pictures a brush file carries beside the settings.+pub struct Pictures<'a> {+ /// The shape (PNG): the brush's image, or its round tip drawn.+ pub shape_png: &'a [u8],+ /// The grain (PNG), or none for no grain.+ pub grain_png: Option<&'a [u8]>,+ /// The brush's preview stroke (PNG).+ pub thumbnail_png: &'a [u8],+ /// Its author's picture and signature (PNG), if it has them.+ pub author_png: Option<&'a [u8]>,+ pub signature_png: Option<&'a [u8]>,+}++/// Where a brush's folder keeps its author's picture and signature.+const AUTHOR_PICTURE: &str = "AuthorPicture/AuthorPicture.png";+const SIGNATURE: &str = "Signature/SignaturePicture.png";++/// Writes `brush` as a brush file by `author`, with `pictures`.+pub fn write(brush: &Brush, author: &str, pictures: &Pictures<'_>) -> Vec<u8> {+ let mut zip = ZipWriter::new();+ add_brush(&mut zip, "", brush, author, pictures);+ zip.finish()+}++/// Writes a set file named `name` of `brushes` (each with its author and pictures), each in a+/// folder named by `id`.+pub fn write_set(name: &str, brushes: &[(&Brush, &str, Pictures<'_>)], id: impl Fn(usize) -> String) -> Vec<u8> {+ let mut zip = ZipWriter::new();+ let folders: Vec<String> = (0..brushes.len()).map(id).collect();+ let mut list = String::from(+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<plist version=\"1.0\">\n<dict>\n\t<key>brushes</key>\n\t<array>\n",+ );+ for f in &folders {+ list.push_str(&format!("\t\t<string>{}</string>\n", escape(f)));+ }+ list.push_str(&format!("\t</array>\n\t<key>name</key>\n\t<string>{}</string>\n</dict>\n</plist>\n", escape(name)));+ zip.add("brushset.plist", list.as_bytes());+ for ((brush, author, pictures), folder) in brushes.iter().zip(&folders) {+ add_brush(&mut zip, &format!("{folder}/"), brush, author, pictures);+ }+ zip.finish()+}++/// A brush's files into `zip` under `prefix`.+fn add_brush(zip: &mut ZipWriter, prefix: &str, brush: &Brush, author: &str, pictures: &Pictures<'_>) {+ let mut b = Builder::new();+ let root = b.reserve();+ let mut fields: Vec<(String, Value)> = Vec::new();+ let mut put = |key: &str, v: Value| fields.push((key.to_owned(), v));+ let name = b.string(&brush.name);+ put("name", name);+ let author = b.string(author);+ put("authorName", author);+ put("version", Value::Int(4));+ put("maxSize", Value::Real(f64::from(brush.max_size / brush.size_unit())));+ put("minSize", Value::Real(f64::from(brush.min_size / brush.size_unit())));+ for &(control, key, kept) in PLAIN {+ put(key, to_file(kept, brush.setting(control)));+ }+ let count = 1.0 + (brush.setting("count") * (crate::studio::MAX_COUNT as f32 - 1.0)).round();+ put("shapeCount", Value::Real(f64::from(count / 16.0)));+ let style = brush.setting("input_style").round();+ put("shapeAzimuth", Value::Bool(style >= 1.0));+ put("shapeRoll", Value::Bool(style >= 2.0));+ let (recursive, max, modulated) = RENDERING+ .get(brush.setting("rendering_mode").round().clamp(0.0, 5.0) as usize)+ .copied()+ .unwrap_or(RENDERING[5]);+ put("renderingRecursiveMixing", Value::Bool(recursive));+ put("renderingMaxTransfer", Value::Bool(max));+ put("renderingModulatedTransfer", Value::Bool(modulated));+ put("taperVersion", Value::Int(if brush.setting("classic_taper") >= 0.5 { 0 } else { 1 }));+ for (control, on, mode) in [+ ("shape_filtering", "shapeFilter", "shapeFilterMode"),+ ("grain_filtering", "textureFilter", "textureFilterMode"),+ ] {+ let v = brush.setting(control).round();+ put(on, Value::Bool(v >= 1.0));+ put(mode, Value::Int(i64::from(v == 1.0)));+ }+ let number = |control: &str| {+ let id = BlendMode::from_id(brush.setting(control).round().max(0.0) as u32).unwrap_or(BlendMode::Normal);+ crate::native::blend_to(id)+ };+ let mode = number("blend_mode");+ let (oldest, older) = crate::native::older_blends(mode);+ put("blendMode", Value::Int(oldest));+ put("extendedBlend", Value::Int(older));+ put("extendedBlend2", Value::Int(mode));+ let grain_blend = number("grain_blend");+ put("grainBlendMode", Value::Int(crate::native::older_blends(grain_blend).1));+ put("grainBlendModeExtended", Value::Int(grain_blend));+ let burnt = number("burnt_blend");+ put("burntEdgesBlendMode", Value::Int(crate::native::older_blends(burnt).1));+ put("burntEdgesBlendModeExtended", Value::Int(burnt));+ put("shapeAngle", Value::Real(f64::from(brush.shape.rotation)));+ // a stock image as the brush's file named it; otherwise the image is its own, the file by+ // its own name+ for (stock, path, inverted) in [+ (&brush.stock.shape, "bundledShapePath", "shapeInverted"),+ (&brush.stock.grain, "bundledGrainPath", "textureInverted"),+ ] {+ match stock {+ Some(s) => {+ let name = b.string(&s.name);+ put(path, name);+ put(inverted, Value::Bool(s.inverted));+ }+ None => {+ put(path, Builder::null());+ put(inverted, Value::Bool(false));+ }+ }+ }+ // the pressure response, and its own curves for the size and the opacity+ for (key, c) in [+ ("dynamicsPressureOverall", &brush.pressure_curve),+ ("dynamicsPressureSizeCurve", &brush.size_curve),+ ("dynamicsPressureOpacityCurve", &brush.opacity_curve),+ ] {+ let points: Vec<Value> = c.points().iter().map(|p| b.string(&format!("{{{:.6}, {:.6}}}", p.x, p.y))).collect();+ let list = b.array(points, true);+ let curve = b.object(&["ValkyrieMagnitudinalCurve", "NSObject"], vec![("points", list)]);+ put(key, curve);+ }+ // the sliders' notches+ for (k, tool) in ["Paint", "Smudge", "Erase"].iter().enumerate() {+ for (kind, lists, curve) in+ [("Sizes", &brush.notches.sizes, SIZE_CURVE), ("Opacities", &brush.notches.opacities, 1.0)]+ {+ let values = lists+ .get(k)+ .map_or(Vec::new(), |l| l.iter().map(|v| Value::Real(f64::from(v.max(0.0).powf(curve)))).collect());+ let array = b.array(values, false);+ put(&format!("saved{tool}{kind}"), array);+ }+ }+ put("paintSize", Value::Real(0.5));+ put("paintOpacity", Value::Real(1.0));+ let refs: Vec<(&str, Value)> = fields.iter().map(|(k, v)| (k.as_str(), v.clone())).collect();+ b.fill(&root, &["SilicaBrush", "ValkyrieBrush", "NSObject"], refs);+ let archive = b.finish(root);+ zip.add(&format!("{prefix}Brush.archive"), &archive);+ zip.add(&format!("{prefix}Shape.png"), pictures.shape_png);+ if let Some(grain) = pictures.grain_png {+ zip.add(&format!("{prefix}Grain.png"), grain);+ }+ zip.add(&format!("{prefix}QuickLook/Thumbnail.png"), pictures.thumbnail_png);+ for (path, png) in [(AUTHOR_PICTURE, pictures.author_png), (SIGNATURE, pictures.signature_png)] {+ if let Some(png) = png {+ zip.add(&format!("{prefix}{path}"), png);+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn conversions_go_both_ways() {+ for kept in+ [Kept::Same, Kept::Curve(2.0), Kept::Curve(3.0), Kept::Times(10.0), Kept::Squared16, Kept::Complement]+ {+ for c in [0.0f32, 0.17, 0.5, 1.0] {+ let back = to_control(kept, to_file(kept, c).as_real().unwrap());+ assert!((back - c).abs() < 1e-5, "{kept:?} {c} {back}");+ }+ }+ // the studio's spacing and grain scale as the file keeps them+ assert!((to_control(Kept::Curve(2.0), 0.042) - 0.1727).abs() < 1e-3);+ assert!((to_control(Kept::Squared16, 1.0) - 0.25).abs() < 1e-6);+ }++ #[test]+ fn a_brush_survives_a_round_trip() {+ let mut brush =+ crate::library::library().into_iter().flat_map(|s| s.brushes).find(|b| b.name == "Flat Brush").unwrap();+ brush.set_setting("spacing", 0.3);+ brush.set_setting("rendering_mode", 3.0);+ brush.set_setting("blend_mode", BlendMode::Multiply.id() as f32);+ brush.set_setting("count", 4.0 / 15.0);+ brush.set_setting("wet_pull", 0.6);+ brush.set_setting("input_style", 1.0);+ brush.notches.sizes[0] = vec![0.25, 0.5];+ brush.size_curve = crate::curve::Curve::new(&[Vec2::new(0.0, 0.0), Vec2::new(0.42, 0.2), Vec2::new(1.0, 1.0)]);+ let file = write(+ &brush,+ "Someone",+ &Pictures {+ shape_png: b"shape",+ grain_png: Some(b"grain"),+ thumbnail_png: b"thumb",+ author_png: Some(b"face"),+ signature_png: None,+ },+ );+ let back = read(&file).unwrap();+ assert_eq!(back.name, "Flat Brush");+ assert_eq!(back.author, "Someone");+ assert_eq!(back.author_picture.as_deref(), Some(&b"face"[..]));+ assert_eq!(back.signature, None);+ assert_eq!(back.shape, Texture::Image { bytes: b"shape".to_vec(), inverted: false });+ assert_eq!(back.grain, Texture::Image { bytes: b"grain".to_vec(), inverted: false });+ assert_eq!(back.notches.sizes[0], vec![0.25, 0.5]);+ let size_curve = back.size_curve.as_ref().unwrap();+ assert!((size_curve[1] - Vec2::new(0.42, 0.2)).length() < 1e-5);+ assert!(back.opacity_curve.is_none());+ assert!((back.shape_angle - brush.shape.rotation).abs() < 1e-6);+ let mut again = Brush::round_pen();+ set_sizes(&mut again, back.max_size, back.min_size);+ for (k, v) in &back.settings {+ again.set_setting(k, *v);+ }+ for key in [+ "spacing",+ "rendering_mode",+ "blend_mode",+ "count",+ "wet_pull",+ "input_style",+ "shape_rotation",+ "max_size",+ "min_size",+ "flow",+ "pressure_size",+ "grain_scale",+ ] {+ assert!(+ (again.setting(key) - brush.setting(key)).abs() < 1e-3,+ "{key}: {} {}",+ again.setting(key),+ brush.setting(key)+ );+ }+ }++ #[test]+ fn stamp_counts_read_as_stored() {+ // between sixteenths, by fifteenths: 0.1392 is three stamps+ assert_eq!(stamp_count(0.1392), 3.0);+ assert_eq!(stamp_count(0.0), 1.0);+ assert_eq!(stamp_count(2.0), 16.0);+ // what is written reads back+ for k in 1..=16u8 {+ assert_eq!(stamp_count(f64::from(k) / 16.0), f32::from(k));+ }+ }++ #[test]+ fn a_set_survives_a_round_trip() {+ let sets = crate::library::library();+ let brushes: Vec<Brush> = sets.first().unwrap().brushes.iter().take(3).cloned().collect();+ let pictures = || Pictures {+ shape_png: b"shape",+ grain_png: None,+ thumbnail_png: b"thumb",+ author_png: None,+ signature_png: None,+ };+ let list: Vec<(&Brush, &str, Pictures<'_>)> = brushes.iter().map(|b| (b, "", pictures())).collect();+ let file = write_set("Sketch & Ink", &list, |i| format!("BRUSH-{i}"));+ let (name, back) = read_set(&file).unwrap();+ assert_eq!(name, "Sketch & Ink");+ let names: Vec<&str> = back.iter().map(|b| b.name.as_str()).collect();+ assert_eq!(names, brushes.iter().map(|b| b.name.as_str()).collect::<Vec<_>>());+ assert_eq!(back.first().unwrap().shape, Texture::Image { bytes: b"shape".to_vec(), inverted: false });+ assert_eq!(back.first().unwrap().grain, Texture::None);+ assert!(read_set(&write(brushes.first().unwrap(), "", &pictures())).is_none());+ }++ #[test]+ fn other_files_are_not_brushes() {+ assert!(read(b"nothing").is_none());+ let mut zip = ZipWriter::new();+ zip.add("something.txt", b"hello");+ assert!(read(&zip.finish()).is_none());+ }++ /// Prints what a brush file holds as the studio's controls:+ /// `BRUSH_FILE=path cargo test -p procraft-engine brush_file_controls -- --ignored --nocapture`.+ #[test]+ #[ignore]+ fn brush_file_controls() {+ let Ok(path) = std::env::var("BRUSH_FILE") else { return };+ let bytes = std::fs::read(path).unwrap();+ if let Some((name, brushes)) = read_set(&bytes) {+ println!(+ "set {name}: {}",+ brushes+ .iter()+ .map(|b| format!("{} ({:?})", b.name, matches!(b.shape, Texture::Image { .. })))+ .collect::<Vec<_>>()+ .join(", ")+ );+ return;+ }+ let file = read(&bytes).unwrap();+ println!(+ "{} by {:?}; shape {:?}",+ file.name,+ file.author,+ match &file.shape {+ Texture::Image { bytes, .. } => format!("image of {} bytes", bytes.len()),+ t => format!("{t:?}"),+ }+ );+ for (k, v) in &file.settings {+ println!(" {k} = {v:.4}");+ }+ }+}diff --git a/crates/engine/src/cms.rs b/crates/engine/src/cms.rsnew file mode 100644index 0000000..d119cab--- /dev/null+++ b/crates/engine/src/cms.rs@@ -0,0 +1,913 @@+//! Colour management: ICC profiles read, and colours moved from one profile to another.+//!+//! A profile takes its device's colours (RGB, CMYK or grey, each 0..1) to the profile connection+//! space (CIE XYZ or Lab, D50) and back, through one of the ICC's pipelines: a matrix with tone+//! curves, a grey tone curve, 8- and 16-bit lookup tables (`mft1`, `mft2`) or the version 4 ones+//! (`mAB `, `mBA `). Colours go from one profile to another through the connection space, by the+//! perceptual tables where a profile has them (no black point compensation).++use std::sync::Arc;++/// What a profile's device colours are.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Space {+ Rgb,+ Cmyk,+ Gray,+}++impl Space {+ /// How many channels its colours have.+ pub fn channels(self) -> usize {+ match self {+ Space::Rgb => 3,+ Space::Cmyk => 4,+ Space::Gray => 1,+ }+ }+}++/// The connection space a profile's tables meet in.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum Pcs {+ Xyz,+ Lab,+}++/// The connection space's white, D50.+pub const D50: [f64; 3] = [0.9642, 1.0, 0.8249];++/// A tone curve over 0..1.+#[derive(Clone, Debug, PartialEq)]+enum Curve {+ Identity,+ Gamma(f64),+ /// Points evenly spread over 0..1, joined by straight lines.+ Table(Vec<f64>),+ /// An ICC parametric curve: its function type (0 to 4) and parameters g, a, b, c, d, e, f.+ Parametric(u16, [f64; 7]),+}++impl Curve {+ fn eval(&self, x: f64) -> f64 {+ let x = x.clamp(0.0, 1.0);+ match self {+ Curve::Identity => x,+ Curve::Gamma(g) => x.powf(*g),+ Curve::Table(t) => {+ let n = t.len();+ if n < 2 {+ return t.first().copied().unwrap_or(x);+ }+ let at = x * (n - 1) as f64;+ let i = (at.floor() as usize).min(n - 2);+ let (a, b) = (t.get(i).copied().unwrap_or(0.0), t.get(i + 1).copied().unwrap_or(0.0));+ a + (b - a) * (at - i as f64)+ }+ Curve::Parametric(kind, p) => {+ let [g, a, b, c, d, e, f] = *p;+ let power = |v: f64| if v > 0.0 { v.powf(g) } else { 0.0 };+ match kind {+ 0 => power(x),+ 1 => {+ if x >= -b / a {+ power(a * x + b)+ } else {+ 0.0+ }+ }+ 2 => {+ if x >= -b / a {+ power(a * x + b) + c+ } else {+ c+ }+ }+ 3 => {+ if x >= d {+ power(a * x + b)+ } else {+ c * x+ }+ }+ _ => {+ if x >= d {+ power(a * x + b) + e+ } else {+ c * x + f+ }+ }+ }+ }+ }+ }++ /// The x the curve takes to `y`, found by halving (curves only ever rise or only ever fall).+ fn inverse(&self, y: f64) -> f64 {+ match self {+ Curve::Identity => y.clamp(0.0, 1.0),+ Curve::Gamma(g) if *g > 0.0 => y.clamp(0.0, 1.0).powf(1.0 / g),+ _ => {+ let rising = self.eval(1.0) >= self.eval(0.0);+ let (mut lo, mut hi) = (0.0f64, 1.0f64);+ for _ in 0..40 {+ let mid = (lo + hi) / 2.0;+ if (self.eval(mid) < y) == rising {+ lo = mid;+ } else {+ hi = mid;+ }+ }+ (lo + hi) / 2.0+ }+ }+ }+}++/// A colour lookup table: `grid` points along each input, `outputs` values (0..1) at each point,+/// the first input varying slowest.+#[derive(Clone, Debug, PartialEq)]+struct Clut {+ grid: Vec<usize>,+ outputs: usize,+ values: Vec<f64>,+}++impl Clut {+ /// The outputs at `input` (0..1 each), interpolated between the grid's corners.+ fn eval(&self, input: &[f64]) -> Vec<f64> {+ let n = self.grid.len();+ let mut base = Vec::with_capacity(n);+ let mut frac = Vec::with_capacity(n);+ for (k, &g) in self.grid.iter().enumerate() {+ let at = input.get(k).copied().unwrap_or(0.0).clamp(0.0, 1.0) * (g.max(2) - 1) as f64;+ let i = (at.floor() as usize).min(g.max(2) - 2);+ base.push(i);+ frac.push(at - i as f64);+ }+ let mut out = vec![0.0; self.outputs];+ for corner in 0..(1usize << n) {+ let (mut weight, mut index) = (1.0, 0usize);+ for k in 0..n {+ let up = (corner >> (n - 1 - k)) & 1;+ let f = frac.get(k).copied().unwrap_or(0.0);+ weight *= if up == 1 { f } else { 1.0 - f };+ let g = self.grid.get(k).copied().unwrap_or(1);+ index = index * g + base.get(k).copied().unwrap_or(0) + up;+ }+ if weight == 0.0 {+ continue;+ }+ for (o, v) in out.iter_mut().enumerate() {+ *v += weight * self.values.get(index * self.outputs + o).copied().unwrap_or(0.0);+ }+ }+ out+ }+}++/// One step of a table pipeline.+#[derive(Clone, Debug, PartialEq)]+enum Stage {+ Curves(Vec<Curve>),+ /// Three values times the matrix, plus the offset.+ Matrix([[f64; 3]; 3], [f64; 3]),+ Clut(Clut),+}++impl Stage {+ fn eval(&self, v: Vec<f64>) -> Vec<f64> {+ match self {+ Stage::Curves(curves) => {+ v.iter().enumerate().map(|(k, &x)| curves.get(k).map_or(x, |c| c.eval(x))).collect()+ }+ Stage::Matrix(m, offset) => {+ let x = [0, 1, 2].map(|k| v.get(k).copied().unwrap_or(0.0));+ m.map(|row| dot(row, x)).iter().zip(offset).map(|(y, o)| y + o).collect()+ }+ Stage::Clut(c) => c.eval(&v),+ }+ }+}++/// How a table pipeline's connection-space end is numbered (0..1 to actual XYZ or Lab).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum Encoding {+ /// XYZ as 0..1.99997 (1.0 at 0x8000).+ Xyz,+ /// Lab from 8-bit and version 4 tables: L 0..100, a and b −128..127.+ Lab,+ /// Lab from 16-bit version 2 tables: L 100 at 0xFF00, a and b 0 at 0x8000.+ LabLegacy,+}++impl Encoding {+ fn decode(self, v: &[f64]) -> [f64; 3] {+ let [x, y, z] = [0, 1, 2].map(|k| v.get(k).copied().unwrap_or(0.0));+ match self {+ Encoding::Xyz => [x, y, z].map(|c| c * 65535.0 / 32768.0),+ Encoding::Lab => [x * 100.0, y * 255.0 - 128.0, z * 255.0 - 128.0],+ Encoding::LabLegacy => {+ [x * 65535.0 / 65280.0 * 100.0, y * 65535.0 / 256.0 - 128.0, z * 65535.0 / 256.0 - 128.0]+ }+ }+ }++ fn encode(self, c: [f64; 3]) -> Vec<f64> {+ let [x, y, z] = c;+ let v = match self {+ Encoding::Xyz => [x, y, z].map(|c| c * 32768.0 / 65535.0),+ Encoding::Lab => [x / 100.0, (y + 128.0) / 255.0, (z + 128.0) / 255.0],+ Encoding::LabLegacy => {+ [x / 100.0 * 65280.0 / 65535.0, (y + 128.0) * 256.0 / 65535.0, (z + 128.0) * 256.0 / 65535.0]+ }+ };+ v.map(|c| c.clamp(0.0, 1.0)).to_vec()+ }+}++/// A way from device colours to the connection space, or back.+#[derive(Clone, Debug, PartialEq)]+enum Pipe {+ /// RGB: the tone curves, then the matrix to XYZ.+ Matrix([Curve; 3], [[f64; 3]; 3]),+ /// Grey: the tone curve gives Y (L* for a Lab profile).+ Gray(Curve),+ /// A table pipeline, its connection-space end numbered as `Encoding` says.+ Table(Vec<Stage>, Encoding),+}++/// An ICC profile as read: what its device colours are and how they reach the connection space.+#[derive(Clone, Debug)]+pub struct IccProfile {+ /// Its description, as lists show it.+ pub name: String,+ pub space: Space,+ pcs: Pcs,+ to_pcs: Pipe,+ from_pcs: Option<Pipe>,+ /// The file, to embed where the profile goes.+ pub bytes: Arc<Vec<u8>>,+}++impl PartialEq for IccProfile {+ fn eq(&self, other: &IccProfile) -> bool {+ self.bytes == other.bytes+ }+}++/// A built-in profile as an ICC profile, made once.+pub fn builtin(profile: crate::profile::Profile) -> Arc<IccProfile> {+ use crate::profile::Profile;+ static MADE: std::sync::OnceLock<Vec<(Profile, Arc<IccProfile>)>> = std::sync::OnceLock::new();+ let made = MADE.get_or_init(|| {+ Profile::ALL+ .iter()+ .filter_map(|&p| IccProfile::parse(&crate::icc::icc(p)).map(|icc| (p, Arc::new(icc))))+ .collect()+ });+ made.iter().find(|(p, _)| *p == profile).map(|(_, icc)| icc.clone()).unwrap_or_else(|| {+ // every built-in profile reads back (a test checks): never reached+ Arc::new(IccProfile {+ name: profile.name().to_owned(),+ space: Space::Rgb,+ pcs: Pcs::Xyz,+ to_pcs: Pipe::Matrix(+ [Curve::Identity, Curve::Identity, Curve::Identity],+ [[0.4361, 0.3851, 0.1431], [0.2225, 0.7169, 0.0606], [0.0139, 0.0971, 0.7141]],+ ),+ from_pcs: None,+ bytes: Arc::new(Vec::new()),+ })+ })+}++/// A canvas's own profile (one it was given, not a built-in one), kept with it as base64 text.+#[derive(Clone, Debug)]+pub struct CanvasIcc(pub Arc<IccProfile>);++impl PartialEq for CanvasIcc {+ fn eq(&self, other: &CanvasIcc) -> bool {+ self.0.bytes == other.0.bytes+ }+}++impl serde::Serialize for CanvasIcc {+ fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {+ s.serialize_str(&crate::base64::encode(&self.0.bytes))+ }+}++impl<'de> serde::Deserialize<'de> for CanvasIcc {+ fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<CanvasIcc, D::Error> {+ let text = String::deserialize(d)?;+ crate::base64::decode(&text)+ .and_then(|bytes| IccProfile::parse(&bytes))+ .map(|p| CanvasIcc(Arc::new(p)))+ .ok_or_else(|| serde::de::Error::custom("not a colour profile"))+ }+}++/// A canvas's own profile as kept, or none if it can't be read (the canvas falls back to its+/// built-in profile rather than failing to open).+pub fn lenient<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<CanvasIcc>, D::Error> {+ let text: Option<String> = serde::Deserialize::deserialize(d)?;+ Ok(text.and_then(|t| crate::base64::decode(&t)).and_then(|b| IccProfile::parse(&b)).map(|p| CanvasIcc(Arc::new(p))))+}++/// Big-endian reads from a profile's bytes; none past the end.+struct Bytes<'a>(&'a [u8]);++impl Bytes<'_> {+ fn u8(&self, at: usize) -> Option<u8> {+ self.0.get(at).copied()+ }+ fn u16(&self, at: usize) -> Option<u16> {+ Some(u16::from_be_bytes(self.0.get(at..at + 2)?.try_into().ok()?))+ }+ fn u32(&self, at: usize) -> Option<u32> {+ Some(u32::from_be_bytes(self.0.get(at..at + 4)?.try_into().ok()?))+ }+ fn s15(&self, at: usize) -> Option<f64> {+ Some(f64::from(i32::from_be_bytes(self.0.get(at..at + 4)?.try_into().ok()?)) / 65536.0)+ }+ fn sig(&self, at: usize) -> Option<[u8; 4]> {+ self.0.get(at..at + 4)?.try_into().ok()+ }+}++impl IccProfile {+ /// Reads a profile; none if it isn't one, or is a kind this can't use (only RGB, CMYK and grey+ /// profiles with a way to the connection space are).+ pub fn parse(bytes: &[u8]) -> Option<IccProfile> {+ let b = Bytes(bytes);+ if bytes.len() < 132 || &b.sig(36)? != b"acsp" {+ return None;+ }+ let space = match &b.sig(16)? {+ b"RGB " => Space::Rgb,+ b"CMYK" => Space::Cmyk,+ b"GRAY" => Space::Gray,+ _ => return None,+ };+ let pcs = match &b.sig(20)? {+ b"XYZ " => Pcs::Xyz,+ b"Lab " => Pcs::Lab,+ _ => return None,+ };+ let count = b.u32(128)? as usize;+ let mut tags = std::collections::HashMap::new();+ for i in 0..count.min(200) {+ let at = 132 + 12 * i;+ let (sig, offset, size) = (b.sig(at)?, b.u32(at + 4)? as usize, b.u32(at + 8)? as usize);+ if offset.checked_add(size).is_some_and(|end| end <= bytes.len()) {+ tags.insert(sig, (offset, size));+ }+ }+ let tag = |name: &[u8; 4]| tags.get(name).copied();+ let name = tag(b"desc").and_then(|(o, s)| text(&b, o, s)).unwrap_or_default();+ let table = |names: [&[u8; 4]; 3], inputs: usize, outputs: usize, to_pcs: bool| {+ names.iter().find_map(|n| tag(n).and_then(|(o, _)| read_table(&b, o, inputs, outputs, to_pcs, pcs)))+ };+ let n = space.channels();+ let to_pcs = match table([b"A2B0", b"A2B1", b"A2B2"], n, 3, true) {+ Some(p) => p,+ None => match space {+ Space::Rgb => {+ let curves = [b"rTRC", b"gTRC", b"bTRC"].map(|t| tag(t).and_then(|(o, _)| read_curve(&b, o)));+ let columns = [b"rXYZ", b"gXYZ", b"bXYZ"]+ .map(|t| tag(t).and_then(|(o, _)| Some([b.s15(o + 8)?, b.s15(o + 12)?, b.s15(o + 16)?])));+ let [Some(r), Some(g), Some(bl)] = curves else { return None };+ let [Some(cr), Some(cg), Some(cb)] = columns else { return None };+ Pipe::Matrix([r, g, bl], [[cr[0], cg[0], cb[0]], [cr[1], cg[1], cb[1]], [cr[2], cg[2], cb[2]]])+ }+ Space::Gray => Pipe::Gray(tag(b"kTRC").and_then(|(o, _)| read_curve(&b, o))?),+ Space::Cmyk => return None,+ },+ };+ let from_pcs = table([b"B2A0", b"B2A1", b"B2A2"], 3, n, false);+ Some(IccProfile { name, space, pcs, to_pcs, from_pcs, bytes: Arc::new(bytes.to_vec()) })+ }++ /// `device` (0..1 each) in the connection space, as D50 XYZ (white's Y 1).+ pub fn to_xyz(&self, device: &[f64]) -> [f64; 3] {+ let pcs = match &self.to_pcs {+ Pipe::Matrix(curves, m) => {+ let mut lin = [0.0; 3];+ for (k, (l, c)) in lin.iter_mut().zip(curves).enumerate() {+ *l = c.eval(device.get(k).copied().unwrap_or(0.0));+ }+ return m.map(|row| dot(row, lin));+ }+ Pipe::Gray(curve) => {+ let y = curve.eval(device.first().copied().unwrap_or(0.0));+ return match self.pcs {+ Pcs::Xyz => D50.map(|w| w * y),+ Pcs::Lab => lab_to_xyz([y * 100.0, 0.0, 0.0]),+ };+ }+ Pipe::Table(stages, encoding) => {+ let v = stages.iter().fold(device.to_vec(), |v, s| s.eval(v));+ encoding.decode(&v)+ }+ };+ match self.pcs {+ Pcs::Xyz => pcs,+ Pcs::Lab => lab_to_xyz(pcs),+ }+ }++ /// The device colour (0..1 each) for D50 `xyz`, clipped to what the device can show.+ pub fn from_xyz(&self, xyz: [f64; 3]) -> Vec<f64> {+ if let Some(Pipe::Table(stages, encoding)) = &self.from_pcs {+ let pcs = match self.pcs {+ Pcs::Xyz => xyz,+ Pcs::Lab => xyz_to_lab(xyz),+ };+ return stages+ .iter()+ .fold(encoding.encode(pcs), |v, s| s.eval(v))+ .iter()+ .map(|c| c.clamp(0.0, 1.0))+ .collect();+ }+ match &self.to_pcs {+ Pipe::Matrix(curves, m) => {+ let lin = invert(*m).map(|row| dot(row, xyz));+ lin.iter().zip(curves).map(|(&l, c)| c.inverse(l.clamp(0.0, 1.0))).collect()+ }+ Pipe::Gray(curve) => {+ let y = match self.pcs {+ Pcs::Xyz => xyz[1],+ Pcs::Lab => xyz_to_lab(xyz)[0] / 100.0,+ };+ vec![curve.inverse(y.clamp(0.0, 1.0))]+ }+ // a table one way and none back: the nearest device colour by searching+ Pipe::Table(..) => vec![0.0; self.space.channels()],+ }+ }++ /// Whether colours can be turned into this profile's (some input-only profiles can't).+ pub fn can_receive(&self) -> bool {+ self.from_pcs.is_some() || !matches!(self.to_pcs, Pipe::Table(..))+ }++ /// `device` in this profile, moved to `to`'s.+ pub fn convert(&self, device: &[f64], to: &IccProfile) -> Vec<f64> {+ to.from_xyz(self.to_xyz(device))+ }+}++/// The text of a `desc`, `mluc` or `text` tag (English if there is a choice).+fn text(b: &Bytes, at: usize, size: usize) -> Option<String> {+ match &b.sig(at)? {+ b"desc" => {+ let n = b.u32(at + 8)? as usize;+ let raw = b.0.get(at + 12..at + 12 + n.min(size))?;+ Some(String::from_utf8_lossy(raw).trim_end_matches('\0').trim().to_owned())+ }+ b"mluc" => {+ let records = b.u32(at + 8)? as usize;+ let pick = (0..records)+ .find(|&r| b.0.get(at + 16 + 12 * r..at + 18 + 12 * r) == Some(b"en".as_slice()))+ .unwrap_or(0);+ let rec = at + 16 + 12 * pick;+ let (len, off) = (b.u32(rec + 4)? as usize, b.u32(rec + 8)? as usize);+ let raw = b.0.get(at + off..at + off + len)?;+ let units: Vec<u16> = raw.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c)).collect();+ Some(String::from_utf16_lossy(&units).trim_end_matches('\0').trim().to_owned())+ }+ b"text" => {+ let raw = b.0.get(at + 8..at + size)?;+ Some(String::from_utf8_lossy(raw).trim_end_matches('\0').trim().to_owned())+ }+ _ => None,+ }+}++/// A `curv` or `para` curve at `at`, and the bytes it takes (to the next 4-byte boundary).+fn read_curve_sized(b: &Bytes, at: usize) -> Option<(Curve, usize)> {+ match &b.sig(at)? {+ b"curv" => {+ let n = b.u32(at + 8)? as usize;+ let curve = match n {+ 0 => Curve::Identity,+ 1 => Curve::Gamma(f64::from(b.u16(at + 12)?) / 256.0),+ _ => Curve::Table(+ (0..n.min(65536))+ .map(|i| Some(f64::from(b.u16(at + 12 + 2 * i)?) / 65535.0))+ .collect::<Option<_>>()?,+ ),+ };+ Some((curve, (12 + 2 * n).next_multiple_of(4)))+ }+ b"para" => {+ let kind = b.u16(at + 8)?;+ let count = match kind {+ 0 => 1,+ 1 => 3,+ 2 => 4,+ 3 => 5,+ 4 => 7,+ _ => return None,+ };+ let mut p = [0.0; 7];+ for (i, v) in p.iter_mut().enumerate().take(count) {+ *v = b.s15(at + 12 + 4 * i)?;+ }+ Some((Curve::Parametric(kind, p), 12 + 4 * count))+ }+ _ => None,+ }+}++fn read_curve(b: &Bytes, at: usize) -> Option<Curve> {+ read_curve_sized(b, at).map(|(c, _)| c)+}++/// `count` curves one after another from `at`.+fn read_curves(b: &Bytes, mut at: usize, count: usize) -> Option<Vec<Curve>> {+ let mut curves = Vec::with_capacity(count);+ for _ in 0..count {+ let (c, size) = read_curve_sized(b, at)?;+ curves.push(c);+ at += size;+ }+ Some(curves)+}++/// A table pipeline tag (`mft1`, `mft2`, `mAB `, `mBA `) at `at` with `inputs` and `outputs`+/// channels: towards the connection space if `to_pcs`.+fn read_table(b: &Bytes, at: usize, inputs: usize, outputs: usize, to_pcs: bool, pcs: Pcs) -> Option<Pipe> {+ let kind = b.sig(at)?;+ let (ins, outs) = (b.u8(at + 8)? as usize, b.u8(at + 9)? as usize);+ if ins != inputs || outs != outputs {+ return None;+ }+ match &kind {+ b"mft1" | b"mft2" => {+ let wide = &kind == b"mft2";+ let grid = b.u8(at + 10)? as usize;+ let m = [0, 1, 2].map(|r| [0, 1, 2].map(|c| b.s15(at + 12 + 4 * (3 * r + c)).unwrap_or(0.0)));+ let (in_entries, out_entries, mut p) =+ if wide { (b.u16(at + 48)? as usize, b.u16(at + 50)? as usize, at + 52) } else { (256, 256, at + 48) };+ let width = if wide { 2 } else { 1 };+ let value = |p: usize| -> Option<f64> {+ if wide { Some(f64::from(b.u16(p)?) / 65535.0) } else { Some(f64::from(b.u8(p)?) / 255.0) }+ };+ let tables = |count: usize, entries: usize, p: &mut usize| -> Option<Vec<Curve>> {+ let mut curves = Vec::with_capacity(count);+ for _ in 0..count {+ let t = (0..entries).map(|i| value(*p + width * i)).collect::<Option<Vec<_>>>()?;+ *p += width * entries;+ curves.push(Curve::Table(t));+ }+ Some(curves)+ };+ let input = tables(ins, in_entries, &mut p)?;+ let points = grid.checked_pow(ins as u32)?.checked_mul(outs)?;+ let values = (0..points).map(|i| value(p + width * i)).collect::<Option<Vec<_>>>()?;+ p += width * points;+ let output = tables(outs, out_entries, &mut p)?;+ let mut stages = Vec::new();+ // the matrix is used only on XYZ input+ if !to_pcs && pcs == Pcs::Xyz && m != [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] {+ stages.push(Stage::Matrix(m, [0.0; 3]));+ }+ stages.push(Stage::Curves(input));+ stages.push(Stage::Clut(Clut { grid: vec![grid; ins], outputs: outs, values }));+ stages.push(Stage::Curves(output));+ let encoding = match pcs {+ Pcs::Xyz => Encoding::Xyz,+ Pcs::Lab if wide => Encoding::LabLegacy,+ Pcs::Lab => Encoding::Lab,+ };+ Some(Pipe::Table(stages, encoding))+ }+ b"mAB " | b"mBA " => {+ let a_to_b = &kind == b"mAB ";+ let offset = |k: usize| b.u32(at + 12 + 4 * k).map(|o| o as usize);+ let (b_off, m_off, mid_off, clut_off, a_off) = (offset(0)?, offset(1)?, offset(2)?, offset(3)?, offset(4)?);+ // A curves face the device, B curves the connection space+ let (a_count, b_count) = if a_to_b { (ins, outs) } else { (outs, ins) };+ let b_curves = if b_off > 0 { Some(read_curves(b, at + b_off, b_count)?) } else { None };+ let a_curves = if a_off > 0 { Some(read_curves(b, at + a_off, a_count)?) } else { None };+ let m_curves = if mid_off > 0 { Some(read_curves(b, at + mid_off, 3)?) } else { None };+ let matrix = if m_off > 0 {+ let v = |k: usize| b.s15(at + m_off + 4 * k);+ Some(([[v(0)?, v(1)?, v(2)?], [v(3)?, v(4)?, v(5)?], [v(6)?, v(7)?, v(8)?]], [v(9)?, v(10)?, v(11)?]))+ } else {+ None+ };+ let clut = if clut_off > 0 {+ let c = at + clut_off;+ let grid: Vec<usize> = (0..ins.min(15)).map(|k| b.u8(c + k).map(usize::from)).collect::<Option<_>>()?;+ let precision = b.u8(c + 16)?;+ let points = grid.iter().try_fold(1usize, |acc, &g| acc.checked_mul(g))?.checked_mul(outs)?;+ let values = (0..points)+ .map(|i| match precision {+ 1 => b.u8(c + 20 + i).map(|v| f64::from(v) / 255.0),+ _ => b.u16(c + 20 + 2 * i).map(|v| f64::from(v) / 65535.0),+ })+ .collect::<Option<Vec<_>>>()?;+ Some(Clut { grid, outputs: outs, values })+ } else {+ None+ };+ let mut stages = Vec::new();+ let push_curves = |c: Option<Vec<Curve>>, stages: &mut Vec<Stage>| {+ if let Some(c) = c {+ stages.push(Stage::Curves(c));+ }+ };+ if a_to_b {+ push_curves(a_curves, &mut stages);+ if let Some(c) = clut {+ stages.push(Stage::Clut(c));+ }+ push_curves(m_curves, &mut stages);+ if let Some((m, o)) = matrix {+ stages.push(Stage::Matrix(m, o));+ }+ push_curves(b_curves, &mut stages);+ } else {+ push_curves(b_curves, &mut stages);+ if let Some((m, o)) = matrix {+ stages.push(Stage::Matrix(m, o));+ }+ push_curves(m_curves, &mut stages);+ if let Some(c) = clut {+ stages.push(Stage::Clut(c));+ }+ push_curves(a_curves, &mut stages);+ }+ let encoding = match pcs {+ Pcs::Xyz => Encoding::Xyz,+ Pcs::Lab => Encoding::Lab,+ };+ Some(Pipe::Table(stages, encoding))+ }+ _ => None,+ }+}++fn dot(row: [f64; 3], v: [f64; 3]) -> f64 {+ row[0] * v[0] + row[1] * v[1] + row[2] * v[2]+}++fn invert(m: [[f64; 3]; 3]) -> [[f64; 3]; 3] {+ let [[a, b, c], [d, e, f], [g, h, i]] = m;+ let det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);+ if det.abs() < 1e-12 {+ return [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];+ }+ [+ [(e * i - f * h) / det, (c * h - b * i) / det, (b * f - c * e) / det],+ [(f * g - d * i) / det, (a * i - c * g) / det, (c * d - a * f) / det],+ [(d * h - e * g) / det, (b * g - a * h) / det, (a * e - b * d) / det],+ ]+}++/// A space's white: full RGB or grey, or no ink.+fn white(space: Space) -> Vec<f32> {+ match space {+ Space::Rgb => vec![1.0; 3],+ Space::Gray => vec![1.0],+ Space::Cmyk => vec![0.0; 4],+ }+}++/// D50 XYZ to CIE Lab.+pub fn xyz_to_lab(xyz: [f64; 3]) -> [f64; 3] {+ let f =+ |t: f64| if t > (6.0f64 / 29.0).powi(3) { t.cbrt() } else { t / (3.0 * (6.0f64 / 29.0).powi(2)) + 4.0 / 29.0 };+ let [x, y, z] = xyz;+ let [fx, fy, fz] = [f(x / D50[0]), f(y / D50[1]), f(z / D50[2])];+ [116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)]+}++/// CIE Lab to D50 XYZ.+pub fn lab_to_xyz(lab: [f64; 3]) -> [f64; 3] {+ let fy = (lab[0] + 16.0) / 116.0;+ let [fx, fz] = [fy + lab[1] / 500.0, fy - lab[2] / 200.0];+ let inv = |t: f64| if t > 6.0 / 29.0 { t * t * t } else { 3.0 * (6.0f64 / 29.0).powi(2) * (t - 4.0 / 29.0) };+ [inv(fx) * D50[0], inv(fy) * D50[1], inv(fz) * D50[2]]+}++/// Colours of one RGB profile moved to another profile's, as a table over the RGB cube:+/// `grid` points along each channel, tetrahedral interpolation between them.+#[derive(Clone, Debug, PartialEq)]+pub struct Lut {+ pub grid: usize,+ /// How many values each point holds (the target's channels).+ pub outputs: usize,+ /// Red varying slowest, then green, then blue.+ pub values: Vec<f32>,+}++impl Lut {+ /// The table taking `from`'s RGB to `to`'s colours, through `via` on the way if given (the+ /// colours a press would print, as `to` shows them).+ pub fn build(from: &IccProfile, to: &IccProfile, via: Option<&IccProfile>, grid: usize) -> Lut {+ let grid = grid.clamp(2, 65);+ let outputs = to.space.channels();+ let mut values = Vec::with_capacity(grid * grid * grid * outputs);+ let step = 1.0 / (grid - 1) as f64;+ for r in 0..grid {+ for g in 0..grid {+ for b in 0..grid {+ // white stays white exactly (paper with no ink), whatever rounding the tables do+ if r == grid - 1 && g == grid - 1 && b == grid - 1 {+ values.extend(white(to.space));+ continue;+ }+ let rgb = [r as f64 * step, g as f64 * step, b as f64 * step];+ let mut xyz = from.to_xyz(&rgb);+ if let Some(press) = via {+ xyz = press.to_xyz(&press.from_xyz(xyz));+ }+ values.extend(to.from_xyz(xyz).iter().map(|&v| v as f32));+ }+ }+ }+ Lut { grid, outputs, values }+ }++ /// The colour for `rgb` (0..1 each).+ pub fn apply(&self, rgb: [f32; 3]) -> Vec<f32> {+ let n = self.grid.max(2);+ let scale = (n - 1) as f32;+ let pos = rgb.map(|c| c.clamp(0.0, 1.0) * scale);+ let base = pos.map(|p| (p.floor() as usize).min(n - 2));+ let [fr, fg, fb] = [pos[0] - base[0] as f32, pos[1] - base[1] as f32, pos[2] - base[2] as f32];+ let at = |dr: usize, dg: usize, db: usize, o: usize| -> f32 {+ let i = ((base[0] + dr) * n + base[1] + dg) * n + base[2] + db;+ self.values.get(i * self.outputs + o).copied().unwrap_or(0.0)+ };+ (0..self.outputs)+ .map(|o| {+ let c000 = at(0, 0, 0, o);+ let c111 = at(1, 1, 1, o);+ // the tetrahedron holding the point, by the order of its fractions+ if fr >= fg {+ if fg >= fb {+ let (c100, c110) = (at(1, 0, 0, o), at(1, 1, 0, o));+ c000 + fr * (c100 - c000) + fg * (c110 - c100) + fb * (c111 - c110)+ } else if fr >= fb {+ let (c100, c101) = (at(1, 0, 0, o), at(1, 0, 1, o));+ c000 + fr * (c100 - c000) + fb * (c101 - c100) + fg * (c111 - c101)+ } else {+ let (c001, c101) = (at(0, 0, 1, o), at(1, 0, 1, o));+ c000 + fb * (c001 - c000) + fr * (c101 - c001) + fg * (c111 - c101)+ }+ } else if fb >= fg {+ let (c001, c011) = (at(0, 0, 1, o), at(0, 1, 1, o));+ c000 + fb * (c001 - c000) + fg * (c011 - c001) + fr * (c111 - c011)+ } else if fb >= fr {+ let (c010, c011) = (at(0, 1, 0, o), at(0, 1, 1, o));+ c000 + fg * (c010 - c000) + fb * (c011 - c010) + fr * (c111 - c011)+ } else {+ let (c010, c110) = (at(0, 1, 0, o), at(1, 1, 0, o));+ c000 + fg * (c010 - c000) + fr * (c110 - c010) + fb * (c111 - c110)+ }+ })+ .collect()+ }++ /// 8-bit RGBA pixels (straight or premultiplied, as `premultiplied` says) moved through the+ /// table, alpha kept; a target with other than three channels leaves them unchanged.+ pub fn apply_rgba(&self, pixels: &mut [u8], premultiplied: bool) {+ if self.outputs != 3 {+ return;+ }+ for px in pixels.as_chunks_mut::<4>().0 {+ let a = f32::from(px[3]) / 255.0;+ if a == 0.0 {+ continue;+ }+ let un = |c: u8| if premultiplied { (f32::from(c) / 255.0 / a).min(1.0) } else { f32::from(c) / 255.0 };+ let out = self.apply([un(px[0]), un(px[1]), un(px[2])]);+ for (c, v) in px.iter_mut().zip(&out).take(3) {+ let v = if premultiplied { v * a } else { *v };+ *c = (v.clamp(0.0, 1.0) * 255.0).round() as u8;+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::profile::Profile;++ fn ours(p: Profile) -> IccProfile {+ IccProfile::parse(&crate::icc::icc(p)).unwrap()+ }++ #[test]+ fn our_own_profiles_read_back() {+ let srgb = ours(Profile::Srgb);+ assert_eq!(srgb.name, "sRGB IEC61966-2.1");+ assert_eq!(srgb.space, Space::Rgb);+ // white is the connection space's white, and comes back+ let white = srgb.to_xyz(&[1.0, 1.0, 1.0]);+ for (w, d) in white.iter().zip(D50) {+ assert!((w - d).abs() < 2e-3, "{white:?}");+ }+ for rgb in [[0.2, 0.5, 0.9], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.7, 0.7, 0.7]] {+ let back = srgb.from_xyz(srgb.to_xyz(&rgb));+ for (a, b) in rgb.iter().zip(&back) {+ assert!((a - b).abs() < 1e-3, "{rgb:?} {back:?}");+ }+ }+ }++ #[test]+ fn moving_between_profiles_matches_the_matrices() {+ let (srgb, p3) = (ours(Profile::Srgb), ours(Profile::DisplayP3));+ for rgb in [[0.0f32, 1.0, 0.0], [0.8, 0.3, 0.1], [0.5, 0.5, 0.5]] {+ let want = Profile::Srgb.convert(rgb, Profile::DisplayP3);+ let got = srgb.convert(&rgb.map(f64::from), &p3);+ for (w, g) in want.iter().zip(&got) {+ assert!((f64::from(*w) - g).abs() < 2e-3, "{rgb:?}: {want:?} {got:?}");+ }+ }+ }++ #[test]+ fn a_table_matches_the_profiles_it_was_made_from() {+ let (srgb, p3) = (ours(Profile::Srgb), ours(Profile::DisplayP3));+ let lut = Lut::build(&srgb, &p3, None, 33);+ for rgb in [[0.0f32, 1.0, 0.0], [0.13, 0.62, 0.91], [0.5, 0.25, 0.75]] {+ let want = srgb.convert(&rgb.map(f64::from), &p3);+ let got = lut.apply(rgb);+ for (w, g) in want.iter().zip(&got) {+ assert!((w - f64::from(*g)).abs() < 3e-3, "{rgb:?}: {want:?} {got:?}");+ }+ }+ let mut px = [0, 255, 0, 255, 10, 20, 30, 0];+ lut.apply_rgba(&mut px, false);+ assert_eq!(px[4..], [10, 20, 30, 0], "clear pixels stay as they are");+ assert!(px[0] > 50 && px[1] > 240 && px[2] > 50 && px[2] < 100, "{px:?}");+ }++ #[test]+ fn lab_goes_both_ways() {+ for lab in [[50.0, 20.0, -30.0], [90.0, -5.0, 80.0], [5.0, 0.0, 0.0]] {+ let back = xyz_to_lab(lab_to_xyz(lab));+ for (a, b) in lab.iter().zip(back) {+ assert!((a - b).abs() < 1e-9);+ }+ }+ }++ #[test]+ fn every_built_in_profile_reads_back() {+ for p in Profile::ALL {+ let icc = builtin(p);+ assert_eq!(icc.name, p.name());+ assert!(!icc.bytes.is_empty());+ }+ }++ #[test]+ fn a_canvas_profile_keeps_as_text() {+ #[derive(serde::Serialize, serde::Deserialize)]+ struct Kept {+ #[serde(default, deserialize_with = "lenient")]+ icc: Option<CanvasIcc>,+ }+ let icc = CanvasIcc(builtin(Profile::DisplayP3));+ let text = serde_json::to_string(&Kept { icc: Some(icc.clone()) }).unwrap();+ assert_eq!(serde_json::from_str::<Kept>(&text).unwrap().icc, Some(icc));+ assert_eq!(serde_json::from_str::<Kept>(r#"{"icc":"bm90IGEgcHJvZmlsZQ=="}"#).unwrap().icc, None);+ assert_eq!(serde_json::from_str::<Kept>("{}").unwrap().icc, None);+ }++ #[test]+ fn other_files_are_not_profiles() {+ assert!(IccProfile::parse(b"not a profile").is_none());+ assert!(IccProfile::parse(&[0; 200]).is_none());+ let mut lab = crate::icc::icc(Profile::Srgb);+ lab[16..20].copy_from_slice(b"Lab ");+ assert!(IccProfile::parse(&lab).is_none(), "a Lab device space isn't one we use");+ }++ /// Prints how the profile in `PROCRAFT_ICC` turns a few Display P3 colours, for comparing with+ /// other colour programs: `cargo test -p procraft-engine cms -- --ignored --nocapture`.+ #[test]+ #[ignore]+ fn print_conversions() {+ let Ok(path) = std::env::var("PROCRAFT_ICC") else { return };+ let target = IccProfile::parse(&std::fs::read(path).unwrap()).unwrap();+ let p3 = ours(Profile::DisplayP3);+ println!("{} {:?}", target.name, target.space);+ for rgb in [[0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [0.2, 0.4, 0.8]] {+ let device = p3.convert(&rgb, &target);+ let back = target.convert(&device, &p3);+ let bytes = |v: &[f64]| v.iter().map(|c| (c * 255.0).round() as u8).collect::<Vec<_>>();+ println!("{rgb:?} -> {:?} -> {:?}", bytes(&device), bytes(&back));+ }+ }+}diff --git a/crates/engine/src/cmyk.rs b/crates/engine/src/cmyk.rsnew file mode 100644index 0000000..38bafcf--- /dev/null+++ b/crates/engine/src/cmyk.rs@@ -0,0 +1,449 @@+//! ProCraft's own CMYK profile, made here: a press printing on coated paper, modelled from the+//! colours of its inks and their overprints, written as an ICC version 2 output profile with+//! 16-bit tables (the same tables for every rendering intent).+//!+//! The model mixes the sixteen overprints of cyan, magenta, yellow and black by the area each+//! covers (inks spread as they print: a 50% dot prints as 65%), the light reaching the eye+//! scattered in the paper. Separations put black in as grey builds up, cap the four inks at 300%+//! between them, and bring colours the press can't print to the nearest it can at their+//! lightness. The tables run from the paper's white to the press's deepest black.++use std::sync::OnceLock;++use crate::cms::{D50, lab_to_xyz, xyz_to_lab};++/// The profile's name, as lists show it.+pub const NAME: &str = "Generic CMYK";++/// The paper and the inks alone and over each other (cyan, magenta, yellow), as CIE Lab (D50).+const PAPER: [f64; 3] = [95.0, 0.0, -2.0];+const OVERPRINTS: [[f64; 3]; 8] = [+ PAPER,+ [89.0, -5.0, 93.0], // yellow+ [48.0, 74.0, -3.0], // magenta+ [47.0, 68.0, 48.0], // magenta and yellow+ [55.0, -37.0, -50.0], // cyan+ [50.0, -65.0, 27.0], // cyan and yellow+ [24.0, 22.0, -46.0], // cyan and magenta+ [23.0, 0.0, 0.0], // all three+];+/// Black ink alone.+const BLACK: [f64; 3] = [16.0, 0.0, 0.0];+/// Light the surface gives back whatever the ink: a share of the paper's.+const FLARE: f64 = 0.008;+/// How far light scatters in the paper (the Yule–Nielsen factor).+const SCATTER: f64 = 1.6;+/// How much a 50% dot grows when printed.+const DOT_GAIN: f64 = 0.15;+/// The most ink the four colours may put down together.+const INK_LIMIT: f64 = 3.0;++/// The press: each overprint's colour (with and without black) ready to mix.+struct Press {+ /// For the 16 overprints (black slowest, then cyan, magenta, yellow): XYZ less the flare,+ /// to the power 1 / SCATTER.+ primaries: [[f64; 3]; 16],+ flare: [f64; 3],+ paper: [f64; 3],+ /// The deepest black it prints, relative to the paper.+ black: [f64; 3],+}++impl Press {+ fn new() -> Press {+ let paper = lab_to_xyz(PAPER);+ let flare = paper.map(|w| w * FLARE);+ let less = |c: [f64; 3]| zip3(lab_to_xyz(c), flare, |x, f| (x - f).max(1e-6));+ let (white, black) = (less(PAPER), less(BLACK));+ let mut primaries = [[0.0; 3]; 16];+ for (i, p) in primaries.iter_mut().enumerate() {+ let base = less(OVERPRINTS.get(i % 8).copied().unwrap_or(PAPER));+ // black over the rest lets through what black alone lets through of the paper+ let x = if i >= 8 { zip3(zip3(base, black, |a, b| a * b), white, |a, w| a / w) } else { base };+ *p = x.map(|v| v.powf(1.0 / SCATTER));+ }+ let mut press = Press { primaries, flare, paper, black: [0.0; 3] };+ press.black = press.relative(press.print(press.separate_black()));+ press+ }++ /// The colour (absolute D50 XYZ) of inks `cmyk` (0..1 each) on the paper.+ fn print(&self, cmyk: [f64; 4]) -> [f64; 3] {+ let [c, m, y, k] = cmyk.map(|v| {+ let v = v.clamp(0.0, 1.0);+ v + 4.0 * DOT_GAIN * v * (1.0 - v)+ });+ let mut sum = [0.0; 3];+ for (i, p) in self.primaries.iter().enumerate() {+ let on = |bit: usize, v: f64| if i & bit != 0 { v } else { 1.0 - v };+ let w = on(8, k) * on(4, c) * on(2, m) * on(1, y);+ if w > 0.0 {+ for (s, v) in sum.iter_mut().zip(p) {+ *s += w * v;+ }+ }+ }+ zip3(sum, self.flare, |s, f| s.powf(SCATTER) + f)+ }++ /// `xyz` relative to the paper: the paper as the connection space's white.+ fn relative(&self, xyz: [f64; 3]) -> [f64; 3] {+ zip3(zip3(xyz, self.paper, |x, p| x / p), D50, |x, w| x * w)+ }++ /// The connection-space colour of `cmyk`: relative to the paper, the press's black at 0.+ fn to_lab(&self, cmyk: [f64; 4]) -> [f64; 3] {+ let above = zip3(self.relative(self.print(cmyk)), self.black, |x, b| x - b);+ let range = zip3(D50, self.black, |w, b| w - b);+ xyz_to_lab(zip3(zip3(above, range, |a, r| a / r), D50, |v, w| (v * w).max(0.0)))+ }++ /// The deepest neutral it prints: black ink, then as much of the others as the limit lets.+ fn separate_black(&self) -> [f64; 4] {+ let k = 0.87;+ let mut best = [0.0, 0.0, 0.0, k];+ let mut darkest = f64::MAX;+ // the balance of the three inks that gives the least light, over a coarse grid+ for c in 50..=100 {+ for m in 50..=100 {+ let (c, m) = (f64::from(c) / 100.0, f64::from(m) / 100.0);+ let y = (INK_LIMIT - k - c - m).clamp(0.0, 1.0);+ let xyz = self.print([c, m, y, k]);+ let lab = xyz_to_lab(self.relative(xyz));+ let score = lab[0] + 0.3 * (lab[1].abs() + lab[2].abs());+ if score < darkest {+ darkest = score;+ best = [c, m, y, k];+ }+ }+ }+ best+ }++ /// The inks for connection-space colour `lab`: black by how grey the colour is, the others+ /// solved for; a colour out of reach comes as near as the press gets at its lightness.+ fn separate(&self, lab: [f64; 3], start: [f64; 4]) -> [f64; 4] {+ let cmy = self.solve(lab, 0.0, [start[0], start[1], start[2]]);+ // grey component replacement: black for the part all three share, from a quarter on+ let grey = cmy.iter().copied().fold(1.0, f64::min);+ let k = (((grey - 0.25) / 0.75).clamp(0.0, 1.0)).powf(1.2) * 0.87;+ if k <= 0.0 {+ return [cmy[0], cmy[1], cmy[2], 0.0];+ }+ let cmy = self.solve(lab, k, cmy);+ [cmy[0], cmy[1], cmy[2], k]+ }++ /// Cyan, magenta and yellow that print `lab` with black `k`, from `start`: the least weighted+ /// difference (lightness counted twice), within the ink limit.+ fn solve(&self, lab: [f64; 3], k: f64, start: [f64; 3]) -> [f64; 3] {+ let error = |cmy: [f64; 3]| {+ let got = self.to_lab([cmy[0], cmy[1], cmy[2], k]);+ [2.0 * (got[0] - lab[0]), got[1] - lab[1], got[2] - lab[2]]+ };+ let fit = |cmy: [f64; 3]| {+ let mut v = cmy.map(|c| c.clamp(0.0, 1.0));+ let total: f64 = v.iter().sum();+ if total + k > INK_LIMIT {+ let scale = (INK_LIMIT - k).max(0.0) / total;+ v = v.map(|c| c * scale);+ }+ v+ };+ let mut cmy = fit(start);+ let mut lambda = 1e-3;+ let mut e = error(cmy);+ let mut cost = dot(e, e);+ for _ in 0..30 {+ if cost < 1e-6 {+ break;+ }+ // the Jacobian, a column for each ink, by small steps (backwards at full ink)+ let column = |which: usize| {+ let h = if pick(cmy, which) + 1e-4 > 1.0 { -1e-4 } else { 1e-4 };+ zip3(error(nudge(cmy, which, h)), e, |a, b| (a - b) / h)+ };+ let [d0, d1, d2] = [column(0), column(1), column(2)];+ // (JᵀJ + λ) step = −Jᵀ e+ let damp = |v: f64| v + lambda * (1.0 + v);+ let a = [+ [damp(dot(d0, d0)), dot(d0, d1), dot(d0, d2)],+ [dot(d1, d0), damp(dot(d1, d1)), dot(d1, d2)],+ [dot(d2, d0), dot(d2, d1), damp(dot(d2, d2))],+ ];+ let g = [-dot(d0, e), -dot(d1, e), -dot(d2, e)];+ let Some(step) = solve3(a, g) else { break };+ let next = fit(zip3(cmy, step, |c, s| c + s));+ let e2 = error(next);+ let cost2 = dot(e2, e2);+ if cost2 < cost {+ (cmy, e, cost) = (next, e2, cost2);+ lambda = (lambda / 3.0).max(1e-7);+ } else {+ lambda *= 4.0;+ if lambda > 1e6 {+ break;+ }+ }+ }+ cmy+ }+}++/// `a` x = `b` for three unknowns; none if `a` can't be inverted.+fn solve3(a: [[f64; 3]; 3], b: [f64; 3]) -> Option<[f64; 3]> {+ let det = |m: [[f64; 3]; 3]| {+ m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])+ + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])+ };+ let d = det(a);+ if d.abs() < 1e-18 {+ return None;+ }+ // Cramer's rule+ let replaced = |k: usize| {+ let [r0, r1, r2] = a;+ [nudge(r0, k, b[0] - pick(r0, k)), nudge(r1, k, b[1] - pick(r1, k)), nudge(r2, k, b[2] - pick(r2, k))]+ };+ Some([det(replaced(0)) / d, det(replaced(1)) / d, det(replaced(2)) / d])+}++/// The three values of `a` and `b` paired through `f`.+fn zip3(a: [f64; 3], b: [f64; 3], f: impl Fn(f64, f64) -> f64) -> [f64; 3] {+ [f(a[0], b[0]), f(a[1], b[1]), f(a[2], b[2])]+}++fn dot(a: [f64; 3], b: [f64; 3]) -> f64 {+ a[0] * b[0] + a[1] * b[1] + a[2] * b[2]+}++/// `v` with `by` added to value `which` (0 to 2).+fn nudge(v: [f64; 3], which: usize, by: f64) -> [f64; 3] {+ match which {+ 0 => [v[0] + by, v[1], v[2]],+ 1 => [v[0], v[1] + by, v[2]],+ _ => [v[0], v[1], v[2] + by],+ }+}++/// Value `which` (0 to 2) of `v`.+fn pick(v: [f64; 3], which: usize) -> f64 {+ match which {+ 0 => v[0],+ 1 => v[1],+ _ => v[2],+ }+}++/// The profile's file, made once.+pub fn profile() -> Vec<u8> {+ static MADE: OnceLock<Vec<u8>> = OnceLock::new();+ MADE.get_or_init(make).clone()+}++/// Grid points along each input of the tables.+const TO_LAB_GRID: usize = 9;+const TO_INK_GRID: usize = 17;++fn make() -> Vec<u8> {+ let press = Press::new();+ // ink to the connection space+ let n = TO_LAB_GRID;+ let mut to_lab = Vec::with_capacity(n.pow(4) * 3);+ for c in 0..n {+ for m in 0..n {+ for y in 0..n {+ for k in 0..n {+ let v = [c, m, y, k].map(|i| i as f64 / (n - 1) as f64);+ to_lab.extend(legacy_lab(press.to_lab(v)));+ }+ }+ }+ }+ // the connection space to ink, each point starting from the one before+ let n = TO_INK_GRID;+ let mut to_ink = Vec::with_capacity(n.pow(3) * 4);+ let mut start = [0.0; 4];+ for l in 0..n {+ for a in 0..n {+ for b in 0..n {+ let v = [l, a, b].map(|i| i as f64 / (n - 1) as f64);+ let lab =+ [v[0] * 65535.0 / 65280.0 * 100.0, v[1] * 65535.0 / 256.0 - 128.0, v[2] * 65535.0 / 256.0 - 128.0];+ let ink = if lab[0] >= 100.0 && lab[1].abs() < 1.0 && lab[2].abs() < 1.0 {+ [0.0; 4]+ } else {+ press.separate(lab, start)+ };+ start = ink;+ to_ink.extend(ink.map(|v| (v.clamp(0.0, 1.0) * 65535.0).round() as u16));+ }+ }+ }+ let a2b = mft2(4, 3, TO_LAB_GRID, &to_lab);+ let b2a = mft2(3, 4, TO_INK_GRID, &to_ink);+ let paper = lab_to_xyz(PAPER);+ let tags: Vec<(&[u8; 4], usize)> = vec![+ (b"desc", 0),+ (b"cprt", 1),+ (b"wtpt", 2),+ (b"A2B0", 3),+ (b"A2B1", 3),+ (b"A2B2", 3),+ (b"B2A0", 4),+ (b"B2A1", 4),+ (b"B2A2", 4),+ ];+ let data = [desc_tag(NAME), text_tag("No copyright, use freely"), xyz_tag(paper), a2b, b2a];+ write(&tags, &data)+}++/// Lab in the 16-bit version 2 numbering (L 100 at 0xFF00, a and b 0 at 0x8000).+fn legacy_lab(lab: [f64; 3]) -> [u16; 3] {+ [lab[0] / 100.0 * 65280.0, (lab[1] + 128.0) * 256.0, (lab[2] + 128.0) * 256.0]+ .map(|v| v.round().clamp(0.0, 65535.0) as u16)+}++/// A 16-bit table pipeline: straight curves either side of the grid of `values`.+fn mft2(inputs: u8, outputs: u8, grid: usize, values: &[u16]) -> Vec<u8> {+ let mut t = b"mft2\0\0\0\0".to_vec();+ t.extend([inputs, outputs, grid as u8, 0]);+ for v in [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0] {+ t.extend(fixed(v));+ }+ t.extend(2u16.to_be_bytes());+ t.extend(2u16.to_be_bytes());+ for _ in 0..inputs {+ t.extend([0u16, 65535].iter().flat_map(|v| v.to_be_bytes()));+ }+ t.extend(values.iter().flat_map(|v| v.to_be_bytes()));+ for _ in 0..outputs {+ t.extend([0u16, 65535].iter().flat_map(|v| v.to_be_bytes()));+ }+ t+}++fn fixed(v: f64) -> [u8; 4] {+ ((v * 65536.0).round() as i32).to_be_bytes()+}++fn xyz_tag(v: [f64; 3]) -> Vec<u8> {+ let mut t = b"XYZ \0\0\0\0".to_vec();+ for c in v {+ t.extend(fixed(c));+ }+ t+}++/// A version 2 text description: the ASCII text, then empty Unicode and ScriptCode parts.+fn desc_tag(s: &str) -> Vec<u8> {+ let mut t = b"desc\0\0\0\0".to_vec();+ t.extend((s.len() as u32 + 1).to_be_bytes());+ t.extend(s.bytes());+ t.push(0);+ t.extend([0u8; 8]);+ t.extend([0u8; 3]);+ t.extend([0u8; 67]);+ t+}++fn text_tag(s: &str) -> Vec<u8> {+ let mut t = b"text\0\0\0\0".to_vec();+ t.extend(s.bytes());+ t.push(0);+ t+}++/// The file: the header, the tag table, then each piece of `data` once on a 4-byte boundary+/// (tags naming the same piece share it).+fn write(tags: &[(&[u8; 4], usize)], data: &[Vec<u8>]) -> Vec<u8> {+ let table_end = 128 + 4 + 12 * tags.len();+ let mut offsets = Vec::with_capacity(data.len());+ let mut body = Vec::new();+ for d in data {+ offsets.push(table_end + body.len());+ body.extend(d);+ while body.len() % 4 != 0 {+ body.push(0);+ }+ }+ let size = table_end + body.len();+ let mut out = Vec::with_capacity(size);+ out.extend((size as u32).to_be_bytes());+ out.extend([0u8; 4]);+ out.extend([2, 0x10, 0, 0]);+ out.extend(b"prtrCMYKLab ");+ // made 2026-01-01+ for v in [2026u16, 1, 1, 0, 0, 0] {+ out.extend(v.to_be_bytes());+ }+ out.extend(b"acsp");+ out.extend([0u8; 24]);+ out.extend(0u32.to_be_bytes());+ for c in D50 {+ out.extend(fixed(c));+ }+ out.extend([0u8; 48]);+ out.extend((tags.len() as u32).to_be_bytes());+ for (sig, piece) in tags {+ let (offset, len) = (offsets.get(*piece).copied().unwrap_or(0), data.get(*piece).map_or(0, Vec::len));+ out.extend(*sig);+ out.extend((offset as u32).to_be_bytes());+ out.extend((len as u32).to_be_bytes());+ }+ out.extend(body);+ out+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::cms::{IccProfile, Space};+ use crate::profile::Profile;++ /// Writes the profile to the file in `PROCRAFT_CMYK`, for trying in other colour programs:+ /// `cargo test -p procraft-engine write_cmyk -- --ignored`.+ #[test]+ #[ignore]+ fn write_cmyk() {+ let Ok(path) = std::env::var("PROCRAFT_CMYK") else { return };+ std::fs::write(path, profile()).unwrap();+ }++ #[test]+ fn the_profile_reads_back() {+ let p = IccProfile::parse(&profile()).unwrap();+ assert_eq!(p.name, NAME);+ assert_eq!(p.space, Space::Cmyk);+ assert!(p.can_receive());+ // no ink is the paper: the connection space's white+ let lab = xyz_to_lab(p.to_xyz(&[0.0; 4]));+ assert!((lab[0] - 100.0).abs() < 0.5 && lab[1].abs() < 0.5 && lab[2].abs() < 0.5, "{lab:?}");+ let ink = p.from_xyz(D50);+ assert!(ink.iter().all(|&v| v < 0.01), "white takes no ink: {ink:?}");+ }++ #[test]+ fn colours_separate_as_a_press_would() {+ let p = IccProfile::parse(&profile()).unwrap();+ let p3 = IccProfile::parse(&crate::icc::icc(Profile::DisplayP3)).unwrap();+ let ink = |rgb: [f64; 3]| p3.convert(&rgb, &p);+ // black: a rich black within the ink limit+ let black = ink([0.0, 0.0, 0.0]);+ let total: f64 = black.iter().sum();+ assert!(black[3] > 0.7 && total > 2.5 && total <= 3.05, "{black:?}");+ // a saturated green takes cyan and yellow, no magenta or black+ let green = ink([0.0, 1.0, 0.0]);+ assert!(green[0] > 0.3 && green[2] > 0.5 && green[1] < 0.05 && green[3] < 0.05, "{green:?}");+ // mid grey takes some black+ let grey = ink([0.5, 0.5, 0.5]);+ assert!(grey[3] > 0.05 && grey[3] < 0.6, "{grey:?}");+ // printed colours come back near where they went in, inside the press's range+ for rgb in [[0.6, 0.5, 0.4], [0.3, 0.4, 0.5], [0.8, 0.8, 0.8]] {+ let back = p.convert(&ink(rgb), &p3);+ for (a, b) in rgb.iter().zip(&back) {+ assert!((a - b).abs() < 0.04, "{rgb:?} {back:?}");+ }+ }+ }+}diff --git a/crates/engine/src/crop.rs b/crates/engine/src/crop.rsnew file mode 100644index 0000000..e59d60f--- /dev/null+++ b/crates/engine/src/crop.rs@@ -0,0 +1,135 @@+//! Cropping and resizing the canvas: where the new canvas's pixels come from on the old one, and+//! the pixels resampled.++use crate::document::MAX_CANVAS_EDGE;+use crate::geom::{Affine, Vec2};++/// A new canvas: its size, and the map from its pixels to the old canvas's.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Crop {+ pub width: u32,+ pub height: u32,+ pub to_old: Affine,+}++/// Keeping the rectangle `rect` (x, y, width, height on the old canvas; it may reach past the+/// edges), turned by `angle` radians about its centre. `size` resamples what is kept to that many+/// pixels; otherwise it keeps a pixel for each of the old canvas's.+pub fn crop(rect: [f32; 4], angle: f32, size: Option<(u32, u32)>) -> Crop {+ let finite = |v: f32, or: f32| if v.is_finite() { v } else { or };+ let [x, y] = [finite(rect[0], 0.0), finite(rect[1], 0.0)];+ let max = MAX_CANVAS_EDGE as f32;+ let (w, h) = (finite(rect[2], 1.0).clamp(1.0, max), finite(rect[3], 1.0).clamp(1.0, max));+ let (width, height) = size.unwrap_or((w.round() as u32, h.round() as u32));+ let (width, height) = (width.clamp(1, MAX_CANVAS_EDGE), height.clamp(1, MAX_CANVAS_EDGE));+ let (fw, fh) = (width as f32, height as f32);+ // a new pixel, about the new canvas's middle, scaled to the rectangle, turned, and placed+ let to_old = Affine::translate(Vec2::new(-fw / 2.0, -fh / 2.0))+ .then(Affine { a: w / fw, d: h / fh, ..Affine::IDENTITY })+ .then(Affine::rotate(finite(angle, 0.0)))+ .then(Affine::translate(Vec2::new(x + w / 2.0, y + h / 2.0)));+ Crop { width, height, to_old }+}++/// `src` (premultiplied RGBA8, `sw` × `sh`) seen through `crop`: bilinear, transparent past its+/// edges. A move by whole pixels copies them as they are.+pub fn resample(src: &[u8], sw: u32, sh: u32, crop: &Crop) -> Vec<u8> {+ let (w, h) = (crop.width as usize, crop.height as usize);+ let mut out = vec![0u8; w * h * 4];+ let m = crop.to_old;+ let whole = |v: f32| (v - v.round()).abs() < 1e-4;+ if m.a == 1.0 && m.b == 0.0 && m.c == 0.0 && m.d == 1.0 && whole(m.e) && whole(m.f) {+ let (dx, dy) = (m.e.round() as i64, m.f.round() as i64);+ for y in 0..h {+ let sy = y as i64 + dy;+ if sy < 0 || sy >= i64::from(sh) {+ continue;+ }+ // the part of the row that lands on the old canvas+ let x0 = (-dx).clamp(0, w as i64) as usize;+ let x1 = (i64::from(sw) - dx).clamp(0, w as i64) as usize;+ if x1 <= x0 {+ continue;+ }+ let from = ((sy as usize) * sw as usize + (x0 as i64 + dx) as usize) * 4;+ let to = (y * w + x0) * 4;+ let n = (x1 - x0) * 4;+ if let (Some(dst), Some(s)) = (out.get_mut(to..to + n), src.get(from..from + n)) {+ dst.copy_from_slice(s);+ }+ }+ return out;+ }+ let pixel = |x: i64, y: i64| -> [f32; 4] {+ if x < 0 || y < 0 || x >= i64::from(sw) || y >= i64::from(sh) {+ return [0.0; 4];+ }+ let i = ((y as usize) * sw as usize + x as usize) * 4;+ src.get(i..i + 4).and_then(|p| <[u8; 4]>::try_from(p).ok()).map_or([0.0; 4], |p| p.map(f32::from))+ };+ for y in 0..h {+ for x in 0..w {+ let p = m.apply(Vec2::new(x as f32 + 0.5, y as f32 + 0.5));+ let (fx, fy) = (p.x - 0.5, p.y - 0.5);+ let (x0, y0) = (fx.floor(), fy.floor());+ let (tx, ty) = (fx - x0, fy - y0);+ let (ix, iy) = (x0 as i64, y0 as i64);+ let (a, b, c, d) = (pixel(ix, iy), pixel(ix + 1, iy), pixel(ix, iy + 1), pixel(ix + 1, iy + 1));+ let i = (y * w + x) * 4;+ if let Some(dst) = out.get_mut(i..i + 4) {+ for (k, v) in dst.iter_mut().enumerate() {+ let at = |p: [f32; 4]| p.get(k).copied().unwrap_or(0.0);+ let top = at(a) + (at(b) - at(a)) * tx;+ let bottom = at(c) + (at(d) - at(c)) * tx;+ *v = (top + (bottom - top) * ty).round().clamp(0.0, 255.0) as u8;+ }+ }+ }+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ fn picture(w: u32, h: u32) -> Vec<u8> {+ (0..w * h).flat_map(|i| [(i % w) as u8 * 10, (i / w) as u8 * 10, 0, 255]).collect()+ }++ #[test]+ fn a_crop_keeps_the_rectangle() {+ let src = picture(8, 6);+ let c = crop([2.0, 1.0, 4.0, 3.0], 0.0, None);+ assert_eq!((c.width, c.height), (4, 3));+ let out = resample(&src, 8, 6, &c);+ // the new top left is the old (2, 1)+ assert_eq!(&out[..4], &[20, 10, 0, 255]);+ assert_eq!(&out[(2 * 4 + 3) * 4..(2 * 4 + 3) * 4 + 4], &[50, 30, 0, 255]);+ }++ #[test]+ fn past_the_edges_is_transparent_and_resampling_scales() {+ let src = picture(4, 4);+ let c = crop([-2.0, 0.0, 6.0, 4.0], 0.0, None);+ let out = resample(&src, 4, 4, &c);+ assert_eq!(c.width, 6);+ assert_eq!(&out[..4], &[0, 0, 0, 0]);+ assert_eq!(&out[2 * 4..2 * 4 + 4], &[0, 0, 0, 255]);+ // the whole of it at twice the size: a flat colour stays flat+ let flat = [9u8, 9, 9, 255].repeat(16);+ let c = crop([0.0, 0.0, 4.0, 4.0], 0.0, Some((8, 8)));+ let out = resample(&flat, 4, 4, &c);+ assert_eq!(out.len(), 8 * 8 * 4);+ assert_eq!(&out[(3 * 8 + 3) * 4..(3 * 8 + 3) * 4 + 4], &[9, 9, 9, 255]);+ }++ #[test]+ fn a_half_turn_reverses_the_picture() {+ let src = picture(4, 2);+ let c = crop([0.0, 0.0, 4.0, 2.0], std::f32::consts::PI, None);+ let out = resample(&src, 4, 2, &c);+ // the new top left is the old bottom right+ assert_eq!(&out[..4], &[30, 10, 0, 255]);+ }+}diff --git a/crates/engine/src/curve.rs b/crates/engine/src/curve.rsnew file mode 100644index 0000000..b865b36--- /dev/null+++ b/crates/engine/src/curve.rs@@ -0,0 +1,156 @@+//! Response curves (pressure, tilt...): a smooth curve through control points on the unit square.++use crate::geom::Vec2;++/// A curve `[0, 1] → [0, 1]` through control points: monotone cubic Hermite interpolation, so it+/// passes through every point and never overshoots between monotone points.+#[derive(Clone, Debug, PartialEq)]+pub struct Curve {+ points: Vec<Vec2>,+ tangents: Vec<f32>,+}++impl Default for Curve {+ fn default() -> Curve {+ Curve::linear()+ }+}++impl Curve {+ pub fn linear() -> Curve {+ Curve::new(&[Vec2::new(0.0, 0.0), Vec2::new(1.0, 1.0)])+ }++ /// Points are clamped to the unit square and sorted by x; of points sharing an x the first+ /// wins. Fewer than two usable points give the identity curve.+ pub fn new(points: &[Vec2]) -> Curve {+ let mut pts: Vec<Vec2> = points+ .iter()+ .filter(|p| p.is_finite())+ .map(|p| Vec2::new(p.x.clamp(0.0, 1.0), p.y.clamp(0.0, 1.0)))+ .collect();+ pts.sort_by(|a, b| a.x.total_cmp(&b.x));+ pts.dedup_by(|later, earlier| (later.x - earlier.x).abs() < 1e-6);+ if pts.len() < 2 {+ pts = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 1.0)];+ }+ let tangents = monotone_tangents(&pts);+ Curve { points: pts, tangents }+ }++ pub fn points(&self) -> &[Vec2] {+ &self.points+ }++ pub fn eval(&self, x: f32) -> f32 {+ let x = if x.is_finite() { x } else { 0.0 };+ let (Some(first), Some(last)) = (self.points.first(), self.points.last()) else { return x };+ if x <= first.x {+ return first.y;+ }+ if x >= last.x {+ return last.y;+ }+ // the segment [i, i + 1] holding x+ let i = self.points.partition_point(|p| p.x <= x).saturating_sub(1);+ let (Some(p0), Some(p1), Some(m0), Some(m1)) =+ (self.points.get(i), self.points.get(i + 1), self.tangents.get(i), self.tangents.get(i + 1))+ else {+ return x;+ };+ let h = p1.x - p0.x;+ if h <= 0.0 {+ return p0.y;+ }+ let t = (x - p0.x) / h;+ let (t2, t3) = (t * t, t * t * t);+ let y = (2.0 * t3 - 3.0 * t2 + 1.0) * p0.y+ + (t3 - 2.0 * t2 + t) * h * m0+ + (-2.0 * t3 + 3.0 * t2) * p1.y+ + (t3 - t2) * h * m1;+ y.clamp(0.0, 1.0)+ }+}++/// Fritsch–Carlson tangents for points sorted by strictly increasing x.+fn monotone_tangents(pts: &[Vec2]) -> Vec<f32> {+ let secants: Vec<f32> = pts+ .windows(2)+ .map(|w| match w {+ [p0, p1] => (p1.y - p0.y) / (p1.x - p0.x),+ _ => 0.0,+ })+ .collect();+ let n = pts.len();+ let mut m = vec![0.0f32; n];+ for (i, slot) in m.iter_mut().enumerate() {+ let before = i.checked_sub(1).and_then(|j| secants.get(j)).copied();+ let after = secants.get(i).copied();+ *slot = match (before, after) {+ (Some(a), Some(b)) if a * b > 0.0 => (a + b) / 2.0,+ (Some(_), Some(_)) => 0.0,+ (Some(a), None) => a,+ (None, Some(b)) => b,+ (None, None) => 0.0,+ };+ }+ for (i, &d) in secants.iter().enumerate() {+ if d == 0.0 {+ if let Some(v) = m.get_mut(i) {+ *v = 0.0;+ }+ if let Some(v) = m.get_mut(i + 1) {+ *v = 0.0;+ }+ continue;+ }+ let (Some(&mi), Some(&mj)) = (m.get(i), m.get(i + 1)) else { continue };+ let (a, b) = (mi / d, mj / d);+ let s = a * a + b * b;+ if s > 9.0 {+ let tau = 3.0 / s.sqrt();+ if let Some(v) = m.get_mut(i) {+ *v = tau * a * d;+ }+ if let Some(v) = m.get_mut(i + 1) {+ *v = tau * b * d;+ }+ }+ }+ m+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn linear_is_identity() {+ let c = Curve::linear();+ for i in 0..=10 {+ let x = i as f32 / 10.0;+ assert!((c.eval(x) - x).abs() < 1e-5);+ }+ }++ #[test]+ fn passes_through_points_and_stays_monotone() {+ let c = Curve::new(&[Vec2::new(0.0, 0.0), Vec2::new(0.3, 0.6), Vec2::new(0.7, 0.7), Vec2::new(1.0, 1.0)]);+ assert!((c.eval(0.3) - 0.6).abs() < 1e-5);+ assert!((c.eval(0.7) - 0.7).abs() < 1e-5);+ let mut prev = 0.0;+ for i in 0..=100 {+ let y = c.eval(i as f32 / 100.0);+ assert!(y + 1e-6 >= prev, "not monotone at {i}");+ prev = y;+ }+ }++ #[test]+ fn bad_input_falls_back() {+ let c = Curve::new(&[Vec2::new(f32::NAN, 0.0)]);+ assert!((c.eval(0.25) - 0.25).abs() < 1e-5);+ assert_eq!(Curve::linear().eval(f32::NAN), 0.0);+ assert_eq!(Curve::linear().eval(4.0), 1.0);+ }+}diff --git a/crates/engine/src/document.rs b/crates/engine/src/document.rsnew file mode 100644index 0000000..6c5e59c--- /dev/null+++ b/crates/engine/src/document.rs@@ -0,0 +1,1684 @@+//! The artwork: canvas size, background and layers. Pixels live with the renderer, keyed by+//! [`LayerId`]; this is the structure around them, cheap to clone (undo keeps copies).++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]+#[serde(transparent)]+pub struct LayerId(pub u64);++/// How a layer combines with what is below it.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]+pub enum BlendMode {+ #[default]+ Normal,+ Multiply,+ Darken,+ /// The darker of what is below and the layer laid over it normally, alpha included: it shows+ /// nothing where there is nothing below.+ Shade,+ ColorBurn,+ LinearBurn,+ DarkerColor,+ Lighten,+ Screen,+ ColorDodge,+ Add,+ LighterColor,+ Overlay,+ SoftLight,+ HardLight,+ VividLight,+ LinearLight,+ PinLight,+ HardMix,+ Difference,+ Exclusion,+ Subtract,+ Divide,+ Hue,+ Saturation,+ Color,+ Luminosity,+}++impl BlendMode {+ /// Every mode, in the order the layer panel lists them (grouped: darken, normal, lighten,+ /// contrast, difference, colour).+ pub const ALL: [BlendMode; 27] = [+ BlendMode::Multiply,+ BlendMode::Darken,+ BlendMode::Shade,+ BlendMode::ColorBurn,+ BlendMode::LinearBurn,+ BlendMode::DarkerColor,+ BlendMode::Normal,+ BlendMode::Lighten,+ BlendMode::Screen,+ BlendMode::ColorDodge,+ BlendMode::Add,+ BlendMode::LighterColor,+ BlendMode::Overlay,+ BlendMode::SoftLight,+ BlendMode::HardLight,+ BlendMode::VividLight,+ BlendMode::LinearLight,+ BlendMode::PinLight,+ BlendMode::HardMix,+ BlendMode::Difference,+ BlendMode::Exclusion,+ BlendMode::Subtract,+ BlendMode::Divide,+ BlendMode::Hue,+ BlendMode::Saturation,+ BlendMode::Color,+ BlendMode::Luminosity,+ ];++ /// The highest of the modes' numbers.+ pub const MAX_ID: u32 = 26;++ /// The renderer's number for the mode (stable: shaders switch on it).+ pub fn id(self) -> u32 {+ match self {+ BlendMode::Normal => 0,+ BlendMode::Multiply => 1,+ BlendMode::Darken => 2,+ BlendMode::ColorBurn => 3,+ BlendMode::LinearBurn => 4,+ BlendMode::DarkerColor => 5,+ BlendMode::Lighten => 6,+ BlendMode::Screen => 7,+ BlendMode::ColorDodge => 8,+ BlendMode::Add => 9,+ BlendMode::LighterColor => 10,+ BlendMode::Overlay => 11,+ BlendMode::SoftLight => 12,+ BlendMode::HardLight => 13,+ BlendMode::VividLight => 14,+ BlendMode::LinearLight => 15,+ BlendMode::PinLight => 16,+ BlendMode::HardMix => 17,+ BlendMode::Difference => 18,+ BlendMode::Exclusion => 19,+ BlendMode::Subtract => 20,+ BlendMode::Divide => 21,+ BlendMode::Hue => 22,+ BlendMode::Saturation => 23,+ BlendMode::Color => 24,+ BlendMode::Luminosity => 25,+ BlendMode::Shade => 26,+ }+ }++ pub fn from_id(id: u32) -> Option<BlendMode> {+ BlendMode::ALL.iter().copied().find(|m| m.id() == id)+ }++ pub fn name(self) -> &'static str {+ match self {+ BlendMode::Normal => "Normal",+ BlendMode::Multiply => "Multiply",+ BlendMode::Darken => "Darken",+ BlendMode::Shade => "Shade",+ BlendMode::ColorBurn => "Color Burn",+ BlendMode::LinearBurn => "Linear Burn",+ BlendMode::DarkerColor => "Darker Color",+ BlendMode::Lighten => "Lighten",+ BlendMode::Screen => "Screen",+ BlendMode::ColorDodge => "Color Dodge",+ BlendMode::Add => "Add",+ BlendMode::LighterColor => "Lighter Color",+ BlendMode::Overlay => "Overlay",+ BlendMode::SoftLight => "Soft Light",+ BlendMode::HardLight => "Hard Light",+ BlendMode::VividLight => "Vivid Light",+ BlendMode::LinearLight => "Linear Light",+ BlendMode::PinLight => "Pin Light",+ BlendMode::HardMix => "Hard Mix",+ BlendMode::Difference => "Difference",+ BlendMode::Exclusion => "Exclusion",+ BlendMode::Subtract => "Subtract",+ BlendMode::Divide => "Divide",+ BlendMode::Hue => "Hue",+ BlendMode::Saturation => "Saturation",+ BlendMode::Color => "Color",+ BlendMode::Luminosity => "Luminosity",+ }+ }+}++/// What a layer in the stack is.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+pub enum LayerKind {+ /// Pixels to paint on.+ #[default]+ Paint,+ /// A group: the layers just below it whose parent it is, composited together first.+ Group,+ /// A mask: just above the layer it belongs to (its parent), showing that layer as much as it+ /// is light.+ Mask,+}++/// How lines of text line up.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+pub enum TextAlign {+ #[default]+ Left,+ Center,+ Right,+ Justify,+}++/// Text a layer holds, still editable: the app draws it into the layer's pixels whenever it+/// changes.+#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]+#[serde(default)]+pub struct LayerText {+ pub text: String,+ /// The typeface's family and style names.+ pub font: String,+ pub style: String,+ /// Letter height, canvas pixels.+ pub size: f32,+ /// Extra space at the caret between two letters, and between all letters, as a fraction of+ /// the size (-1..1).+ pub kerning: f32,+ pub tracking: f32,+ /// Extra space between lines, and the letters raised, as a fraction of the size (-1..1).+ pub leading: f32,+ pub baseline: f32,+ pub opacity: f32,+ pub align: TextAlign,+ pub underline: bool,+ pub outline: bool,+ pub vertical: bool,+ pub all_caps: bool,+ /// 0..1 in the document's profile.+ pub color: [f32; 3],+ /// The text box's top left corner, canvas pixels, and how wide it wraps (0: no wrapping).+ pub origin: [f32; 2],+ pub width: f32,+}++impl Default for LayerText {+ fn default() -> Self {+ LayerText {+ text: String::new(),+ font: String::new(),+ style: String::new(),+ size: 64.0,+ kerning: 0.0,+ tracking: 0.0,+ leading: 0.0,+ baseline: 0.0,+ opacity: 1.0,+ align: TextAlign::Left,+ underline: false,+ outline: false,+ vertical: false,+ all_caps: false,+ color: [0.0; 3],+ origin: [0.0; 2],+ width: 0.0,+ }+ }+}++impl LayerText {+ /// The same text with every number in range.+ pub fn sanitized(mut self) -> LayerText {+ let unit = |v: f32| if v.is_finite() { v.clamp(-1.0, 1.0) } else { 0.0 };+ self.size = if self.size.is_finite() { self.size.clamp(1.0, 4096.0) } else { 64.0 };+ self.kerning = unit(self.kerning);+ self.tracking = unit(self.tracking);+ self.leading = unit(self.leading);+ self.baseline = unit(self.baseline);+ self.opacity = if self.opacity.is_finite() { self.opacity.clamp(0.0, 1.0) } else { 1.0 };+ self.color = self.color.map(|c| if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.0 });+ self.origin = self.origin.map(|c| if c.is_finite() { c.clamp(-1.0e6, 1.0e6) } else { 0.0 });+ self.width = if self.width.is_finite() { self.width.clamp(0.0, 1.0e6) } else { 0.0 };+ self.text = self.text.chars().take(100_000).collect();+ self+ }++ /// A layer name from the text: its first line, shortened.+ pub fn name(&self) -> Option<String> {+ let line = self.text.lines().map(str::trim).find(|l| !l.is_empty())?;+ Some(line.chars().take(64).collect())+ }+}++#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]+pub struct Layer {+ pub id: LayerId,+ pub name: String,+ pub visible: bool,+ pub opacity: f32,+ pub blend: BlendMode,+ /// Painting only changes pixels that already have alpha.+ pub alpha_lock: bool,+ /// Shown only where the nearest unclipped layer below has alpha.+ pub clipped: bool,+ /// No painting or changes.+ pub locked: bool,+ /// What colour fills and automatic selections look at instead of the current layer (one+ /// layer at most).+ #[serde(default)]+ pub reference: bool,+ #[serde(default)]+ pub kind: LayerKind,+ /// A mask's layer, or the group a layer is in.+ #[serde(default)]+ pub parent: Option<LayerId>,+ /// A group shown closed in the layers panel.+ #[serde(default)]+ pub collapsed: bool,+ /// A text layer's text, until its pixels are changed some other way.+ #[serde(default)]+ pub text: Option<LayerText>,+}++/// Largest canvas edge, pixels.+pub const MAX_CANVAS_EDGE: u32 = 16384;++/// Memory the layers' pixels may take unless the device says otherwise, bytes.+pub const LAYER_BUDGET: u64 = 2 * 1024 * 1024 * 1024;++/// Memory the layers' pixels may take on this device, bytes: it sets how many layers a canvas+/// holds.+static BUDGET: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(LAYER_BUDGET);++/// Sets the memory layers may take on this device (256 MiB to 64 GiB).+pub fn set_layer_budget(bytes: u64) {+ BUDGET.store(bytes.clamp(256 << 20, 64 << 30), std::sync::atomic::Ordering::Relaxed);+}++#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]+pub struct Document {+ width: u32,+ height: u32,+ /// Background colour, 0..1 in the document's profile.+ pub background: [f32; 3],+ pub background_visible: bool,+ /// Bottom layer first.+ layers: Vec<Layer>,+ current: LayerId,+ /// Layers picked to act on together with the current one (in the layers panel); not saved.+ #[serde(skip)]+ picked: Vec<LayerId>,+ next_id: u64,+ /// The drawing guide over the canvas.+ #[serde(default)]+ pub guide: crate::guide::Guide,+ /// Dots per inch, for the canvas's printed size and in files that carry one.+ #[serde(default = "default_dpi")]+ pub dpi: f32,+ /// Animation Assist's settings while it is on.+ #[serde(default)]+ pub animation: Option<crate::animation::Animation>,+ /// The colour profile its pixels and colours are in.+ #[serde(default)]+ pub profile: crate::profile::Profile,+ /// A profile of its own: an RGB one its pixels and colours are in, or a CMYK one its colours+ /// print to (its pixels then in Display P3, shown as the press would print them). None for the+ /// built-in profiles.+ #[serde(default, deserialize_with = "crate::cms::lenient", skip_serializing_if = "Option::is_none")]+ pub icc: Option<crate::cms::CanvasIcc>,+}++/// A document's profile settings apart from it.+struct ProfileSettings {+ profile: crate::profile::Profile,+ icc: Option<crate::cms::CanvasIcc>,+}++impl ProfileSettings {+ fn rgb_profile(&self) -> std::sync::Arc<crate::cms::IccProfile> {+ match &self.icc {+ Some(i) if i.0.space == crate::cms::Space::Rgb => i.0.clone(),+ // a CMYK canvas's pixels are in Display P3+ Some(_) => crate::cms::builtin(crate::profile::Profile::DisplayP3),+ None => crate::cms::builtin(self.profile),+ }+ }+}++fn default_dpi() -> f32 {+ crate::formats::DPI as f32+}++impl Document {+ /// A canvas of `width` × `height` pixels (each clamped to 1..=[`MAX_CANVAS_EDGE`]) with a white+ /// background and one empty layer.+ pub fn new(width: u32, height: u32) -> Document {+ let mut doc = Document {+ width: width.clamp(1, MAX_CANVAS_EDGE),+ height: height.clamp(1, MAX_CANVAS_EDGE),+ background: [1.0, 1.0, 1.0],+ background_visible: true,+ layers: Vec::new(),+ current: LayerId(0),+ picked: Vec::new(),+ next_id: 1,+ guide: crate::guide::Guide::new(width.clamp(1, MAX_CANVAS_EDGE), height.clamp(1, MAX_CANVAS_EDGE)),+ dpi: default_dpi(),+ animation: None,+ profile: crate::profile::Profile::Srgb,+ icc: None,+ };+ doc.add_layer();+ doc+ }++ /// A canvas of `width` × `height` pixels holding `layers` (bottom first), `current` chosen if+ /// it is one of them; what doesn't fit the rules (masks away from their layers, parents that+ /// aren't groups...) is put right as [`Document::repaired`] does. With no layers it has one.+ pub fn from_layers(width: u32, height: u32, layers: Vec<Layer>, current: LayerId) -> Document {+ let mut doc = Document::new(width, height);+ if layers.is_empty() {+ return doc;+ }+ doc.layers = layers;+ let mut doc = doc.repaired();+ let first = doc.layers.iter().find(|l| l.kind == LayerKind::Paint).map(|l| l.id);+ doc.current = if doc.layer(current).is_some_and(|l| l.kind == LayerKind::Paint) {+ current+ } else {+ first.unwrap_or(current)+ };+ doc+ }++ pub fn width(&self) -> u32 {+ self.width+ }++ /// How many layers with pixels (paint layers and masks) a canvas this size holds.+ pub fn layer_cap(&self) -> usize {+ let bytes = u64::from(self.width) * u64::from(self.height) * 4;+ let budget = BUDGET.load(std::sync::atomic::Ordering::Relaxed);+ usize::try_from(budget / bytes.max(1)).unwrap_or(usize::MAX).max(1)+ }++ /// Whether `more` more layers with pixels fit under [`Document::layer_cap`].+ pub fn has_room(&self, more: usize) -> bool {+ self.pixel_layer_ids().count() + more <= self.layer_cap()+ }++ /// The same document on a canvas of `width` × `height` (each clamped to+ /// 1..=[`MAX_CANVAS_EDGE`]); the drawing guide is centred on it again.+ pub fn resized(&self, width: u32, height: u32) -> Document {+ let mut d = self.clone();+ d.width = width.clamp(1, MAX_CANVAS_EDGE);+ d.height = height.clamp(1, MAX_CANVAS_EDGE);+ d.guide.centre = [d.width as f32 / 2.0, d.height as f32 / 2.0];+ d.guide.vanishing.clear();+ d+ }++ pub fn height(&self) -> u32 {+ self.height+ }++ /// Puts the document in profile `to`, its background and text colours turned into it so they+ /// look the same (the layers' pixels are the renderer's).+ pub fn change_profile(&mut self, to: crate::profile::Profile) {+ self.change_to(to, None);+ }++ /// Puts the document in built-in profile `profile` with profile `icc` of its own (see+ /// [`Document::icc`]), its background and text colours turned into the RGB profile its pixels+ /// are then in.+ pub fn change_to(&mut self, profile: crate::profile::Profile, icc: Option<crate::cms::CanvasIcc>) {+ // between built-in profiles: their matrices, exactly+ if self.icc.is_none() && icc.is_none() {+ let from = self.profile;+ self.background = from.convert(self.background, profile);+ for text in self.layers.iter_mut().filter_map(|l| l.text.as_mut()) {+ text.color = from.convert(text.color, profile);+ }+ self.profile = profile;+ return;+ }+ let from = self.rgb_profile();+ let mut next = self.clone_settings();+ next.profile = profile;+ next.icc = icc;+ let to = next.rgb_profile();+ let turn = |c: [f32; 3]| -> [f32; 3] {+ let v = from.convert(&c.map(f64::from), &to);+ [0, 1, 2].map(|k| v.get(k).copied().unwrap_or(0.0) as f32)+ };+ if !std::sync::Arc::ptr_eq(&from, &to) && from != to {+ self.background = turn(self.background);+ for text in self.layers.iter_mut().filter_map(|l| l.text.as_mut()) {+ text.color = turn(text.color);+ }+ }+ self.profile = next.profile;+ self.icc = next.icc;+ }++ /// Just the profile settings, to ask what profile they make.+ fn clone_settings(&self) -> ProfileSettings {+ ProfileSettings { profile: self.profile, icc: self.icc.clone() }+ }++ /// The profile its colours print to, if it is a CMYK canvas.+ pub fn press(&self) -> Option<std::sync::Arc<crate::cms::IccProfile>> {+ self.icc.as_ref().filter(|i| i.0.space == crate::cms::Space::Cmyk).map(|i| i.0.clone())+ }++ /// The RGB profile its pixels and colours are in: its own, else the built-in one.+ pub fn rgb_profile(&self) -> std::sync::Arc<crate::cms::IccProfile> {+ self.clone_settings().rgb_profile()+ }++ /// Its profile's name, as lists show it.+ pub fn profile_name(&self) -> String {+ self.icc.as_ref().map_or_else(|| self.profile.name().to_owned(), |i| i.0.name.clone())+ }++ /// The profile a picture of it carries: the RGB one its colours are in (a CMYK canvas's+ /// pictures show the press's colours in Display P3).+ pub fn picture_icc(&self) -> Vec<u8> {+ match &self.icc {+ Some(i) if i.0.space == crate::cms::Space::Rgb => i.0.bytes.to_vec(),+ Some(_) => crate::icc::icc(crate::profile::Profile::DisplayP3),+ None => crate::icc::icc(self.profile),+ }+ }++ /// The layers whose pixels are colours (paint layers, not masks), bottom first.+ pub fn colour_layer_ids(&self) -> impl Iterator<Item = LayerId> + '_ {+ self.layers.iter().filter(|l| l.kind == LayerKind::Paint).map(|l| l.id)+ }++ /// Bottom layer first.+ pub fn layers(&self) -> &[Layer] {+ &self.layers+ }++ /// Makes `id` the reference layer (or, not `on`, no layer); false if there is no such layer.+ pub fn set_reference(&mut self, id: LayerId, on: bool) -> bool {+ if self.layer(id).is_none() {+ return false;+ }+ for l in &mut self.layers {+ l.reference = on && l.id == id;+ }+ true+ }++ /// The reference layer, if one is set.+ pub fn reference(&self) -> Option<LayerId> {+ self.layers.iter().find(|l| l.reference).map(|l| l.id)+ }++ pub fn layer(&self, id: LayerId) -> Option<&Layer> {+ self.layers.iter().find(|l| l.id == id)+ }++ fn layer_mut(&mut self, id: LayerId) -> Option<&mut Layer> {+ self.layers.iter_mut().find(|l| l.id == id)+ }++ pub fn index_of(&self, id: LayerId) -> Option<usize> {+ self.layers.iter().position(|l| l.id == id)+ }++ pub fn current(&self) -> LayerId {+ self.current+ }++ pub fn set_current(&mut self, id: LayerId) -> bool {+ let found = self.layer(id).is_some();+ if found {+ self.current = id;+ }+ found+ }++ /// The layers picked besides the current one, bottom first.+ pub fn picked(&self) -> Vec<LayerId> {+ self.layers.iter().filter(|l| l.id != self.current && self.picked.contains(&l.id)).map(|l| l.id).collect()+ }++ pub fn is_picked(&self, id: LayerId) -> bool {+ id != self.current && self.picked.contains(&id) && self.layer(id).is_some()+ }++ /// Picks layer `id` to act on with the current one, or unpicks it; false for the current+ /// layer or one that isn't there.+ pub fn toggle_pick(&mut self, id: LayerId) -> bool {+ if id == self.current || self.layer(id).is_none() {+ return false;+ }+ match self.picked.iter().position(|p| *p == id) {+ Some(i) => {+ self.picked.remove(i);+ }+ None => self.picked.push(id),+ }+ true+ }++ /// Picks every layer, groups and masks too; false if all already were.+ pub fn pick_all(&mut self) -> bool {+ let all: Vec<LayerId> = self.layers.iter().map(|l| l.id).filter(|id| *id != self.current).collect();+ if all.iter().all(|id| self.picked.contains(id)) {+ return false;+ }+ self.picked = all;+ true+ }++ /// Unpicks everything; false if nothing was picked.+ pub fn clear_picks(&mut self) -> bool {+ let any = !self.picked().is_empty();+ self.picked.clear();+ any+ }++ /// The current layer and the picked ones, bottom first.+ pub fn chosen(&self) -> Vec<LayerId> {+ self.layers.iter().filter(|l| l.id == self.current || self.picked.contains(&l.id)).map(|l| l.id).collect()+ }++ /// What is chosen as whole items, bottom first: a mask stands for its layer, and what is in a+ /// chosen group goes with it.+ fn chosen_items(&self) -> Vec<LayerId> {+ let mut items: Vec<LayerId> = Vec::new();+ for id in self.chosen() {+ let Some(l) = self.layer(id) else { continue };+ let item = if l.kind == LayerKind::Mask { l.parent } else { Some(id) };+ if let Some(item) = item.filter(|i| !items.contains(i)) {+ items.push(item);+ }+ }+ let groups: Vec<LayerId> =+ items.iter().copied().filter(|g| self.layer(*g).is_some_and(|l| l.kind == LayerKind::Group)).collect();+ items.retain(|id| !groups.iter().any(|g| self.is_inside(*id, *g)));+ items.sort_by_key(|id| self.index_of(*id).unwrap_or(usize::MAX));+ items+ }++ /// Puts what is chosen in a new group where the top of it was (in its group), keeping its+ /// order; the picks are cleared. Returns the group.+ pub fn group_chosen(&mut self) -> Option<LayerId> {+ let items = self.chosen_items();+ let top = *items.last()?;+ let parent = self.group_of(top);+ let top_end = self.unit(top)?.end;+ // lifted out top down, so the ranges below stay where they were+ let mut moved: Vec<Layer> = Vec::new();+ for id in items.iter().rev() {+ let unit = self.unit(*id)?;+ let mut part: Vec<Layer> = self.layers.drain(unit).collect();+ part.append(&mut moved);+ moved = part;+ }+ let group = self.blank(LayerKind::Group, "New group".to_owned(), parent);+ let gid = group.id;+ for l in &mut moved {+ if items.contains(&l.id) {+ l.parent = Some(gid);+ }+ }+ let at = top_end.saturating_sub(moved.len()).min(self.layers.len());+ self.layers.splice(at..at, moved.into_iter().chain(std::iter::once(group)));+ self.picked.clear();+ self.fix_clips();+ Some(gid)+ }++ /// Copies of what is chosen (each with its mask, or everything in it), together just above+ /// the top of it and in its group, in order; the copies become the current layer and the+ /// picks. Returns each (original, copy) pair of layers whose pixels the renderer copies.+ pub fn duplicate_chosen(&mut self) -> Option<Vec<(LayerId, LayerId)>> {+ let items = self.chosen_items();+ let top = *items.last()?;+ let parent = self.group_of(top);+ let at = self.unit(top)?.end;+ let mut copies: Vec<Layer> = Vec::new();+ let mut pairs = Vec::new();+ let mut made = std::collections::HashMap::new();+ for id in &items {+ let unit = self.unit(*id)?;+ let originals: Vec<Layer> = self.layers.get(unit)?.to_vec();+ for l in &originals {+ let copy = self.new_id();+ made.insert(l.id, copy);+ }+ let renamed = |old: LayerId| made.get(&old).copied().unwrap_or(old);+ for l in &originals {+ let mut c = l.clone();+ c.id = renamed(l.id);+ c.reference = false;+ c.parent = if l.id == *id { parent } else { l.parent.map(renamed) };+ if l.kind != LayerKind::Group {+ pairs.push((l.id, c.id));+ }+ copies.push(c);+ }+ }+ self.layers.splice(at..at, copies);+ self.current = made.get(&self.current).copied().unwrap_or(self.current);+ self.picked = self.picked.iter().filter_map(|p| made.get(p).copied()).collect();+ self.fix_clips();+ Some(pairs)+ }++ /// Moves what is chosen (each with what goes with it, in its order) together to position `to`+ /// of the stack without them (0 = bottom), joining the group they land in as+ /// [`Document::move_layer`] does.+ pub fn move_chosen(&mut self, to: usize) -> bool {+ let items = self.chosen_items();+ if items.is_empty() {+ return false;+ }+ let mut moved: Vec<Layer> = Vec::new();+ for id in items.iter().rev() {+ let Some(unit) = self.unit(*id) else { return false };+ let mut part: Vec<Layer> = self.layers.drain(unit).collect();+ part.append(&mut moved);+ moved = part;+ }+ let mut to = to.min(self.layers.len());+ // never between a layer and its mask+ if self.layers.get(to).is_some_and(|l| l.kind == LayerKind::Mask) {+ to += 1;+ }+ let parent = self.layers.get(to).and_then(|above| match above.kind {+ LayerKind::Group => Some(above.id),+ _ => self.group_of(above.id),+ });+ for l in &mut moved {+ if items.contains(&l.id) {+ l.parent = parent;+ }+ }+ self.layers.splice(to..to, moved);+ self.fix_clips();+ true+ }++ /// Removes what is chosen and unlocked as [`Document::delete_layer`] does (the last paint+ /// layer stays); the picks are cleared. False if nothing went.+ pub fn delete_chosen(&mut self) -> bool {+ let mut any = false;+ for id in self.chosen().into_iter().rev() {+ if self.layer(id).is_some_and(|l| !l.locked) {+ any |= self.delete_layer(id);+ }+ }+ self.picked.clear();+ any+ }++ /// Merging what is chosen: its bottom paint layer, and what is chosen above that (layers+ /// without masks, and groups), bottom first, for the renderer to draw into it. None unless+ /// there is something to merge or if any of it is locked.+ pub fn merge_chosen_plan(&self) -> Option<(LayerId, Vec<LayerId>)> {+ let items = self.chosen_items();+ if items.iter().any(|id| self.layer(*id).is_some_and(|l| l.locked)) {+ return None;+ }+ let at = items.iter().position(|id| self.layer(*id).is_some_and(|l| l.kind == LayerKind::Paint))?;+ let lower = *items.get(at)?;+ let uppers: Vec<LayerId> = items+ .get(at + 1..)?+ .iter()+ .copied()+ .filter(|id| self.layer(*id).is_some_and(|l| l.kind == LayerKind::Group) || self.mask_of(*id).is_none())+ .collect();+ (!uppers.is_empty()).then_some((lower, uppers))+ }++ /// Removes `uppers` (each with everything in it) once they were drawn into `lower`, which+ /// becomes current; the picks are cleared.+ pub fn finish_merge_chosen(&mut self, lower: LayerId, uppers: &[LayerId]) -> bool {+ if self.layer(lower).is_none() {+ return false;+ }+ for id in uppers.iter().rev() {+ if let Some(unit) = self.unit(*id) {+ self.layers.drain(unit);+ }+ }+ self.current = lower;+ self.picked.clear();+ self.rasterize(lower);+ self.fix_clips();+ true+ }++ fn new_id(&mut self) -> LayerId {+ let id = LayerId(self.next_id);+ self.next_id += 1;+ id+ }++ /// A blank layer of `kind` named `name`, with a new id.+ fn blank(&mut self, kind: LayerKind, name: String, parent: Option<LayerId>) -> Layer {+ Layer {+ id: self.new_id(),+ name,+ visible: true,+ opacity: 1.0,+ blend: BlendMode::Normal,+ alpha_lock: false,+ clipped: false,+ locked: false,+ reference: false,+ kind,+ parent,+ collapsed: false,+ text: None,+ }+ }++ /// Adds a text layer above the current one (in its group), named after its text, and makes+ /// it current.+ pub fn add_text_layer(&mut self, text: LayerText) -> LayerId {+ let id = self.add_layer();+ if let Some(l) = self.layer_mut(id) {+ let text = text.sanitized();+ if let Some(name) = text.name() {+ l.name = name;+ }+ l.text = Some(text);+ }+ id+ }++ /// Changes a text layer's text (renaming it after the text); false if it isn't one.+ pub fn set_text(&mut self, id: LayerId, text: LayerText) -> bool {+ let Some(l) = self.layer_mut(id).filter(|l| l.text.is_some()) else { return false };+ let text = text.sanitized();+ if let Some(name) = text.name() {+ l.name = name;+ }+ l.text = Some(text);+ true+ }++ /// Makes a text layer an ordinary one, its pixels kept; false if it wasn't one.+ pub fn rasterize(&mut self, id: LayerId) -> bool {+ self.layer_mut(id).and_then(|l| l.text.take()).is_some()+ }++ /// Adds an empty layer above the current one (in its group) and makes it current. It is named+ /// after the number of entries the stack will have, so a deleted layer's number comes back.+ pub fn add_layer(&mut self) -> LayerId {+ let name = format!("Layer {}", self.layers.len() + 1);+ // above the current layer's mask, or above the current group, in the same group+ let (at, parent) = match self.layer(self.current) {+ Some(c) => {+ let owner = if c.kind == LayerKind::Mask { c.parent.unwrap_or(c.id) } else { c.id };+ let top = self.mask_of(owner).unwrap_or(owner);+ (self.index_of(top).map_or(self.layers.len(), |i| i + 1), self.group_of(owner))+ }+ None => (self.layers.len(), None),+ };+ let layer = self.blank(LayerKind::Paint, name, parent);+ let id = layer.id;+ self.layers.insert(at.min(self.layers.len()), layer);+ self.current = id;+ id+ }++ /// The mask of layer `id`, if it has one.+ pub fn mask_of(&self, id: LayerId) -> Option<LayerId> {+ let at = self.index_of(id)?;+ self.layers.get(at + 1).filter(|l| l.kind == LayerKind::Mask && l.parent == Some(id)).map(|l| l.id)+ }++ /// The group directly holding `id` (for a mask, its layer's group), if any.+ pub fn group_of(&self, id: LayerId) -> Option<LayerId> {+ let l = self.layer(id)?;+ let l = match l.kind {+ LayerKind::Mask => self.layer(l.parent?).filter(|o| o.kind == LayerKind::Paint)?,+ _ => l,+ };+ l.parent.filter(|p| *p != l.id && self.layer(*p).is_some_and(|g| g.kind == LayerKind::Group))+ }++ /// How many groups `id` is inside.+ pub fn depth(&self, id: LayerId) -> usize {+ let mut depth = 0;+ let mut at = self.group_of(id);+ while let Some(g) = at {+ depth += 1;+ if depth >= self.layers.len() {+ break;+ }+ at = self.group_of(g);+ }+ depth+ }++ /// The deepest any layer sits in groups.+ pub fn max_depth(&self) -> usize {+ self.layers.iter().map(|l| self.depth(l.id)).max().unwrap_or(0)+ }++ /// Whether `id` is somewhere inside group `group`.+ pub fn is_inside(&self, id: LayerId, group: LayerId) -> bool {+ let mut at = self.group_of(id);+ for _ in 0..self.layers.len() {+ match at {+ Some(g) if g == group => return true,+ Some(g) => at = self.group_of(g),+ None => return false,+ }+ }+ false+ }++ /// The layers and groups directly in `group` (None: the top level), bottom first, without+ /// masks.+ pub fn members(&self, group: Option<LayerId>) -> Vec<LayerId> {+ self.layers.iter().filter(|l| l.kind != LayerKind::Mask && self.group_of(l.id) == group).map(|l| l.id).collect()+ }++ /// Everything inside group `id`, at any depth, masks included, bottom first.+ pub fn contents(&self, id: LayerId) -> Vec<LayerId> {+ self.layers.iter().filter(|l| self.is_inside(l.id, id)).map(|l| l.id).collect()+ }++ /// Where a layer sits in the stack with what goes with it: a paint layer with its mask, a+ /// group with everything in it (just below its entry).+ fn unit(&self, id: LayerId) -> Option<std::ops::Range<usize>> {+ let at = self.index_of(id)?;+ let l = self.layers.get(at)?;+ match l.kind {+ LayerKind::Paint => Some(at..at + 1 + usize::from(self.mask_of(id).is_some())),+ LayerKind::Mask => {+ let owner = self.layer(l.parent?).filter(|o| o.kind == LayerKind::Paint)?.id;+ self.unit(owner)+ }+ LayerKind::Group => {+ let mut start = at;+ while start > 0 && self.layers.get(start - 1).is_some_and(|b| self.is_inside(b.id, id)) {+ start -= 1;+ }+ Some(start..at + 1)+ }+ }+ }++ /// The layer or group just below `id` in the same group, if any.+ pub fn below(&self, id: LayerId) -> Option<LayerId> {+ let start = self.unit(id)?.start;+ let b = self.layers.get(start.checked_sub(1)?)?;+ let b = if b.kind == LayerKind::Mask { b.parent? } else { b.id };+ (self.group_of(b) == self.group_of(id)).then_some(b)+ }++ /// Paint layers in the stack.+ fn paint_count(&self) -> usize {+ self.layers.iter().filter(|l| l.kind == LayerKind::Paint).count()+ }++ /// Adds a mask to paint layer `id` (just above it) and makes it current; the renderer fills it+ /// white. None if the layer can't take one or has one.+ pub fn add_mask(&mut self, id: LayerId) -> Option<LayerId> {+ let at = self.index_of(id)?;+ if self.layer(id)?.kind != LayerKind::Paint || self.mask_of(id).is_some() {+ return None;+ }+ let mask = self.blank(LayerKind::Mask, "Layer Mask".to_owned(), Some(id));+ let new = mask.id;+ self.layers.insert(at + 1, mask);+ self.current = new;+ Some(new)+ }++ /// Groups layer or group `id` with what is just below it in its group: both go in a new group+ /// there, or, when that is a group, `id` goes in it at its top. Returns the group; None if+ /// nothing is below.+ pub fn combine_down(&mut self, id: LayerId) -> Option<LayerId> {+ if self.layer(id)?.kind == LayerKind::Mask {+ return None;+ }+ let below = self.below(id)?;+ let unit = self.unit(id)?;+ if self.layer(below)?.kind == LayerKind::Group {+ // the group's entry moves up over the layer, which joins it at its top+ let at = self.index_of(below)?;+ let entry = self.layers.remove(at);+ self.layers.insert(unit.end - 1, entry);+ self.layer_mut(id)?.parent = Some(below);+ return Some(below);+ }+ let group = self.blank(LayerKind::Group, "New group".to_owned(), self.group_of(id));+ let new = group.id;+ self.layers.insert(unit.end, group);+ self.layer_mut(id)?.parent = Some(new);+ let lower = self.layer_mut(below)?;+ lower.parent = Some(new);+ // now at the bottom of the group, it has nothing to clip to+ lower.clipped = false;+ Some(new)+ }++ /// Takes the layers in group `id` out one level and removes the group; its top layer becomes+ /// current.+ pub fn ungroup(&mut self, id: LayerId) -> bool {+ if self.layer(id).is_none_or(|l| l.kind != LayerKind::Group) {+ return false;+ }+ let up = self.group_of(id);+ let members = self.members(Some(id));+ for m in &members {+ if let Some(l) = self.layer_mut(*m) {+ l.parent = up;+ }+ }+ let Some(at) = self.index_of(id) else { return false };+ self.layers.remove(at);+ if self.current == id {+ self.current = members.last().copied().unwrap_or(id);+ }+ self.settle_current(at);+ self.fix_clips();+ true+ }++ /// Replaces group `id` and everything in it with one paint layer where it was, named after its+ /// bottom layer and with the group's opacity, blend and visibility, made current. The renderer+ /// draws the group into it.+ pub fn flatten(&mut self, id: LayerId) -> Option<LayerId> {+ let group = self.layer(id).filter(|l| l.kind == LayerKind::Group)?.clone();+ let unit = self.unit(id)?;+ let name = self+ .layers+ .get(unit.clone())?+ .iter()+ .find(|l| l.kind == LayerKind::Paint)+ .map_or_else(|| group.name.clone(), |l| l.name.clone());+ let mut layer = self.blank(LayerKind::Paint, name, self.group_of(id));+ layer.visible = group.visible;+ layer.opacity = group.opacity;+ layer.blend = group.blend;+ let new = layer.id;+ let start = unit.start;+ self.layers.drain(unit);+ self.layers.insert(start, layer);+ self.current = new;+ self.fix_clips();+ Some(new)+ }++ pub fn set_collapsed(&mut self, id: LayerId, collapsed: bool) -> bool {+ self.layer_mut(id).filter(|l| l.kind == LayerKind::Group).map(|l| l.collapsed = collapsed).is_some()+ }++ /// A copy of `id` just above it (same name and settings), made current. The renderer copies+ /// the pixels.+ pub fn duplicate_layer(&mut self, id: LayerId) -> Option<LayerId> {+ self.duplicate(id).map(|(copy, _)| copy)+ }++ /// A copy of layer or group `id` (with its mask, or everything in it) just above it, made+ /// current; returns the copy and each (original, copy) pair of layers whose pixels the+ /// renderer copies.+ pub fn duplicate(&mut self, id: LayerId) -> Option<(LayerId, Vec<(LayerId, LayerId)>)> {+ if self.layer(id)?.kind == LayerKind::Mask {+ return None;+ }+ let unit = self.unit(id)?;+ let originals: Vec<Layer> = self.layers.get(unit.clone())?.to_vec();+ let mut new_ids = std::collections::HashMap::new();+ for l in &originals {+ let copy = self.new_id();+ new_ids.insert(l.id, copy);+ }+ let renamed = |old: LayerId| new_ids.get(&old).copied().unwrap_or(old);+ let copies: Vec<Layer> = originals+ .iter()+ .map(|l| {+ let mut c = l.clone();+ c.id = renamed(l.id);+ c.reference = false;+ if l.id != id {+ c.parent = l.parent.map(renamed);+ }+ c+ })+ .collect();+ let pairs = originals.iter().filter(|l| l.kind != LayerKind::Group).map(|l| (l.id, renamed(l.id))).collect();+ let copy = renamed(id);+ self.layers.splice(unit.end..unit.end, copies);+ self.current = copy;+ Some((copy, pairs))+ }++ /// Removes a layer, with its mask, or a group with everything in it; the last paint layer+ /// can't be removed. The layer below (or above) becomes current.+ pub fn delete_layer(&mut self, id: LayerId) -> bool {+ let Some(layer) = self.layer(id) else { return false };+ let mut gone: Vec<LayerId> = match layer.kind {+ LayerKind::Group => self.contents(id),+ LayerKind::Paint => self.mask_of(id).into_iter().collect(),+ LayerKind::Mask => Vec::new(),+ };+ gone.push(id);+ let painted = self.layers.iter().filter(|l| l.kind == LayerKind::Paint && gone.contains(&l.id)).count();+ if self.paint_count() <= painted {+ return false;+ }+ let Some(at) = self.index_of(id) else { return false };+ let below = gone.iter().filter_map(|g| self.index_of(*g)).filter(|&i| i < at).count();+ self.layers.retain(|l| !gone.contains(&l.id));+ self.settle_current(at - below);+ self.fix_clips();+ true+ }++ /// When the current layer is gone, the one now below `at` (or the bottom one) becomes current.+ fn settle_current(&mut self, at: usize) {+ if self.layer(self.current).is_some() {+ return;+ }+ let next = at.saturating_sub(1).min(self.layers.len().saturating_sub(1));+ if let Some(l) = self.layers.get(next) {+ self.current = l.id;+ }+ }++ /// Unclips layers that no longer have a paint layer below them in their group.+ fn fix_clips(&mut self) {+ let stray: Vec<LayerId> =+ self.layers.iter().filter(|l| l.clipped && !self.can_clip(l.id)).map(|l| l.id).collect();+ for id in stray {+ if let Some(l) = self.layer_mut(id) {+ l.clipped = false;+ }+ }+ }++ /// Moves a paint layer (with its mask) or a group (with everything in it) to position `to`+ /// (0 = bottom, counted without them), clamped to the stack. It joins the group it lands in,+ /// or leaves its group.+ pub fn move_layer(&mut self, id: LayerId, to: usize) -> bool {+ if self.layer(id).is_none_or(|l| l.kind == LayerKind::Mask) {+ return false;+ }+ let Some(range) = self.unit(id) else { return false };+ let unit: Vec<Layer> = self.layers.drain(range).collect();+ let mut to = to.min(self.layers.len());+ // never between a layer and its mask+ if self.layers.get(to).is_some_and(|l| l.kind == LayerKind::Mask) {+ to += 1;+ }+ // landing below a group's entry, or among its layers, it joins that group+ let parent = self.layers.get(to).and_then(|above| match above.kind {+ LayerKind::Group => Some(above.id),+ _ => self.group_of(above.id),+ });+ for (k, mut l) in unit.into_iter().enumerate() {+ if l.id == id {+ l.parent = parent;+ }+ self.layers.insert(to + k, l);+ }+ self.fix_clips();+ true+ }++ /// What `id` merges into: the paint layer just below it in its group, if `id` is a paint layer+ /// or a group and neither has a mask.+ pub fn merge_target(&self, id: LayerId) -> Option<LayerId> {+ let layer = self.layer(id)?;+ let below = self.below(id)?;+ let plain = |l: LayerId| self.layer(l).is_some_and(|l| l.kind == LayerKind::Paint) && self.mask_of(l).is_none();+ ((layer.kind == LayerKind::Group || plain(id)) && plain(below)).then_some(below)+ }++ /// Removes `id` (with everything in it) after it was merged down; the layer below becomes+ /// current.+ pub fn finish_merge_down(&mut self, id: LayerId) -> bool {+ let Some(below) = self.merge_target(id) else { return false };+ let Some(unit) = self.unit(id) else { return false };+ self.layers.drain(unit);+ self.current = below;+ // merged into, a text layer's pixels are no longer just its text+ self.rasterize(below);+ true+ }++ /// Whether paint layer `id` can be clipped: a paint layer is just below it in its group.+ pub fn can_clip(&self, id: LayerId) -> bool {+ self.layer(id).is_some_and(|l| l.kind == LayerKind::Paint)+ && self.below(id).and_then(|b| self.layer(b)).is_some_and(|b| b.kind == LayerKind::Paint)+ }++ /// The layer `id` is clipped to: the nearest unclipped paint layer below it in its group.+ pub fn clip_base(&self, id: LayerId) -> Option<LayerId> {+ if !self.layer(id)?.clipped {+ return None;+ }+ let mut at = self.below(id);+ for _ in 0..self.layers.len() {+ let l = self.layer(at?)?;+ if l.kind != LayerKind::Paint {+ return None;+ }+ if !l.clipped {+ return Some(l.id);+ }+ at = self.below(l.id);+ }+ None+ }++ pub fn set_visible(&mut self, id: LayerId, visible: bool) -> bool {+ self.layer_mut(id).map(|l| l.visible = visible).is_some()+ }++ pub fn set_opacity(&mut self, id: LayerId, opacity: f32) -> bool {+ let o = if opacity.is_finite() { opacity.clamp(0.0, 1.0) } else { return false };+ self.layer_mut(id).map(|l| l.opacity = o).is_some()+ }++ pub fn set_blend(&mut self, id: LayerId, blend: BlendMode) -> bool {+ self.layer_mut(id).map(|l| l.blend = blend).is_some()+ }++ pub fn set_alpha_lock(&mut self, id: LayerId, on: bool) -> bool {+ self.layer_mut(id).map(|l| l.alpha_lock = on).is_some()+ }++ pub fn set_locked(&mut self, id: LayerId, on: bool) -> bool {+ self.layer_mut(id).map(|l| l.locked = on).is_some()+ }++ /// Clipping needs a paint layer below in the same group.+ pub fn set_clipped(&mut self, id: LayerId, on: bool) -> bool {+ if on && !self.can_clip(id) {+ return false;+ }+ self.layer_mut(id).map(|l| l.clipped = on).is_some()+ }++ pub fn rename(&mut self, id: LayerId, name: &str) -> bool {+ let name = name.trim();+ if name.is_empty() {+ return false;+ }+ self.layer_mut(id).map(|l| l.name = name.chars().take(256).collect()).is_some()+ }++ /// A document read from a file, made consistent: sizes in range, at least one layer, a current+ /// layer that exists, settings in range, ids that won't collide.+ pub fn repaired(mut self) -> Document {+ self.width = self.width.clamp(1, MAX_CANVAS_EDGE);+ self.height = self.height.clamp(1, MAX_CANVAS_EDGE);+ self.background = self.background.map(|c| if c.is_finite() { c.clamp(0.0, 1.0) } else { 1.0 });+ self.dpi = if self.dpi.is_finite() { self.dpi.clamp(1.0, 9999.0) } else { default_dpi() };+ self.animation = self.animation.map(crate::animation::Animation::repaired);+ let mut seen = std::collections::HashSet::new();+ self.layers.retain(|l| seen.insert(l.id));+ for l in &mut self.layers {+ l.opacity = if l.opacity.is_finite() { l.opacity.clamp(0.0, 1.0) } else { 1.0 };+ if l.name.trim().is_empty() {+ l.name = "Layer".to_owned();+ }+ }+ let top = self.layers.iter().map(|l| l.id.0).max().unwrap_or(0);+ self.next_id = self.next_id.max(top + 1);+ // masks only just above their layers; parents only groups that exist+ let ids: Vec<LayerId> = self.layers.iter().map(|l| l.id).collect();+ let kinds: Vec<(LayerId, LayerKind)> = self.layers.iter().map(|l| (l.id, l.kind)).collect();+ let kind_of = |id: LayerId| kinds.iter().find(|(i, _)| *i == id).map(|(_, k)| *k);+ let mut keep = Vec::with_capacity(self.layers.len());+ for (i, l) in self.layers.iter().enumerate() {+ let ok = match l.kind {+ LayerKind::Mask => {+ let below = i.checked_sub(1).and_then(|b| ids.get(b)).copied();+ l.parent.is_some() && l.parent == below && below.and_then(kind_of) == Some(LayerKind::Paint)+ }+ _ => true,+ };+ keep.push(ok);+ }+ let mut k = keep.iter();+ self.layers.retain(|_| k.next().copied().unwrap_or(true));+ for l in &mut self.layers {+ if l.kind != LayerKind::Mask && l.parent.and_then(kind_of) != Some(LayerKind::Group) {+ l.parent = None;+ }+ }+ // groups inside themselves are taken out+ for id in ids {+ let mut seen = std::collections::HashSet::new();+ let mut at = Some(id);+ while let Some(a) = at {+ if !seen.insert(a) {+ if let Some(l) = self.layer_mut(a) {+ l.parent = None;+ }+ break;+ }+ at = self.group_of(a);+ }+ }+ self.tidy();+ if self.paint_count() == 0 {+ self.add_layer();+ }+ self.fix_clips();+ if self.layer(self.current).is_none() {+ self.current = self.layers.last().map_or(LayerId(0), |l| l.id);+ }+ let (current, ids): (LayerId, Vec<LayerId>) = (self.current, self.layers.iter().map(|l| l.id).collect());+ self.picked.retain(|p| *p != current && ids.contains(p));+ self+ }++ /// Orders the stack so each group's contents sit just below it and each mask just above its+ /// layer, keeping the order otherwise.+ fn tidy(&mut self) {+ let mut order = Vec::with_capacity(self.layers.len());+ self.emit(None, &mut order, 0);+ let mut old = std::mem::take(&mut self.layers);+ for id in order {+ if let Some(i) = old.iter().position(|l| l.id == id) {+ self.layers.push(old.swap_remove(i));+ }+ }+ }++ /// The ids of `group`'s members in stack order, each group's contents before it.+ fn emit(&self, group: Option<LayerId>, order: &mut Vec<LayerId>, depth: usize) {+ if depth > self.layers.len() {+ return;+ }+ for m in self.members(group) {+ if self.layer(m).is_some_and(|l| l.kind == LayerKind::Group) {+ self.emit(Some(m), order, depth + 1);+ order.push(m);+ } else {+ order.push(m);+ if let Some(mask) = self.layers.iter().find(|l| l.kind == LayerKind::Mask && l.parent == Some(m)) {+ order.push(mask.id);+ }+ }+ }+ }++ /// Every layer id, for checking what the renderer must keep.+ pub fn layer_ids(&self) -> impl Iterator<Item = LayerId> + '_ {+ self.layers.iter().map(|l| l.id)+ }++ /// The layers with pixels of their own (not groups).+ pub fn pixel_layer_ids(&self) -> impl Iterator<Item = LayerId> + '_ {+ self.layers.iter().filter(|l| l.kind != LayerKind::Group).map(|l| l.id)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn new_document_has_one_current_layer() {+ let d = Document::new(0, 99_999);+ assert_eq!((d.width(), d.height()), (1, MAX_CANVAS_EDGE));+ assert_eq!(d.layers().len(), 1);+ assert_eq!(d.layers()[0].name, "Layer 1");+ assert_eq!(d.current(), d.layers()[0].id);+ }++ #[test]+ fn layers_go_above_the_current_one() {+ let mut d = Document::new(10, 10);+ let first = d.current();+ let second = d.add_layer();+ assert!(d.set_current(first));+ let third = d.add_layer();+ let order: Vec<LayerId> = d.layers().iter().map(|l| l.id).collect();+ assert_eq!(order, vec![first, third, second]);+ assert!(!d.set_current(LayerId(999)));+ assert_eq!(d.current(), third);+ }++ #[test]+ fn duplicate_delete_move() {+ let mut d = Document::new(10, 10);+ let a = d.current();+ d.set_opacity(a, 0.5);+ let b = d.duplicate_layer(a).unwrap();+ assert_eq!(d.layer(b).unwrap().opacity, 0.5);+ assert_eq!(d.layer(b).unwrap().name, d.layer(a).unwrap().name);+ assert_eq!(d.current(), b);+ assert!(d.move_layer(b, 0));+ assert_eq!(d.layers()[0].id, b);+ assert!(d.delete_layer(b));+ assert_eq!(d.current(), a);+ assert!(!d.delete_layer(a), "the last layer stays");+ }++ #[test]+ fn clipping_and_merge() {+ let mut d = Document::new(10, 10);+ let base = d.current();+ let mid = d.add_layer();+ let top = d.add_layer();+ assert!(!d.set_clipped(base, true));+ assert!(d.set_clipped(mid, true) && d.set_clipped(top, true));+ assert_eq!(d.clip_base(top), Some(base));+ assert_eq!(d.clip_base(base), None);+ assert_eq!(d.merge_target(top), Some(mid));+ assert_eq!(d.merge_target(base), None);+ assert!(d.finish_merge_down(top));+ assert_eq!(d.current(), mid);+ // moving a clipped layer to the bottom unclips it+ assert!(d.move_layer(mid, 0));+ assert!(!d.layers()[0].clipped);+ }++ #[test]+ fn masks_and_groups() {+ let mut d = Document::new(10, 10);+ let a = d.current();+ let b = d.add_layer();+ // a mask sits just above its layer and becomes current+ let m = d.add_mask(b).unwrap();+ assert_eq!(d.mask_of(b), Some(m));+ assert_eq!(d.current(), m);+ assert!(d.add_mask(b).is_none() && d.add_mask(m).is_none());+ // a new layer goes above the mask, not between+ let c = d.add_layer();+ assert_eq!(d.index_of(c), Some(3));+ assert_eq!(d.layer(c).unwrap().name, "Layer 4", "the mask counts in the number");+ // combine down: c and b (with its mask) in a group above them+ let g = d.combine_down(c).unwrap();+ assert_eq!(d.index_of(g), Some(4));+ assert_eq!(d.contents(g), vec![b, m, c]);+ assert_eq!(d.members(Some(g)), vec![b, c]);+ assert_eq!(d.group_of(m), Some(g));+ // merging needs plain neighbours in the same group; clipping a paint layer below+ assert_eq!(d.merge_target(c), None);+ assert!(d.can_clip(c) && !d.can_clip(b));+ // moved out to the bottom it leaves the group, and its mask comes with it+ assert!(d.move_layer(b, 0));+ assert_eq!(ids(&d), vec![b, m, a, c, g]);+ assert_eq!(d.group_of(b), None);+ assert_eq!(d.contents(g), vec![c]);+ // moved back under the group's entry it joins it+ assert!(d.move_layer(b, 2));+ assert_eq!(d.group_of(b), Some(g));+ // deleting a layer takes its mask; deleting the group takes everything in it+ assert!(d.delete_layer(g));+ assert_eq!(d.layers().len(), 1);+ assert_eq!(d.layers()[0].id, a);+ assert!(!d.delete_layer(a), "the last paint layer stays");+ }++ #[test]+ fn the_layer_cap_follows_the_canvas_size() {+ assert_eq!(Document::new(2048, 2048).layer_cap(), 128);+ assert_eq!(Document::new(16384, 16384).layer_cap(), 2);+ let d = Document::new(16384, 16384);+ assert!(d.has_room(1) && !d.has_room(2));+ }++ #[test]+ fn text_layers_keep_their_text_until_rasterized() {+ let mut d = Document::new(100, 100);+ let base = d.current();+ let text = LayerText {+ text: "\n Hello there\nsecond".to_owned(),+ size: f32::NAN,+ opacity: 3.0,+ ..LayerText::default()+ };+ let t = d.add_text_layer(text);+ assert_eq!(d.current(), t);+ let layer = d.layer(t).unwrap();+ assert_eq!(layer.name, "Hello there");+ let kept = layer.text.clone().unwrap();+ assert_eq!((kept.size, kept.opacity), (64.0, 1.0));+ assert!(!d.set_text(base, kept.clone()), "an ordinary layer has no text");+ assert!(d.set_text(t, LayerText { text: "Bye".to_owned(), ..kept }));+ assert_eq!(d.layer(t).unwrap().name, "Bye");+ // saved and read back+ let back: Document = serde_json::from_str(&serde_json::to_string(&d).unwrap()).unwrap();+ assert_eq!(back.layer(t).unwrap().text, d.layer(t).unwrap().text);+ // a duplicate is a text layer too; merging another layer into it rasterizes it+ let copy = d.duplicate_layer(t).unwrap();+ assert!(d.layer(copy).unwrap().text.is_some());+ assert!(d.finish_merge_down(copy));+ assert!(d.layer(t).unwrap().text.is_none());+ assert!(!d.rasterize(t));+ }++ fn ids(d: &Document) -> Vec<LayerId> {+ d.layers().iter().map(|l| l.id).collect()+ }++ #[test]+ fn groups_nest_ungroup_and_flatten() {+ let mut d = Document::new(10, 10);+ let a = d.current();+ let b = d.add_layer();+ let g = d.combine_down(b).unwrap();+ assert_eq!(ids(&d), vec![a, b, g]);+ // a layer above the group, combined down, joins it at its top+ assert!(d.set_current(g));+ let c = d.add_layer();+ assert_eq!(d.layer(c).unwrap().name, "Layer 4", "the group counts in the number");+ assert_eq!(d.group_of(c), None);+ assert_eq!(d.combine_down(c), Some(g));+ assert_eq!(ids(&d), vec![a, b, c, g]);+ // inside, combining makes a group in the group+ let inner = d.combine_down(c).unwrap();+ assert_eq!(ids(&d), vec![a, b, c, inner, g]);+ assert_eq!((d.depth(c), d.depth(inner), d.depth(a), d.max_depth()), (2, 1, 1, 2));+ assert_eq!(d.members(Some(g)), vec![a, inner]);+ assert_eq!((d.below(inner), d.merge_target(inner)), (Some(a), Some(a)));+ assert_eq!((d.below(b), d.merge_target(b)), (None, None));+ // a group moves with everything in it+ assert!(d.move_layer(inner, 0));+ assert_eq!(ids(&d), vec![b, c, inner, a, g]);+ assert_eq!(d.group_of(inner), Some(g));+ // ungrouping lifts the members one level; the top one becomes current+ assert!(d.set_current(g));+ assert!(d.ungroup(g));+ assert_eq!(ids(&d), vec![b, c, inner, a]);+ assert_eq!((d.current(), d.group_of(inner), d.depth(c)), (a, None, 1));+ // flattening leaves one layer where the group was, named after its bottom layer+ let flat = d.flatten(inner).unwrap();+ assert_eq!(ids(&d), vec![flat, a]);+ assert_eq!(d.layer(flat).unwrap().name, "Layer 2");+ assert_eq!(d.current(), flat);+ assert!(d.flatten(flat).is_none());+ // a group duplicates with everything in it; a layer with its mask+ let g = d.combine_down(a).unwrap();+ let m = d.add_mask(a).unwrap();+ let (copy, pairs) = d.duplicate(g).unwrap();+ assert_eq!(d.members(Some(copy)).len(), 2);+ assert_eq!(pairs.len(), 3);+ assert!(pairs.contains(&(m, d.mask_of(d.members(Some(copy))[1]).unwrap())));+ assert_eq!(d.index_of(copy), Some(d.layers().len() - 1));+ }++ #[test]+ fn repair_orders_groups_and_breaks_loops() {+ let mut d = Document::new(10, 10);+ let a = d.current();+ let b = d.add_layer();+ let g = d.combine_down(b).unwrap();+ // contents put back under their group, in their order+ let mut scrambled = d.clone();+ scrambled.layers.reverse();+ assert_eq!(ids(&scrambled.repaired()), vec![b, a, g]);+ // two groups inside each other+ assert!(d.set_current(g));+ let c = d.add_layer();+ let e = d.add_layer();+ let h = d.combine_down(e).unwrap();+ assert_eq!(ids(&d), vec![a, b, g, c, e, h]);+ let mut looped = d.clone();+ for l in &mut looped.layers {+ if l.id == g {+ l.parent = Some(h);+ }+ if l.id == h {+ l.parent = Some(g);+ }+ }+ let fixed = looped.repaired();+ assert_eq!(fixed.layers().len(), 6);+ assert!(fixed.max_depth() <= 2);+ }++ #[test]+ fn repair_drops_stray_masks_and_parents() {+ let mut d = Document::new(10, 10);+ let a = d.current();+ let m = d.add_mask(a).unwrap();+ let mut broken = d.clone();+ broken.layers.swap(0, 1);+ let fixed = broken.repaired();+ assert!(fixed.layer(m).is_none());+ let mut orphan = d.clone();+ orphan.layers[0].parent = Some(LayerId(999));+ assert_eq!(orphan.repaired().layers()[0].parent, None);+ }++ #[test]+ fn saves_and_repairs() {+ let mut d = Document::new(300, 200);+ let a = d.current();+ d.add_layer();+ d.set_blend(a, BlendMode::Multiply);+ let json = serde_json::to_string(&d).unwrap();+ let back: Document = serde_json::from_str(&json).unwrap();+ assert_eq!(back.clone().repaired(), d);+ // a broken file is made usable+ let broken = json.replace("\"current\":2", "\"current\":77").replace("\"width\":300", "\"width\":0");+ let fixed = serde_json::from_str::<Document>(&broken).unwrap().repaired();+ assert_eq!(fixed.width(), 1);+ assert!(fixed.layer(fixed.current()).is_some());+ let id = fixed.clone().add_layer();+ assert!(fixed.layer(id).is_none(), "new ids don't collide");+ }++ #[test]+ fn blend_ids_round_trip_and_settings_validate() {+ for m in BlendMode::ALL {+ assert_eq!(BlendMode::from_id(m.id()), Some(m));+ }+ assert_eq!(BlendMode::ALL.iter().map(|m| m.id()).max(), Some(BlendMode::MAX_ID));+ let mut d = Document::new(10, 10);+ let a = d.current();+ assert!(!d.set_opacity(a, f32::NAN));+ assert!(d.set_opacity(a, 3.0));+ assert_eq!(d.layer(a).unwrap().opacity, 1.0);+ assert!(!d.rename(a, " "));+ assert!(d.rename(a, " Sketch "));+ assert_eq!(d.layer(a).unwrap().name, "Sketch");+ }++ /// A stack of `n` paint layers named 1..n, bottom first; the top one current.+ fn stack(n: usize) -> (Document, Vec<LayerId>) {+ let mut d = Document::new(10, 10);+ let mut ids = vec![d.current()];+ for _ in 1..n {+ ids.push(d.add_layer());+ }+ for (i, id) in ids.iter().enumerate() {+ d.rename(*id, &(i + 1).to_string());+ }+ (d, ids)+ }++ fn names(d: &Document) -> Vec<String> {+ d.layers().iter().map(|l| l.name.clone()).collect()+ }++ #[test]+ fn picks_toggle_and_never_hold_the_current_layer() {+ let (mut d, ids) = stack(4);+ let [a, b, c, top]: [LayerId; 4] = ids.try_into().unwrap();+ assert!(!d.toggle_pick(top));+ assert!(d.toggle_pick(a) && d.toggle_pick(c));+ assert_eq!(d.picked(), [a, c]);+ assert_eq!(d.chosen(), [a, c, top]);+ assert!(d.toggle_pick(c));+ assert_eq!(d.picked(), [a]);+ assert!(d.pick_all());+ assert_eq!(d.picked(), [a, b, c]);+ assert!(!d.pick_all());+ // a picked layer made current is no longer a pick+ d.set_current(b);+ assert_eq!(d.picked(), [a, c]);+ assert!(d.clear_picks() && !d.clear_picks());+ }++ #[test]+ fn picked_layers_group_where_the_top_one_was() {+ let (mut d, ids) = stack(5);+ let [one, _, three, _, five]: [LayerId; 5] = ids.try_into().unwrap();+ d.set_current(three);+ d.toggle_pick(one);+ d.toggle_pick(five);+ let g = d.group_chosen().unwrap();+ assert_eq!(names(&d), ["2", "4", "1", "3", "5", "New group"]);+ assert!([one, three, five].iter().all(|l| d.group_of(*l) == Some(g)));+ assert_eq!(d.current(), three);+ assert!(d.picked().is_empty());+ }++ #[test]+ fn picked_layers_duplicate_together_above_the_top_one() {+ let (mut d, ids) = stack(4);+ let [one, _, three, _]: [LayerId; 4] = ids.try_into().unwrap();+ d.set_current(three);+ d.toggle_pick(one);+ let pairs = d.duplicate_chosen().unwrap();+ assert_eq!(names(&d), ["1", "2", "3", "1", "3", "4"]);+ assert_eq!(pairs.len(), 2);+ // the copies are what is chosen now+ let copies: Vec<LayerId> = pairs.iter().map(|(_, c)| *c).collect();+ assert_eq!(d.chosen(), copies);+ assert_eq!(d.layer(d.current()).unwrap().name, "3");+ }++ #[test]+ fn picked_layers_move_together() {+ let (mut d, ids) = stack(5);+ let [one, _, three, _, _]: [LayerId; 5] = ids.try_into().unwrap();+ d.set_current(three);+ d.toggle_pick(one);+ // to the top of what is left: 2, 4, 5+ assert!(d.move_chosen(3));+ assert_eq!(names(&d), ["2", "4", "5", "1", "3"]);+ assert!(d.move_chosen(0));+ assert_eq!(names(&d), ["1", "3", "2", "4", "5"]);+ }++ #[test]+ fn picked_layers_delete_and_merge_into_the_bottom_one() {+ let (mut d, ids) = stack(4);+ let [one, two, three, four]: [LayerId; 4] = ids.try_into().unwrap();+ d.set_current(three);+ d.toggle_pick(one);+ assert_eq!(d.merge_chosen_plan(), Some((one, vec![three])));+ assert!(d.finish_merge_chosen(one, &[three]));+ assert_eq!(names(&d), ["1", "2", "4"]);+ assert_eq!(d.current(), one);+ d.toggle_pick(two);+ d.set_locked(four, true);+ d.toggle_pick(four);+ // a locked layer stops a merge, and stays when the rest is deleted+ assert_eq!(d.merge_chosen_plan(), None);+ assert!(d.delete_chosen());+ assert_eq!(names(&d), ["4"]);+ }+}diff --git a/crates/engine/src/formats.rs b/crates/engine/src/formats.rsnew file mode 100644index 0000000..4f276ea--- /dev/null+++ b/crates/engine/src/formats.rs@@ -0,0 +1,1187 @@+//! Writing pictures for other apps: layered PSD, TIFF and PDF. Each takes straight-alpha RGBA8+//! pixels, rows top to bottom, and returns the file's bytes. A CMYK canvas's files keep its+//! press's inks: its pixels go through a table to them (`press`).++use crate::cms::Lut;+use crate::document::BlendMode;++/// A canvas's resolution unless it says otherwise, dots per inch.+pub const DPI: u32 = 132;++/// One layer as a PSD shows it.+pub struct PsdLayer<'a> {+ pub name: &'a str,+ pub kind: PsdKind<'a>,+ pub opacity: f32,+ pub visible: bool,+ pub blend: BlendMode,+ /// Clipped to the layer below.+ pub clipped: bool,+}++pub enum PsdKind<'a> {+ /// Pixels (the canvas's size), and a mask (its grey, the canvas's size) if it has one.+ Pixels {+ rgba: &'a [u8],+ mask: Option<&'a [u8]>,+ },+ /// The start of a group: the layers after it, up to its [`PsdKind::GroupEnd`], are in it.+ GroupStart {+ open: bool,+ },+ GroupEnd,+}++/// A layered PSD: `layers` top first (groups as a start, their layers, then an end), and the+/// flattened picture; `icc` is the colour profile it carries (none if empty). With a `press`+/// table it is a CMYK PSD (inks kept inverted, as PSDs keep them; the picture flattened on white).+pub fn psd(+ width: u32,+ height: u32,+ dpi: f32,+ icc: &[u8],+ layers: &[PsdLayer<'_>],+ composite: &[u8],+ press: Option<&Lut>,+) -> Vec<u8> {+ let fixed = (dpi.clamp(1.0, 9999.0) * 65536.0).round() as u32;+ let mut out = Vec::new();+ out.extend_from_slice(b"8BPS");+ put16(&mut out, 1);+ out.extend_from_slice(&[0; 6]);+ put16(&mut out, 4);+ put32(&mut out, height);+ put32(&mut out, width);+ put16(&mut out, 8);+ put16(&mut out, if press.is_some() { 4 } else { 3 });+ // no colour mode data+ put32(&mut out, 0);+ // image resources: the resolution+ let mut resources = Vec::new();+ resources.extend_from_slice(b"8BIM");+ put16(&mut resources, 0x03ED);+ put16(&mut resources, 0);+ put32(&mut resources, 16);+ for _ in 0..2 {+ put32(&mut resources, fixed);+ put16(&mut resources, 1);+ put16(&mut resources, 1);+ }+ // and the colour profile+ if !icc.is_empty() {+ resources.extend_from_slice(b"8BIM");+ put16(&mut resources, 0x040F);+ put16(&mut resources, 0);+ put32(&mut resources, icc.len() as u32);+ resources.extend_from_slice(icc);+ if icc.len() % 2 == 1 {+ resources.push(0);+ }+ }+ put32(&mut out, resources.len() as u32);+ out.extend_from_slice(&resources);++ // layers, listed bottom first, a group as its end marker, its layers, then its start+ let mut records = Vec::new();+ let mut channels = Vec::new();+ let count = layers.len();+ for layer in layers.iter().rev() {+ record(&mut records, &mut channels, width, height, layer, press);+ }+ let mut info = Vec::new();+ put16(&mut info, (count as i16).wrapping_neg() as u16);+ info.extend_from_slice(&records);+ info.extend_from_slice(&channels);+ if info.len() % 2 == 1 {+ info.push(0);+ }+ let mut section = Vec::new();+ put32(&mut section, info.len() as u32);+ section.extend_from_slice(&info);+ // no global mask+ put32(&mut section, 0);+ put32(&mut out, section.len() as u32);+ out.extend_from_slice(§ion);++ // the flattened picture: four channels, packed (RGBA, or the inks on white)+ let planes: Vec<Vec<u8>> = match press {+ None => (0..4).map(|c| plane(composite, c)).collect(),+ Some(table) => {+ let inks = inks(composite, table, true);+ (0..4).map(|c| inks.iter().skip(c).step_by(4).map(|v| 255 - v).collect()).collect()+ }+ };+ put16(&mut out, 1);+ let rows: Vec<Vec<Vec<u8>>> =+ planes.iter().map(|p| p.chunks(width.max(1) as usize).map(packbits).collect()).collect();+ for plane in &rows {+ for row in plane {+ put16(&mut out, row.len() as u16);+ }+ }+ for plane in &rows {+ for row in plane {+ out.extend_from_slice(row);+ }+ }+ out+}++/// A layer's record (into `records`) and its channels' pixels (into `channels`): RGB, or the+/// inks `press` gives (inverted).+fn record(+ records: &mut Vec<u8>,+ channels: &mut Vec<u8>,+ width: u32,+ height: u32,+ layer: &PsdLayer<'_>,+ press: Option<&Lut>,+) {+ let ids: &[i16] = if press.is_some() { &[-1, 0, 1, 2, 3] } else { &[-1, 0, 1, 2] };+ let (rect, data): ([u32; 4], Vec<(i16, Vec<u8>)>) = match &layer.kind {+ PsdKind::Pixels { rgba, mask } => {+ let rect = bounds(rgba, width, height).unwrap_or([0, 0, 0, 0]);+ // five bytes a pixel for inks: the four inverted, then alpha+ let (pixels, stride) = match press {+ None => (rgba.to_vec(), 4),+ Some(table) => {+ let inks = inks(rgba, table, false);+ let mut five = Vec::with_capacity(rgba.len() / 4 * 5);+ for (ink, px) in inks.as_chunks::<4>().0.iter().zip(rgba.as_chunks::<4>().0) {+ five.extend(ink.map(|v| 255 - v));+ five.push(px[3]);+ }+ (five, 5)+ }+ };+ let mut data: Vec<(i16, Vec<u8>)> = ids+ .iter()+ .map(|&id| (id, packed(&cropped_plane(&pixels, width, rect, stride, channel(id, stride)), rect)))+ .collect();+ if let Some(m) = mask {+ data.push((-2, packed(m, [0, 0, width, height])));+ }+ (rect, data)+ }+ // groups have no pixels: empty channels+ _ => ([0, 0, 0, 0], ids.iter().map(|&id| (id, vec![0, 0])).collect()),+ };+ let [left, top, right, bottom] = rect;+ for v in [top, left, bottom, right] {+ put32(records, v);+ }+ put16(records, data.len() as u16);+ for (id, bytes) in &data {+ put16(records, *id as u16);+ put32(records, bytes.len() as u32);+ }+ records.extend_from_slice(b"8BIM");+ let group_start = matches!(layer.kind, PsdKind::GroupStart { .. });+ records.extend_from_slice(if group_start && layer.blend == BlendMode::Normal {+ b"pass"+ } else {+ blend_key(layer.blend)+ });+ records.push((layer.opacity.clamp(0.0, 1.0) * 255.0).round() as u8);+ records.push(u8::from(layer.clipped));+ // bit 1: hidden; bit 3 and 4: the record describes a group divider+ let mut flags = if layer.visible { 0 } else { 2 };+ if !matches!(layer.kind, PsdKind::Pixels { .. }) {+ flags |= 0x18;+ }+ records.push(flags);+ records.push(0);+ let mut extra = Vec::new();+ match &layer.kind {+ PsdKind::Pixels { mask: Some(_), .. } => {+ put32(&mut extra, 20);+ for v in [0, 0, height, width] {+ put32(&mut extra, v);+ }+ extra.extend_from_slice(&[255, 0, 0, 0]);+ }+ _ => put32(&mut extra, 0),+ }+ // no blending ranges+ put32(&mut extra, 0);+ let name = if matches!(layer.kind, PsdKind::GroupEnd) { "</Layer group>" } else { layer.name };+ let latin: Vec<u8> = name.chars().map(|c| if c.is_ascii() { c as u8 } else { b'?' }).take(255).collect();+ extra.push(latin.len() as u8);+ extra.extend_from_slice(&latin);+ while extra.len() % 4 != 0 {+ extra.push(0);+ }+ // the name in full+ let units: Vec<u16> = name.encode_utf16().collect();+ let mut luni = Vec::new();+ put32(&mut luni, units.len() as u32);+ for u in &units {+ put16(&mut luni, *u);+ }+ if luni.len() % 2 == 1 {+ luni.push(0);+ }+ tagged(&mut extra, b"luni", &luni);+ // a group's start and end+ match layer.kind {+ PsdKind::GroupStart { open } => {+ let mut lsct = Vec::new();+ put32(&mut lsct, if open { 1 } else { 2 });+ tagged(&mut extra, b"lsct", &lsct);+ }+ PsdKind::GroupEnd => {+ let mut lsct = Vec::new();+ put32(&mut lsct, 3);+ tagged(&mut extra, b"lsct", &lsct);+ }+ PsdKind::Pixels { .. } => {}+ }+ put32(records, extra.len() as u32);+ records.extend_from_slice(&extra);+ for (_, bytes) in data {+ channels.extend_from_slice(&bytes);+ }+}++fn tagged(out: &mut Vec<u8>, key: &[u8; 4], data: &[u8]) {+ out.extend_from_slice(b"8BIM");+ out.extend_from_slice(key);+ put32(out, data.len() as u32);+ out.extend_from_slice(data);+}++/// Which byte of a pixel (`stride` bytes, alpha last) a PSD channel id is.+fn channel(id: i16, stride: usize) -> usize {+ match id {+ 0 => 0,+ 1 => 1,+ 2 => 2,+ 3 if stride > 4 => 3,+ _ => stride - 1,+ }+}++/// The inks (cyan, magenta, yellow, black; 0 for none) `table` gives each of the straight RGBA+/// `pixels`, a pixel's colour first laid on white if `on_white`.+fn inks(pixels: &[u8], table: &Lut, on_white: bool) -> Vec<u8> {+ let mut out = Vec::with_capacity(pixels.len());+ for &[r, g, b, a] in pixels.as_chunks::<4>().0 {+ // nothing there: no ink+ if a == 0 && !on_white {+ out.extend([0; 4]);+ continue;+ }+ let a = if on_white { f32::from(a) / 255.0 } else { 1.0 };+ let c = |v: u8| (f32::from(v) / 255.0) * a + (1.0 - a);+ let ink = table.apply([c(r), c(g), c(b)]);+ out.extend((0..4).map(|k| (ink.get(k).copied().unwrap_or(0.0).clamp(0.0, 1.0) * 255.0).round() as u8));+ }+ out+}++/// One byte of every pixel.+fn plane(rgba: &[u8], c: usize) -> Vec<u8> {+ rgba.as_chunks::<4>().0.iter().map(|p| p.get(c).copied().unwrap_or(0)).collect()+}++/// Byte `c` of every pixel (`stride` bytes) in `rect` (left, top, right, bottom).+fn cropped_plane(pixels: &[u8], width: u32, [left, top, right, bottom]: [u32; 4], stride: usize, c: usize) -> Vec<u8> {+ let mut out = Vec::with_capacity(((right - left) * (bottom - top)) as usize);+ for y in top..bottom {+ for x in left..right {+ out.push(pixels.get((y * width + x) as usize * stride + c).copied().unwrap_or(0));+ }+ }+ out+}++/// A channel's pixels in `rect`, packed row by row with their sizes first.+fn packed(plane: &[u8], [left, top, right, bottom]: [u32; 4]) -> Vec<u8> {+ let w = (right - left) as usize;+ let mut out = Vec::new();+ put16(&mut out, 1);+ if w == 0 || bottom <= top {+ return out;+ }+ let rows: Vec<Vec<u8>> = plane.chunks(w).take((bottom - top) as usize).map(packbits).collect();+ for row in &rows {+ put16(&mut out, row.len() as u16);+ }+ for row in rows {+ out.extend_from_slice(&row);+ }+ out+}++/// The smallest box (left, top, right, bottom) around pixels with any alpha.+fn bounds(rgba: &[u8], width: u32, height: u32) -> Option<[u32; 4]> {+ let mut b: Option<[u32; 4]> = None;+ for y in 0..height {+ for x in 0..width {+ if rgba.get(((y * width + x) * 4 + 3) as usize).is_some_and(|a| *a > 0) {+ b = Some(match b {+ Some([l, t, r, bt]) => [l.min(x), t.min(y), r.max(x + 1), bt.max(y + 1)],+ None => [x, y, x + 1, y + 1],+ });+ }+ }+ }+ b+}++/// PackBits: runs of a repeated byte, and stretches of different ones, at most 128 each.+fn packbits(row: &[u8]) -> Vec<u8> {+ let mut out = Vec::with_capacity(row.len() + row.len() / 128 + 1);+ let mut i = 0;+ while i < row.len() {+ let Some(&b) = row.get(i) else { break };+ let run = row.get(i..).map_or(1, |rest| rest.iter().take(128).take_while(|&&v| v == b).count());+ if run >= 2 {+ out.push((1i16 - run as i16) as u8);+ out.push(b);+ i += run;+ } else {+ // up to the next run of three or the stretch's limit+ let start = i;+ while i < row.len() && i - start < 128 {+ let three = row.get(i..i + 3).is_some_and(|w| w.iter().all(|v| Some(v) == w.first()));+ if three {+ break;+ }+ i += 1;+ }+ if i == start {+ i += 1;+ }+ out.push((i - start - 1) as u8);+ out.extend_from_slice(row.get(start..i).unwrap_or_default());+ }+ }+ out+}++/// The four letters PSD names a blend mode by.+fn blend_key(mode: BlendMode) -> &'static [u8; 4] {+ match mode {+ BlendMode::Normal => b"norm",+ BlendMode::Multiply => b"mul ",+ // the format has no shade: darken is nearest+ BlendMode::Darken | BlendMode::Shade => b"dark",+ BlendMode::ColorBurn => b"idiv",+ BlendMode::LinearBurn => b"lbrn",+ BlendMode::DarkerColor => b"dkCl",+ BlendMode::Lighten => b"lite",+ BlendMode::Screen => b"scrn",+ BlendMode::ColorDodge => b"div ",+ BlendMode::Add => b"lddg",+ BlendMode::LighterColor => b"lgCl",+ BlendMode::Overlay => b"over",+ BlendMode::SoftLight => b"sLit",+ BlendMode::HardLight => b"hLit",+ BlendMode::VividLight => b"vLit",+ BlendMode::LinearLight => b"lLit",+ BlendMode::PinLight => b"pLit",+ BlendMode::HardMix => b"hMix",+ BlendMode::Difference => b"diff",+ BlendMode::Exclusion => b"smud",+ BlendMode::Subtract => b"fsub",+ BlendMode::Divide => b"fdiv",+ BlendMode::Hue => b"hue ",+ BlendMode::Saturation => b"sat ",+ BlendMode::Color => b"colr",+ BlendMode::Luminosity => b"lum ",+ }+}++/// A TIFF: RGBA with straight alpha, compressed with Deflate, at `dpi`, carrying the colour+/// profile `icc` (none if empty).+pub fn tiff(width: u32, height: u32, dpi: f32, icc: &[u8], rgba: &[u8]) -> Vec<u8> {+ write_tiff(width, height, dpi, icc, rgba, false)+}++/// A CMYK TIFF: the picture flattened on white and turned into the inks `press` gives, carrying+/// the press's profile `icc`.+pub fn tiff_cmyk(width: u32, height: u32, dpi: f32, icc: &[u8], rgba: &[u8], press: &Lut) -> Vec<u8> {+ write_tiff(width, height, dpi, icc, &inks(rgba, press, true), true)+}++/// A TIFF of four bytes a pixel: RGBA, or (`cmyk`) four inks with no alpha.+fn write_tiff(width: u32, height: u32, dpi: f32, icc: &[u8], pixels: &[u8], cmyk: bool) -> Vec<u8> {+ let tenths = (dpi.clamp(1.0, 9999.0) * 10.0).round() as u32;+ let data = miniz_oxide::deflate::compress_to_vec_zlib(pixels, 6);+ // header, then the pixels, then the bits per sample, the resolutions and the directory+ let mut out = Vec::new();+ out.extend_from_slice(b"II");+ out.extend_from_slice(&42u16.to_le_bytes());+ out.extend_from_slice(&0u32.to_le_bytes());+ let pixels_at = out.len() as u32;+ out.extend_from_slice(&data);+ if out.len() % 2 == 1 {+ out.push(0);+ }+ let bits_at = out.len() as u32;+ for _ in 0..4 {+ out.extend_from_slice(&8u16.to_le_bytes());+ }+ let res_at = out.len() as u32;+ for _ in 0..2 {+ out.extend_from_slice(&tenths.to_le_bytes());+ out.extend_from_slice(&10u32.to_le_bytes());+ }+ let icc_at = out.len() as u32;+ out.extend_from_slice(icc);+ if out.len() % 2 == 1 {+ out.push(0);+ }+ let dir_at = out.len() as u32;+ if let Some(slot) = out.get_mut(4..8) {+ slot.copy_from_slice(&dir_at.to_le_bytes());+ }+ // (tag, type, count, value): type 3 short, 4 long, 5 rational, 7 bytes+ let mut entries: Vec<(u16, u16, u32, u32)> = vec![+ (256, 4, 1, width),+ (257, 4, 1, height),+ (258, 3, 4, bits_at),+ (259, 3, 1, 8),+ // RGB, or separated inks+ (262, 3, 1, if cmyk { 5 } else { 2 }),+ (273, 4, 1, pixels_at),+ (277, 3, 1, 4),+ (278, 4, 1, height),+ (279, 4, 1, data.len() as u32),+ (282, 5, 1, res_at),+ (283, 5, 1, res_at + 8),+ (296, 3, 1, 2),+ ];+ if cmyk {+ // the inks are cyan, magenta, yellow and black+ entries.push((332, 3, 1, 1));+ } else {+ // the fourth sample is straight alpha+ entries.push((338, 3, 1, 2));+ }+ if !icc.is_empty() {+ entries.push((34675, 7, icc.len() as u32, icc_at));+ }+ out.extend_from_slice(&(entries.len() as u16).to_le_bytes());+ for (tag, kind, count, value) in entries {+ out.extend_from_slice(&tag.to_le_bytes());+ out.extend_from_slice(&kind.to_le_bytes());+ out.extend_from_slice(&count.to_le_bytes());+ out.extend_from_slice(&value.to_le_bytes());+ }+ out.extend_from_slice(&0u32.to_le_bytes());+ out+}++/// A PDF with a page for each picture (straight-alpha RGBA, all `width` × `height`), each page+/// the picture's size at `dpi`; the pictures' colours are in the profile `icc` (if not empty).+/// At `quality` 100 the pictures are kept exactly; below, their colours are JPEG at that quality+/// (their alpha still exact). With a `press` table the pages are its inks, flattened on white,+/// as CMYK JPEG at `quality` (`icc` then the press's profile).+pub fn pdf(+ width: u32,+ height: u32,+ dpi: f32,+ icc: &[u8],+ pages: &[&[u8]],+ quality: u8,+ press: Option<&Lut>,+) -> Vec<u8> {+ let dpi = dpi.clamp(1.0, 9999.0);+ let (pw, ph) = (width as f32 * 72.0 / dpi, height as f32 * 72.0 / dpi);+ let mut objects: Vec<Vec<u8>> = Vec::new();+ // 1: the catalog, 2: the page tree; then per page: page, contents, image, its alpha+ let first = 3;+ let kids: Vec<String> = (0..pages.len()).map(|i| format!("{} 0 R", first + i * 4)).collect();+ objects.push(b"<< /Type /Catalog /Pages 2 0 R >>".to_vec());+ objects.push(format!("<< /Type /Pages /Kids [{}] /Count {} >>", kids.join(" "), pages.len()).into_bytes());+ // the colour profile goes after the pages+ let device = if press.is_some() { "/DeviceCMYK" } else { "/DeviceRGB" };+ let colours =+ if icc.is_empty() { device.to_owned() } else { format!("[/ICCBased {} 0 R]", first + pages.len() * 4) };+ for (i, rgba) in pages.iter().enumerate() {+ let n = first + i * 4;+ objects.push(+ format!(+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {pw:.2} {ph:.2}] /Contents {} 0 R /Resources << /XObject << /Im0 {} 0 R >> >> >>",+ n + 1,+ n + 2+ )+ .into_bytes(),+ );+ let draw = format!("q {pw:.2} 0 0 {ph:.2} 0 0 cm /Im0 Do Q");+ objects.push(stream(&format!("<< /Length {} >>", draw.len()), draw.as_bytes()));+ if let Some(table) = press {+ let jpg = crate::jpeg::encode_cmyk(&inks(rgba, table, true), width, height, quality.max(1));+ objects.push(stream(+ &format!(+ "<< /Type /XObject /Subtype /Image /Width {width} /Height {height} /Interpolate true /ColorSpace {colours} /Decode [1 0 1 0 1 0 1 0] /BitsPerComponent 8 /Filter /DCTDecode /Length {} >>",+ jpg.len()+ ),+ &jpg,+ ));+ // no alpha: kept so the objects keep their numbers+ objects.push(b"null".to_vec());+ continue;+ }+ let mut rgb = Vec::with_capacity(rgba.len() / 4 * 3);+ for &[r, g, b, _] in rgba.as_chunks::<4>().0 {+ rgb.extend_from_slice(&[r, g, b]);+ }+ let alpha = plane(rgba, 3);+ let (rgb, filter) = if quality >= 100 {+ (miniz_oxide::deflate::compress_to_vec_zlib(&rgb, 6), "FlateDecode")+ } else {+ (crate::jpeg::encode(&rgb, width, height, quality), "DCTDecode")+ };+ let alpha = miniz_oxide::deflate::compress_to_vec_zlib(&alpha, 6);+ objects.push(stream(+ &format!(+ "<< /Type /XObject /Subtype /Image /Width {width} /Height {height} /ColorSpace {colours} /BitsPerComponent 8 /Filter /{filter} /SMask {} 0 R /Length {} >>",+ n + 3,+ rgb.len()+ ),+ &rgb,+ ));+ objects.push(stream(+ &format!(+ "<< /Type /XObject /Subtype /Image /Width {width} /Height {height} /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>",+ alpha.len()+ ),+ &alpha,+ ));+ }+ if !icc.is_empty() {+ let n = if press.is_some() { 4 } else { 3 };+ objects.push(stream(&format!("<< /N {n} /Alternate {device} /Length {} >>", icc.len()), icc));+ }+ let mut out = b"%PDF-1.4\n%\xE2\xE3\xCF\xD3\n".to_vec();+ let mut offsets = Vec::with_capacity(objects.len());+ for (i, body) in objects.iter().enumerate() {+ offsets.push(out.len());+ out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());+ out.extend_from_slice(body);+ out.extend_from_slice(b"\nendobj\n");+ }+ let xref = out.len();+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes());+ for o in offsets {+ out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());+ }+ out.extend_from_slice(+ format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes(),+ );+ out+}++fn stream(dict: &str, data: &[u8]) -> Vec<u8> {+ let mut out = dict.as_bytes().to_vec();+ out.extend_from_slice(b"\nstream\n");+ out.extend_from_slice(data);+ out.extend_from_slice(b"\nendstream");+ out+}++/// An animated GIF: `frames` (straight-alpha RGBA, all `width` × `height`) shown `delay_cs`+/// hundredths of a second each, looping forever. See [`GifWriter`].+pub fn gif(width: u32, height: u32, frames: &[&[u8]], delay_cs: u16) -> Vec<u8> {+ let mut g = GifWriter::new(width, height);+ for rgba in frames {+ g.frame(rgba, delay_cs, false);+ }+ g.finish()+}++/// An animated GIF written a frame at a time, looping forever. Each frame gets its own+/// 255-colour palette; a pixel under half opaque is transparent.+pub struct GifWriter {+ out: Vec<u8>,+ width: u16,+ height: u16,+}++impl GifWriter {+ /// A GIF `width` × `height` (each 1 to 65535).+ pub fn new(width: u32, height: u32) -> GifWriter {+ let (w, h) = (width.clamp(1, 65535) as u16, height.clamp(1, 65535) as u16);+ let mut out = b"GIF89a".to_vec();+ out.extend_from_slice(&w.to_le_bytes());+ out.extend_from_slice(&h.to_le_bytes());+ // no global colour table+ out.extend_from_slice(&[0x00, 0, 0]);+ // loop forever+ out.extend_from_slice(&[0x21, 0xFF, 11]);+ out.extend_from_slice(b"NETSCAPE2.0");+ out.extend_from_slice(&[3, 1, 0, 0, 0]);+ GifWriter { out, width: w, height: h }+ }++ /// Adds a frame (straight-alpha RGBA, the GIF's size) shown `delay_cs` hundredths of a+ /// second; `dither` spreads each pixel's palette error to its neighbours.+ pub fn frame(&mut self, rgba: &[u8], delay_cs: u16, dither: bool) {+ let (w, h) = (self.width, self.height);+ let pixels = rgba.as_chunks::<4>().0;+ let (palette, used) = palette(pixels, usize::from(w) * usize::from(h));+ let indices =+ if dither { dithered(pixels, usize::from(w), &palette, used) } else { nearest_all(pixels, &palette, used) };+ let out = &mut self.out;+ // the frame clears to transparent after it shows; index 255 is transparent+ out.extend_from_slice(&[0x21, 0xF9, 4, 0b0000_1001]);+ out.extend_from_slice(&delay_cs.to_le_bytes());+ out.extend_from_slice(&[TRANSPARENT, 0]);+ out.push(0x2C);+ out.extend_from_slice(&[0, 0, 0, 0]);+ out.extend_from_slice(&w.to_le_bytes());+ out.extend_from_slice(&h.to_le_bytes());+ // a local colour table of 256 entries+ out.push(0b1000_0111);+ for c in palette.iter().take(256) {+ out.extend_from_slice(c);+ }+ out.push(8);+ for block in lzw(&indices).chunks(255) {+ out.push(block.len() as u8);+ out.extend_from_slice(block);+ }+ out.push(0);+ }++ /// The GIF's bytes.+ pub fn finish(mut self) -> Vec<u8> {+ self.out.push(0x3B);+ self.out+ }+}++/// The palette index transparent pixels take.+const TRANSPARENT: u8 = 255;++/// Up to 255 colours for the opaque pixels (median cut), padded to 256, and how many are used.+fn palette(pixels: &[[u8; 4]], n: usize) -> (Vec<[u8; 3]>, usize) {+ // a sample of the opaque colours is enough to find the palette+ let step = (n / 65_536).max(1);+ let sample: Vec<[u8; 3]> =+ pixels.iter().step_by(step).filter(|p| p[3] >= 128).map(|p| [p[0], p[1], p[2]]).collect();+ let mut boxes: Vec<Vec<[u8; 3]>> = if sample.is_empty() { Vec::new() } else { vec![sample] };+ while boxes.len() < 255 {+ // split the box with the widest channel spread+ let widest = boxes+ .iter()+ .enumerate()+ .filter(|(_, b)| b.len() > 1)+ .map(|(i, b)| (i, spread(b)))+ .max_by_key(|(_, (range, _))| *range);+ let Some((i, (range, channel))) = widest else { break };+ if range == 0 {+ break;+ }+ let mut b = boxes.swap_remove(i);+ b.sort_unstable_by_key(|c| c.get(channel).copied().unwrap_or(0));+ let upper = b.split_off(b.len() / 2);+ boxes.push(b);+ boxes.push(upper);+ }+ let mut palette: Vec<[u8; 3]> = boxes+ .iter()+ .map(|b| {+ let sum = b+ .iter()+ .fold([0u64; 3], |s, c| [s[0] + u64::from(c[0]), s[1] + u64::from(c[1]), s[2] + u64::from(c[2])]);+ let k = b.len().max(1) as u64;+ [(sum[0] / k) as u8, (sum[1] / k) as u8, (sum[2] / k) as u8]+ })+ .collect();+ palette.resize(256, [0, 0, 0]);+ (palette, boxes.len().max(1))+}++/// The nearest of a palette's first colours, remembered per 6 bits a channel (judged from the+/// middle of each step, so no colour is pulled one way).+struct Nearest<'a> {+ palette: &'a [[u8; 3]],+ used: usize,+ cache: Vec<u8>,+ cached: Vec<bool>,+}++impl Nearest<'_> {+ fn new(palette: &[[u8; 3]], used: usize) -> Nearest<'_> {+ Nearest { palette, used, cache: vec![u8::MAX; 1 << 18], cached: vec![false; 1 << 18] }+ }++ fn find(&mut self, c: [u8; 3]) -> u8 {+ let key = (usize::from(c[0] >> 2) << 12) | (usize::from(c[1] >> 2) << 6) | usize::from(c[2] >> 2);+ if self.cached.get(key) == Some(&true) {+ return self.cache.get(key).copied().unwrap_or(0);+ }+ let c = c.map(|v| (v & !3) | 2);+ let best = self+ .palette+ .iter()+ .take(self.used)+ .enumerate()+ .min_by_key(|(_, p)| {+ let d = |a: u8, b: u8| (i32::from(a) - i32::from(b)).pow(2);+ d(p[0], c[0]) + d(p[1], c[1]) + d(p[2], c[2])+ })+ .map_or(0, |(i, _)| i as u8);+ if let (Some(slot), Some(flag)) = (self.cache.get_mut(key), self.cached.get_mut(key)) {+ *slot = best;+ *flag = true;+ }+ best+ }+}++/// Each pixel's nearest palette colour.+fn nearest_all(pixels: &[[u8; 4]], palette: &[[u8; 3]], used: usize) -> Vec<u8> {+ let mut nearest = Nearest::new(palette, used);+ pixels.iter().map(|p| if p[3] < 128 { TRANSPARENT } else { nearest.find([p[0], p[1], p[2]]) }).collect()+}++/// Each pixel's palette colour with Floyd–Steinberg error diffusion, rows `width` wide.+fn dithered(pixels: &[[u8; 4]], width: usize, palette: &[[u8; 3]], used: usize) -> Vec<u8> {+ let mut nearest = Nearest::new(palette, used);+ let width = width.max(1);+ // the error carried into this row and the next, per channel, a pixel of margin each side+ let mut this = vec![[0i32; 3]; width + 2];+ let mut next = vec![[0i32; 3]; width + 2];+ let mut out = Vec::with_capacity(pixels.len());+ for row in pixels.chunks(width) {+ for (x, p) in row.iter().enumerate() {+ if p[3] < 128 {+ out.push(TRANSPARENT);+ continue;+ }+ let carried = this.get(x + 1).copied().unwrap_or([0; 3]);+ let want = [+ (i32::from(p[0]) + carried[0] / 16).clamp(0, 255),+ (i32::from(p[1]) + carried[1] / 16).clamp(0, 255),+ (i32::from(p[2]) + carried[2] / 16).clamp(0, 255),+ ];+ let i = nearest.find(want.map(|v| v as u8));+ out.push(i);+ let got = palette.get(usize::from(i)).copied().unwrap_or([0; 3]);+ let err = [want[0] - i32::from(got[0]), want[1] - i32::from(got[1]), want[2] - i32::from(got[2])];+ let add = |buf: &mut Vec<[i32; 3]>, at: usize, weight: i32| {+ if let Some(e) = buf.get_mut(at) {+ for (e, d) in e.iter_mut().zip(err) {+ *e += d * weight;+ }+ }+ };+ add(&mut this, x + 2, 7);+ add(&mut next, x, 3);+ add(&mut next, x + 1, 5);+ add(&mut next, x + 2, 1);+ }+ std::mem::swap(&mut this, &mut next);+ next.iter_mut().for_each(|e| *e = [0; 3]);+ }+ out+}++/// The widest channel range in a box of colours, and which channel.+fn spread(b: &[[u8; 3]]) -> (u8, usize) {+ (0..3)+ .map(|k| {+ let (lo, hi) = b.iter().fold((u8::MAX, 0u8), |(lo, hi), c| {+ let v = c.get(k).copied().unwrap_or(0);+ (lo.min(v), hi.max(v))+ });+ (hi.saturating_sub(lo), k)+ })+ .max()+ .unwrap_or((0, 0))+}++/// GIF's variable-width LZW, 8-bit symbols, packed least significant bit first.+fn lzw(indices: &[u8]) -> Vec<u8> {+ const CLEAR: u16 = 256;+ const END: u16 = 257;+ let mut out = Vec::new();+ let (mut acc, mut bits) = (0u32, 0u32);+ let mut put = |code: u16, width: u32, out: &mut Vec<u8>| {+ acc |= u32::from(code) << bits;+ bits += width;+ while bits >= 8 {+ out.push(acc as u8);+ acc >>= 8;+ bits -= 8;+ }+ };+ let mut table: std::collections::HashMap<(u16, u8), u16> = std::collections::HashMap::new();+ let mut next = 258u16;+ let mut width = 9u32;+ put(CLEAR, width, &mut out);+ let mut current: Option<u16> = None;+ for &k in indices {+ let Some(prefix) = current else {+ current = Some(u16::from(k));+ continue;+ };+ if let Some(&code) = table.get(&(prefix, k)) {+ current = Some(code);+ continue;+ }+ put(prefix, width, &mut out);+ if next < 4096 {+ table.insert((prefix, k), next);+ next += 1;+ if next > (1 << width) && width < 12 {+ width += 1;+ }+ } else {+ // the table is full: start again+ put(CLEAR, width, &mut out);+ table.clear();+ next = 258;+ width = 9;+ }+ current = Some(u16::from(k));+ }+ if let Some(prefix) = current {+ put(prefix, width, &mut out);+ }+ put(END, width, &mut out);+ if bits > 0 {+ out.push(acc as u8);+ }+ out+}++fn put16(out: &mut Vec<u8>, v: u16) {+ out.extend_from_slice(&v.to_be_bytes());+}++fn put32(out: &mut Vec<u8>, v: u32) {+ out.extend_from_slice(&v.to_be_bytes());+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_cmyk_canvas_writes_its_inks() {+ use crate::cms::{IccProfile, Lut, builtin};+ use crate::profile::Profile;+ let press = IccProfile::parse(&crate::cmyk::profile()).unwrap();+ let table = Lut::build(&builtin(Profile::DisplayP3), &press, None, 17);+ // a green square, half see-through around it+ let (w, h) = (8u32, 8u32);+ let rgba: Vec<u8> = (0..w * h)+ .flat_map(|i| {+ if (2..6).contains(&(i % w)) && (2..6).contains(&(i / w)) { [0, 255, 0, 255] } else { [0, 0, 0, 0] }+ })+ .collect();+ let icc = &*press.bytes;+ let t = tiff_cmyk(w, h, 300.0, icc, &rgba, &table);+ let p = pdf(w, h, 300.0, icc, &[&rgba], 100, Some(&table));+ let layers = [PsdLayer {+ name: "Green",+ kind: PsdKind::Pixels { rgba: &rgba, mask: None },+ opacity: 1.0,+ visible: true,+ blend: BlendMode::Normal,+ clipped: false,+ }];+ let f = psd(w, h, 300.0, icc, &layers, &rgba, Some(&table));+ // CMYK mode, four channels+ assert_eq!((u16::from_be_bytes([f[12], f[13]]), u16::from_be_bytes([f[24], f[25]])), (4, 4));+ assert!(p.windows(11).any(|w| w == b"/DeviceCMYK") && p.windows(9).any(|w| w == b"/N 4 /Alt"));+ if let Ok(dir) = std::env::var("FORMATS_CMYK_OUT") {+ std::fs::write(format!("{dir}/cmyk.tiff"), &t).unwrap();+ std::fs::write(format!("{dir}/cmyk.pdf"), &p).unwrap();+ std::fs::write(format!("{dir}/cmyk.psd"), &f).unwrap();+ }+ }++ fn unpack(data: &[u8]) -> Vec<u8> {+ let mut out = Vec::new();+ let mut i = 0;+ while i < data.len() {+ let n = data[i] as i8;+ i += 1;+ if n >= 0 {+ out.extend_from_slice(&data[i..i + n as usize + 1]);+ i += n as usize + 1;+ } else if n != -128 {+ out.extend(std::iter::repeat_n(data[i], (1 - n as i32) as usize));+ i += 1;+ }+ }+ out+ }++ #[test]+ fn packbits_round_trips() {+ for row in [+ vec![],+ vec![7],+ vec![1, 1, 1, 1, 2, 3, 4, 4, 5],+ (0..300).map(|i| (i % 7) as u8).collect::<Vec<_>>(),+ vec![9; 500],+ (0..400).map(|i| if i % 50 < 25 { 3 } else { (i * 13 % 251) as u8 }).collect(),+ ] {+ assert_eq!(unpack(&packbits(&row)), row, "{row:?}");+ }+ }++ fn be16(b: &[u8], at: usize) -> u16 {+ u16::from_be_bytes([b[at], b[at + 1]])+ }++ fn be32(b: &[u8], at: usize) -> u32 {+ u32::from_be_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]])+ }++ #[test]+ fn a_psd_has_its_layers_and_picture() {+ let (w, h) = (4u32, 3u32);+ let mut red = vec![0u8; (w * h * 4) as usize];+ red[4..8].copy_from_slice(&[255, 0, 0, 255]);+ let blue = [0, 0, 255, 128].repeat((w * h) as usize);+ let mask = vec![255u8; (w * h) as usize];+ let layers = [+ PsdLayer {+ name: "Group",+ kind: PsdKind::GroupStart { open: true },+ opacity: 1.0,+ visible: true,+ blend: BlendMode::Normal,+ clipped: false,+ },+ PsdLayer {+ name: "Rouge é",+ kind: PsdKind::Pixels { rgba: &red, mask: Some(&mask) },+ opacity: 0.5,+ visible: false,+ blend: BlendMode::Multiply,+ clipped: true,+ },+ PsdLayer {+ name: "",+ kind: PsdKind::GroupEnd,+ opacity: 1.0,+ visible: true,+ blend: BlendMode::Normal,+ clipped: false,+ },+ PsdLayer {+ name: "Blue",+ kind: PsdKind::Pixels { rgba: &blue, mask: None },+ opacity: 1.0,+ visible: true,+ blend: BlendMode::Normal,+ clipped: false,+ },+ ];+ let composite = vec![200u8; (w * h * 4) as usize];+ let f = psd(w, h, 132.0, &[], &layers, &composite, None);+ assert_eq!(&f[..4], b"8BPS");+ assert_eq!((be16(&f, 12), be32(&f, 14), be32(&f, 18), be16(&f, 22), be16(&f, 24)), (4, h, w, 8, 3));+ // past the colour data and the resources to the layers+ let mut at = 26;+ at += 4 + be32(&f, at) as usize;+ at += 4 + be32(&f, at) as usize;+ let section = be32(&f, at) as usize;+ let info = at + 4;+ assert_eq!(be16(&f, info + 4) as i16, -4);+ // the first record is the bottom layer: "Blue", the whole canvas+ let r = info + 6;+ assert_eq!([be32(&f, r), be32(&f, r + 4), be32(&f, r + 8), be32(&f, r + 12)], [0, 0, h, w]);+ assert_eq!(be16(&f, r + 16), 4);+ let blend = r + 18 + 4 * 6;+ assert_eq!(&f[blend..blend + 8], b"8BIMnorm");+ assert!(f.windows(14).any(|x| x == b"</Layer group>"));+ assert!(f.windows(4).any(|x| x == b"lsct") && f.windows(4).any(|x| x == b"luni"));+ // the red layer: its one pixel, multiply, half opacity, clipped, hidden, with a mask+ let red_rect = f.windows(16).position(|x| x == [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2]).unwrap();+ assert_eq!(be16(&f, red_rect + 16), 5);+ let blend = red_rect + 18 + 5 * 6;+ assert_eq!(&f[blend..blend + 12], b"8BIMmul \x80\x01\x02\x00");+ // the picture follows the layers, packed+ let image = at + 4 + section;+ assert_eq!(be16(&f, image), 1);+ let first_row = be16(&f, image + 2) as usize;+ let data = image + 2 + 4 * h as usize * 2;+ assert_eq!(unpack(&f[data..data + first_row]), vec![200; w as usize]);+ }++ #[test]+ fn a_tiff_and_a_pdf_hold_the_pixels() {+ let (w, h) = (3u32, 2u32);+ let rgba: Vec<u8> = (0..w * h * 4).map(|i| (i * 11 % 256) as u8).collect();+ let t = tiff(w, h, 132.0, &[], &rgba);+ assert_eq!(&t[..4], b"II*\0");+ let dir = u32::from_le_bytes(t[4..8].try_into().unwrap()) as usize;+ let entries = u16::from_le_bytes([t[dir], t[dir + 1]]) as usize;+ let entry = |tag: u16| {+ (0..entries)+ .map(|i| dir + 2 + i * 12)+ .find(|&e| u16::from_le_bytes([t[e], t[e + 1]]) == tag)+ .map(|e| u32::from_le_bytes(t[e + 8..e + 12].try_into().unwrap()))+ };+ assert_eq!((entry(256), entry(257), entry(259), entry(338)), (Some(w), Some(h), Some(8), Some(2)));+ let (at, len) = (entry(273).unwrap() as usize, entry(279).unwrap() as usize);+ assert_eq!(miniz_oxide::inflate::decompress_to_vec_zlib(&t[at..at + len]).unwrap(), rgba);+ let p = pdf(w, h, 132.0, &[], &[&rgba, &rgba], 100, None);+ let text = String::from_utf8_lossy(&p);+ assert!(text.starts_with("%PDF-1.4") && text.trim_end().ends_with("%%EOF"));+ assert!(text.contains("/Count 2") && text.contains("/SMask"));+ // the cross-reference table points at each object+ let xref: usize = text.rsplit("startxref\n").next().unwrap().lines().next().unwrap().parse().unwrap();+ assert!(p[xref..].starts_with(b"xref"));+ let table = std::str::from_utf8(&p[xref..]).unwrap();+ let first: usize = table.lines().nth(3).unwrap()[..10].parse().unwrap();+ assert!(p[first..].starts_with(b"1 0 obj"));+ }++ /// A small GIF LZW decoder, to check the encoder against.+ fn unlzw(data: &[u8]) -> Vec<u8> {+ let mut out = Vec::new();+ let (mut acc, mut bits, mut pos) = (0u32, 0u32, 0usize);+ let mut width = 9u32;+ let mut table: Vec<Vec<u8>> = (0..258).map(|i| if i < 256 { vec![i as u8] } else { vec![] }).collect();+ let mut prev: Option<Vec<u8>> = None;+ loop {+ while bits < width {+ if pos >= data.len() {+ return out;+ }+ acc |= u32::from(data[pos]) << bits;+ pos += 1;+ bits += 8;+ }+ let code = (acc & ((1 << width) - 1)) as usize;+ acc >>= width;+ bits -= width;+ if code == 256 {+ table.truncate(258);+ width = 9;+ prev = None;+ continue;+ }+ if code == 257 {+ return out;+ }+ let entry = if code < table.len() {+ table[code].clone()+ } else {+ let p = prev.clone().unwrap();+ let mut e = p.clone();+ e.push(p[0]);+ e+ };+ out.extend_from_slice(&entry);+ if let Some(p) = prev {+ let mut e = p.clone();+ e.push(entry[0]);+ table.push(e);+ if table.len() == (1 << width) && width < 12 {+ width += 1;+ }+ }+ prev = Some(entry);+ }+ }++ #[test]+ fn lzw_round_trips() {+ for data in [+ vec![1u8, 1, 1, 1, 2, 2, 3],+ (0..5000).map(|i| (i % 7) as u8).collect::<Vec<_>>(),+ (0..20000).map(|i| ((i * 31 + i / 17) % 251) as u8).collect::<Vec<_>>(),+ vec![9; 9000],+ ] {+ assert_eq!(unlzw(&lzw(&data)), data);+ }+ }++ #[test]+ fn a_gif_has_its_frames() {+ let (w, h) = (6u32, 4u32);+ let red = [255u8, 0, 0, 255].repeat(24);+ let mut half = [0u8, 0, 255, 255].repeat(24);+ half[..48].iter_mut().skip(3).step_by(4).for_each(|a| *a = 0);+ let g = gif(w, h, &[&red, &half], 7);+ assert_eq!(&g[..6], b"GIF89a");+ assert_eq!(*g.last().unwrap(), 0x3B);+ assert!(g.windows(11).any(|x| x == b"NETSCAPE2.0"));+ // two frames, each with its delay+ let gces: Vec<usize> =+ g.windows(3).enumerate().filter(|(_, x)| x == &[0x21, 0xF9, 4]).map(|(i, _)| i).collect();+ assert_eq!(gces.len(), 2);+ assert_eq!(u16::from_le_bytes([g[gces[0] + 4], g[gces[0] + 5]]), 7);+ // the first frame's pixels decode to one colour, red in its palette+ let desc = gces[0] + 8;+ assert_eq!(g[desc], 0x2C);+ let table = desc + 10;+ let data = table + 768 + 1;+ let mut lz = Vec::new();+ let mut at = data;+ while g[at] != 0 {+ lz.extend_from_slice(&g[at + 1..at + 1 + g[at] as usize]);+ at += 1 + g[at] as usize;+ }+ let px = unlzw(&lz);+ assert_eq!(px.len(), 24);+ let i = px[0] as usize;+ assert!(px.iter().all(|&p| p as usize == i));+ assert_eq!(&g[table + i * 3..table + i * 3 + 3], &[255, 0, 0]);+ }++ #[test]+ fn dithering_mixes_palette_colours_for_a_ramp() {+ // a grey ramp wider than any palette: dithered, neighbouring pixels differ more often+ let (w, h) = (512u32, 4u32);+ let rgba: Vec<u8> = (0..w * h)+ .flat_map(|i| {+ let v = ((i % w) * 255 / (w - 1)) as u8;+ [v, v, v, 255]+ })+ .collect();+ let px = rgba.as_chunks::<4>().0;+ let (pal, used) = palette(px, (w * h) as usize);+ let plain = nearest_all(px, &pal, used);+ let mixed = dithered(px, w as usize, &pal, used);+ assert_eq!(plain.len(), mixed.len());+ // the average colour along a row stays close to the ramp's+ let mean =+ |idx: &[u8]| idx[..w as usize].iter().map(|&i| f64::from(pal[i as usize][0])).sum::<f64>() / f64::from(w);+ assert!((mean(&mixed) - 127.5).abs() < 2.0);+ // a GIF made a frame at a time ends like one made at once+ let mut g = GifWriter::new(w, h);+ g.frame(&rgba, 7, true);+ let bytes = g.finish();+ assert_eq!(*bytes.last().unwrap(), 0x3B);+ }++ #[test]+ fn files_carry_the_colour_profile() {+ let icc = crate::icc::icc(crate::profile::Profile::DisplayP3);+ let rgba = vec![200u8; 4 * 4 * 4];+ let has = |hay: &[u8], needle: &[u8]| hay.windows(needle.len()).any(|w| w == needle);+ // TIFF: the profile and an InterColorProfile entry (tag 34675, type 7)+ let t = tiff(4, 4, 132.0, &icc, &rgba);+ assert!(has(&t, &icc));+ assert!(has(&t, &[0x73, 0x87, 7, 0]));+ // PSD: an image resource 1039 holding it+ let mut res = b"8BIM".to_vec();+ res.extend_from_slice(&[0x04, 0x0F, 0, 0]);+ res.extend_from_slice(&(icc.len() as u32).to_be_bytes());+ res.extend_from_slice(&icc);+ let f = psd(4, 4, 132.0, &icc, &[], &rgba, None);+ assert!(has(&f, &res));+ // PDF: the images in an ICC-based space+ let p = pdf(4, 4, 132.0, &icc, &[&rgba], 100, None);+ // below 100 its colours are JPEG+ let jpeg = pdf(4, 4, 132.0, &icc, &[&rgba], 60, None);+ assert!(jpeg.windows(9).any(|w| w == b"DCTDecode"));+ assert!(has(&p, b"/ColorSpace [/ICCBased") && has(&p, &icc));+ // without one, none+ assert!(!has(&tiff(4, 4, 132.0, &[], &rgba), &[0x73, 0x87]));+ }+}diff --git a/crates/engine/src/geom.rs b/crates/engine/src/geom.rsnew file mode 100644index 0000000..8eeff3e--- /dev/null+++ b/crates/engine/src/geom.rs@@ -0,0 +1,376 @@+//! Points, affine maps and pixel rectangles.++use std::ops::{Add, Mul, Sub};++#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct Vec2 {+ pub x: f32,+ pub y: f32,+}++impl Vec2 {+ pub const ZERO: Vec2 = Vec2 { x: 0.0, y: 0.0 };++ pub const fn new(x: f32, y: f32) -> Vec2 {+ Vec2 { x, y }+ }++ pub fn length(self) -> f32 {+ self.x.hypot(self.y)+ }++ pub fn distance(self, other: Vec2) -> f32 {+ (self - other).length()+ }++ pub fn lerp(self, other: Vec2, t: f32) -> Vec2 {+ self + (other - self) * t+ }++ pub fn is_finite(self) -> bool {+ self.x.is_finite() && self.y.is_finite()+ }++ pub fn dot(self, other: Vec2) -> f32 {+ self.x * other.x + self.y * other.y+ }++ /// The z of the 3D cross product: positive when `other` turns anticlockwise from this.+ pub fn cross(self, other: Vec2) -> f32 {+ self.x * other.y - self.y * other.x+ }++ /// This at length 1, or `fallback` when it has no length.+ pub fn normalized_or(self, fallback: Vec2) -> Vec2 {+ let len = self.length();+ if len > 1e-9 && len.is_finite() { self * (1.0 / len) } else { fallback }+ }+}++impl Add for Vec2 {+ type Output = Vec2;+ fn add(self, o: Vec2) -> Vec2 {+ Vec2::new(self.x + o.x, self.y + o.y)+ }+}++impl Sub for Vec2 {+ type Output = Vec2;+ fn sub(self, o: Vec2) -> Vec2 {+ Vec2::new(self.x - o.x, self.y - o.y)+ }+}++impl Mul<f32> for Vec2 {+ type Output = Vec2;+ fn mul(self, s: f32) -> Vec2 {+ Vec2::new(self.x * s, self.y * s)+ }+}++/// A 2-D affine map `p ↦ (a·x + c·y + e, b·x + d·y + f)`.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Affine {+ pub a: f32,+ pub b: f32,+ pub c: f32,+ pub d: f32,+ pub e: f32,+ pub f: f32,+}++impl Affine {+ pub const IDENTITY: Affine = Affine { a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: 0.0, f: 0.0 };++ pub fn translate(t: Vec2) -> Affine {+ Affine { e: t.x, f: t.y, ..Affine::IDENTITY }+ }++ pub fn scale(s: f32) -> Affine {+ Affine { a: s, d: s, ..Affine::IDENTITY }+ }++ /// Rotation by `radians`, clockwise on a y-down screen.+ pub fn rotate(radians: f32) -> Affine {+ let (s, c) = radians.sin_cos();+ Affine { a: c, b: s, c: -s, d: c, e: 0.0, f: 0.0 }+ }++ /// `self`, then `next`.+ pub fn then(self, next: Affine) -> Affine {+ let n = next;+ Affine {+ a: n.a * self.a + n.c * self.b,+ b: n.b * self.a + n.d * self.b,+ c: n.a * self.c + n.c * self.d,+ d: n.b * self.c + n.d * self.d,+ e: n.a * self.e + n.c * self.f + n.e,+ f: n.b * self.e + n.d * self.f + n.f,+ }+ }++ pub fn apply(self, p: Vec2) -> Vec2 {+ Vec2::new(self.a * p.x + self.c * p.y + self.e, self.b * p.x + self.d * p.y + self.f)+ }++ pub fn determinant(self) -> f32 {+ self.a * self.d - self.b * self.c+ }++ pub fn inverse(self) -> Option<Affine> {+ let det = self.determinant();+ if !det.is_finite() || det.abs() < 1e-12 {+ return None;+ }+ let inv = 1.0 / det;+ let (a, b, c, d) = (self.d * inv, -self.b * inv, -self.c * inv, self.a * inv);+ Some(Affine { a, b, c, d, e: -(a * self.e + c * self.f), f: -(b * self.e + d * self.f) })+ }++ /// The uniform scale of a similarity map (the zoom).+ pub fn scale_factor(self) -> f32 {+ self.determinant().abs().sqrt()+ }++ /// The rotation of a similarity map, radians.+ pub fn rotation(self) -> f32 {+ self.b.atan2(self.a)+ }++ pub fn is_finite(self) -> bool {+ [self.a, self.b, self.c, self.d, self.e, self.f].iter().all(|v| v.is_finite())+ }+}++/// A projective map of the plane (3 × 3, row-major, acting on `(x, y, 1)`): it carries any four+/// corners to any other four, so it covers moving, scaling, rotating and distorting.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Homography {+ m: [f64; 9],+}++impl Homography {+ pub const IDENTITY: Homography = Homography { m: [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0] };++ /// The map from the unit square's corners (0, 0), (1, 0), (1, 1), (0, 1) to `q` in that order.+ pub fn square_to_quad(q: [Vec2; 4]) -> Option<Homography> {+ let [p0, p1, p2, p3] = q.map(|p| (f64::from(p.x), f64::from(p.y)));+ let sx = p0.0 - p1.0 + p2.0 - p3.0;+ let sy = p0.1 - p1.1 + p2.1 - p3.1;+ let (g, h) = if sx.abs() < 1e-12 && sy.abs() < 1e-12 {+ (0.0, 0.0)+ } else {+ let (dx1, dx2, dy1, dy2) = (p1.0 - p2.0, p3.0 - p2.0, p1.1 - p2.1, p3.1 - p2.1);+ let den = dx1 * dy2 - dx2 * dy1;+ if den.abs() < 1e-12 {+ return None;+ }+ ((sx * dy2 - dx2 * sy) / den, (dx1 * sy - sx * dy1) / den)+ };+ let m = [+ p1.0 - p0.0 + g * p1.0,+ p3.0 - p0.0 + h * p3.0,+ p0.0,+ p1.1 - p0.1 + g * p1.1,+ p3.1 - p0.1 + h * p3.1,+ p0.1,+ g,+ h,+ 1.0,+ ];+ let out = Homography { m };+ (out.is_finite() && out.determinant().abs() > 1e-12).then_some(out)+ }++ /// The map carrying corners `from` to corners `to` (each in the order of [`Self::square_to_quad`]).+ pub fn quad_to_quad(from: [Vec2; 4], to: [Vec2; 4]) -> Option<Homography> {+ let a = Homography::square_to_quad(from)?.inverse()?;+ Some(a.then(Homography::square_to_quad(to)?))+ }++ /// `self`, then `next`.+ pub fn then(self, next: Homography) -> Homography {+ let [a0, a1, a2, a3, a4, a5, a6, a7, a8] = self.m;+ let [b0, b1, b2, b3, b4, b5, b6, b7, b8] = next.m;+ Homography {+ m: [+ b0 * a0 + b1 * a3 + b2 * a6,+ b0 * a1 + b1 * a4 + b2 * a7,+ b0 * a2 + b1 * a5 + b2 * a8,+ b3 * a0 + b4 * a3 + b5 * a6,+ b3 * a1 + b4 * a4 + b5 * a7,+ b3 * a2 + b4 * a5 + b5 * a8,+ b6 * a0 + b7 * a3 + b8 * a6,+ b6 * a1 + b7 * a4 + b8 * a7,+ b6 * a2 + b7 * a5 + b8 * a8,+ ],+ }+ }++ pub fn determinant(self) -> f64 {+ let [a, b, c, d, e, f, g, h, i] = self.m;+ a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g)+ }++ pub fn inverse(self) -> Option<Homography> {+ let det = self.determinant();+ if !det.is_finite() || det.abs() < 1e-18 {+ return None;+ }+ let [a, b, c, d, e, f, g, h, i] = self.m;+ let k = 1.0 / det;+ Some(Homography {+ m: [+ (e * i - f * h) * k,+ (c * h - b * i) * k,+ (b * f - c * e) * k,+ (f * g - d * i) * k,+ (a * i - c * g) * k,+ (c * d - a * f) * k,+ (d * h - e * g) * k,+ (b * g - a * h) * k,+ (a * e - b * d) * k,+ ],+ })+ }++ /// Where `p` goes; `None` where the map sends it to infinity.+ pub fn apply(self, p: Vec2) -> Option<Vec2> {+ let [a, b, c, d, e, f, g, h, i] = self.m;+ let (x, y) = (f64::from(p.x), f64::from(p.y));+ let w = g * x + h * y + i;+ if w.abs() < 1e-12 {+ return None;+ }+ Some(Vec2::new(((a * x + b * y + c) / w) as f32, ((d * x + e * y + f) / w) as f32))+ }++ /// The matrix, row-major, for a shader.+ pub fn to_f32(self) -> [f32; 9] {+ self.m.map(|v| v as f32)+ }++ pub fn is_finite(self) -> bool {+ self.m.iter().all(|v| v.is_finite())+ }+}++/// An integer pixel rectangle `[x0, x1) × [y0, y1)`, empty when it has no area.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct IRect {+ pub x0: i32,+ pub y0: i32,+ pub x1: i32,+ pub y1: i32,+}++impl IRect {+ pub const EMPTY: IRect = IRect { x0: 0, y0: 0, x1: 0, y1: 0 };++ pub const fn new(x0: i32, y0: i32, x1: i32, y1: i32) -> IRect {+ IRect { x0, y0, x1, y1 }+ }++ pub fn from_size(width: u32, height: u32) -> IRect {+ IRect::new(0, 0, i32::try_from(width).unwrap_or(i32::MAX), i32::try_from(height).unwrap_or(i32::MAX))+ }++ /// The pixels a disc can touch, with one pixel to spare for anti-aliasing.+ pub fn around(center: Vec2, radius: f32) -> IRect {+ if !center.is_finite() || !radius.is_finite() {+ return IRect::EMPTY;+ }+ let r = radius.max(0.0) + 1.0;+ IRect::new(+ (center.x - r).floor() as i32,+ (center.y - r).floor() as i32,+ (center.x + r).ceil() as i32,+ (center.y + r).ceil() as i32,+ )+ }++ pub fn is_empty(self) -> bool {+ self.x0 >= self.x1 || self.y0 >= self.y1+ }++ pub fn width(self) -> u32 {+ u32::try_from(self.x1.saturating_sub(self.x0)).unwrap_or(0)+ }++ pub fn height(self) -> u32 {+ u32::try_from(self.y1.saturating_sub(self.y0)).unwrap_or(0)+ }++ pub fn union(self, o: IRect) -> IRect {+ if self.is_empty() {+ return o;+ }+ if o.is_empty() {+ return self;+ }+ IRect::new(self.x0.min(o.x0), self.y0.min(o.y0), self.x1.max(o.x1), self.y1.max(o.y1))+ }++ pub fn intersect(self, o: IRect) -> IRect {+ let r = IRect::new(self.x0.max(o.x0), self.y0.max(o.y0), self.x1.min(o.x1), self.y1.min(o.y1));+ if r.is_empty() { IRect::EMPTY } else { r }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn close(a: Vec2, b: Vec2) -> bool {+ a.distance(b) < 1e-3+ }++ #[test]+ fn affine_inverse_round_trips() {+ let m = Affine::scale(2.5).then(Affine::rotate(0.7)).then(Affine::translate(Vec2::new(30.0, -12.0)));+ let inv = m.inverse().unwrap();+ let p = Vec2::new(17.0, 41.0);+ assert!(close(inv.apply(m.apply(p)), p));+ assert!((m.scale_factor() - 2.5).abs() < 1e-4);+ assert!((m.rotation() - 0.7).abs() < 1e-4);+ }++ #[test]+ fn degenerate_affine_has_no_inverse() {+ assert!(Affine::scale(0.0).inverse().is_none());+ }++ #[test]+ fn homography_carries_corners_to_corners() {+ let from = [Vec2::new(10.0, 20.0), Vec2::new(110.0, 20.0), Vec2::new(110.0, 70.0), Vec2::new(10.0, 70.0)];+ let to = [Vec2::new(0.0, 0.0), Vec2::new(200.0, 30.0), Vec2::new(180.0, 160.0), Vec2::new(-20.0, 120.0)];+ let h = Homography::quad_to_quad(from, to).unwrap();+ for (f, t) in from.iter().zip(&to) {+ assert!(close(h.apply(*f).unwrap(), *t), "{f:?} -> {t:?}");+ }+ let back = h.inverse().unwrap();+ let p = Vec2::new(47.0, 33.0);+ assert!(close(back.apply(h.apply(p).unwrap()).unwrap(), p));+ }++ #[test]+ fn homography_of_a_moved_rectangle_is_affine() {+ let from = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(4.0, 2.0), Vec2::new(0.0, 2.0)];+ let to = from.map(|p| p * 2.0 + Vec2::new(5.0, -3.0));+ let h = Homography::quad_to_quad(from, to).unwrap();+ assert!(close(h.apply(Vec2::new(1.0, 1.0)).unwrap(), Vec2::new(7.0, -1.0)));+ assert!(Homography::quad_to_quad(from, [Vec2::new(0.0, 0.0); 4]).is_none(), "a quad with no area");+ }++ #[test]+ fn rects() {+ let a = IRect::new(0, 0, 10, 10);+ let b = IRect::new(5, 5, 20, 8);+ assert_eq!(a.union(b), IRect::new(0, 0, 20, 10));+ assert_eq!(a.intersect(b), IRect::new(5, 5, 10, 8));+ assert!(a.intersect(IRect::new(11, 11, 12, 12)).is_empty());+ assert_eq!(IRect::EMPTY.union(b), b);+ assert_eq!(IRect::around(Vec2::new(5.5, 5.5), 2.0), IRect::new(2, 2, 9, 9));+ assert!(IRect::around(Vec2::new(f32::NAN, 0.0), 2.0).is_empty());+ }+}diff --git a/crates/engine/src/guide.rs b/crates/engine/src/guide.rsnew file mode 100644index 0000000..527bbca--- /dev/null+++ b/crates/engine/src/guide.rs@@ -0,0 +1,379 @@+//! Drawing guides over the canvas: a 2D grid, an isometric grid, perspective, or symmetry, drawn as+//! lines to follow. With assisted drawing on, strokes keep to them: along the grid's directions,+//! towards the vanishing points, or mirrored about the symmetry.++use std::f32::consts::{FRAC_PI_6, PI, TAU};++use crate::geom::Vec2;++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+pub enum GuideKind {+ #[default]+ Grid,+ Isometric,+ Perspective,+ Symmetry,+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+pub enum SymmetryKind {+ #[default]+ Vertical,+ Horizontal,+ Quadrant,+ Radial,+}++/// One kind of guide's look: its opacity and line thickness (0..1), its grid's size (canvas+/// pixels), and its colour (0..1 along the colour bar, see [`bar_color`]).+#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]+pub struct GuideLook {+ pub opacity: f32,+ pub thickness: f32,+ pub size: f32,+ pub color: f32,+}++#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]+pub struct Guide {+ pub on: bool,+ pub kind: GuideKind,+ /// Each kind's look, in [`GuideKind`] order.+ pub looks: [GuideLook; 4],+ /// Where the grid starts and the symmetry turns about (canvas pixels), and its turn (radians).+ pub centre: [f32; 2],+ pub angle: f32,+ pub symmetry: SymmetryKind,+ /// Symmetry turns copies round instead of mirroring them.+ pub rotational: bool,+ pub assisted: bool,+ /// Perspective's vanishing points (canvas pixels), one to three.+ pub vanishing: Vec<[f32; 2]>,+}++/// The kinds' looks as a new guide starts.+pub const STARTS: [GuideLook; 4] = [+ GuideLook { opacity: 0.36, thickness: 0.64, size: 71.0, color: 0.0 },+ GuideLook { opacity: 0.30, thickness: 0.60, size: 82.0, color: 0.0 },+ GuideLook { opacity: 1.0, thickness: 0.70, size: 71.0, color: 0.33 },+ GuideLook { opacity: 0.41, thickness: 0.60, size: 71.0, color: 0.0 },+];++/// The guide colour bar: dark through blue, green, orange, red and pink to white, as stops.+const BAR: [[u8; 3]; 21] = [+ [5, 4, 10],+ [1, 12, 44],+ [0, 24, 87],+ [8, 57, 132],+ [18, 139, 182],+ [25, 198, 203],+ [27, 208, 184],+ [47, 208, 131],+ [103, 192, 100],+ [188, 155, 76],+ [206, 144, 73],+ [217, 118, 68],+ [218, 87, 74],+ [220, 65, 77],+ [229, 61, 113],+ [236, 54, 171],+ [245, 52, 222],+ [245, 92, 249],+ [251, 146, 253],+ [252, 202, 255],+ [232, 225, 233],+];++/// The colour (sRGB 0..1) at `t` (0..1) along the guide colour bar.+pub fn bar_color(t: f32) -> [f32; 3] {+ let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 };+ let at = t * (BAR.len() - 1) as f32;+ let i = (at.floor() as usize).min(BAR.len() - 2);+ let f = at - i as f32;+ let (Some(a), Some(b)) = (BAR.get(i), BAR.get(i + 1)) else { return [0.0; 3] };+ [0, 1, 2].map(|k| {+ let (x, y) = (f32::from(a.get(k).copied().unwrap_or(0)), f32::from(b.get(k).copied().unwrap_or(0)));+ (x + (y - x) * f) / 255.0+ })+}++/// The part of the segment `a`–`b` inside `0..w` × `0..h` (Liang–Barsky), if a visible part is.+fn clip(a: Vec2, b: Vec2, w: f32, h: f32) -> Option<(Vec2, Vec2)> {+ let d = b - a;+ let (mut t0, mut t1) = (0.0f32, 1.0f32);+ for (p, q) in [(-d.x, a.x), (d.x, w - a.x), (-d.y, a.y), (d.y, h - a.y)] {+ if p == 0.0 {+ if q < 0.0 {+ return None;+ }+ } else {+ let r = q / p;+ if p < 0.0 {+ t0 = t0.max(r);+ } else {+ t1 = t1.min(r);+ }+ }+ }+ let (s, e) = (a + d * t0, a + d * t1);+ (t0 < t1 && s.distance(e) >= 0.5).then_some((s, e))+}++impl Default for Guide {+ /// A guide for no canvas in particular (documents saved before guides; recentred on opening).+ fn default() -> Guide {+ Guide::new(0, 0)+ }+}++impl Guide {+ /// A guide for a `width` × `height` canvas, off, centred on it.+ pub fn new(width: u32, height: u32) -> Guide {+ Guide {+ on: false,+ kind: GuideKind::Grid,+ looks: STARTS,+ centre: [width as f32 / 2.0, height as f32 / 2.0],+ angle: 0.0,+ symmetry: SymmetryKind::Vertical,+ rotational: false,+ assisted: false,+ vanishing: Vec::new(),+ }+ }++ pub fn look(&self) -> GuideLook {+ self.looks.get(self.kind as usize).copied().unwrap_or(STARTS[0])+ }++ fn centre(&self) -> Vec2 {+ Vec2::new(self.centre[0], self.centre[1])+ }++ /// The guide's lines over a `width` × `height` canvas, as segments (canvas pixels) kept within+ /// it.+ pub fn lines(&self, width: u32, height: u32) -> Vec<(Vec2, Vec2)> {+ let (w, h) = (width as f32, height as f32);+ self.unclipped(width, height).into_iter().filter_map(|(a, b)| clip(a, b, w, h)).collect()+ }++ fn unclipped(&self, width: u32, height: u32) -> Vec<(Vec2, Vec2)> {+ let (w, h) = (width as f32, height as f32);+ let reach = w.hypot(h);+ let c = self.centre();+ let size = self.look().size.max(4.0);+ let family = |dir: f32| -> Vec<(Vec2, Vec2)> {+ // parallel lines `size` apart through the centre, long enough to cross the canvas+ let along = Vec2::new(dir.cos(), dir.sin());+ let across = Vec2::new(-along.y, along.x);+ let n = (reach / size).ceil() as i32 + 1;+ (-n..=n)+ .map(|k| {+ let o = c + across * (k as f32 * size);+ (o - along * reach, o + along * reach)+ })+ .collect()+ };+ match self.kind {+ GuideKind::Grid => [family(self.angle), family(self.angle + PI / 2.0)].concat(),+ GuideKind::Isometric => {+ // verticals, and lines thirty degrees either side of the horizontal, spaced so+ // the three meet in triangles+ let iso = size * FRAC_PI_6.cos();+ let mut out = Vec::new();+ for dir in [self.angle + PI / 2.0, self.angle + FRAC_PI_6, self.angle - FRAC_PI_6] {+ let along = Vec2::new(dir.cos(), dir.sin());+ let across = Vec2::new(-along.y, along.x);+ let n = (reach / iso).ceil() as i32 + 1;+ out.extend((-n..=n).map(|k| {+ let o = c + across * (k as f32 * iso);+ (o - along * reach, o + along * reach)+ }));+ }+ out+ }+ GuideKind::Perspective => {+ // rays from each vanishing point, and a horizon through the first two+ let mut out = Vec::new();+ for v in &self.vanishing {+ let v = Vec2::new(v[0], v[1]);+ out.extend((0..36).map(|k| {+ let a = k as f32 * TAU / 36.0;+ (v, v + Vec2::new(a.cos(), a.sin()) * reach * 2.0)+ }));+ }+ if let (Some(a), Some(b)) = (self.vanishing.first(), self.vanishing.get(1)) {+ let (a, b) = (Vec2::new(a[0], a[1]), Vec2::new(b[0], b[1]));+ let d = (b - a).normalized_or(Vec2::new(1.0, 0.0));+ out.push((a - d * reach * 2.0, b + d * reach * 2.0));+ }+ out+ }+ GuideKind::Symmetry => {+ let axes: Vec<f32> = match self.symmetry {+ SymmetryKind::Vertical => vec![self.angle + PI / 2.0],+ SymmetryKind::Horizontal => vec![self.angle],+ SymmetryKind::Quadrant => vec![self.angle, self.angle + PI / 2.0],+ SymmetryKind::Radial => (0..4).map(|k| self.angle + k as f32 * PI / 4.0).collect(),+ };+ axes.into_iter()+ .map(|a| {+ let d = Vec2::new(a.cos(), a.sin()) * reach;+ (c - d, c + d)+ })+ .collect()+ }+ }+ }++ /// Where a stamp at `p` is drawn again by the symmetry (not counting `p` itself), each with the+ /// turn to add to its angle and whether it is mirrored.+ pub fn copies(&self, p: Vec2) -> Vec<(Vec2, f32, bool)> {+ if !self.on || !self.assisted || self.kind != GuideKind::Symmetry {+ return Vec::new();+ }+ let c = self.centre();+ let turn = |q: Vec2, a: f32| {+ let d = q - c;+ c + Vec2::new(d.x * a.cos() - d.y * a.sin(), d.x * a.sin() + d.y * a.cos())+ };+ // mirrored across the line through the centre at angle `a`+ let mirror = |q: Vec2, a: f32| {+ let d = q - c;+ let (s, co) = ((2.0 * a).sin(), (2.0 * a).cos());+ c + Vec2::new(d.x * co + d.y * s, d.x * s - d.y * co)+ };+ let base = self.angle;+ let (count, axis) = match self.symmetry {+ SymmetryKind::Vertical => (2, base + PI / 2.0),+ SymmetryKind::Horizontal => (2, base),+ SymmetryKind::Quadrant => (4, base),+ SymmetryKind::Radial => (8, base),+ };+ if self.rotational || count > 2 {+ // turned copies; mirrored ones in between for a kaleidoscope unless only turning+ let step = TAU / count as f32;+ let mut out = Vec::new();+ for k in 1..count {+ let a = step * k as f32;+ if self.rotational || k % 2 == 0 {+ out.push((turn(p, a), a, false));+ } else {+ // the mirror axis between the two neighbouring turned copies+ let m = axis + a / 2.0;+ out.push((mirror(p, m), 2.0 * m, true));+ }+ }+ return out;+ }+ vec![(mirror(p, axis), 2.0 * axis, true)]+ }++ /// Assisted drawing: where a stroke begun at `start` goes when the input is at `p` (canvas+ /// pixels), kept along the guide's nearest direction.+ pub fn assist(&self, start: Vec2, p: Vec2) -> Vec2 {+ if !self.on || !self.assisted {+ return p;+ }+ let d = p - start;+ let along = |dirs: &[f32]| -> Vec2 {+ // the direction (or its reverse) the movement is nearest to+ let best = dirs.iter().copied().fold((0.0f32, f32::MIN), |best, a| {+ let u = Vec2::new(a.cos(), a.sin());+ let dot = d.dot(u).abs();+ if dot > best.1 { (a, dot) } else { best }+ });+ let u = Vec2::new(best.0.cos(), best.0.sin());+ start + u * d.dot(u)+ };+ match self.kind {+ GuideKind::Grid => along(&[self.angle, self.angle + PI / 2.0]),+ GuideKind::Isometric => along(&[self.angle + PI / 2.0, self.angle + FRAC_PI_6, self.angle - FRAC_PI_6]),+ GuideKind::Perspective => {+ // towards one of the vanishing points, or level or upright+ let mut dirs: Vec<f32> = self+ .vanishing+ .iter()+ .map(|v| {+ let to = Vec2::new(v[0], v[1]) - start;+ to.y.atan2(to.x)+ })+ .collect();+ if self.vanishing.len() < 3 {+ dirs.push(PI / 2.0);+ }+ if self.vanishing.len() < 2 {+ dirs.push(0.0);+ }+ along(&dirs)+ }+ GuideKind::Symmetry => p,+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn on(kind: GuideKind) -> Guide {+ Guide { on: true, kind, assisted: true, ..Guide::new(200, 100) }+ }++ #[test]+ fn grids_cross_the_canvas_in_their_spacing() {+ let g = on(GuideKind::Grid);+ let lines = g.lines(200, 100);+ // vertical lines 71 apart through the centre: x = 100 ± 71k+ assert!(lines.iter().any(|(a, b)| (a.x - 171.0).abs() < 1e-3 && (b.x - 171.0).abs() < 1e-3));+ assert!(!lines.is_empty());+ assert!(!on(GuideKind::Isometric).lines(200, 100).is_empty());+ let mut p = on(GuideKind::Perspective);+ assert!(p.lines(200, 100).is_empty());+ p.vanishing = vec![[0.0, 50.0], [200.0, 50.0]];+ let rays = p.lines(200, 100);+ assert!(rays.len() > 30);+ assert!(+ rays.iter()+ .all(|(a, b)| [a, b].iter().all(|q| q.x >= -1e-3 && q.x <= 200.001 && q.y >= -1e-3 && q.y <= 100.001))+ );+ }++ #[test]+ fn assisted_strokes_keep_to_the_guide() {+ let g = on(GuideKind::Grid);+ let start = Vec2::new(10.0, 10.0);+ assert_eq!(g.assist(start, Vec2::new(50.0, 14.0)), Vec2::new(50.0, 10.0));+ assert!((g.assist(start, Vec2::new(12.0, 60.0)).x - 10.0).abs() < 1e-4);+ let iso = on(GuideKind::Isometric);+ let p = iso.assist(start, Vec2::new(60.0, 40.0));+ let d = p - start;+ assert!((d.y.atan2(d.x) - FRAC_PI_6).abs() < 1e-4);+ // off, nothing moves+ let off = Guide { assisted: false, ..g };+ assert_eq!(off.assist(start, Vec2::new(50.0, 14.0)), Vec2::new(50.0, 14.0));+ }++ #[test]+ fn symmetry_mirrors_and_turns() {+ let g = on(GuideKind::Symmetry);+ // vertical: mirrored across x = 100+ let c = g.copies(Vec2::new(70.0, 20.0));+ assert_eq!(c.len(), 1);+ assert!((c[0].0.x - 130.0).abs() < 1e-3 && (c[0].0.y - 20.0).abs() < 1e-3 && c[0].2);+ let quad = Guide { symmetry: SymmetryKind::Quadrant, ..g.clone() };+ assert_eq!(quad.copies(Vec2::new(70.0, 20.0)).len(), 3);+ let radial = Guide { symmetry: SymmetryKind::Radial, rotational: true, ..g.clone() };+ let r = radial.copies(Vec2::new(110.0, 50.0));+ assert_eq!(r.len(), 7);+ assert!(r.iter().all(|(q, _, mirrored)| (q.distance(Vec2::new(100.0, 50.0)) - 10.0).abs() < 1e-3 && !mirrored));+ assert!(on(GuideKind::Grid).copies(Vec2::ZERO).is_empty());+ }++ #[test]+ fn the_colour_bar_runs_dark_to_light() {+ assert!(bar_color(0.0).iter().all(|&v| v < 0.05));+ assert!(bar_color(1.0).iter().all(|&v| v > 0.85));+ assert_eq!(bar_color(f32::NAN), bar_color(0.0));+ }+}diff --git a/crates/engine/src/icc.rs b/crates/engine/src/icc.rsnew file mode 100644index 0000000..c520a24--- /dev/null+++ b/crates/engine/src/icc.rs@@ -0,0 +1,218 @@+//! ICC profiles for the colour profiles a canvas can be in, made here from the colour spaces'+//! definitions: a version 4 RGB display profile with a matrix and three tone curves.+//!+//! The primaries come from their chromaticities and the white point (D65), adapted to the ICC's+//! D50 with the Bradford transform; the tone curve is the sRGB curve as a parametric curve.++use crate::profile::Profile;++/// D65's chromaticity.+const D65: (f64, f64) = (0.3127, 0.3290);++/// The ICC connection space's white, D50, as XYZ.+const D50: [f64; 3] = [0.9642, 1.0, 0.8249];++/// The Bradford cone response matrix.+const BRADFORD: [[f64; 3]; 3] = [[0.8951, 0.2664, -0.1614], [-0.7502, 1.7135, 0.0367], [0.0389, -0.0685, 1.0296]];++/// The red, green and blue chromaticities of `profile`.+fn primaries(profile: Profile) -> [(f64, f64); 3] {+ if profile.is_p3() {+ [(0.680, 0.320), (0.265, 0.690), (0.150, 0.060)]+ } else {+ [(0.640, 0.330), (0.300, 0.600), (0.150, 0.060)]+ }+}++fn xyz(c: (f64, f64)) -> [f64; 3] {+ [c.0 / c.1, 1.0, (1.0 - c.0 - c.1) / c.1]+}++fn transpose(m: [[f64; 3]; 3]) -> [[f64; 3]; 3] {+ let [[a, b, c], [d, e, f], [g, h, i]] = m;+ [[a, d, g], [b, e, h], [c, f, i]]+}++fn mul(a: [[f64; 3]; 3], b: [[f64; 3]; 3]) -> [[f64; 3]; 3] {+ let columns = transpose(b);+ a.map(|row| columns.map(|col| row[0] * col[0] + row[1] * col[1] + row[2] * col[2]))+}++fn apply(m: [[f64; 3]; 3], v: [f64; 3]) -> [f64; 3] {+ m.map(|row| row[0] * v[0] + row[1] * v[1] + row[2] * v[2])+}++fn inverse(m: [[f64; 3]; 3]) -> [[f64; 3]; 3] {+ let [[a, b, c], [d, e, f], [g, h, i]] = m;+ let det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);+ [+ [(e * i - f * h) / det, (c * h - b * i) / det, (b * f - c * e) / det],+ [(f * g - d * i) / det, (a * i - c * g) / det, (c * d - a * f) / det],+ [(d * h - e * g) / det, (b * g - a * h) / det, (a * e - b * d) / det],+ ]+}++/// The Bradford adaptation from `from` white (XYZ) to D50.+fn adaptation(from: [f64; 3]) -> [[f64; 3]; 3] {+ let s = apply(BRADFORD, from);+ let d = apply(BRADFORD, D50);+ let scale = [[d[0] / s[0], 0.0, 0.0], [0.0, d[1] / s[1], 0.0], [0.0, 0.0, d[2] / s[2]]];+ mul(inverse(BRADFORD), mul(scale, BRADFORD))+}++/// The profile's RGB-to-XYZ matrix (columns red, green, blue), adapted to D50, and the+/// adaptation itself.+fn matrices(profile: Profile) -> ([[f64; 3]; 3], [[f64; 3]; 3]) {+ let [r, g, b] = primaries(profile).map(xyz);+ let white = xyz(D65);+ let m = [[r[0], g[0], b[0]], [r[1], g[1], b[1]], [r[2], g[2], b[2]]];+ let s = apply(inverse(m), white);+ let rgb_to_xyz = m.map(|row| [row[0] * s[0], row[1] * s[1], row[2] * s[2]]);+ let chad = adaptation(white);+ (mul(chad, rgb_to_xyz), chad)+}++/// A number as ICC's s15Fixed16.+fn fixed(v: f64) -> [u8; 4] {+ ((v * 65536.0).round() as i32).to_be_bytes()+}++fn xyz_tag(v: [f64; 3]) -> Vec<u8> {+ let mut t = b"XYZ \0\0\0\0".to_vec();+ for c in v {+ t.extend(fixed(c));+ }+ t+}++/// A 'mluc' text in English.+fn text_tag(s: &str) -> Vec<u8> {+ let utf16: Vec<u8> = s.encode_utf16().flat_map(u16::to_be_bytes).collect();+ let mut t = b"mluc\0\0\0\0".to_vec();+ t.extend(1u32.to_be_bytes());+ t.extend(12u32.to_be_bytes());+ t.extend(b"enUS");+ t.extend((utf16.len() as u32).to_be_bytes());+ t.extend(28u32.to_be_bytes());+ t.extend(utf16);+ t+}++/// The sRGB tone curve as a parametric curve (function type 3).+fn curve_tag() -> Vec<u8> {+ let mut t = b"para\0\0\0\0".to_vec();+ t.extend(3u16.to_be_bytes());+ t.extend([0, 0]);+ for v in [2.4, 1.0 / 1.055, 0.055 / 1.055, 1.0 / 12.92, 0.040_45] {+ t.extend(fixed(v));+ }+ t+}++fn sf32_tag(m: [[f64; 3]; 3]) -> Vec<u8> {+ let mut t = b"sf32\0\0\0\0".to_vec();+ for row in m {+ for v in row {+ t.extend(fixed(v));+ }+ }+ t+}++/// An ICC profile for `profile`: what an image file carries so that other programs show its+/// colours as the canvas does.+pub fn icc(profile: Profile) -> Vec<u8> {+ let (m, chad) = matrices(profile);+ let [red, green, blue] = transpose(m);+ let curve = curve_tag();+ let tags: Vec<(&[u8; 4], Vec<u8>)> = vec![+ (b"desc", text_tag(profile.name())),+ (b"cprt", text_tag("No copyright, use freely")),+ (b"wtpt", xyz_tag(D50)),+ (b"chad", sf32_tag(chad)),+ (b"rXYZ", xyz_tag(red)),+ (b"gXYZ", xyz_tag(green)),+ (b"bXYZ", xyz_tag(blue)),+ (b"rTRC", curve.clone()),+ (b"gTRC", curve.clone()),+ (b"bTRC", curve),+ ];+ // the tag table, then each tag's data on a 4-byte boundary+ let mut offset = 128 + 4 + 12 * tags.len();+ let mut table = (tags.len() as u32).to_be_bytes().to_vec();+ let mut data = Vec::new();+ for (sig, bytes) in &tags {+ table.extend(sig.as_slice());+ table.extend((offset as u32).to_be_bytes());+ table.extend((bytes.len() as u32).to_be_bytes());+ data.extend(bytes);+ while data.len() % 4 != 0 {+ data.push(0);+ }+ offset = 128 + 4 + 12 * tags.len() + data.len();+ }+ let size = 128 + table.len() + data.len();+ let mut out = Vec::with_capacity(size);+ out.extend((size as u32).to_be_bytes());+ out.extend([0; 4]); // preferred CMM: none+ out.extend([4, 0x30, 0, 0]); // version 4.3+ out.extend(b"mntrRGB XYZ ");+ out.extend([0x07, 0xEA, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0]); // made 2026-01-01+ out.extend(b"acsp");+ out.extend([0; 4 + 4 + 4 + 4 + 8 + 4]); // platform, flags, maker, model, attributes, intent (perceptual)+ for c in D50 {+ out.extend(fixed(c));+ }+ out.extend([0; 4 + 16 + 28]); // creator, profile ID (not computed), reserved+ out.extend(table);+ out.extend(data);+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ fn be32(b: &[u8], at: usize) -> u32 {+ u32::from_be_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]])+ }++ fn tag<'a>(icc: &'a [u8], sig: &[u8; 4]) -> &'a [u8] {+ let n = be32(icc, 128) as usize;+ for i in 0..n {+ let at = 132 + 12 * i;+ if &icc[at..at + 4] == sig {+ let (off, len) = (be32(icc, at + 4) as usize, be32(icc, at + 8) as usize);+ return &icc[off..off + len];+ }+ }+ panic!("no tag {sig:?}");+ }++ fn xyz_of(t: &[u8]) -> [f64; 3] {+ [0, 1, 2]+ .map(|i| i32::from_be_bytes([t[8 + 4 * i], t[9 + 4 * i], t[10 + 4 * i], t[11 + 4 * i]]) as f64 / 65536.0)+ }++ #[test]+ fn the_profiles_carry_their_primaries() {+ for (profile, red, green, blue) in [+ (Profile::Srgb, [0.4361, 0.2225, 0.0139], [0.3851, 0.7169, 0.0971], [0.1431, 0.0606, 0.7141]),+ (Profile::DisplayP3, [0.5151, 0.2412, -0.0011], [0.2920, 0.6922, 0.0419], [0.1571, 0.0666, 0.7841]),+ ] {+ let icc = icc(profile);+ assert_eq!(be32(&icc, 0) as usize, icc.len());+ assert_eq!(&icc[36..40], b"acsp");+ assert_eq!(&icc[12..20], b"mntrRGB ");+ for (sig, want) in [(b"rXYZ", red), (b"gXYZ", green), (b"bXYZ", blue)] {+ let got = xyz_of(tag(&icc, sig));+ assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 5e-4), "{profile:?} {sig:?} {got:?}");+ }+ // the three primaries add up to the connection space's white+ let sum = [0, 1, 2]+ .map(|i| xyz_of(tag(&icc, b"rXYZ"))[i] + xyz_of(tag(&icc, b"gXYZ"))[i] + xyz_of(tag(&icc, b"bXYZ"))[i]);+ assert!(sum.iter().zip(D50).all(|(s, w)| (s - w).abs() < 2e-3), "{sum:?}");+ assert_eq!(&tag(&icc, b"rTRC")[..4], b"para");+ }+ }+}diff --git a/crates/engine/src/input.rs b/crates/engine/src/input.rsnew file mode 100644index 0000000..7a02de6--- /dev/null+++ b/crates/engine/src/input.rs@@ -0,0 +1,45 @@+//! Input as the platform reports it.++use crate::geom::Vec2;++/// What touched the canvas.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Pointer {+ Finger,+ Stylus,+ /// The eraser end of a pen.+ StylusEraser,+ Mouse,+}++impl Pointer {+ /// Whether the input reports pressure (fingers and mice don't).+ pub fn has_pressure(self) -> bool {+ matches!(self, Pointer::Stylus | Pointer::StylusEraser)+ }+}++/// One input sample, including the in-between samples the platform batched since the last event.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Sample {+ /// Position in screen pixels (or canvas pixels once the view has mapped it).+ pub pos: Vec2,+ /// 0..1; ignored for inputs without pressure.+ pub pressure: f32,+ /// Angle from the screen's normal, radians (0 = upright, π/2 = flat).+ pub tilt: f32,+ /// Direction the pen leans towards, radians clockwise from screen-up.+ pub azimuth: f32,+ /// Milliseconds on a monotonic clock.+ pub time_ms: f64,+}++impl Sample {+ pub fn at(pos: Vec2, pressure: f32, time_ms: f64) -> Sample {+ Sample { pos, pressure, tilt: 0.0, azimuth: 0.0, time_ms }+ }++ pub fn is_finite(&self) -> bool {+ self.pos.is_finite() && self.pressure.is_finite() && self.time_ms.is_finite()+ }+}diff --git a/crates/engine/src/jpeg.rs b/crates/engine/src/jpeg.rsnew file mode 100644index 0000000..333532c--- /dev/null+++ b/crates/engine/src/jpeg.rs@@ -0,0 +1,357 @@+//! A baseline JPEG encoder (8-bit, YCbCr 4:4:4, the standard's example tables), for pictures+//! inside the files we write (a PDF's pages).++/// The standard's example quantisation tables (luminance, chrominance), in row order.+const LUMA_Q: [u8; 64] = [+ 16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51,+ 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, 120, 101,+ 72, 92, 95, 98, 112, 100, 103, 99,+];+const CHROMA_Q: [u8; 64] = [+ 17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99,+ 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,+ 99, 99, 99, 99, 99, 99,+];++/// Where each coefficient goes in the zigzag order.+const ZIGZAG: [usize; 64] = [+ 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21,+ 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54,+ 47, 55, 62, 63,+];++// the standard's example Huffman tables: code counts per length 1..16, then the symbols+const DC_LUMA_BITS: [u8; 16] = [0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0];+const DC_CHROMA_BITS: [u8; 16] = [0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0];+const DC_SYMBOLS: [u8; 12] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];+const AC_LUMA_BITS: [u8; 16] = [0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7D];+const AC_LUMA_SYMBOLS: [u8; 162] = [+ 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14,+ 0x32, 0x81, 0x91, 0xA1, 0x08, 0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09,+ 0x0A, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A,+ 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65,+ 0x66, 0x67, 0x68, 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88,+ 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9,+ 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA,+ 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA,+ 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA,+];+const AC_CHROMA_BITS: [u8; 16] = [0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77];+const AC_CHROMA_SYMBOLS: [u8; 162] = [+ 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32,+ 0x81, 0x08, 0x14, 0x42, 0x91, 0xA1, 0xB1, 0xC1, 0x09, 0x23, 0x33, 0x52, 0xF0, 0x15, 0x62, 0x72, 0xD1, 0x0A, 0x16,+ 0x24, 0x34, 0xE1, 0x25, 0xF1, 0x17, 0x18, 0x19, 0x1A, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x35, 0x36, 0x37, 0x38, 0x39,+ 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64,+ 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x82, 0x83, 0x84, 0x85, 0x86,+ 0x87, 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7,+ 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8,+ 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9,+ 0xEA, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA,+];++/// A Huffman table as (code, length) per symbol.+struct Codes([(u16, u8); 256]);++impl Codes {+ fn new(bits: &[u8; 16], symbols: &[u8]) -> Codes {+ let mut table = [(0u16, 0u8); 256];+ let mut code = 0u16;+ let mut k = 0;+ for (len, &count) in bits.iter().enumerate() {+ for _ in 0..count {+ if let Some(t) = symbols.get(k).and_then(|&s| table.get_mut(usize::from(s))) {+ *t = (code, len as u8 + 1);+ }+ code = code.wrapping_add(1);+ k += 1;+ }+ code <<= 1;+ }+ Codes(table)+ }++ fn get(&self, symbol: u8) -> (u16, u8) {+ self.0.get(usize::from(symbol)).copied().unwrap_or((0, 0))+ }+}++/// Bits written most significant first, 0xFF bytes stuffed with a zero.+struct Bits {+ out: Vec<u8>,+ acc: u32,+ n: u32,+}++impl Bits {+ fn put(&mut self, value: u16, len: u8) {+ if len == 0 {+ return;+ }+ self.acc = (self.acc << len) | (u32::from(value) & ((1 << len) - 1));+ self.n += u32::from(len);+ while self.n >= 8 {+ let byte = (self.acc >> (self.n - 8)) as u8;+ self.out.push(byte);+ if byte == 0xFF {+ self.out.push(0);+ }+ self.n -= 8;+ }+ self.acc &= (1 << self.n) - 1;+ }++ /// Pads the last byte with ones.+ fn flush(&mut self) {+ if self.n > 0 {+ let pad = 8 - self.n as u8;+ self.put((1 << pad) - 1, pad);+ }+ }+}++/// The 8 × 8 forward DCT of `block` (values centred on 0), rows then columns.+fn dct(block: &mut [f32; 64]) {+ let mut cos = [[0f32; 8]; 8];+ for (u, row) in cos.iter_mut().enumerate() {+ let c = if u == 0 { std::f32::consts::FRAC_1_SQRT_2 } else { 1.0 };+ for (x, v) in row.iter_mut().enumerate() {+ *v = 0.5 * c * (((2 * x + 1) as f32) * (u as f32) * std::f32::consts::PI / 16.0).cos();+ }+ }+ let mut tmp = [0f32; 64];+ for y in 0..8 {+ for (u, row) in cos.iter().enumerate() {+ let mut s = 0.0;+ for (x, c) in row.iter().enumerate() {+ s += block.get(y * 8 + x).copied().unwrap_or(0.0) * c;+ }+ if let Some(t) = tmp.get_mut(y * 8 + u) {+ *t = s;+ }+ }+ }+ for u in 0..8 {+ for (v, row) in cos.iter().enumerate() {+ let mut s = 0.0;+ for (y, c) in row.iter().enumerate() {+ s += tmp.get(y * 8 + u).copied().unwrap_or(0.0) * c;+ }+ if let Some(b) = block.get_mut(v * 8 + u) {+ *b = s;+ }+ }+ }+}++/// A quantisation table scaled for `quality` (1..100), in row order.+fn scaled(table: &[u8; 64], quality: u8) -> [u8; 64] {+ let q = u32::from(quality.clamp(1, 100));+ let scale = if q < 50 { 5000 / q } else { 200 - 2 * q };+ table.map(|v| ((u32::from(v) * scale + 50) / 100).clamp(1, 255) as u8)+}++/// The number of bits `v` needs, and those bits as JPEG writes a coefficient.+fn magnitude(v: i32) -> (u8, u16) {+ let a = v.unsigned_abs();+ let size = (32 - a.leading_zeros()) as u8;+ // a negative value is written as its ones' complement in `size` bits+ let raw = if v < 0 { (v - 1) as u32 } else { v as u32 };+ (size, (raw & ((1u32 << size) - 1)) as u16)+}++/// How a JPEG's components are kept.+#[derive(Clone, Copy, PartialEq, Eq)]+enum Kind {+ /// Luminance and two colour differences, from RGB.+ Ycc,+ /// Four inks, each inverted, as print programs keep CMYK JPEGs (with their marker saying so).+ Cmyk,+}++/// `rgb` (`width` × `height`, 3 bytes a pixel, top row first) as a baseline JPEG at `quality`+/// (1..100).+pub fn encode(rgb: &[u8], width: u32, height: u32, quality: u8) -> Vec<u8> {+ encode_with(Kind::Ycc, width, height, quality, |at| {+ let (r, g, b) = match rgb.get(at * 3..at * 3 + 3) {+ Some(&[r, g, b]) => (f32::from(r), f32::from(g), f32::from(b)),+ _ => (0.0, 0.0, 0.0),+ };+ [+ 0.299 * r + 0.587 * g + 0.114 * b - 128.0,+ -0.168_736 * r - 0.331_264 * g + 0.5 * b,+ 0.5 * r - 0.418_688 * g - 0.081_312 * b,+ 0.0,+ ]+ })+}++/// `cmyk` (`width` × `height`, 4 bytes a pixel: cyan, magenta, yellow and black ink, 0 for none)+/// as a baseline JPEG at `quality` (1..100), each ink inverted under an Adobe marker as print+/// programs keep them (a PDF reading it says `/Decode [1 0 1 0 1 0 1 0]`).+pub fn encode_cmyk(cmyk: &[u8], width: u32, height: u32, quality: u8) -> Vec<u8> {+ encode_with(Kind::Cmyk, width, height, quality, |at| {+ let ink = |k: usize| f32::from(cmyk.get(at * 4 + k).copied().unwrap_or(0));+ [127.0 - ink(0), 127.0 - ink(1), 127.0 - ink(2), 127.0 - ink(3)]+ })+}++/// The JPEG of a `width` × `height` picture whose components (level-shifted: −128..127) at each+/// pixel `pixel` gives, top row first.+fn encode_with(kind: Kind, width: u32, height: u32, quality: u8, pixel: impl Fn(usize) -> [f32; 4]) -> Vec<u8> {+ let (w, h) = (width.clamp(1, 65535) as usize, height.clamp(1, 65535) as usize);+ let n = if kind == Kind::Cmyk { 4 } else { 3 };+ // the tables (quantisation and Huffman) each component uses: inks all use the first+ let table_of = |c: usize| usize::from(kind == Kind::Ycc && c > 0);+ let tables = [scaled(&LUMA_Q, quality), scaled(&CHROMA_Q, quality)];+ let mut out = vec![0xFF, 0xD8];+ match kind {+ // JFIF header+ Kind::Ycc => out.extend_from_slice(&[0xFF, 0xE0, 0, 16, b'J', b'F', b'I', b'F', 0, 1, 1, 0, 0, 1, 0, 1, 0, 0]),+ // the Adobe marker: version 100, no flags, no colour transform+ Kind::Cmyk => out.extend_from_slice(&[0xFF, 0xEE, 0, 14, b'A', b'd', b'o', b'b', b'e', 0, 100, 0, 0, 0, 0, 0]),+ }+ for (id, t) in tables.iter().enumerate() {+ out.extend_from_slice(&[0xFF, 0xDB, 0, 67, id as u8]);+ out.extend(ZIGZAG.iter().map(|&i| t.get(i).copied().unwrap_or(1)));+ }+ out.extend_from_slice(&[0xFF, 0xC0]);+ out.extend_from_slice(&(8 + 3 * n as u16).to_be_bytes());+ out.push(8);+ out.extend_from_slice(&(h as u16).to_be_bytes());+ out.extend_from_slice(&(w as u16).to_be_bytes());+ out.push(n as u8);+ for c in 0..n {+ out.extend_from_slice(&[c as u8 + 1, 0x11, table_of(c) as u8]);+ }+ for (class_id, bits, symbols) in [+ (0x00u8, &DC_LUMA_BITS, &DC_SYMBOLS[..]),+ (0x10, &AC_LUMA_BITS, &AC_LUMA_SYMBOLS[..]),+ (0x01, &DC_CHROMA_BITS, &DC_SYMBOLS[..]),+ (0x11, &AC_CHROMA_BITS, &AC_CHROMA_SYMBOLS[..]),+ ] {+ let len = (3 + 16 + symbols.len()) as u16;+ out.extend_from_slice(&[0xFF, 0xC4]);+ out.extend_from_slice(&len.to_be_bytes());+ out.push(class_id);+ out.extend_from_slice(bits);+ out.extend_from_slice(symbols);+ }+ out.extend_from_slice(&[0xFF, 0xDA]);+ out.extend_from_slice(&(6 + 2 * n as u16).to_be_bytes());+ out.push(n as u8);+ for c in 0..n {+ let t = table_of(c) as u8;+ out.extend_from_slice(&[c as u8 + 1, (t << 4) | t]);+ }+ out.extend_from_slice(&[0, 63, 0]);++ let dc = [Codes::new(&DC_LUMA_BITS, &DC_SYMBOLS), Codes::new(&DC_CHROMA_BITS, &DC_SYMBOLS)];+ let ac = [Codes::new(&AC_LUMA_BITS, &AC_LUMA_SYMBOLS), Codes::new(&AC_CHROMA_BITS, &AC_CHROMA_SYMBOLS)];+ let mut bits = Bits { out, acc: 0, n: 0 };+ let mut previous = [0i32; 4];+ for by in (0..h).step_by(8) {+ for bx in (0..w).step_by(8) {+ // the block's components, edges repeated past the picture+ let mut blocks = [[0f32; 64]; 4];+ for k in 0..64 {+ let (sx, sy) = ((bx + k % 8).min(w - 1), (by + k / 8).min(h - 1));+ for (block, value) in blocks.iter_mut().zip(pixel(sy * w + sx)) {+ if let Some(slot) = block.get_mut(k) {+ *slot = value;+ }+ }+ }+ for ((c, block), last) in blocks.iter_mut().enumerate().take(n).zip(previous.iter_mut()) {+ let t = table_of(c);+ let (Some(dc), Some(ac)) = (dc.get(t), ac.get(t)) else { continue };+ dct(block);+ let q = tables.get(t).copied().unwrap_or([1; 64]);+ let coeff: Vec<i32> = ZIGZAG+ .iter()+ .map(|&i| {+ (block.get(i).copied().unwrap_or(0.0) / f32::from(q.get(i).copied().unwrap_or(1))).round()+ as i32+ })+ .collect();+ let first = coeff.first().copied().unwrap_or(0);+ let (size, value) = magnitude(first - *last);+ *last = first;+ let (code, len) = dc.get(size);+ bits.put(code, len);+ bits.put(value, size);+ let mut zeros = 0u8;+ for &v in coeff.get(1..).unwrap_or(&[]) {+ if v == 0 {+ zeros += 1;+ continue;+ }+ while zeros >= 16 {+ let (code, len) = ac.get(0xF0);+ bits.put(code, len);+ zeros -= 16;+ }+ let (size, value) = magnitude(v);+ let (code, len) = ac.get((zeros << 4) | size);+ bits.put(code, len);+ bits.put(value, size);+ zeros = 0;+ }+ if zeros > 0 {+ let (code, len) = ac.get(0x00);+ bits.put(code, len);+ }+ }+ }+ }+ bits.flush();+ let mut out = bits.out;+ out.extend_from_slice(&[0xFF, 0xD9]);+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_picture_encodes_to_a_well_formed_file() {+ let (w, h) = (37u32, 21u32);+ let rgb: Vec<u8> = (0..w * h).flat_map(|i| [(i % 256) as u8, (i * 3 % 256) as u8, 128]).collect();+ let jpg = encode(&rgb, w, h, 85);+ assert_eq!(&jpg[..2], &[0xFF, 0xD8]);+ assert_eq!(&jpg[jpg.len() - 2..], &[0xFF, 0xD9]);+ // the frame header gives the size+ let sof = jpg.windows(2).position(|m| m == [0xFF, 0xC0]).unwrap();+ assert_eq!(u16::from_be_bytes([jpg[sof + 5], jpg[sof + 6]]), 21);+ assert_eq!(u16::from_be_bytes([jpg[sof + 7], jpg[sof + 8]]), 37);+ // lower quality, smaller file+ assert!(encode(&rgb, w, h, 20).len() < jpg.len());+ // if asked to, a sample is written for a decoder to check+ if let Ok(out) = std::env::var("JPEG_SAMPLE_OUT") {+ std::fs::write(out, &jpg).unwrap();+ }+ }++ #[test]+ fn inks_encode_too() {+ let (w, h) = (19u32, 11u32);+ let cmyk: Vec<u8> = (0..w * h).flat_map(|i| [(i % 256) as u8, 0, 200, 30]).collect();+ let jpg = encode_cmyk(&cmyk, w, h, 90);+ // the Adobe marker, and four components in the frame+ assert!(jpg.windows(7).any(|m| m == [0xFF, 0xEE, 0, 14, b'A', b'd', b'o']));+ let sof = jpg.windows(2).position(|m| m == [0xFF, 0xC0]).unwrap();+ assert_eq!(jpg[sof + 9], 4);+ if let Ok(out) = std::env::var("JPEG_CMYK_SAMPLE_OUT") {+ std::fs::write(out, &jpg).unwrap();+ }+ }++ #[test]+ fn coefficients_take_the_bits_they_need() {+ assert_eq!(magnitude(0), (0, 0));+ assert_eq!(magnitude(1), (1, 1));+ assert_eq!(magnitude(-1), (1, 0));+ assert_eq!(magnitude(-3), (2, 0));+ assert_eq!(magnitude(5), (3, 5));+ }+}diff --git a/crates/engine/src/keyed.rs b/crates/engine/src/keyed.rsnew file mode 100644index 0000000..dfa977b--- /dev/null+++ b/crates/engine/src/keyed.rs@@ -0,0 +1,264 @@+//! Keyed archives: an object graph kept in a binary property list (`$objects`, `$top`). Reading+//! follows references and unwraps the common containers; writing builds the object list.++use crate::plist::{self, Value};++/// A keyed archive read from a property list.+pub struct Archive {+ objects: Vec<Value>,+ root: u64,+}++/// An object of an archive: its fields, and its class's name.+#[derive(Clone, Copy)]+pub struct Object<'a> {+ archive: &'a Archive,+ fields: &'a Value,+}++impl Archive {+ /// The archive in `bytes`, if it is one.+ pub fn read(bytes: &[u8]) -> Option<Archive> {+ let top = plist::read(bytes)?;+ let objects = match top.get("$objects")? {+ Value::Array(a) => a.clone(),+ _ => return None,+ };+ let root = top.get("$top")?.get("root")?.as_uid()?;+ Some(Archive { objects, root })+ }++ /// The archive's root object.+ pub fn root(&self) -> Option<Object<'_>> {+ self.object(self.root)+ }++ fn object(&self, uid: u64) -> Option<Object<'_>> {+ let fields = self.objects.get(usize::try_from(uid).ok()?)?;+ match fields {+ Value::Dict(_) => Some(Object { archive: self, fields }),+ _ => None,+ }+ }++ /// The value at `uid`, references followed (`$null` reads as none).+ fn value(&self, uid: u64) -> Option<&Value> {+ match self.objects.get(usize::try_from(uid).ok()?)? {+ Value::String(s) if s == "$null" => None,+ v => Some(v),+ }+ }+}++impl<'a> Object<'a> {+ /// The class the object was archived as.+ pub fn class(&self) -> Option<&'a str> {+ let uid = self.fields.get("$class")?.as_uid()?;+ self.archive.object(uid)?.fields.get("$classname")?.as_str()+ }++ /// The raw value of `key`, a reference followed once.+ pub fn raw(&self, key: &str) -> Option<&'a Value> {+ match self.fields.get(key)? {+ Value::Uid(u) => self.archive.value(*u),+ v => Some(v),+ }+ }++ /// The object `key` refers to.+ pub fn object(&self, key: &str) -> Option<Object<'a>> {+ self.archive.object(self.fields.get(key)?.as_uid()?)+ }++ pub fn int(&self, key: &str) -> Option<i64> {+ self.raw(key)?.as_int()+ }++ pub fn real(&self, key: &str) -> Option<f64> {+ self.raw(key)?.as_real()+ }++ pub fn bool(&self, key: &str) -> Option<bool> {+ self.raw(key)?.as_bool()+ }++ pub fn data(&self, key: &str) -> Option<&'a [u8]> {+ match self.raw(key)? {+ Value::Data(d) => Some(d),+ // data kept as an object (NSMutableData)+ Value::Dict(_) => self.object(key)?.fields.get("NS.data")?.as_data(),+ _ => None,+ }+ }++ /// A string: inline, or an `NSString` object.+ pub fn string(&self, key: &str) -> Option<String> {+ match self.raw(key)? {+ Value::String(s) => Some(s.clone()),+ Value::Dict(_) => self.object(key)?.fields.get("NS.string")?.as_str().map(str::to_owned),+ _ => None,+ }+ }++ /// The values of an array (`NS.objects`) that `key` refers to, references followed once:+ /// strings and numbers kept inline.+ pub fn values(&self, key: &str) -> Vec<&'a Value> {+ let Some(list) = self.object(key).and_then(|o| o.fields.get("NS.objects")?.as_array()) else {+ return Vec::new();+ };+ list.iter()+ .filter_map(|v| match v {+ Value::Uid(u) => self.archive.value(*u),+ v => Some(v),+ })+ .collect()+ }++ /// The objects of an array (`NS.objects`) that `key` refers to.+ pub fn array(&self, key: &str) -> Vec<Object<'a>> {+ let Some(list) = self.object(key).and_then(|o| o.fields.get("NS.objects")?.as_array()) else {+ return Vec::new();+ };+ list.iter().filter_map(|v| self.archive.object(v.as_uid()?)).collect()+ }+}++/// Builds a keyed archive: objects are added and referred to by the index [`Builder::add`] gives.+pub struct Builder {+ objects: Vec<Value>,+ classes: Vec<(String, u64)>,+}++impl Default for Builder {+ fn default() -> Builder {+ Builder::new()+ }+}++impl Builder {+ pub fn new() -> Builder {+ Builder { objects: vec![Value::String("$null".to_owned())], classes: Vec::new() }+ }++ /// The reference to nothing.+ pub fn null() -> Value {+ Value::Uid(0)+ }++ /// Adds a value (a string, data...) and gives its reference.+ pub fn add(&mut self, v: Value) -> Value {+ self.objects.push(v);+ Value::Uid(self.objects.len() as u64 - 1)+ }++ /// Reserves a place for an object filled in later with [`Builder::set`] (for objects that refer+ /// back to themselves through others).+ pub fn reserve(&mut self) -> Value {+ self.add(Value::Null)+ }++ /// Fills the place `at` reserved.+ pub fn set(&mut self, at: &Value, v: Value) {+ if let Some(slot) = at.as_uid().and_then(|u| self.objects.get_mut(usize::try_from(u).ok()?)) {+ *slot = v;+ }+ }++ /// The reference to a class record `name`, whose class chain is `chain` (itself first).+ pub fn class(&mut self, chain: &[&str]) -> Value {+ let name = chain.first().copied().unwrap_or("NSObject");+ if let Some((_, uid)) = self.classes.iter().find(|(n, _)| n == name) {+ return Value::Uid(*uid);+ }+ let record = Value::Dict(vec![+ ("$classes".to_owned(), Value::Array(chain.iter().map(|c| Value::String((*c).to_owned())).collect())),+ ("$classname".to_owned(), Value::String(name.to_owned())),+ ]);+ let r = self.add(record);+ if let Some(uid) = r.as_uid() {+ self.classes.push((name.to_owned(), uid));+ }+ r+ }++ /// An object of class `chain` with `fields`.+ pub fn object(&mut self, chain: &[&str], fields: Vec<(&str, Value)>) -> Value {+ let at = self.reserve();+ self.fill(&at, chain, fields);+ at+ }++ /// Fills a reserved place with an object of class `chain`.+ pub fn fill(&mut self, at: &Value, chain: &[&str], fields: Vec<(&str, Value)>) {+ let class = self.class(chain);+ let mut entries: Vec<(String, Value)> = fields.into_iter().map(|(k, v)| (k.to_owned(), v)).collect();+ entries.push(("$class".to_owned(), class));+ self.set(at, Value::Dict(entries));+ }++ /// A string object's reference.+ pub fn string(&mut self, s: &str) -> Value {+ self.add(Value::String(s.to_owned()))+ }++ /// An array (`NSArray`, or `NSMutableArray` if `mutable`) of references.+ pub fn array(&mut self, items: Vec<Value>, mutable: bool) -> Value {+ let chain: &[&str] =+ if mutable { &["NSMutableArray", "NSArray", "NSObject"] } else { &["NSArray", "NSObject"] };+ self.object(chain, vec![("NS.objects", Value::Array(items))])+ }++ /// The archive, rooted at `root`.+ pub fn finish(self, root: Value) -> Vec<u8> {+ plist::write(&Value::Dict(vec![+ ("$version".to_owned(), Value::Int(100_000)),+ ("$archiver".to_owned(), Value::String("NSKeyedArchiver".to_owned())),+ ("$top".to_owned(), Value::Dict(vec![("root".to_owned(), root)])),+ ("$objects".to_owned(), Value::Array(self.objects)),+ ]))+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn an_object_graph_round_trips() {+ let mut b = Builder::new();+ let doc = b.reserve();+ let name = b.string("Layer 1");+ let layer = b.object(+ &["SilicaLayer", "ValkyrieLayer", "NSObject"],+ vec![+ ("name", name),+ ("opacity", Value::Real(0.5)),+ ("hidden", Value::Bool(true)),+ ("document", doc.clone()),+ ],+ );+ let layers = b.array(vec![layer], true);+ let title = b.string("Untitled");+ b.fill(+ &doc,+ &["SilicaDocument", "ValkyrieDocument", "NSObject"],+ vec![("layers", layers), ("name", title), ("tileSize", Value::Int(256)), ("mask", Builder::null())],+ );+ let bytes = b.finish(doc);++ let archive = Archive::read(&bytes).unwrap();+ let root = archive.root().unwrap();+ assert_eq!(root.class(), Some("SilicaDocument"));+ assert_eq!(root.string("name").as_deref(), Some("Untitled"));+ assert_eq!(root.int("tileSize"), Some(256));+ assert!(root.object("mask").is_none());+ let layers = root.array("layers");+ assert_eq!(layers.len(), 1);+ let l = layers.first().unwrap();+ assert_eq!(l.class(), Some("SilicaLayer"));+ assert_eq!(l.string("name").as_deref(), Some("Layer 1"));+ assert_eq!(l.real("opacity"), Some(0.5));+ assert_eq!(l.bool("hidden"), Some(true));+ assert_eq!(l.object("document").and_then(|d| d.class()), Some("SilicaDocument"));+ }+}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsnew file mode 100644index 0000000..f489f71--- /dev/null+++ b/crates/engine/src/lib.rs@@ -0,0 +1,37 @@+//! ProCraft's painting engine: the document model, brushes and stroke geometry, and the canvas+//! view. No GPU and no platform code: `procraft-gpu` draws what this crate describes, and the app+//! feeds it input.++pub mod animation;+pub mod applz4;+pub mod base64;+pub mod brush;+pub mod brushfile;+pub mod cms;+pub mod cmyk;+pub mod crop;+pub mod curve;+pub mod document;+pub mod formats;+pub mod geom;+pub mod guide;+pub mod icc;+pub mod input;+pub mod jpeg;+pub mod keyed;+pub mod library;+pub mod motion;+pub mod native;+pub mod plist;+pub mod preview;+pub mod profile;+pub mod quickshape;+pub mod selection;+pub mod stroke;+pub mod studio;+pub mod textures;+pub mod tone;+pub mod transform;+pub mod view;+pub mod warp;+pub mod zip;diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rsnew file mode 100644index 0000000..f1bc57d--- /dev/null+++ b/crates/engine/src/library.rs@@ -0,0 +1,2711 @@+//! ProCraft's own brushes, grouped in sets. Every preset here is designed for ProCraft on the+//! shared brush model (shapes and grains from `textures`).++use crate::brush::{Brush, Grain, GrainMode, Rendering, Shape, Taper, Tilt};+use crate::curve::Curve;+use crate::geom::Vec2;+use crate::textures::{grain, shape};++#[derive(Clone, Debug, PartialEq)]+pub struct BrushSet {+ pub name: &'static str,+ pub brushes: Vec<Brush>,+}++/// The brush sets. A set's place here and a brush's place in its set are how kept libraries refer+/// to what they started from, so new sets and brushes only ever go at the end; [`SHELF`] is the+/// order a new library shows them in.+pub fn library() -> Vec<BrushSet> {+ vec![+ BrushSet {+ name: "Sketching",+ brushes: vec![+ graphite(),+ soft_pencil(),+ technical_pencil(),+ lead_holder(),+ coloured_pencil(),+ sketch_pen(),+ hb_pencil(),+ six_b_pencil(),+ graphite_stick(),+ charcoal_pencil(),+ shading_pencil(),+ ballpoint(),+ ],+ },+ BrushSet {+ name: "Inking",+ brushes: vec![+ Brush::round_pen(),+ fine_liner(),+ brush_pen(),+ dip_pen(),+ marker(),+ dry_ink(),+ studio_ink(),+ gel_pen(),+ thick_liner(),+ felt_tip(),+ rough_ink(),+ ink_bleed(),+ ],+ },+ BrushSet {+ name: "Painting",+ brushes: vec![+ round_brush(),+ flat_brush(),+ bristle_brush(),+ dry_brush(),+ gouache(),+ oil_paint(),+ palette_knife(),+ filbert(),+ fan_brush(),+ rigger(),+ sable(),+ impasto(),+ acrylic(),+ tempera(),+ scumble(),+ ],+ },+ BrushSet {+ name: "Airbrushing",+ brushes: vec![+ soft_airbrush(),+ hard_airbrush(),+ medium_airbrush(),+ fine_mist(),+ flat_airbrush(),+ grainy_airbrush(),+ stipple_airbrush(),+ feather_airbrush(),+ tight_airbrush(),+ ],+ },+ BrushSet {+ name: "Charcoals",+ brushes: vec![+ charcoal_stick(),+ willow_charcoal(),+ compressed_charcoal(),+ vine_charcoal(),+ charcoal_dust(),+ charcoal_block(),+ burnt_stick(),+ smudged_charcoal(),+ soft_charcoal(),+ ],+ },+ BrushSet {+ name: "Textures",+ brushes: vec![+ speckles(),+ canvas_texture(),+ dot_screen(),+ crosshatch(),+ rough_wall(),+ grit(),+ stipple(),+ wood_grain(),+ brickwork(),+ fish_scales(),+ cell_wall(),+ marble(),+ pinstripe(),+ honeycomb(),+ leather(),+ sandpaper(),+ checkerboard(),+ ],+ },+ BrushSet {+ name: "Drawing",+ brushes: vec![+ chalk(),+ soft_pastel(),+ oil_pastel(),+ wax_crayon(),+ conte(),+ hard_pastel(),+ chalk_pencil(),+ pastel_pencil(),+ litho_crayon(),+ ],+ },+ BrushSet {+ name: "Watercolour",+ brushes: vec![+ wet_wash(),+ round_wash(),+ granulating_wash(),+ blot(),+ bleeding_wash(),+ flat_wash(),+ dry_wash(),+ salt(),+ splash(),+ mop_brush(),+ ],+ },+ BrushSet {+ name: "Calligraphy",+ brushes: vec![+ chisel_nib(),+ script_brush(),+ monoline(),+ ribbon(),+ pointed_nib(),+ broad_pen(),+ italic_nib(),+ felt_brush(),+ copperplate(),+ ],+ },+ BrushSet {+ name: "Spray Paint",+ brushes: vec![spray_can(), fat_cap(), flick(), mist(), drips(), hard_spray(), splatter_can(), skinny_cap()],+ },+ BrushSet {+ name: "Nature",+ brushes: vec![+ leaves(),+ grass(),+ clouds(),+ bark(),+ foliage(),+ pine(),+ twigs(),+ moss(),+ flowers(),+ fur(),+ pebbles(),+ feathers(),+ reeds(),+ ],+ },+ BrushSet {+ name: "Effects",+ brushes: vec![+ sparkle(),+ bokeh(),+ smoke(),+ snow(),+ light_trail(),+ glow(),+ stars(),+ bubbles(),+ embers(),+ rain(),+ snowflakes(),+ ],+ },+ BrushSet {+ name: "Pixel",+ brushes: vec![+ pixel(),+ dither(),+ hatching_pen(),+ pixel_checker(),+ pixel_spray(),+ pixel_round(),+ pixel_line(),+ ],+ },+ BrushSet {+ name: "Elements",+ brushes: vec![fire(), smoke_puff(), water_drops(), ripples(), lightning(), ice(), sea_foam(), fog()],+ },+ BrushSet {+ name: "Industrial",+ brushes: vec![+ rusted(),+ cement(),+ grunge(),+ scratched_metal(),+ steel_wool(),+ rivets(),+ grime(),+ oil_stain(),+ ],+ },+ BrushSet {+ name: "Organic",+ brushes: vec![hair(), skin_pores(), freckles(), reptile(), coral(), lichen(), seeds(), veins()],+ },+ BrushSet {+ name: "Abstract",+ brushes: vec![+ hearts(),+ confetti(),+ triangles(),+ diamonds(),+ speed_lines(),+ scribbles(),+ dot_trail(),+ dashes(),+ ],+ },+ BrushSet {+ name: "Touchups",+ brushes: vec![soft_blender(), grainy_blender(), retouch(), highlight(), shadow(), noise(), fine_detail()],+ },+ BrushSet {+ name: "Retro",+ brushes: vec![+ ben_day(),+ screen_tone(),+ comic_ink(),+ retro_stipple(),+ pop_dots(),+ retro_lines(),+ offset_print(),+ ],+ },+ BrushSet {+ name: "Vintage",+ brushes: vec![+ worn_ink(),+ letterpress(),+ old_paper(),+ sepia_wash(),+ scratchy_pen(),+ rubber_stamp(),+ faded_print(),+ ],+ },+ BrushSet {+ name: "Luminance",+ brushes: vec![+ neon(),+ glimmer(),+ lens_dust(),+ flare(),+ halo(),+ light_leak(),+ aurora(),+ fairy_dust(),+ soft_glow(),+ overlay_light(),+ ],+ },+ ]+}++/// The order a new library shows the sets in, by their place in [`library`].+pub const SHELF: [usize; 21] = [0, 1, 6, 2, 7, 8, 3, 9, 4, 5, 16, 13, 19, 20, 14, 15, 10, 11, 17, 18, 12];++fn named(name: &str, b: Brush) -> Brush {+ Brush { name: name.to_owned(), ..b }+}++/// `b` with Brush Studio controls set (keys and values as [`Brush::set_setting`] takes them).+fn with(mut b: Brush, settings: &[(&str, f32)]) -> Brush {+ for &(key, value) in settings {+ b.set_setting(key, value);+ }+ b+}++/// `b` shown at `preview` of its largest size in the library (scattered shapes need room).+fn previewed(b: Brush, preview: f32) -> Brush {+ with(b, &[("preview_size", preview)])+}++/// A grain fixed to the canvas.+fn paper(image: u32, scale: f32, depth: f32) -> Grain {+ Grain { image: Some(image), mode: GrainMode::Texturized, scale, depth, source: None }+}++/// A grain that travels with each stamp.+fn moving(image: u32, scale: f32, depth: f32) -> Grain {+ Grain { image: Some(image), mode: GrainMode::Moving, scale, depth, source: None }+}++/// A pressure curve that rises fast: a light touch already gives most of the line.+fn firm_curve() -> Curve {+ Curve::new(&[Vec2::new(0.0, 0.0), Vec2::new(0.35, 0.6), Vec2::new(1.0, 1.0)])+}++/// A pressure curve that eases in: light touches stay light.+fn soft_curve() -> Curve {+ Curve::new(&[Vec2::new(0.0, 0.0), Vec2::new(0.5, 0.3), Vec2::new(1.0, 1.0)])+}++fn graphite() -> Brush {+ named(+ "Graphite",+ Brush {+ spacing: 0.06,+ streamline: 0.1,+ hardness: 0.7,+ min_size: 1.0,+ max_size: 24.0,+ flow: 0.85,+ pressure_size: 0.3,+ pressure_opacity: 0.9,+ pressure_curve: soft_curve(),+ pen_taper: Taper { start: 0.05, end: 0.08, size: 0.4, opacity: 0.3 },+ touch_taper: Taper::NONE,+ shape: Shape { image: Some(shape::GRAINY_DISC), randomise: true, ..Shape::default() },+ grain: Grain {+ image: Some(grain::PAPER),+ mode: GrainMode::Texturized,+ scale: 120.0,+ depth: 0.6,+ source: None,+ },+ tilt: Tilt { angle: 0.35, size: 1.2, opacity: 0.55 },+ ..Brush::round_pen()+ },+ )+}++fn soft_pencil() -> Brush {+ named(+ "Soft Pencil",+ Brush {+ max_size: 40.0,+ flow: 0.7,+ grain: Grain {+ image: Some(grain::COARSE),+ mode: GrainMode::Texturized,+ scale: 200.0,+ depth: 0.7,+ source: None,+ },+ ..graphite()+ },+ )+}++fn technical_pencil() -> Brush {+ named(+ "Technical Pencil",+ Brush {+ spacing: 0.05,+ hardness: 0.95,+ max_size: 10.0,+ flow: 1.0,+ pressure_size: 0.1,+ pressure_opacity: 0.6,+ shape: Shape::default(),+ grain: Grain {+ image: Some(grain::PAPER),+ mode: GrainMode::Texturized,+ scale: 120.0,+ depth: 0.35,+ source: None,+ },+ tilt: Tilt::default(),+ ..graphite()+ },+ )+}++fn fine_liner() -> Brush {+ named(+ "Fine Liner",+ Brush {+ streamline: 0.5,+ hardness: 0.97,+ max_size: 30.0,+ pressure_size: 0.15,+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ )+}++fn brush_pen() -> Brush {+ named(+ "Brush Pen",+ Brush {+ streamline: 0.45,+ max_size: 80.0,+ pressure_size: 0.95,+ pressure_curve: soft_curve(),+ pen_taper: Taper { start: 0.3, end: 0.4, size: 0.95, opacity: 0.0 },+ touch_taper: Taper { start: 0.2, end: 0.3, size: 0.9, opacity: 0.0 },+ ..Brush::round_pen()+ },+ )+}++fn round_brush() -> Brush {+ named(+ "Round Brush",+ Brush {+ spacing: 0.05,+ streamline: 0.2,+ hardness: 0.6,+ max_size: 160.0,+ flow: 0.35,+ pressure_size: 0.6,+ pressure_opacity: 0.5,+ pen_taper: Taper { start: 0.1, end: 0.1, size: 0.5, opacity: 0.2 },+ ..Brush::round_pen()+ },+ )+}++fn flat_brush() -> Brush {+ named(+ "Flat Brush",+ Brush {+ spacing: 0.03,+ streamline: 0.2,+ max_size: 160.0,+ flow: 0.9,+ pressure_size: 0.4,+ pressure_opacity: 0.4,+ shape: Shape {+ image: Some(shape::FLAT),+ follow: 1.0,+ rotation: std::f32::consts::FRAC_PI_2,+ roundness: 1.0,+ ..Shape::default()+ },+ grain: Grain { image: Some(grain::WEAVE), mode: GrainMode::Moving, scale: 90.0, depth: 0.35, source: None },+ // aligned stamps that don't build up keep the shape's streaks+ rendering: Rendering::Strongest,+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ )+}++fn bristle_brush() -> Brush {+ named(+ "Bristle Brush",+ Brush {+ shape: Shape {+ image: Some(shape::BRISTLES),+ follow: 1.0,+ rotation: std::f32::consts::FRAC_PI_2,+ ..Shape::default()+ },+ grain: Grain { image: Some(grain::FIBRE), mode: GrainMode::Moving, scale: 120.0, depth: 0.6, source: None },+ flow: 0.9,+ ..flat_brush()+ },+ )+}++fn soft_airbrush() -> Brush {+ named(+ "Soft Airbrush",+ Brush {+ spacing: 0.04,+ streamline: 0.0,+ hardness: 0.0,+ min_size: 4.0,+ max_size: 600.0,+ flow: 0.08,+ pressure_size: 0.0,+ pressure_opacity: 0.8,+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ shape: Shape { image: Some(shape::SOFT_ROUND), ..Shape::default() },+ ..Brush::round_pen()+ },+ )+}++fn hard_airbrush() -> Brush {+ named(+ "Hard Airbrush",+ Brush { hardness: 0.85, flow: 0.25, shape: Shape::default(), max_size: 400.0, ..soft_airbrush() },+ )+}++fn charcoal_stick() -> Brush {+ named(+ "Charcoal Stick",+ Brush {+ spacing: 0.08,+ streamline: 0.1,+ max_size: 90.0,+ flow: 0.6,+ pressure_size: 0.4,+ pressure_opacity: 0.7,+ shape: Shape {+ image: Some(shape::CHUNK),+ randomise: true,+ size_jitter: 0.25,+ opacity_jitter: 0.3,+ ..Shape::default()+ },+ grain: Grain {+ image: Some(grain::COARSE),+ mode: GrainMode::Texturized,+ scale: 260.0,+ depth: 0.95,+ source: None,+ },+ tilt: Tilt { angle: 0.3, size: 1.0, opacity: 0.3 },+ pen_taper: Taper { start: 0.05, end: 0.05, size: 0.3, opacity: 0.2 },+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ )+}++fn willow_charcoal() -> Brush {+ previewed(+ named(+ "Willow Charcoal",+ Brush {+ max_size: 50.0,+ flow: 0.8,+ rendering: Rendering::Strongest,+ grain: Grain {+ image: Some(grain::PAPER),+ mode: GrainMode::Texturized,+ scale: 200.0,+ depth: 0.7,+ source: None,+ },+ ..charcoal_stick()+ },+ ),+ 0.3,+ )+}++fn speckles() -> Brush {+ previewed(+ named(+ "Speckles",+ Brush {+ spacing: 0.6,+ streamline: 0.0,+ max_size: 120.0,+ flow: 1.0,+ pressure_size: 0.3,+ pressure_opacity: 0.0,+ shape: Shape {+ image: Some(shape::SPLATTER),+ randomise: true,+ throw: 0.6,+ count: 2,+ size_jitter: 0.6,+ opacity_jitter: 0.4,+ ..Shape::default()+ },+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ ),+ 0.35,+ )+}++fn canvas_texture() -> Brush {+ named(+ "Canvas Texture",+ Brush {+ spacing: 0.05,+ hardness: 0.3,+ max_size: 500.0,+ flow: 0.7,+ pressure_size: 0.0,+ pressure_opacity: 0.6,+ shape: Shape { image: Some(shape::SOFT_ROUND), ..Shape::default() },+ grain: Grain {+ image: Some(grain::WEAVE),+ mode: GrainMode::Texturized,+ scale: 64.0,+ depth: 1.0,+ source: None,+ },+ rendering: Rendering::Strongest,+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ )+}++// ---- Sketching, from the lead holder on ----++fn lead_holder() -> Brush {+ named(+ "Lead Holder",+ Brush {+ hardness: 0.9,+ max_size: 8.0,+ flow: 0.9,+ pressure_size: 0.15,+ pressure_opacity: 0.85,+ shape: Shape::default(),+ grain: paper(grain::PAPER, 100.0, 0.25),+ tilt: Tilt { angle: 0.4, size: 0.6, opacity: 0.4 },+ ..graphite()+ },+ )+}++fn coloured_pencil() -> Brush {+ named(+ "Coloured Pencil",+ Brush {+ hardness: 0.8,+ max_size: 20.0,+ flow: 0.8,+ pressure_opacity: 0.95,+ grain: paper(grain::LINEN, 90.0, 0.65),+ ..graphite()+ },+ )+}++fn sketch_pen() -> Brush {+ named(+ "Sketch Pen",+ Brush {+ streamline: 0.25,+ hardness: 0.92,+ max_size: 14.0,+ pressure_size: 0.5,+ grain: paper(grain::PAPER, 160.0, 0.2),+ pen_taper: Taper { start: 0.04, end: 0.08, size: 0.6, opacity: 0.0 },+ ..Brush::round_pen()+ },+ )+}++// ---- Inking, from the dip pen on ----++fn dip_pen() -> Brush {+ named(+ "Dip Pen",+ Brush {+ streamline: 0.4,+ hardness: 0.98,+ min_size: 0.5,+ max_size: 40.0,+ pressure_size: 1.0,+ pressure_curve: soft_curve(),+ pen_taper: Taper { start: 0.15, end: 0.3, size: 1.0, opacity: 0.0 },+ touch_taper: Taper { start: 0.1, end: 0.2, size: 0.9, opacity: 0.0 },+ ..Brush::round_pen()+ },+ )+}++fn marker() -> Brush {+ named(+ "Marker",+ Brush {+ spacing: 0.03,+ streamline: 0.2,+ hardness: 0.9,+ max_size: 70.0,+ flow: 0.55,+ pressure_size: 0.0,+ pressure_opacity: 0.2,+ // a chisel tip held at one angle; overlaps in a stroke don't darken+ shape: Shape { roundness: 0.35, rotation: std::f32::consts::FRAC_PI_4, ..Shape::default() },+ rendering: Rendering::Strongest,+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ )+}++fn dry_ink() -> Brush {+ named(+ "Dry Ink",+ Brush {+ streamline: 0.3,+ hardness: 0.95,+ max_size: 50.0,+ pressure_size: 0.7,+ grain: paper(grain::COARSE, 220.0, 0.55),+ pen_taper: Taper { start: 0.1, end: 0.2, size: 0.8, opacity: 0.0 },+ ..Brush::round_pen()+ },+ )+}++// ---- Painting, from the dry brush on ----++fn dry_brush() -> Brush {+ named(+ "Dry Brush",+ Brush {+ flow: 0.85,+ shape: Shape {+ image: Some(shape::DRY),+ follow: 1.0,+ rotation: std::f32::consts::FRAC_PI_2,+ ..Shape::default()+ },+ grain: moving(grain::FIBRE, 140.0, 0.5),+ ..flat_brush()+ },+ )+}++fn gouache() -> Brush {+ with(+ named(+ "Gouache",+ Brush {+ spacing: 0.04,+ streamline: 0.2,+ hardness: 0.75,+ max_size: 140.0,+ flow: 0.9,+ pressure_size: 0.5,+ pressure_opacity: 0.3,+ shape: Shape { image: Some(shape::CHUNK), randomise: true, ..Shape::default() },+ grain: moving(grain::PAPER, 160.0, 0.3),+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ ),+ &[("wet_dilution", 0.05), ("wet_attack", 0.7), ("wet_pull", 0.25)],+ )+}++fn oil_paint() -> Brush {+ with(+ named("Oil Paint", Brush { flow: 1.0, max_size: 180.0, ..bristle_brush() }),+ &[("wet_dilution", 0.1), ("wet_attack", 0.35), ("wet_pull", 0.6), ("wet_grade", 0.3)],+ )+}++fn palette_knife() -> Brush {+ with(+ named(+ "Palette Knife",+ Brush {+ hardness: 1.0,+ flow: 1.0,+ pressure_size: 0.2,+ shape: Shape {+ image: Some(shape::SQUARE),+ follow: 1.0,+ roundness: 0.25,+ rotation: std::f32::consts::FRAC_PI_2,+ ..Shape::default()+ },+ grain: moving(grain::CRUMPLED, 120.0, 0.35),+ ..flat_brush()+ },+ ),+ &[("wet_dilution", 0.1), ("wet_pull", 0.85), ("wet_attack", 0.8)],+ )+}++// ---- Airbrushing, from the medium airbrush on ----++fn medium_airbrush() -> Brush {+ named("Medium Airbrush", Brush { hardness: 0.5, flow: 0.15, shape: Shape::default(), ..soft_airbrush() })+}++fn fine_mist() -> Brush {+ named(+ "Fine Mist",+ Brush {+ spacing: 0.08,+ max_size: 300.0,+ flow: 0.5,+ shape: Shape { image: Some(shape::SPRAY), randomise: true, size_jitter: 0.2, ..Shape::default() },+ ..soft_airbrush()+ },+ )+}++fn flat_airbrush() -> Brush {+ named(+ "Flat Airbrush",+ Brush {+ flow: 0.25,+ shape: Shape {+ image: Some(shape::SOFT_ROUND),+ roundness: 0.3,+ follow: 1.0,+ rotation: std::f32::consts::FRAC_PI_2,+ ..Shape::default()+ },+ ..soft_airbrush()+ },+ )+}++// ---- Charcoals, from the compressed charcoal on ----++fn compressed_charcoal() -> Brush {+ named(+ "Compressed Charcoal",+ Brush { flow: 0.85, max_size: 70.0, grain: paper(grain::COARSE, 200.0, 0.8), ..charcoal_stick() },+ )+}++fn vine_charcoal() -> Brush {+ named(+ "Vine Charcoal",+ Brush {+ max_size: 22.0,+ flow: 0.55,+ shape: Shape { image: Some(shape::GRAINY_DISC), randomise: true, ..Shape::default() },+ grain: paper(grain::PAPER, 160.0, 0.85),+ ..charcoal_stick()+ },+ )+}++fn charcoal_dust() -> Brush {+ named(+ "Charcoal Dust",+ Brush {+ spacing: 0.1,+ hardness: 0.0,+ max_size: 260.0,+ flow: 0.18,+ pressure_size: 0.2,+ pressure_opacity: 0.8,+ shape: Shape { image: Some(shape::CLOUD), randomise: true, ..Shape::default() },+ grain: paper(grain::COARSE, 240.0, 0.9),+ pen_taper: Taper::NONE,+ ..charcoal_stick()+ },+ )+}++// ---- Textures, from the dot screen on ----++/// A broad soft brush laying `grain` down where it passes.+fn texture_brush(name: &str, image: u32, scale: f32) -> Brush {+ named(name, Brush { hardness: 0.6, flow: 0.9, grain: paper(image, scale, 1.0), ..canvas_texture() })+}++fn dot_screen() -> Brush {+ texture_brush("Dot Screen", grain::HALFTONE, 96.0)+}++fn crosshatch() -> Brush {+ texture_brush("Crosshatch", grain::HATCHING, 160.0)+}++fn rough_wall() -> Brush {+ texture_brush("Rough Wall", grain::CONCRETE, 256.0)+}++fn grit() -> Brush {+ texture_brush("Grit", grain::NOISE, 128.0)+}++fn stipple() -> Brush {+ texture_brush("Stipple", grain::STIPPLE, 200.0)+}++// ---- Drawing ----++fn chalk() -> Brush {+ named(+ "Chalk",+ Brush {+ spacing: 0.06,+ streamline: 0.1,+ max_size: 80.0,+ flow: 0.75,+ pressure_size: 0.3,+ pressure_opacity: 0.7,+ shape: Shape { image: Some(shape::PASTEL), randomise: true, ..Shape::default() },+ grain: paper(grain::CONCRETE, 220.0, 0.85),+ tilt: Tilt { angle: 0.3, size: 1.2, opacity: 0.3 },+ pen_taper: Taper { start: 0.03, end: 0.03, size: 0.3, opacity: 0.2 },+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ )+}++fn soft_pastel() -> Brush {+ named(+ "Soft Pastel",+ Brush {+ max_size: 120.0,+ flow: 0.6,+ shape: Shape { image: Some(shape::PASTEL), randomise: true, size_jitter: 0.15, ..Shape::default() },+ grain: paper(grain::PAPER, 200.0, 0.75),+ ..chalk()+ },+ )+}++fn oil_pastel() -> Brush {+ named(+ "Oil Pastel",+ Brush {+ flow: 0.95,+ max_size: 90.0,+ grain: paper(grain::CRUMPLED, 180.0, 0.55),+ rendering: Rendering::Strongest,+ ..chalk()+ },+ )+}++fn wax_crayon() -> Brush {+ named(+ "Wax Crayon",+ Brush {+ hardness: 0.85,+ max_size: 40.0,+ flow: 0.9,+ shape: Shape::default(),+ grain: paper(grain::LINEN, 140.0, 0.9),+ ..chalk()+ },+ )+}++fn conte() -> Brush {+ named(+ "Conté",+ Brush {+ max_size: 50.0,+ flow: 0.8,+ shape: Shape { image: Some(shape::SQUARE), roundness: 0.5, follow_azimuth: true, ..Shape::default() },+ grain: paper(grain::PAPER, 150.0, 0.7),+ ..chalk()+ },+ )+}++// ---- Watercolour ----++fn wet_wash() -> Brush {+ with(+ named(+ "Wet Wash",+ Brush {+ spacing: 0.05,+ streamline: 0.15,+ hardness: 0.3,+ max_size: 300.0,+ flow: 0.85,+ pressure_size: 0.3,+ pressure_opacity: 0.6,+ shape: Shape { image: Some(shape::CLOUD), randomise: true, ..Shape::default() },+ grain: paper(grain::WASH, 400.0, 0.45),+ rendering: Rendering::Strongest,+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ ),+ &[("wet_dilution", 0.55), ("wet_pull", 0.2), ("wet_edges", 0.55)],+ )+}++fn round_wash() -> Brush {+ with(+ named(+ "Round Wash",+ Brush {+ hardness: 0.6,+ max_size: 160.0,+ flow: 0.9,+ pressure_size: 0.8,+ shape: Shape::default(),+ pen_taper: Taper { start: 0.1, end: 0.2, size: 0.8, opacity: 0.0 },+ ..wet_wash()+ },+ ),+ &[("wet_dilution", 0.35), ("wet_edges", 0.4)],+ )+}++fn granulating_wash() -> Brush {+ with(+ named("Granulating Wash", Brush { grain: paper(grain::WASH, 220.0, 0.85), flow: 0.9, ..wet_wash() }),+ &[("burnt_edges", 0.3)],+ )+}++fn blot() -> Brush {+ with(+ named(+ "Blot",+ Brush {+ spacing: 0.9,+ max_size: 220.0,+ flow: 0.9,+ shape: Shape {+ image: Some(shape::BLOT),+ randomise: true,+ throw: 0.4,+ size_jitter: 0.5,+ opacity_jitter: 0.3,+ ..Shape::default()+ },+ ..wet_wash()+ },+ ),+ &[("wet_edges", 0.7), ("preview_size", 0.25)],+ )+}++fn bleeding_wash() -> Brush {+ with(named("Bleeding Wash", Brush { flow: 0.8, ..wet_wash() }), &[("wet_dilution", 0.8), ("wet_blur", 0.6)])+}++// ---- Calligraphy ----++/// A nib held at one angle: broad one way, thin the other.+fn nib(name: &str, roundness: f32, angle: f32) -> Brush {+ named(+ name,+ Brush {+ spacing: 0.02,+ streamline: 0.45,+ hardness: 1.0,+ max_size: 60.0,+ pressure_size: 0.35,+ pressure_opacity: 0.0,+ shape: Shape { roundness, rotation: angle, ..Shape::default() },+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ )+}++fn chisel_nib() -> Brush {+ nib("Chisel Nib", 0.18, std::f32::consts::FRAC_PI_4)+}++fn ribbon() -> Brush {+ Brush { max_size: 90.0, pressure_size: 0.1, ..nib("Ribbon", 0.08, std::f32::consts::FRAC_PI_6) }+}++fn script_brush() -> Brush {+ named(+ "Script Brush",+ Brush {+ streamline: 0.55,+ max_size: 70.0,+ pressure_size: 1.0,+ pressure_curve: firm_curve(),+ pen_taper: Taper { start: 0.2, end: 0.45, size: 1.0, opacity: 0.0 },+ touch_taper: Taper { start: 0.25, end: 0.35, size: 0.9, opacity: 0.0 },+ ..brush_pen()+ },+ )+}++fn monoline() -> Brush {+ named(+ "Monoline",+ Brush {+ streamline: 0.65,+ hardness: 1.0,+ max_size: 30.0,+ pressure_size: 0.0,+ pressure_opacity: 0.0,+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ )+}++fn pointed_nib() -> Brush {+ named(+ "Pointed Nib",+ Brush {+ streamline: 0.5,+ min_size: 0.3,+ max_size: 36.0,+ pressure_size: 1.0,+ pressure_curve: soft_curve(),+ pen_taper: Taper { start: 0.05, end: 0.1, size: 1.0, opacity: 0.0 },+ ..dip_pen()+ },+ )+}++// ---- Spray Paint ----++fn spray_can() -> Brush {+ named(+ "Spray Can",+ Brush {+ spacing: 0.12,+ streamline: 0.05,+ hardness: 0.5,+ max_size: 260.0,+ flow: 0.85,+ pressure_size: 0.4,+ pressure_opacity: 0.5,+ shape: Shape { image: Some(shape::SPRAY), randomise: true, throw: 0.05, ..Shape::default() },+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ )+}++fn fat_cap() -> Brush {+ named(+ "Fat Cap",+ Brush {+ max_size: 500.0,+ flow: 0.7,+ shape: Shape { image: Some(shape::SPRAY), randomise: true, count: 2, throw: 0.1, ..Shape::default() },+ ..spray_can()+ },+ )+}++fn flick() -> Brush {+ named(+ "Flick",+ Brush {+ spacing: 1.2,+ max_size: 300.0,+ flow: 1.0,+ shape: Shape {+ image: Some(shape::SPLATTER),+ randomise: true,+ throw: 1.0,+ size_jitter: 0.7,+ opacity_jitter: 0.2,+ ..Shape::default()+ },+ ..spray_can()+ },+ )+}++fn mist() -> Brush {+ named(+ "Mist",+ Brush {+ spacing: 0.06,+ hardness: 0.0,+ max_size: 600.0,+ flow: 0.2,+ shape: Shape { image: Some(shape::SOFT_ROUND), ..Shape::default() },+ grain: paper(grain::NOISE, 96.0, 0.7),+ ..spray_can()+ },+ )+}++// ---- Nature ----++/// Colour that varies a little from stamp to stamp, as leaves and blades do.+const NATURAL: [(&str, f32); 2] = [("stamp_hue", 0.06), ("stamp_darkness", 0.3)];++fn leaves() -> Brush {+ previewed(+ with(+ named(+ "Leaves",+ Brush {+ spacing: 0.7,+ streamline: 0.0,+ max_size: 160.0,+ flow: 1.0,+ pressure_size: 0.4,+ pressure_opacity: 0.0,+ shape: Shape {+ image: Some(shape::LEAF),+ randomise: true,+ throw: 0.8,+ size_jitter: 0.5,+ ..Shape::default()+ },+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ ),+ &NATURAL,+ ),+ 0.3,+ )+}++fn grass() -> Brush {+ previewed(+ with(+ named(+ "Grass",+ Brush {+ spacing: 0.35,+ shape: Shape { image: Some(shape::GRASS), throw: 0.15, size_jitter: 0.4, ..Shape::default() },+ ..leaves()+ },+ ),+ &NATURAL,+ ),+ 0.3,+ )+}++fn clouds() -> Brush {+ named(+ "Clouds",+ Brush {+ spacing: 0.25,+ streamline: 0.0,+ hardness: 0.2,+ max_size: 500.0,+ flow: 0.35,+ pressure_size: 0.3,+ pressure_opacity: 0.6,+ shape: Shape {+ image: Some(shape::CLOUD),+ randomise: true,+ throw: 0.3,+ size_jitter: 0.4,+ ..Shape::default()+ },+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ )+}++fn bark() -> Brush {+ named("Bark", Brush { grain: moving(grain::CRUMPLED, 100.0, 0.7), flow: 0.95, ..dry_brush() })+}++fn foliage() -> Brush {+ previewed(+ with(+ named(+ "Foliage",+ Brush {+ spacing: 0.3,+ shape: Shape {+ image: Some(shape::CHUNK),+ randomise: true,+ throw: 0.6,+ count: 2,+ size_jitter: 0.5,+ opacity_jitter: 0.3,+ ..Shape::default()+ },+ grain: moving(grain::COARSE, 120.0, 0.6),+ ..leaves()+ },+ ),+ &NATURAL,+ ),+ 0.25,+ )+}++// ---- Effects ----++fn sparkle() -> Brush {+ previewed(+ named(+ "Sparkle",+ Brush {+ spacing: 1.2,+ streamline: 0.0,+ max_size: 200.0,+ flow: 1.0,+ pressure_size: 0.5,+ pressure_opacity: 0.0,+ shape: Shape { image: Some(shape::SPARKLE), throw: 1.2, size_jitter: 0.5, ..Shape::default() },+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ ),+ 0.25,+ )+}++fn bokeh() -> Brush {+ previewed(+ named(+ "Bokeh",+ Brush {+ spacing: 0.8,+ max_size: 260.0,+ flow: 0.9,+ shape: Shape {+ image: Some(shape::RING),+ throw: 1.4,+ size_jitter: 0.6,+ opacity_jitter: 0.4,+ ..Shape::default()+ },+ ..sparkle()+ },+ ),+ 0.2,+ )+}++fn smoke() -> Brush {+ named(+ "Smoke",+ Brush {+ spacing: 0.08,+ streamline: 0.3,+ hardness: 0.0,+ max_size: 400.0,+ flow: 0.22,+ pressure_size: 0.3,+ pressure_opacity: 0.6,+ shape: Shape { image: Some(shape::WISP), follow: 1.0, size_jitter: 0.2, ..Shape::default() },+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ )+}++fn snow() -> Brush {+ previewed(+ named(+ "Snow",+ Brush {+ spacing: 1.0,+ hardness: 0.4,+ max_size: 60.0,+ shape: Shape { throw: 2.0, count: 3, size_jitter: 0.8, opacity_jitter: 0.5, ..Shape::default() },+ ..sparkle()+ },+ ),+ 0.4,+ )+}++fn light_trail() -> Brush {+ with(+ named(+ "Light Trail",+ Brush {+ spacing: 0.03,+ streamline: 0.5,+ hardness: 0.0,+ max_size: 120.0,+ flow: 0.35,+ pressure_size: 0.6,+ pressure_opacity: 0.3,+ shape: Shape { image: Some(shape::SOFT_ROUND), ..Shape::default() },+ pen_taper: Taper { start: 0.2, end: 0.4, size: 0.9, opacity: 0.6 },+ touch_taper: Taper { start: 0.2, end: 0.4, size: 0.9, opacity: 0.6 },+ ..Brush::round_pen()+ },+ ),+ &[("blend_mode", ADD)],+ )+}++/// Soft light added to what is under it: it glows over dark colours (and shows nothing on white).+fn glow() -> Brush {+ with(+ named(+ "Glow",+ Brush {+ spacing: 0.05,+ streamline: 0.2,+ hardness: 0.0,+ max_size: 500.0,+ flow: 0.15,+ pressure_size: 0.4,+ pressure_opacity: 0.6,+ shape: Shape { image: Some(shape::SOFT_ROUND), ..Shape::default() },+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ ),+ &[("blend_mode", ADD)],+ )+}++/// The Add blend mode's number.+const ADD: f32 = 9.0;++// ---- Pixel ----++fn pixel() -> Brush {+ named(+ "Pixel",+ Brush {+ spacing: 0.05,+ streamline: 0.0,+ hardness: 1.0,+ min_size: 1.0,+ max_size: 32.0,+ flow: 1.0,+ pressure_size: 0.0,+ pressure_opacity: 0.0,+ shape: Shape { image: Some(shape::SQUARE), ..Shape::default() },+ rendering: Rendering::Strongest,+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ )+}++fn dither() -> Brush {+ previewed(named("Dither", Brush { max_size: 200.0, grain: paper(grain::HALFTONE, 64.0, 1.0), ..pixel() }), 0.2)+}++fn hatching_pen() -> Brush {+ previewed(+ named(+ "Hatching Pen",+ Brush {+ spacing: 0.15,+ max_size: 120.0,+ shape: Shape { image: Some(shape::HATCH), ..Shape::default() },+ rendering: Rendering::Strongest,+ ..pixel()+ },+ ),+ 0.3,+ )+}++// ---- More brushes, set by set ----++/// The Multiply, Screen, Colour Dodge, Overlay and Soft Light blend modes' numbers.+const MULTIPLY: f32 = 1.0;+const SCREEN: f32 = 7.0;+const DODGE: f32 = 8.0;+const OVERLAY: f32 = 11.0;+const SOFT_LIGHT: f32 = 12.0;++/// A brush laying `image` down in separate stamps, `spacing` apart (of their size), turned at+/// random and thrown `throw` of their size from the line: no streamline, no tapers.+fn stamps(name: &str, image: u32, spacing: f32, max_size: f32, throw: f32) -> Brush {+ named(+ name,+ Brush {+ spacing,+ streamline: 0.0,+ max_size,+ flow: 1.0,+ pressure_size: 0.4,+ pressure_opacity: 0.0,+ shape: Shape { image: Some(image), randomise: true, throw, size_jitter: 0.4, ..Shape::default() },+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ )+}++/// `image` lying along the stroke: what runs up and down the image runs along the line.+fn along(image: u32) -> Shape {+ Shape { image: Some(image), follow: 1.0, rotation: std::f32::consts::FRAC_PI_2, ..Shape::default() }+}++// Sketching++fn hb_pencil() -> Brush {+ named(+ "HB Pencil",+ Brush { hardness: 0.8, max_size: 14.0, flow: 0.75, grain: paper(grain::PAPER, 110.0, 0.5), ..graphite() },+ )+}++fn six_b_pencil() -> Brush {+ named(+ "6B Pencil",+ Brush {+ max_size: 48.0,+ flow: 0.95,+ pressure_opacity: 0.7,+ grain: paper(grain::COARSE, 160.0, 0.75),+ tilt: Tilt { angle: 0.3, size: 1.6, opacity: 0.6 },+ ..graphite()+ },+ )+}++fn graphite_stick() -> Brush {+ named(+ "Graphite Stick",+ Brush {+ max_size: 70.0,+ flow: 0.7,+ shape: Shape { image: Some(shape::PASTEL), randomise: true, ..Shape::default() },+ grain: paper(grain::PAPER, 140.0, 0.8),+ tilt: Tilt { angle: 0.25, size: 2.0, opacity: 0.4 },+ ..graphite()+ },+ )+}++fn charcoal_pencil() -> Brush {+ named(+ "Charcoal Pencil",+ Brush { hardness: 0.75, max_size: 26.0, flow: 0.9, grain: paper(grain::COARSE, 180.0, 0.85), ..graphite() },+ )+}++/// The side of the lead: broad, soft and built up with pressure.+fn shading_pencil() -> Brush {+ named(+ "Shading Pencil",+ Brush {+ spacing: 0.05,+ hardness: 0.4,+ max_size: 110.0,+ flow: 0.35,+ pressure_size: 0.1,+ pressure_opacity: 1.0,+ shape: Shape { image: Some(shape::SOFT_ROUND), ..Shape::default() },+ grain: paper(grain::PAPER, 120.0, 0.85),+ pen_taper: Taper::NONE,+ ..graphite()+ },+ )+}++fn ballpoint() -> Brush {+ named(+ "Ballpoint",+ Brush {+ streamline: 0.2,+ hardness: 0.95,+ max_size: 7.0,+ flow: 0.85,+ pressure_size: 0.2,+ pressure_opacity: 0.6,+ grain: paper(grain::PAPER, 90.0, 0.15),+ pen_taper: Taper { start: 0.02, end: 0.04, size: 0.3, opacity: 0.3 },+ ..Brush::round_pen()+ },+ )+}++// Inking++fn studio_ink() -> Brush {+ named(+ "Studio Ink",+ Brush {+ streamline: 0.6,+ hardness: 1.0,+ max_size: 60.0,+ pressure_size: 0.9,+ pressure_curve: firm_curve(),+ pen_taper: Taper { start: 0.2, end: 0.3, size: 1.0, opacity: 0.0 },+ ..Brush::round_pen()+ },+ )+}++fn gel_pen() -> Brush {+ named(+ "Gel Pen",+ Brush {+ streamline: 0.3,+ hardness: 0.97,+ max_size: 12.0,+ pressure_size: 0.2,+ pen_taper: Taper { start: 0.02, end: 0.03, size: 0.4, opacity: 0.0 },+ ..Brush::round_pen()+ },+ )+}++fn thick_liner() -> Brush {+ named("Thick Liner", Brush { max_size: 90.0, pressure_size: 0.25, ..fine_liner() })+}++fn felt_tip() -> Brush {+ named(+ "Felt Tip",+ Brush {+ spacing: 0.04,+ streamline: 0.25,+ hardness: 0.85,+ max_size: 24.0,+ flow: 0.75,+ pressure_size: 0.15,+ pressure_opacity: 0.25,+ grain: paper(grain::FIBRE, 120.0, 0.25),+ rendering: Rendering::Strongest,+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ )+}++/// Ink with a ragged edge: each stamp thrown a little to one side.+fn rough_ink() -> Brush {+ with(+ named("Rough Ink", Brush { spacing: 0.03, streamline: 0.0, max_size: 30.0, pressure_size: 0.6, ..dip_pen() }),+ &[("jitter_lateral", 0.1)],+ )+}++fn ink_bleed() -> Brush {+ with(+ named(+ "Ink Bleed",+ Brush {+ hardness: 0.7,+ max_size: 50.0,+ pressure_size: 0.7,+ grain: paper(grain::WASH, 200.0, 0.3),+ ..dip_pen()+ },+ ),+ &[("wet_edges", 0.6), ("wet_dilution", 0.2)],+ )+}++// Painting++fn filbert() -> Brush {+ with(+ named(+ "Filbert",+ Brush {+ hardness: 0.7,+ shape: Shape { roundness: 0.6, ..along(shape::FLAT) },+ grain: moving(grain::FIBRE, 120.0, 0.4),+ ..flat_brush()+ },+ ),+ &[("wet_dilution", 0.1), ("wet_attack", 0.4), ("wet_pull", 0.4)],+ )+}++fn fan_brush() -> Brush {+ named(+ "Fan Brush",+ Brush {+ spacing: 0.02,+ flow: 0.9,+ max_size: 200.0,+ shape: along(shape::HAIR),+ grain: Grain::default(),+ rendering: Rendering::Strongest,+ ..flat_brush()+ },+ )+}++/// A long thin liner: hair-fine at both ends.+fn rigger() -> Brush {+ named(+ "Rigger",+ Brush {+ streamline: 0.4,+ hardness: 0.85,+ max_size: 16.0,+ flow: 0.9,+ pressure_size: 0.9,+ grain: moving(grain::FIBRE, 80.0, 0.2),+ pen_taper: Taper { start: 0.3, end: 0.5, size: 1.0, opacity: 0.0 },+ ..round_brush()+ },+ )+}++fn sable() -> Brush {+ with(+ named(+ "Sable",+ Brush {+ hardness: 0.75,+ max_size: 90.0,+ flow: 0.6,+ pressure_size: 0.8,+ pressure_opacity: 0.3,+ shape: Shape { image: Some(shape::SOFT_ROUND), ..Shape::default() },+ ..round_brush()+ },+ ),+ &[("wet_dilution", 0.1), ("wet_pull", 0.3)],+ )+}++fn impasto() -> Brush {+ with(+ named(+ "Impasto",+ Brush {+ hardness: 0.9,+ max_size: 120.0,+ flow: 1.0,+ shape: Shape { image: Some(shape::CHUNK), randomise: true, ..Shape::default() },+ grain: moving(grain::CRUMPLED, 100.0, 0.5),+ ..gouache()+ },+ ),+ &[("wet_dilution", 0.1), ("wet_attack", 0.9), ("wet_pull", 0.7)],+ )+}++fn acrylic() -> Brush {+ with(+ named("Acrylic", Brush { flow: 0.95, grain: moving(grain::WEAVE, 100.0, 0.45), ..bristle_brush() }),+ &[("wet_dilution", 0.1), ("wet_attack", 0.6), ("wet_pull", 0.35)],+ )+}++fn tempera() -> Brush {+ named(+ "Tempera",+ Brush {+ hardness: 0.85,+ max_size: 40.0,+ flow: 0.8,+ grain: paper(grain::PAPER, 120.0, 0.4),+ rendering: Rendering::Strongest,+ ..round_brush()+ },+ )+}++/// Thin broken colour dragged over what is there.+fn scumble() -> Brush {+ named(+ "Scumble",+ Brush {+ hardness: 0.5,+ max_size: 200.0,+ flow: 0.4,+ shape: Shape { image: Some(shape::CHUNK), randomise: true, throw: 0.15, ..Shape::default() },+ grain: paper(grain::COARSE, 200.0, 0.8),+ ..round_brush()+ },+ )+}++// Airbrushing++fn grainy_airbrush() -> Brush {+ named("Grainy Airbrush", Brush { flow: 0.15, grain: paper(grain::NOISE, 64.0, 0.8), ..soft_airbrush() })+}++fn stipple_airbrush() -> Brush {+ named("Stipple Airbrush", Brush { flow: 0.3, grain: paper(grain::SPECKLE, 128.0, 1.0), ..soft_airbrush() })+}++fn feather_airbrush() -> Brush {+ named(+ "Feather Airbrush",+ Brush {+ flow: 0.12,+ pressure_size: 0.6,+ pen_taper: Taper { start: 0.2, end: 0.3, size: 0.9, opacity: 0.5 },+ ..soft_airbrush()+ },+ )+}++fn tight_airbrush() -> Brush {+ named(+ "Tight Airbrush",+ Brush {+ hardness: 0.95,+ max_size: 200.0,+ flow: 0.5,+ pressure_size: 0.5,+ shape: Shape::default(),+ ..soft_airbrush()+ },+ )+}++// Charcoals++fn charcoal_block() -> Brush {+ named(+ "Charcoal Block",+ Brush {+ max_size: 140.0,+ flow: 0.75,+ // the side of the block, broad across the stroke+ shape: Shape { image: Some(shape::SQUARE), roundness: 0.35, ..along(shape::SQUARE) },+ grain: paper(grain::COARSE, 260.0, 0.95),+ ..charcoal_stick()+ },+ )+}++fn burnt_stick() -> Brush {+ named(+ "Burnt Stick",+ Brush {+ max_size: 60.0,+ flow: 0.9,+ shape: Shape { image: Some(shape::GRAINY_DISC), randomise: true, ..Shape::default() },+ grain: paper(grain::CRUMPLED, 220.0, 0.8),+ ..charcoal_stick()+ },+ )+}++fn smudged_charcoal() -> Brush {+ named(+ "Smudged Charcoal",+ Brush {+ hardness: 0.0,+ max_size: 200.0,+ flow: 0.3,+ shape: along(shape::SMUDGE),+ grain: paper(grain::PAPER, 200.0, 0.6),+ ..charcoal_stick()+ },+ )+}++fn soft_charcoal() -> Brush {+ named(+ "Soft Charcoal",+ Brush { max_size: 70.0, flow: 0.7, grain: paper(grain::SAND, 160.0, 0.9), ..charcoal_stick() },+ )+}++// Textures++fn wood_grain() -> Brush {+ texture_brush("Wood Grain", grain::WOOD, 400.0)+}++fn brickwork() -> Brush {+ texture_brush("Brickwork", grain::BRICK, 512.0)+}++fn fish_scales() -> Brush {+ texture_brush("Fish Scales", grain::SCALES, 256.0)+}++fn cell_wall() -> Brush {+ texture_brush("Cell Wall", grain::CELLS, 300.0)+}++fn marble() -> Brush {+ texture_brush("Marble", grain::MARBLE, 600.0)+}++fn pinstripe() -> Brush {+ texture_brush("Pinstripe", grain::STRIPES, 160.0)+}++fn honeycomb() -> Brush {+ texture_brush("Honeycomb", grain::HEXAGONS, 400.0)+}++fn leather() -> Brush {+ texture_brush("Leather", grain::LEATHER, 300.0)+}++fn sandpaper() -> Brush {+ texture_brush("Sandpaper", grain::SAND, 128.0)+}++fn checkerboard() -> Brush {+ texture_brush("Checkerboard", grain::CHECKER, 128.0)+}++// Drawing++fn hard_pastel() -> Brush {+ named(+ "Hard Pastel",+ Brush {+ max_size: 60.0,+ flow: 0.8,+ shape: Shape { image: Some(shape::SQUARE), roundness: 0.6, follow_azimuth: true, ..Shape::default() },+ grain: paper(grain::SAND, 180.0, 0.8),+ ..chalk()+ },+ )+}++fn chalk_pencil() -> Brush {+ named(+ "Chalk Pencil",+ Brush {+ hardness: 0.8,+ max_size: 18.0,+ flow: 0.85,+ shape: Shape::default(),+ grain: paper(grain::PAPER, 120.0, 0.8),+ ..chalk()+ },+ )+}++fn pastel_pencil() -> Brush {+ named(+ "Pastel Pencil",+ Brush {+ max_size: 26.0,+ shape: Shape { image: Some(shape::GRAINY_DISC), randomise: true, ..Shape::default() },+ grain: paper(grain::LINEN, 110.0, 0.7),+ ..chalk()+ },+ )+}++fn litho_crayon() -> Brush {+ named(+ "Litho Crayon",+ Brush {+ hardness: 0.9,+ max_size: 36.0,+ flow: 1.0,+ shape: Shape::default(),+ grain: paper(grain::COARSE, 160.0, 0.75),+ rendering: Rendering::Strongest,+ ..chalk()+ },+ )+}++// Watercolour++fn flat_wash() -> Brush {+ with(named("Flat Wash", Brush { max_size: 200.0, shape: along(shape::FLAT), ..wet_wash() }), &[("wet_edges", 0.5)])+}++fn dry_wash() -> Brush {+ with(+ named("Dry Wash", Brush { flow: 0.7, grain: paper(grain::COARSE, 300.0, 0.85), ..wet_wash() }),+ &[("wet_dilution", 0.3)],+ )+}++/// Pale blooms where salt drank the paint: a wash full of holes.+fn salt() -> Brush {+ with(+ named(+ "Salt",+ Brush {+ spacing: 0.3,+ max_size: 240.0,+ shape: Shape {+ image: Some(shape::SPONGE),+ randomise: true,+ throw: 0.2,+ size_jitter: 0.3,+ ..Shape::default()+ },+ ..wet_wash()+ },+ ),+ &[("wet_edges", 0.6)],+ )+}++fn splash() -> Brush {+ with(+ named(+ "Splash",+ Brush {+ spacing: 0.8,+ max_size: 260.0,+ flow: 0.9,+ shape: Shape {+ image: Some(shape::SPLATTER),+ randomise: true,+ throw: 0.8,+ size_jitter: 0.6,+ ..Shape::default()+ },+ ..wet_wash()+ },+ ),+ &[("wet_edges", 0.7), ("preview_size", 0.25)],+ )+}++fn mop_brush() -> Brush {+ with(+ named(+ "Mop Brush",+ Brush {+ hardness: 0.2,+ max_size: 400.0,+ pressure_size: 0.7,+ shape: Shape { image: Some(shape::SOFT_ROUND), ..Shape::default() },+ ..wet_wash()+ },+ ),+ &[("wet_dilution", 0.45), ("wet_edges", 0.35)],+ )+}++// Calligraphy++fn broad_pen() -> Brush {+ Brush { max_size: 90.0, ..nib("Broad Pen", 0.12, 0.0) }+}++fn italic_nib() -> Brush {+ nib("Italic Nib", 0.22, std::f32::consts::FRAC_PI_3)+}++fn felt_brush() -> Brush {+ named(+ "Felt Brush",+ Brush {+ hardness: 0.95,+ max_size: 50.0,+ pressure_size: 0.9,+ grain: paper(grain::FIBRE, 120.0, 0.3),+ ..script_brush()+ },+ )+}++fn copperplate() -> Brush {+ named("Copperplate", Brush { streamline: 0.6, min_size: 0.2, max_size: 28.0, ..pointed_nib() })+}++// Spray Paint++fn drips() -> Brush {+ let mut b = stamps("Drips", shape::DRIP, 1.0, 200.0, 0.6);+ b.shape.randomise = false;+ b.shape.opacity_jitter = 0.2;+ previewed(b, 0.25)+}++fn hard_spray() -> Brush {+ named(+ "Hard Spray",+ Brush {+ hardness: 0.9,+ flow: 0.6,+ shape: Shape::default(),+ grain: paper(grain::NOISE, 64.0, 0.6),+ ..spray_can()+ },+ )+}++fn splatter_can() -> Brush {+ named(+ "Splatter Can",+ Brush {+ spacing: 0.5,+ shape: Shape {+ image: Some(shape::SPLATTER),+ randomise: true,+ throw: 0.5,+ count: 2,+ size_jitter: 0.5,+ ..Shape::default()+ },+ ..spray_can()+ },+ )+}++fn skinny_cap() -> Brush {+ named("Skinny Cap", Brush { max_size: 60.0, flow: 0.95, ..spray_can() })+}++// Nature++/// A Nature stamp brush: `image` scattered, its colour shifting a little from stamp to stamp.+fn natural(name: &str, image: u32, spacing: f32, max_size: f32, throw: f32) -> Brush {+ previewed(with(stamps(name, image, spacing, max_size, throw), &NATURAL), 0.3)+}++fn pine() -> Brush {+ natural("Pine", shape::NEEDLES, 0.5, 200.0, 0.5)+}++fn twigs() -> Brush {+ natural("Twigs", shape::TWIG, 0.8, 220.0, 0.6)+}++fn moss() -> Brush {+ natural("Moss", shape::MOSS, 0.25, 160.0, 0.4)+}++fn flowers() -> Brush {+ natural("Flowers", shape::FLOWER, 0.9, 120.0, 0.9)+}++fn fur() -> Brush {+ with(+ named(+ "Fur",+ Brush {+ spacing: 0.12,+ streamline: 0.2,+ max_size: 160.0,+ flow: 0.9,+ pressure_size: 0.4,+ pressure_opacity: 0.3,+ shape: Shape { size_jitter: 0.3, ..along(shape::FUR) },+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ ),+ &[("stamp_darkness", 0.2)],+ )+}++fn pebbles() -> Brush {+ natural("Pebbles", shape::STONE, 0.9, 120.0, 0.8)+}++fn feathers() -> Brush {+ natural("Feathers", shape::FEATHER, 1.2, 240.0, 0.7)+}++fn reeds() -> Brush {+ let mut b = natural("Reeds", shape::STREAK, 0.4, 260.0, 0.8);+ b.shape.randomise = false;+ b.shape.count = 3;+ b+}++// Effects++fn stars() -> Brush {+ previewed(stamps("Stars", shape::STAR, 1.2, 120.0, 1.2), 0.25)+}++fn bubbles() -> Brush {+ let mut b = stamps("Bubbles", shape::BUBBLE, 1.0, 200.0, 1.4);+ b.shape.size_jitter = 0.7;+ b.shape.opacity_jitter = 0.3;+ previewed(b, 0.2)+}++/// Sparks drifting off: small soft dots added to what is under them.+fn embers() -> Brush {+ let mut b = stamps("Embers", shape::SOFT_ROUND, 1.0, 40.0, 2.0);+ b.hardness = 0.3;+ b.shape.count = 2;+ b.shape.size_jitter = 0.8;+ b.shape.opacity_jitter = 0.6;+ previewed(with(b, &[("blend_mode", ADD)]), 0.4)+}++fn rain() -> Brush {+ let mut b = stamps("Rain", shape::STREAK, 1.0, 160.0, 1.5);+ b.shape.randomise = false;+ b.shape.rotation = 0.3;+ b.shape.count = 3;+ b.shape.opacity_jitter = 0.5;+ previewed(b, 0.3)+}++fn snowflakes() -> Brush {+ previewed(stamps("Snowflakes", shape::SNOWFLAKE, 1.2, 100.0, 1.4), 0.25)+}++// Pixel++fn pixel_checker() -> Brush {+ named("Pixel Checker", Brush { max_size: 200.0, grain: paper(grain::CHECKER, 32.0, 1.0), ..pixel() })+}++fn pixel_spray() -> Brush {+ named(+ "Pixel Spray",+ Brush {+ spacing: 0.5,+ max_size: 12.0,+ shape: Shape { image: Some(shape::SQUARE), throw: 3.0, count: 3, ..Shape::default() },+ ..pixel()+ },+ )+}++fn pixel_round() -> Brush {+ named("Pixel Round", Brush { shape: Shape::default(), ..pixel() })+}++fn pixel_line() -> Brush {+ named("Pixel Line", Brush { max_size: 4.0, streamline: 0.5, ..pixel() })+}++// ---- Elements ----++fn fire() -> Brush {+ let mut b = stamps("Fire", shape::FLAME, 0.35, 220.0, 0.35);+ b.shape.randomise = false;+ b.shape.count = 2;+ b.shape.opacity_jitter = 0.4;+ previewed(with(b, &[("stamp_hue", 0.05), ("stamp_lightness", 0.3)]), 0.3)+}++fn smoke_puff() -> Brush {+ named("Smoke Puff", Brush { flow: 0.2, hardness: 0.0, ..clouds() })+}++fn water_drops() -> Brush {+ let mut b = stamps("Water Drops", shape::DROPLET, 1.3, 90.0, 1.3);+ b.shape.randomise = false;+ previewed(b, 0.25)+}++fn ripples() -> Brush {+ texture_brush("Ripples", grain::CAUSTICS, 400.0)+}++/// Forked light: bolts end to end along the stroke, added to what is under them.+fn lightning() -> Brush {+ with(+ named(+ "Lightning",+ Brush {+ spacing: 1.0,+ streamline: 0.3,+ max_size: 300.0,+ pressure_size: 0.0,+ pressure_opacity: 0.0,+ shape: along(shape::BOLT),+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ ),+ &[("blend_mode", ADD), ("preview_size", 0.3)],+ )+}++fn ice() -> Brush {+ previewed(stamps("Ice", shape::CRACK, 0.6, 200.0, 0.3), 0.3)+}++fn sea_foam() -> Brush {+ let mut b = stamps("Sea Foam", shape::SPONGE, 0.4, 200.0, 0.4);+ b.flow = 0.7;+ b.shape.count = 2;+ b+}++fn fog() -> Brush {+ named("Fog", Brush { max_size: 1200.0, flow: 0.08, spacing: 0.15, ..clouds() })+}++// ---- Industrial ----++fn rusted() -> Brush {+ let mut b = texture_brush("Rusted", grain::RUST, 300.0);+ b.shape = Shape { image: Some(shape::CHUNK), randomise: true, ..Shape::default() };+ b+}++fn cement() -> Brush {+ texture_brush("Cement", grain::CONCRETE, 180.0)+}++fn grunge() -> Brush {+ texture_brush("Grunge", grain::GRUNGE, 400.0)+}++fn scratched_metal() -> Brush {+ texture_brush("Scratched Metal", grain::SCRATCHES, 300.0)+}++fn steel_wool() -> Brush {+ let mut b = stamps("Steel Wool", shape::HAIR, 0.3, 160.0, 0.3);+ b.flow = 0.6;+ b.shape.count = 2;+ b.shape.size_jitter = 0.5;+ previewed(b, 0.3)+}++/// Evenly spaced round heads, as on a seam.+fn rivets() -> Brush {+ named(+ "Rivets",+ Brush {+ spacing: 2.2,+ streamline: 0.4,+ hardness: 0.9,+ max_size: 60.0,+ pressure_size: 0.0,+ shape: Shape { image: Some(shape::RING), ..Shape::default() },+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ )+}++fn grime() -> Brush {+ named("Grime", Brush { grain: paper(grain::GRUNGE, 300.0, 0.9), flow: 0.6, ..spray_can() })+}++fn oil_stain() -> Brush {+ with(named("Oil Stain", Brush { flow: 0.5, ..blot() }), &[("blend_mode", MULTIPLY)])+}++// ---- Organic ----++fn hair() -> Brush {+ previewed(+ named(+ "Hair",+ Brush {+ spacing: 0.04,+ streamline: 0.5,+ max_size: 120.0,+ flow: 0.8,+ pressure_size: 0.5,+ pressure_opacity: 0.4,+ shape: along(shape::HAIR),+ pen_taper: Taper { start: 0.2, end: 0.3, size: 0.6, opacity: 0.4 },+ rendering: Rendering::Strongest,+ ..Brush::round_pen()+ },+ ),+ 0.3,+ )+}++fn skin_pores() -> Brush {+ Brush { flow: 0.5, ..texture_brush("Skin Pores", grain::LEATHER, 90.0) }+}++fn freckles() -> Brush {+ let mut b = stamps("Freckles", shape::SOFT_ROUND, 0.8, 16.0, 1.5);+ b.hardness = 0.5;+ b.shape.count = 2;+ b.shape.size_jitter = 0.7;+ b.shape.opacity_jitter = 0.6;+ previewed(b, 0.4)+}++fn reptile() -> Brush {+ texture_brush("Reptile", grain::SCALES, 120.0)+}++fn coral() -> Brush {+ previewed(with(stamps("Coral", shape::SPONGE, 0.5, 200.0, 0.5), &NATURAL), 0.3)+}++fn lichen() -> Brush {+ natural("Lichen", shape::MOSS, 0.6, 120.0, 0.9)+}++fn seeds() -> Brush {+ natural("Seeds", shape::DIAMOND, 1.0, 30.0, 1.5)+}++fn veins() -> Brush {+ let mut b = stamps("Veins", shape::CRACK, 0.7, 150.0, 0.2);+ b.flow = 0.8;+ previewed(b, 0.3)+}++// ---- Abstract ----++fn hearts() -> Brush {+ previewed(stamps("Hearts", shape::HEART, 1.2, 100.0, 1.0), 0.25)+}++fn confetti() -> Brush {+ previewed(with(stamps("Confetti", shape::CONFETTI, 0.8, 200.0, 0.8), &[("stamp_hue", 1.0)]), 0.25)+}++fn triangles() -> Brush {+ previewed(stamps("Triangles", shape::TRIANGLE, 1.2, 90.0, 1.0), 0.25)+}++fn diamonds() -> Brush {+ previewed(stamps("Diamonds", shape::DIAMOND, 1.2, 90.0, 1.0), 0.25)+}++fn speed_lines() -> Brush {+ with(+ named(+ "Speed Lines",+ Brush {+ spacing: 0.6,+ streamline: 0.5,+ max_size: 300.0,+ pressure_size: 0.0,+ pressure_opacity: 0.0,+ shape: Shape { count: 3, opacity_jitter: 0.5, size_jitter: 0.5, ..along(shape::STREAK) },+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ ),+ &[("jitter_lateral", 0.6)],+ )+}++fn scribbles() -> Brush {+ previewed(stamps("Scribbles", shape::SCRIBBLE, 0.7, 160.0, 0.4), 0.3)+}++/// A dotted line: round dots a little apart.+fn dot_trail() -> Brush {+ named(+ "Dot Trail",+ Brush {+ spacing: 1.6,+ streamline: 0.5,+ hardness: 1.0,+ max_size: 50.0,+ pressure_size: 0.3,+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ )+}++/// A dashed line: short bars along the stroke.+fn dashes() -> Brush {+ named(+ "Dashes",+ Brush {+ shape: Shape { image: Some(shape::SQUARE), roundness: 0.3, follow: 1.0, ..Shape::default() },+ spacing: 2.0,+ ..dot_trail()+ },+ )+}++// ---- Touchups ----++fn soft_blender() -> Brush {+ named(+ "Soft Blender",+ Brush {+ spacing: 0.05,+ streamline: 0.2,+ hardness: 0.0,+ max_size: 300.0,+ flow: 0.2,+ pressure_size: 0.3,+ pressure_opacity: 0.7,+ shape: Shape { image: Some(shape::SOFT_ROUND), ..Shape::default() },+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ )+}++fn grainy_blender() -> Brush {+ named("Grainy Blender", Brush { grain: paper(grain::PAPER, 160.0, 0.6), flow: 0.3, ..soft_blender() })+}++fn retouch() -> Brush {+ named("Retouch", Brush { max_size: 60.0, hardness: 0.4, flow: 0.4, ..soft_blender() })+}++fn highlight() -> Brush {+ with(named("Highlight", Brush { flow: 0.3, ..soft_blender() }), &[("blend_mode", SCREEN)])+}++fn shadow() -> Brush {+ with(named("Shadow", Brush { flow: 0.25, ..soft_blender() }), &[("blend_mode", MULTIPLY)])+}++fn noise() -> Brush {+ named("Noise", Brush { grain: paper(grain::NOISE, 96.0, 1.0), flow: 0.3, ..soft_blender() })+}++fn fine_detail() -> Brush {+ named(+ "Fine Detail",+ Brush {+ streamline: 0.3,+ hardness: 0.85,+ max_size: 12.0,+ flow: 0.9,+ pressure_size: 0.6,+ pressure_opacity: 0.4,+ ..Brush::round_pen()+ },+ )+}++// ---- Retro ----++fn ben_day() -> Brush {+ texture_brush("Ben Day", grain::HALFTONE, 200.0)+}++fn screen_tone() -> Brush {+ texture_brush("Screen Tone", grain::HALFTONE, 48.0)+}++fn comic_ink() -> Brush {+ named("Comic Ink", Brush { pressure_curve: Curve::linear(), max_size: 40.0, ..studio_ink() })+}++fn retro_stipple() -> Brush {+ Brush { hardness: 0.95, ..texture_brush("Retro Stipple", grain::STIPPLE, 120.0) }+}++fn pop_dots() -> Brush {+ named("Pop Dots", Brush { spacing: 1.2, max_size: 80.0, pressure_size: 0.6, ..dot_trail() })+}++fn retro_lines() -> Brush {+ texture_brush("Retro Lines", grain::STRIPES, 64.0)+}++/// Colour printed in dots, darkening what is under it.+fn offset_print() -> Brush {+ with(+ named(+ "Offset Print",+ Brush { hardness: 0.9, flow: 0.9, grain: paper(grain::HALFTONE, 80.0, 0.6), ..round_brush() },+ ),+ &[("blend_mode", MULTIPLY)],+ )+}++// ---- Vintage ----++fn worn_ink() -> Brush {+ named("Worn Ink", Brush { grain: paper(grain::GRUNGE, 260.0, 0.7), ..dry_ink() })+}++fn letterpress() -> Brush {+ named("Letterpress", Brush { hardness: 1.0, grain: paper(grain::SAND, 200.0, 0.5), ..monoline() })+}++fn old_paper() -> Brush {+ Brush { flow: 0.4, ..texture_brush("Old Paper", grain::CRUMPLED, 500.0) }+}++fn sepia_wash() -> Brush {+ with(+ named("Sepia Wash", Brush { grain: paper(grain::WASH, 300.0, 0.6), flow: 0.6, ..wet_wash() }),+ &[("blend_mode", MULTIPLY)],+ )+}++fn scratchy_pen() -> Brush {+ named("Scratchy Pen", Brush { grain: paper(grain::SCRATCHES, 160.0, 0.6), ..dip_pen() })+}++fn rubber_stamp() -> Brush {+ Brush { hardness: 0.95, shape: Shape::default(), ..texture_brush("Rubber Stamp", grain::GRUNGE, 200.0) }+}++fn faded_print() -> Brush {+ Brush { flow: 0.5, ..texture_brush("Faded Print", grain::RUST, 260.0) }+}++// ---- Luminance ----++/// A bright core in a soft glow, added to what is under it.+fn neon() -> Brush {+ with(+ named(+ "Neon",+ Brush {+ spacing: 0.04,+ streamline: 0.5,+ hardness: 0.0,+ max_size: 80.0,+ flow: 0.5,+ pressure_size: 0.3,+ pressure_opacity: 0.0,+ shape: Shape { image: Some(shape::SOFT_ROUND), ..Shape::default() },+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ },+ ),+ &[("blend_mode", ADD)],+ )+}++fn glimmer() -> Brush {+ with(named("Glimmer", Brush { max_size: 80.0, ..sparkle() }), &[("blend_mode", ADD)])+}++fn lens_dust() -> Brush {+ let mut b = stamps("Lens Dust", shape::RING, 1.0, 300.0, 1.8);+ b.flow = 0.35;+ b.shape.size_jitter = 0.8;+ b.shape.opacity_jitter = 0.7;+ previewed(with(b, &[("blend_mode", SCREEN)]), 0.2)+}++fn flare() -> Brush {+ named("Flare", Brush { shape: Shape { image: Some(shape::SPARKLE), ..Shape::default() }, ..glow() })+}++fn halo() -> Brush {+ with(named("Halo", Brush { flow: 0.4, ..bokeh() }), &[("blend_mode", SCREEN)])+}++fn light_leak() -> Brush {+ with(named("Light Leak", Brush { max_size: 1500.0, flow: 0.12, ..glow() }), &[("blend_mode", SCREEN)])+}++fn aurora() -> Brush {+ with(named("Aurora", Brush { flow: 0.3, ..smoke() }), &[("blend_mode", ADD), ("stamp_hue", 0.1)])+}++fn fairy_dust() -> Brush {+ with(+ named("Fairy Dust", Brush { flow: 0.8, grain: paper(grain::SPECKLE, 160.0, 1.0), ..mist() }),+ &[("blend_mode", DODGE)],+ )+}++fn soft_glow() -> Brush {+ with(named("Soft Glow", Brush { flow: 0.25, ..glow() }), &[("blend_mode", SOFT_LIGHT)])+}++fn overlay_light() -> Brush {+ with(named("Overlay Light", Brush { flow: 0.3, ..glow() }), &[("blend_mode", OVERLAY)])+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::textures::{grains, shapes};++ #[test]+ fn library_is_complete_and_consistent() {+ let sets = library();+ assert!(sets.len() >= 6);+ let mut shelf = SHELF.to_vec();+ shelf.sort_unstable();+ assert_eq!(shelf, (0..sets.len()).collect::<Vec<_>>(), "the shelf shows every set once");+ let (shape_count, grain_count) = (shapes().len() as u32, grains().len() as u32);+ let mut names = std::collections::HashSet::new();+ for set in &sets {+ assert!(!set.brushes.is_empty(), "{}", set.name);+ for b in &set.brushes {+ assert!(names.insert(b.name.clone()), "duplicate brush name {}", b.name);+ assert!(b.shape.image.is_none_or(|i| i < shape_count), "{}", b.name);+ assert!(b.grain.image.is_none_or(|i| i < grain_count), "{}", b.name);+ assert!(b.min_size < b.max_size && b.spacing > 0.0 && b.flow > 0.0, "{}", b.name);+ assert!(b.grain.image.is_none() || b.grain.scale > 0.0, "{}", b.name);+ }+ }+ }+}diff --git a/crates/engine/src/motion.rs b/crates/engine/src/motion.rsnew file mode 100644index 0000000..ad6e1ac--- /dev/null+++ b/crates/engine/src/motion.rs@@ -0,0 +1,137 @@+//! Timing curves for things the engine moves on its own (the view settling into place).++/// A damped spring released from 0 towards 1, stiff enough to come within a thousandth of its end+/// in `seconds`; `damping` 1 is critical, less bounces.+#[derive(Clone, Copy, Debug)]+pub struct Spring {+ seconds: f32,+ damping: f32,+ omega: f32,+}++impl Spring {+ pub fn new(seconds: f32, damping: f32) -> Spring {+ let seconds = if seconds.is_finite() { seconds.max(1e-3) } else { 0.3 };+ let damping = if damping.is_finite() { damping.clamp(0.05, 1.0) } else { 1.0 };+ // the slowest natural frequency at which the motion has settled by then+ let (mut lo, mut hi) = (0.01_f64, 2000.0_f64);+ for _ in 0..60 {+ let mid = (lo + hi) / 2.0;+ if envelope(mid, f64::from(damping), f64::from(seconds)) > 1e-3 {+ lo = mid;+ } else {+ hi = mid;+ }+ }+ Spring { seconds, damping, omega: hi as f32 }+ }++ pub fn seconds(&self) -> f32 {+ self.seconds+ }++ /// Where it is `t` seconds after release (exactly 1 from its time on).+ pub fn at(&self, t: f32) -> f32 {+ if !t.is_finite() || t >= self.seconds {+ return 1.0;+ }+ if t <= 0.0 {+ return 0.0;+ }+ let (t, z, w) = (f64::from(t), f64::from(self.damping), f64::from(self.omega));+ let off = if z < 1.0 {+ let wd = w * (1.0 - z * z).sqrt();+ (-z * w * t).exp() * (-(wd * t).cos() - z * w / wd * (wd * t).sin())+ } else {+ (-1.0 - w * t) * (-w * t).exp()+ };+ (1.0 + off) as f32+ }+}++/// A cubic-bezier timing curve from (0, 0) to (1, 1) through the control points (x1, y1) and+/// (x2, y2), run over `seconds`.+#[derive(Clone, Copy, Debug)]+pub struct Bezier {+ pub seconds: f32,+ pub x1: f32,+ pub y1: f32,+ pub x2: f32,+ pub y2: f32,+}++impl Bezier {+ /// Slowing to a stop: (0, 0, 0.58, 1).+ pub fn ease_out(seconds: f32) -> Bezier {+ Bezier { seconds, x1: 0.0, y1: 0.0, x2: 0.58, y2: 1.0 }+ }++ /// How far along it is `t` seconds in (exactly 1 from its time on).+ pub fn at(&self, t: f32) -> f32 {+ if !t.is_finite() || t >= self.seconds {+ return 1.0;+ }+ if t <= 0.0 {+ return 0.0;+ }+ let x = t / self.seconds.max(1e-6);+ let curve =+ |u: f32, a: f32, b: f32| 3.0 * (1.0 - u) * (1.0 - u) * u * a + 3.0 * (1.0 - u) * u * u * b + u * u * u;+ // the curve's own parameter where it is x across, by halving+ let (mut lo, mut hi) = (0.0_f32, 1.0_f32);+ for _ in 0..30 {+ let mid = (lo + hi) / 2.0;+ if curve(mid, self.x1, self.x2) < x {+ lo = mid;+ } else {+ hi = mid;+ }+ }+ curve((lo + hi) / 2.0, self.y1, self.y2)+ }+}++/// How far from its end the motion can still be at time `t`, at frequency `w`.+fn envelope(w: f64, z: f64, t: f64) -> f64 {+ if z < 1.0 {+ let wd = w * (1.0 - z * z).sqrt();+ let c = z * w / wd;+ (1.0 + c * c).sqrt() * (-z * w * t).exp()+ } else {+ (1.0 + w * t) * (-w * t).exp()+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_spring_starts_still_and_settles_in_its_time() {+ for damping in [0.6, 0.8, 1.0] {+ let s = Spring::new(0.5, damping);+ assert_eq!(s.at(0.0), 0.0);+ assert!(s.at(0.01) < 0.05);+ assert!((s.at(0.499) - 1.0).abs() < 2e-3, "{damping}: {}", s.at(0.499));+ assert_eq!(s.at(0.5), 1.0);+ }+ // a softer one goes past its end on the way+ let s = Spring::new(0.5, 0.6);+ assert!((0..50).map(|i| s.at(i as f32 / 100.0)).fold(0.0_f32, f32::max) > 1.0);+ }++ #[test]+ fn ease_out_starts_fast_and_slows_to_its_end() {+ let e = Bezier::ease_out(0.3);+ assert_eq!(e.at(0.0), 0.0);+ assert_eq!(e.at(0.3), 1.0);+ // ahead of a straight line all the way, and never back+ let mut last = 0.0;+ for i in 1..30 {+ let t = i as f32 / 100.0;+ let v = e.at(t);+ assert!(v > t / 0.3 && v >= last, "{t}: {v}");+ last = v;+ }+ }+}diff --git a/crates/engine/src/native.rs b/crates/engine/src/native.rsnew file mode 100644index 0000000..1f6da9c--- /dev/null+++ b/crates/engine/src/native.rs@@ -0,0 +1,1028 @@+//! The layered artwork package matched 1:1: a zip holding a keyed archive of the document+//! (`Document.archive`), a folder of LZ4 tiles per layer named by the layer's UUID, and a preview+//! (`QuickLook/Thumbnail.png`).+//!+//! Tiles are `tileSize` squares (smaller along the right and top edges), rows stored bottom-up,+//! pixels premultiplied RGBA (masks: one grey byte). A missing tile is empty. The canvas is stored+//! unturned; `orientation` (1 to 4) says how many quarter turns it is shown at.++use std::sync::Arc;++use crate::applz4;+use crate::cms::{CanvasIcc, IccProfile, Space};+use crate::document::{BlendMode, Document, Layer, LayerId, LayerKind};+use crate::keyed::{Archive, Builder, Object};+use crate::plist::Value;+use crate::profile::Profile;+use crate::zip::{ZipReader, ZipWriter};++/// The file extension of the package.+pub const EXTENSION: &str = "procreate";+/// The edge of a tile written.+const TILE: u32 = 256;++/// An artwork read from a package.+pub struct Imported {+ pub document: Document,+ /// Paint layers' pixels (premultiplied RGBA) and masks' (grey in every channel, opaque), by id.+ pub pixels: Vec<(LayerId, Vec<u8>)>,+ pub name: String,+ pub author: String,+ pub strokes: u64,+ pub tracked_seconds: f64,+}++/// Why a package couldn't be read.+#[derive(Debug, PartialEq, Eq)]+pub enum ReadError {+ NotAPackage,+ Damaged(&'static str),+ TooLarge,+}++/// Reads a package.+pub fn read(bytes: &[u8]) -> Result<Imported, ReadError> {+ let zip = ZipReader::new(bytes).ok_or(ReadError::NotAPackage)?;+ let archive = Archive::read(&zip.read("Document.archive").ok_or(ReadError::NotAPackage)?)+ .ok_or(ReadError::Damaged("document"))?;+ let root = archive.root().ok_or(ReadError::Damaged("document"))?;+ let (w, h) = root.string("size").and_then(|s| parse_size(&s)).ok_or(ReadError::Damaged("size"))?;+ if w == 0 || h == 0 {+ return Err(ReadError::Damaged("size"));+ }+ if w > crate::document::MAX_CANVAS_EDGE || h > crate::document::MAX_CANVAS_EDGE {+ return Err(ReadError::TooLarge);+ }+ let tile =+ root.int("tileSize").and_then(|t| u32::try_from(t).ok()).filter(|t| (16..=4096).contains(t)).unwrap_or(TILE);+ let orientation = root.int("orientation").filter(|o| (1..=4).contains(o)).unwrap_or(1);+ let turns = match orientation {+ 2 => 3,+ 3 => 2,+ 4 => 1,+ _ => 0,+ };+ let flip_x = root.bool("flippedHorizontally").unwrap_or(false);+ let flip_y = root.bool("flippedVertically").unwrap_or(false);+ let (dw, dh) = if turns % 2 == 1 { (h, w) } else { (w, h) };+ let canvas = Canvas { zip: &zip, w, h, tile, turns, flip_x, flip_y };++ let mut layers: Vec<Layer> = Vec::new();+ let mut pixels: Vec<(LayerId, Vec<u8>)> = Vec::new();+ let mut next = 1u64;+ let mut selected = None;+ let selected_uuid = root.object("selectedLayer").and_then(|l| l.string("UUID"));+ let mut items = root.array("unwrappedLayers");+ if items.is_empty() {+ items = root.array("layers");+ }+ // the archive lists the top first; ours goes bottom first+ for item in items.iter().rev() {+ add_item(&canvas, item, None, &mut layers, &mut pixels, &mut next, selected_uuid.as_deref(), &mut selected)?;+ }+ let mut document = Document::from_layers(dw, dh, layers, selected.unwrap_or(LayerId(1)));+ if let Some(c) = root.data("backgroundColor").and_then(floats4) {+ document.background = [c[0], c[1], c[2]].map(|v| v.clamp(0.0, 1.0));+ }+ document.background_visible = !root.bool("backgroundHidden").unwrap_or(false);+ if let Some(dpi) = root.real("SilicaDocumentArchiveDPIKey").filter(|d| d.is_finite() && *d > 0.0) {+ document.dpi = dpi as f32;+ }+ let kept = root.object("colorProfile");+ let profile = kept.as_ref().and_then(|p| p.string("SiColorProfileArchiveICCNameKey"));+ let icc = kept.as_ref().and_then(|p| p.data("SiColorProfileArchiveICCDataKey")).and_then(IccProfile::parse);+ let nearest = match profile.as_deref() {+ Some(p) if p.contains("P3") => Profile::DisplayP3,+ _ => Profile::Srgb,+ };+ match (profile.as_deref().and_then(Profile::from_name), icc) {+ (Some(builtin), _) => document.profile = builtin,+ // a CMYK canvas keeps its pixels in Display P3; an RGB profile of its own keeps them in it+ (None, Some(icc)) if icc.space == Space::Cmyk => {+ document.profile = Profile::DisplayP3;+ document.icc = Some(CanvasIcc(Arc::new(icc)));+ }+ (None, Some(icc)) if icc.space == Space::Rgb => {+ document.profile = nearest;+ document.icc = Some(CanvasIcc(Arc::new(icc)));+ }+ _ => document.profile = nearest,+ }+ let document = document.repaired();+ Ok(Imported {+ document,+ pixels,+ name: root.string("name").filter(|n| !n.trim().is_empty()).unwrap_or_else(|| "Untitled Artwork".to_owned()),+ author: root.string("authorName").unwrap_or_default(),+ strokes: root.int("strokeCount").and_then(|s| u64::try_from(s).ok()).unwrap_or(0),+ tracked_seconds: root+ .real("SilicaDocumentTrackedTimeKey")+ .filter(|t| t.is_finite() && *t >= 0.0)+ .unwrap_or(0.0),+ })+}++/// "{w, h}" → (w, h).+fn parse_size(s: &str) -> Option<(u32, u32)> {+ let inner = s.trim().strip_prefix('{')?.strip_suffix('}')?;+ let (a, b) = inner.split_once(',')?;+ let w = a.trim().parse::<f64>().ok()?;+ let h = b.trim().parse::<f64>().ok()?;+ (w.is_finite() && h.is_finite() && w >= 0.0 && h >= 0.0).then_some((w.round() as u32, h.round() as u32))+}++/// Four little-endian floats.+fn floats4(d: &[u8]) -> Option<[f32; 4]> {+ let (chunks, _) = d.as_chunks::<4>();+ let v: Vec<f32> = chunks.iter().take(4).map(|c| f32::from_le_bytes(*c)).collect();+ Some([*v.first()?, *v.get(1)?, *v.get(2)?, *v.get(3)?])+}++/// What reading a layer's pixels needs: the package and how the canvas is stored and shown.+struct Canvas<'a> {+ zip: &'a ZipReader<'a>,+ w: u32,+ h: u32,+ tile: u32,+ turns: u32,+ flip_x: bool,+ flip_y: bool,+}++impl Canvas<'_> {+ /// A layer's pixels, `bpp` bytes each, top row first, turned as the canvas is shown; where no+ /// tile was stored, every byte is `blank`.+ fn pixels(&self, uuid: &str, bpp: usize, blank: u8) -> Result<Vec<u8>, ReadError> {+ let (w, h, t) = (self.w as usize, self.h as usize, self.tile as usize);+ let mut out = vec![blank; w * h * bpp];+ let prefix = format!("{uuid}/");+ let names: Vec<String> =+ self.zip.names().filter(|n| n.starts_with(&prefix) && n.ends_with(".lz4")).map(str::to_owned).collect();+ for name in names {+ let Some((tx, ty)) = name+ .get(prefix.len()..name.len() - 4)+ .and_then(|s| s.split_once('~'))+ .and_then(|(x, y)| Some((x.parse::<usize>().ok()?, y.parse::<usize>().ok()?)))+ else {+ continue;+ };+ if tx * t >= w || ty * t >= h {+ continue;+ }+ let (tw, th) = (t.min(w - tx * t), t.min(h - ty * t));+ let Some(packed) = self.zip.read(&name) else { return Err(ReadError::Damaged("tile")) };+ let raw = applz4::decode(&packed, tw * th * bpp).ok_or(ReadError::Damaged("tile"))?;+ if raw.len() != tw * th * bpp {+ return Err(ReadError::Damaged("tile size"));+ }+ for r in 0..th {+ // rows are stored bottom-up+ let row = h - 1 - (ty * t + r);+ let src = raw.get(r * tw * bpp..(r + 1) * tw * bpp).ok_or(ReadError::Damaged("tile"))?;+ let at = (row * w + tx * t) * bpp;+ out.get_mut(at..at + tw * bpp).ok_or(ReadError::Damaged("tile"))?.copy_from_slice(src);+ }+ }+ Ok(orient(&out, w, h, bpp, self.turns, self.flip_x, self.flip_y))+ }+}++/// `src` (`w` × `h`, `bpp` bytes a pixel, top row first) turned `turns` quarter turns clockwise,+/// then mirrored.+fn orient(src: &[u8], w: usize, h: usize, bpp: usize, turns: u32, flip_x: bool, flip_y: bool) -> Vec<u8> {+ if turns == 0 && !flip_x && !flip_y {+ return src.to_vec();+ }+ let (dw, dh) = if turns % 2 == 1 { (h, w) } else { (w, h) };+ let mut out = vec![0u8; src.len()];+ for y in 0..dh {+ for x in 0..dw {+ let (mx, my) = (if flip_x { dw - 1 - x } else { x }, if flip_y { dh - 1 - y } else { y });+ // the source pixel shown at (mx, my) after the turn+ let (sx, sy) = match turns % 4 {+ 1 => (my, h - 1 - mx),+ 2 => (w - 1 - mx, h - 1 - my),+ 3 => (w - 1 - my, mx),+ _ => (mx, my),+ };+ let (s, d) = ((sy * w + sx) * bpp, (y * dw + x) * bpp);+ if let (Some(from), Some(to)) = (src.get(s..s + bpp), out.get_mut(d..d + bpp)) {+ to.copy_from_slice(from);+ }+ }+ }+ out+}++/// Adds an archived item (a layer with its mask, or a group with what it holds, top first) to+/// `layers`, bottom first.+#[allow(clippy::too_many_arguments)]+fn add_item(+ canvas: &Canvas<'_>,+ item: &Object<'_>,+ parent: Option<LayerId>,+ layers: &mut Vec<Layer>,+ pixels: &mut Vec<(LayerId, Vec<u8>)>,+ next: &mut u64,+ selected_uuid: Option<&str>,+ selected: &mut Option<LayerId>,+) -> Result<(), ReadError> {+ if layers.len() > 4096 {+ return Err(ReadError::TooLarge);+ }+ let mut id = || {+ let i = LayerId(*next);+ *next += 1;+ i+ };+ match item.class() {+ Some("SilicaGroup") | Some("ValkyrieGroup") => {+ let gid = id();+ // the group sits above what it holds+ for child in item.array("children").iter().rev() {+ add_item(canvas, child, Some(gid), layers, pixels, next, selected_uuid, selected)?;+ }+ layers.push(Layer {+ id: gid,+ name: item.string("name").unwrap_or_else(|| "New group".to_owned()),+ visible: !item.bool("isHidden").unwrap_or(false),+ opacity: item.real("opacity").unwrap_or(1.0) as f32,+ blend: BlendMode::Normal,+ alpha_lock: false,+ clipped: item.bool("isClipped").unwrap_or(false),+ locked: item.bool("isLocked").unwrap_or(false),+ reference: false,+ kind: LayerKind::Group,+ parent,+ collapsed: item.bool("isCollapsed").unwrap_or(false),+ text: None,+ });+ }+ _ => {+ let lid = id();+ let uuid = item.string("UUID").unwrap_or_default();+ if selected_uuid == Some(uuid.as_str()) {+ *selected = Some(lid);+ }+ let blend = item+ .int("extendedBlend2")+ .or_else(|| item.int("extendedBlend"))+ .or_else(|| item.int("blend"))+ .unwrap_or(0);+ layers.push(Layer {+ id: lid,+ name: item.string("name").unwrap_or_else(|| "Layer".to_owned()),+ visible: !item.bool("hidden").unwrap_or(false),+ opacity: item.real("opacity").unwrap_or(1.0) as f32,+ blend: blend_from(blend),+ alpha_lock: item.bool("preserve").unwrap_or(false),+ clipped: item.bool("clipped").unwrap_or(false),+ locked: item.bool("locked").unwrap_or(false),+ reference: false,+ kind: LayerKind::Paint,+ parent,+ collapsed: false,+ text: None,+ });+ if !uuid.is_empty() {+ pixels.push((lid, canvas.pixels(&uuid, 4, 0)?));+ }+ // a mask goes just above its layer+ if let Some(mask) = item.object("mask") {+ let mid = id();+ layers.push(Layer {+ id: mid,+ name: "Layer Mask".to_owned(),+ visible: !mask.bool("hidden").unwrap_or(false),+ opacity: 1.0,+ blend: BlendMode::Normal,+ alpha_lock: false,+ clipped: false,+ locked: mask.bool("locked").unwrap_or(false),+ reference: false,+ kind: LayerKind::Mask,+ parent: Some(lid),+ collapsed: false,+ text: None,+ });+ if let Some(m) = mask.string("UUID") {+ // a mask stores only the tiles painted on: the rest shows the layer+ let grey = canvas.pixels(&m, 1, 255)?;+ pixels.push((mid, grey.iter().flat_map(|&g| [g, g, g, 255]).collect()));+ }+ }+ }+ }+ Ok(())+}++/// Each blend mode's number in the package (`extendedBlend2`).+const BLENDS: [(i64, BlendMode); 27] = [+ (0, BlendMode::Normal),+ (1, BlendMode::Multiply),+ (2, BlendMode::Screen),+ (3, BlendMode::Add),+ (4, BlendMode::Lighten),+ (5, BlendMode::Exclusion),+ (6, BlendMode::Difference),+ (7, BlendMode::Subtract),+ (8, BlendMode::LinearBurn),+ (9, BlendMode::ColorDodge),+ (10, BlendMode::ColorBurn),+ (11, BlendMode::Overlay),+ (12, BlendMode::HardLight),+ (13, BlendMode::Color),+ (14, BlendMode::Luminosity),+ (15, BlendMode::Hue),+ (16, BlendMode::Saturation),+ (17, BlendMode::SoftLight),+ (19, BlendMode::Shade),+ (20, BlendMode::HardMix),+ (21, BlendMode::VividLight),+ (22, BlendMode::LinearLight),+ (23, BlendMode::PinLight),+ (24, BlendMode::LighterColor),+ (25, BlendMode::DarkerColor),+ (26, BlendMode::Divide),+ (34, BlendMode::Darken),+];++pub(crate) fn blend_from(n: i64) -> BlendMode {+ BLENDS.iter().find(|(id, _)| *id == n).map_or(BlendMode::Normal, |(_, m)| *m)+}++pub(crate) fn blend_to(b: BlendMode) -> i64 {+ BLENDS.iter().find(|(_, m)| *m == b).map_or(0, |(id, _)| *id)+}++/// A blend number as the two older keys hold it (`blend`, `extendedBlend`): the oldest stops at+/// 19, and Darken, renumbered since, is 19 in both.+pub(crate) fn older_blends(id: i64) -> (i64, i64) {+ match id {+ 34 => (19, 19),+ _ => (if id <= 19 { id } else { 0 }, id),+ }+}++/// What an export writes besides the document: each paint layer's pixels (premultiplied RGBA)+/// and each mask's (grey in red), the flattened picture (premultiplied, background included) and+/// the preview PNG.+pub struct Export<'a> {+ pub document: &'a Document,+ pub pixels: &'a std::collections::HashMap<LayerId, Vec<u8>>,+ pub composite: &'a [u8],+ pub thumbnail_png: &'a [u8],+ pub name: &'a str,+ pub author: &'a str,+ pub strokes: u64,+ pub tracked_seconds: f64,+ /// Seeds the layers' UUIDs.+ pub seed: u64,+}++/// Writes a package.+pub fn write(e: &Export<'_>) -> Vec<u8> {+ let doc = e.document;+ let (w, h) = (doc.width(), doc.height());+ let mut zip = ZipWriter::new();+ let mut b = Builder::new();+ let mut uuids = Uuids(e.seed ^ 0x9E37_79B9_7F4A_7C15);+ let doc_ref = b.reserve();++ // layers and groups, top first, as nested lists+ let tops = top_first(doc, None);+ let mut selected = Builder::null();+ let mut items = Vec::new();+ for id in tops {+ items.push(write_item(&mut b, &mut zip, &mut uuids, e, &doc_ref, id, &mut selected));+ }+ let layers = b.array(items.clone(), true);+ let unwrapped = b.array(items, false);+ let composite_uuid = uuids.next();+ write_tiles(&mut zip, &composite_uuid, e.composite, w, h, 4, 0);+ let composite = layer_record(&mut b, &doc_ref, &composite_uuid, None, LayerRecord::plain(1), w, h);+ let mask_uuid = uuids.next();+ let mask = layer_record(&mut b, &doc_ref, &mask_uuid, None, LayerRecord::plain(2), w, h);+ let saved_masks = b.array(Vec::new(), true);++ let [r, g, bl] = doc.background;+ let background = b.add(Value::Data([r, g, bl, 1.0].iter().flat_map(|v| v.to_le_bytes()).collect()));+ let hsba = {+ let (hh, s, v) = hsv(r, g, bl);+ b.add(Value::Data([hh, s, v, 1.0].iter().flat_map(|v| v.to_le_bytes()).collect()))+ };+ let icc_name = b.string(&doc.profile_name());+ let icc_data = doc.icc.as_ref().map_or_else(|| crate::icc::icc(doc.profile), |i| i.0.bytes.to_vec());+ let profile = b.object(+ &["ValkyrieColorProfile", "NSObject"],+ vec![("SiColorProfileArchiveICCNameKey", icc_name), ("SiColorProfileArchiveICCDataKey", Value::Data(icc_data))],+ );+ let animation = b.object(+ &["ValkyrieDocumentAnimation", "NSObject"],+ vec![+ ("animationMode", Value::Int(0)),+ ("frameRate", Value::Int(15)),+ ("onionSkinCount", Value::Int(12)),+ ("onionSkinOpacity", Value::Real(0.6)),+ ("playbackDirection", Value::Int(0)),+ ("playbackMode", Value::Int(1)),+ ("primaryMixed", Value::Bool(false)),+ ],+ );+ let size = b.string(&format!("{{{w}, {h}}}"));+ let name = b.string(e.name);+ let author = if e.author.is_empty() { Builder::null() } else { b.string(e.author) };+ let strokes = b.add(Value::Int(i64::try_from(e.strokes).unwrap_or(i64::MAX)));+ let reference_kind = b.string("{0, 0}");+ let reference_size = b.string("{350, 532}");+ b.fill(+ &doc_ref,+ &["SilicaDocument", "ValkyrieDocument", "NSObject"],+ vec![+ ("SilicaDocumentArchiveDPIKey", Value::Real(f64::from(doc.dpi))),+ ("SilicaDocumentArchiveUnitKey", Value::Int(0)),+ ("SilicaDocumentTrackedTimeKey", Value::Real(e.tracked_seconds)),+ ("SilicaDocumentVideoPurgedKey", Value::Bool(false)),+ ("animation", animation),+ ("authorName", author),+ ("backgroundColor", background),+ ("backgroundColorHSBA", hsba),+ ("backgroundHidden", Value::Bool(!doc.background_visible)),+ ("colorProfile", profile),+ ("composite", composite),+ ("faceBackgroundHidden", Value::Bool(false)),+ ("featureSet", Value::Int(1)),+ ("flippedHorizontally", Value::Bool(false)),+ ("flippedVertically", Value::Bool(false)),+ ("isFirstItemAnimationForeground", Value::Bool(false)),+ ("isLastItemAnimationBackground", Value::Bool(false)),+ ("layers", layers),+ ("legacyBehaviour", Value::Int(1)),+ ("mask", mask),+ ("name", name),+ ("orientation", Value::Int(1)),+ ("primaryItem", selected.clone()),+ ("reference3D", Value::Bool(false)),+ ("referenceAnchor", Value::Int(0)),+ ("referenceCorner", Value::Int(0)),+ ("referenceDocked", Value::Bool(false)),+ ("referenceKind", reference_kind),+ ("referenceOrientation", Value::Int(0)),+ ("referenceSize", reference_size),+ ("referenceVisibility", Value::Bool(false)),+ ("selectedLayer", selected),+ ("selectedSamplerLayer", Builder::null()),+ ("size", size),+ ("solo", Builder::null()),+ ("strokeCount", strokes),+ ("tileSize", Value::Int(i64::from(TILE))),+ ("unwrappedLayers", unwrapped),+ ("userSavedSelectionMasks", saved_masks),+ ("version", Value::Int(2)),+ ("videoEnabled", Value::Bool(false)),+ ],+ );+ zip.add("Document.archive", &b.finish(doc_ref));+ zip.add("QuickLook/Thumbnail.png", e.thumbnail_png);+ zip.finish()+}++/// The ids of what is directly in `group` (or at the top), top first; masks left out.+fn top_first(doc: &Document, group: Option<LayerId>) -> Vec<LayerId> {+ doc.layers().iter().rev().filter(|l| l.kind != LayerKind::Mask && l.parent == group).map(|l| l.id).collect()+}++/// Writes a layer (with its mask and tiles) or a group (with what it holds); gives its record.+fn write_item(+ b: &mut Builder,+ zip: &mut ZipWriter,+ uuids: &mut Uuids,+ e: &Export<'_>,+ doc_ref: &Value,+ id: LayerId,+ selected: &mut Value,+) -> Value {+ let doc = e.document;+ let (w, h) = (doc.width(), doc.height());+ let Some(l) = doc.layer(id) else { return Builder::null() };+ if l.kind == LayerKind::Group {+ let children: Vec<Value> =+ top_first(doc, Some(id)).into_iter().map(|c| write_item(b, zip, uuids, e, doc_ref, c, selected)).collect();+ let children = b.array(children, true);+ let name = b.string(&l.name);+ return b.object(+ &["SilicaGroup", "ValkyrieGroup", "NSObject"],+ vec![+ ("animationHeldLength", Value::Int(0)),+ ("children", children),+ ("document", doc_ref.clone()),+ ("isClipped", Value::Bool(l.clipped)),+ ("isCollapsed", Value::Bool(l.collapsed)),+ ("isHidden", Value::Bool(!l.visible)),+ ("isLocked", Value::Bool(l.locked)),+ ("isPrivate", Value::Bool(false)),+ ("name", name),+ ("opacity", Value::Real(f64::from(l.opacity))),+ ],+ );+ }+ let uuid = uuids.next();+ let px = e.pixels.get(&id);+ if let Some(px) = px {+ write_tiles(zip, &uuid, px, w, h, 4, 0);+ }+ let mask = doc.mask_of(id).and_then(|m| {+ let ml = doc.layer(m)?;+ let mask_uuid = uuids.next();+ let grey: Option<Vec<u8>> = e.pixels.get(&m).map(|px| px.as_chunks::<4>().0.iter().map(|&[r, ..]| r).collect());+ if let Some(grey) = &grey {+ write_tiles(zip, &mask_uuid, grey, w, h, 1, 255);+ }+ let rec = LayerRecord {+ kind: 3,+ name: Some("Layer Mask"),+ bounds: Some(grey.map_or([0.0; 4], |g| bounds(&g, w, h, 1, 255))),+ opacity: 1.0,+ blend: 0,+ hidden: !ml.visible,+ locked: ml.locked,+ clipped: false,+ alpha_lock: false,+ };+ Some(layer_record(b, doc_ref, &mask_uuid, None, rec, w, h))+ });+ let rec = LayerRecord {+ kind: 0,+ name: Some(&l.name),+ bounds: Some(px.map_or([0.0; 4], |px| bounds(px, w, h, 4, 0))),+ opacity: l.opacity,+ blend: blend_to(l.blend),+ hidden: !l.visible,+ locked: l.locked,+ clipped: l.clipped,+ alpha_lock: l.alpha_lock,+ };+ let r = layer_record(b, doc_ref, &uuid, mask, rec, w, h);+ if id == doc.current() {+ *selected = r.clone();+ }+ r+}++/// A layer's settings as archived.+struct LayerRecord<'a> {+ /// 0 paint, 1 the flattened picture, 2 the selection, 3 a layer's mask.+ kind: i64,+ name: Option<&'a str>,+ /// What is painted: x, y from the bottom, width and height (all 0 if nothing); `None` where+ /// it isn't kept (the flattened picture).+ bounds: Option<[f64; 4]>,+ opacity: f32,+ blend: i64,+ hidden: bool,+ locked: bool,+ clipped: bool,+ alpha_lock: bool,+}++impl LayerRecord<'_> {+ fn plain(kind: i64) -> LayerRecord<'static> {+ LayerRecord {+ kind,+ name: None,+ bounds: (kind != 1).then_some([0.0; 4]),+ opacity: 1.0,+ blend: 0,+ hidden: false,+ locked: false,+ clipped: false,+ alpha_lock: false,+ }+ }+}++fn layer_record(+ b: &mut Builder,+ doc_ref: &Value,+ uuid: &str,+ mask: Option<Value>,+ r: LayerRecord<'_>,+ w: u32,+ h: u32,+) -> Value {+ let uuid = b.string(uuid);+ let name = match r.name {+ Some(n) => b.string(n),+ None => Builder::null(),+ };+ let rect = b.add(Value::Data(r.bounds.unwrap_or_default().iter().flat_map(|v| v.to_le_bytes()).collect()));+ let identity: Vec<u8> = [1.0f64, 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1.]+ .iter()+ .flat_map(|v| v.to_le_bytes())+ .collect();+ let transform = b.add(Value::Data(identity));+ let pdf_transform = b.string("[0, 0, 0, 0, 0, 0]");+ let time_keys: Vec<Value> = ["flags", "value", "timescale", "epoch"].iter().map(|k| b.string(k)).collect();+ let zeros: Vec<Value> = (0..4).map(|_| b.add(Value::Int(0))).collect();+ let video_time = b.object(+ &["NSDictionary", "NSObject"],+ vec![("NS.keys", Value::Array(time_keys)), ("NS.objects", Value::Array(zeros))],+ );+ b.object(+ &["SilicaLayer", "ValkyrieLayer", "NSObject"],+ vec![+ ("UUID", uuid),+ ("animationHeldLength", Value::Int(0)),+ ("blend", Value::Int(older_blends(r.blend).0)),+ ("bundledImagePath", Builder::null()),+ ("bundledMaskPath", Builder::null()),+ ("bundledVideoPath", Builder::null()),+ ("clipped", Value::Bool(r.clipped)),+ ("contentsRect", rect),+ ("contentsRectValid", Value::Bool(r.bounds.is_some())),+ ("document", doc_ref.clone()),+ ("extendedBlend", Value::Int(older_blends(r.blend).1)),+ ("extendedBlend2", Value::Int(r.blend)),+ ("hidden", Value::Bool(r.hidden)),+ ("locked", Value::Bool(r.locked)),+ ("mask", mask.unwrap_or_else(Builder::null)),+ ("name", name),+ ("opacity", Value::Real(f64::from(r.opacity))),+ ("perspectiveAssisted", Value::Bool(false)),+ ("preserve", Value::Bool(r.alpha_lock)),+ ("private", Value::Bool(false)),+ ("sizeHeight", Value::Int(i64::from(h))),+ ("sizeWidth", Value::Int(i64::from(w))),+ ("text", Builder::null()),+ ("textPDF", Builder::null()),+ ("textPDFTransform", pdf_transform),+ ("textureSet", Builder::null()),+ ("transform", transform),+ ("type", Value::Int(r.kind)),+ ("version", Value::Int(4)),+ ("videoTime", video_time),+ ],+ )+}++/// The smallest rectangle holding every pixel of `px` that isn't all `blank`: x, y from the+/// bottom, width and height; all 0 if there is none.+fn bounds(px: &[u8], w: u32, h: u32, bpp: usize, blank: u8) -> [f64; 4] {+ let (w, h) = (w as usize, h as usize);+ let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0, 0);+ for (i, p) in px.chunks_exact(bpp).enumerate().take(w * h) {+ if p.iter().any(|&v| v != blank) {+ let (x, y) = (i % w, i / w);+ (x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x), y1.max(y));+ }+ }+ if x0 == usize::MAX {+ return [0.0; 4];+ }+ [x0 as f64, (h - 1 - y1) as f64, (x1 - x0 + 1) as f64, (y1 - y0 + 1) as f64]+}++/// Writes `px` (`w` × `h`, `bpp` bytes a pixel, top row first) as tiles under `uuid/`, leaving out+/// those whose every byte is `blank` (clear paint, white mask).+fn write_tiles(zip: &mut ZipWriter, uuid: &str, px: &[u8], w: u32, h: u32, bpp: usize, blank: u8) {+ let (w, h, t) = (w as usize, h as usize, TILE as usize);+ for ty in 0..h.div_ceil(t) {+ for tx in 0..w.div_ceil(t) {+ let (tw, th) = (t.min(w - tx * t), t.min(h - ty * t));+ let mut raw = Vec::with_capacity(tw * th * bpp);+ for r in 0..th {+ let row = h - 1 - (ty * t + r);+ let at = (row * w + tx * t) * bpp;+ raw.extend_from_slice(px.get(at..at + tw * bpp).unwrap_or(&[]));+ }+ if raw.len() != tw * th * bpp || raw.iter().all(|&v| v == blank) {+ continue;+ }+ zip.add(&format!("{uuid}/{tx}~{ty}.lz4"), &applz4::encode(&raw));+ }+ }+}++/// UUIDs from a seed (random enough to tell layers apart).+struct Uuids(u64);++impl Uuids {+ fn next(&mut self) -> String {+ let mut word = || {+ // splitmix64+ self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);+ let mut z = self.0;+ z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);+ z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);+ z ^ (z >> 31)+ };+ let (a, c) = (word(), word());+ format!(+ "{:08X}-{:04X}-4{:03X}-{:04X}-{:012X}",+ a >> 32,+ (a >> 16) & 0xFFFF,+ a & 0x0FFF,+ ((c >> 48) & 0x3FFF) | 0x8000,+ c & 0xFFFF_FFFF_FFFF+ )+ }+}++/// Hue, saturation and brightness of a colour, all 0..1.+fn hsv(r: f32, g: f32, b: f32) -> (f32, f32, f32) {+ let max = r.max(g).max(b);+ let min = r.min(g).min(b);+ let d = max - min;+ let h = if d <= 0.0 {+ 0.0+ } else if max == r {+ ((g - b) / d).rem_euclid(6.0) / 6.0+ } else if max == g {+ ((b - r) / d + 2.0) / 6.0+ } else {+ ((r - g) / d + 4.0) / 6.0+ };+ (h, if max <= 0.0 { 0.0 } else { d / max }, max)+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::collections::HashMap;++ fn painted(w: u32, h: u32, f: impl Fn(u32, u32) -> [u8; 4]) -> Vec<u8> {+ let mut out = Vec::with_capacity((w * h * 4) as usize);+ for y in 0..h {+ for x in 0..w {+ out.extend_from_slice(&f(x, y));+ }+ }+ out+ }++ #[test]+ fn an_artwork_survives_a_round_trip() {+ let (w, h) = (300, 520);+ let mut doc = Document::new(w, h);+ let base = doc.current();+ doc.rename(base, "Sketch");+ doc.set_opacity(base, 0.75);+ doc.set_blend(base, BlendMode::Multiply);+ let top = doc.add_layer();+ doc.rename(top, "Ink");+ doc.set_clipped(top, true);+ let mask = doc.add_mask(base).unwrap();+ doc.background = [0.2, 0.4, 0.6];+ let mut pixels = HashMap::new();+ // a gradient that tells top from bottom and left from right+ let sketch = painted(w, h, |x, y| [(x % 256) as u8, (y % 256) as u8, 0, 255]);+ let ink = painted(w, h, |x, y| if (x / 37 + y / 41) % 3 == 0 { [10, 20, 30, 128] } else { [0; 4] });+ let grey = painted(w, h, |x, _| {+ let g = if x < 150 { 255 } else { 0 };+ [g, g, g, 255]+ });+ pixels.insert(base, sketch.clone());+ pixels.insert(top, ink.clone());+ pixels.insert(mask, grey.clone());+ let composite = vec![255u8; (w * h * 4) as usize];+ let bytes = write(&Export {+ document: &doc,+ pixels: &pixels,+ composite: &composite,+ thumbnail_png: &[],+ name: "Round trip",+ author: "",+ strokes: 7,+ tracked_seconds: 12.5,+ seed: 42,+ });++ let back = read(&bytes).unwrap();+ assert_eq!(back.name, "Round trip");+ assert_eq!(back.strokes, 7);+ let d = &back.document;+ assert_eq!((d.width(), d.height()), (w, h));+ assert!((d.background[2] - 0.6).abs() < 1e-6);+ let kinds: Vec<(LayerKind, &str)> = d.layers().iter().map(|l| (l.kind, l.name.as_str())).collect();+ assert_eq!(kinds, [(LayerKind::Paint, "Sketch"), (LayerKind::Mask, "Layer Mask"), (LayerKind::Paint, "Ink")]);+ let sk = d.layers().first().unwrap();+ assert_eq!((sk.blend, sk.opacity), (BlendMode::Multiply, 0.75));+ assert!(d.layers().get(2).unwrap().clipped);+ let px = |i: usize| &back.pixels.iter().find(|(id, _)| *id == d.layers().get(i).unwrap().id).unwrap().1;+ assert_eq!(px(0), &sketch);+ assert_eq!(px(1), &grey);+ assert_eq!(px(2), &ink);+ }++ #[test]+ fn a_canvas_keeps_its_own_profile() {+ let (w, h) = (40, 30);+ let pixels = HashMap::new();+ let composite = vec![255u8; (w * h * 4) as usize];+ let export = |doc: &Document| {+ read(&write(&Export {+ document: doc,+ pixels: &pixels,+ composite: &composite,+ thumbnail_png: &[],+ name: "Profiles",+ author: "",+ strokes: 0,+ tracked_seconds: 0.0,+ seed: 1,+ }))+ .unwrap()+ .document+ };+ // a CMYK canvas: its pixels in Display P3, the press profile kept whole+ let mut doc = Document::new(w, h);+ let press = IccProfile::parse(&crate::cmyk::profile()).unwrap();+ doc.change_to(Profile::DisplayP3, Some(CanvasIcc(Arc::new(press))));+ let back = export(&doc);+ assert_eq!(back.profile, Profile::DisplayP3);+ assert_eq!(back.icc, doc.icc);+ assert_eq!(back.profile_name(), crate::cmyk::NAME);+ assert!(back.press().is_some());+ // a built-in profile stays built in+ let mut doc = Document::new(w, h);+ doc.change_profile(Profile::DisplayP3);+ let back = export(&doc);+ assert_eq!((back.profile, back.icc.is_none()), (Profile::DisplayP3, true));+ }++ #[test]+ fn every_blend_mode_has_its_number() {+ for m in BlendMode::ALL {+ assert_eq!(blend_from(blend_to(m)), m, "{m:?}");+ }+ assert_eq!(+ (blend_to(BlendMode::Shade), blend_to(BlendMode::Darken), blend_to(BlendMode::Divide)),+ (19, 34, 26)+ );+ // the older keys: Darken keeps its old number, and the oldest stops at 19+ assert_eq!(older_blends(34), (19, 19));+ assert_eq!(older_blends(26), (0, 26));+ assert_eq!(older_blends(14), (14, 14));+ assert_eq!(blend_from(18), BlendMode::Normal);+ }++ #[test]+ fn masks_keep_only_what_is_painted_on_them() {+ let (w, h) = (300, 520);+ let mut doc = Document::new(w, h);+ let base = doc.current();+ let mask = doc.add_mask(base).unwrap();+ // white but for a dark square near the top left+ let grey =+ painted(+ w,+ h,+ |x, y| if (10..20).contains(&x) && (20..24).contains(&y) { [0, 0, 0, 255] } else { [255; 4] },+ );+ let mut pixels = HashMap::new();+ pixels.insert(base, vec![0u8; (w * h * 4) as usize]);+ pixels.insert(mask, grey.clone());+ let bytes = write(&Export {+ document: &doc,+ pixels: &pixels,+ composite: &vec![255u8; (w * h * 4) as usize],+ thumbnail_png: &[],+ name: "",+ author: "",+ strokes: 0,+ tracked_seconds: 0.0,+ seed: 3,+ });+ // the picture's 6 tiles, the mask's one, none for the clear layer+ let zip = ZipReader::new(&bytes).unwrap();+ assert_eq!(zip.names().filter(|n| n.ends_with(".lz4")).count(), 7);+ let back = read(&bytes).unwrap();+ let m = back.document.layers().iter().find(|l| l.kind == LayerKind::Mask).unwrap();+ assert_eq!(back.pixels.iter().find(|(id, _)| *id == m.id).unwrap().1, grey);+ assert_eq!(bounds(&grey, w, h, 4, 255), [10.0, 496.0, 10.0, 4.0]);+ }++ #[test]+ fn bounds_count_rows_from_the_bottom() {+ let mut px = vec![0u8; 4 * 3];+ px[1] = 9;+ assert_eq!(bounds(&px, 4, 3, 1, 0), [1.0, 2.0, 1.0, 1.0]);+ assert_eq!(bounds(&[0; 12], 4, 3, 1, 0), [0.0; 4]);+ }++ #[test]+ fn groups_keep_what_they_hold() {+ let mut doc = Document::new(64, 64);+ let a = doc.current();+ let b = doc.add_layer();+ doc.set_current(b);+ let g = doc.combine_down(b).unwrap();+ doc.rename(g, "Pair");+ doc.set_collapsed(g, true);+ let c = doc.add_layer();+ let mut pixels = HashMap::new();+ for id in [a, b, c] {+ pixels.insert(id, vec![0u8; 64 * 64 * 4]);+ }+ let bytes = write(&Export {+ document: &doc,+ pixels: &pixels,+ composite: &[0; 64 * 64 * 4],+ thumbnail_png: &[],+ name: "",+ author: "",+ strokes: 0,+ tracked_seconds: 0.0,+ seed: 1,+ });+ let back = read(&bytes).unwrap();+ let d = &back.document;+ assert_eq!(back.name, "Untitled Artwork");+ let group = d.layers().iter().find(|l| l.kind == LayerKind::Group).unwrap();+ assert_eq!(group.name, "Pair");+ assert!(group.collapsed);+ // the same tree: kinds, and which group each sits in, bottom first+ let shape = |d: &Document| {+ d.layers().iter().map(|l| (l.kind, l.parent.and_then(|p| d.index_of(p)))).collect::<Vec<_>>()+ };+ assert_eq!(shape(d), shape(&doc));+ }++ #[test]+ fn turned_canvases_are_shown_upright() {+ // 3 × 2, values = index; a quarter turn clockwise makes it 2 × 3+ let src: Vec<u8> = (0..6).collect();+ assert_eq!(orient(&src, 3, 2, 1, 1, false, false), [3, 0, 4, 1, 5, 2]);+ assert_eq!(orient(&src, 3, 2, 1, 2, false, false), [5, 4, 3, 2, 1, 0]);+ assert_eq!(orient(&src, 3, 2, 1, 3, false, false), [2, 5, 1, 4, 0, 3]);+ assert_eq!(orient(&src, 3, 2, 1, 0, true, false), [2, 1, 0, 5, 4, 3]);+ assert_eq!(parse_size("{1488, 2266}"), Some((1488, 2266)));+ assert_eq!(parse_size("1488x2266"), None);+ }++ #[test]+ fn what_isnt_a_package_is_refused() {+ assert_eq!(read(b"hello").err(), Some(ReadError::NotAPackage));+ let mut z = ZipWriter::new();+ z.add("Document.archive", b"not an archive");+ assert_eq!(read(&z.finish()).err(), Some(ReadError::Damaged("document")));+ }++ /// A real package, when one is given (`PACKAGE_SAMPLE=path`): it reads, the right size.+ #[test]+ fn a_sample_reads() {+ let Ok(path) = std::env::var("PACKAGE_SAMPLE") else { return };+ let bytes = std::fs::read(path).unwrap();+ let back = read(&bytes).unwrap();+ eprintln!(+ "{} x {}, layers {:?}",+ back.document.width(),+ back.document.height(),+ back.document.layers().iter().map(|l| (&l.name, l.kind, l.blend)).collect::<Vec<_>>()+ );+ assert!(!back.pixels.is_empty());+ // and, if asked, the first layer's coverage as a picture to look at+ if let (Ok(out), Some((_, px))) = (std::env::var("PACKAGE_SAMPLE_OUT"), back.pixels.first()) {+ let mut pgm = format!(+ "P5 {} {} 255+",+ back.document.width(),+ back.document.height()+ )+ .into_bytes();+ pgm.extend(px.as_chunks::<4>().0.iter().map(|p| 255 - p[3]));+ std::fs::write(out, pgm).unwrap();+ }+ // and, if asked, written back as a package (`PACKAGE_REWRITE=path`), the paint layers+ // flattened over the background for the composite, the sample's own preview kept+ if let Ok(out) = std::env::var("PACKAGE_REWRITE") {+ let doc = &back.document;+ let bg = doc.background.map(|c| (c * 255.0).round() as u8);+ let mut composite: Vec<u8> =+ (0..doc.width() * doc.height()).flat_map(|_| [bg[0], bg[1], bg[2], 255]).collect();+ for layer in doc.layers().iter().filter(|l| l.kind == LayerKind::Paint && l.visible) {+ let Some((_, px)) = back.pixels.iter().find(|(id, _)| *id == layer.id) else { continue };+ for (d, s) in composite.as_chunks_mut::<4>().0.iter_mut().zip(px.as_chunks::<4>().0) {+ let keep = 255 - u32::from(s[3]);+ for c in 0..4 {+ d[c] = (u32::from(s[c]) + (u32::from(d[c]) * keep + 127) / 255).min(255) as u8;+ }+ }+ }+ let preview = ZipReader::new(&bytes).unwrap().read("QuickLook/Thumbnail.png").unwrap();+ let pixels = back.pixels.iter().cloned().collect();+ let package = write(&Export {+ document: doc,+ pixels: &pixels,+ composite: &composite,+ thumbnail_png: &preview,+ name: &back.name,+ author: &back.author,+ strokes: back.strokes,+ tracked_seconds: back.tracked_seconds,+ seed: 7,+ });+ std::fs::write(out, package).unwrap();+ }+ }+}diff --git a/crates/engine/src/plist.rs b/crates/engine/src/plist.rsnew file mode 100644index 0000000..e0a0f91--- /dev/null+++ b/crates/engine/src/plist.rs@@ -0,0 +1,406 @@+//! Binary property lists (`bplist00`): reading them into [`Value`]s and writing them back. Enough+//! of the format for keyed archives: no 128-bit integers, sets or legacy types.++/// A property list value.+#[derive(Clone, Debug, PartialEq)]+pub enum Value {+ Null,+ Bool(bool),+ Int(i64),+ Real(f64),+ /// Seconds since 2001-01-01.+ Date(f64),+ Data(Vec<u8>),+ String(String),+ /// A reference to another object of a keyed archive.+ Uid(u64),+ Array(Vec<Value>),+ /// Keys in the order they were read (or are to be written).+ Dict(Vec<(String, Value)>),+}++impl Value {+ /// The value of `key`, if this is a dictionary that has it.+ pub fn get(&self, key: &str) -> Option<&Value> {+ match self {+ Value::Dict(entries) => entries.iter().find(|(k, _)| k == key).map(|(_, v)| v),+ _ => None,+ }+ }++ pub fn as_str(&self) -> Option<&str> {+ match self {+ Value::String(s) => Some(s),+ _ => None,+ }+ }++ pub fn as_int(&self) -> Option<i64> {+ match self {+ Value::Int(i) => Some(*i),+ Value::Real(r) if r.is_finite() => Some(*r as i64),+ Value::Bool(b) => Some(i64::from(*b)),+ _ => None,+ }+ }++ pub fn as_real(&self) -> Option<f64> {+ match self {+ Value::Real(r) => Some(*r),+ Value::Int(i) => Some(*i as f64),+ _ => None,+ }+ }++ pub fn as_bool(&self) -> Option<bool> {+ match self {+ Value::Bool(b) => Some(*b),+ Value::Int(i) => Some(*i != 0),+ _ => None,+ }+ }++ pub fn as_data(&self) -> Option<&[u8]> {+ match self {+ Value::Data(d) => Some(d),+ _ => None,+ }+ }++ pub fn as_uid(&self) -> Option<u64> {+ match self {+ Value::Uid(u) => Some(*u),+ _ => None,+ }+ }++ pub fn as_array(&self) -> Option<&[Value]> {+ match self {+ Value::Array(a) => Some(a),+ _ => None,+ }+ }+}++/// Deepest nesting read: a list deeper than this is refused rather than followed.+const MAX_DEPTH: usize = 64;+/// Most objects a list may claim to hold.+const MAX_OBJECTS: u64 = 4_000_000;++/// Reads a binary property list; `None` if it isn't one or is damaged.+pub fn read(bytes: &[u8]) -> Option<Value> {+ if bytes.get(..8)? != b"bplist00" {+ return None;+ }+ let trailer = bytes.get(bytes.len().checked_sub(32)?..)?;+ let offset_size = usize::from(*trailer.get(6)?);+ let ref_size = usize::from(*trailer.get(7)?);+ let count = be(trailer.get(8..16)?)?;+ let top = be(trailer.get(16..24)?)?;+ let table = be(trailer.get(24..32)?)?;+ if !(1..=8).contains(&offset_size) || !(1..=8).contains(&ref_size) || count > MAX_OBJECTS || top >= count {+ return None;+ }+ let reader = Reader { bytes, offset_size, ref_size, count, table: usize::try_from(table).ok()? };+ reader.object(top, 0)+}++struct Reader<'a> {+ bytes: &'a [u8],+ offset_size: usize,+ ref_size: usize,+ count: u64,+ table: usize,+}++impl Reader<'_> {+ fn offset_of(&self, object: u64) -> Option<usize> {+ if object >= self.count {+ return None;+ }+ let at = self.table.checked_add(usize::try_from(object).ok()?.checked_mul(self.offset_size)?)?;+ usize::try_from(be(self.bytes.get(at..at.checked_add(self.offset_size)?)?)?).ok()+ }++ /// The length that follows a marker whose low nibble is `low`, and where the content starts.+ fn length(&self, at: usize, low: u8) -> Option<(usize, usize)> {+ if low != 0x0F {+ return Some((usize::from(low), at + 1));+ }+ let marker = *self.bytes.get(at + 1)?;+ if marker >> 4 != 0x1 {+ return None;+ }+ let size = 1usize << (marker & 0x0F);+ let len = usize::try_from(be(self.bytes.get(at + 2..at + 2 + size)?)?).ok()?;+ Some((len, at + 2 + size))+ }++ fn reference(&self, at: usize, i: usize) -> Option<u64> {+ let start = at.checked_add(i.checked_mul(self.ref_size)?)?;+ be(self.bytes.get(start..start.checked_add(self.ref_size)?)?)+ }++ fn object(&self, object: u64, depth: usize) -> Option<Value> {+ if depth > MAX_DEPTH {+ return None;+ }+ let at = self.offset_of(object)?;+ let marker = *self.bytes.get(at)?;+ let (kind, low) = (marker >> 4, marker & 0x0F);+ Some(match kind {+ 0x0 => match low {+ 0x8 => Value::Bool(false),+ 0x9 => Value::Bool(true),+ _ => Value::Null,+ },+ 0x1 => {+ let size = 1usize.checked_shl(u32::from(low))?;+ let raw = self.bytes.get(at + 1..at + 1 + size)?;+ // 8-byte integers are signed; shorter ones are unsigned+ let v = be(raw)?;+ Value::Int(if size == 8 { v as i64 } else { i64::try_from(v).ok()? })+ }+ 0x2 => match low {+ 2 => Value::Real(f64::from(f32::from_be_bytes(self.bytes.get(at + 1..at + 5)?.try_into().ok()?))),+ 3 => Value::Real(f64::from_be_bytes(self.bytes.get(at + 1..at + 9)?.try_into().ok()?)),+ _ => return None,+ },+ 0x3 => Value::Date(f64::from_be_bytes(self.bytes.get(at + 1..at + 9)?.try_into().ok()?)),+ 0x4 => {+ let (len, start) = self.length(at, low)?;+ Value::Data(self.bytes.get(start..start.checked_add(len)?)?.to_vec())+ }+ 0x5 => {+ let (len, start) = self.length(at, low)?;+ let raw = self.bytes.get(start..start.checked_add(len)?)?;+ Value::String(raw.iter().map(|&b| char::from(b)).collect())+ }+ 0x6 => {+ let (len, start) = self.length(at, low)?;+ let raw = self.bytes.get(start..start.checked_add(len.checked_mul(2)?)?)?;+ let units: Vec<u16> = raw.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c)).collect();+ Value::String(String::from_utf16_lossy(&units))+ }+ 0x8 => Value::Uid(be(self.bytes.get(at + 1..at + 2 + usize::from(low))?)?),+ 0xA => {+ let (len, start) = self.length(at, low)?;+ let mut items = Vec::with_capacity(len.min(4096));+ for i in 0..len {+ items.push(self.object(self.reference(start, i)?, depth + 1)?);+ }+ Value::Array(items)+ }+ 0xD => {+ let (len, start) = self.length(at, low)?;+ let values = start.checked_add(len.checked_mul(self.ref_size)?)?;+ let mut entries = Vec::with_capacity(len.min(4096));+ for i in 0..len {+ let key = match self.object(self.reference(start, i)?, depth + 1)? {+ Value::String(s) => s,+ _ => return None,+ };+ entries.push((key, self.object(self.reference(values, i)?, depth + 1)?));+ }+ Value::Dict(entries)+ }+ _ => return None,+ })+ }+}++/// A big-endian unsigned integer of up to 8 bytes.+fn be(bytes: &[u8]) -> Option<u64> {+ if bytes.is_empty() || bytes.len() > 8 {+ return None;+ }+ Some(bytes.iter().fold(0u64, |acc, &b| (acc << 8) | u64::from(b)))+}++/// Writes `value` as a binary property list.+pub fn write(value: &Value) -> Vec<u8> {+ let mut objects: Vec<Vec<u8>> = Vec::new();+ // first pass: count the objects so references get their width+ let count = count_objects(value);+ let ref_size = width_for(count as u64);+ flatten(value, &mut objects, ref_size);+ let mut out = b"bplist00".to_vec();+ let mut offsets = Vec::with_capacity(objects.len());+ for o in &objects {+ offsets.push(out.len() as u64);+ out.extend_from_slice(o);+ }+ let table = out.len() as u64;+ let offset_size = width_for(table);+ for o in offsets {+ put_be(&mut out, o, offset_size);+ }+ out.extend_from_slice(&[0; 6]);+ out.push(offset_size as u8);+ out.push(ref_size as u8);+ out.extend_from_slice(&(objects.len() as u64).to_be_bytes());+ out.extend_from_slice(&0u64.to_be_bytes());+ out.extend_from_slice(&table.to_be_bytes());+ out+}++fn count_objects(v: &Value) -> usize {+ match v {+ Value::Array(items) => 1 + items.iter().map(count_objects).sum::<usize>(),+ Value::Dict(entries) => 1 + entries.iter().map(|(_, v)| 1 + count_objects(v)).sum::<usize>(),+ _ => 1,+ }+}++fn width_for(max: u64) -> usize {+ if max < 1 << 8 {+ 1+ } else if max < 1 << 16 {+ 2+ } else if max < 1 << 32 {+ 4+ } else {+ 8+ }+}++fn put_be(out: &mut Vec<u8>, v: u64, size: usize) {+ out.extend_from_slice(v.to_be_bytes().get(8 - size..).unwrap_or(&[]));+}++/// Adds `v` (and what it holds) to `objects`; returns its index. Objects are written in the order+/// they are first reached, a container before its contents.+fn flatten(v: &Value, objects: &mut Vec<Vec<u8>>, ref_size: usize) -> u64 {+ let index = objects.len();+ objects.push(Vec::new());+ let body = match v {+ Value::Null => vec![0x00],+ Value::Bool(b) => vec![if *b { 0x09 } else { 0x08 }],+ Value::Int(i) => {+ let mut o = Vec::new();+ if *i >= 0 && *i < 1 << 8 {+ o.push(0x10);+ o.push(*i as u8);+ } else if *i >= 0 && *i < 1 << 16 {+ o.push(0x11);+ o.extend_from_slice(&(*i as u16).to_be_bytes());+ } else if *i >= 0 && *i < 1 << 32 {+ o.push(0x12);+ o.extend_from_slice(&(*i as u32).to_be_bytes());+ } else {+ o.push(0x13);+ o.extend_from_slice(&i.to_be_bytes());+ }+ o+ }+ Value::Real(r) => {+ let mut o = vec![0x23];+ o.extend_from_slice(&r.to_be_bytes());+ o+ }+ Value::Date(d) => {+ let mut o = vec![0x33];+ o.extend_from_slice(&d.to_be_bytes());+ o+ }+ Value::Data(d) => {+ let mut o = marker(0x4, d.len());+ o.extend_from_slice(d);+ o+ }+ Value::String(s) => {+ if s.is_ascii() {+ let mut o = marker(0x5, s.len());+ o.extend_from_slice(s.as_bytes());+ o+ } else {+ let units: Vec<u16> = s.encode_utf16().collect();+ let mut o = marker(0x6, units.len());+ for u in units {+ o.extend_from_slice(&u.to_be_bytes());+ }+ o+ }+ }+ Value::Uid(u) => {+ let size = width_for(*u);+ let mut o = vec![0x80 | (size as u8 - 1)];+ put_be(&mut o, *u, size);+ o+ }+ Value::Array(items) => {+ let refs: Vec<u64> = items.iter().map(|i| flatten(i, objects, ref_size)).collect();+ let mut o = marker(0xA, refs.len());+ for r in refs {+ put_be(&mut o, r, ref_size);+ }+ o+ }+ Value::Dict(entries) => {+ let keys: Vec<u64> =+ entries.iter().map(|(k, _)| flatten(&Value::String(k.clone()), objects, ref_size)).collect();+ let values: Vec<u64> = entries.iter().map(|(_, v)| flatten(v, objects, ref_size)).collect();+ let mut o = marker(0xD, keys.len());+ for r in keys.into_iter().chain(values) {+ put_be(&mut o, r, ref_size);+ }+ o+ }+ };+ if let Some(slot) = objects.get_mut(index) {+ *slot = body;+ }+ index as u64+}++/// A marker of `kind` for `len` items, with the long-length form past 14.+fn marker(kind: u8, len: usize) -> Vec<u8> {+ if len < 15 {+ return vec![(kind << 4) | len as u8];+ }+ let size = width_for(len as u64);+ let power = size.trailing_zeros() as u8;+ let mut o = vec![(kind << 4) | 0x0F, 0x10 | power];+ put_be(&mut o, len as u64, size);+ o+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn values_round_trip() {+ let v = Value::Dict(vec![+ ("$version".into(), Value::Int(100_000)),+ ("big".into(), Value::Int(-5_000_000_000)),+ ("flag".into(), Value::Bool(true)),+ ("real".into(), Value::Real(132.5)),+ ("data".into(), Value::Data((0..40).collect())),+ ("text".into(), Value::String("Layer 1".into())),+ ("wide".into(), Value::String("Ébauche ✏".into())),+ ("long".into(), Value::String("x".repeat(300))),+ ("ref".into(), Value::Uid(1)),+ ("list".into(), Value::Array(vec![Value::Uid(2), Value::Null, Value::Date(3.0)])),+ ]);+ let bytes = write(&v);+ assert_eq!(read(&bytes), Some(v));+ }++ #[test]+ fn damaged_lists_are_refused() {+ assert_eq!(read(b"not a plist"), None);+ let bytes = write(&Value::Array(vec![Value::Int(1); 20]));+ for cut in [10, bytes.len() / 2, bytes.len() - 1] {+ assert_eq!(read(bytes.get(..cut).unwrap()), None, "cut at {cut}");+ }+ // a header and a trailer pointing nowhere+ let mut fake = b"bplist00".to_vec();+ fake.extend_from_slice(&[0; 6]);+ fake.extend_from_slice(&[1, 1]);+ fake.extend_from_slice(&5u64.to_be_bytes());+ fake.extend_from_slice(&0u64.to_be_bytes());+ fake.extend_from_slice(&9999u64.to_be_bytes());+ assert_eq!(read(&fake), None);+ }+}diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rsnew file mode 100644index 0000000..d1f13a7--- /dev/null+++ b/crates/engine/src/preview.rs@@ -0,0 +1,189 @@+//! The sample stroke a brush is shown with in the library and in the files it is shared in: a+//! gentle wave across a canvas of [`CANVAS`] pixels, drawn fast, its pressure swelling to full in+//! the middle, at a size the brush's preview size sets.++use crate::brush::Brush;+use crate::geom::Vec2;+use crate::input::Sample;++/// The canvas the sample stroke is drawn on (pixels); a preview of another size fits it in.+pub const CANVAS: (f32, f32) = (1060.0, 324.0);++/// How many pen samples the stroke has.+const SAMPLES: usize = 36;++/// The time between samples (milliseconds): a pen reporting 240 times a second.+const STEP_MS: f64 = 1000.0 / 240.0;++/// The wave, across and down the canvas (shares of its width and height) for 0..1 along it, as+/// polynomial coefficients (lowest power first).+const ACROSS: [f32; 6] = [0.11003, 0.74916, 0.032273, 0.045396, -0.087172, 0.03133];+const DOWN: [f32; 6] = [0.57235, 0.59775, -1.0046, -1.413, 2.7134, -0.97521];++/// The pressure the pen's swell is turned into: the brush's preview minimum plus this many times+/// the swell (times its preview pressure scale).+const PRESSURE_GAIN: f32 = 1.0;++/// Where along the wave `t` (0..1) is, in canvas pixels.+fn along(t: f32) -> Vec2 {+ let poly = |c: &[f32; 6]| c.iter().rev().fold(0.0, |acc, k| acc * t + k);+ Vec2::new(poly(&ACROSS) * CANVAS.0, poly(&DOWN) * CANVAS.1)+}++/// The pen's swell at `t` (0..1 along): light at the ends, full in the middle.+fn swell(t: f32) -> f32 {+ 1.005 * (-9.0 * (t - 0.5) * (t - 0.5)).exp()+}++/// The sample stroke for `brush`, in canvas pixels.+pub fn samples(brush: &Brush) -> Vec<Sample> {+ let least = brush.setting("preview_pressure_min");+ // the control's full travel doubles the pressure+ let gain = PRESSURE_GAIN * 2.0 * brush.setting("preview_pressure_scale");+ // the pen's direction turned by the preview's own offset (a quarter turn at 1)+ let azimuth = brush.setting("preview_tilt_offset") * std::f32::consts::FRAC_PI_2;+ (0..SAMPLES)+ .map(|i| {+ let t = i as f32 / (SAMPLES - 1) as f32;+ let pressure = (least + gain * swell(t)).clamp(0.0, 1.0);+ Sample { azimuth, ..Sample::at(along(t), pressure, i as f64 * STEP_MS) }+ })+ .collect()+}++/// The brush's size along the sample stroke, from its least (0) to its most (1): the preview size,+/// less for brushes so big they would not fit, more for small ones (to be seen) and for those+/// that thin out with speed (the stroke is fast).+pub fn size_share(brush: &Brush) -> f32 {+ let units = size_units(brush);+ let small = if units < 4.0 { (0.1 - units.min(0.08)) * 9.5 } else { 0.0 };+ share(brush, units, small)+}++/// The size the studio's drawing pad draws at, as [`size_share`] but without the boost for small+/// brushes.+pub fn pad_size_share(brush: &Brush) -> f32 {+ share(brush, size_units(brush), 0.0)+}++/// The brush's most size in the units brush files keep it in.+fn size_units(brush: &Brush) -> f32 {+ brush.biggest() / brush.size_unit()+}++fn share(brush: &Brush, units: f32, small: f32) -> f32 {+ let speed = 0.3 * brush.setting("speed_size").abs();+ let share = speed + small + brush.setting("preview_size") / (units / 2.0).max(1.0);+ if share.is_finite() { share.clamp(0.0, 1.0) } else { 0.0 }+}++/// The diameter the sample stroke is drawn at (canvas pixels).+pub fn diameter(brush: &Brush) -> f32 {+ let most = brush.biggest();+ let least = brush.min_size.min(most);+ (least + (most - least) * size_share(brush)).max(0.5)+}++/// The canvas (premultiplied RGBA8, [`CANVAS`] in size) fitted into a `width` × `height` preview:+/// as big as fits, in the middle, each pixel the average of the canvas pixels it covers.+pub fn fit(canvas: &[u8], width: u32, height: u32) -> Vec<u8> {+ fit_image(canvas, (CANVAS.0 as u32, CANVAS.1 as u32), width, height)+}++/// An image (premultiplied RGBA8, `size` big) fitted into a `width` × `height` preview, as+/// [`fit`] fits the canvas.+pub fn fit_image(canvas: &[u8], size: (u32, u32), width: u32, height: u32) -> Vec<u8> {+ let (sw, sh) = (size.0 as usize, size.1 as usize);+ let (w, h) = (width as usize, height as usize);+ let k = (width as f32 / size.0.max(1) as f32).min(height as f32 / size.1.max(1) as f32);+ // for each preview row or column, the canvas ones under it and how much of it each covers+ let spans = |n: usize, source: usize, fitted: f32| -> Vec<Vec<(usize, f32)>> {+ let start = (n as f32 - fitted) / 2.0;+ (0..n)+ .map(|o| {+ let (a, b) = ((o as f32 - start) / k, (o as f32 + 1.0 - start) / k);+ let (first, last) = (a.max(0.0).floor() as usize, (b.min(source as f32).ceil() as usize).min(source));+ (first..last)+ .map(|i| (i, ((i as f32 + 1.0).min(b) - (i as f32).max(a)).max(0.0) * k))+ .filter(|&(_, weight)| weight > 0.0)+ .collect()+ })+ .collect()+ };+ let (columns, rows) = (spans(w, sw, sw as f32 * k), spans(h, sh, sh as f32 * k));+ let mut out = vec![0u8; w * h * 4];+ for (y, row) in rows.iter().enumerate() {+ for (x, column) in columns.iter().enumerate() {+ let mut sum = [0.0f32; 4];+ for &(sy, wy) in row {+ for &(sx, wx) in column {+ let at = (sy * sw + sx) * 4;+ if let Some(p) = canvas.get(at..at + 4) {+ for (s, &v) in sum.iter_mut().zip(p) {+ *s += f32::from(v) * wx * wy;+ }+ }+ }+ }+ let at = (y * w + x) * 4;+ if let Some(dst) = out.get_mut(at..at + 4) {+ for (d, s) in dst.iter_mut().zip(sum) {+ *d = s.round().clamp(0.0, 255.0) as u8;+ }+ }+ }+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_wave_crosses_the_canvas() {+ let s = samples(&Brush::round_pen());+ assert_eq!(s.len(), SAMPLES);+ let (first, last) = (s.first().unwrap(), s.last().unwrap());+ assert!((first.pos.x - 116.6).abs() < 0.5 && (last.pos.x - 933.9).abs() < 0.5);+ assert!(s.iter().all(|p| p.pos.y > 0.4 * CANVAS.1 && p.pos.y < 0.7 * CANVAS.1));+ // light at the ends, swelling to full in the middle+ assert!(first.pressure < 0.15 && last.pressure < 0.15);+ assert!(s.get(SAMPLES / 4).unwrap().pressure < 0.6);+ assert_eq!(s.get(SAMPLES / 2).unwrap().pressure, 1.0);+ assert!((last.time_ms - 35.0 * STEP_MS).abs() < 1e-9);+ }++ #[test]+ fn small_brushes_show_bigger_and_big_ones_smaller() {+ let mut b = Brush::round_pen();+ b.set_setting("preview_size", 0.3);+ let unit = b.size_unit();+ // under 0.08 of a unit, a small brush is shown up to nearly its full size+ b.max_size = 0.04 * unit;+ assert!((size_share(&b) - (0.3 + 0.06 * 9.5)).abs() < 1e-4);+ b.max_size = 1.0 * unit;+ assert!((size_share(&b) - 0.49).abs() < 1e-4);+ // from 2 units the preview size is shared out over the size+ b.max_size = 8.0 * unit;+ assert!((size_share(&b) - 0.075).abs() < 1e-4);+ }++ #[test]+ fn the_canvas_fits_in_the_middle() {+ let (sw, sh) = (CANVAS.0 as usize, CANVAS.1 as usize);+ // opaque white on the left half+ let canvas: Vec<u8> = (0..sw * sh).flat_map(|i| if i % sw < sw / 2 { [255u8; 4] } else { [0; 4] }).collect();+ // half the size: the halves stay halves+ let half = fit(&canvas, 530, 162);+ assert_eq!(half.len(), 530 * 162 * 4);+ assert_eq!(half.get((80 * 530 + 264) * 4..(80 * 530 + 265) * 4), Some(&[255u8; 4][..]));+ assert_eq!(half.get((80 * 530 + 265) * 4..(80 * 530 + 266) * 4), Some(&[0u8; 4][..]));+ // a taller preview: the canvas across its width, empty above and below+ let tall = fit(&canvas, 106, 100);+ let a = |x: usize, y: usize| tall.get((y * 106 + x) * 4 + 3).copied();+ assert_eq!(a(10, 2), Some(0));+ assert_eq!(a(10, 50), Some(255));+ assert_eq!(a(10, 97), Some(0));+ }+}diff --git a/crates/engine/src/profile.rs b/crates/engine/src/profile.rsnew file mode 100644index 0000000..3d25201--- /dev/null+++ b/crates/engine/src/profile.rs@@ -0,0 +1,182 @@+//! Colour profiles: which RGB space a canvas's numbers are in, and colours moved between spaces.+//!+//! Every profile here encodes with the sRGB tone curve. The sRGB ones share sRGB's primaries (they+//! differ only in how their files describe rendering), so moving between them changes nothing;+//! Display P3 has wider primaries, the same white (D65) and the same curve.++/// A canvas's colour profile.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+pub enum Profile {+ /// sRGB IEC61966-2.1.+ #[default]+ Srgb,+ DisplayP3,+ SrgbV4Appearance,+ SrgbV4Preference,+ SrgbV4PreferenceDisplayClass,+}++/// Linear Display P3 to linear sRGB (both D65).+const P3_TO_SRGB: [[f32; 3]; 3] =+ [[1.224_940_2, -0.224_940_4, 0.0], [-0.042_056_955, 1.042_057, 0.0], [-0.019_637_555, -0.078_636_05, 1.098_273_6]];++/// Linear sRGB to linear Display P3.+const SRGB_TO_P3: [[f32; 3]; 3] =+ [[0.822_462_1, 0.177_538, 0.0], [0.033_194_2, 0.966_805_8, 0.0], [0.017_082_67, 0.072_397_4, 0.910_519_9]];++const IDENTITY: [[f32; 3]; 3] = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];++impl Profile {+ /// The RGB profiles, in the order lists show them.+ pub const ALL: [Profile; 5] = [+ Profile::DisplayP3,+ Profile::Srgb,+ Profile::SrgbV4Appearance,+ Profile::SrgbV4Preference,+ Profile::SrgbV4PreferenceDisplayClass,+ ];++ /// Its name, as lists and files show it.+ pub fn name(self) -> &'static str {+ match self {+ Profile::Srgb => "sRGB IEC61966-2.1",+ Profile::DisplayP3 => "Display P3",+ Profile::SrgbV4Appearance => "sRGB v4 ICC Appearance",+ Profile::SrgbV4Preference => "sRGB v4 ICC Preference",+ Profile::SrgbV4PreferenceDisplayClass => "sRGB v4 ICC Preference Display Class",+ }+ }++ /// The profile named `name`, if it is one.+ pub fn from_name(name: &str) -> Option<Profile> {+ Profile::ALL.into_iter().find(|p| p.name() == name)+ }++ /// Whether it has Display P3's wider primaries (else sRGB's).+ pub fn is_p3(self) -> bool {+ self == Profile::DisplayP3+ }++ /// The matrix taking linear light in this profile to linear light in `to`.+ pub fn matrix_to(self, to: Profile) -> [[f32; 3]; 3] {+ match (self.is_p3(), to.is_p3()) {+ (true, false) => P3_TO_SRGB,+ (false, true) => SRGB_TO_P3,+ _ => IDENTITY,+ }+ }++ /// `rgb` (encoded, 0..1) in this profile as encoded values in `to`, clipped to its gamut.+ pub fn convert(self, rgb: [f32; 3], to: Profile) -> [f32; 3] {+ if self.is_p3() == to.is_p3() {+ return rgb;+ }+ apply(self.matrix_to(to), rgb.map(decode)).map(|c| encode(c.clamp(0.0, 1.0)))+ }++ /// An 8-bit RGB colour (0xRRGGBB) in this profile, in `to`.+ pub fn convert_rgb(self, rgb: u32, to: Profile) -> u32 {+ let c = [(rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF].map(|v| v as f32 / 255.0);+ let [r, g, b] = self.convert(c, to).map(|v| (v * 255.0).round().clamp(0.0, 255.0) as u32);+ (r << 16) | (g << 8) | b+ }++ /// Premultiplied RGBA8 pixels in this profile turned into `to` in place, looking the same+ /// where `to` can show them and clipped where it can't.+ pub fn convert_pixels(self, pixels: &mut [u8], to: Profile) {+ if self.is_p3() == to.is_p3() {+ return;+ }+ let m = self.matrix_to(to);+ let linear: [f32; 256] = std::array::from_fn(|i| decode(i as f32 / 255.0));+ let encoded: Vec<f32> = (0..=ENCODE_STEPS).map(|i| encode(i as f32 / ENCODE_STEPS as f32)).collect();+ for px in pixels.as_chunks_mut::<4>().0 {+ let a = u32::from(px[3]);+ if a == 0 {+ continue;+ }+ let straight = [px[0], px[1], px[2]]+ .map(|c| linear.get(((u32::from(c) * 255 + a / 2) / a).min(255) as usize).copied().unwrap_or(1.0));+ let [r, g, b] = apply(m, straight).map(|v| {+ let e = encoded.get((v.clamp(0.0, 1.0) * ENCODE_STEPS as f32).round() as usize).copied().unwrap_or(1.0);+ (e * a as f32).round().clamp(0.0, 255.0) as u8+ });+ [px[0], px[1], px[2]] = [r, g, b];+ }+ }+}++/// How finely [`Profile::convert_pixels`] steps linear light when encoding it: about a fifth of an+/// 8-bit step near black, where the curve is steepest.+const ENCODE_STEPS: usize = 16384;++/// The matrix `m` times `v`.+pub fn apply(m: [[f32; 3]; 3], v: [f32; 3]) -> [f32; 3] {+ m.map(|row| row[0] * v[0] + row[1] * v[1] + row[2] * v[2])+}++/// The sRGB tone curve undone: an encoded value (0..1) as linear light.+pub fn decode(c: f32) -> f32 {+ if c <= 0.040_45 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }+}++/// Linear light (0..1) encoded with the sRGB tone curve.+pub fn encode(c: f32) -> f32 {+ if c <= 0.003_130_8 { c * 12.92 } else { 1.055 * c.powf(1.0 / 2.4) - 0.055 }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn colours_go_between_the_profiles() {+ // white, black and greys are the same in both+ for g in [0.0, 0.25, 0.5, 1.0] {+ let c = Profile::Srgb.convert([g, g, g], Profile::DisplayP3);+ assert!(c.iter().all(|v| (v - g).abs() < 1e-3), "{c:?}");+ }+ // sRGB's red is inside P3, and comes back+ let red = Profile::Srgb.convert([1.0, 0.0, 0.0], Profile::DisplayP3);+ assert!(+ (red[0] - 0.917).abs() < 0.01 && (red[1] - 0.200).abs() < 0.01 && (red[2] - 0.139).abs() < 0.01,+ "{red:?}"+ );+ let back = Profile::DisplayP3.convert(red, Profile::Srgb);+ assert!((back[0] - 1.0).abs() < 2e-3 && back[1] < 2e-3 && back[2] < 2e-3, "{back:?}");+ // P3's red is outside sRGB: clipped+ let clipped = Profile::DisplayP3.convert([1.0, 0.0, 0.0], Profile::Srgb);+ assert!((clipped[0] - 1.0).abs() < 1e-5 && clipped[1] == 0.0 && clipped[2] == 0.0, "{clipped:?}");+ // between the sRGB ones nothing moves+ assert_eq!(Profile::Srgb.convert([0.3, 0.6, 0.9], Profile::SrgbV4Preference), [0.3, 0.6, 0.9]);+ assert_eq!(Profile::Srgb.convert_rgb(0xFF0000, Profile::DisplayP3), 0xEA3323);+ }++ #[test]+ fn pixels_go_between_the_profiles() {+ // opaque sRGB red, half-covered sRGB red, a grey and nothing, premultiplied+ let mut px = vec![255, 0, 0, 255, 128, 0, 0, 128, 90, 90, 90, 200, 0, 0, 0, 0];+ Profile::Srgb.convert_pixels(&mut px, Profile::DisplayP3);+ assert_eq!(&px[0..4], &[0xEA, 0x33, 0x23, 255]);+ // the half-covered red is the same colour, half as much+ assert!(px[4].abs_diff(0x75) <= 1 && px[5].abs_diff(0x1A) <= 1 && px[6].abs_diff(0x12) <= 1, "{px:?}");+ assert_eq!(px[7], 128);+ assert!(px[8..11].iter().all(|&c| c.abs_diff(90) <= 1), "{px:?}");+ assert_eq!(&px[12..16], &[0, 0, 0, 0]);+ // and back+ Profile::DisplayP3.convert_pixels(&mut px, Profile::Srgb);+ assert!(px[0] >= 254 && px[1] <= 1 && px[2] <= 1, "{px:?}");+ // between the sRGB ones nothing moves+ let mut same = vec![10, 20, 30, 40];+ Profile::Srgb.convert_pixels(&mut same, Profile::SrgbV4Appearance);+ assert_eq!(same, [10, 20, 30, 40]);+ }++ #[test]+ fn names_go_both_ways() {+ for p in Profile::ALL {+ assert_eq!(Profile::from_name(p.name()), Some(p));+ }+ assert_eq!(Profile::from_name("Adobe RGB"), None);+ }+}diff --git a/crates/engine/src/quickshape.rs b/crates/engine/src/quickshape.rsnew file mode 100644index 0000000..7ea6565--- /dev/null+++ b/crates/engine/src/quickshape.rs@@ -0,0 +1,717 @@+//! Shapes recognised in a stroke drawn and held: a line, a polyline or an arc for open strokes;+//! an ellipse or circle, a triangle, a quadrilateral, a rectangle or square for closed ones. Each+//! comes with the nodes it is edited by and the outline the brush redraws it along.++use std::f32::consts::TAU;++use crate::geom::Vec2;++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ShapeKind {+ Line,+ Polyline,+ Arc,+ Ellipse,+ Circle,+ Triangle,+ EquilateralTriangle,+ Quadrilateral,+ Rectangle,+ Square,+}++/// A recognised shape: its kind and the nodes that define and edit it.+///+/// Nodes, by kind: a line's two ends; a polyline's corners; an arc's ends and a point on it; an+/// ellipse's or circle's centre and the four ends of its axes; a polygon's corners.+#[derive(Clone, Debug, PartialEq)]+pub struct Shape {+ pub kind: ShapeKind,+ pub nodes: Vec<Vec2>,+}++/// How straight a stroke must be (its widest gap from the chord, as a share of the chord) to be a+/// line.+const STRAIGHT: f32 = 0.06;+/// A stroke whose ends are this close (a share of its length) is closed.+const CLOSED: f32 = 0.18;+/// Simplifying a stroke into corners keeps points this far off (a share of its size).+const CORNER_TOLERANCE: f32 = 0.08;+/// Points sampled around a curved outline.+const OUTLINE_STEPS: usize = 128;++impl Shape {+ /// The shape's outline, from where the stroke began, as the brush should redraw it.+ pub fn outline(&self) -> Vec<Vec2> {+ match self.kind {+ ShapeKind::Line | ShapeKind::Polyline => self.nodes.clone(),+ ShapeKind::Arc => arc_points(&self.nodes),+ ShapeKind::Ellipse | ShapeKind::Circle => ellipse_points(&self.nodes),+ _ => {+ let mut pts = self.nodes.clone();+ if let Some(&first) = pts.first() {+ pts.push(first);+ }+ pts+ }+ }+ }++ /// The handles shown while editing: the nodes, and for polygons the middle of each side.+ pub fn handles(&self) -> Vec<Vec2> {+ match self.kind {+ ShapeKind::Ellipse | ShapeKind::Circle => self.nodes.iter().skip(1).copied().collect(),+ ShapeKind::Triangle+ | ShapeKind::EquilateralTriangle+ | ShapeKind::Quadrilateral+ | ShapeKind::Rectangle+ | ShapeKind::Square => {+ let n = self.nodes.len();+ let mut out = self.nodes.clone();+ for i in 0..n {+ if let (Some(&a), Some(&b)) = (self.nodes.get(i), self.nodes.get((i + 1) % n)) {+ out.push(a.lerp(b, 0.5));+ }+ }+ out+ }+ _ => self.nodes.clone(),+ }+ }++ /// Moves handle `index` (as [`Shape::handles`] lists them) to `to`, keeping the shape its kind.+ pub fn move_handle(&mut self, index: usize, to: Vec2) {+ if !to.is_finite() {+ return;+ }+ match self.kind {+ ShapeKind::Ellipse | ShapeKind::Circle => self.move_axis(index, to),+ ShapeKind::Rectangle | ShapeKind::Square => self.move_rect_handle(index, to),+ ShapeKind::Triangle | ShapeKind::EquilateralTriangle | ShapeKind::Quadrilateral => {+ let n = self.nodes.len();+ if index < n {+ if let Some(p) = self.nodes.get_mut(index) {+ *p = to;+ }+ } else {+ // a side's middle moves the whole side+ let side = index - n;+ let (Some(&a), Some(&b)) = (self.nodes.get(side), self.nodes.get((side + 1) % n)) else { return };+ let by = to - a.lerp(b, 0.5);+ for k in [side, (side + 1) % n] {+ if let Some(p) = self.nodes.get_mut(k) {+ *p = *p + by;+ }+ }+ }+ if self.kind == ShapeKind::EquilateralTriangle {+ self.kind = ShapeKind::Triangle;+ }+ }+ _ => {+ if let Some(p) = self.nodes.get_mut(index) {+ *p = to;+ }+ }+ }+ }++ /// The same shape as another kind it can be shown as (an ellipse as a circle, a quadrilateral+ /// as a rectangle, ...); kinds it cannot become come back unchanged.+ pub fn as_kind(&self, kind: ShapeKind, stroke: &[Vec2]) -> Shape {+ if kind == self.kind {+ return self.clone();+ }+ match kind {+ ShapeKind::Circle => {+ let (c, a, b) = self.ellipse_frame();+ let r = (a.length() + b.length()) * 0.5;+ axes_shape(ShapeKind::Circle, c, Vec2::new(r, 0.0), Vec2::new(0.0, r))+ }+ ShapeKind::Ellipse => fit_ellipse(stroke),+ ShapeKind::Square | ShapeKind::Rectangle => {+ let rect = fit_rect(stroke);+ if kind == ShapeKind::Square { squared(&rect) } else { rect }+ }+ ShapeKind::Quadrilateral => polygon(stroke, 4).unwrap_or_else(|| fit_rect(stroke)),+ ShapeKind::Triangle => polygon(stroke, 3).unwrap_or_else(|| self.clone()),+ ShapeKind::EquilateralTriangle => equilateral(&polygon(stroke, 3).unwrap_or_else(|| self.clone())),+ ShapeKind::Line => line_of(stroke),+ _ => self.clone(),+ }+ }++ /// An ellipse's centre and its two half-axes.+ fn ellipse_frame(&self) -> (Vec2, Vec2, Vec2) {+ let get = |i: usize| self.nodes.get(i).copied().unwrap_or(Vec2::ZERO);+ let c = get(0);+ (c, get(1) - c, get(2) - c)+ }++ fn move_axis(&mut self, index: usize, to: Vec2) {+ let (c, a, b) = self.ellipse_frame();+ let along = to - c;+ if self.kind == ShapeKind::Circle {+ let r = along.length();+ *self = axes_shape(ShapeKind::Circle, c, Vec2::new(r, 0.0), Vec2::new(0.0, r));+ return;+ }+ // handles 0 and 2 are the first axis's ends, 1 and 3 the second's: the dragged one turns+ // the ellipse and sets its length, the other keeps its length at a right angle+ let (first, second) = if index.is_multiple_of(2) {+ let len = along.length().max(1.0);+ let sign = if index == 2 { -1.0 } else { 1.0 };+ let u = along * (sign / len);+ (u * len, Vec2::new(-u.y, u.x) * b.length())+ } else {+ let len = along.length().max(1.0);+ let sign = if index == 3 { -1.0 } else { 1.0 };+ let v = along * (sign / len);+ (Vec2::new(v.y, -v.x) * a.length(), v * len)+ };+ *self = axes_shape(ShapeKind::Ellipse, c, first, second);+ }++ fn move_rect_handle(&mut self, index: usize, to: Vec2) {+ let get = |i: usize| self.nodes.get(i).copied().unwrap_or(Vec2::ZERO);+ let (p0, p1, p3) = (get(0), get(1), get(3));+ let u = (p1 - p0).normalized_or(Vec2::new(1.0, 0.0));+ let v = (p3 - p0).normalized_or(Vec2::new(0.0, 1.0));+ // the rectangle in its own frame: corner 0 at the origin, sides along u and v+ let (mut x0, mut y0, mut x1, mut y1) = (0.0f32, 0.0f32, (p1 - p0).dot(u), (p3 - p0).dot(v));+ let local = Vec2::new((to - p0).dot(u), (to - p0).dot(v));+ match index {+ 0 => (x0, y0) = (local.x, local.y),+ 1 => (x1, y0) = (local.x, local.y),+ 2 => (x1, y1) = (local.x, local.y),+ 3 => (x0, y1) = (local.x, local.y),+ 4 => y0 = local.y,+ 5 => x1 = local.x,+ 6 => y1 = local.y,+ _ => x0 = local.x,+ }+ if self.kind == ShapeKind::Square {+ // a square keeps its sides equal: the larger move wins+ let side = (x1 - x0).abs().max((y1 - y0).abs());+ if index == 0 || index == 3 || index == 7 {+ x0 = x1 - side * (x1 - x0).signum();+ } else {+ x1 = x0 + side * (x1 - x0).signum();+ }+ if index == 0 || index == 1 || index == 4 {+ y0 = y1 - side * (y1 - y0).signum();+ } else {+ y1 = y0 + side * (y1 - y0).signum();+ }+ }+ let at = |x: f32, y: f32| p0 + u * x + v * y;+ self.nodes = vec![at(x0, y0), at(x1, y0), at(x1, y1), at(x0, y1)];+ }+}++/// The shapes a held stroke (canvas points, in drawing order) could be, best first; empty if it is+/// too short to be anything.+pub fn recognise(stroke: &[Vec2]) -> Vec<Shape> {+ let pts: Vec<Vec2> = stroke.iter().copied().filter(|p| p.is_finite()).collect();+ let length = path_length(&pts);+ let (Some(&first), Some(&last)) = (pts.first(), pts.last()) else { return Vec::new() };+ if pts.len() < 2 || length < 4.0 {+ return Vec::new();+ }+ let chord = first.distance(last);+ let widest = pts.iter().map(|&p| distance_to_segment(p, first, last)).fold(0.0f32, f32::max);+ if widest <= STRAIGHT * chord.max(1.0) {+ return vec![line_of(&pts)];+ }+ if chord > CLOSED * length {+ // open: corners make a polyline; an even bend an arc+ let corners = simplify(&pts, CORNER_TOLERANCE * size(&pts));+ let arc = fit_arc(&pts);+ let arc_error = arc.as_ref().map_or(f32::MAX, |a| arc_error(a, &pts));+ if corners.len() >= 3 && (sharp_corner(&pts, &corners) || arc_error > 0.04) {+ return vec![Shape { kind: ShapeKind::Polyline, nodes: corners }, line_of(&pts)];+ }+ return match arc {+ Some(a) => vec![a, line_of(&pts)],+ None => vec![Shape { kind: ShapeKind::Polyline, nodes: corners }],+ };+ }+ // closed: an ellipse against the polygon the corners make+ let ellipse = fit_ellipse(&pts);+ let ellipse_error = outline_error(&ellipse, &pts);+ let corners = closed_corners(&pts);+ let polygon_shape = match corners.len() {+ 3 => Some(Shape { kind: ShapeKind::Triangle, nodes: corners }),+ 4 => Some(Shape { kind: ShapeKind::Quadrilateral, nodes: corners }),+ _ => None,+ };+ let (c, a, b) = ellipse.ellipse_frame();+ let round = a.length().min(b.length()) / a.length().max(b.length()).max(1e-3);+ let mut out = Vec::new();+ match polygon_shape {+ Some(p) if outline_error(&p, &pts) < ellipse_error * 0.8 => {+ if p.kind == ShapeKind::Triangle {+ out.push(p.clone());+ out.push(equilateral(&p));+ } else {+ out.push(p);+ out.push(fit_rect(&pts));+ out.push(ellipse);+ }+ }+ Some(p) => {+ out.push(ellipse);+ if p.kind == ShapeKind::Quadrilateral {+ out.push(p);+ out.push(fit_rect(&pts));+ } else {+ out.push(p);+ }+ }+ None => {+ out.push(ellipse);+ if round > 0.75 {+ let r = (a.length() + b.length()) * 0.5;+ out.push(axes_shape(ShapeKind::Circle, c, Vec2::new(r, 0.0), Vec2::new(0.0, r)));+ }+ }+ }+ out+}++fn path_length(pts: &[Vec2]) -> f32 {+ pts.windows(2)+ .map(|w| match w {+ [a, b] => a.distance(*b),+ _ => 0.0,+ })+ .sum()+}++fn size(pts: &[Vec2]) -> f32 {+ let (lo, hi) = bounds(pts);+ (hi - lo).length().max(1.0)+}++fn bounds(pts: &[Vec2]) -> (Vec2, Vec2) {+ pts.iter().fold((Vec2::new(f32::MAX, f32::MAX), Vec2::new(f32::MIN, f32::MIN)), |(lo, hi), p| {+ (Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y)))+ })+}++fn distance_to_segment(p: Vec2, a: Vec2, b: Vec2) -> f32 {+ let ab = b - a;+ let len2 = ab.dot(ab);+ if len2 <= 1e-9 {+ return p.distance(a);+ }+ let t = ((p - a).dot(ab) / len2).clamp(0.0, 1.0);+ p.distance(a + ab * t)+}++fn line_of(pts: &[Vec2]) -> Shape {+ let first = pts.first().copied().unwrap_or(Vec2::ZERO);+ let last = pts.last().copied().unwrap_or(first);+ Shape { kind: ShapeKind::Line, nodes: vec![first, last] }+}++/// The corners that keep the path within `tolerance` (Ramer–Douglas–Peucker), ends included.+fn simplify(pts: &[Vec2], tolerance: f32) -> Vec<Vec2> {+ fn keep(pts: &[Vec2], tolerance: f32, out: &mut Vec<Vec2>) {+ let (Some(&a), Some(&b)) = (pts.first(), pts.last()) else { return };+ let far = pts+ .iter()+ .enumerate()+ .map(|(i, &p)| (i, distance_to_segment(p, a, b)))+ .fold((0, 0.0f32), |best, x| if x.1 > best.1 { x } else { best });+ if far.1 > tolerance && far.0 > 0 && far.0 + 1 < pts.len() {+ keep(pts.get(..=far.0).unwrap_or(&[]), tolerance, out);+ out.pop();+ keep(pts.get(far.0..).unwrap_or(&[]), tolerance, out);+ } else {+ out.push(a);+ out.push(b);+ }+ }+ let mut out = Vec::new();+ keep(pts, tolerance, &mut out);+ out.dedup();+ out+}++/// A closed stroke's corners: simplified from the point farthest from its start, so the start+/// is not taken for a corner when it is not one.+fn closed_corners(pts: &[Vec2]) -> Vec<Vec2> {+ let tolerance = CORNER_TOLERANCE * size(pts);+ let Some(&start) = pts.first() else { return Vec::new() };+ let far = pts.iter().enumerate().fold((0, 0.0f32), |best, (i, p)| {+ let d = p.distance(start);+ if d > best.1 { (i, d) } else { best }+ });+ // walk once round from the far point, back to it+ let mut ring: Vec<Vec2> = pts.get(far.0..).unwrap_or(&[]).to_vec();+ ring.extend(pts.get(..=far.0).unwrap_or(&[]));+ let mut corners = simplify(&ring, tolerance);+ // the far point opens and closes the ring; drop it at the end, and anything nearly straight+ corners.pop();+ let n = corners.len();+ let kept: Vec<Vec2> = (0..n)+ .filter_map(|i| {+ let prev = corners.get((i + n - 1) % n)?;+ let p = corners.get(i)?;+ let next = corners.get((i + 1) % n)?;+ let turn = (*p - *prev).normalized_or(Vec2::ZERO).dot((*next - *p).normalized_or(Vec2::ZERO));+ (turn < 0.9).then_some(*p)+ })+ .collect();+ // in drawing order from the corner nearest the start+ let first = kept.iter().enumerate().fold((0, f32::MAX), |best, (i, p)| {+ let d = p.distance(start);+ if d < best.1 { (i, d) } else { best }+ });+ let mut ordered = kept.get(first.0..).unwrap_or(&[]).to_vec();+ ordered.extend(kept.get(..first.0).unwrap_or(&[]));+ ordered+}++/// The polygon with `n` corners the stroke makes, if it makes one.+fn polygon(pts: &[Vec2], n: usize) -> Option<Shape> {+ let corners = closed_corners(pts);+ let kind = if n == 3 { ShapeKind::Triangle } else { ShapeKind::Quadrilateral };+ (corners.len() == n).then_some(Shape { kind, nodes: corners })+}++/// The ellipse with the stroke's centre and spread: for points evenly round an ellipse, the+/// spread along each axis is half the axis squared.+fn fit_ellipse(pts: &[Vec2]) -> Shape {+ let (c, weight) = pts.windows(2).fold((Vec2::ZERO, 0.0f32), |(sum, w), pair| match pair {+ [a, b] => {+ let l = a.distance(*b);+ (sum + a.lerp(*b, 0.5) * l, w + l)+ }+ _ => (sum, w),+ });+ let c = if weight > 0.0 { c * (1.0 / weight) } else { pts.first().copied().unwrap_or(Vec2::ZERO) };+ let (mut xx, mut xy, mut yy) = (0.0f32, 0.0f32, 0.0f32);+ for pair in pts.windows(2) {+ if let [a, b] = pair {+ let l = a.distance(*b);+ let d = a.lerp(*b, 0.5) - c;+ xx += d.x * d.x * l;+ xy += d.x * d.y * l;+ yy += d.y * d.y * l;+ }+ }+ let w = weight.max(1e-6);+ let (xx, xy, yy) = (xx / w, xy / w, yy / w);+ // the spread's principal axes+ let mean = (xx + yy) * 0.5;+ let gap = (((xx - yy) * 0.5).powi(2) + xy * xy).sqrt();+ let (l1, l2) = (mean + gap, (mean - gap).max(0.0));+ let angle = 0.5 * (2.0 * xy).atan2(xx - yy);+ let u = Vec2::new(angle.cos(), angle.sin());+ let v = Vec2::new(-u.y, u.x);+ // the first axis points to where the stroke began, so the outline starts there+ let start = pts.first().copied().unwrap_or(c) - c;+ let (a, b) = ((2.0 * l1).sqrt(), (2.0 * l2).sqrt());+ let (ua, vb) = if start.dot(u).abs() / a.max(1e-3) >= start.dot(v).abs() / b.max(1e-3) {+ (u * a * start.dot(u).signum(), v * b)+ } else {+ (v * b * start.dot(v).signum(), u * a * -1.0)+ };+ axes_shape(ShapeKind::Ellipse, c, ua, vb)+}++fn axes_shape(kind: ShapeKind, c: Vec2, a: Vec2, b: Vec2) -> Shape {+ Shape { kind, nodes: vec![c, c + a, c + b, c - a, c - b] }+}++fn ellipse_points(nodes: &[Vec2]) -> Vec<Vec2> {+ let get = |i: usize| nodes.get(i).copied().unwrap_or(Vec2::ZERO);+ let (c, a, b) = (get(0), get(1) - get(0), get(2) - get(0));+ (0..=OUTLINE_STEPS)+ .map(|i| {+ let t = i as f32 / OUTLINE_STEPS as f32 * TAU;+ c + a * t.cos() + b * t.sin()+ })+ .collect()+}++/// The rectangle along the stroke's corners (or its spread), oriented with its sides.+fn fit_rect(pts: &[Vec2]) -> Shape {+ let corners = closed_corners(pts);+ // the sides' mean direction (folded into a quarter turn) sets the rectangle's turn+ let angle = if corners.len() >= 3 {+ let n = corners.len();+ let (s, c) = (0..n).fold((0.0f32, 0.0f32), |(s, c), i| {+ let (Some(a), Some(b)) = (corners.get(i), corners.get((i + 1) % n)) else { return (s, c) };+ let d = *b - *a;+ let t = d.y.atan2(d.x) * 4.0;+ let w = d.length();+ (s + t.sin() * w, c + t.cos() * w)+ });+ s.atan2(c) / 4.0+ } else {+ 0.0+ };+ let u = Vec2::new(angle.cos(), angle.sin());+ let v = Vec2::new(-u.y, u.x);+ let source = if corners.len() >= 3 { corners } else { pts.to_vec() };+ let (mut x0, mut y0, mut x1, mut y1) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);+ for p in &source {+ let (x, y) = (p.dot(u), p.dot(v));+ (x0, x1, y0, y1) = (x0.min(x), x1.max(x), y0.min(y), y1.max(y));+ }+ let at = |x: f32, y: f32| u * x + v * y;+ let nodes = vec![at(x0, y0), at(x1, y0), at(x1, y1), at(x0, y1)];+ let start = pts.first().copied().unwrap_or(Vec2::ZERO);+ Shape { kind: ShapeKind::Rectangle, nodes: from_nearest(nodes, start) }+}++fn squared(rect: &Shape) -> Shape {+ let get = |i: usize| rect.nodes.get(i).copied().unwrap_or(Vec2::ZERO);+ let (p0, p1, p3) = (get(0), get(1), get(3));+ let side = (p0.distance(p1) + p0.distance(p3)) * 0.5;+ let c = p0.lerp(get(2), 0.5);+ let u = (p1 - p0).normalized_or(Vec2::new(1.0, 0.0)) * (side * 0.5);+ let v = (p3 - p0).normalized_or(Vec2::new(0.0, 1.0)) * (side * 0.5);+ Shape { kind: ShapeKind::Square, nodes: vec![c - u - v, c + u - v, c + u + v, c - u + v] }+}++fn equilateral(t: &Shape) -> Shape {+ let c = t.nodes.iter().fold(Vec2::ZERO, |a, &p| a + p) * (1.0 / t.nodes.len().max(1) as f32);+ let first = t.nodes.first().copied().unwrap_or(c) - c;+ let r = t.nodes.iter().map(|p| p.distance(c)).sum::<f32>() / t.nodes.len().max(1) as f32;+ let a0 = first.y.atan2(first.x);+ // the same turning sense as the stroke+ let turn = match (t.nodes.get(1), t.nodes.get(2)) {+ (Some(&b), Some(&d)) => {+ let a = t.nodes.first().copied().unwrap_or(c);+ if (b - a).cross(d - a) >= 0.0 { 1.0 } else { -1.0 }+ }+ _ => 1.0,+ };+ let nodes = (0..3).map(|k| {+ let a = a0 + turn * k as f32 * TAU / 3.0;+ c + Vec2::new(a.cos(), a.sin()) * r+ });+ Shape { kind: ShapeKind::EquilateralTriangle, nodes: nodes.collect() }+}++fn from_nearest(nodes: Vec<Vec2>, start: Vec2) -> Vec<Vec2> {+ let first = nodes.iter().enumerate().fold((0, f32::MAX), |best, (i, p)| {+ let d = p.distance(start);+ if d < best.1 { (i, d) } else { best }+ });+ let mut out = nodes.get(first.0..).unwrap_or(&[]).to_vec();+ out.extend(nodes.get(..first.0).unwrap_or(&[]));+ out+}++/// The arc through the stroke's ends and its middle point.+fn fit_arc(pts: &[Vec2]) -> Option<Shape> {+ let a = *pts.first()?;+ let b = *pts.get(pts.len() / 2)?;+ let c = *pts.last()?;+ circle_through(a, b, c)?;+ Some(Shape { kind: ShapeKind::Arc, nodes: vec![a, b, c] })+}++fn circle_through(a: Vec2, b: Vec2, c: Vec2) -> Option<(Vec2, f32)> {+ let d = 2.0 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y));+ if d.abs() < 1e-6 {+ return None;+ }+ let (a2, b2, c2) = (a.dot(a), b.dot(b), c.dot(c));+ let centre = Vec2::new(+ (a2 * (b.y - c.y) + b2 * (c.y - a.y) + c2 * (a.y - b.y)) / d,+ (a2 * (c.x - b.x) + b2 * (a.x - c.x) + c2 * (b.x - a.x)) / d,+ );+ Some((centre, centre.distance(a)))+}++fn arc_points(nodes: &[Vec2]) -> Vec<Vec2> {+ let get = |i: usize| nodes.get(i).copied().unwrap_or(Vec2::ZERO);+ let (a, b, c) = (get(0), get(1), get(2));+ let Some((centre, r)) = circle_through(a, b, c) else { return vec![a, c] };+ let angle = |p: Vec2| (p - centre).y.atan2((p - centre).x);+ let (ta, tb, tc) = (angle(a), angle(b), angle(c));+ // the sweep from a to c that passes b+ let norm = |t: f32| t.rem_euclid(TAU);+ let ccw = norm(tb - ta) <= norm(tc - ta);+ let sweep = if ccw { norm(tc - ta) } else { -norm(ta - tc) };+ (0..=OUTLINE_STEPS)+ .map(|i| {+ let t = ta + sweep * i as f32 / OUTLINE_STEPS as f32;+ centre + Vec2::new(t.cos(), t.sin()) * r+ })+ .collect()+}++/// How far the stroke strays from the arc, on average, as a share of the stroke's size.+fn arc_error(arc: &Shape, pts: &[Vec2]) -> f32 {+ let get = |i: usize| arc.nodes.get(i).copied().unwrap_or(Vec2::ZERO);+ let Some((centre, r)) = circle_through(get(0), get(1), get(2)) else { return f32::MAX };+ pts.iter().map(|p| (p.distance(centre) - r).abs()).sum::<f32>() / pts.len().max(1) as f32 / size(pts)+}++/// Whether the stroke turns sharply at any of the corners it simplifies to: its direction just+/// before a corner and just after differ by more than a corner's worth.+fn sharp_corner(pts: &[Vec2], corners: &[Vec2]) -> bool {+ let reach = path_length(pts) * 0.05;+ corners.iter().skip(1).take(corners.len().saturating_sub(2)).any(|&c| {+ let Some(at) = pts.iter().position(|&p| p == c) else { return false };+ let walk = |forward: bool| {+ let mut gone = 0.0;+ let mut i = at;+ loop {+ let next = if forward { i + 1 } else { i.wrapping_sub(1) };+ let (Some(&a), Some(&b)) = (pts.get(i), pts.get(next)) else { return pts.get(i).copied() };+ gone += a.distance(b);+ i = next;+ if gone >= reach {+ return Some(b);+ }+ }+ };+ let (Some(before), Some(after)) = (walk(false), walk(true)) else { return false };+ let turn = (c - before).normalized_or(Vec2::ZERO).dot((after - c).normalized_or(Vec2::ZERO));+ // more than about forty degrees+ turn < 0.77+ })+}++/// How far the stroke strays from a shape's outline, on average, as a share of the stroke's size.+fn outline_error(shape: &Shape, pts: &[Vec2]) -> f32 {+ let outline = shape.outline();+ let near = |p: Vec2| {+ outline+ .windows(2)+ .map(|w| match w {+ [a, b] => distance_to_segment(p, *a, *b),+ _ => f32::MAX,+ })+ .fold(f32::MAX, f32::min)+ };+ pts.iter().map(|&p| near(p)).sum::<f32>() / pts.len().max(1) as f32 / size(pts)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn wobbly_circle(r: f32, squash: f32, n: usize) -> Vec<Vec2> {+ (0..=n)+ .map(|i| {+ let t = i as f32 / n as f32 * TAU;+ Vec2::new(200.0 + r * t.cos() + 3.0 * (5.0 * t).sin(), 200.0 + r * squash * t.sin())+ })+ .collect()+ }++ fn polygon_path(corners: &[Vec2], per_side: usize) -> Vec<Vec2> {+ let mut out = Vec::new();+ for i in 0..corners.len() {+ let (a, b) = (corners[i], corners[(i + 1) % corners.len()]);+ for k in 0..per_side {+ out.push(a.lerp(b, k as f32 / per_side as f32) + Vec2::new(0.0, if k % 2 == 0 { 1.0 } else { -1.0 }));+ }+ }+ out.push(corners[0]);+ out+ }++ #[test]+ fn a_nearly_straight_stroke_is_a_line() {+ let pts: Vec<Vec2> =+ (0..40).map(|i| Vec2::new(i as f32 * 8.0, 100.0 + if i % 2 == 0 { 2.0 } else { -2.0 })).collect();+ let found = recognise(&pts);+ assert_eq!(found[0].kind, ShapeKind::Line);+ assert_eq!(found[0].nodes, vec![pts[0], pts[39]]);+ }++ #[test]+ fn closed_round_strokes_are_ellipses_and_circles() {+ let found = recognise(&wobbly_circle(100.0, 0.6, 80));+ assert_eq!(found[0].kind, ShapeKind::Ellipse);+ let (c, a, b) = found[0].ellipse_frame();+ assert!(c.distance(Vec2::new(200.0, 200.0)) < 5.0, "{c:?}");+ assert!((a.length().max(b.length()) - 100.0).abs() < 8.0 && (a.length().min(b.length()) - 60.0).abs() < 8.0);+ let round = recognise(&wobbly_circle(100.0, 1.0, 80));+ assert!(round.iter().any(|s| s.kind == ShapeKind::Circle));+ // the outline starts where the stroke did+ assert!(found[0].outline()[0].distance(Vec2::new(303.0, 200.0)) < 12.0);+ }++ #[test]+ fn closed_cornered_strokes_are_polygons() {+ let rect = [Vec2::new(100.0, 100.0), Vec2::new(400.0, 105.0), Vec2::new(395.0, 300.0), Vec2::new(105.0, 295.0)];+ let found = recognise(&polygon_path(&rect, 20));+ assert_eq!(found[0].kind, ShapeKind::Quadrilateral, "{found:?}");+ assert!(found.iter().any(|s| s.kind == ShapeKind::Rectangle));+ let tri = [Vec2::new(200.0, 50.0), Vec2::new(350.0, 300.0), Vec2::new(50.0, 300.0)];+ let found = recognise(&polygon_path(&tri, 25));+ assert_eq!(found[0].kind, ShapeKind::Triangle, "{found:?}");+ assert_eq!(found[1].kind, ShapeKind::EquilateralTriangle);+ }++ #[test]+ fn open_strokes_are_arcs_or_polylines() {+ let arc: Vec<Vec2> = (0..=40)+ .map(|i| {+ let t = i as f32 / 40.0 * 2.0;+ Vec2::new(200.0 + 150.0 * t.cos(), 200.0 + 150.0 * t.sin())+ })+ .collect();+ assert_eq!(recognise(&arc)[0].kind, ShapeKind::Arc);+ let zig = [Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0), Vec2::new(100.0, 100.0), Vec2::new(200.0, 100.0)];+ let mut path = Vec::new();+ for w in zig.windows(2) {+ for k in 0..15 {+ path.push(w[0].lerp(w[1], k as f32 / 15.0));+ }+ }+ path.push(zig[3]);+ let found = recognise(&path);+ assert_eq!(found[0].kind, ShapeKind::Polyline);+ assert_eq!(found[0].nodes.len(), 4);+ }++ #[test]+ fn handles_edit_their_shapes() {+ let mut rect = Shape {+ kind: ShapeKind::Rectangle,+ nodes: vec![Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0), Vec2::new(100.0, 50.0), Vec2::new(0.0, 50.0)],+ };+ assert_eq!(rect.handles().len(), 8);+ rect.move_handle(2, Vec2::new(120.0, 80.0));+ assert_eq!(rect.nodes[2], Vec2::new(120.0, 80.0));+ assert_eq!(rect.nodes[0], Vec2::new(0.0, 0.0));+ rect.move_handle(4, Vec2::new(60.0, -10.0));+ assert_eq!(rect.nodes[0].y, -10.0);+ let mut circle = axes_shape(ShapeKind::Circle, Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(0.0, 10.0));+ circle.move_handle(1, Vec2::new(0.0, 30.0));+ assert!((circle.nodes[1].distance(circle.nodes[0]) - 30.0).abs() < 1e-3);+ let mut ellipse = axes_shape(ShapeKind::Ellipse, Vec2::ZERO, Vec2::new(40.0, 0.0), Vec2::new(0.0, 20.0));+ ellipse.move_handle(0, Vec2::new(0.0, 50.0));+ let (_, a, b) = ellipse.ellipse_frame();+ assert!((a.length() - 50.0).abs() < 1e-3 && (b.length() - 20.0).abs() < 1e-3 && a.dot(b).abs() < 1e-3);+ let mut line = Shape { kind: ShapeKind::Line, nodes: vec![Vec2::ZERO, Vec2::new(10.0, 0.0)] };+ line.move_handle(1, Vec2::new(5.0, 5.0));+ assert_eq!(line.nodes[1], Vec2::new(5.0, 5.0));+ line.move_handle(9, Vec2::new(5.0, 5.0));+ line.move_handle(0, Vec2::new(f32::NAN, 0.0));+ assert_eq!(line.nodes[0], Vec2::ZERO);+ }++ #[test]+ fn shapes_change_kind() {+ let pts = wobbly_circle(100.0, 0.6, 80);+ let e = recognise(&pts).remove(0);+ let c = e.as_kind(ShapeKind::Circle, &pts);+ assert_eq!(c.kind, ShapeKind::Circle);+ let s = e.as_kind(ShapeKind::Square, &pts);+ assert!((s.nodes[0].distance(s.nodes[1]) - s.nodes[0].distance(s.nodes[3])).abs() < 1e-3);+ assert!(recognise(&[Vec2::ZERO]).is_empty());+ }+}diff --git a/crates/engine/src/selection.rs b/crates/engine/src/selection.rsnew file mode 100644index 0000000..d73471e--- /dev/null+++ b/crates/engine/src/selection.rs@@ -0,0 +1,436 @@+//! Selections: how much of each canvas pixel is selected (0 none, 255 all), made from shapes or by+//! colour, and combined, inverted and feathered.++use crate::geom::Vec2;++/// A selection over a `width` × `height` canvas, one byte per pixel, rows top to bottom.+#[derive(Clone, Debug, PartialEq)]+pub struct Mask {+ pub width: u32,+ pub height: u32,+ pub data: Vec<u8>,+}++/// How a new shape joins the selection there is.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Combine {+ Add,+ Remove,+}++/// Rows of sub-samples per pixel when filling a polygon.+const POLYGON_ROWS: usize = 4;++impl Mask {+ /// Nothing selected.+ pub fn empty(width: u32, height: u32) -> Mask {+ Mask { width, height, data: vec![0; width as usize * height as usize] }+ }++ pub fn is_empty(&self) -> bool {+ self.data.iter().all(|&v| v == 0)+ }++ /// The rectangle between corners `a` and `b` (canvas pixels), with partly covered edge pixels.+ pub fn rect(width: u32, height: u32, a: Vec2, b: Vec2) -> Mask {+ let (x0, x1) = (a.x.min(b.x), a.x.max(b.x));+ let (y0, y1) = (a.y.min(b.y), a.y.max(b.y));+ let mut m = Mask::empty(width, height);+ let w = width as usize;+ let cover = |lo: f32, hi: f32, p: usize| (hi.min(p as f32 + 1.0) - lo.max(p as f32)).clamp(0.0, 1.0);+ let cols: Vec<f32> = (0..w).map(|x| cover(x0, x1, x)).collect();+ for (y, row) in m.data.chunks_exact_mut(w.max(1)).enumerate() {+ let cy = cover(y0, y1, y);+ if cy <= 0.0 {+ continue;+ }+ for (v, cx) in row.iter_mut().zip(&cols) {+ *v = to_byte(cx * cy);+ }+ }+ m+ }++ /// The ellipse in the box between corners `a` and `b`, with soft edge pixels.+ pub fn ellipse(width: u32, height: u32, a: Vec2, b: Vec2) -> Mask {+ let c = a.lerp(b, 0.5);+ let (rx, ry) = (((b.x - a.x) / 2.0).abs(), ((b.y - a.y) / 2.0).abs());+ let mut m = Mask::empty(width, height);+ if rx < 1e-3 || ry < 1e-3 {+ return m;+ }+ let w = width as usize;+ let (y_lo, y_hi) =+ ((c.y - ry - 1.0).max(0.0) as usize, ((c.y + ry + 1.0).max(0.0) as usize).min(height as usize));+ let (x_lo, x_hi) = ((c.x - rx - 1.0).max(0.0) as usize, ((c.x + rx + 1.0).max(0.0) as usize).min(w));+ for y in y_lo..y_hi {+ let Some(row) = m.data.get_mut(y * w..(y + 1) * w) else { continue };+ for x in x_lo..x_hi {+ let p = Vec2::new((x as f32 + 0.5 - c.x) / rx, (y as f32 + 0.5 - c.y) / ry);+ let len = p.length();+ // the distance from the edge in pixels: the implicit function over its gradient+ let gradient = Vec2::new(p.x / rx, p.y / ry).length().max(1e-6);+ let distance = (len - 1.0) * len / gradient;+ if let Some(v) = row.get_mut(x) {+ *v = to_byte(0.5 - distance);+ }+ }+ }+ m+ }++ /// The polygon through `points` (canvas pixels, closed back to the first), filled by the+ /// non-zero rule, with partly covered edge pixels.+ pub fn polygon(width: u32, height: u32, points: &[Vec2]) -> Mask {+ let mut m = Mask::empty(width, height);+ let pts: Vec<Vec2> = points.iter().copied().filter(|p| p.is_finite()).collect();+ if pts.len() < 3 {+ return m;+ }+ let w = width as usize;+ let edges: Vec<(Vec2, Vec2)> = pts.iter().zip(pts.iter().cycle().skip(1)).map(|(a, b)| (*a, *b)).collect();+ let (lo, hi) = pts.iter().fold((f32::MAX, f32::MIN), |(lo, hi), p| (lo.min(p.y), hi.max(p.y)));+ let (y_lo, y_hi) = (lo.max(0.0) as usize, (hi.max(0.0).ceil() as usize).min(height as usize));+ let mut coverage = vec![0.0f32; w + 1];+ let mut crossings: Vec<(f32, i32)> = Vec::new();+ for y in y_lo..y_hi {+ coverage.iter_mut().for_each(|c| *c = 0.0);+ for sub in 0..POLYGON_ROWS {+ let sy = y as f32 + (sub as f32 + 0.5) / POLYGON_ROWS as f32;+ crossings.clear();+ for &(a, b) in &edges {+ if (a.y <= sy) != (b.y <= sy) {+ let x = a.x + (sy - a.y) / (b.y - a.y) * (b.x - a.x);+ crossings.push((x, if b.y > a.y { 1 } else { -1 }));+ }+ }+ crossings.sort_by(|p, q| p.0.total_cmp(&q.0));+ let mut winding = 0;+ for pair in crossings.windows(2) {+ let [(x0, d), (x1, _)] = pair else { continue };+ winding += d;+ if winding != 0 {+ add_span(&mut coverage, *x0, *x1, 1.0 / POLYGON_ROWS as f32);+ }+ }+ }+ if let Some(row) = m.data.get_mut(y * w..(y + 1) * w) {+ for (v, c) in row.iter_mut().zip(&coverage) {+ *v = to_byte(*c);+ }+ }+ }+ m+ }++ /// Joins `other` to this selection.+ pub fn combine(&mut self, other: &Mask, how: Combine) {+ for (a, &b) in self.data.iter_mut().zip(&other.data) {+ *a = match how {+ Combine::Add => (*a).max(b),+ Combine::Remove => (*a).min(255 - b),+ };+ }+ }++ pub fn invert(&mut self) {+ self.data.iter_mut().for_each(|v| *v = 255 - *v);+ }++ /// Softens the edges: three box blurs `radius` pixels wide each way (close to a Gaussian).+ pub fn feather(&mut self, radius: f32) {+ let r = radius.max(0.0).round() as usize;+ if r == 0 {+ return;+ }+ let (w, h) = (self.width as usize, self.height as usize);+ let mut values: Vec<f32> = self.data.iter().map(|&v| f32::from(v)).collect();+ let mut line = Vec::new();+ for _ in 0..3 {+ for y in 0..h {+ blur_line(&mut values, y * w, 1, w, r, &mut line);+ }+ for x in 0..w {+ blur_line(&mut values, x, w, h, r, &mut line);+ }+ }+ for (v, f) in self.data.iter_mut().zip(&values) {+ *v = f.round().clamp(0.0, 255.0) as u8;+ }+ }++ /// The pixels joined to `seed` whose colour is within `threshold` (0..1) of the seed's, in+ /// premultiplied RGBA8 `pixels` the mask's size: an automatic selection.+ pub fn by_colour(width: u32, height: u32, pixels: &[u8], seed: (u32, u32), threshold: f32) -> Mask {+ let mut m = Mask::empty(width, height);+ let (w, h) = (width as usize, height as usize);+ let at = |x: usize, y: usize| -> [f32; 4] {+ let i = (y * w + x) * 4;+ match pixels.get(i..i + 4) {+ Some(&[r, g, b, a]) => [r, g, b, a].map(|v| f32::from(v) / 255.0),+ _ => [0.0; 4],+ }+ };+ let (sx, sy) = (seed.0 as usize, seed.1 as usize);+ if sx >= w || sy >= h {+ return m;+ }+ let target = at(sx, sy);+ let limit = threshold.clamp(0.0, 1.0) * 2.0;+ let near = |c: [f32; 4]| c.iter().zip(&target).map(|(a, b)| (a - b).abs()).sum::<f32>() <= limit;+ let mut stack = vec![(sx, sy)];+ while let Some((x, y)) = stack.pop() {+ let i = y * w + x;+ if m.data.get(i).copied() != Some(0) || !near(at(x, y)) {+ continue;+ }+ if let Some(v) = m.data.get_mut(i) {+ *v = 255;+ }+ if x > 0 {+ stack.push((x - 1, y));+ }+ if x + 1 < w {+ stack.push((x + 1, y));+ }+ if y > 0 {+ stack.push((x, y - 1));+ }+ if y + 1 < h {+ stack.push((x, y + 1));+ }+ }+ m+ }+}++impl Mask {+ /// How much is selected at canvas point `p`, between pixel centres.+ fn sample(&self, p: Vec2) -> f32 {+ let (x, y) = (p.x - 0.5, p.y - 0.5);+ let (x0, y0) = (x.floor(), y.floor());+ let (fx, fy) = (x - x0, y - y0);+ let at = |xi: f32, yi: f32| -> f32 {+ if xi < 0.0 || yi < 0.0 || xi >= self.width as f32 || yi >= self.height as f32 {+ return 0.0;+ }+ let i = yi as usize * self.width as usize + xi as usize;+ f32::from(self.data.get(i).copied().unwrap_or(0)) / 255.0+ };+ let top = at(x0, y0) * (1.0 - fx) + at(x0 + 1.0, y0) * fx;+ let bottom = at(x0, y0 + 1.0) * (1.0 - fx) + at(x0 + 1.0, y0 + 1.0) * fx;+ top * (1.0 - fy) + bottom * fy+ }++ /// The selection moved as content is: each pixel takes what `to_source` (a pixel centre to+ /// where it came from) finds there.+ pub fn moved(&self, to_source: impl Fn(Vec2) -> Option<Vec2>) -> Mask {+ let mut out = Mask::empty(self.width, self.height);+ let w = self.width as usize;+ for (y, row) in out.data.chunks_exact_mut(w.max(1)).enumerate() {+ for (x, v) in row.iter_mut().enumerate() {+ if let Some(s) = to_source(Vec2::new(x as f32 + 0.5, y as f32 + 0.5)) {+ *v = to_byte(self.sample(s));+ }+ }+ }+ out+ }++ /// The selection moved through a mesh of triangles, three corners each of (where it goes,+ /// where it came from) in pixels, as a warp moves content.+ pub fn warped(&self, triangles: &[[f32; 4]]) -> Mask {+ let mut out = Mask::empty(self.width, self.height);+ let (w, h) = (self.width as usize, self.height as usize);+ for &[a, b, c] in triangles.as_chunks::<3>().0 {+ let (pa, pb, pc) = (Vec2::new(a[0], a[1]), Vec2::new(b[0], b[1]), Vec2::new(c[0], c[1]));+ let area = (pb.x - pa.x) * (pc.y - pa.y) - (pc.x - pa.x) * (pb.y - pa.y);+ if area.abs() < 1e-9 {+ continue;+ }+ let (lo_x, hi_x) = (+ pa.x.min(pb.x).min(pc.x).floor().max(0.0) as usize,+ (pa.x.max(pb.x).max(pc.x).ceil().max(0.0) as usize).min(w),+ );+ let (lo_y, hi_y) = (+ pa.y.min(pb.y).min(pc.y).floor().max(0.0) as usize,+ (pa.y.max(pb.y).max(pc.y).ceil().max(0.0) as usize).min(h),+ );+ for y in lo_y..hi_y {+ for x in lo_x..hi_x {+ let p = Vec2::new(x as f32 + 0.5, y as f32 + 0.5);+ // where p falls in the triangle, as weights of its corners+ let wb = ((p.x - pa.x) * (pc.y - pa.y) - (pc.x - pa.x) * (p.y - pa.y)) / area;+ let wc = ((pb.x - pa.x) * (p.y - pa.y) - (p.x - pa.x) * (pb.y - pa.y)) / area;+ let wa = 1.0 - wb - wc;+ if wa < -1e-4 || wb < -1e-4 || wc < -1e-4 {+ continue;+ }+ let s = Vec2::new(a[2] * wa + b[2] * wb + c[2] * wc, a[3] * wa + b[3] * wb + c[3] * wc);+ if let Some(v) = out.data.get_mut(y * w + x) {+ *v = (*v).max(to_byte(self.sample(s)));+ }+ }+ }+ }+ out+ }+}++/// The Gaussian's sigma (canvas pixels) for a blur `amount` (0..1), as feathering and the Gaussian+/// blur use it: it widens faster than the amount, from a fraction of a pixel to about 680.+pub fn feather_radius(amount: f32) -> f32 {+ let a = amount.clamp(0.0, 1.0);+ if a <= 0.0 {+ return 0.0;+ }+ let taps = ((a.sqrt() * 63.0).floor() + 1.0).min(64.0);+ let scale = (a * 32.0).floor().max(1.0);+ taps / 3.0 * scale+}++fn to_byte(v: f32) -> u8 {+ (v.clamp(0.0, 1.0) * 255.0).round() as u8+}++/// Adds `amount` × the covered part of each pixel between `x0` and `x1` to `row`.+fn add_span(row: &mut [f32], x0: f32, x1: f32, amount: f32) {+ let n = row.len().saturating_sub(1) as f32;+ let (x0, x1) = (x0.clamp(0.0, n), x1.clamp(0.0, n));+ if x1 <= x0 {+ return;+ }+ let (first, last) = (x0.floor() as usize, x1.floor() as usize);+ if first == last {+ if let Some(c) = row.get_mut(first) {+ *c += (x1 - x0) * amount;+ }+ return;+ }+ if let Some(c) = row.get_mut(first) {+ *c += (first as f32 + 1.0 - x0) * amount;+ }+ for c in row.iter_mut().take(last).skip(first + 1) {+ *c += amount;+ }+ if let Some(c) = row.get_mut(last) {+ *c += (x1 - last as f32) * amount;+ }+}++/// One box blur `r` either side along a line of `len` values `step` apart from `start`, edges+/// held at their last value.+fn blur_line(values: &mut [f32], start: usize, step: usize, len: usize, r: usize, line: &mut Vec<f32>) {+ line.clear();+ line.extend((0..len).map(|i| values.get(start + i * step).copied().unwrap_or(0.0)));+ let get = |i: isize| line.get(i.clamp(0, len as isize - 1) as usize).copied().unwrap_or(0.0);+ let span = (2 * r + 1) as f32;+ let mut sum: f32 = (-(r as isize)..=r as isize).map(get).sum();+ for i in 0..len {+ if let Some(v) = values.get_mut(start + i * step) {+ *v = sum / span;+ }+ sum += get(i as isize + r as isize + 1) - get(i as isize - r as isize);+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn at(m: &Mask, x: u32, y: u32) -> u8 {+ m.data[(y * m.width + x) as usize]+ }++ #[test]+ fn a_rectangle_covers_its_pixels_and_part_of_its_edges() {+ let m = Mask::rect(10, 10, Vec2::new(7.5, 8.0), Vec2::new(2.0, 2.0));+ assert_eq!(at(&m, 2, 2), 255);+ assert_eq!(at(&m, 7, 5), 128);+ assert_eq!(at(&m, 8, 5), 0);+ assert_eq!(at(&m, 1, 1), 0);+ assert!(!m.is_empty());+ assert!(Mask::empty(4, 4).is_empty());+ }++ #[test]+ fn an_ellipse_is_round_with_soft_edges() {+ let m = Mask::ellipse(40, 40, Vec2::new(0.5, 0.5), Vec2::new(39.5, 19.5));+ assert_eq!(at(&m, 20, 10), 255);+ assert_eq!(at(&m, 1, 1), 0);+ assert_eq!(at(&m, 20, 25), 0);+ // the pixel the end of the long axis runs through is about half covered+ let edge = at(&m, 39, 9);+ assert!(edge > 40 && edge < 220, "{edge}");+ }++ #[test]+ fn a_polygon_fills_by_the_non_zero_rule() {+ let tri = [Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(0.0, 10.0)];+ let m = Mask::polygon(12, 12, &tri);+ assert_eq!(at(&m, 1, 1), 255);+ assert_eq!(at(&m, 8, 8), 0);+ // a pixel the diagonal cuts in half+ let half = at(&m, 4, 5);+ assert!((100..=155).contains(&half), "{half}");+ // a square traced twice the same way stays filled+ let sq = [Vec2::new(2.0, 2.0), Vec2::new(8.0, 2.0), Vec2::new(8.0, 8.0), Vec2::new(2.0, 8.0)];+ let twice: Vec<Vec2> = sq.iter().chain(&sq).copied().collect();+ assert_eq!(at(&Mask::polygon(12, 12, &twice), 5, 5), 255);+ assert!(Mask::polygon(12, 12, &tri[..2]).is_empty());+ }++ #[test]+ fn adding_removing_inverting_and_feathering() {+ let mut m = Mask::rect(20, 20, Vec2::new(0.0, 0.0), Vec2::new(10.0, 20.0));+ m.combine(&Mask::rect(20, 20, Vec2::new(10.0, 0.0), Vec2::new(15.0, 20.0)), Combine::Add);+ assert_eq!(at(&m, 12, 5), 255);+ m.combine(&Mask::rect(20, 20, Vec2::new(0.0, 0.0), Vec2::new(20.0, 5.0)), Combine::Remove);+ assert_eq!(at(&m, 2, 2), 0);+ assert_eq!(at(&m, 2, 7), 255);+ m.invert();+ assert_eq!(at(&m, 2, 2), 255);+ assert_eq!(at(&m, 2, 7), 0);+ let mut f = Mask::rect(40, 40, Vec2::new(10.0, 10.0), Vec2::new(30.0, 30.0));+ f.feather(3.0);+ assert_eq!(at(&f, 20, 20), 255);+ let edge = at(&f, 10, 20);+ assert!(edge > 60 && edge < 200, "{edge}");+ assert!(at(&f, 6, 20) < at(&f, 10, 20));+ }++ #[test]+ fn a_selection_moves_with_its_content() {+ let m = Mask::rect(20, 20, Vec2::new(0.0, 0.0), Vec2::new(5.0, 5.0));+ // 10 right: each pixel looks 10 left+ let moved = m.moved(|p| Some(p - Vec2::new(10.0, 0.0)));+ assert_eq!(at(&moved, 12, 2), 255);+ assert_eq!(at(&moved, 2, 2), 0);+ // the same through two triangles+ let c = |x: f32, y: f32| [x + 10.0, y, x, y];+ let mesh = [c(0.0, 0.0), c(20.0, 0.0), c(20.0, 20.0), c(0.0, 0.0), c(20.0, 20.0), c(0.0, 20.0)];+ let warped = m.warped(&mesh);+ assert_eq!(at(&warped, 12, 2), 255);+ assert_eq!(at(&warped, 2, 2), 0);+ }++ #[test]+ fn the_feather_widens_with_its_amount() {+ assert_eq!(feather_radius(0.0), 0.0);+ assert!((feather_radius(0.52) - 245.3).abs() < 0.5, "{}", feather_radius(0.52));+ assert!(feather_radius(0.1) < feather_radius(0.2) && feather_radius(1.0) > 650.0);+ }++ #[test]+ fn colour_selection_floods_what_matches_and_is_joined() {+ // a 6 × 1 strip: red, red, blue, red, red, red+ let red = [255u8, 0, 0, 255];+ let blue = [0u8, 0, 255, 255];+ let px: Vec<u8> = [red, red, blue, red, red, red].concat();+ let m = Mask::by_colour(6, 1, &px, (0, 0), 0.1);+ assert_eq!(m.data, vec![255, 255, 0, 0, 0, 0]);+ let all = Mask::by_colour(6, 1, &px, (0, 0), 1.0);+ assert!(all.data.iter().all(|&v| v == 255));+ assert!(Mask::by_colour(6, 1, &px, (9, 0), 0.5).is_empty());+ }+}diff --git a/crates/engine/src/stroke.rs b/crates/engine/src/stroke.rsnew file mode 100644index 0000000..4017ca9--- /dev/null+++ b/crates/engine/src/stroke.rs@@ -0,0 +1,1465 @@+//! From input samples to stamps: stabilisation and streamline smoothing, pressure, tilt and speed+//! response, spacing, the shape's placement (rotation, scatter, count, jitter, roundness) and+//! taper.++use crate::brush::{Brush, FLOW_POWER, Rendering, Taper, Tilt};+use crate::curve::Curve;+use crate::geom::{IRect, Vec2};+use crate::input::{Pointer, Sample};+use crate::studio::{SPACING_FLOOR, SPACING_SPAN};++/// One dab of the brush tip, in canvas pixels.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Stamp {+ pub center: Vec2,+ /// Half the stamp's width.+ pub radius: f32,+ /// 0..1, before the stroke's opacity.+ pub alpha: f32,+ /// Rotation, radians.+ pub angle: f32,+ /// 1 = as drawn; lower squashes the stamp across its rotation.+ pub roundness: f32,+ /// Where a moving grain is read from: the stamp's middle in the grain (canvas pixels), each+ /// point of the stamp read that far from it as on the canvas (the grain never turns or+ /// squashes with the stamp). A rolling grain is read in place, so it stays put as the stamps+ /// move over it; a static one moves along with each stamp.+ pub grain_offset: Vec2,+ /// How hard the pen presses the paint into a grain (the pressure, 0..1), and how much that+ /// counts (the brush's pressure bleed, 0..1): pressed harder, the paint takes on more of the+ /// stamp and grain, its strongest parts first.+ pub grain_press: f32,+ pub grain_bleed: f32,+ /// The shape mirrored across its own vertical and horizontal axes.+ pub flip: [bool; 2],+ /// The colour shifted: hue (turns), saturation and lightness (each −1..1).+ pub shift: [f32; 3],+ /// How much of the secondary colour it paints with, 0..1.+ pub secondary: f32,+ /// A moving grain's depth and tile size here, as multiples of the brush's.+ pub grain_depth: f32,+ pub grain_size: f32,+ /// How far it fades across its width from its leading edge (a leaning pen's shading), 0..1.+ pub gradation: f32,+ /// How far a taper has thinned it (its size multiplier, 1 = not at all): a round tip's rim+ /// thins with it, so a tapered stamp is drawn as the whole stamp scaled down.+ pub taper: f32,+ /// What light pressure lets through (the brush's opacity transfer), 0..1: for a capped+ /// rendering the most the stamp builds up to, else already in its alpha.+ pub transfer: f32,+}++impl Stamp {+ /// A plain round stamp.+ pub fn round(center: Vec2, radius: f32, alpha: f32) -> Stamp {+ Stamp {+ center,+ radius,+ alpha,+ angle: 0.0,+ roundness: 1.0,+ grain_offset: Vec2::ZERO,+ grain_press: 1.0,+ grain_bleed: 0.0,+ flip: [false; 2],+ shift: [0.0; 3],+ secondary: 0.0,+ grain_depth: 1.0,+ grain_size: 1.0,+ gradation: 0.0,+ taper: 1.0,+ transfer: 1.0,+ }+ }++ /// Pixels the stamp can touch: its square shape at any rotation.+ pub fn bounds(&self) -> IRect {+ IRect::around(self.center, self.radius * std::f32::consts::SQRT_2)+ }+}++/// A stamp before taper: where it sits on the path, and its size and alpha from the input.+#[derive(Clone, Copy, Debug)]+struct Placed {+ center: Vec2,+ distance: f32,+ diameter: f32,+ alpha: f32,+ angle: f32,+ roundness: f32,+ flip: [bool; 2],+ shift: [f32; 3],+ secondary: f32,+ grain_depth: f32,+ grain_size: f32,+ grain_press: f32,+ gradation: f32,+ transfer: f32,+}++#[derive(Clone, Copy, Debug)]+struct PathPoint {+ pos: Vec2,+ pressure: f32,+ /// The pressure as size, opacity, bleed and roundness each follow it (see `soften`).+ soft: [f32; 4],+ tilt: f32,+ azimuth: f32,+ /// How fast the input moves, 0..1 of [`FAST`].+ speed: f32,+}++impl PathPoint {+ fn lerp(self, to: PathPoint, t: f32) -> PathPoint {+ PathPoint {+ pos: self.pos.lerp(to.pos, t),+ pressure: self.pressure + (to.pressure - self.pressure) * t,+ soft: [0, 1, 2, 3].map(|k| {+ let (a, b) = (self.soft.get(k).copied().unwrap_or(1.0), to.soft.get(k).copied().unwrap_or(1.0));+ a + (b - a) * t+ }),+ tilt: self.tilt + (to.tilt - self.tilt) * t,+ azimuth: to.azimuth,+ speed: self.speed + (to.speed - self.speed) * t,+ }+ }+}++/// Speed for the speed dynamics, from how far the pen moves on screen in a frame of a 60 Hz+/// display (points): none up to `SLOW`, then rising (as the square root) to full `SPAN` further+/// on. Both scale with the input's speed distance.+const SLOW: f32 = 25.0;+const SPAN: f32 = 100.0;+/// How many frames the speed is smoothed over.+const SPEED_FRAMES: f32 = 3.0;+/// The frames between two samples with the same time: those of a pen sampled 240 times a second.+const SAMPLE_FRAMES: f32 = 0.25;+/// Stabilisation averages up to this many of the latest input points.+const MOST_AVERAGED: usize = 32;+/// At full motion filtering, how little the filtered pen moves toward each new point; and at full+/// expression, how much of the way back to the pen it comes.+const MOTION_FILTER_MOST: f32 = 0.9;+const EXPRESSION_MOST: f32 = 0.5;+/// A lateral or linear jitter of 1 moves a stamp up to this many diameters.+const JITTER_REACH: f32 = 2.0;+/// A fall off of 1 fades a stroke out over this many diameters.+const FALLOFF_SPAN: f32 = 30.0;++/// The brush's controls the builder reads beyond its own fields (see `studio`), read once.+#[derive(Clone, Copy, Debug, Default)]+struct Extras {+ spacing_jitter: f32,+ jitter_lateral: f32,+ jitter_linear: f32,+ falloff: f32,+ count_jitter: f32,+ pressure_roundness: f32,+ tilt_roundness: f32,+ roundness_jitter: f32,+ speed_size: f32,+ speed_opacity: f32,+ speed_spacing: f32,+ stabilization: f32,+ flip_x: bool,+ flip_y: bool,+ /// Colour jitter per stamp and per stroke (hue, saturation, lightness, darkness), and the+ /// colour's response to pressure and tilt (hue, saturation, brightness, −1..1).+ stamp_color: [f32; 4],+ stroke_color: [f32; 4],+ pressure_color: [f32; 3],+ tilt_color: [f32; 3],+ /// How far a moving grain rolls along with the stroke, 0 (static) to 1 (rolling), and whether+ /// each stroke starts somewhere else in the grain.+ grain_movement: f32,+ grain_offset_jitter: bool,+ /// Light pressure lowering (or, negative, raising) each stamp's flow, −1..1.+ pressure_flow: f32,+ /// How slowly size, opacity, bleed and roundness follow the pressure when the pen moves fast.+ pressure_response: [f32; 4],+ /// Light pressure, and leaning, letting more of a moving grain through (bleed), 0..1.+ pressure_bleed: f32,+ tilt_bleed: f32,+ /// A moving grain's depth varied from stamp to stamp, and the least it goes to, 0..1.+ grain_depth_jitter: f32,+ grain_depth_min: f32,+ /// A moving grain sized with the stamp (0) or fixed (1, cropped).+ grain_zoom: f32,+ /// How blunt the pen's and the finger's taper ends are, 0 (sharp) to 1.+ pen_taper_tip: f32,+ touch_taper_tip: f32,+ /// The secondary colour mixed in per stamp and per stroke (jitter, 0..1), and by light+ /// pressure and by leaning (−1..1).+ stamp_secondary: f32,+ stroke_secondary: f32,+ pressure_secondary: f32,+ tilt_secondary: f32,+ /// How a leaning pen shades the stamp across its width, 0..1.+ tilt_gradation: f32,+ /// How much a lean's growth depends on the stroke running across the lean (none along it),+ /// 0..1.+ tilt_compression: f32,+ /// The stamp's roundness upright and at the most lean (the roundness tilt), 0..1.+ tilt_roundness_max: f32,+ /// Where each tilt control starts (see [`Tilt::reach`]).+ tilt_angles: TiltAngles,+ /// The brush's own motion filtering and expression, with the app's.+ motion_filtering: f32,+ motion_expression: f32,+ /// The gap per unit of stamp size: the older spacing (version 0) puts stamps 1/√2 as far+ /// apart as the newer.+ spacing_stride: f32,+}++/// Each tilt control's angle (its dial's share of a quarter turn).+#[derive(Clone, Copy, Debug, Default)]+struct TiltAngles {+ opacity: f32,+ size: f32,+ gradation: f32,+ bleed: f32,+ roundness: f32,+ /// Hue, saturation and brightness.+ color: [f32; 3],+ secondary: f32,+}++impl Extras {+ fn of(b: &Brush) -> Extras {+ let unit = |k: &str| b.setting(k).clamp(0.0, 1.0);+ let both = |k: &str| b.setting(k).clamp(-1.0, 1.0);+ Extras {+ spacing_jitter: unit("spacing_jitter"),+ jitter_lateral: unit("jitter_lateral"),+ jitter_linear: unit("jitter_linear"),+ falloff: unit("falloff"),+ count_jitter: unit("count_jitter"),+ pressure_roundness: both("pressure_roundness"),+ tilt_roundness: both("tilt_roundness"),+ roundness_jitter: unit("roundness_jitter_y").max(unit("roundness_jitter_x")),+ speed_size: both("speed_size"),+ speed_opacity: both("speed_opacity"),+ speed_spacing: unit("speed_spacing"),+ stabilization: unit("stabilization"),+ flip_x: unit("flip_x") >= 0.5,+ flip_y: unit("flip_y") >= 0.5,+ stamp_color: ["stamp_hue", "stamp_saturation", "stamp_lightness", "stamp_darkness"].map(unit),+ stroke_color: ["stroke_hue", "stroke_saturation", "stroke_lightness", "stroke_darkness"].map(unit),+ pressure_color: ["pressure_hue", "pressure_saturation", "pressure_brightness"].map(both),+ tilt_color: ["tilt_hue", "tilt_saturation", "tilt_brightness"].map(both),+ grain_movement: unit("grain_movement"),+ grain_offset_jitter: b.setting("grain_offset_jitter") >= 0.5,+ pressure_flow: both("pressure_flow"),+ pressure_response: [+ "pressure_size_response",+ "pressure_opacity_response",+ "pressure_bleed_response",+ "pressure_roundness_response",+ ]+ .map(unit),+ // the control's place to the power 2.2+ pressure_bleed: unit("pressure_bleed").powf(2.2),+ tilt_bleed: unit("tilt_bleed").powf(2.2),+ grain_depth_jitter: unit("grain_depth_jitter"),+ grain_depth_min: unit("grain_depth_min"),+ grain_zoom: unit("grain_zoom"),+ pen_taper_tip: unit("pen_taper_tip"),+ touch_taper_tip: unit("touch_taper_tip"),+ stamp_secondary: unit("stamp_secondary"),+ stroke_secondary: unit("stroke_secondary"),+ pressure_secondary: both("pressure_secondary"),+ tilt_secondary: both("tilt_secondary"),+ tilt_gradation: unit("tilt_gradation"),+ tilt_compression: unit("tilt_size_compression"),+ tilt_roundness_max: unit("tilt_roundness_max"),+ tilt_angles: TiltAngles {+ opacity: unit("opacity_tilt_angle"),+ size: unit("size_tilt_angle"),+ gradation: unit("gradation_tilt_angle"),+ bleed: unit("bleed_tilt_angle"),+ roundness: unit("roundness_tilt_angle"),+ color: ["hue_tilt_angle", "saturation_tilt_angle", "brightness_tilt_angle"].map(unit),+ secondary: unit("secondary_tilt_angle"),+ },+ motion_filtering: unit("motion_filtering"),+ motion_expression: unit("motion_expression"),+ spacing_stride: if b.setting("spacing_version") < 0.5 { std::f32::consts::FRAC_1_SQRT_2 } else { 1.0 },+ }+ }+}++/// Streamline is tuned for input at this interval; other rates are scaled to match.+const REFERENCE_INTERVAL_MS: f64 = 1000.0 / 120.0;+/// How fast a stroke starts is read over its first this many milliseconds, and how fast it ends+/// over its last (for the tapers that last a time).+const PACE_WINDOW_MS: f64 = 20.0;+const END_PACE_WINDOW_MS: f64 = 60.0;+/// How far (canvas pixels) offset jitter may move a stroke's start in a moving grain.+const GRAIN_JITTER_SPAN: f32 = 1024.0;+/// Stamps a stroke may hold (a guard against runaway input, far above any real stroke).+const MAX_STAMPS: usize = 400_000;++/// A small deterministic random source (xorshift), so a stroke replays identically.+#[derive(Clone, Debug)]+struct Random(u32);++impl Random {+ /// 0..1.+ fn next(&mut self) -> f32 {+ let mut x = self.0;+ x ^= x << 13;+ x ^= x >> 17;+ x ^= x << 5;+ self.0 = x;+ (x >> 8) as f32 / (1u32 << 24) as f32+ }+}++/// Builds one stroke. Feed it samples in canvas pixels as they arrive ([`StrokeBuilder::add`]+/// returns the stamps to draw now), then [`StrokeBuilder::finish`] for the final stamps, which+/// include the end taper and the catch-up to where the pen lifted.+#[derive(Clone, Debug)]+pub struct StrokeBuilder {+ brush: Brush,+ diameter: f32,+ pointer: Pointer,+ pressure: Option<f32>,+ smoothed: Option<PathPoint>,+ last_sample: Option<Sample>,+ head: Option<PathPoint>,+ direction: f32,+ /// The length of the last stretch of path walked (canvas pixels), none before the first.+ last_seg: f32,+ /// How much the brush is scaled on this canvas (the size the stroke was asked for over the+ /// brush's own), which leaning's growth takes too.+ scale: f32,+ carry: f32,+ length: f32,+ placed: Vec<Placed>,+ bounds: IRect,+ random: Random,+ extras: Extras,+ /// The latest input points, for stabilisation; the speed, smoothed; the next gap's jitter.+ recent: Vec<Vec2>,+ speed: f32,+ /// Whether the speed has been measured (the first move is taken as it is).+ speed_known: bool,+ /// The pressure as each use follows it, at the last sample; and how many samples so far.+ soft: Option<[f32; 4]>,+ segments: u32,+ /// A sample stroke drawn for show: no speed, and the pressure taken as it comes.+ steady: bool,+ /// The samples are the path itself, pressed as they say: nothing smooths either.+ exact: bool,+ gap_jitter: f32,+ /// The whole stroke's colour shift, drawn once.+ stroke_shift: [f32; 3],+ /// The stroke's share of the secondary colour, picked as it starts.+ stroke_secondary: f32,+ /// How far the canvas is turned on screen, for a brush whose shapes keep to the screen.+ screen_turn: f32,+ /// Screen points a canvas pixel spans, for the speed dynamics.+ points_per_pixel: f32,+ input: InputSettings,+ /// Where the motion filter has the pen.+ filtered: Option<Vec2>,+ /// Where in a moving grain the stroke starts.+ grain_start: Vec2,+ /// How far the input has gone (canvas pixels, as it came) and when: its latest stretch, the+ /// time it started and how fast it went at first (for the tapers that last a time).+ trail: std::collections::VecDeque<(f64, f32)>,+ input_length: f32,+ started_ms: Option<f64>,+ start_pace: Option<f32>,+}++/// Smoothing and pressure set for every stroke, whatever the brush, on top of the brush's own.+#[derive(Clone, Debug, PartialEq)]+pub struct InputSettings {+ /// The average of the latest points, 0..1 (as the brush's stabilisation).+ pub stabilization: f32,+ /// Shaky movement filtered out, 0..1, and how much of the hand's own motion comes back, 0..1.+ pub motion_filtering: f32,+ pub motion_expression: f32,+ /// Pressure changes smoothed, 0..1.+ pub pressure_smoothing: f32,+ /// What pen pressure becomes before the brush's own curve.+ pub pressure_curve: Curve,+ /// How far input must move for the speed dynamics to count it as fast, as a part of the+ /// usual distance (0.25..1): less makes slower movement fast.+ pub speed_distance: f32,+}++impl Default for InputSettings {+ fn default() -> Self {+ InputSettings {+ stabilization: 0.0,+ motion_filtering: 0.0,+ motion_expression: 0.0,+ pressure_smoothing: 0.0,+ pressure_curve: Curve::linear(),+ speed_distance: 1.0,+ }+ }+}++/// Two amounts, 0..1, together: each takes away what the other leaves.+fn together(a: f32, b: f32) -> f32 {+ 1.0 - (1.0 - a.clamp(0.0, 1.0)) * (1.0 - b.clamp(0.0, 1.0))+}++impl StrokeBuilder {+ /// The stroke with the app's own smoothing and pressure as well as the brush's.+ pub fn with_input(mut self, input: InputSettings) -> StrokeBuilder {+ self.extras.stabilization = together(self.extras.stabilization, input.stabilization);+ self.input = input;+ self+ }++ /// The stroke drawn on a canvas turned `rotation` radians on screen: a brush oriented to the+ /// screen turns its shapes back by as much, so they keep their angle on screen.+ pub fn on_view_turned(mut self, rotation: f32) -> StrokeBuilder {+ if self.brush.setting("orient_to_screen") >= 0.5 && rotation.is_finite() {+ self.screen_turn = rotation;+ }+ self+ }++ /// The stroke drawn with the canvas shown at `points_per_pixel` screen points a canvas pixel:+ /// the speed dynamics go by how fast the pen moves on screen.+ pub fn seen_at(mut self, points_per_pixel: f32) -> StrokeBuilder {+ if points_per_pixel.is_finite() && points_per_pixel > 0.0 {+ self.points_per_pixel = points_per_pixel;+ }+ self+ }++ /// The stroke drawn for show (the library's sample): it never counts as fast, and each use of+ /// the pressure takes it as it comes.+ pub fn steady(mut self) -> StrokeBuilder {+ self.steady = true;+ self+ }++ /// The samples are the path to draw, exactly (the drawing pad's sample scribble): no+ /// streamline, stabilisation or motion filtering moves it, and each use of the pressure takes+ /// it as it comes.+ /// The brush scaled `scale` times on this canvas (as its diameter already is), for what+ /// leaning adds to it.+ pub fn scaled(mut self, scale: f32) -> StrokeBuilder {+ if scale.is_finite() && scale > 0.0 {+ self.scale = scale;+ }+ self+ }++ pub fn exact_path(mut self) -> StrokeBuilder {+ self.exact = true;+ self+ }++ /// A stroke with `brush` at `diameter` canvas pixels (the size slider's value).+ pub fn new(brush: Brush, diameter: f32, pointer: Pointer) -> StrokeBuilder {+ StrokeBuilder::with_seed(brush, diameter, pointer, 0x9e37_79b9)+ }++ /// As [`StrokeBuilder::new`], with the seed for scatter, jitter and random rotation.+ pub fn with_seed(brush: Brush, diameter: f32, pointer: Pointer, seed: u32) -> StrokeBuilder {+ let diameter = if diameter.is_finite() { diameter.max(0.5) } else { 1.0 };+ StrokeBuilder {+ brush,+ diameter,+ pointer,+ pressure: None,+ smoothed: None,+ last_sample: None,+ head: None,+ direction: 0.0,+ last_seg: 0.0,+ scale: 1.0,+ carry: 0.0,+ length: 0.0,+ placed: Vec::new(),+ bounds: IRect::EMPTY,+ random: Random(seed | 1),+ extras: Extras::default(),+ recent: Vec::new(),+ speed: 0.0,+ speed_known: false,+ soft: None,+ segments: 0,+ steady: false,+ exact: false,+ gap_jitter: 1.0,+ stroke_shift: [0.0; 3],+ stroke_secondary: 0.0,+ screen_turn: 0.0,+ points_per_pixel: 1.0,+ input: InputSettings::default(),+ filtered: None,+ grain_start: Vec2::ZERO,+ trail: std::collections::VecDeque::new(),+ input_length: 0.0,+ started_ms: None,+ start_pace: None,+ }+ .reading_extras()+ }++ fn reading_extras(mut self) -> StrokeBuilder {+ self.extras = Extras::of(&self.brush);+ let jitter = self.extras.stroke_color;+ self.stroke_shift = self.color_jitter(jitter);+ if self.extras.stroke_secondary > 0.0 {+ self.stroke_secondary = self.extras.stroke_secondary * self.random.next();+ }+ if self.extras.grain_offset_jitter {+ self.grain_start = Vec2::new(self.random.next(), self.random.next()) * GRAIN_JITTER_SPAN;+ }+ self+ }++ /// A random colour shift by `jitter` (hue, saturation, lightness, darkness).+ fn color_jitter(&mut self, [hue, saturation, lightness, darkness]: [f32; 4]) -> [f32; 3] {+ if hue == 0.0 && saturation == 0.0 && lightness == 0.0 && darkness == 0.0 {+ return [0.0; 3];+ }+ [+ (self.random.next() * 2.0 - 1.0) * hue * 0.5,+ -self.random.next() * saturation,+ self.random.next() * lightness - self.random.next() * darkness,+ ]+ }++ pub fn pointer(&self) -> Pointer {+ self.pointer+ }++ /// The stamp diameter at full pressure (the size slider's value), canvas pixels.+ pub fn diameter(&self) -> f32 {+ self.diameter+ }++ pub fn brush(&self) -> &Brush {+ &self.brush+ }++ /// Pixels the stroke covers so far.+ pub fn bounds(&self) -> IRect {+ self.bounds+ }++ /// Path length so far, canvas pixels.+ pub fn length(&self) -> f32 {+ self.length+ }++ pub fn stamp_count(&self) -> usize {+ self.placed.len()+ }++ /// Adds samples (canvas pixels) and returns the stamps they add. Non-finite samples are skipped.+ pub fn add(&mut self, samples: &[Sample]) -> Vec<Stamp> {+ let mut out = Vec::new();+ for s in samples.iter().filter(|s| s.is_finite()) {+ self.push(*s, &mut out);+ }+ out+ }++ /// The stamps `samples` would add, without adding them (for drawing predicted input).+ pub fn preview(&self, samples: &[Sample]) -> Vec<Stamp> {+ self.clone().add(samples)+ }++ /// Every stamp so far as currently drawn (no end taper yet).+ pub fn stamps(&self) -> Vec<Stamp> {+ self.placed.iter().map(|p| self.finish_stamp(p, None)).collect()+ }++ /// Ends the stroke: walks on to where the pen lifted and applies the end taper. Returns all of+ /// the stroke's stamps, as they should finally be drawn.+ pub fn finish(&mut self) -> Vec<Stamp> {+ if let (Some(last), Some(head)) = (self.last_sample, self.head) {+ let to = PathPoint {+ pos: last.pos,+ pressure: self.pressure.unwrap_or(1.0),+ soft: self.soft.unwrap_or(head.soft),+ tilt: head.tilt,+ azimuth: head.azimuth,+ speed: head.speed,+ };+ let mut ignored = Vec::new();+ self.walk_to(to, &mut ignored);+ }+ let length = self.length;+ let stamps: Vec<Stamp> = self.placed.iter().map(|p| self.finish_stamp(p, Some(length))).collect();+ self.bounds = stamps.iter().fold(IRect::EMPTY, |b, s| b.union(s.bounds()));+ stamps+ }++ fn push(&mut self, s: Sample, out: &mut Vec<Stamp>) {+ let pen = self.pointer.has_pressure();+ let raw = if pen { self.input.pressure_curve.eval(s.pressure.clamp(0.0, 1.0)).clamp(0.0, 1.0) } else { 1.0 };+ let smoothing = together(self.brush.pressure_smoothing, self.input.pressure_smoothing).min(0.95);+ let pressure = match self.pressure {+ None => raw,+ Some(p) => p + (raw - p) * (1.0 - smoothing),+ };+ self.pressure = Some(pressure);+ let (tilt, azimuth) = if pen { (s.tilt, s.azimuth) } else { (0.0, 0.0) };+ let curved = self.brush.pressures(pressure);+ let soft = match (self.last_sample, self.soft) {+ (Some(last), Some(before)) if !self.steady && !self.exact => {+ let frames = ((s.time_ms - last.time_ms).abs() * 0.06) as f32;+ let frames = if frames > 0.0 { frames } else { SAMPLE_FRAMES };+ self.soften(curved, before, frames, s.pos.distance(last.pos))+ }+ _ => curved,+ };+ self.soft = Some(soft);+ self.segments = self.segments.saturating_add(1);+ if let Some(last) = self.last_sample {+ // frames of a 60 Hz display since the last sample+ let frames = ((s.time_ms - last.time_ms).abs() * 0.06) as f32;+ let frames = if frames > 0.0 { frames } else { SAMPLE_FRAMES };+ let moved = s.pos.distance(last.pos) * self.points_per_pixel / frames;+ let scale = self.input.speed_distance.clamp(0.25, 1.0);+ let over = (moved - SLOW * scale) / (SPAN * scale);+ let now = if over > 0.0 && !self.steady { over.sqrt().min(1.0) } else { 0.0 };+ // the first move as it is; later ones smoothed over a few frames+ let held = if self.speed_known { SPEED_FRAMES / frames } else { 0.0 };+ self.speed = ((now + held * self.speed) / (held + 1.0)).clamp(0.0, 1.0);+ self.speed_known = true;+ }+ // motion filtering: the pen followed slowly, so small shakes fall away; the expression+ // gives back part of the hand's own motion+ let mut pos = s.pos;+ let filtering = together(self.extras.motion_filtering, self.input.motion_filtering);+ if filtering > 0.0 && !self.exact {+ let follow = 1.0 - filtering * MOTION_FILTER_MOST;+ let f = self.filtered.map_or(s.pos, |f| f.lerp(s.pos, follow));+ self.filtered = Some(f);+ let expression = together(self.extras.motion_expression, self.input.motion_expression);+ pos = f.lerp(s.pos, expression * EXPRESSION_MOST);+ }+ // stabilisation: the average of the latest points, more of them the stronger it is+ if self.extras.stabilization > 0.0 && !self.exact {+ self.recent.push(pos);+ let keep = 1 + (self.extras.stabilization * (MOST_AVERAGED - 1) as f32) as usize;+ let over = self.recent.len().saturating_sub(keep);+ self.recent.drain(..over);+ let sum = self.recent.iter().fold(Vec2::ZERO, |a, &p| a + p);+ pos = sum * (1.0 / self.recent.len() as f32);+ }+ let target = PathPoint { pos, pressure, soft, tilt, azimuth, speed: self.speed };+ let smoothed = match (self.smoothed, self.last_sample) {+ (Some(prev), Some(last)) if !self.exact => {+ let dt = (s.time_ms - last.time_ms).clamp(0.5, 50.0);+ let keep = (self.brush.streamline.clamp(0.0, 1.0) * 0.92).powf((dt / REFERENCE_INTERVAL_MS) as f32);+ PathPoint { pos: prev.pos.lerp(target.pos, 1.0 - keep), ..target }+ }+ _ => target,+ };+ self.smoothed = Some(smoothed);+ self.keep_pace(s);+ self.last_sample = Some(s);+ self.walk_to(smoothed, out);+ }++ /// Notes how far and how fast the input has come with `s`.+ fn keep_pace(&mut self, s: Sample) {+ self.input_length += self.last_sample.map_or(0.0, |l| s.pos.distance(l.pos));+ let started = *self.started_ms.get_or_insert(s.time_ms);+ self.trail.push_back((s.time_ms, self.input_length));+ while self.trail.len() > 2 && self.trail.get(1).is_some_and(|&(t, _)| s.time_ms - t >= END_PACE_WINDOW_MS) {+ self.trail.pop_front();+ }+ if self.start_pace.is_none() && s.time_ms - started >= PACE_WINDOW_MS {+ self.start_pace = Some(self.input_length / (s.time_ms - started) as f32);+ }+ }++ /// How fast the stroke started and how fast it is going now (lately), canvas pixels a+ /// millisecond; samples without times count as coming at the usual rate.+ fn paces(&self) -> (f32, f32) {+ let pace = |gone: f32, ms: f64, samples: usize| {+ let ms = if ms >= 1.0 { ms } else { samples.saturating_sub(1) as f64 * REFERENCE_INTERVAL_MS };+ if ms > 0.0 { gone / ms as f32 } else { 0.0 }+ };+ let now = match (self.trail.front(), self.trail.back()) {+ (Some(&(t0, l0)), Some(&(t1, l1))) => pace(l1 - l0, t1 - t0, self.trail.len()),+ _ => 0.0,+ };+ let started = self.start_pace.unwrap_or_else(|| {+ let ms = match (self.started_ms, self.last_sample) {+ (Some(t0), Some(last)) => last.time_ms - t0,+ _ => 0.0,+ };+ pace(self.input_length, ms, self.segments as usize)+ });+ (started, now)+ }++ /// Walks the path from its head to `to`, placing stamps at the brush's spacing.+ fn walk_to(&mut self, to: PathPoint, out: &mut Vec<Stamp>) {+ let Some(from) = self.head else {+ // the first point always gets a stamp, so a tap leaves a dot+ self.head = Some(to);+ self.place(to, 0.0, out);+ return;+ };+ let seg = from.pos.distance(to.pos);+ if seg.is_nan() || seg <= 1e-4 {+ self.head = Some(PathPoint { pos: from.pos, ..to });+ return;+ }+ let d = to.pos - from.pos;+ self.direction = d.y.atan2(d.x);+ self.last_seg = seg;+ let mut done = 0.0f32;+ while self.placed.len() < MAX_STAMPS {+ let need = self.step(from.lerp(to, done / seg)) - self.carry;+ if done + need > seg {+ self.carry += seg - done;+ break;+ }+ done += need.max(0.0);+ self.carry = 0.0;+ self.place(from.lerp(to, done / seg), self.length + done, out);+ }+ self.length += seg;+ self.head = Some(to);+ }++ /// The stamp diameter at a point of the path, before jitter and taper.+ fn diameter_at(&self, p: PathPoint) -> f32 {+ let (pressure, _) = self.brush.factors(p.soft[0], p.soft[1]);+ // faster input thins the stroke (or, the other way, widens it)+ let speed = (1.0 - self.extras.speed_size * p.speed).max(0.05);+ let drawn = self.diameter * pressure * speed;+ // leaning adds to it, up to the most the brush may be+ let most = (self.brush.biggest() * self.scale).max(drawn);+ (drawn + self.tilt_growth(p)).min(most)+ }++ /// How far the pen leans past where a tilt control at `theta` starts (see [`Tilt::reach`]);+ /// nothing for a finger.+ fn leaning(&self, p: PathPoint, theta: f32) -> f32 {+ if self.pointer.has_pressure() { Tilt::reach(p.tilt, theta) } else { 0.0 }+ }++ /// What leaning adds to the stamp's diameter (canvas pixels): the tilt size, as far as the+ /// lean has gone, the more the stroke runs across the lean.+ fn tilt_growth(&self, p: PathPoint) -> f32 {+ let size = self.brush.tilt.size;+ if size == 0.0 {+ return 0.0;+ }+ let reach = self.leaning(p, self.extras.tilt_angles.size);+ (size * reach * self.across_lean(p) * self.brush.size_unit() * self.scale).max(0.0)+ }++ /// How much of a lean's growth the stamp takes: with compression, none while the stroke runs+ /// along the lean, all of it across; without, all of it. A dab on its own takes it all.+ fn across_lean(&self, p: PathPoint) -> f32 {+ let compression = self.extras.tilt_compression;+ if compression <= 0.0 || self.last_seg <= 0.0 {+ return 1.0;+ }+ // the lean's direction on the canvas: the pen's orientation is clockwise from up on the screen+ let lean = p.azimuth - std::f32::consts::FRAC_PI_2 - self.screen_turn;+ let quarters = (self.direction - lean) / std::f32::consts::FRAC_PI_2;+ let across = ((quarters + 1.0).rem_euclid(2.0) - 1.0).abs();+ // a short step between inputs counts for less+ let long = 1.0 - 1.0 / (self.last_seg * self.last_seg);+ ((1.0 - compression) + compression * across * (across + long).max(0.0).sqrt()).clamp(0.0, 1.0)+ }++ /// Distance to the next stamp: the spacing's share of the stamp's square, and half a pixel+ /// more (and a little with the spacing), wider apart the faster the input, jittered per gap.+ fn step(&self, p: PathPoint) -> f32 {+ let spacing = self.brush.spacing.max(0.005);+ let extra = 0.5 + (spacing - SPACING_FLOOR).max(0.0) / (SPACING_SPAN / 2.0);+ let speed = 1.0 + 2.0 * self.extras.speed_spacing * p.speed;+ ((spacing * self.square_at(p) * self.extras.spacing_stride + extra) * speed * self.gap_jitter).max(0.25)+ }++ /// Each use's pressure followed from `before` towards `now` over `frames` (of a 60 Hz display)+ /// in which the pen moved `moved` canvas pixels: when the pen moves fast, a use with a response+ /// speed lags (to (frames / pixels, at least 0.2) to the power twice its response, each+ /// sample), and every use is evened out with what it was, more so the more often the pen+ /// reports (eased in over the stroke's first frames).+ fn soften(&self, now: [f32; 4], before: [f32; 4], frames: f32, moved: f32) -> [f32; 4] {+ let pace = if moved > 0.0 { (frames / moved).clamp(0.2, 1.0) } else { 1.0 };+ let held = 2.0 / frames.max(1e-3);+ let ramp = (self.segments as f32 / held).clamp(0.0, 1.0) * held;+ [0, 1, 2, 3].map(|k| {+ let (n, b) = (now.get(k).copied().unwrap_or(1.0), before.get(k).copied().unwrap_or(1.0));+ let response = self.extras.pressure_response.get(k).copied().unwrap_or(0.0);+ let followed = b + (n - b) * pace.powf(2.0 * response);+ ((followed + b * ramp) / (ramp + 1.0)).clamp(0.0, 1.0)+ })+ }++ /// The square a stamp's shape fills at a point (a round tip covers only part of it).+ fn square_at(&self, p: PathPoint) -> f32 {+ let round_tip = self.brush.shape.image.is_none() && self.brush.shape.source.is_none();+ self.diameter_at(p) / if round_tip { crate::brushfile::ROUND_TIP_SHARE } else { 1.0 }+ }++ /// The opacity a stamp drawn "over" needs so that a brush that builds up gradually reaches,+ /// after one pass, what it would have with `alpha` (each stamp adding `alpha` of what is left,+ /// squared). `overlap` is how many stamps cover a point in one pass.+ fn gradual(alpha: f32, overlap: f32) -> f32 {+ let n = overlap.clamp(1.0, 512.0);+ let mut built = 0.0f32;+ for _ in 0..n.ceil() as u32 {+ built += alpha * (1.0 - built) * (1.0 - built);+ }+ 1.0 - (1.0 - built.min(1.0)).powf(1.0 / n.ceil())+ }++ fn place(&mut self, p: PathPoint, distance: f32, out: &mut Vec<Stamp>) {+ let x = self.extras;+ if x.spacing_jitter > 0.0 {+ self.gap_jitter = (1.0 + x.spacing_jitter * (self.random.next() * 2.0 - 1.0)).max(0.05);+ }+ let diameter = self.diameter_at(p);+ let (_, pressure_alpha) = self.brush.factors(p.soft[0], p.soft[1]);+ // leaning fades the stamp by the square root of how far it has gone+ let fade = self.leaning(p, x.tilt_angles.opacity).sqrt() * self.brush.tilt.opacity;+ let tilt_alpha = if fade >= 0.0 { 1.0 - fade } else { 1.0 - (fade + self.brush.tilt.opacity) };+ let speed_alpha = (1.0 - x.speed_opacity * p.speed).clamp(0.0, 1.0);+ let falloff = (1.0 - distance * x.falloff / (FALLOFF_SPAN * self.diameter)).max(0.0);+ let light = 1.0 - p.soft[2].clamp(0.0, 1.0);+ let pressure_flow = (1.0 - x.pressure_flow * light).clamp(0.0, 1.0);+ // flow, pressure, tilt and speed together through the opacity range, eased; then what+ // pressure lets through (the brush's pressure flow) and the fall off+ let b = &self.brush;+ let control = b.flow.clamp(0.0, 1.0).powf(1.0 / FLOW_POWER) * pressure_alpha * tilt_alpha * speed_alpha;+ let ranged = (b.min_opacity + (b.max_opacity - b.min_opacity) * control).clamp(0.01, 1.0);+ // a capped stroke builds up towards what the pressure lets through rather than taking it+ let transfer = pressure_flow;+ let through = if self.brush.rendering == Rendering::Capped { 1.0 } else { pressure_flow };+ let mut alpha = ranged.powf(FLOW_POWER) * through * falloff;+ // (wet paint is laid stamp by stamp as it is mixed, not built up gradually)+ if self.brush.rendering == Rendering::Gradual && !self.brush.mixes_wet() {+ alpha = StrokeBuilder::gradual(alpha, diameter / self.step(p));+ }+ let shape = self.brush.shape.clone();+ let count = shape.count.clamp(1, 16);+ let dropped = (self.random.next() * x.count_jitter * count as f32) as u32;+ let (along, across) = (+ Vec2::new(self.direction.cos(), self.direction.sin()),+ Vec2::new(-self.direction.sin(), self.direction.cos()),+ );+ // leaning adds the same to the stamp's height as to its width, then the roundness tilt+ // takes it from its upright roundness towards its leaning one+ let grown = self.tilt_growth(p);+ let drawn = (diameter - grown).max(1e-3);+ let shaped =+ shape.roundness.clamp(0.05, 1.0) * (1.0 - x.pressure_roundness * (1.0 - p.soft[3].clamp(0.0, 1.0)));+ let leant = self.leaning(p, x.tilt_angles.roundness);+ let tilted = x.tilt_roundness_max * (1.0 - leant) + (1.0 - x.tilt_roundness) * leant;+ let base_roundness = (drawn * shaped + grown) / (drawn + grown) * tilted;+ for _ in 0..(count - dropped.min(count - 1)) {+ let size = 1.0 - shape.size_jitter.clamp(0.0, 1.0) * self.random.next();+ let fade = 1.0 - shape.opacity_jitter.clamp(0.0, 1.0) * self.random.next();+ let mut center = p.pos;+ if x.jitter_lateral > 0.0 {+ center =+ center + across * ((self.random.next() * 2.0 - 1.0) * x.jitter_lateral * JITTER_REACH * diameter);+ }+ if x.jitter_linear > 0.0 {+ center =+ center + along * ((self.random.next() * 2.0 - 1.0) * x.jitter_linear * JITTER_REACH * diameter);+ }+ if shape.throw > 0.0 {+ let a = self.random.next() * std::f32::consts::TAU;+ let r = self.random.next().sqrt() * shape.throw * diameter;+ center = center + Vec2::new(a.cos() * r, a.sin() * r);+ }+ let mut angle = shape.rotation - self.screen_turn + shape.follow * self.direction;+ if shape.follow_azimuth {+ angle += p.azimuth;+ }+ if shape.randomise {+ angle += self.random.next() * std::f32::consts::TAU;+ }+ if shape.scatter > 0.0 {+ angle += (self.random.next() * 2.0 - 1.0) * shape.scatter * std::f32::consts::PI;+ }+ let roundness = (base_roundness * (1.0 - x.roundness_jitter * self.random.next())).clamp(0.05, 1.0);+ let flip = [x.flip_x && self.random.next() < 0.5, x.flip_y && self.random.next() < 0.5];+ let stamp_shift = self.color_jitter(x.stamp_color);+ // light pressure and leaning shift the colour as far as their controls say+ let lean = x.tilt_angles.color.map(|theta| self.leaning(p, theta));+ let shift = [0, 1, 2].map(|k| {+ let by = |a: &[f32; 3]| a.get(k).copied().unwrap_or(0.0);+ let scale = if k == 0 { 0.5 } else { 1.0 };+ by(&stamp_shift)+ + by(&self.stroke_shift)+ + scale * (by(&x.pressure_color) * light + by(&x.tilt_color) * by(&lean))+ });+ // random numbers only for the controls in use, so strokes without them replay as before+ let secondary = (if x.stamp_secondary > 0.0 { x.stamp_secondary * self.random.next() } else { 0.0 }+ + self.stroke_secondary+ + x.pressure_secondary * light+ + x.tilt_secondary * self.leaning(p, x.tilt_angles.secondary))+ .clamp(0.0, 1.0);+ // a moving grain: deeper (or shallower) from stamp to stamp, never under its least;+ // leaning lets more of it through+ let base = self.brush.grain.depth.max(1e-3);+ let jitter = if x.grain_depth_jitter > 0.0 { x.grain_depth_jitter * self.random.next() } else { 0.0 };+ let mut depth = base * (1.0 - jitter);+ depth += (1.0 - depth) * (x.tilt_bleed * self.leaning(p, x.tilt_angles.bleed)).clamp(0.0, 1.0);+ let grain_press = (1.0 - light).clamp(0.0, 1.0);+ let depth = depth.max(x.grain_depth_min).clamp(0.0, 1.0);+ // sized with the stamp, against the stroke's size, unless cropped+ let grain_size = 1.0 + (diameter * size / self.diameter.max(1e-3) - 1.0) * (1.0 - x.grain_zoom);+ let placed = Placed {+ center,+ distance,+ diameter: diameter * size,+ alpha: alpha * fade,+ angle,+ roundness,+ flip,+ shift,+ secondary,+ grain_depth: depth / base,+ grain_size: grain_size.max(0.05),+ grain_press,+ gradation: (x.tilt_gradation * self.leaning(p, x.tilt_angles.gradation)).max(0.0).sqrt().min(1.0),+ transfer,+ };+ self.placed.push(placed);+ let stamp = self.finish_stamp(&placed, None);+ self.bounds = self.bounds.union(stamp.bounds());+ out.push(stamp);+ }+ }++ /// Where a stamp's moving grain is read from (see [`Stamp::grain_offset`]): in place on the+ /// canvas as far as the grain rolls, from wherever the stroke starts in it.+ fn grain_offset(&self, p: &Placed) -> Vec2 {+ self.grain_start + p.center * self.extras.grain_movement+ }++ fn taper(&self) -> &Taper {+ if self.pointer.has_pressure() { &self.brush.pen_taper } else { &self.brush.touch_taper }+ }++ fn finish_stamp(&self, p: &Placed, length: Option<f32>) -> Stamp {+ // a brush file's classic taper as measured; the newer kind on touch lasts a time as+ // measured, on a pen it goes by stamp diameters+ let classic = self.brush.extra.get("classic_taper").is_some_and(|&v| v >= 0.5);+ let (size, alpha) = if classic {+ self.taper().classic_factors(p.distance, length, self.paces().1)+ } else if !self.pointer.has_pressure() {+ self.taper().timed_factors(p.distance, length, self.paces())+ } else {+ self.taper().factors(p.distance, length, self.diameter)+ };+ // a blunt tip keeps part of the width where a sharp one comes to a point+ let tip = if self.pointer.has_pressure() { self.extras.pen_taper_tip } else { self.extras.touch_taper_tip };+ let size = size + (1.0 - size) * tip * 0.5;+ Stamp {+ center: p.center,+ radius: (p.diameter * size * 0.5).max(0.25),+ alpha: (p.alpha * alpha).clamp(0.0, 1.0),+ angle: p.angle,+ roundness: p.roundness,+ grain_offset: self.grain_offset(p),+ grain_press: p.grain_press,+ grain_bleed: self.extras.pressure_bleed.clamp(0.0, 1.0),+ flip: p.flip,+ shift: p.shift,+ secondary: p.secondary,+ grain_depth: p.grain_depth,+ grain_size: p.grain_size,+ gradation: p.gradation,+ taper: size.clamp(0.0, 1.0),+ transfer: p.transfer,+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::brush::{Shape, Taper, Tilt};++ fn plain() -> Brush {+ Brush {+ streamline: 0.0,+ pressure_smoothing: 0.0,+ spacing: 0.1,+ pen_taper: Taper::NONE,+ touch_taper: Taper::NONE,+ ..Brush::round_pen()+ }+ }++ fn line(n: usize, len: f32) -> Vec<Sample> {+ (0..=n).map(|i| Sample::at(Vec2::new(len * i as f32 / n as f32, 50.0), 1.0, i as f64 * 4.0)).collect()+ }++ #[test]+ fn tap_leaves_one_stamp() {+ let mut b = StrokeBuilder::new(plain(), 10.0, Pointer::Stylus);+ assert_eq!(b.add(&[Sample::at(Vec2::new(3.0, 4.0), 0.5, 0.0)]).len(), 1);+ let all = b.finish();+ assert_eq!(all.len(), 1);+ assert_eq!(all[0].center, Vec2::new(3.0, 4.0));+ }++ #[test]+ fn pressure_is_evened_out_unless_the_stroke_is_steady() {+ let b = Brush { pressure_size: 1.0, ..plain() };+ // light, then full pressure halfway along, from a pen reporting 240 times a second+ let samples: Vec<Sample> = (0..40)+ .map(|i| {+ let pressure = if i < 20 { 0.2 } else { 1.0 };+ Sample::at(Vec2::new(i as f32 * 4.0, 50.0), pressure, f64::from(i) * 1000.0 / 240.0)+ })+ .collect();+ let radius_at = |mut s: StrokeBuilder, x: f32| {+ s.add(&samples);+ s.finish().iter().find(|st| st.center.x >= x).map_or(0.0, |st| st.radius)+ };+ // just after the jump the stroke is still on its way up; drawn steady it is there at once+ let soft = radius_at(StrokeBuilder::new(b.clone(), 10.0, Pointer::Stylus), 84.0);+ let steady = radius_at(StrokeBuilder::new(b.clone(), 10.0, Pointer::Stylus).steady(), 84.0);+ assert!(soft < steady * 0.8, "{soft} {steady}");+ assert!((steady - 5.0).abs() < 1e-3);+ // and it gets there+ let late = radius_at(StrokeBuilder::new(b, 10.0, Pointer::Stylus), 150.0);+ assert!(late > 4.5, "{late}");+ }++ #[test]+ fn a_gradual_brush_reaches_in_one_pass_what_its_rule_says() {+ // ten stamps over a point, each adding 0.168 of what is left, squared+ let mut built = 0.0f32;+ for _ in 0..10 {+ built += 0.168 * (1.0 - built) * (1.0 - built);+ }+ let alpha = StrokeBuilder::gradual(0.168, 10.0);+ assert!(alpha < 0.168);+ assert!((1.0 - (1.0 - alpha).powi(10) - built).abs() < 1e-4);+ // one stamp at full opacity covers fully either way+ assert!((StrokeBuilder::gradual(1.0, 10.0) - 1.0).abs() < 1e-6);+ }++ #[test]+ fn stamps_are_evenly_spaced() {+ let mut b = StrokeBuilder::new(plain(), 10.0, Pointer::Stylus);+ b.add(&line(37, 100.0));+ let all = b.finish();+ // spacing 0.1 of the round tip's square (10 px is 0.797 of it), half a pixel, and a little+ // with the spacing: about 1.8 px, over 100 px, plus the first stamp+ let gap = 0.1 * 10.0 / crate::brushfile::ROUND_TIP_SHARE + 0.5 + (0.1 - SPACING_FLOOR) / (SPACING_SPAN / 2.0);+ assert_eq!(all.len(), (100.0 / gap) as usize + 1);+ for w in all.windows(2) {+ let d = w[0].center.distance(w[1].center);+ assert!((d - gap).abs() < 1e-3, "gap {d}");+ }+ assert!(b.bounds().x0 <= -5 && b.bounds().x1 >= 105);+ }++ #[test]+ fn spacing_carries_across_samples() {+ let mut few = StrokeBuilder::new(plain(), 10.0, Pointer::Stylus);+ few.add(&line(3, 100.0));+ let mut many = StrokeBuilder::new(plain(), 10.0, Pointer::Stylus);+ many.add(&line(97, 100.0));+ assert_eq!(few.finish().len(), many.finish().len());+ }++ #[test]+ fn pressure_scales_stamps_but_not_fingers() {+ let samples = [Sample::at(Vec2::new(0.0, 0.0), 0.0, 0.0)];+ let mut pen = StrokeBuilder::new(plain(), 10.0, Pointer::Stylus);+ let light = pen.add(&samples);+ let mut finger = StrokeBuilder::new(plain(), 10.0, Pointer::Finger);+ let touch = finger.add(&samples);+ assert!(light[0].radius < touch[0].radius);+ assert_eq!(touch[0].radius, 5.0);+ }++ #[test]+ fn streamline_smooths_a_zigzag() {+ let zigzag: Vec<Sample> = (0..200)+ .map(|i| Sample::at(Vec2::new(i as f32, if i % 2 == 0 { 0.0 } else { 10.0 }), 1.0, i as f64 * 8.0))+ .collect();+ let spread = |streamline: f32| {+ let mut b = StrokeBuilder::new(Brush { streamline, ..plain() }, 4.0, Pointer::Stylus);+ b.add(&zigzag);+ let s = b.stamps();+ let ys: Vec<f32> = s[s.len() / 2..].iter().map(|s| s.center.y).collect();+ ys.iter().cloned().fold(f32::MIN, f32::max) - ys.iter().cloned().fold(f32::MAX, f32::min)+ };+ assert!(spread(0.9) < spread(0.0) * 0.5);+ }++ #[test]+ fn an_exact_path_is_not_smoothed() {+ let zigzag: Vec<Sample> = (0..200)+ .map(|i| Sample::at(Vec2::new(i as f32, if i % 2 == 0 { 0.0 } else { 10.0 }), 1.0, i as f64 * 8.0))+ .collect();+ let brush = Brush { streamline: 0.9, ..plain() };+ let mut b = StrokeBuilder::new(brush, 4.0, Pointer::Stylus).exact_path();+ b.add(&zigzag);+ let ys: Vec<f32> = b.stamps().iter().map(|s| s.center.y).collect();+ assert!(ys.iter().any(|&y| y > 9.9) && ys.iter().any(|&y| y < 0.1));+ }++ #[test]+ fn finish_catches_up_and_tapers_the_end() {+ let brush =+ Brush { streamline: 0.9, pen_taper: Taper { start: 0.0, end: 0.5, size: 1.0, opacity: 0.0 }, ..plain() };+ let mut b = StrokeBuilder::new(brush, 4.0, Pointer::Stylus);+ b.add(&line(50, 300.0));+ let live_end = b.stamps().last().unwrap().center;+ let all = b.finish();+ let end = all.last().unwrap();+ assert!(end.center.distance(Vec2::new(300.0, 50.0)) < 1.0);+ assert!(live_end.x < 299.0, "streamline lags while drawing");+ assert!(end.radius < 0.5);+ assert!(all[all.len() / 2].radius > 1.9);+ }++ #[test]+ fn a_touch_stroke_tapers_over_what_it_covers_in_the_taper_s_time() {+ let brush = Brush { touch_taper: Taper { start: 0.5, end: 0.5, size: 1.0, opacity: 0.0 }, ..plain() };+ // 600 px drawn in samples `ms` apart: the faster, the longer the tapered ends+ let near_end = |ms: f64| {+ let mut b = StrokeBuilder::new(brush.clone(), 20.0, Pointer::Finger);+ let samples: Vec<Sample> =+ (0..=60).map(|i| Sample::at(Vec2::new(i as f32 * 10.0, 50.0), 1.0, i as f64 * ms)).collect();+ b.add(&samples);+ let all = b.finish();+ let at = |x: f32| {+ all.iter().min_by(|a, b| (a.center.x - x).abs().total_cmp(&(b.center.x - x).abs())).unwrap().radius+ };+ (at(600.0 - 50.0), at(300.0))+ };+ let (fast, full) = near_end(8.0);+ let (slow, _) = near_end(32.0);+ assert!(fast < full * 0.8, "{fast} {full}");+ assert!((slow - full).abs() < 1e-3, "{slow} {full}");+ }++ #[test]+ fn bad_samples_are_skipped() {+ let mut b = StrokeBuilder::new(plain(), 10.0, Pointer::Stylus);+ assert!(b.add(&[Sample::at(Vec2::new(f32::NAN, 0.0), 1.0, 0.0)]).is_empty());+ assert_eq!(b.finish().len(), 0);+ }++ #[test]+ fn scatter_turns_each_stamp_at_random_in_place() {+ let shape = Shape { scatter: 1.0, ..Shape::default() };+ let mut b = StrokeBuilder::new(Brush { shape, ..plain() }, 10.0, Pointer::Stylus);+ let stamps = b.add(&line(20, 200.0));+ assert!(stamps.iter().all(|s| (s.center.y - 50.0).abs() < 1e-3), "on the path");+ let turned = stamps.iter().filter(|s| s.angle.abs() > 0.5).count();+ assert!(turned > stamps.len() / 3, "{turned} of {}", stamps.len());+ assert!(stamps.iter().all(|s| s.angle.abs() <= std::f32::consts::PI + 1e-3));+ }++ #[test]+ fn shape_placement_rotates_scatters_and_counts() {+ let shape = Shape { follow: 1.0, throw: 1.0, count: 3, size_jitter: 0.5, roundness: 0.4, ..Shape::default() };+ let mut b = StrokeBuilder::new(Brush { shape, ..plain() }, 10.0, Pointer::Stylus);+ // a vertical line: the stroke heads +y, so the stamps turn a quarter+ let down: Vec<Sample> =+ (0..=10).map(|i| Sample::at(Vec2::new(50.0, i as f32 * 10.0), 1.0, i as f64 * 4.0)).collect();+ let stamps = b.add(&down);+ assert_eq!(stamps.len() % 3, 0, "three per step");+ let later = &stamps[stamps.len() - 1];+ assert!((later.angle - std::f32::consts::FRAC_PI_2).abs() < 1e-3);+ assert_eq!(later.roundness, 0.4);+ assert!(stamps.iter().any(|s| (s.center.x - 50.0).abs() > 0.5), "thrown off the path");+ assert!(+ stamps.iter().all(|s| s.radius <= 5.0 + 1e-4 && s.radius >= 2.5 - 1e-4),+ "jittered smaller, never larger"+ );+ // the same seed replays the same stroke+ let mut again = StrokeBuilder::new(Brush { shape: b.brush().shape.clone(), ..plain() }, 10.0, Pointer::Stylus);+ assert_eq!(again.add(&down), stamps);+ }++ #[test]+ fn tilt_widens_the_pen_but_not_fingers() {+ let angle = 0.1 * std::f32::consts::FRAC_PI_2;+ let brush =+ Brush { tilt: Tilt { angle, size: 0.1, opacity: 0.0 }, pressure_size: 0.0, max_size: 500.0, ..plain() };+ let mut tilted = Sample::at(Vec2::new(0.0, 0.0), 1.0, 0.0);+ tilted.tilt = crate::brush::FLAT_TILT;+ let pen = StrokeBuilder::new(brush.clone(), 10.0, Pointer::Stylus).preview(&[tilted]);+ let finger = StrokeBuilder::new(brush.clone(), 10.0, Pointer::Finger).preview(&[tilted]);+ // a dab takes all of the lean's growth: the tilt size, as far as the lean has gone+ let grown = 0.1 * Tilt::reach(crate::brush::FLAT_TILT, 0.1) * brush.size_unit();+ assert!((pen[0].radius - (10.0 + grown) / 2.0).abs() < 1e-3, "{}", pen[0].radius);+ assert_eq!(finger[0].radius, 5.0);+ // upright, next to nothing+ tilted.tilt = 0.0;+ let upright = StrokeBuilder::new(brush, 10.0, Pointer::Stylus).preview(&[tilted]);+ assert!(upright[0].radius < 5.1);+ }++ #[test]+ fn a_leaning_pen_grows_across_the_stroke_shades_and_rounds_the_stamp() {+ let flat = |x: f32, azimuth: f32| {+ let mut s = Sample::at(Vec2::new(x, 0.0), 1.0, f64::from(x));+ s.tilt = crate::brush::FLAT_TILT;+ s.azimuth = azimuth;+ s+ };+ let stamps = |settings: &[(&str, f32)], azimuth: f32| {+ let angle = 0.1 * std::f32::consts::FRAC_PI_2;+ let mut b =+ Brush { tilt: Tilt { angle, size: 0.1, opacity: 0.0 }, pressure_size: 0.0, max_size: 500.0, ..plain() };+ for (k, v) in settings {+ b.set_setting(k, *v);+ }+ let stroke = [flat(0.0, azimuth), flat(20.0, azimuth), flat(40.0, azimuth)];+ StrokeBuilder::new(b, 10.0, Pointer::Stylus).preview(&stroke)+ };+ // drawn along x: leaning along it (orientation pointing right) grows nothing, leaning+ // across it (pointing up) all of it; without compression either way+ let along = stamps(&[], std::f32::consts::FRAC_PI_2);+ let across = stamps(&[], 0.0);+ let last = |v: &[Stamp]| v.last().map_or(0.0, |s| s.radius);+ assert!((last(&along) - 5.0).abs() < 0.01, "{}", last(&along));+ assert!(last(&across) > 10.0, "{}", last(&across));+ let loose = stamps(&[("tilt_size_compression", 0.0)], std::f32::consts::FRAC_PI_2);+ assert!((last(&loose) - last(&across)).abs() < 0.01);+ // shading by the square root of the gradation as far as the lean has gone; the+ // roundness tilt takes the stamp to its leaning roundness as far+ let reach = Tilt::reach(crate::brush::FLAT_TILT, 0.1);+ let shaded = stamps(&[("tilt_gradation", 0.6), ("tilt_size", 0.0)], 0.0);+ assert!((shaded[0].gradation - (0.6 * reach).sqrt()).abs() < 1e-4, "{}", shaded[0].gradation);+ let rounded = stamps(&[("tilt_roundness", 0.5), ("tilt_size", 0.0)], 0.0);+ assert!((rounded[0].roundness - (1.0 - 0.5 * reach)).abs() < 1e-4, "{}", rounded[0].roundness);+ }++ #[test]+ fn the_studios_dynamics_shape_the_stroke() {+ let with = |key: &str, v: f32| {+ let mut b = plain();+ b.set_setting(key, v);+ let mut s = StrokeBuilder::new(b, 10.0, Pointer::Stylus);+ s.add(&line(50, 200.0));+ s.finish()+ };+ let base = with("spacing", 0.1);+ // jitter moves stamps off the line+ assert!(with("jitter_lateral", 1.0).iter().any(|s| (s.center.y - 50.0).abs() > 2.0));+ assert!(base.iter().all(|s| (s.center.y - 50.0).abs() < 1e-3));+ // spacing jitter changes how many stamps there are+ assert_ne!(with("spacing_jitter", 1.0).len(), base.len());+ // fall off fades the far end+ let faded = with("falloff", 1.0);+ assert!(faded.last().unwrap().alpha < faded[0].alpha * 0.5);+ // fast input (600 px in 200 ms: 50 px a frame) thins the stroke with speed size+ let fast = |b: Brush| {+ let mut s = StrokeBuilder::new(b, 10.0, Pointer::Stylus);+ s.add(&line(50, 600.0));+ s.finish()+ };+ let base = fast(plain());+ let mut b = plain();+ b.set_setting("speed_size", 1.0);+ let thin = fast(b);+ assert!(thin[thin.len() / 2].radius < base[base.len() / 2].radius);+ // and thinner still when a shorter distance counts as fast+ let mut b = plain();+ b.set_setting("speed_size", 1.0);+ let mut s = StrokeBuilder::new(b, 10.0, Pointer::Stylus)+ .with_input(InputSettings { speed_distance: 0.25, ..InputSettings::default() });+ s.add(&line(50, 600.0));+ let thinner = s.finish();+ // and not at all when slow (200 px in 200 ms) or seen small (a quarter point a pixel)+ let mut b = plain();+ b.set_setting("speed_size", 1.0);+ let mut s = StrokeBuilder::new(b.clone(), 10.0, Pointer::Stylus);+ s.add(&line(50, 200.0));+ assert!((s.finish()[25].radius - base[base.len() / 2].radius).abs() < 1e-4);+ let mut s = StrokeBuilder::new(b, 10.0, Pointer::Stylus).seen_at(0.25);+ s.add(&line(50, 600.0));+ assert!((s.finish()[40].radius - base[base.len() / 2].radius).abs() < 1e-4);+ assert!(thinner[thinner.len() / 2].radius < thin[thin.len() / 2].radius);+ // roundness falls with light pressure+ let mut b = plain();+ b.set_setting("pressure_roundness", 1.0);+ let light = StrokeBuilder::new(b, 10.0, Pointer::Stylus).preview(&[Sample::at(Vec2::new(0.0, 0.0), 0.2, 0.0)]);+ assert!(light[0].roundness < 0.3);+ // stabilisation averages a zigzag away+ let zigzag: Vec<Sample> = (0..100)+ .map(|i| Sample::at(Vec2::new(i as f32 * 2.0, if i % 2 == 0 { 0.0 } else { 20.0 }), 1.0, i as f64 * 8.0))+ .collect();+ let mut b = plain();+ b.set_setting("stabilization", 1.0);+ let mut s = StrokeBuilder::new(b, 4.0, Pointer::Stylus);+ s.add(&zigzag);+ let ys: Vec<f32> = s.stamps()[40..].iter().map(|s| s.center.y).collect();+ let spread = ys.iter().cloned().fold(f32::MIN, f32::max) - ys.iter().cloned().fold(f32::MAX, f32::min);+ assert!(spread < 5.0, "{spread}");+ }++ #[test]+ fn more_of_the_studios_dynamics_shape_the_stroke() {+ let stroke = |settings: &[(&str, f32)], pressure: f32, taper: Taper| {+ let mut b = Brush { pen_taper: taper, ..plain() };+ b.grain.image = Some(0);+ b.grain.mode = crate::brush::GrainMode::Moving;+ b.grain.depth = 0.5;+ for &(k, v) in settings {+ b.set_setting(k, v);+ }+ let mut s = StrokeBuilder::new(b, 10.0, Pointer::Stylus);+ let samples: Vec<Sample> =+ (0..=50).map(|i| Sample::at(Vec2::new(i as f32 * 4.0, 50.0), pressure, i as f64 * 4.0)).collect();+ s.add(&samples);+ s.finish()+ };+ let mid = |v: &[Stamp]| v[v.len() / 2];+ // flow falls with light pressure+ let plain_light = mid(&stroke(&[], 0.3, Taper::NONE));+ let flow_light = mid(&stroke(&[("pressure_flow", 1.0)], 0.3, Taper::NONE));+ assert!(flow_light.alpha < plain_light.alpha * 0.5, "{} {}", flow_light.alpha, plain_light.alpha);+ // a blunt tip keeps width at the stroke's ends+ let taper = Taper { start: 0.3, end: 0.3, size: 1.0, opacity: 0.0 };+ let sharp = stroke(&[], 1.0, taper.clone())[0].radius;+ let blunt = stroke(&[("pen_taper_tip", 1.0)], 1.0, taper)[0].radius;+ assert!(blunt > sharp + 1.0, "{blunt} {sharp}");+ // the secondary colour: by light pressure, and jittered per stamp+ assert_eq!(mid(&stroke(&[], 0.3, Taper::NONE)).secondary, 0.0);+ assert!((mid(&stroke(&[("pressure_secondary", 1.0)], 0.3, Taper::NONE)).secondary - 0.7).abs() < 0.05);+ let jittered = stroke(&[("stamp_secondary", 1.0)], 1.0, Taper::NONE);+ assert!(jittered.iter().any(|s| s.secondary > 0.5) && jittered.iter().any(|s| s.secondary < 0.5));+ // a moving grain: filled in by pressing harder, never under its least, jittered+ assert!((mid(&stroke(&[], 0.3, Taper::NONE)).grain_depth - 1.0).abs() < 1e-5);+ let light = mid(&stroke(&[("pressure_bleed", 1.0)], 0.3, Taper::NONE));+ let hard = mid(&stroke(&[("pressure_bleed", 1.0)], 0.9, Taper::NONE));+ assert!((light.grain_press - 0.3).abs() < 0.05 && (hard.grain_press - 0.9).abs() < 0.05);+ assert!((hard.grain_depth - 1.0).abs() < 1e-5 && (hard.grain_bleed - 1.0).abs() < 1e-5);+ assert_eq!(mid(&stroke(&[], 0.9, Taper::NONE)).grain_bleed, 0.0);+ assert!(+ stroke(&[("grain_depth_jitter", 1.0), ("grain_depth_min", 0.4)], 1.0, Taper::NONE)+ .iter()+ .all(|s| s.grain_depth >= 0.8 - 1e-4)+ );+ // sized with the stamp when it follows the size: a lighter, smaller stamp, a smaller grain+ let pressured = |zoom: f32| {+ let mut b = plain();+ b.pressure_size = 1.0;+ b.set_setting("grain_zoom", zoom);+ let mut s = StrokeBuilder::new(b, 10.0, Pointer::Stylus);+ s.add(&[Sample::at(Vec2::new(0.0, 0.0), 0.5, 0.0)]);+ s.finish()[0].grain_size+ };+ assert!((pressured(1.0) - 1.0).abs() < 1e-5);+ assert!(pressured(0.0) < 0.8);+ // the brush's own motion filtering smooths as the app's does+ let zigzag: Vec<Sample> = (0..60)+ .map(|i| Sample::at(Vec2::new(i as f32 * 2.0, if i % 2 == 0 { 0.0 } else { 20.0 }), 1.0, i as f64 * 8.0))+ .collect();+ let spread = |filtering: f32| {+ let mut b = plain();+ b.set_setting("motion_filtering", filtering);+ let mut s = StrokeBuilder::new(b, 4.0, Pointer::Stylus);+ s.add(&zigzag);+ let ys: Vec<f32> = s.stamps()[20..].iter().map(|s| s.center.y).collect();+ ys.iter().cloned().fold(f32::MIN, f32::max) - ys.iter().cloned().fold(f32::MAX, f32::min)+ };+ assert!(spread(1.0) < spread(0.0) * 0.5, "{} {}", spread(1.0), spread(0.0));+ }++ #[test]+ fn a_brush_oriented_to_the_screen_turns_back_with_the_canvas() {+ let turned = |orient: f32| {+ let mut b = plain();+ b.set_setting("orient_to_screen", orient);+ let mut s = StrokeBuilder::new(b, 10.0, Pointer::Stylus).on_view_turned(0.5);+ s.add(&[Sample::at(Vec2::new(0.0, 0.0), 1.0, 0.0)]);+ s.finish()[0].angle+ };+ assert_eq!(turned(0.0), 0.0);+ assert!((turned(1.0) + 0.5).abs() < 1e-6);+ }++ #[test]+ fn preview_does_not_change_the_stroke() {+ let mut b = StrokeBuilder::new(plain(), 10.0, Pointer::Stylus);+ b.add(&line(10, 50.0));+ let before = b.stamp_count();+ let ahead = b.preview(&[Sample::at(Vec2::new(80.0, 50.0), 1.0, 100.0)]);+ assert!(!ahead.is_empty());+ assert_eq!(b.stamp_count(), before);+ }++ #[test]+ fn the_apps_input_settings_smooth_and_curve_pressure() {+ let brush = Brush::round_pen();+ let samples: Vec<Sample> = (0..120)+ .map(|i| {+ let x = i as f32 * 4.0;+ // a shake up and down every other point+ let y = if i % 2 == 0 { 0.0 } else { 6.0 };+ let mut s = Sample::at(Vec2::new(x, y), 0.5, f64::from(i) * 8.0);+ s.tilt = 0.0;+ s+ })+ .collect();+ let spread = |input: InputSettings| {+ let mut b = StrokeBuilder::new(brush.clone(), 4.0, Pointer::Stylus).with_input(input);+ let stamps = b.add(&samples);+ // once settled: the last stamps+ let ys: Vec<f32> = stamps.iter().rev().take(15).map(|s| s.center.y).collect();+ ys.iter().cloned().fold(f32::MIN, f32::max) - ys.iter().cloned().fold(f32::MAX, f32::min)+ };+ let plain = spread(InputSettings::default());+ let filtered = spread(InputSettings { motion_filtering: 1.0, ..InputSettings::default() });+ let expressive =+ spread(InputSettings { motion_filtering: 1.0, motion_expression: 1.0, ..InputSettings::default() });+ assert!(filtered < plain * 0.5, "{filtered} vs {plain}");+ assert!(expressive > filtered, "{expressive} vs {filtered}");+ // a curve that doubles light pressure makes bigger stamps+ let curved = InputSettings {+ pressure_curve: Curve::new(&[Vec2::new(0.0, 0.0), Vec2::new(0.5, 1.0), Vec2::new(1.0, 1.0)]),+ ..InputSettings::default()+ };+ let mut a = StrokeBuilder::new(brush.clone(), 20.0, Pointer::Stylus);+ let mut b = StrokeBuilder::new(brush, 20.0, Pointer::Stylus).with_input(curved);+ let (sa, sb) = (a.add(&samples[..1]), b.add(&samples[..1]));+ assert!(sb[0].radius >= sa[0].radius, "{} vs {}", sb[0].radius, sa[0].radius);+ }++ #[test]+ fn a_moving_grain_rolls_as_far_as_its_movement_says_and_may_start_anywhere() {+ let offsets = |movement: f32, jitter: f32, seed: u32| {+ let mut brush = Brush::round_pen();+ brush.set_setting("grain_movement", movement);+ brush.set_setting("grain_offset_jitter", jitter);+ let mut b = StrokeBuilder::with_seed(brush, 4.0, Pointer::Stylus, seed);+ let mut stamps = b.add(&line(20, 100.0));+ stamps.extend(b.finish());+ stamps.iter().map(|s| s.grain_offset).collect::<Vec<_>>()+ };+ // rolling: the grain moves with the stroke; static: it stays put under the tip+ let rolling = offsets(1.0, 0.0, 7);+ let first = rolling.first().copied().unwrap_or(Vec2::ZERO);+ let last = rolling.last().copied().unwrap_or(Vec2::ZERO);+ assert!(last.x - first.x > 50.0, "{first:?} {last:?}");+ assert!(offsets(0.0, 0.0, 7).iter().all(|o| *o == Vec2::ZERO));+ // offset jitter starts each stroke somewhere else in the grain+ let a = offsets(0.0, 1.0, 7)[0];+ let b = offsets(0.0, 1.0, 8)[0];+ assert_ne!(a, b);+ assert!(a.x >= 0.0 && a.x <= GRAIN_JITTER_SPAN && a.y >= 0.0 && a.y <= GRAIN_JITTER_SPAN);+ }+}diff --git a/crates/engine/src/studio.rs b/crates/engine/src/studio.rsnew file mode 100644index 0000000..d7ba82e--- /dev/null+++ b/crates/engine/src/studio.rs@@ -0,0 +1,445 @@+//! The brush settings as the brush studio shows them: each control by its key, holding what the+//! control shows (0..1; −1..1 for the controls that go both ways; 0 or 1 for a switch; the index+//! for a choice). Controls the engine does not draw yet keep their values with the brush.++use std::f32::consts::PI;++use crate::brush::{Brush, FLOW_POWER, GrainMode, Rendering};+use crate::document::BlendMode;++/// The most size (in brush-file units, see [`Brush::size_unit`]) the size controls can reach, for+/// a brush spaced at least [`ROOMY_SPACING`] apart; a control's place is the size's share of the+/// brush's own most size (see [`Brush::most_size`]) to the power 1/2.2.+pub const MOST_SIZE: f32 = 16.0;+/// The spacing (as files keep it) from which a brush may be as big as [`MOST_SIZE`]; closer+/// spaced brushes are kept smaller, down to 1 unit at none.+pub const ROOMY_SPACING: f32 = 0.02;+const SIZE_CONTROL_CURVE: f32 = 2.2;+/// The largest grain tile (canvas pixels) the grain scale control reaches.+pub const MAX_GRAIN_SCALE: f32 = 1024.0;+/// The smallest grain tile, canvas pixels.+const LEAST_GRAIN_SCALE: f32 = 4.0;+/// The most stamps placed at each step.+pub const MAX_COUNT: u32 = 16;++/// Where the controls kept in the brush's `extra` start (the others start where the brush is);+/// any control not listed starts at 0.+const STARTS: &[(&str, f32)] = &[+ ("pen_tip_animation", 1.0),+ // leaning grows the stamp only as the stroke runs across the lean; the stamp as round as+ // its shape until the roundness tilt takes it+ ("tilt_size_compression", 1.0),+ ("tilt_roundness_max", 1.0),+ // the newer spacing (see [`Brush::spacing`])+ ("spacing_version", 1.0),+ ("classic_taper", 1.0),+ ("shape_filtering", 2.0),+ ("grain_movement", 1.0),+ ("grain_zoom", 1.0),+ // grain and burnt edges multiply+ ("grain_blend", 1.0),+ ("burnt_blend", 1.0),+ ("grain_offset_jitter", 1.0),+ ("grain_filtering", 2.0),+ ("grain_follows_camera", 1.0),+ ("wet_pull", 0.75),+ ("tilt_size_compression", 1.0),+ ("hover_pressure", 0.44),+ ("hover_fill", 1.0),+ ("smudge_pull", 0.75),+ ("preview_size", 0.09),+ // the control's middle: the file's 1, of 0 to 2+ ("preview_pressure_scale", 0.5),+ // the hover outline in contrasting rings+ ("cursor_outline", 1.0),+];++/// The controls drawn from the brush's own fields (the others are kept in its `extra`).+pub const DRAWN: [&str; 37] = [+ "spacing",+ "streamline",+ "streamline_pressure",+ "pen_taper_start",+ "pen_taper_end",+ "pen_taper_size",+ "pen_taper_opacity",+ "touch_taper_start",+ "touch_taper_end",+ "touch_taper_size",+ "touch_taper_opacity",+ "input_style",+ "shape_rotation",+ "scatter",+ "count",+ "randomized",+ "roundness",+ "shape_angle",+ "grain_behavior",+ "grain_scale",+ "grain_depth",+ "rendering_mode",+ "flow",+ "jitter_size",+ "jitter_opacity",+ "pressure_size",+ "pressure_opacity",+ "tilt_angle",+ "tilt_opacity",+ "tilt_size",+ "max_size",+ "min_size",+ "max_opacity",+ "min_opacity",+ "smudge_pull",+ "preview_size",+ "wet_pull",+];++/// Spacing as the studio's control shows it: the gap between stamp centres, in stamp diameters,+/// rises with the control to the power [`SPACING_CURVE`], from [`SPACING_FLOOR`] at none to almost+/// three diameters at the full control (so most of the control is spent on close spacings).+pub(crate) const SPACING_FLOOR: f32 = 0.0083;+pub(crate) const SPACING_SPAN: f32 = 2.0 * std::f32::consts::SQRT_2;+const SPACING_CURVE: f32 = 2.2;++impl Brush {+ /// The most size (brush-file units) the brush may have: [`MOST_SIZE`] when spaced at least+ /// [`ROOMY_SPACING`] apart, less the closer its stamps are (so a stroke stays a manageable+ /// number of stamps), 1 at no spacing.+ pub fn most_size(&self) -> f32 {+ let spacing = ((self.spacing - SPACING_FLOOR) / (SPACING_SPAN / 2.0)).max(0.0);+ if spacing <= 0.0 { 1.0 } else { 1.0 + (MOST_SIZE - 1.0) * (spacing / ROOMY_SPACING).min(1.0) }+ }++ /// Whether the brush mixes its paint wet with what is under it: a blending rendering mode+ /// (Uniform or Intense Blending; glazes never mix) with some dilution (without water the+ /// other wet settings do nothing).+ pub fn mixes_wet(&self) -> bool {+ self.setting("wet_dilution") > 0.0 && self.setting("rendering_mode") >= 3.5+ }++ /// Whether the brush blends (Uniform or Intense Blending, mixing as it goes): its opacity+ /// slider lightens each stamp instead of capping the stroke.+ pub fn blends(&self) -> bool {+ self.setting("rendering_mode") >= 3.5+ }++ fn has_wet_mix(&self) -> bool {+ self.extra.contains_key("wet_pull") || self.setting("wet_charge") > 0.0 || self.setting("wet_dilution") > 0.0+ }++ /// A size control's place for `size` canvas pixels.+ fn size_control(&self, size: f32) -> f32 {+ (size / self.size_unit() / self.most_size()).clamp(0.0, 1.0).powf(1.0 / SIZE_CONTROL_CURVE)+ }++ /// The size (canvas pixels) at a size control's place.+ fn size_from_control(&self, place: f32) -> f32 {+ self.most_size() * place.clamp(0.0, 1.0).powf(SIZE_CONTROL_CURVE) * self.size_unit()+ }+}++fn flag(on: bool) -> f32 {+ if on { 1.0 } else { 0.0 }+}++impl Brush {+ /// The value the control `key` shows.+ pub fn setting(&self, key: &str) -> f32 {+ match key {+ "spacing" => ((self.spacing - SPACING_FLOOR).max(0.0) / SPACING_SPAN).powf(1.0 / SPACING_CURVE),+ "streamline" => self.streamline,+ "streamline_pressure" => self.pressure_smoothing,+ "pen_taper_start" => self.pen_taper.start,+ "pen_taper_end" => self.pen_taper.end,+ "pen_taper_size" => self.pen_taper.size,+ "pen_taper_opacity" => self.pen_taper.opacity,+ "touch_taper_start" => self.touch_taper.start,+ "touch_taper_end" => self.touch_taper.end,+ "touch_taper_size" => self.touch_taper.size,+ "touch_taper_opacity" => self.touch_taper.opacity,+ "input_style" => self.extra_or("input_style", flag(self.shape.follow_azimuth)),+ "shape_rotation" => self.shape.follow,+ "scatter" => self.shape.scatter / 2.0,+ "count" => (self.shape.count.clamp(1, MAX_COUNT) - 1) as f32 / (MAX_COUNT - 1) as f32,+ "randomized" => flag(self.shape.randomise),+ "roundness" => self.shape.roundness,+ // the shape's own turn, as a share of a full turn+ "shape_angle" => (self.shape.rotation / std::f32::consts::TAU).rem_euclid(1.0),+ "grain_behavior" => flag(self.grain.mode == GrainMode::Texturized),+ // the smallest tile reads as none (a file's 0)+ "grain_scale" => {+ if self.grain.scale <= LEAST_GRAIN_SCALE {+ 0.0+ } else {+ self.grain.scale / MAX_GRAIN_SCALE+ }+ }+ "grain_depth" => self.grain.depth,+ "rendering_mode" => {+ // a brush of ours (no mode kept) as the mode it draws like+ let drawn = match self.rendering {+ Rendering::Strongest => 0.0,+ Rendering::BuildUp if self.has_wet_mix() => 5.0,+ Rendering::BuildUp => 2.0,+ Rendering::Gradual => 3.0,+ Rendering::Capped => 1.0,+ };+ self.extra_or("rendering_mode", drawn)+ }+ "flow" => self.flow.max(0.0).powf(1.0 / FLOW_POWER),+ "jitter_size" => self.shape.size_jitter,+ "jitter_opacity" => self.shape.opacity_jitter,+ "pressure_size" => self.pressure_size,+ "pressure_opacity" => self.pressure_opacity,+ "tilt_angle" => self.tilt.angle / (PI / 2.0),+ // each tilt control's own angle, else the tilt angle's+ "opacity_tilt_angle"+ | "size_tilt_angle"+ | "gradation_tilt_angle"+ | "bleed_tilt_angle"+ | "roundness_tilt_angle"+ | "hue_tilt_angle"+ | "saturation_tilt_angle"+ | "brightness_tilt_angle"+ | "secondary_tilt_angle" => self.extra_or(key, self.tilt.angle / (PI / 2.0)),+ "tilt_opacity" => self.tilt.opacity,+ "tilt_size" => self.tilt.size,+ "max_size" => self.size_control(self.max_size),+ // read only: the size the size controls reach at their end, for showing them+ "most_size" => self.most_size(),+ "min_size" => self.size_control(self.min_size),+ "max_opacity" => self.max_opacity,+ "min_opacity" => self.min_opacity,+ _ => self.extra_or(key, STARTS.iter().find(|(k, _)| *k == key).map_or(0.0, |&(_, v)| v)),+ }+ }++ /// Sets each control of `settings`, the sizes last: the spacing sets how big the brush may be,+ /// so where their controls sit.+ pub fn set_settings<'a>(&mut self, settings: impl IntoIterator<Item = (&'a str, f32)>) {+ let (sizes, rest): (Vec<_>, Vec<_>) =+ settings.into_iter().partition(|(k, _)| matches!(*k, "max_size" | "min_size"));+ for (k, v) in rest.into_iter().chain(sizes) {+ self.set_setting(k, v);+ }+ }++ /// Sets the control `key` to `value` (kept to the control's range); not a number does nothing.+ pub fn set_setting(&mut self, key: &str, value: f32) {+ if !value.is_finite() {+ return;+ }+ let unit = value.clamp(0.0, 1.0);+ let both = value.clamp(-1.0, 1.0);+ let on = value >= 0.5;+ match key {+ "spacing" => self.spacing = SPACING_FLOOR + SPACING_SPAN * unit.powf(SPACING_CURVE),+ "streamline" => self.streamline = unit,+ "streamline_pressure" => self.pressure_smoothing = unit,+ "pen_taper_start" => self.pen_taper.start = unit,+ "pen_taper_end" => self.pen_taper.end = unit,+ "pen_taper_size" => self.pen_taper.size = unit,+ "pen_taper_opacity" => self.pen_taper.opacity = unit,+ "touch_taper_start" => self.touch_taper.start = unit,+ "touch_taper_end" => self.touch_taper.end = unit,+ "touch_taper_size" => self.touch_taper.size = unit,+ "touch_taper_opacity" => self.touch_taper.opacity = unit,+ "input_style" => {+ // touch only, azimuth, or azimuth and barrel roll (which turns with the azimuth)+ let style = value.round().clamp(0.0, 2.0);+ self.shape.follow_azimuth = style >= 1.0;+ self.extra.insert(key.to_owned(), style);+ }+ // how far the stamp turns with the stroke (its fixed angle is the shape's own)+ "shape_rotation" => self.shape.follow = both,+ "scatter" => self.shape.scatter = unit * 2.0,+ "count" => self.shape.count = 1 + (unit * (MAX_COUNT - 1) as f32).round() as u32,+ "randomized" => self.shape.randomise = on,+ "roundness" => self.shape.roundness = unit.max(0.05),+ "shape_angle" => self.shape.rotation = value.rem_euclid(1.0) * std::f32::consts::TAU,+ "grain_behavior" => self.grain.mode = if on { GrainMode::Texturized } else { GrainMode::Moving },+ "grain_scale" => self.grain.scale = (unit * MAX_GRAIN_SCALE).max(LEAST_GRAIN_SCALE),+ "grain_depth" => self.grain.depth = unit,+ "rendering_mode" => {+ // Light Glaze keeps the strongest stamp; Heavy Glaze and Uniform Blending build up+ // gradually; the others build up+ let mode = value.round().clamp(0.0, 5.0);+ self.rendering = match mode as u8 {+ 0 => Rendering::Strongest,+ 1 => Rendering::Capped,+ 3 | 4 => Rendering::Gradual,+ _ => Rendering::BuildUp,+ };+ self.extra.insert(key.to_owned(), mode);+ }+ // blend modes are kept by number (as the layers' are numbered)+ "blend_mode" | "grain_blend" | "burnt_blend" => {+ self.extra.insert(key.to_owned(), value.round().clamp(0.0, BlendMode::MAX_ID as f32));+ }+ "flow" => self.flow = unit.powf(FLOW_POWER),+ "jitter_size" => self.shape.size_jitter = unit,+ "jitter_opacity" => self.shape.opacity_jitter = unit,+ "pressure_size" => self.pressure_size = both,+ "pressure_opacity" => self.pressure_opacity = both,+ "tilt_angle" => self.tilt.angle = unit * PI / 2.0,+ "tilt_opacity" => self.tilt.opacity = unit,+ "tilt_size" => self.tilt.size = unit,+ // the least size is kept no larger than the most+ "max_size" => {+ self.max_size = self.size_from_control(unit).max(0.5);+ self.min_size = self.min_size.min(self.max_size);+ }+ "min_size" => self.min_size = self.size_from_control(unit).min(self.max_size),+ "max_opacity" => self.max_opacity = unit,+ "min_opacity" => self.min_opacity = unit,+ // choices of three, kept by their place in the list+ "shape_filtering" | "grain_filtering" | "cursor_outline" | "hover_fill" | "relative_to_stroke" => {+ self.extra.insert(key.to_owned(), value.round().clamp(0.0, 2.0));+ }+ _ => {+ self.extra.insert(key.to_owned(), both);+ }+ }+ }++ /// Every control whose value differs from `shipped`'s, with its value: those drawn from the+ /// brush's fields and those kept with it.+ pub fn changes_from(&self, shipped: &Brush) -> Vec<(String, f32)> {+ let mut keys: Vec<&str> = DRAWN.to_vec();+ keys.extend(self.extra.keys().map(String::as_str));+ keys.sort_unstable();+ keys.dedup();+ keys.into_iter()+ .map(|k| (k, self.setting(k)))+ .filter(|&(k, v)| (v - shipped.setting(k)).abs() > 1e-6)+ .map(|(k, v)| (k.to_owned(), v))+ .collect()+ }++ fn extra_or(&self, key: &str, start: f32) -> f32 {+ self.extra.get(key).copied().unwrap_or(start)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn controls_round_trip() {+ let mut b = Brush::round_pen();+ for (key, v) in [+ ("spacing", 0.3),+ ("streamline", 0.66),+ ("pen_taper_size", 0.12),+ ("shape_rotation", -0.5),+ ("scatter", 0.25),+ ("roundness", 0.4),+ ("grain_scale", 0.25),+ ("flow", 0.8),+ ("pressure_size", -0.3),+ ("tilt_angle", 0.5),+ ("max_size", 0.23),+ ("min_size", 0.02),+ ("max_opacity", 0.9),+ ("wet_pull", 0.4),+ ("hue_jitter", 0.1),+ ] {+ b.set_setting(key, v);+ assert!((b.setting(key) - v).abs() < 1e-4, "{key}: {} != {v}", b.setting(key));+ }+ b.set_setting("count", 3.0 / 15.0);+ assert_eq!(b.shape.count, 4);+ b.set_setting("rendering_mode", 4.0);+ assert_eq!((b.rendering, b.setting("rendering_mode")), (Rendering::Gradual, 4.0));+ b.set_setting("grain_behavior", 1.0);+ assert_eq!(b.grain.mode, GrainMode::Texturized);+ // the smallest grain tile reads as none, as set+ b.set_setting("grain_scale", 0.0);+ assert_eq!((b.grain.scale, b.setting("grain_scale")), (LEAST_GRAIN_SCALE, 0.0));+ b.set_setting("spacing", f32::NAN);+ assert!((b.setting("spacing") - 0.3).abs() < 1e-6);+ // where not set, controls start where the brush is, or at their own start+ assert_eq!(Brush::round_pen().setting("smudge_pull"), 0.75);+ assert_eq!(Brush::round_pen().setting("nothing_here"), 0.0);+ }++ #[test]+ fn spacing_follows_its_curve() {+ let mut b = Brush::round_pen();+ b.set_setting("spacing", 0.0);+ assert!((b.spacing - SPACING_FLOOR).abs() < 1e-6);+ b.set_setting("spacing", 1.0);+ assert!((b.spacing - SPACING_FLOOR - SPACING_SPAN).abs() < 1e-5);+ // three quarters of the control: stamps about 1.5 diameters apart, round dots with gaps+ b.set_setting("spacing", 0.75);+ assert!((b.spacing - 1.51).abs() < 0.01, "{}", b.spacing);+ // a spacing tighter than the floor shows as none+ b.spacing = 0.001;+ assert_eq!(b.setting("spacing"), 0.0);+ }++ #[test]+ fn changes_replay_onto_the_shipped_brush() {+ let shipped = Brush::round_pen();+ let mut b = shipped.clone();+ b.set_setting("spacing", 0.4);+ b.set_setting("max_size", 0.6);+ b.set_setting("min_size", 0.2);+ b.set_setting("wet_attack", 0.3);+ let changes = b.changes_from(&shipped);+ assert!(changes.iter().any(|(k, _)| k == "wet_attack"));+ assert!(!changes.iter().any(|(k, _)| k == "flow"));+ let mut again = shipped.clone();+ for (k, v) in &changes {+ again.set_setting(k, *v);+ }+ assert!(again.changes_from(&b).is_empty(), "{:?}", again.changes_from(&b));+ }++ #[test]+ fn close_spacing_keeps_brushes_smaller() {+ let mut b = Brush::round_pen();+ // a file's spacing of 0.0064 lets a brush be 5.8 units at most; none, 1+ b.set_setting("spacing", (0.0064f32 / 2.0).powf(1.0 / 2.2));+ assert!((b.most_size() - 5.8).abs() < 1e-3, "{}", b.most_size());+ b.set_setting("spacing", 0.0);+ assert_eq!(b.most_size(), 1.0);+ // and its size is held to it+ b.max_size = 10.0 * b.size_unit();+ assert!((b.diameter(1.0) - b.size_unit()).abs() < 1e-3);+ }++ #[test]+ fn choices_of_three_keep_their_last() {+ let mut b = Brush::round_pen();+ for key in ["shape_filtering", "grain_filtering", "cursor_outline", "hover_fill"] {+ b.set_setting(key, 2.0);+ assert_eq!(b.setting(key), 2.0, "{key}");+ b.set_setting(key, 7.0);+ assert_eq!(b.setting(key), 2.0, "{key}");+ }+ }++ #[test]+ fn the_size_controls_share_one_scale() {+ let mut b = Brush::round_pen();+ // the end of the control is the most size; a quarter of a unit sits at (1/64)^(1/2.2)+ // spaced roomily, the end of the control is the most size; a quarter of a unit sits at+ // (1/64)^(1/2.2)+ b.set_setting("spacing", 0.5);+ assert_eq!(b.most_size(), MOST_SIZE);+ b.set_setting("max_size", 1.0);+ assert!((b.max_size - MOST_SIZE * b.size_unit()).abs() < 1e-2);+ b.set_setting("max_size", (0.25f32 / MOST_SIZE).powf(1.0 / 2.2));+ assert!((b.max_size - 0.25 * b.size_unit()).abs() < 1e-3);+ // the least size is its own, not a share of the most, and no larger than it+ b.set_setting("min_size", (0.1f32 / MOST_SIZE).powf(1.0 / 2.2));+ assert!((b.min_size - 0.1 * b.size_unit()).abs() < 1e-3);+ b.set_setting("max_size", 1.0);+ assert!((b.min_size - 0.1 * b.size_unit()).abs() < 1e-3);+ b.set_setting("min_size", 1.0);+ assert_eq!(b.min_size, b.max_size);+ }+}diff --git a/crates/engine/src/textures.rs b/crates/engine/src/textures.rsnew file mode 100644index 0000000..bfa0302--- /dev/null+++ b/crates/engine/src/textures.rs@@ -0,0 +1,1658 @@+//! Brush shape and grain images, generated here (ProCraft's own, made procedurally at start-up):+//! 8-bit greyscale, white = paint. Grains tile seamlessly.++use std::f32::consts::{FRAC_PI_2, PI, TAU};++/// Edge of every shape and grain image, pixels.+pub const TEXTURE_SIZE: usize = 256;++/// A square greyscale image, `TEXTURE_SIZE` on a side, rows top to bottom.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct GrayImage {+ pub name: &'static str,+ pub pixels: Vec<u8>,+}++/// Shapes, by index (brushes refer to them by index).+pub mod shape {+ pub const SOFT_ROUND: u32 = 0;+ pub const GRAINY_DISC: u32 = 1;+ pub const CHUNK: u32 = 2;+ pub const BRISTLES: u32 = 3;+ pub const SPLATTER: u32 = 4;+ pub const FLAT: u32 = 5;+ pub const PASTEL: u32 = 6;+ pub const BLOT: u32 = 7;+ pub const LEAF: u32 = 8;+ pub const GRASS: u32 = 9;+ pub const SPARKLE: u32 = 10;+ pub const CLOUD: u32 = 11;+ pub const SQUARE: u32 = 12;+ pub const DRY: u32 = 13;+ pub const RING: u32 = 14;+ pub const SPRAY: u32 = 15;+ pub const HATCH: u32 = 16;+ pub const WISP: u32 = 17;+ pub const STAR: u32 = 18;+ pub const FUR: u32 = 19;+ pub const DROPLET: u32 = 20;+ pub const FLAME: u32 = 21;+ pub const BUBBLE: u32 = 22;+ pub const STONE: u32 = 23;+ pub const STREAK: u32 = 24;+ pub const FLOWER: u32 = 25;+ pub const TWIG: u32 = 26;+ pub const CRACK: u32 = 27;+ pub const SPONGE: u32 = 28;+ pub const TRIANGLE: u32 = 29;+ pub const DIAMOND: u32 = 30;+ pub const NEEDLES: u32 = 31;+ pub const FEATHER: u32 = 32;+ pub const CONFETTI: u32 = 33;+ pub const HAIR: u32 = 34;+ pub const SMUDGE: u32 = 35;+ pub const MOSS: u32 = 36;+ pub const HEART: u32 = 37;+ pub const SNOWFLAKE: u32 = 38;+ pub const SCRIBBLE: u32 = 39;+ pub const DRIP: u32 = 40;+ pub const BOLT: u32 = 41;+ pub const BLOCK: u32 = 42;+ pub const STOCK_GRAINY_DISC: u32 = 43;+ pub const STOCK_CHUNK: u32 = 44;+ pub const STOCK_PASTEL: u32 = 45;+ pub const STOCK_DAB: u32 = 46;+}++/// Grains, by index.+pub mod grain {+ pub const PAPER: u32 = 0;+ pub const COARSE: u32 = 1;+ pub const WEAVE: u32 = 2;+ pub const FIBRE: u32 = 3;+ pub const LINEN: u32 = 4;+ pub const WASH: u32 = 5;+ pub const CONCRETE: u32 = 6;+ pub const HALFTONE: u32 = 7;+ pub const HATCHING: u32 = 8;+ pub const NOISE: u32 = 9;+ pub const CRUMPLED: u32 = 10;+ pub const STIPPLE: u32 = 11;+ pub const WOOD: u32 = 12;+ pub const BRICK: u32 = 13;+ pub const SCALES: u32 = 14;+ pub const CELLS: u32 = 15;+ pub const MARBLE: u32 = 16;+ pub const STRIPES: u32 = 17;+ pub const GRUNGE: u32 = 18;+ pub const SAND: u32 = 19;+ pub const HEXAGONS: u32 = 20;+ pub const CAUSTICS: u32 = 21;+ pub const LEATHER: u32 = 22;+ pub const BARK: u32 = 23;+ pub const SCRATCHES: u32 = 24;+ pub const CHECKER: u32 = 25;+ pub const SPECKLE: u32 = 26;+ pub const TWILL: u32 = 27;+ pub const RUST: u32 = 28;+ pub const RECYCLED: u32 = 29;+ pub const SHEET: u32 = 30;+ pub const WORN: u32 = 31;+ pub const CHARCOAL: u32 = 32;+ pub const FINE_NOISE: u32 = 33;+ pub const SPECKLED: u32 = 34;+ pub const MOTTLED: u32 = 35;+}++/// The Coarse grain's tooth: below this the fibres darken it, by this much a unit.+const COARSE_LIGHT: f32 = 0.6;+const COARSE_DEPTH: f32 = 1.25;++/// The shapes, made once.+pub fn shapes() -> Vec<GrayImage> {+ static MADE: std::sync::OnceLock<Vec<GrayImage>> = std::sync::OnceLock::new();+ MADE.get_or_init(make_shapes).clone()+}++/// The grains, made once.+pub fn grains() -> Vec<GrayImage> {+ static MADE: std::sync::OnceLock<Vec<GrayImage>> = std::sync::OnceLock::new();+ MADE.get_or_init(make_grains).clone()+}++fn make_shapes() -> Vec<GrayImage> {+ let mut shapes = vec![+ // full well out towards its edge: stamped along a stroke it builds up to a soft line most of+ // its width across, with a short fade at each side+ GrayImage { name: "Soft round", pixels: field(|x, y| smooth(1.0 - radius(x, y)).powf(0.62)) },+ GrayImage {+ name: "Grainy disc",+ pixels: field(|x, y| {+ let edge = 1.0 - radius(x, y);+ let n = fbm(x * 12.0, y * 12.0, 12, 3, 11);+ (edge * 6.0).clamp(0.0, 1.0) * (0.55 + 0.45 * n).clamp(0.0, 1.0) * if n > 0.25 { 1.0 } else { n * 4.0 }+ }),+ },+ GrayImage {+ name: "Chunk",+ pixels: field(|x, y| {+ let n = fbm(x * 4.0, y * 4.0, 4, 4, 23);+ let r = radius(x, y) + (n - 0.5) * 0.55;+ let edge = smooth(((1.0 - r) * 5.0).clamp(0.0, 1.0));+ edge * (0.6 + 0.4 * fbm(x * 16.0, y * 16.0, 16, 2, 7))+ }),+ },+ GrayImage {+ name: "Bristles",+ pixels: field(|x, y| {+ let across = (x - 0.5).abs() * 2.0;+ let along = (y - 0.5).abs() * 2.0;+ let hairs = 0.5 + 0.5 * (x * 60.0 + fbm(x * 8.0, y, 8, 2, 5) * 6.0).sin();+ let body =+ smooth(((1.0 - across) * 4.0).clamp(0.0, 1.0)) * smooth(((1.0 - along) * 2.5).clamp(0.0, 1.0));+ body * (0.35 + 0.65 * hairs)+ }),+ },+ GrayImage {+ name: "Splatter",+ pixels: {+ let dots = scatter_points(41, 26);+ field(|x, y| {+ dots.iter().fold(0.0f32, |acc, &(cx, cy, r)| {+ let d = ((x - cx).powi(2) + (y - cy).powi(2)).sqrt() / r;+ acc.max(smooth(((1.0 - d) * 3.0).clamp(0.0, 1.0)))+ })+ })+ },+ },+ GrayImage {+ name: "Flat",+ pixels: field(|x, y| {+ let across = (x - 0.5).abs() * 2.0;+ let along = (y - 0.5).abs() * 2.0;+ smooth(((1.0 - across) * 3.0).clamp(0.0, 1.0)) * smooth(((1.0 - along) * 6.0).clamp(0.0, 1.0))+ }),+ },+ GrayImage {+ name: "Pastel",+ pixels: field(|x, y| {+ // a worn block: squarish, ragged at its edge, patchy inside+ let n = fbm(x * 6.0, y * 6.0, 6, 4, 31);+ let block = 1.0 - ((x - 0.5).abs() * 2.0).max((y - 0.5).abs() * 2.4);+ let edge = smooth(((block - 0.12 + (n - 0.5) * 0.45) * 5.0).clamp(0.0, 1.0));+ edge * contrast(fbm(x * 24.0, y * 24.0, 24, 3, 37), 1.8).max(0.25)+ }),+ },+ GrayImage {+ name: "Blot",+ pixels: {+ let drops = scatter_points(53, 9);+ field(move |x, y| {+ // spread over two thirds of the square, as a stock ink blot's mass+ let (x, y) = (0.5 + (x - 0.5) / 1.22, 0.5 + (y - 0.5) / 1.22);+ let n = fbm(x * 3.0, y * 3.0, 3, 3, 41);+ let body = smooth(((0.62 - radius(x, y) - (n - 0.5) * 0.5) * 9.0).clamp(0.0, 1.0));+ let spots = drops.iter().fold(0.0f32, |acc, &(cx, cy, r)| {+ // pushed out towards the edge+ let (dx, dy) = ((cx - 0.5) * 2.2 + 0.5, (cy - 0.5) * 2.2 + 0.5);+ let d = ((x - dx).powi(2) + (y - dy).powi(2)).sqrt() / (r * 0.6);+ acc.max(smooth(((1.0 - d) * 4.0).clamp(0.0, 1.0)))+ });+ body.max(spots) * (1.0 - 0.05 * radius(x, y))+ })+ },+ },+ GrayImage {+ name: "Leaf",+ pixels: field(|x, y| {+ // pointing up, widest below the middle, a pale midrib and a short stem+ let (u, v) = ((x - 0.5) * 2.0, (y - 0.5) * 2.0);+ let t = ((v + 0.85) / 1.5).clamp(0.0, 1.0);+ let width = 0.52 * (t * std::f32::consts::PI).sin().powf(0.8) * (1.0 - 0.25 * t);+ let blade = smooth(((width - u.abs()) * 30.0).clamp(0.0, 1.0)) * f32::from(u8::from(v < 0.65));+ let rib =+ 1.0 - 0.5 * smooth(((0.025 - u.abs()) * 60.0).clamp(0.0, 1.0)) * f32::from(u8::from(v > -0.6));+ let stem = smooth(((0.03 - u.abs()) * 60.0).clamp(0.0, 1.0)) * f32::from(u8::from(v > 0.6 && v < 0.9));+ (blade * rib).max(stem)+ }),+ },+ GrayImage {+ name: "Grass",+ pixels: field(|x, y| {+ // blades from the bottom, each leaning and narrowing to its tip+ (0..11).fold(0.0f32, |acc, k| {+ let base = 0.12 + 0.76 * hash(k, 1, 61);+ let lean = (hash(k, 2, 61) - 0.5) * 0.5;+ let top = 0.08 + 0.35 * hash(k, 3, 61);+ let along = ((0.92 - y) / (0.92 - top)).clamp(0.0, 1.0);+ if y < top || y > 0.92 {+ return acc;+ }+ let cx = base + lean * along * along;+ let half = 0.03 * (1.0 - along).powf(0.7);+ acc.max(smooth(((half - (x - cx).abs()) * 160.0).clamp(0.0, 1.0)))+ })+ }),+ },+ GrayImage {+ name: "Sparkle",+ pixels: field(|x, y| {+ // four long points and four short ones, each narrowing to its tip, over a small glow+ let (u, v) = ((x - 0.5).abs() * 2.0, (y - 0.5).abs() * 2.0);+ let point = |along: f32, off: f32| {+ let width = 0.09 * (1.0 - along).max(0.0).powf(1.4) + 0.004;+ smooth(1.0 - off / width) * f32::from(u8::from(along < 1.0))+ };+ let long = point(u, v).max(point(v, u));+ let (a, b) =+ ((u + v) * std::f32::consts::FRAC_1_SQRT_2, (u - v).abs() * std::f32::consts::FRAC_1_SQRT_2);+ let short = point(a * 1.8, b * 1.4) * 0.8;+ let glow = (-(u * u + v * v) * 40.0).exp();+ long.max(short).max(glow).min(1.0) * smooth(((1.0 - radius(x, y)) * 8.0).clamp(0.0, 1.0))+ }),+ },+ GrayImage {+ name: "Cloud",+ pixels: {+ let puffs = scatter_points(71, 9);+ field(move |x, y| {+ // puffs drawn in towards the middle, overlapping into one cloud+ let lumps = puffs.iter().fold(0.0f32, |acc, &(cx, cy, r)| {+ let (px, py) = (0.5 + (cx - 0.5) * 0.75, 0.5 + (cy - 0.5) * 0.6);+ let d = ((x - px).powi(2) + (y - py).powi(2)).sqrt() / (r * 1.5 + 0.2);+ acc.max(smooth((1.0 - d).clamp(0.0, 1.0) * 1.6))+ });+ let n = fbm(x * 8.0, y * 8.0, 8, 4, 73);+ (lumps * (0.6 + 0.55 * n)).min(1.0) * smooth(((1.0 - radius(x, y)) * 4.0).clamp(0.0, 1.0))+ })+ },+ },+ GrayImage {+ name: "Square",+ pixels: field(|x, y| f32::from(u8::from((x - 0.5).abs() < 0.4 && (y - 0.5).abs() < 0.4))),+ },+ GrayImage {+ name: "Dry",+ pixels: field(|x, y| {+ // a flat stroke's worth of hairs, broken where the paint ran out+ let across = (x - 0.5).abs() * 2.0;+ let along = (y - 0.5).abs() * 2.0;+ let hair = value_noise(x * 90.0, y * 2.0, 90, 83);+ let broken = smooth(((hair - 0.35) * 5.0).clamp(0.0, 1.0));+ let body =+ smooth(((1.0 - across) * 6.0).clamp(0.0, 1.0)) * smooth(((1.0 - along) * 3.0).clamp(0.0, 1.0));+ body * broken+ }),+ },+ GrayImage {+ name: "Ring",+ pixels: field(|x, y| {+ let r = radius(x, y);+ let band = smooth(((0.06 - (r - 0.82).abs()) * 40.0).clamp(0.0, 1.0));+ band.max(0.25 * smooth(((0.8 - r) * 10.0).clamp(0.0, 1.0)))+ }),+ },+ GrayImage {+ name: "Spray",+ pixels: {+ // fine droplets, thick in the middle and thinning out+ let drops: Vec<(f32, f32, f32)> = (0..420)+ .map(|i| {+ let a = hash(i, 1, 97) * std::f32::consts::TAU;+ let d = (hash(i, 2, 97) * hash(i, 4, 97)).sqrt() * 0.46;+ (0.5 + a.cos() * d, 0.5 + a.sin() * d, 0.004 + 0.006 * hash(i, 3, 97))+ })+ .collect();+ field(move |x, y| {+ drops.iter().fold(0.0f32, |acc, &(cx, cy, r)| {+ let d = ((x - cx).powi(2) + (y - cy).powi(2)).sqrt() / r;+ acc.max((1.5 - d).clamp(0.0, 1.0))+ })+ })+ },+ },+ GrayImage {+ name: "Hatch",+ pixels: field(|x, y| {+ let lines = 0.5 + 0.5 * ((x + y) * std::f32::consts::TAU * 9.0).cos();+ let ink = smooth(((lines - 0.55) * 6.0).clamp(0.0, 1.0));+ ink * smooth(((1.0 - radius(x, y)) * 5.0).clamp(0.0, 1.0))+ }),+ },+ GrayImage {+ name: "Wisp",+ pixels: field(|x, y| {+ // bands bent by noise: smoke curling+ let warp = fbm(x * 3.0, y * 3.0, 3, 3, 109);+ let bands = 0.5 + 0.5 * ((y + warp * 0.6) * std::f32::consts::TAU * 3.0).sin();+ let soft = smooth(((1.0 - radius(x, y)) * 2.0).clamp(0.0, 1.0));+ (bands.powi(3) * soft * (0.6 + 0.6 * fbm(x * 6.0, y * 6.0, 6, 3, 113))).min(1.0)+ }),+ },+ GrayImage {+ name: "Star",+ pixels: field(|x, y| {+ // five points, one straight up, the edges between them curving in+ let (u, v) = centred(x, y);+ let s = ((v.atan2(u) + FRAC_PI_2) / TAU * 5.0).rem_euclid(1.0);+ let edge = 0.4 + 0.52 * ((s - 0.5).abs() * 2.0).powf(1.6);+ smooth((edge - (u * u + v * v).sqrt()) * 40.0)+ }),+ },+ GrayImage {+ name: "Fur",+ pixels: field(|x, y| {+ // fine hairs from a band low down, bending as they rise and narrowing to their tips+ (0..48).fold(0.0f32, |acc, k| {+ let (foot, top) = (0.75 + 0.12 * hash(k, 2, 131), 0.1 + 0.3 * hash(k, 3, 131));+ if y < top || y > foot {+ return acc;+ }+ let along = (foot - y) / (foot - top);+ let cx = 0.15 + 0.7 * hash(k, 1, 131) + (hash(k, 4, 131) - 0.5) * 0.3 * along * along;+ let half = 0.008 * (1.0 - along).powf(0.6) + 0.001;+ acc.max(smooth((half - (x - cx).abs()) * 400.0) * (0.5 + 0.5 * hash(k, 5, 131)))+ })+ }),+ },+ GrayImage {+ name: "Droplet",+ pixels: field(|x, y| {+ // round below and drawn up to a point; a strong rim, a paler middle, a bright spot+ let (u, v) = centred(x, y);+ let (cy, r) = (0.3, 0.58);+ let width = if v >= cy {+ (r * r - (v - cy).powi(2)).max(0.0).sqrt()+ } else {+ r * ((v + 0.92) / (cy + 0.92)).clamp(0.0, 1.0).powf(1.5)+ };+ let inside = width - u.abs();+ let rim = 0.55 + 0.45 * smooth((0.12 - inside) * 12.0);+ let spot = smooth((0.1 - ((u + 0.2).powi(2) + (v - 0.18).powi(2)).sqrt()) * 30.0);+ smooth(inside * 30.0) * rim * (1.0 - 0.8 * spot)+ }),+ },+ GrayImage {+ name: "Flame",+ pixels: field(|x, y| {+ // a tongue of fire: round and full at its foot, flickering up to a point+ let (u, v) = centred(x, y);+ let t = ((0.85 - v) / 1.8).clamp(0.0, 1.0);+ let width = if t < 0.2 {+ 0.46 * (1.0 - ((0.2 - t) / 0.2).powi(2)).max(0.0).sqrt()+ } else {+ 0.46 * ((1.0 - t) / 0.8).powf(1.5)+ };+ // the upper part sways and frays into tongues+ let sway = (fbm(x * 2.0, y * 4.0, 2, 3, 137) - 0.5) * 0.9 * t.powf(1.2);+ let fray = (fbm(x * 6.0, y * 3.0, 3, 3, 139) - 0.5) * 0.35 * t;+ let body = smooth((width + fray - (u - sway).abs()) * 18.0);+ let flicker = 0.75 + 0.35 * fbm(x * 8.0, y * 8.0, 8, 3, 141);+ (body * (0.6 + 0.4 * (1.0 - t)) * flicker).min(1.0)+ }),+ },+ GrayImage {+ name: "Bubble",+ pixels: field(|x, y| {+ // a thin skin, a faint inside and a curved highlight to the upper left+ let r = radius(x, y);+ let skin = smooth((0.05 - (r - 0.86).abs()) * 50.0);+ let inside = 0.12 * smooth((0.86 - r) * 10.0);+ let a = (y - 0.5).atan2(x - 0.5);+ let arc = smooth(1.0 - ((a + 2.36) / 0.6).abs()) * smooth((0.05 - (r - 0.66).abs()) * 40.0);+ skin.max(inside).max(arc * 0.9)+ }),+ },+ GrayImage {+ name: "Stone",+ pixels: {+ // an angular pebble: straight edges between seven corners, lit from the upper left+ let corners: Vec<(f32, f32)> = (0..7)+ .map(|k| {+ let a = (k as f32 + 0.4 * hash(k, 1, 139)) / 7.0 * TAU;+ let r = 0.62 + 0.3 * hash(k, 2, 139);+ (a.cos() * r, a.sin() * r)+ })+ .collect();+ field(move |x, y| {+ let (u, v) = centred(x, y);+ let (edge, inside) = polygon(&corners, u, v);+ if !inside {+ return 0.0;+ }+ let lit = 0.85 - 0.15 * (u + v);+ smooth(edge * 30.0) * (lit * (0.75 + 0.3 * fbm(x * 10.0, y * 10.0, 10, 3, 141))).min(1.0)+ })+ },+ },+ GrayImage {+ name: "Streak",+ pixels: field(|x, y| {+ // a long thin line, thickest a little below the middle, fading out at both ends+ let (u, v) = centred(x, y);+ let half = 0.035 * (1.0 - ((v - 0.05) / 0.85).powi(2)).max(0.0);+ smooth((half - u.abs()) * 100.0)+ }),+ },+ GrayImage {+ name: "Flower",+ pixels: field(|x, y| {+ // five rounded petals round a paler middle+ let (u, v) = centred(x, y);+ let (r, a) = ((u * u + v * v).sqrt(), v.atan2(u) + FRAC_PI_2);+ let petal = (a * 2.5).cos().abs();+ let body = smooth((0.3 + 0.6 * petal.sqrt() - r) * 25.0);+ let middle = 1.0 - 0.45 * smooth((0.2 - r) * 20.0);+ body * (0.8 + 0.2 * petal) * middle+ }),+ },+ GrayImage {+ name: "Twig",+ pixels: {+ // a stick with three side shoots, each thinning to its end+ let parts = [+ ((0.02, 0.92), (-0.04, -0.88), 0.07, 0.025),+ ((0.0, 0.35), (-0.55, -0.25), 0.04, 0.012),+ ((-0.02, -0.15), (0.5, -0.6), 0.035, 0.01),+ ((-0.03, -0.5), (-0.3, -0.85), 0.025, 0.008),+ ];+ field(move |x, y| {+ let (u, v) = centred(x, y);+ parts.iter().fold(0.0f32, |acc, &(a, b, w0, w1)| {+ let (d, t) = segment(u, v, a, b);+ acc.max(smooth((w0 + (w1 - w0) * t - d) * 60.0))+ }) * (0.8 + 0.25 * fbm(x * 4.0, y * 32.0, 4, 2, 143)).min(1.0)+ })+ },+ },+ GrayImage {+ name: "Crack",+ pixels: {+ let lines = cracks(149);+ field(move |x, y| {+ let (u, v) = centred(x, y);+ lines.iter().fold(0.0f32, |acc, &(a, b, w)| acc.max(smooth((w - segment(u, v, a, b).0) * 120.0)))+ })+ },+ },+ GrayImage {+ name: "Sponge",+ pixels: field(|x, y| {+ // a round dab full of holes of every size+ let n = fbm(x * 4.0, y * 4.0, 4, 2, 151);+ let body = smooth((0.9 - radius(x, y) - (n - 0.5) * 0.3) * 8.0);+ let (near, _) = cells(x, y, 10, 157);+ let (fine, _) = cells(x, y, 22, 163);+ body * smooth((near - 0.28) * 6.0) * smooth((fine - 0.22) * 6.0)+ }),+ },+ GrayImage {+ name: "Triangle",+ pixels: field(|x, y| {+ // pointing up, its middle at the centre+ let (u, v) = centred(x, y);+ let d = (v - 0.45).max(0.866 * u.abs() - 0.5 * v - 0.45);+ smooth(-d * 60.0)+ }),+ },+ GrayImage {+ name: "Diamond",+ pixels: field(|x, y| {+ let (u, v) = centred(x, y);+ smooth((1.0 - u.abs() / 0.6 - v.abs() / 0.95) * 20.0)+ }),+ },+ GrayImage {+ name: "Needles",+ pixels: {+ // a sprig: a stem with pairs of needles slanting up, shorter towards its tip+ let mut parts = vec![((0.0, 0.92), (0.0, -0.9), 0.025)];+ for k in 0..13 {+ let at = 0.8 - k as f32 * 0.13;+ let len = 0.25 + 0.25 * (at + 0.9) / 1.7;+ for side in [-1.0f32, 1.0] {+ parts.push(((0.0, at), (side * len * 0.77, at - len * 0.64), 0.012));+ }+ }+ field(move |x, y| {+ let (u, v) = centred(x, y);+ parts.iter().fold(0.0f32, |acc, &(a, b, w)| {+ let (d, t) = segment(u, v, a, b);+ acc.max(smooth((w * (1.0 - 0.6 * t) - d) * 150.0))+ })+ })+ },+ },+ GrayImage {+ name: "Feather",+ pixels: field(|x, y| {+ // a vane round a quill, its barbs slanting out and up, split here and there+ let (u, v) = centred(x, y);+ let t = (v + 0.95) / 1.85;+ let vane = 0.42 * (PI * (t / 0.82).clamp(0.0, 1.0)).sin().powf(0.7);+ let lean = u + 0.08 * (t * PI).sin();+ let barbs = 0.5 + 0.5 * ((v + lean.abs() * 0.8) * TAU * 14.0).cos();+ let split = smooth((value_noise((v + lean.abs() * 0.8) * 9.0, u.signum(), 9, 167) - 0.2) * 8.0);+ let body = smooth((vane - lean.abs()) * 30.0) * (0.55 + 0.45 * barbs) * split;+ let quill = smooth((0.018 * (1.0 - 0.3 * t) - lean.abs()) * 120.0) * f32::from(u8::from(t < 1.0));+ body.max(quill)+ }),+ },+ GrayImage {+ name: "Confetti",+ pixels: {+ // little paper strips turned every way+ let strips: Vec<(f32, f32, f32, f32, f32, f32)> = (0..22)+ .map(|i| {+ let a = hash(i, 1, 173) * TAU;+ let d = hash(i, 2, 173).sqrt() * 0.36;+ let turn = hash(i, 3, 173) * PI;+ let (w, h) = (0.012 + 0.012 * hash(i, 4, 173), 0.03 + 0.025 * hash(i, 5, 173));+ (0.5 + a.cos() * d, 0.5 + a.sin() * d, turn, w, h, 0.6 + 0.4 * hash(i, 6, 173))+ })+ .collect();+ field(move |x, y| {+ strips.iter().fold(0.0f32, |acc, &(cx, cy, turn, w, h, ink)| {+ let (dx, dy) = (x - cx, y - cy);+ let (s, c) = turn.sin_cos();+ let (along, across) = (dx * c + dy * s, dy * c - dx * s);+ acc.max(smooth((w - across.abs()).min(h - along.abs()) * 600.0) * ink)+ })+ })+ },+ },+ GrayImage {+ name: "Hair",+ pixels: field(|x, y| {+ // a lock of long strands, each waving a little+ let ends = smooth((y - 0.06) * 12.0) * smooth((0.94 - y) * 12.0);+ (0..9).fold(0.0f32, |acc, k| {+ let cx = 0.22 + 0.56 * (k as f32 + hash(k, 1, 179) * 0.6) / 9.0;+ let wave = 0.05 * (y * TAU * 1.2 + hash(k, 2, 179) * TAU).sin();+ acc.max(smooth((0.006 - (x - cx - wave).abs()) * 500.0) * (0.6 + 0.4 * hash(k, 3, 179)))+ }) * ends+ }),+ },+ GrayImage {+ name: "Smudge",+ pixels: field(|x, y| {+ // a soft oval dragged along: streaks run its length+ let (u, v) = centred(x, y);+ let soft = smooth(1.0 - (u * u / 0.5 + v * v / 0.95).sqrt()).powf(0.8);+ soft * (0.6 + 0.4 * value_noise(x * 40.0, y * 3.0, 40, 181))+ }),+ },+ GrayImage {+ name: "Moss",+ pixels: field(|x, y| {+ // clumped fuzz, thick in the middle and sparse at the edge+ let falloff = 1.0 - radius(x, y);+ let n = fbm(x * 16.0, y * 16.0, 16, 3, 191);+ smooth((n - 0.62 + falloff * 0.35) * 8.0) * smooth(falloff * 4.0)+ }),+ },+ GrayImage {+ name: "Heart",+ pixels: {+ let outline = heart();+ field(move |x, y| {+ let (u, v) = centred(x, y);+ let (edge, inside) = polygon(&outline, u, v);+ if inside { smooth(edge * 40.0) } else { 0.0 }+ })+ },+ },+ GrayImage {+ name: "Snowflake",+ pixels: field(|x, y| {+ // six arms, each with two pairs of side branches, round a small hexagon+ let (u, v) = centred(x, y);+ let r = (u * u + v * v).sqrt();+ let sector = TAU / 6.0;+ let a = v.atan2(u).rem_euclid(sector);+ let a = a.min(sector - a);+ let (px, py) = (r * a.cos(), r * a.sin());+ let arm = smooth((0.03 - segment(px, py, (0.0, 0.0), (0.88, 0.0)).0) * 80.0);+ let branch = |at: f32, len: f32| {+ let tip = (at + len * 0.5, len * 0.866);+ smooth((0.022 - segment(px, py, (at, 0.0), tip).0) * 80.0)+ };+ let middle = smooth((0.16 - r) * 40.0);+ arm.max(branch(0.38, 0.28)).max(branch(0.6, 0.2)).max(middle)+ }),+ },+ GrayImage {+ name: "Scribble",+ pixels: {+ // a looping line wandering round the middle+ let points: Vec<(f32, f32)> = (0..=96)+ .map(|i| {+ let t = i as f32 / 96.0 * TAU * 1.5;+ (+ 0.5 * (2.1 * t).sin() + 0.25 * (5.3 * t + 1.0).sin(),+ 0.5 * (1.7 * t).cos() + 0.25 * (4.1 * t + 2.0).sin(),+ )+ })+ .collect();+ field(move |x, y| {+ let (u, v) = centred(x, y);+ points+ .windows(2)+ .filter_map(|w| Some(segment(u, v, *w.first()?, *w.get(1)?).0))+ .fold(0.0f32, |acc, d| acc.max(smooth((0.02 - d) * 80.0)))+ })+ },+ },+ GrayImage {+ name: "Drip",+ pixels: field(|x, y| {+ // a blob with paint running down from it to a bead+ let (u, v) = centred(x, y);+ let blob = smooth((0.35 - (u * u + (v + 0.55).powi(2)).sqrt()) * 30.0);+ let run = smooth((0.06 - (u - 0.03 * (v * 3.0).sin()).abs()) * 60.0)+ * f32::from(u8::from(v > -0.6 && v < 0.66));+ let bead = smooth((0.1 - (u * u + (v - 0.7).powi(2)).sqrt()) * 40.0);+ blob.max(run).max(bead)+ }),+ },+ GrayImage {+ name: "Bolt",+ pixels: {+ // a zigzag from the top edge's middle to the bottom's, with two short forks, in a+ // faint glow: laid end to end along a stroke, one bolt runs into the next+ let mut points = vec![(0.0f32, -1.0f32)];+ for k in 1..8 {+ points.push(((hash(k, 1, 197) - 0.5) * 0.5, -1.0 + k as f32 * 0.25));+ }+ points.push((0.0, 1.0));+ let mut parts: Vec<Line> =+ points.windows(2).filter_map(|w| Some((*w.first()?, *w.get(1)?, 0.035))).collect();+ for (k, &from) in points.iter().enumerate().skip(2).step_by(3).take(2) {+ let side = if from.0 > 0.0 { 1.0 } else { -1.0 };+ let to = (from.0 + side * (0.25 + 0.15 * hash(k as i32, 2, 197)), from.1 + 0.2);+ parts.push((from, to, 0.018));+ }+ field(move |x, y| {+ let (u, v) = centred(x, y);+ let d = parts.iter().fold(f32::MAX, |acc, &(a, b, w)| acc.min(segment(u, v, a, b).0 - w));+ smooth(-d * 120.0).max(0.3 * smooth(1.0 - d.max(0.0) * 8.0)) * smooth((1.0 - u.abs()) * 6.0)+ })+ },+ },+ GrayImage {+ name: "Block",+ pixels: field(|x, y| {+ // a solid upright block, half as wide as it is tall, with a few specks out of it+ let (dx, dy) = ((x - 0.5).abs(), (y - 0.47).abs());+ let edge = smooth((0.245 - dx) * 60.0) * smooth((0.4 - dy) * 60.0);+ let n = TEXTURE_SIZE as f32;+ let speck = hash((x * n / 3.0) as i32, (y * n / 3.0) as i32, 1601);+ edge * if speck > 0.86 { 0.25 } else { 1.0 }+ }),+ },+ ];+ // stand-ins for stock shapes: ours drawn smaller in their square, as the stock shapes that come+ // nearest them spread their mass over about half of the square's width, not three quarters+ let shrunk = |index: u32, by: f32, name: &'static str| GrayImage {+ name,+ pixels: shrunk(shapes.get(index as usize).map_or(&[][..], |s| &s.pixels[..]), by),+ };+ let more = [+ shrunk(shape::GRAINY_DISC, SHRINK_DISC, "Grainy dot"),+ shrunk(shape::CHUNK, SHRINK_CHUNK, "Small chunk"),+ shrunk(shape::PASTEL, SHRINK_PASTEL, "Small pastel"),+ ];+ // a solid dab: the small chunk filled in (stock stamped dabs are solid through most of+ // their area: inked mean about 0.85, mostly over 0.9, against the chunk's 0.68)+ let dab = more.get(1).map(|c| c.pixels.iter().map(|&v| (f32::from(v) * DAB_GAIN).min(255.0) as u8).collect());+ shapes.extend(more);+ shapes.push(GrayImage { name: "Solid dab", pixels: dab.unwrap_or_default() });+ shapes+}++/// How much the solid dab raises the small chunk's values.+const DAB_GAIN: f32 = 1.4;++/// How much smaller the stock stand-ins draw our grainy disc, chunk and pastel shapes: as measured,+/// stock brushes on them paint as much of the reference's drawing pad as ours then do (the disc's+/// and the chunk's median areas within 3%; the pastel by the stock shapes' spread alone).+const SHRINK_DISC: f32 = 1.7;+const SHRINK_CHUNK: f32 = 1.47;+const SHRINK_PASTEL: f32 = 1.35;++/// `pixels` (a square image) drawn `by` times smaller about its middle, empty around.+fn shrunk(pixels: &[u8], by: f32) -> Vec<u8> {+ let n = TEXTURE_SIZE;+ let img: Vec<f32> = pixels.iter().map(|&v| f32::from(v)).collect();+ let mut out = vec![0u8; n * n];+ for (k, px) in out.iter_mut().enumerate() {+ let (x, y) = ((k % n) as f32 + 0.5, (k / n) as f32 + 0.5);+ let half = n as f32 / 2.0;+ let (u, v) = (half + (x - half) * by, half + (y - half) * by);+ if u < 0.5 || v < 0.5 || u > n as f32 - 0.5 || v > n as f32 - 0.5 {+ continue;+ }+ *px = sample_wrapped(&img, n, u - 0.5, v - 0.5).round().clamp(0.0, 255.0) as u8;+ }+ out+}++fn make_grains() -> Vec<GrayImage> {+ let mut grains = vec![+ GrayImage { name: "Paper", pixels: field(|x, y| contrast(fbm(x * 32.0, y * 32.0, 32, 4, 101), 1.6)) },+ GrayImage {+ name: "Coarse",+ pixels: field(|x, y| {+ // fine fibres crossing both ways, light with darker threads between (as a charcoal+ // paper's tooth lets paint through)+ let along = fbm_xy(x * 128.0, y * 48.0, (128, 48), 3, 202);+ let down = fbm_xy(x * 48.0, y * 128.0, (48, 128), 3, 203);+ let n = (along + down) / 2.0;+ let dark = ((COARSE_LIGHT - n) * COARSE_DEPTH).max(0.0);+ 0.97 - dark+ }),+ },+ GrayImage {+ name: "Weave",+ pixels: field(|x, y| {+ // horizontal and vertical threads, crossing over and under in a checker+ let across = 0.5 + 0.5 * (y * TAU * 16.0).sin();+ let down = 0.5 + 0.5 * (x * TAU * 16.0).sin();+ let over = 0.5 + 0.5 * (x * TAU * 8.0).sin() * (y * TAU * 8.0).sin();+ let n = fbm(x * 64.0, y * 64.0, 64, 2, 303);+ (across + (down - across) * over) * 0.8 + 0.2 * n+ }),+ },+ GrayImage {+ name: "Fibre",+ pixels: field(|x, y| {+ contrast(0.6 * fbm(x * 64.0, y * 4.0, 64, 3, 404) + 0.4 * fbm(x * 4.0, y * 64.0, 4, 3, 505), 1.8)+ }),+ },+ GrayImage {+ name: "Linen",+ pixels: field(|x, y| {+ // uneven threads: their thickness wanders+ let across = value_noise(x * 4.0, y * 4.0, 4, 601);+ let down = value_noise(x * 4.0, y * 4.0, 4, 607);+ let threads = 0.5+ + 0.25 * ((y * 24.0 + across * 1.5) * std::f32::consts::TAU).sin()+ + 0.25 * ((x * 24.0 + down * 1.5) * std::f32::consts::TAU).sin();+ contrast(threads * 0.8 + 0.2 * fbm(x * 32.0, y * 32.0, 32, 2, 613), 1.6)+ }),+ },+ GrayImage {+ name: "Wash",+ pixels: field(|x, y| {+ // broad pools of pigment, granulated+ let pools = fbm(x * 4.0, y * 4.0, 4, 3, 701);+ let grains = fbm(x * 64.0, y * 64.0, 64, 2, 709);+ contrast(0.7 * pools + 0.3 * grains, 1.9)+ }),+ },+ GrayImage {+ name: "Concrete",+ pixels: field(|x, y| {+ let surface = fbm(x * 16.0, y * 16.0, 16, 4, 801);+ let pits = fbm(x * 32.0, y * 32.0, 32, 2, 809);+ let pitted = if pits < 0.3 { pits / 0.3 * 0.4 } else { 1.0 };+ contrast(surface, 1.4) * pitted+ }),+ },+ GrayImage {+ name: "Halftone",+ pixels: field(|x, y| {+ // a dot grid, 16 across+ let (fx, fy) = ((x * 16.0).fract() - 0.5, (y * 16.0).fract() - 0.5);+ smooth(((0.36 - (fx * fx + fy * fy).sqrt()) * 30.0).clamp(0.0, 1.0))+ }),+ },+ GrayImage {+ name: "Hatching",+ pixels: field(|x, y| {+ // two sets of diagonal lines, slightly wavering+ let w = (fbm(x * 8.0, y * 8.0, 8, 2, 901) - 0.5) * 0.04;+ let one = 0.5 + 0.5 * ((x + y + w) * std::f32::consts::TAU * 16.0).cos();+ let two = 0.5 + 0.5 * ((x - y + w) * std::f32::consts::TAU * 16.0).cos();+ smooth(((one.max(two) - 0.7) * 6.0).clamp(0.0, 1.0))+ }),+ },+ GrayImage {+ name: "Noise",+ pixels: field(|x, y| {+ // near white, darkened here and there by fine flecks about two texels across: each+ // texel the average of sparse specks over it and its neighbours to the right and+ // below (wrapping, so it tiles), as a speckled image shrunk to half+ let n = TEXTURE_SIZE as i32;+ let (i, j) = ((x * n as f32) as i32, (y * n as f32) as i32);+ let specks: f32 = (0..4)+ .map(|k| {+ let u = hash((i + k % 2).rem_euclid(n), (j + k / 2).rem_euclid(n), 1471);+ ((u - 0.5) * 2.0).max(0.0).powi(2)+ })+ .sum();+ 1.0 - specks / 4.0+ }),+ },+ GrayImage {+ name: "Crumpled",+ pixels: field(|x, y| {+ // ridges where folds were+ let ridged = 1.0 - (fbm(x * 6.0, y * 6.0, 6, 4, 1103) * 2.0 - 1.0).abs();+ contrast(ridged.powi(2), 1.5)+ }),+ },+ GrayImage {+ name: "Stipple",+ pixels: field(|x, y| {+ // a dot in each of 32 cells across, placed and sized at random+ let (cx, cy) = ((x * 32.0).floor() as i32, (y * 32.0).floor() as i32);+ let (ox, oy) = (0.25 + 0.5 * hash(cx, cy, 1201), 0.25 + 0.5 * hash(cx, cy, 1213));+ let r = 0.2 + 0.2 * hash(cx, cy, 1223);+ let (fx, fy) = ((x * 32.0).fract() - ox, (y * 32.0).fract() - oy);+ smooth(((r - (fx * fx + fy * fy).sqrt()) * 20.0).clamp(0.0, 1.0))+ }),+ },+ GrayImage {+ name: "Wood",+ pixels: field(|x, y| {+ // growth rings running across, bent round knots, fine fibres along them+ let bend = fbm(x * 2.0, y * 2.0, 2, 3, 1301);+ let rings = 0.5 + 0.5 * ((y * 10.0 + bend * 2.0) * TAU).sin();+ let fibres = fbm_xy(x * 4.0, y * 64.0, (4, 64), 2, 1307);+ contrast(0.6 * rings.powf(0.7) + 0.4 * fibres, 1.3)+ }),+ },+ GrayImage {+ name: "Brick",+ pixels: field(|x, y| {+ // eight courses of four bricks, every other one shifted by half; worn faces, deep joints+ let row = (y * 8.0).floor() as i32;+ let shift = 0.5 * row.rem_euclid(2) as f32;+ let (fx, fy) = ((x * 4.0 + shift).fract(), (y * 8.0).fract());+ let joint = (fx.min(1.0 - fx) / 4.0).min(fy.min(1.0 - fy) / 8.0);+ let brick = ((x * 4.0 + shift).floor() as i32).rem_euclid(4);+ let face = 0.62 + 0.18 * hash(brick, row, 1311) + 0.25 * fbm(x * 16.0, y * 16.0, 16, 3, 1313);+ smooth((joint - 0.006) * 300.0) * face.min(1.0)+ }),+ },+ GrayImage {+ name: "Scales",+ pixels: field(|x, y| {+ // rows of round scales, each row lying over the one above, darker at their edges+ let (px, py) = (x * 8.0, y * 16.0);+ let (ci, cj) = (px.floor() as i32, py.floor() as i32);+ let mut best: Option<(i32, f32)> = None;+ for j in cj - 2..=cj + 2 {+ for i in ci - 1..=ci + 1 {+ let cx = i as f32 + 0.5 * j.rem_euclid(2) as f32;+ let d = ((px - cx).powi(2) + ((py - j as f32) * 0.5).powi(2)).sqrt() / 0.62;+ if d < 1.0 && best.is_none_or(|(bj, _)| j > bj) {+ best = Some((j, d));+ }+ }+ }+ best.map_or(0.0, |(_, d)| 0.3 + 0.7 * smooth((1.0 - d) * 3.0))+ }),+ },+ GrayImage {+ name: "Cells",+ pixels: field(|x, y| {+ let (f1, f2) = cells(x, y, 12, 1321);+ smooth((f2 - f1 - 0.06) * 8.0) * (0.8 + 0.2 * f1)+ }),+ },+ GrayImage {+ name: "Marble",+ pixels: field(|x, y| {+ // thin dark veins wandering through a pale stone+ let warp = fbm(x * 4.0, y * 4.0, 4, 5, 1331);+ let veins = ((x + y + warp * 1.6) * TAU * 2.0).sin().abs();+ veins.powf(0.25) * (0.85 + 0.15 * fbm(x * 32.0, y * 32.0, 32, 2, 1337))+ }),+ },+ GrayImage {+ name: "Stripes",+ pixels: field(|x, y| {+ let wobble = (fbm(x * 4.0, y * 4.0, 4, 2, 1341) - 0.5) * 0.4;+ smooth((0.5 + 0.5 * ((x * 12.0 + wobble) * TAU).cos() - 0.5) * 6.0)+ }),+ },+ GrayImage {+ name: "Grunge",+ pixels: field(|x, y| {+ // blotches, flecks knocked out of them+ let blotch = contrast(fbm(x * 6.0, y * 6.0, 6, 5, 1351), 2.4);+ let flecks = smooth((value_noise(x * 96.0, y * 96.0, 96, 1357) - 0.8) * 10.0);+ (blotch - flecks * 0.8).max(0.0) * (0.8 + 0.2 * fbm(x * 32.0, y * 32.0, 32, 2, 1359))+ }),+ },+ GrayImage {+ name: "Sand",+ pixels: field(|x, y| {+ let fine = value_noise(x * 128.0, y * 128.0, 128, 1361);+ contrast(0.7 * fine + 0.3 * value_noise(x * 64.0, y * 64.0, 64, 1367), 2.6)+ }),+ },+ GrayImage {+ name: "Hexagons",+ pixels: field(|x, y| {+ // a honeycomb's walls: 14 cells across, 16 rows (as near to regular as tiling allows)+ let (cols, rows) = (14.0f32, 16.0f32);+ let (ci, cj) = ((x * cols).floor() as i32, (y * rows).floor() as i32);+ let (mut f1, mut f2) = (f32::MAX, f32::MAX);+ for j in cj - 1..=cj + 1 {+ for i in ci - 1..=ci + 1 {+ let cx = (i as f32 + 0.5 + 0.5 * j.rem_euclid(2) as f32) / cols;+ let d = ((x - cx).powi(2) + (y - (j as f32 + 0.5) / rows).powi(2)).sqrt();+ (f1, f2) = if d < f1 { (d, f1) } else { (f1, f2.min(d)) };+ }+ }+ smooth((f2 - f1 - 0.006) * 200.0)+ }),+ },+ GrayImage {+ name: "Caustics",+ pixels: field(|x, y| {+ // light netted on the bottom of a pool: bright where the cells meet+ let wx = (fbm(x * 3.0, y * 3.0, 3, 3, 1381) - 0.5) * 0.15;+ let wy = (fbm(x * 3.0, y * 3.0, 3, 3, 1387) - 0.5) * 0.15;+ let (f1, f2) = cells(x + wx, y + wy, 8, 1391);+ 1.0 - smooth((f2 - f1) * 5.0)+ }),+ },+ GrayImage {+ name: "Leather",+ pixels: field(|x, y| {+ let (f1, f2) = cells(x, y, 24, 1401);+ let crease = smooth((f2 - f1) * 6.0) * (0.8 + 0.2 * f1);+ let pores = smooth((value_noise(x * 128.0, y * 128.0, 128, 1409) - 0.75) * 8.0);+ contrast(crease * (0.8 + 0.2 * fbm(x * 8.0, y * 8.0, 8, 2, 1405)) - 0.3 * pores, 1.3)+ }),+ },+ GrayImage {+ name: "Bark",+ pixels: field(|x, y| {+ // deep furrows running up and down+ let ridges = 1.0 - (fbm_xy(x * 16.0, y * 2.0, (16, 2), 4, 1411) * 2.0 - 1.0).abs();+ contrast(ridges.powf(1.5) * (0.8 + 0.2 * fbm(x * 32.0, y * 32.0, 32, 2, 1413)), 1.6)+ }),+ },+ GrayImage {+ name: "Scratches",+ pixels: {+ // fine lines every way across a worn surface+ let lines: Vec<(f32, f32, f32, f32, f32)> = (0..60)+ .map(|k| {+ let a = hash(k, 3, 1421) * PI;+ let len = 0.05 + 0.2 * hash(k, 4, 1421).powi(2);+ (hash(k, 1, 1421), hash(k, 2, 1421), a.cos() * len, a.sin() * len, 0.6 + 0.4 * hash(k, 5, 1421))+ })+ .collect();+ field(move |x, y| {+ let marks = lines.iter().fold(0.0f32, |acc, &(cx, cy, dx, dy, depth)| {+ // the nearest copy of the line, the image wrapping round+ let (u, v) = (x - cx - (x - cx).round(), y - cy - (y - cy).round());+ acc.max(smooth((0.002 - segment(u, v, (-dx, -dy), (dx, dy)).0) * 400.0) * depth)+ });+ (1.0 - 0.9 * marks) * (0.9 + 0.1 * fbm(x * 16.0, y * 16.0, 16, 2, 1427))+ })+ },+ },+ GrayImage {+ name: "Checker",+ pixels: field(|x, y| {+ // shifted by half a square, so its edges fall inside one, not between two+ let (i, j) = ((x * 16.0 + 0.5).floor() as i32, (y * 16.0 + 0.5).floor() as i32);+ f32::from(u8::from((i + j).rem_euclid(2) == 0))+ }),+ },+ GrayImage {+ name: "Speckle",+ pixels: field(|x, y| {+ // a sparse spray of tiny dots+ let (ci, cj) = ((x * 32.0).floor() as i32, (y * 32.0).floor() as i32);+ if hash(ci, cj, 1431) > 0.5 {+ return 0.0;+ }+ let (ox, oy) = (0.3 + 0.4 * hash(ci, cj, 1433), 0.3 + 0.4 * hash(ci, cj, 1437));+ let (fx, fy) = ((x * 32.0).fract() - ox, (y * 32.0).fract() - oy);+ smooth((0.1 + 0.2 * hash(ci, cj, 1439) - (fx * fx + fy * fy).sqrt()) * 10.0)+ }),+ },+ GrayImage {+ name: "Twill",+ pixels: field(|x, y| {+ // diagonal ribs, each thread showing in short steps+ let rib = 0.5 + 0.5 * ((x + y) * 32.0 * TAU).cos();+ let steps = 0.5 + 0.5 * (x * 64.0 * TAU).cos();+ contrast(0.6 * rib + 0.25 * steps + 0.15 * fbm(x * 32.0, y * 32.0, 32, 2, 1441), 1.5)+ }),+ },+ GrayImage {+ name: "Rust",+ pixels: field(|x, y| {+ // patches eaten away, pitted inside+ let n = fbm(x * 8.0, y * 8.0, 8, 5, 1451);+ let patches = smooth((n - 0.45) * 6.0);+ let pits = smooth((value_noise(x * 64.0, y * 64.0, 64, 1459) - 0.7) * 6.0);+ contrast(0.35 + 0.65 * patches * (1.0 - 0.6 * pits), 1.3)+ }),+ },+ GrayImage { name: "Recycled", pixels: recycled() },+ GrayImage { name: "Paper sheet", pixels: sheet() },+ GrayImage { name: "Worn paper", pixels: worn() },+ ];+ // stand-ins for stock grains: our own patterns with their values spread as measured from+ // brushes drawn with the stock ones+ let respread = |grains: &[GrayImage], from: u32, spread: &[(f32, f32)]| {+ let raw: Vec<f32> =+ grains.get(from as usize).map_or(Vec::new(), |g| g.pixels.iter().map(|&v| f32::from(v)).collect());+ ranked(&raw, spread)+ };+ let charcoal = respread(&grains, grain::COARSE, &CHARCOAL_SPREAD);+ let fine_noise = respread(&grains, grain::NOISE, &FINE_NOISE_SPREAD);+ let speckled = ranked(&soft_noise(1601, 0.4), &SPECKLED_SPREAD);+ grains.push(GrayImage { name: "Charcoal", pixels: charcoal });+ grains.push(GrayImage { name: "Fine noise", pixels: fine_noise });+ grains.push(GrayImage { name: "Speckled", pixels: speckled });+ grains.push(GrayImage { name: "Mottled", pixels: ranked(&soft_noise(4001, 0.4), &MOTTLED_SPREAD) });+ grains+}++/// The charcoal grain's values: most of it from 0.19 to 0.41, a fifth the bright tops of the tooth+/// (as measured from brushes drawn with stock charcoal grains, their stamps building up past it).+const CHARCOAL_SPREAD: [(f32, f32); 9] = [+ (0.0, 0.0),+ (0.188, 0.04),+ (0.225, 0.1),+ (0.262, 0.2),+ (0.3, 0.5),+ (0.338, 0.6),+ (0.413, 0.8),+ (1.0, 0.9),+ (1.0, 1.0),+];++/// The fine noise's values: narrow and dark, from about 0.14 to 0.39 (as measured from a brush+/// drawn with a stock noise grain).+const FINE_NOISE_SPREAD: [(f32, f32); 6] =+ [(0.075, 0.0), (0.141, 0.05), (0.191, 0.25), (0.235, 0.5), (0.279, 0.75), (0.39, 1.0)];++/// The speckled grain's values: a twentieth black, half under 0.09, thinning out up to 0.83. Read+/// between its texels (softened noise, a 230 px tile), it comes out as measured pixel by pixel+/// from a stock speckled grain against how far its stamps build up there (half under 0.095, up+/// to about 0.68), with grain 1.5 px across.+const SPECKLED_SPREAD: [(f32, f32); 15] = [+ (0.0, 0.0),+ (0.003, 0.05),+ (0.012, 0.1),+ (0.03, 0.2),+ (0.048, 0.3),+ (0.068, 0.4),+ (0.09, 0.5),+ (0.117, 0.6),+ (0.147, 0.7),+ (0.195, 0.8),+ (0.292, 0.9),+ (0.395, 0.95),+ (0.506, 0.98),+ (0.655, 0.99),+ (0.825, 1.0),+];++/// The mottled grain's values: mostly light, half over 0.6, from about 0.25 to 0.9 (as a stock+/// grain is applied, typically: the middle of those whose names say nothing of what they are).+const MOTTLED_SPREAD: [(f32, f32); 8] =+ [(0.0, 0.0), (0.25, 0.05), (0.4, 0.2), (0.55, 0.4), (0.65, 0.6), (0.75, 0.8), (0.88, 0.95), (1.0, 1.0)];++/// The paper sheet's values: narrow, nearly all from 0.11 to 0.5, half under 0.29 (a stock paper+/// grain's own values, half as light again, as the stand-ins measured against the reference's pad+/// all come out; narrow, a thin line drawn on it stays smooth).+const SHEET_SPREAD: [(f32, f32); 11] = [+ (0.0, 0.0),+ (0.03, 0.01),+ (0.106, 0.05),+ (0.153, 0.1),+ (0.217, 0.25),+ (0.294, 0.5),+ (0.377, 0.75),+ (0.459, 0.9),+ (0.506, 0.95),+ (0.606, 0.99),+ (0.9, 1.0),+];++/// A paper sheet: fine tooth, each texel its own (as the stock paper's, whose grain is a pixel or+/// two across), its values ranked onto [`SHEET_SPREAD`].+fn sheet() -> Vec<u8> {+ ranked(&soft_noise(3001, 0.0), &SHEET_SPREAD)+}++/// The worn paper's values, as [`RECYCLED_SPREAD`]: light, most of it full and hardly any under+/// 0.33 (as measured from a brush pressed into a stock worn paper).+const WORN_SPREAD: [(f32, f32); 8] =+ [(0.15, 0.0), (0.33, 0.02), (0.48, 0.12), (0.96, 0.3), (1.0, 0.41), (1.0, 0.85), (1.0, 0.99), (1.0, 1.0)];++/// Worn paper: mottled and scuffed, its values ranked onto [`WORN_SPREAD`].+fn worn() -> Vec<u8> {+ let n = TEXTURE_SIZE;+ let raw: Vec<f32> = (0..n * n)+ .map(|k| {+ let (u, v) = (((k % n) as f32 + 0.5) / n as f32, ((k / n) as f32 + 0.5) / n as f32);+ let mottle = fbm(u * 16.0, v * 16.0, 16, 4, 3101);+ let scuffs = value_noise(u * 128.0, v * 32.0, 128, 3109);+ 0.6 * mottle + 0.25 * scuffs + 0.15 * value_noise(u * 256.0, v * 256.0, 256, 3119)+ })+ .collect();+ ranked(&raw, &WORN_SPREAD)+}++/// `raw` values ranked onto `spread` ((value, share at or below it), rising): the darkest share+/// of them takes the darkest values, and so on.+fn ranked(raw: &[f32], spread: &[(f32, f32)]) -> Vec<u8> {+ let mut order: Vec<usize> = (0..raw.len()).collect();+ order.sort_by(|&a, &b| raw.get(a).unwrap_or(&0.0).total_cmp(raw.get(b).unwrap_or(&0.0)));+ let mut pixels = vec![0u8; raw.len()];+ let count = order.len().max(1) as f32;+ let last = spread.last().map_or(1.0, |s| s.0);+ for (rank, &k) in order.iter().enumerate() {+ let share = (rank as f32 + 0.5) / count;+ let at = spread.windows(2).find(|w| matches!(w, [_, b] if share <= b.1));+ let value = match at {+ Some([a, b]) => a.0 + (b.0 - a.0) * (share - a.1) / (b.1 - a.1).max(1e-6),+ _ => last,+ };+ if let Some(p) = pixels.get_mut(k) {+ *p = (value * 255.0).round().clamp(0.0, 255.0) as u8;+ }+ }+ pixels+}++/// The recycled paper's values, as a share of the image at or below each (value, share): about+/// an eighth dark fibre, little in between, the sheet itself light, most of it 0.8 and over.+const RECYCLED_SPREAD: [(f32, f32); 11] = [+ (0.0, 0.0),+ (0.075, 0.02),+ (0.225, 0.06),+ (0.33, 0.13),+ (0.48, 0.16),+ (0.81, 0.33),+ (0.96, 0.41),+ (1.0, 0.52),+ (1.0, 0.82),+ (1.0, 0.99),+ (1.0, 1.0),+];++/// Recycled paper: a light, mottled sheet flecked with small dark rough-edged bits, its values+/// ranked onto [`RECYCLED_SPREAD`].+fn recycled() -> Vec<u8> {+ const CELLS: i32 = 32;+ let n = TEXTURE_SIZE;+ // the distance from texel (x, y) to the nearest fleck, in texels: a short segment, at most one+ // to a cell, wrapping so the image tiles+ let cell = n as f32 / CELLS as f32;+ let fibre = |x: f32, y: f32| -> f32 {+ let (ci, cj) = ((x / cell).floor() as i32, (y / cell).floor() as i32);+ let mut nearest = f32::MAX;+ for dj in -1..=1 {+ for di in -1..=1 {+ let (i, j) = (ci + di, cj + dj);+ let (wi, wj) = (i.rem_euclid(CELLS), j.rem_euclid(CELLS));+ if hash(wi, wj, 2011) > 0.62 {+ continue;+ }+ let centre = ((i as f32 + hash(wi, wj, 2017)) * cell, (j as f32 + hash(wi, wj, 2027)) * cell);+ let turn = hash(wi, wj, 2029) * std::f32::consts::PI;+ let half = 0.3 + 1.7 * hash(wi, wj, 2039);+ let (dx, dy) = (x - centre.0, y - centre.1);+ let (c, s) = (turn.cos(), turn.sin());+ let along = (dx * c + dy * s).clamp(-half, half);+ let (ex, ey) = (dx - along * c, dy - along * s);+ nearest = nearest.min((ex * ex + ey * ey).sqrt());+ }+ }+ nearest+ };+ let raw: Vec<f32> = (0..n * n)+ .map(|k| {+ let (x, y) = ((k % n) as f32 + 0.5, (k / n) as f32 + 0.5);+ let (u, v) = (x / n as f32, y / n as f32);+ let sheet = 0.6 * fbm(u * 16.0, v * 16.0, 16, 4, 2003) + 0.4 * value_noise(u * 128.0, v * 128.0, 128, 2053);+ let rough = 0.8 + 0.9 * value_noise(u * 256.0, v * 256.0, 256, 2063);+ sheet - 1.5 * smooth(1.0 - fibre(x, y) / rough)+ })+ .collect();+ ranked(&raw, &RECYCLED_SPREAD)+}++/// An image from `f(x, y)` with x, y in 0..1 at pixel centres and values clamped to 0..1.+/// Bands of rows are made side by side, one to a core.+fn field(f: impl Fn(f32, f32) -> f32 + Sync) -> Vec<u8> {+ let n = TEXTURE_SIZE;+ let mut out = vec![0u8; n * n];+ let threads = std::thread::available_parallelism().map_or(1, |t| t.get()).clamp(1, 8);+ let rows = n.div_ceil(threads);+ std::thread::scope(|s| {+ for (band, pixels) in out.chunks_mut(rows * n).enumerate() {+ let f = &f;+ s.spawn(move || {+ for (k, px) in pixels.iter_mut().enumerate() {+ let (i, j) = (k % n, band * rows + k / n);+ let v = f((i as f32 + 0.5) / n as f32, (j as f32 + 0.5) / n as f32);+ *px = (v.clamp(0.0, 1.0) * 255.0).round() as u8;+ }+ });+ }+ });+ out+}++/// White noise softened over each texel's neighbours by `side` (`side`, 1, `side` each way,+/// wrapping round, so it tiles).+fn soft_noise(seed: u32, side: f32) -> Vec<f32> {+ let n = TEXTURE_SIZE as i32;+ let at = |i: i32, j: i32| hash(i.rem_euclid(n), j.rem_euclid(n), seed);+ let weight = |d: i32| if d == 0 { 1.0 } else { side };+ (0..n * n)+ .map(|k| {+ let (i, j) = (k % n, k / n);+ let mut v = 0.0;+ for dj in -1..=1 {+ for di in -1..=1 {+ v += weight(di) * weight(dj) * at(i + di, j + dj);+ }+ }+ v+ })+ .collect()+}++/// Distance from the centre, 1 at the inscribed circle.+fn radius(x: f32, y: f32) -> f32 {+ ((x - 0.5).powi(2) + (y - 0.5).powi(2)).sqrt() * 2.0+}++fn smooth(t: f32) -> f32 {+ let t = t.clamp(0.0, 1.0);+ t * t * (3.0 - 2.0 * t)+}++fn contrast(v: f32, k: f32) -> f32 {+ ((v - 0.5) * k + 0.5).clamp(0.0, 1.0)+}++/// A hash of a lattice point to 0..1.+fn hash(x: i32, y: i32, seed: u32) -> f32 {+ let mut h =+ (x as u32).wrapping_mul(0x8da6_b343) ^ (y as u32).wrapping_mul(0xd816_3841) ^ seed.wrapping_mul(0xcb1a_b31f);+ h ^= h >> 13;+ h = h.wrapping_mul(0x5bd1_e995);+ h ^= h >> 15;+ (h & 0x00ff_ffff) as f32 / 0x00ff_ffff as f32+}++/// Value noise on a lattice that repeats every `period` cells, so the image tiles.+fn value_noise(x: f32, y: f32, period: i32, seed: u32) -> f32 {+ value_noise_xy(x, y, (period, period), seed)+}++/// Value noise on a lattice that repeats every `period.0` cells across and `period.1` down.+fn value_noise_xy(x: f32, y: f32, period: (i32, i32), seed: u32) -> f32 {+ let (xi, yi) = (x.floor() as i32, y.floor() as i32);+ let (fx, fy) = (smooth(x - xi as f32), smooth(y - yi as f32));+ let (px, py) = (period.0.max(1), period.1.max(1));+ let at = |i: i32, j: i32| hash(i.rem_euclid(px), j.rem_euclid(py), seed);+ let top = at(xi, yi) + (at(xi + 1, yi) - at(xi, yi)) * fx;+ let bottom = at(xi, yi + 1) + (at(xi + 1, yi + 1) - at(xi, yi + 1)) * fx;+ top + (bottom - top) * fy+}++/// Fractal value noise: `octaves` layers, each at twice the frequency (and period) of the last.+fn fbm(x: f32, y: f32, period: i32, octaves: u32, seed: u32) -> f32 {+ fbm_xy(x, y, (period, period), octaves, seed)+}++/// [`fbm`] repeating every `period.0` cells across and `period.1` down.+fn fbm_xy(x: f32, y: f32, period: (i32, i32), octaves: u32, seed: u32) -> f32 {+ let (mut sum, mut amp, mut norm, mut f) = (0.0, 0.5, 0.0, 1.0f32);+ for o in 0..octaves {+ let p = (period.0 * f as i32, period.1 * f as i32);+ sum += amp * value_noise_xy(x * f, y * f, p, seed.wrapping_add(o * 7919));+ norm += amp;+ amp *= 0.5;+ f *= 2.0;+ }+ sum / norm+}++/// A heart's outline (in −1..1, point down), from the usual sum of cosines.+fn heart() -> Vec<(f32, f32)> {+ (0..96)+ .map(|i| {+ let t = i as f32 / 96.0 * TAU;+ let x = 16.0 * t.sin().powi(3);+ let y = 13.0 * t.cos() - 5.0 * (2.0 * t).cos() - 2.0 * (3.0 * t).cos() - (4.0 * t).cos();+ (x / 19.0, -(y + 2.5) / 19.0)+ })+ .collect()+}++/// A line drawn in a shape: its two ends and its half width.+type Line = ((f32, f32), (f32, f32), f32);++/// `x`, `y` (0..1) as −1..1 from the centre.+fn centred(x: f32, y: f32) -> (f32, f32) {+ ((x - 0.5) * 2.0, (y - 0.5) * 2.0)+}++/// The distance from (`x`, `y`) to the segment `a`–`b`, and how far along it (0..1) the nearest+/// point is.+fn segment(x: f32, y: f32, a: (f32, f32), b: (f32, f32)) -> (f32, f32) {+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);+ let len2 = (dx * dx + dy * dy).max(1e-12);+ let t = (((x - a.0) * dx + (y - a.1) * dy) / len2).clamp(0.0, 1.0);+ (((x - a.0 - dx * t).powi(2) + (y - a.1 - dy * t).powi(2)).sqrt(), t)+}++/// The distance from (`x`, `y`) to the edge of the polygon through `corners`, and whether the+/// point is inside it.+fn polygon(corners: &[(f32, f32)], x: f32, y: f32) -> (f32, bool) {+ let mut edge = f32::MAX;+ let mut inside = false;+ for (i, &a) in corners.iter().enumerate() {+ let b = corners.get((i + 1) % corners.len()).copied().unwrap_or(a);+ edge = edge.min(segment(x, y, a, b).0);+ if (a.1 > y) != (b.1 > y) && x < (b.0 - a.0) * (y - a.1) / (b.1 - a.1) + a.0 {+ inside = !inside;+ }+ }+ (edge, inside)+}++/// The distances to the nearest and second nearest of points scattered one to a cell, `n` cells+/// across, the cells wrapping round so the image tiles (in cell widths).+fn cells(x: f32, y: f32, n: i32, seed: u32) -> (f32, f32) {+ let (px, py) = (x * n as f32, y * n as f32);+ let (ci, cj) = (px.floor() as i32, py.floor() as i32);+ let (mut f1, mut f2) = (f32::MAX, f32::MAX);+ for j in cj - 1..=cj + 1 {+ for i in ci - 1..=ci + 1 {+ let (wi, wj) = (i.rem_euclid(n), j.rem_euclid(n));+ let (ox, oy) = (hash(wi, wj, seed), hash(wi, wj, seed.wrapping_add(1)));+ let d = ((i as f32 + ox - px).powi(2) + (j as f32 + oy - py).powi(2)).sqrt();+ (f1, f2) = if d < f1 { (d, f1) } else { (f1, f2.min(d)) };+ }+ }+ (f1, f2)+}++/// Cracks spreading from the middle (in −1..1): three jagged lines, each with a few side cracks,+/// as segments (start, end, half width).+fn cracks(seed: u32) -> Vec<Line> {+ /// `steps` steps of a jagged line from `from` (its heading wandering), stopping short of the+ /// edge; where it ended up and its heading there.+ fn walk(+ lines: &mut Vec<Line>,+ from: (f32, f32),+ heading: f32,+ steps: i32,+ width: f32,+ k: i32,+ seed: u32,+ ) -> ((f32, f32), f32) {+ let (mut at, mut a) = (from, heading);+ for s in 0..steps {+ a += hash(k, s, seed) - 0.5;+ let next = (at.0 + a.cos() * 0.15, at.1 + a.sin() * 0.15);+ if (next.0 * next.0 + next.1 * next.1).sqrt() > 0.92 {+ break;+ }+ lines.push((at, next, width * (1.0 - s as f32 / steps as f32 * 0.5)));+ at = next;+ }+ (at, a)+ }+ let mut lines = Vec::new();+ let mut branches = Vec::new();+ for k in 0..3 {+ let (mut at, mut heading) = ((0.0, 0.0), (k as f32 + hash(k, 99, seed) * 0.4) / 3.0 * TAU);+ for part in 0..3 {+ (at, heading) = walk(&mut lines, at, heading, 2, 0.03 - part as f32 * 0.007, k * 10 + part, seed);+ branches.push((at, heading + (hash(k, part + 50, seed) - 0.5) * 2.4));+ }+ }+ for (i, (from, heading)) in branches.into_iter().enumerate() {+ walk(&mut lines, from, heading, 3, 0.012, 100 + i as i32, seed);+ }+ lines+}++/// `count` dots (centre x, centre y, radius) inside the image, deterministic for `seed`.+fn scatter_points(seed: u32, count: i32) -> Vec<(f32, f32, f32)> {+ (0..count)+ .map(|i| {+ let a = hash(i, 1, seed) * std::f32::consts::TAU;+ let d = hash(i, 2, seed).sqrt() * 0.38;+ (0.5 + a.cos() * d, 0.5 + a.sin() * d, 0.02 + 0.07 * hash(i, 3, seed).powi(2))+ })+ .collect()+}++/// How a grain is made to repeat without seams (the grain editor's Auto repeat).+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Repeat {+ /// The image this many times across the tile, 1 to 4.+ pub scale: f32,+ /// Turned by this much, radians.+ pub rotation: f32,+ /// How far in from the tile's edges the image is faded into its shifted copy, 0..1 (1: to+ /// the middle).+ pub overlap: f32,+ /// How sharp that fade is, 0 (soft) to 1 (hard).+ pub hardness: f32,+ /// Fade into the shifted copy turned round, not just shifted.+ pub mirror: bool,+ /// Fade the fine detail over a narrower band than the broad tones.+ pub pyramid: bool,+}++/// `pixels` (a `TEXTURE_SIZE` square greyscale image; anything else comes back unchanged) made to+/// tile without seams as `repeat` says: faded at its edges into a copy shifted by half a tile,+/// which runs on across them, then scaled and turned (wrapping round) and faded again.+pub fn repeatable(pixels: &[u8], repeat: Repeat) -> Vec<u8> {+ let n = TEXTURE_SIZE;+ if pixels.len() != n * n {+ return pixels.to_vec();+ }+ let img: Vec<f32> = pixels.iter().map(|&v| f32::from(v)).collect();+ let seamless = blend_edges(&img, repeat);+ let scale = if repeat.scale.is_finite() { repeat.scale.clamp(1.0, 4.0) } else { 1.0 };+ let rotation = if repeat.rotation.is_finite() { repeat.rotation } else { 0.0 };+ let out = if (scale - 1.0).abs() < 1e-4 && rotation.abs() < 1e-4 {+ seamless+ } else {+ // the seamless image read through the scale and turn, wrapping round, its edges faded again+ let (sin, cos) = rotation.sin_cos();+ let half = n as f32 / 2.0;+ let mut moved = vec![0.0; n * n];+ for y in 0..n {+ for x in 0..n {+ let (dx, dy) = (x as f32 + 0.5 - half, y as f32 + 0.5 - half);+ let u = (dx * cos + dy * sin) * scale + half;+ let v = (-dx * sin + dy * cos) * scale + half;+ if let Some(px) = moved.get_mut(y * n + x) {+ *px = sample_wrapped(&seamless, n, u - 0.5, v - 0.5);+ }+ }+ }+ blend_edges(&moved, repeat)+ };+ out.iter().map(|&v| v.round().clamp(0.0, 255.0) as u8).collect()+}++/// `img` faded at its edges into its copy shifted by half a tile (turned round too, with+/// mirror), over a band `overlap` of the way to the middle.+fn blend_edges(img: &[f32], repeat: Repeat) -> Vec<f32> {+ let n = TEXTURE_SIZE;+ let half = n / 2;+ let at = |x: usize, y: usize| img.get(y * n + x).copied().unwrap_or(0.0);+ let other: Vec<f32> = (0..n * n)+ .map(|i| {+ let (x, y) = ((i % n + half) % n, (i / n + half) % n);+ if repeat.mirror { at(n - 1 - x, n - 1 - y) } else { at(x, y) }+ })+ .collect();+ let overlap = if repeat.overlap.is_finite() { repeat.overlap.clamp(0.0, 1.0) } else { 1.0 };+ let width = overlap * half as f32;+ if width < 1.0 {+ return img.to_vec();+ }+ let hardness = if repeat.hardness.is_finite() { repeat.hardness.clamp(0.0, 1.0) } else { 0.0 };+ // how much of the image itself shows at (x, y): none at the edges, all a band in+ let mask = |x: usize, y: usize, band: f32| {+ let d = x.min(n - 1 - x).min(y).min(n - 1 - y) as f32 + 0.5;+ let t = (d / band.max(1.0)).clamp(0.0, 1.0);+ smooth((t - 0.5) * (1.0 + hardness * 8.0) + 0.5)+ };+ let mix = |a: &[f32], b: &[f32], band: f32| -> Vec<f32> {+ (0..n * n)+ .map(|i| {+ let m = mask(i % n, i / n, band);+ let (p, q) = (a.get(i).copied().unwrap_or(0.0), b.get(i).copied().unwrap_or(0.0));+ p * m + q * (1.0 - m)+ })+ .collect()+ };+ if !repeat.pyramid {+ return mix(img, &other, width);+ }+ // broad tones over the whole band, fine detail over a third of it+ let (low_a, low_b) = (blurred(img, n / 32), blurred(&other, n / 32));+ let high = |v: &[f32], low: &[f32]| v.iter().zip(low).map(|(a, b)| a - b).collect::<Vec<f32>>();+ let tones = mix(&low_a, &low_b, width);+ let detail = mix(&high(img, &low_a), &high(&other, &low_b), width / 3.0);+ tones.iter().zip(&detail).map(|(a, b)| a + b).collect()+}++/// A box blur of radius `r` over the square image, wrapping round its edges.+fn blurred(img: &[f32], r: usize) -> Vec<f32> {+ let n = TEXTURE_SIZE;+ let span = (2 * r + 1) as f32;+ let pass = |src: &[f32], across: bool| -> Vec<f32> {+ let at = |a: usize, b: usize| {+ let (x, y) = if across { (a % n, b) } else { (b, a % n) };+ src.get(y * n + x).copied().unwrap_or(0.0)+ };+ let mut out = vec![0.0; n * n];+ for b in 0..n {+ for a in 0..n {+ let sum: f32 = (0..=2 * r).map(|k| at(a + n - r + k, b)).sum();+ let (x, y) = if across { (a, b) } else { (b, a) };+ if let Some(px) = out.get_mut(y * n + x) {+ *px = sum / span;+ }+ }+ }+ out+ };+ pass(&pass(img, true), false)+}++/// The image at (`u`, `v`) (pixel corners at whole numbers), bilinear, wrapping round.+fn sample_wrapped(img: &[f32], n: usize, u: f32, v: f32) -> f32 {+ let (fx, fy) = (u.floor(), v.floor());+ let (tx, ty) = (u - fx, v - fy);+ let wrap = |c: f32| (c as i64).rem_euclid(n as i64) as usize;+ let at = |x: f32, y: f32| img.get(wrap(y) * n + wrap(x)).copied().unwrap_or(0.0);+ let top = at(fx, fy) * (1.0 - tx) + at(fx + 1.0, fy) * tx;+ let bottom = at(fx, fy + 1.0) * (1.0 - tx) + at(fx + 1.0, fy + 1.0) * tx;+ top * (1.0 - ty) + bottom * ty+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn images_have_the_right_size_and_content() {+ for img in shapes().into_iter().chain(grains()) {+ assert_eq!(img.pixels.len(), TEXTURE_SIZE * TEXTURE_SIZE, "{}", img.name);+ let max = *img.pixels.iter().max().unwrap();+ let min = *img.pixels.iter().min().unwrap();+ // (a stand-in spread as measured may stay dark, as the fine noise does)+ assert!(max >= min + 48, "{} has contrast", img.name);+ }+ }++ #[test]+ fn shapes_are_empty_at_the_corners() {+ for img in shapes() {+ assert!(img.pixels[0] < 8, "{} corner {}", img.name, img.pixels[0]);+ }+ }++ #[test]+ fn grains_tile() {+ // the left column continues from the right one as any column does from its neighbour+ for img in grains() {+ let n = TEXTURE_SIZE;+ let step = |a: usize, b: usize| -> u32 {+ (0..n).map(|j| u32::from(img.pixels[j * n + a].abs_diff(img.pixels[j * n + b]))).sum::<u32>() / n as u32+ };+ let inside = (1..n).map(|i| step(i - 1, i)).sum::<u32>() / (n as u32 - 1);+ let seam = step(n - 1, 0);+ assert!(seam <= inside * 3 / 2 + 6, "{} seam {seam}, inside {inside}", img.name);+ }+ }++ /// Writes every shape and grain as a PGM into the directory in `PROCRAFT_DUMP`, for looking at+ /// them: `cargo test -p procraft-engine dump_textures -- --ignored`.+ #[test]+ #[ignore]+ fn dump_textures() {+ let Ok(dir) = std::env::var("PROCRAFT_DUMP") else { return };+ for (kind, images) in [("shape", shapes()), ("grain", grains())] {+ for (i, img) in images.iter().enumerate() {+ let mut pgm = format!(+ "P5 {TEXTURE_SIZE} {TEXTURE_SIZE} 255+"+ )+ .into_bytes();+ pgm.extend(&img.pixels);+ std::fs::write(format!("{dir}/{kind}-{i:02}-{}.pgm", img.name.replace(' ', "_")), pgm).unwrap();+ }+ }+ }++ #[test]+ fn generation_is_deterministic() {+ assert_eq!(shapes(), shapes());+ assert_eq!(grains(), grains());+ }++ #[test]+ fn a_repeated_grain_has_no_seams() {+ let n = TEXTURE_SIZE;+ // a ramp: a hard edge where it wraps round+ let ramp: Vec<u8> = (0..n * n).map(|i| (i % n * 255 / (n - 1)) as u8).collect();+ let jump =+ |img: &[u8]| (0..n).map(|y| (i32::from(img[y * n]) - i32::from(img[y * n + n - 1])).abs()).max().unwrap();+ assert!(jump(&ramp) > 200);+ let base = Repeat { scale: 1.0, rotation: 0.0, overlap: 1.0, hardness: 0.0, mirror: false, pyramid: false };+ for r in [+ base,+ Repeat { mirror: true, ..base },+ Repeat { pyramid: true, ..base },+ Repeat { scale: 2.0, rotation: 0.6, ..base },+ ] {+ let out = repeatable(&ramp, r);+ assert!(jump(&out) <= 6, "{r:?}: {}", jump(&out));+ }+ // no overlap: left as it was+ assert_eq!(repeatable(&ramp, Repeat { overlap: 0.0, ..base }), ramp);+ assert_eq!(repeatable(&[1, 2, 3], base), vec![1, 2, 3]);+ }+}diff --git a/crates/engine/src/tone.rs b/crates/engine/src/tone.rsnew file mode 100644index 0000000..2104097--- /dev/null+++ b/crates/engine/src/tone.rs@@ -0,0 +1,132 @@+//! Tone tables for adjustments: a curve through points (a natural cubic spline) and a gradient+//! between colour stops, each baked into 256 entries.++/// A curve through `points` (x and y in 0..1, any order): a natural cubic spline through them,+/// held flat beyond the first and last, baked into 256 entries 0..255. With fewer than two points,+/// the straight line from (0, 0) to (1, 1).+pub fn curve_table(points: &[(f32, f32)]) -> [u8; 256] {+ let mut pts: Vec<(f32, f32)> = points.iter().copied().filter(|(x, y)| x.is_finite() && y.is_finite()).collect();+ pts.sort_by(|a, b| a.0.total_cmp(&b.0));+ pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6);+ if pts.len() < 2 {+ pts = vec![(0.0, 0.0), (1.0, 1.0)];+ }+ let second = natural_second_derivatives(&pts);+ std::array::from_fn(|i| {+ let x = i as f32 / 255.0;+ let y = spline_at(&pts, &second, x);+ (y.clamp(0.0, 1.0) * 255.0).round() as u8+ })+}++/// The second derivatives at the points of the natural cubic spline through them (zero at both+/// ends), by the tridiagonal system's sweep.+fn natural_second_derivatives(pts: &[(f32, f32)]) -> Vec<f32> {+ let n = pts.len();+ let mut m = vec![0.0f32; n];+ if n < 3 {+ return m;+ }+ let mut up = vec![0.0f32; n];+ for i in 1..n - 1 {+ let (Some(&(x0, y0)), Some(&(x1, y1)), Some(&(x2, y2))) = (pts.get(i - 1), pts.get(i), pts.get(i + 1)) else {+ continue;+ };+ let sig = (x1 - x0) / (x2 - x0);+ let p = sig * m.get(i - 1).copied().unwrap_or(0.0) + 2.0;+ if let Some(v) = m.get_mut(i) {+ *v = (sig - 1.0) / p;+ }+ let slope = (y2 - y1) / (x2 - x1) - (y1 - y0) / (x1 - x0);+ let prev = up.get(i - 1).copied().unwrap_or(0.0);+ if let Some(u) = up.get_mut(i) {+ *u = (6.0 * slope / (x2 - x0) - sig * prev) / p;+ }+ }+ // back substitution, the last second derivative zero+ let mut second = vec![0.0f32; n];+ for i in (1..n - 1).rev() {+ let next = second.get(i + 1).copied().unwrap_or(0.0);+ let value = m.get(i).copied().unwrap_or(0.0) * next + up.get(i).copied().unwrap_or(0.0);+ if let Some(s) = second.get_mut(i) {+ *s = value;+ }+ }+ second+}++/// The spline through `pts` (with second derivatives `second`) at `x`, flat beyond its ends.+fn spline_at(pts: &[(f32, f32)], second: &[f32], x: f32) -> f32 {+ let (Some(&(first_x, first_y)), Some(&(last_x, last_y))) = (pts.first(), pts.last()) else { return x };+ if x <= first_x {+ return first_y;+ }+ if x >= last_x {+ return last_y;+ }+ let hi = pts.iter().position(|p| p.0 >= x).unwrap_or(pts.len() - 1).max(1);+ let lo = hi - 1;+ let (Some(&(x0, y0)), Some(&(x1, y1))) = (pts.get(lo), pts.get(hi)) else { return x };+ let (m0, m1) = (second.get(lo).copied().unwrap_or(0.0), second.get(hi).copied().unwrap_or(0.0));+ let h = x1 - x0;+ let a = (x1 - x) / h;+ let b = (x - x0) / h;+ a * y0 + b * y1 + ((a * a * a - a) * m0 + (b * b * b - b) * m1) * h * h / 6.0+}++/// A gradient between colour `stops` (position 0..1 and RGB 0..1, any order), baked into 256 RGB+/// entries, held at the end colours beyond the first and last stop. Black to white without stops.+pub fn gradient_table(stops: &[(f32, [f32; 3])]) -> [[u8; 3]; 256] {+ let mut s: Vec<(f32, [f32; 3])> = stops.iter().copied().filter(|(p, _)| p.is_finite()).collect();+ s.sort_by(|a, b| a.0.total_cmp(&b.0));+ if s.is_empty() {+ s = vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])];+ }+ let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;+ std::array::from_fn(|i| {+ let x = i as f32 / 255.0;+ let next = s.iter().position(|st| st.0 >= x);+ let colour = match next {+ Some(0) | None => s.get(if next.is_none() { s.len() - 1 } else { 0 }).map_or([0.0; 3], |st| st.1),+ Some(k) => {+ let (Some(a), Some(b)) = (s.get(k - 1), s.get(k)) else { return [0; 3] };+ let t = if b.0 > a.0 { (x - a.0) / (b.0 - a.0) } else { 0.0 };+ [0, 1, 2]+ .map(|c| a.1.get(c).copied().unwrap_or(0.0) * (1.0 - t) + b.1.get(c).copied().unwrap_or(0.0) * t)+ }+ };+ colour.map(byte)+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_straight_curve_leaves_tones_alone_and_points_bend_it() {+ let straight = curve_table(&[]);+ assert_eq!(straight[0], 0);+ assert_eq!(straight[128], 128);+ assert_eq!(straight[255], 255);+ // through (0.5, 0.75): the midtones lift, the ends stay+ let lifted = curve_table(&[(0.0, 0.0), (0.5, 0.75), (1.0, 1.0)]);+ assert_eq!(lifted[0], 0);+ assert!((i32::from(lifted[128]) - 191).abs() <= 2, "{}", lifted[128]);+ assert_eq!(lifted[255], 255);+ assert!(lifted[64] > 64 && lifted[192] > 192);+ // held flat beyond its ends+ let short = curve_table(&[(0.25, 0.1), (0.75, 0.9)]);+ assert_eq!(short[0], short[60]);+ assert_eq!(short[255], 230);+ }++ #[test]+ fn a_gradient_runs_between_its_stops() {+ let g = gradient_table(&[(1.0, [1.0, 1.0, 0.0]), (0.0, [0.0, 0.0, 1.0])]);+ assert_eq!(g[0], [0, 0, 255]);+ assert_eq!(g[255], [255, 255, 0]);+ assert_eq!(g[128], [128, 128, 127]);+ assert_eq!(gradient_table(&[])[255], [255, 255, 255]);+ }+}diff --git a/crates/engine/src/transform.rs b/crates/engine/src/transform.rsnew file mode 100644index 0000000..3076fbb--- /dev/null+++ b/crates/engine/src/transform.rs@@ -0,0 +1,871 @@+//! Transforming a layer's content: the box drawn around it, and how its handles, the toolbar's+//! actions and undo change where the content goes.+//!+//! The content's place is the quad its source rectangle's corners are carried to; the box is+//! usually that quad, but turning the box alone (the node below it) leaves the content where it is+//! and fits the box around it at the new angle. Every change to the box carries the content with+//! it through the map from the old box to the new one.+//!+//! A warp lays a 4 × 4 mesh (`warp.rs`) over the content; once there is one it places the content,+//! and the box is its corners.++use crate::geom::{Affine, Homography, Vec2};+use crate::warp::{self, Mesh};++/// How the box's handles change the content.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TransformMode {+ /// Corners and edges stretch the box along its own axes.+ Freeform,+ /// Corners and edges scale the box, keeping its proportions.+ Uniform,+ /// Corners move on their own; edges move both their corners.+ Distort,+ /// The content is bent through a mesh: its points, or the surface between them, are dragged.+ Warp,+}++/// What a drag holds.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Handle {+ /// A corner node: 0 top left, 1 top right, 2 bottom right, 3 bottom left.+ Corner(u8),+ /// The node in the middle of an edge: 0 top, 1 right, 2 bottom, 3 left.+ Edge(u8),+ /// The node above the box: turns the content about the box's centre.+ Rotate,+ /// The node below the box: turns the box alone, which then fits the content again.+ TurnBox,+ /// Anywhere else: moves the content (in a warp, drags the mesh's surface under the touch).+ Move,+ /// One of a warp's 16 control points, row by row.+ Mesh(u8),+}++/// Four corners: top left, top right, bottom right, bottom left.+pub type Quad = [Vec2; 4];++#[derive(Clone, Copy, Debug, PartialEq)]+struct Placement {+ content: Quad,+ frame: Quad,+ warp: Option<Mesh>,+}++/// An open transform.+#[derive(Clone, Debug)]+pub struct Transform {+ source: Quad,+ /// The convex hull of the content's pixels, in source coordinates.+ hull: Vec<Vec2>,+ now: Placement,+ history: Vec<Placement>,+ /// The handle held, where the drag started and the placement then.+ drag: Option<(Handle, Vec2, Placement)>,+ /// Lines a moved box snaps onto besides the canvas's own (canvas pixels): other layers'+ /// edges and middles, across (x) and down (y).+ snap_lines: (Vec<f32>, Vec<f32>),+}++/// What a drag is pulled towards.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct Guides {+ /// Moves keep to 15° directions once past `lock_after`, and turns to 15° steps.+ pub magnetics: bool,+ /// How far (canvas pixels) a move goes before its direction locks.+ pub lock_after: f32,+ /// A moved box's edges and centre this near (canvas pixels) the canvas's edges or centre go+ /// onto them; none for no snapping.+ pub snap: Option<f32>,+ /// The canvas's size.+ pub canvas: Vec2,+}++/// Smallest scale a handle can bring the box to.+const MIN_SCALE: f32 = 0.01;++/// The step magnetics keeps directions and turns to.+const MAGNETIC_STEP: f32 = std::f32::consts::PI / 12.0;++impl Transform {+ /// A transform of the content inside the rectangle (`x`, `y`, `width`, `height`, canvas+ /// pixels) whose pixels' convex hull is `hull`.+ pub fn new(x: f32, y: f32, width: f32, height: f32, hull: Vec<Vec2>) -> Transform {+ let source =+ [Vec2::new(x, y), Vec2::new(x + width, y), Vec2::new(x + width, y + height), Vec2::new(x, y + height)];+ let now = Placement { content: source, frame: source, warp: None };+ Transform { source, hull, now, history: Vec::new(), drag: None, snap_lines: (Vec::new(), Vec::new()) }+ }++ /// Other things a moved box snaps onto: their bounds (`x`, `y`, `width`, `height`, canvas+ /// pixels), by their edges and middles.+ pub fn set_snap_targets(&mut self, bounds: &[[f32; 4]]) {+ let ok = |v: &f32| v.is_finite();+ self.snap_lines = (+ bounds.iter().flat_map(|&[x, _, w, _]| [x, x + w / 2.0, x + w]).filter(ok).collect(),+ bounds.iter().flat_map(|&[_, y, _, h]| [y, y + h / 2.0, y + h]).filter(ok).collect(),+ );+ }++ /// The source rectangle's corners.+ pub fn source(&self) -> Quad {+ self.source+ }++ /// Where the source rectangle's corners are now.+ pub fn content(&self) -> Quad {+ self.now.content+ }++ /// The box shown around the content.+ pub fn frame(&self) -> Quad {+ self.now.frame+ }++ /// The warp's mesh, once there is one.+ pub fn warp(&self) -> Option<Mesh> {+ self.now.warp+ }++ pub fn can_undo(&self) -> bool {+ !self.history.is_empty()+ }++ /// Lays a warp's mesh evenly over the content, unless there is one already (not a step of its+ /// own: nothing moves).+ pub fn start_warp(&mut self) {+ if self.now.warp.is_none() {+ self.now.warp = Some(warp::over_quad(self.now.content));+ self.now.frame = self.now.content;+ }+ }++ /// A drag of `handle` starts at canvas point `at`.+ pub fn grab(&mut self, handle: Handle, at: Vec2) {+ self.drag = Some((handle, at, self.now));+ }++ /// The drag reached canvas point `to`, in `mode`, pulled by `guides`. Returns whether+ /// anything moved.+ pub fn drag(&mut self, mode: TransformMode, to: Vec2, guides: &Guides) -> bool {+ let Some((handle, from, start)) = self.drag else { return false };+ if !to.is_finite() {+ return false;+ }+ let next = self.dragged(handle, mode, from, to, start, guides).unwrap_or(start);+ let moved = next != self.now;+ self.now = next;+ moved+ }++ /// The drag ends; a change is kept as an undo step.+ pub fn release(&mut self) {+ if let Some((_, _, start)) = self.drag.take()+ && start != self.now+ {+ self.history.push(start);+ }+ }++ /// The drag is abandoned (a second finger came down): the box goes back.+ pub fn cancel_drag(&mut self) {+ if let Some((_, _, start)) = self.drag.take() {+ self.now = start;+ }+ }++ /// Mirrors the content across the box's upright axis.+ pub fn flip_horizontal(&mut self) {+ let [a, b, c, d] = self.now.frame;+ self.change(|p| {+ let content = carry(p, [b, a, d, c])?;+ // a mesh mirrors by taking its columns in the other order+ let warp =+ p.warp.map(|m| std::array::from_fn(|k| m.get(k / 4 * 4 + 3 - k % 4).copied().unwrap_or_default()));+ Some(Placement { content, frame: p.frame, warp })+ });+ }++ /// Mirrors the content across the box's level axis.+ pub fn flip_vertical(&mut self) {+ let [a, b, c, d] = self.now.frame;+ self.change(|p| {+ let content = carry(p, [d, c, b, a])?;+ let warp =+ p.warp.map(|m| std::array::from_fn(|k| m.get((3 - k / 4) * 4 + k % 4).copied().unwrap_or_default()));+ Some(Placement { content, frame: p.frame, warp })+ });+ }++ /// Turns the box and content by `radians` (clockwise on screen) about the box's centre.+ pub fn rotate(&mut self, radians: f32) {+ let c = centre(self.now.frame);+ let m = Affine::translate(Vec2::ZERO - c).then(Affine::rotate(radians)).then(Affine::translate(c));+ self.change(|p| Some(map_placement(p, m)));+ }++ /// The box's width and height (canvas pixels), along its top and left edges.+ pub fn size(&self) -> (f32, f32) {+ let [a, b, _, d] = self.now.frame;+ (a.distance(b), a.distance(d))+ }++ /// How far the box is turned from upright (radians, clockwise on screen).+ pub fn angle(&self) -> f32 {+ let [a, b, ..] = self.now.frame;+ angle(b - a)+ }++ /// Makes the box `width` × `height` (canvas pixels) about its centre, turned as it is: a+ /// size typed in. A negative size mirrors the content that way.+ pub fn set_size(&mut self, width: f32, height: f32) {+ let (w, h) = self.size();+ if !(width.is_finite() && height.is_finite()) || width.abs() < 1.0 || height.abs() < 1.0 || w <= 0.0 || h <= 0.0+ {+ return;+ }+ let c = centre(self.now.frame);+ let turn = self.angle();+ let stretch = Affine { a: width.abs() / w, d: height.abs() / h, ..Affine::IDENTITY };+ let m = Affine::translate(Vec2::ZERO - c)+ .then(Affine::rotate(-turn))+ .then(stretch)+ .then(Affine::rotate(turn))+ .then(Affine::translate(c));+ self.change(|p| Some(map_placement(p, m)));+ if width < 0.0 {+ self.flip_horizontal();+ }+ if height < 0.0 {+ self.flip_vertical();+ }+ }++ /// Turns the box to `radians` from upright (clockwise on screen) about its centre: an angle+ /// typed in.+ pub fn set_angle(&mut self, radians: f32) {+ if radians.is_finite() {+ self.rotate(radians - self.angle());+ }+ }++ /// Scales the box, upright and keeping its proportions, to fit a `width` × `height` canvas,+ /// centred.+ pub fn fit(&mut self, width: f32, height: f32) {+ let [a, b, _, d] = self.now.frame;+ let (w, h) = (a.distance(b), a.distance(d));+ if w <= 0.0 || h <= 0.0 {+ return;+ }+ let k = (width / w).min(height / h);+ let (w, h) = (w * k, h * k);+ let (x, y) = ((width - w) / 2.0, (height - h) / 2.0);+ let to = [Vec2::new(x, y), Vec2::new(x + w, y), Vec2::new(x + w, y + h), Vec2::new(x, y + h)];+ self.change(|p| carry_all(p, to));+ }++ /// Moves the content one canvas pixel towards `toward`, along whichever axis it is further+ /// along from the box's centre.+ pub fn nudge(&mut self, toward: Vec2) {+ let d = toward - centre(self.now.frame);+ if !d.is_finite() || d == Vec2::ZERO {+ return;+ }+ let step = if d.x.abs() >= d.y.abs() { Vec2::new(d.x.signum(), 0.0) } else { Vec2::new(0.0, d.y.signum()) };+ self.change(|p| Some(map_placement(p, Affine::translate(step))));+ }++ /// Puts the content back where it started.+ pub fn reset(&mut self) {+ let source = self.source;+ self.change(|_| Some(Placement { content: source, frame: source, warp: None }));+ }++ /// Takes back the last change. Returns whether there was one.+ pub fn undo(&mut self) -> bool {+ self.drag = None;+ match self.history.pop() {+ Some(p) => {+ self.now = p;+ true+ }+ None => false,+ }+ }++ /// Applies `f` to the placement, kept as an undo step when it changes anything.+ fn change(&mut self, f: impl FnOnce(&Placement) -> Option<Placement>) {+ self.drag = None;+ let finite =+ |n: &Placement| n.content.iter().chain(&n.frame).chain(n.warp.iter().flatten()).all(|v| v.is_finite());+ if let Some(next) = f(&self.now).filter(finite)+ && next != self.now+ {+ self.history.push(self.now);+ self.now = next;+ }+ }++ fn dragged(+ &self,+ handle: Handle,+ mode: TransformMode,+ from: Vec2,+ to: Vec2,+ start: Placement,+ guides: &Guides,+ ) -> Option<Placement> {+ let f = start.frame;+ let delta = to - from;+ if mode == TransformMode::Warp+ && let Some(mesh) = start.warp+ {+ return Some(warped(mesh, handle, from, delta));+ }+ let distort = mode == TransformMode::Distort;+ let next = match handle {+ Handle::Move => {+ let mut delta = delta;+ if guides.magnetics && delta.length() > guides.lock_after {+ // the direction keeps to the 15° step at or below it+ let step = (angle(delta) / MAGNETIC_STEP).floor() * MAGNETIC_STEP;+ let (sin, cos) = step.sin_cos();+ let along = delta.x * cos + delta.y * sin;+ delta = Vec2::new(cos, sin) * along;+ }+ if let Some(reach) = guides.snap {+ delta = delta + snap_offset(f.map(|p| p + delta), guides.canvas, &self.snap_lines, reach);+ }+ map_placement(&start, Affine::translate(delta))+ }+ Handle::Rotate => {+ let c = centre(f);+ let mut turn = angle(to - c) - angle(from - c);+ if guides.magnetics {+ let [a, b, ..] = f;+ let was = angle(b - a);+ turn = ((was + turn) / MAGNETIC_STEP).round() * MAGNETIC_STEP - was;+ }+ map_placement(+ &start,+ Affine::translate(Vec2::ZERO - c).then(Affine::rotate(turn)).then(Affine::translate(c)),+ )+ }+ Handle::TurnBox => {+ let c = centre(f);+ let turn = angle(to - c) - angle(from - c);+ let [a, b, ..] = f;+ let frame = self.fit_box(&start, angle(b - a) + turn)?;+ Placement { frame, ..start }+ }+ Handle::Mesh(_) => start,+ Handle::Corner(i) => {+ let i = usize::from(i % 4);+ let (corner, anchor) = (at(f, i), at(f, i + 2));+ if distort {+ let mut frame = f;+ set(&mut frame, i, corner + delta);+ return carry_all(&start, frame);+ }+ let target = corner + delta;+ let m = if mode == TransformMode::Uniform {+ scale_about(anchor, projected_scale(target, corner, anchor))+ } else {+ // the target in the box's own axes, against the corner's+ let basis = basis(f)?.inverse()?;+ let (t, c) = (basis.apply(target - anchor), basis.apply(corner - anchor));+ let sx = if c.x.abs() > 1e-6 { (t.x / c.x).max(MIN_SCALE) } else { 1.0 };+ let sy = if c.y.abs() > 1e-6 { (t.y / c.y).max(MIN_SCALE) } else { 1.0 };+ axes_scale_about(f, anchor, sx, sy)?+ };+ map_placement(&start, m)+ }+ Handle::Edge(k) => {+ let k = usize::from(k % 4);+ if distort {+ let mut frame = f;+ set(&mut frame, k, at(f, k) + delta);+ set(&mut frame, k + 1, at(f, k + 1) + delta);+ return carry_all(&start, frame);+ }+ let mid = at(f, k).lerp(at(f, k + 1), 0.5);+ let anchor = at(f, k + 2).lerp(at(f, k + 3), 0.5);+ let s = projected_scale(mid + delta, mid, anchor);+ let m = if mode == TransformMode::Uniform {+ scale_about(anchor, s)+ } else if k % 2 == 0 {+ axes_scale_about(f, anchor, 1.0, s)?+ } else {+ axes_scale_about(f, anchor, s, 1.0)?+ };+ map_placement(&start, m)+ }+ };+ Some(next)+ }++ /// The box at `radians` that just holds the content placed as in `p`.+ fn fit_box(&self, p: &Placement, radians: f32) -> Option<Quad> {+ let to_content = Homography::quad_to_quad(self.source, p.content)?;+ let [s0, s1, _, s3] = self.source;+ let (w, h) = (s1.x - s0.x, s3.y - s0.y);+ let place = |q: Vec2| match p.warp {+ Some(m) if w > 0.0 && h > 0.0 => Some(warp::point(&m, (q.x - s0.x) / w, (q.y - s0.y) / h)),+ _ => to_content.apply(q),+ };+ let points: Vec<Vec2> = if self.hull.is_empty() {+ p.warp.map_or(p.content.to_vec(), |m| m.to_vec())+ } else {+ self.hull.iter().filter_map(|&q| place(q)).collect()+ };+ let (sin, cos) = radians.sin_cos();+ let (u, v) = (Vec2::new(cos, sin), Vec2::new(-sin, cos));+ let dot = |a: Vec2, b: Vec2| a.x * b.x + a.y * b.y;+ let (mut u0, mut u1, mut v0, mut v1) = (f32::MAX, f32::MIN, f32::MAX, f32::MIN);+ for q in &points {+ let (pu, pv) = (dot(*q, u), dot(*q, v));+ u0 = u0.min(pu);+ u1 = u1.max(pu);+ v0 = v0.min(pv);+ v1 = v1.max(pv);+ }+ (u0 <= u1 && v0 <= v1).then(|| [u * u0 + v * v0, u * u1 + v * v0, u * u1 + v * v1, u * u0 + v * v1])+ }+}++/// The convex hull of `points`, without repeats.+pub fn convex_hull(points: &[Vec2]) -> Vec<Vec2> {+ let mut pts: Vec<Vec2> = points.iter().copied().filter(|p| p.is_finite()).collect();+ pts.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y)));+ pts.dedup();+ if pts.len() < 3 {+ return pts;+ }+ let mut lower = half_hull(pts.iter());+ let mut upper = half_hull(pts.iter().rev());+ // each half ends where the other starts+ lower.pop();+ upper.pop();+ lower.append(&mut upper);+ lower+}++/// One side of the hull of points sorted along x (monotone chain).+fn half_hull<'a>(points: impl Iterator<Item = &'a Vec2>) -> Vec<Vec2> {+ let cross = |o: Vec2, a: Vec2, b: Vec2| (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);+ let mut chain: Vec<Vec2> = Vec::new();+ for &p in points {+ while let [.., a, b] = *chain.as_slice() {+ if cross(a, b, p) > 0.0 {+ break;+ }+ chain.pop();+ }+ chain.push(p);+ }+ chain+}++/// How far to shift `frame` so that the nearest of its left, middle and right (and top, middle and+/// bottom) lands on a line, the canvas's edges and middle or one of `others` (across, down),+/// when one is within `reach`.+fn snap_offset(frame: Quad, canvas: Vec2, others: &(Vec<f32>, Vec<f32>), reach: f32) -> Vec2 {+ let axis = |values: [f32; 4], size: f32, others: &[f32]| {+ let (lo, hi) = values.iter().fold((f32::MAX, f32::MIN), |(lo, hi), &v| (lo.min(v), hi.max(v)));+ let features = [lo, (lo + hi) / 2.0, hi];+ let lines = [0.0, size / 2.0, size];+ let mut best: Option<f32> = None;+ for f in features {+ for &l in lines.iter().chain(others) {+ let d = l - f;+ if d.abs() <= reach && best.is_none_or(|b| d.abs() < b.abs()) {+ best = Some(d);+ }+ }+ }+ best.unwrap_or(0.0)+ };+ Vec2::new(axis(frame.map(|p| p.x), canvas.x, &others.0), axis(frame.map(|p| p.y), canvas.y, &others.1))+}++fn at(q: Quad, i: usize) -> Vec2 {+ q.get(i % 4).copied().unwrap_or_default()+}++fn set(q: &mut Quad, i: usize, v: Vec2) {+ if let Some(p) = q.get_mut(i % 4) {+ *p = v;+ }+}++fn centre(q: Quad) -> Vec2 {+ let [a, b, c, d] = q;+ (a + b + c + d) * 0.25+}++fn angle(v: Vec2) -> f32 {+ v.y.atan2(v.x)+}++/// The scale about `anchor` that brings `point` nearest `target` along the line through them.+fn projected_scale(target: Vec2, point: Vec2, anchor: Vec2) -> f32 {+ let (t, p) = (target - anchor, point - anchor);+ let len2 = p.x * p.x + p.y * p.y;+ if len2 <= 1e-12 {+ return 1.0;+ }+ ((t.x * p.x + t.y * p.y) / len2).max(MIN_SCALE)+}++fn scale_about(anchor: Vec2, s: f32) -> Affine {+ Affine::translate(Vec2::ZERO - anchor).then(Affine::scale(s)).then(Affine::translate(anchor))+}++/// The box's own axes (its top and left edges) as a linear map from unit axes.+fn basis(f: Quad) -> Option<Affine> {+ let [a, b, _, d] = f;+ let (e1, e2) = (b - a, d - a);+ let m = Affine { a: e1.x, b: e1.y, c: e2.x, d: e2.y, e: 0.0, f: 0.0 };+ (m.determinant().abs() > 1e-9).then_some(m)+}++/// Scaling by `sx` along the box's top edge and `sy` along its left edge, about `anchor`.+fn axes_scale_about(f: Quad, anchor: Vec2, sx: f32, sy: f32) -> Option<Affine> {+ let b = basis(f)?;+ let s = Affine { a: sx, d: sy, ..Affine::IDENTITY };+ Some(Affine::translate(Vec2::ZERO - anchor).then(b.inverse()?).then(s).then(b).then(Affine::translate(anchor)))+}++fn map_placement(p: &Placement, m: Affine) -> Placement {+ Placement {+ content: p.content.map(|v| m.apply(v)),+ frame: p.frame.map(|v| m.apply(v)),+ warp: p.warp.map(|w| w.map(|v| m.apply(v))),+ }+}++/// Everything carried along as the box goes from where it is to `frame`.+fn carry_all(p: &Placement, frame: Quad) -> Option<Placement> {+ let h = Homography::quad_to_quad(p.frame, frame)?;+ let content = carry(p, frame)?;+ let warp = match p.warp {+ Some(m) => {+ let mut out = m;+ for v in &mut out {+ *v = h.apply(*v)?;+ }+ Some(out)+ }+ None => None,+ };+ Some(Placement { content, frame, warp })+}++/// A drag in a warp: a control point (a corner node is its control point), or the surface under the+/// touch; off the mesh, the whole mesh moves. The box follows the mesh's corners.+fn warped(mesh: Mesh, handle: Handle, from: Vec2, delta: Vec2) -> Placement {+ let point = match handle {+ Handle::Mesh(k) => Some(usize::from(k % 16)),+ Handle::Corner(i) => [0, 3, 15, 12].get(usize::from(i % 4)).copied(),+ _ => None,+ };+ let next = match point {+ Some(k) => {+ let mut m = mesh;+ if let Some(p) = m.get_mut(k) {+ *p = *p + delta;+ }+ m+ }+ None => match warp::locate(&mesh, from) {+ Some((u, v)) => warp::drag_surface(&mesh, u, v, delta),+ None => mesh.map(|p| p + delta),+ },+ };+ let corners = [next[0], next[3], next[15], next[12]];+ Placement { content: corners, frame: corners, warp: Some(next) }+}++/// The content carried along as the box goes from where it is to `frame`.+fn carry(p: &Placement, frame: Quad) -> Option<Quad> {+ let h = Homography::quad_to_quad(p.frame, frame)?;+ let [a, b, c, d] = p.content;+ Some([h.apply(a)?, h.apply(b)?, h.apply(c)?, h.apply(d)?])+}++#[cfg(test)]+mod tests {+ use super::*;++ fn close(a: Vec2, b: Vec2) -> bool {+ a.distance(b) < 1e-3+ }++ fn quad_close(a: Quad, b: Quad) -> bool {+ a.iter().zip(&b).all(|(p, q)| close(*p, *q))+ }++ fn rect(x: f32, y: f32, w: f32, h: f32) -> Quad {+ [Vec2::new(x, y), Vec2::new(x + w, y), Vec2::new(x + w, y + h), Vec2::new(x, y + h)]+ }++ const NONE: Guides = Guides { magnetics: false, lock_after: 0.0, snap: None, canvas: Vec2::ZERO };++ fn box_100x200() -> Transform {+ Transform::new(100.0, 100.0, 100.0, 200.0, Vec::new())+ }++ #[test]+ fn moving_carries_box_and_content_and_undoes() {+ let mut t = box_100x200();+ t.grab(Handle::Move, Vec2::new(150.0, 150.0));+ assert!(t.drag(TransformMode::Uniform, Vec2::new(160.0, 130.0), &NONE));+ t.release();+ assert!(quad_close(t.content(), rect(110.0, 80.0, 100.0, 200.0)));+ assert!(quad_close(t.frame(), t.content()));+ assert!(t.can_undo());+ assert!(t.undo());+ assert!(quad_close(t.content(), rect(100.0, 100.0, 100.0, 200.0)));+ assert!(!t.undo());+ }++ #[test]+ fn uniform_corners_scale_about_the_opposite_corner() {+ let mut t = box_100x200();+ t.grab(Handle::Corner(2), Vec2::new(200.0, 300.0));+ // along the diagonal: twice the size+ t.drag(TransformMode::Uniform, Vec2::new(300.0, 500.0), &NONE);+ assert!(quad_close(t.content(), rect(100.0, 100.0, 200.0, 400.0)));+ // off the diagonal: the nearest point on it+ t.drag(TransformMode::Uniform, Vec2::new(300.0, 300.0), &NONE);+ let s = (200.0 * 100.0 + 200.0 * 200.0) / (100.0 * 100.0 + 200.0 * 200.0);+ assert!(quad_close(t.content(), rect(100.0, 100.0, 100.0 * s, 200.0 * s)));+ }++ #[test]+ fn uniform_edges_scale_about_the_opposite_edge() {+ let mut t = box_100x200();+ t.grab(Handle::Edge(1), Vec2::new(200.0, 200.0));+ t.drag(TransformMode::Uniform, Vec2::new(250.0, 260.0), &NONE);+ // the left edge's middle (100, 200) stays+ assert!(quad_close(t.content(), rect(100.0, 50.0, 150.0, 300.0)));+ }++ #[test]+ fn freeform_stretches_along_the_box() {+ let mut t = box_100x200();+ t.grab(Handle::Corner(2), Vec2::new(200.0, 300.0));+ t.drag(TransformMode::Freeform, Vec2::new(300.0, 320.0), &NONE);+ assert!(quad_close(t.content(), rect(100.0, 100.0, 200.0, 220.0)));+ t.release();+ t.grab(Handle::Edge(0), Vec2::new(200.0, 100.0));+ t.drag(TransformMode::Freeform, Vec2::new(500.0, 210.0), &NONE);+ assert!(quad_close(t.content(), rect(100.0, 210.0, 200.0, 110.0)));+ // and along a turned box's own axes+ let mut t = box_100x200();+ t.rotate(std::f32::consts::FRAC_PI_2);+ let [_, _, br, _] = t.frame();+ t.grab(Handle::Corner(2), br);+ t.drag(TransformMode::Freeform, br + Vec2::new(-50.0, 0.0), &NONE);+ let [a, b, _, d] = t.frame();+ assert!((a.distance(b) - 100.0).abs() < 1e-3 && (a.distance(d) - 250.0).abs() < 1e-3);+ }++ #[test]+ fn distort_moves_corners_and_edges_on_their_own() {+ let mut t = box_100x200();+ t.grab(Handle::Corner(1), Vec2::new(200.0, 100.0));+ t.drag(TransformMode::Distort, Vec2::new(230.0, 80.0), &NONE);+ let [a, b, c, d] = t.content();+ assert!(close(a, Vec2::new(100.0, 100.0)) && close(b, Vec2::new(230.0, 80.0)));+ assert!(close(c, Vec2::new(200.0, 300.0)) && close(d, Vec2::new(100.0, 300.0)));+ t.release();+ t.grab(Handle::Edge(3), Vec2::new(100.0, 200.0));+ t.drag(TransformMode::Distort, Vec2::new(90.0, 200.0), &NONE);+ let [a, _, _, d] = t.content();+ assert!(close(a, Vec2::new(90.0, 100.0)) && close(d, Vec2::new(90.0, 300.0)));+ }++ #[test]+ fn rotating_turns_about_the_centre_and_a_cancelled_drag_goes_back() {+ let mut t = box_100x200();+ t.grab(Handle::Rotate, Vec2::new(150.0, 50.0));+ // from straight above the centre (150, 200) to straight right of it: a quarter turn+ t.drag(TransformMode::Uniform, Vec2::new(400.0, 200.0), &NONE);+ let [a, ..] = t.content();+ assert!(close(a, Vec2::new(250.0, 150.0)), "{a:?}");+ t.cancel_drag();+ assert!(quad_close(t.content(), rect(100.0, 100.0, 100.0, 200.0)));+ assert!(!t.can_undo());+ }++ #[test]+ fn turning_the_box_refits_it_and_leaves_the_content() {+ let hull = vec![Vec2::new(100.0, 100.0), Vec2::new(200.0, 100.0), Vec2::new(100.0, 300.0)];+ let mut t = Transform::new(100.0, 100.0, 100.0, 200.0, hull);+ // the node below the box, a quarter turn clockwise about the centre+ t.grab(Handle::TurnBox, Vec2::new(150.0, 350.0));+ t.drag(TransformMode::Uniform, Vec2::new(0.0, 200.0), &NONE);+ assert!(quad_close(t.content(), rect(100.0, 100.0, 100.0, 200.0)));+ let [a, b, c, d] = t.frame();+ // a quarter turn: the box's top runs down the screen; it still just holds the triangle+ assert!(close(a, Vec2::new(200.0, 100.0)) && close(b, Vec2::new(200.0, 300.0)), "{a:?} {b:?}");+ assert!(close(c, Vec2::new(100.0, 300.0)) && close(d, Vec2::new(100.0, 100.0)), "{c:?} {d:?}");+ }++ #[test]+ fn flips_rotation_fit_and_reset() {+ let mut t = box_100x200();+ t.flip_horizontal();+ let [a, b, ..] = t.content();+ assert!(close(a, Vec2::new(200.0, 100.0)) && close(b, Vec2::new(100.0, 100.0)));+ assert!(quad_close(t.frame(), rect(100.0, 100.0, 100.0, 200.0)));+ t.flip_horizontal();+ t.flip_vertical();+ let [a, .., d] = t.content();+ assert!(close(a, Vec2::new(100.0, 300.0)) && close(d, Vec2::new(100.0, 100.0)));+ t.reset();+ t.rotate(std::f32::consts::FRAC_PI_4);+ assert!(close(centre(t.frame()), Vec2::new(150.0, 200.0)));+ let [a, b, ..] = t.frame();+ assert!((angle(b - a) - std::f32::consts::FRAC_PI_4).abs() < 1e-4);+ t.fit(1000.0, 1000.0);+ assert!(quad_close(t.frame(), rect(250.0, 0.0, 500.0, 1000.0)));+ t.reset();+ assert!(quad_close(t.content(), rect(100.0, 100.0, 100.0, 200.0)));+ // every action was a step+ let mut steps = 0;+ while t.undo() {+ steps += 1;+ }+ assert_eq!(steps, 7);+ // a reset with nothing changed is not a step+ t.reset();+ assert!(!t.can_undo());+ }++ #[test]+ fn magnetics_keep_moves_and_turns_to_15_degree_steps() {+ let magnetic = Guides { magnetics: true, lock_after: 4.0, ..NONE };+ let mut t = box_100x200();+ t.grab(Handle::Move, Vec2::new(150.0, 200.0));+ // a short wobble is free+ t.drag(TransformMode::Uniform, Vec2::new(152.0, 201.0), &magnetic);+ assert!(close(t.content()[0], Vec2::new(102.0, 101.0)));+ // 10° below level keeps to level (the step at or below it)+ let d = Vec2::new(100.0 * 10f32.to_radians().cos(), 100.0 * 10f32.to_radians().sin());+ t.drag(TransformMode::Uniform, Vec2::new(150.0, 200.0) + d, &magnetic);+ let [a, ..] = t.content();+ assert!((a.y - 100.0).abs() < 1e-3 && (a.x - (100.0 + d.x)).abs() < 1e-3, "{a:?}");+ t.cancel_drag();+ // a turn of 40° keeps to 45°+ let c = Vec2::new(150.0, 200.0);+ t.grab(Handle::Rotate, c + Vec2::new(0.0, -100.0));+ let turned = (-90f32 + 40.0).to_radians();+ t.drag(TransformMode::Uniform, c + Vec2::new(turned.cos(), turned.sin()) * 100.0, &magnetic);+ let [a, b, ..] = t.frame();+ assert!((angle(b - a).to_degrees() - 45.0).abs() < 1e-3);+ }++ #[test]+ fn snapping_pulls_a_moved_box_onto_the_canvas_lines() {+ let snap = Guides { snap: Some(10.0), canvas: Vec2::new(1000.0, 1000.0), ..NONE };+ let mut t = box_100x200();+ t.grab(Handle::Move, Vec2::new(150.0, 200.0));+ // the left edge 6 from the canvas's edge, the middle 4 from the canvas's middle: the nearer wins+ t.drag(TransformMode::Uniform, Vec2::new(56.0, 504.0), &snap);+ let [a, ..] = t.content();+ assert!(close(a, Vec2::new(0.0, 400.0)), "{a:?}");+ // out of reach: free+ t.drag(TransformMode::Uniform, Vec2::new(80.0, 470.0), &snap);+ assert!(close(t.content()[0], Vec2::new(30.0, 370.0)));+ // another layer's right edge at 333 takes the box's left edge, 3 off+ t.set_snap_targets(&[[233.0, 700.0, 100.0, 100.0]]);+ t.drag(TransformMode::Uniform, Vec2::new(380.0, 470.0), &snap);+ assert!(close(t.content()[0], Vec2::new(333.0, 370.0)), "{:?}", t.content()[0]);+ }++ #[test]+ fn a_nudge_moves_one_pixel_towards_the_tap() {+ let mut t = box_100x200();+ t.nudge(Vec2::new(500.0, 210.0));+ assert!(close(t.content()[0], Vec2::new(101.0, 100.0)));+ t.nudge(Vec2::new(151.0, 0.0));+ assert!(close(t.content()[0], Vec2::new(101.0, 99.0)));+ t.nudge(centre(t.frame()));+ assert!(t.undo() && t.undo() && !t.undo());+ }++ #[test]+ fn a_warp_bends_through_its_mesh_and_flips_and_resets() {+ let mut t = box_100x200();+ t.start_warp();+ let m = t.warp().unwrap();+ assert!(close(m[5], Vec2::new(100.0 + 100.0 / 3.0, 100.0 + 200.0 / 3.0)));+ // a corner node is its control point+ t.grab(Handle::Corner(2), Vec2::new(200.0, 300.0));+ t.drag(TransformMode::Warp, Vec2::new(230.0, 310.0), &NONE);+ t.release();+ assert!(close(t.warp().unwrap()[15], Vec2::new(230.0, 310.0)));+ assert!(close(t.frame()[2], Vec2::new(230.0, 310.0)));+ // the surface under the touch follows it+ let before = t.warp().unwrap();+ let at = warp::point(&before, 0.5, 0.5);+ t.grab(Handle::Move, at);+ t.drag(TransformMode::Warp, at + Vec2::new(20.0, 0.0), &NONE);+ assert!(close(warp::point(&t.warp().unwrap(), 0.5, 0.5), at + Vec2::new(20.0, 0.0)));+ // off the mesh: all of it moves+ t.grab(Handle::Move, Vec2::new(0.0, 0.0));+ t.drag(TransformMode::Warp, Vec2::new(5.0, 0.0), &NONE);+ assert!(close(t.warp().unwrap()[0], before[0] + Vec2::new(5.0, 0.0)));+ t.release();+ t.flip_horizontal();+ let flipped = t.warp().unwrap();+ assert!(close(flipped[0], before[3] + Vec2::new(5.0, 0.0)));+ t.rotate(std::f32::consts::FRAC_PI_2);+ t.reset();+ assert_eq!(t.warp(), None);+ assert!(t.undo() && t.warp().is_some());+ }++ #[test]+ fn hull_of_a_square_with_inner_points() {+ let pts = [+ Vec2::new(0.0, 0.0),+ Vec2::new(2.0, 0.0),+ Vec2::new(1.0, 1.0),+ Vec2::new(2.0, 2.0),+ Vec2::new(0.0, 2.0),+ Vec2::new(1.0, 0.0),+ Vec2::new(0.0, 0.0),+ ];+ let hull = convex_hull(&pts);+ assert_eq!(hull.len(), 4, "{hull:?}");+ for corner in [Vec2::new(0.0, 0.0), Vec2::new(2.0, 0.0), Vec2::new(2.0, 2.0), Vec2::new(0.0, 2.0)] {+ assert!(hull.contains(&corner));+ }+ assert_eq!(convex_hull(&[Vec2::new(1.0, 1.0)]).len(), 1);+ }++ #[test]+ fn a_size_and_an_angle_typed_in() {+ let mut t = box_100x200();+ let c = centre(t.frame());+ t.set_size(50.0, 400.0);+ let (w, h) = t.size();+ assert!((w - 50.0).abs() < 1e-3 && (h - 400.0).abs() < 1e-3, "{w} {h}");+ assert!(close(centre(t.frame()), c));+ t.set_angle(30f32.to_radians());+ assert!((t.angle().to_degrees() - 30.0).abs() < 1e-3);+ // turned, a size keeps the turn+ t.set_size(100.0, 100.0);+ assert!((t.angle().to_degrees() - 30.0).abs() < 1e-3);+ let (w, h) = t.size();+ assert!((w - 100.0).abs() < 1e-2 && (h - 100.0).abs() < 1e-2);+ // nothing for sizes under a pixel or not numbers+ t.set_size(0.5, 10.0);+ t.set_size(f32::NAN, 10.0);+ assert!((t.size().0 - 100.0).abs() < 1e-2);+ assert!(t.undo() && t.undo() && t.undo() && !t.undo());+ }+}diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rsnew file mode 100644index 0000000..8def37c--- /dev/null+++ b/crates/engine/src/view.rs@@ -0,0 +1,205 @@+//! Where the canvas sits on screen.++use crate::geom::{Affine, Vec2};++/// Zoom limits (screen pixels per canvas pixel).+pub const MIN_ZOOM: f32 = 0.02;+pub const MAX_ZOOM: f32 = 64.0;++/// The canvas-to-screen map: a move, a uniform zoom and a rotation.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct View {+ to_screen: Affine,+}++impl View {+ /// The whole canvas, centred and as large as fits.+ pub fn fit(canvas: (u32, u32), screen: (u32, u32)) -> View {+ View::fit_inside(canvas, screen, [0.0; 4])+ }++ /// The whole canvas, centred and as large as fits in the screen less `insets` (left, top,+ /// right, bottom, screen pixels): clear of the interface.+ pub fn fit_inside(canvas: (u32, u32), screen: (u32, u32), insets: [f32; 4]) -> View {+ let [left, top, right, bottom] = insets.map(|v| if v.is_finite() { v.max(0.0) } else { 0.0 });+ let (cw, ch) = (canvas.0.max(1) as f32, canvas.1.max(1) as f32);+ let (sw, sh) = (screen.0.max(1) as f32, screen.1.max(1) as f32);+ let (w, h) = ((sw - left - right).max(1.0), (sh - top - bottom).max(1.0));+ let zoom = (w / cw).min(h / ch).clamp(MIN_ZOOM, MAX_ZOOM);+ let offset = Vec2::new(left + (w - cw * zoom) / 2.0, top + (h - ch * zoom) / 2.0);+ View { to_screen: Affine::scale(zoom).then(Affine::translate(offset)) }+ }++ /// As [`View::fit_inside`], with the canvas turned by `quarter_turns` right angles (clockwise+ /// on the screen): fitted as it shows, its sides swapped for an odd number of turns.+ pub fn fit_turned(canvas: (u32, u32), screen: (u32, u32), insets: [f32; 4], quarter_turns: i32) -> View {+ let turns = quarter_turns.rem_euclid(4);+ if turns == 0 {+ return View::fit_inside(canvas, screen, insets);+ }+ let [left, top, right, bottom] = insets.map(|v| if v.is_finite() { v.max(0.0) } else { 0.0 });+ let (cw, ch) = (canvas.0.max(1) as f32, canvas.1.max(1) as f32);+ let (sw, sh) = (screen.0.max(1) as f32, screen.1.max(1) as f32);+ let (w, h) = ((sw - left - right).max(1.0), (sh - top - bottom).max(1.0));+ let (shown_w, shown_h) = if turns % 2 == 1 { (ch, cw) } else { (cw, ch) };+ let zoom = (w / shown_w).min(h / shown_h).clamp(MIN_ZOOM, MAX_ZOOM);+ let middle = Vec2::new(left + w / 2.0, top + h / 2.0);+ let to_screen = Affine::translate(Vec2::new(-cw / 2.0, -ch / 2.0))+ .then(Affine::rotate(turns as f32 * std::f32::consts::FRAC_PI_2))+ .then(Affine::scale(zoom))+ .then(Affine::translate(middle));+ View { to_screen }+ }++ /// How many right angles the view is turned by, to the nearest.+ pub fn quarter_turns(&self) -> i32 {+ let r = self.rotation();+ if r.is_finite() { (r / std::f32::consts::FRAC_PI_2).round() as i32 } else { 0 }+ }++ /// The canvas point `centre` in the middle of a `screen`, at `zoom` and turned by `rotation`+ /// (radians): a view kept with an artwork, put back on a screen of any size.+ pub fn centred(centre: Vec2, zoom: f32, rotation: f32, screen: (u32, u32)) -> Option<View> {+ if !(centre.is_finite() && zoom.is_finite() && rotation.is_finite()) {+ return None;+ }+ let middle = Vec2::new(screen.0.max(1) as f32 / 2.0, screen.1.max(1) as f32 / 2.0);+ let to_screen = Affine::translate(Vec2::new(-centre.x, -centre.y))+ .then(Affine::rotate(rotation))+ .then(Affine::scale(zoom.clamp(MIN_ZOOM, MAX_ZOOM)))+ .then(Affine::translate(middle));+ Some(View { to_screen })+ }++ /// The view `t` (0..1) of the way from `a` to `b`: the zoom (in proportion), the turn (the short+ /// way round) and where the canvas point `centre` shows on the screen, each in step.+ pub fn between(a: &View, b: &View, centre: Vec2, t: f32) -> View {+ let t = if t.is_finite() { t } else { 1.0 };+ let (za, zb) = (a.zoom().max(MIN_ZOOM), b.zoom().max(MIN_ZOOM));+ let zoom = za * (zb / za).powf(t);+ let mut turn = b.rotation() - a.rotation();+ while turn > std::f32::consts::PI {+ turn -= std::f32::consts::TAU;+ }+ while turn < -std::f32::consts::PI {+ turn += std::f32::consts::TAU;+ }+ let rotation = a.rotation() + turn * t;+ let (pa, pb) = (a.to_screen.apply(centre), b.to_screen.apply(centre));+ let at = pa + (pb - pa) * t;+ let to_screen = Affine::translate(Vec2::new(-centre.x, -centre.y))+ .then(Affine::rotate(rotation))+ .then(Affine::scale(zoom.clamp(MIN_ZOOM, MAX_ZOOM)))+ .then(Affine::translate(at));+ View { to_screen }+ }++ /// A view mapping the canvas to the screen by `to_screen`.+ pub fn from_affine(to_screen: Affine) -> View {+ View { to_screen }+ }++ pub fn to_screen(&self) -> Affine {+ self.to_screen+ }++ pub fn screen_to_canvas(&self, p: Vec2) -> Option<Vec2> {+ self.to_screen.inverse().map(|m| m.apply(p))+ }++ pub fn zoom(&self) -> f32 {+ self.to_screen.scale_factor()+ }++ pub fn rotation(&self) -> f32 {+ self.to_screen.rotation()+ }++ /// One step of a two-finger gesture: the canvas scales by `scale` and turns by `rotation`+ /// around `pivot` (screen pixels), then follows the fingers by `pan`. Zoom stays within limits;+ /// non-finite input is ignored.+ pub fn gesture(&mut self, pivot: Vec2, pan: Vec2, scale: f32, rotation: f32) {+ if !pivot.is_finite() || !pan.is_finite() || !(scale.is_finite() && scale > 0.0) || !rotation.is_finite() {+ return;+ }+ let zoom = self.zoom();+ let s = (zoom * scale).clamp(MIN_ZOOM, MAX_ZOOM) / zoom;+ let step = Affine::translate(Vec2::ZERO - pivot)+ .then(Affine::scale(s))+ .then(Affine::rotate(rotation))+ .then(Affine::translate(pivot + pan));+ let next = self.to_screen.then(step);+ if next.is_finite() && next.inverse().is_some() {+ self.to_screen = next;+ }+ }+}++#[cfg(test)]+mod tests {+ #[test]+ fn fitting_keeps_the_nearest_right_angle_and_fits_it_on_its_side() {+ let on_side = View::fit_turned((100, 200), (400, 400), [0.0; 4], 1);+ assert_eq!(on_side.quarter_turns(), 1);+ // shown 200 wide and 100 tall, it is as wide as the screen+ assert!((on_side.zoom() - 2.0).abs() < 1e-4);+ let corners = [(0.0, 0.0), (100.0, 0.0), (0.0, 200.0), (100.0, 200.0)]+ .map(|(x, y)| on_side.to_screen().apply(Vec2::new(x, y)));+ let (xs, ys): (Vec<f32>, Vec<f32>) = corners.iter().map(|p| (p.x, p.y)).unzip();+ let span = |v: &[f32]| v.iter().cloned().fold(f32::MIN, f32::max) - v.iter().cloned().fold(f32::MAX, f32::min);+ assert!((span(&xs) - 400.0).abs() < 1e-3 && (span(&ys) - 200.0).abs() < 1e-3);+ // turned a little, fitting straightens it; nearly on its side, it goes on its side+ let mut v = View::fit((100, 100), (400, 400));+ v.gesture(Vec2::new(200.0, 200.0), Vec2::ZERO, 1.0, 0.6);+ assert_eq!(v.quarter_turns(), 0);+ v.gesture(Vec2::new(200.0, 200.0), Vec2::ZERO, 1.0, 0.6);+ assert_eq!(v.quarter_turns(), 1);+ }++ use super::*;++ #[test]+ fn fit_centres_the_canvas() {+ let v = View::fit((1000, 2000), (800, 800));+ assert!((v.zoom() - 0.4).abs() < 1e-6);+ let tl = v.to_screen().apply(Vec2::ZERO);+ assert!((tl.x - 200.0).abs() < 1e-3 && tl.y.abs() < 1e-3);+ }++ #[test]+ fn gesture_keeps_the_pivot_under_the_fingers() {+ let mut v = View::fit((1000, 1000), (1000, 1000));+ let pivot = Vec2::new(300.0, 700.0);+ let under = v.screen_to_canvas(pivot).unwrap();+ v.gesture(pivot, Vec2::ZERO, 2.0, 0.5);+ assert!(v.to_screen().apply(under).distance(pivot) < 1e-2);+ assert!((v.zoom() - 2.0).abs() < 1e-4);+ v.gesture(pivot, Vec2::new(10.0, -5.0), 1.0, 0.0);+ assert!(v.to_screen().apply(under).distance(pivot + Vec2::new(10.0, -5.0)) < 1e-2);+ }++ #[test]+ fn zoom_is_clamped_and_bad_input_ignored() {+ let mut v = View::fit((100, 100), (100, 100));+ v.gesture(Vec2::ZERO, Vec2::ZERO, 1e9, 0.0);+ assert!((v.zoom() - MAX_ZOOM).abs() < 1e-2);+ let before = v;+ v.gesture(Vec2::ZERO, Vec2::ZERO, f32::NAN, 0.0);+ v.gesture(Vec2::ZERO, Vec2::ZERO, -1.0, 0.0);+ assert_eq!(v, before);+ }++ #[test]+ fn a_fit_keeps_clear_of_insets_and_a_kept_view_comes_back_anywhere() {+ // 100 x 100 in 200 x 300 less 20 on the left and 40 on top: 180 wide, centred in 260+ let v = View::fit_inside((100, 100), (200, 300), [20.0, 40.0, 0.0, 0.0]);+ let p = v.to_screen().apply(Vec2::new(0.0, 0.0));+ assert!((v.zoom() - 1.8).abs() < 1e-4 && (p.x - 20.0).abs() < 1e-3 && (p.y - 80.0).abs() < 1e-3, "{p:?}");+ // canvas (30, 40) in the middle, twice the size, turned: on any screen+ let c = View::centred(Vec2::new(30.0, 40.0), 2.0, 0.5, (400, 600)).unwrap();+ let m = c.to_screen().apply(Vec2::new(30.0, 40.0));+ assert!((m.x - 200.0).abs() < 1e-3 && (m.y - 300.0).abs() < 1e-3);+ assert!((c.zoom() - 2.0).abs() < 1e-4 && (c.to_screen().rotation() - 0.5).abs() < 1e-4);+ assert!(View::centred(Vec2::new(f32::NAN, 0.0), 1.0, 0.0, (10, 10)).is_none());+ }+}diff --git a/crates/engine/src/warp.rs b/crates/engine/src/warp.rsnew file mode 100644index 0000000..5dbad37--- /dev/null+++ b/crates/engine/src/warp.rs@@ -0,0 +1,206 @@+//! A warp: a bicubic Bézier patch of 4 × 4 control points carrying the unit square (the content's+//! source rectangle) onto the canvas.++use crate::geom::Vec2;++/// Control points row by row, row 0 at the top, four to a row.+pub type Mesh = [Vec2; 16];++/// The cubic Bernstein weights at `t`.+fn bernstein(t: f32) -> [f32; 4] {+ let s = 1.0 - t;+ [s * s * s, 3.0 * s * s * t, 3.0 * s * t * t, t * t * t]+}++/// The weights' derivatives at `t`.+fn bernstein_slope(t: f32) -> [f32; 4] {+ let s = 1.0 - t;+ [-3.0 * s * s, 3.0 * s * s - 6.0 * s * t, 6.0 * s * t - 3.0 * t * t, 3.0 * t * t]+}++/// The weight of each control point at (`u`, `v`), row by row.+fn weights(bu: [f32; 4], bv: [f32; 4]) -> impl Iterator<Item = f32> {+ bv.into_iter().flat_map(move |wv| bu.map(|wu| wu * wv))+}++fn sum(m: &Mesh, w: impl Iterator<Item = f32>) -> Vec2 {+ m.iter().zip(w).fold(Vec2::ZERO, |acc, (p, w)| acc + *p * w)+}++/// The mesh laid evenly over the quad `q` (top left, top right, bottom right, bottom left).+pub fn over_quad(q: [Vec2; 4]) -> Mesh {+ let [a, b, c, d] = q;+ std::array::from_fn(|k| {+ let (u, v) = ((k % 4) as f32 / 3.0, (k / 4) as f32 / 3.0);+ a.lerp(b, u).lerp(d.lerp(c, u), v)+ })+}++/// The patch's point at (`u`, `v`).+pub fn point(m: &Mesh, u: f32, v: f32) -> Vec2 {+ sum(m, weights(bernstein(u), bernstein(v)))+}++/// Where on the patch canvas point `p` lies, as (u, v) in the unit square; none when it is off the+/// patch.+pub fn locate(m: &Mesh, p: Vec2) -> Option<(f32, f32)> {+ // the nearest of a coarse grid, then Newton steps+ let mut best = (0.5, 0.5, f32::MAX);+ for a in 0..=8 {+ for b in 0..=8 {+ let (u, v) = (a as f32 / 8.0, b as f32 / 8.0);+ let d = point(m, u, v).distance(p);+ if d < best.2 {+ best = (u, v, d);+ }+ }+ }+ let (mut u, mut v, _) = best;+ for _ in 0..16 {+ let du = sum(m, weights(bernstein_slope(u), bernstein(v)));+ let dv = sum(m, weights(bernstein(u), bernstein_slope(v)));+ let r = point(m, u, v) - p;+ let det = du.x * dv.y - du.y * dv.x;+ if !det.is_finite() || det.abs() < 1e-9 {+ break;+ }+ u = (u - (r.x * dv.y - r.y * dv.x) / det).clamp(-0.5, 1.5);+ v = (v - (du.x * r.y - du.y * r.x) / det).clamp(-0.5, 1.5);+ }+ let inside = |t: f32| (-1e-3..=1.0 + 1e-3).contains(&t);+ (point(m, u, v).distance(p) < 0.5 && inside(u) && inside(v)).then(|| (u.clamp(0.0, 1.0), v.clamp(0.0, 1.0)))+}++/// Which third of the patch `t` falls in (0, 1 or 2) and how far through it.+fn third(t: f32) -> (usize, f32) {+ let x = (t * 3.0).clamp(0.0, 3.0);+ let i = (x.floor() as usize).min(2);+ (i, x - i as f32)+}++/// The mesh after its point at (`u`, `v`) is dragged by `delta`. The 2 × 2 control points around+/// the point share the move, more to the nearer ones, scaled so that the point follows exactly.+pub fn drag_surface(m: &Mesh, u: f32, v: f32, delta: Vec2) -> Mesh {+ let (row, tv) = third(v);+ let (col, tu) = third(u);+ // how the move is shared along each axis: nearly even, leaning to the nearer pair+ let lean = |t: f32| 0.075 + 0.85 * t;+ let share = |k: usize| -> f32 {+ let (i, j) = (k / 4, k % 4);+ let along_v = if i == row {+ 1.0 - lean(tv)+ } else if i == row + 1 {+ lean(tv)+ } else {+ 0.0+ };+ let along_u = if j == col {+ 1.0 - lean(tu)+ } else if j == col + 1 {+ lean(tu)+ } else {+ 0.0+ };+ along_v * along_u+ };+ let moved: f32 = weights(bernstein(u), bernstein(v)).enumerate().map(|(k, w)| w * share(k)).sum();+ if !moved.is_finite() || moved <= 1e-6 {+ return *m;+ }+ std::array::from_fn(|k| m.get(k).copied().unwrap_or_default() + delta * (share(k) / moved))+}++/// The patch as triangles over a `steps` × `steps` grid, each corner as (canvas x, y, source x, y):+/// the source is the rectangle `source` (top left, top right, bottom right, bottom left) laid over+/// the unit square.+pub fn triangles(m: &Mesh, source: [Vec2; 4], steps: usize) -> Vec<[f32; 4]> {+ let steps = steps.max(1);+ let [s0, s1, _, s3] = source;+ let corner = |a: usize, b: usize| {+ let (u, v) = (a as f32 / steps as f32, b as f32 / steps as f32);+ let p = point(m, u, v);+ let s = s0 + (s1 - s0) * u + (s3 - s0) * v;+ [p.x, p.y, s.x, s.y]+ };+ let mut out = Vec::with_capacity(steps * steps * 6);+ for b in 0..steps {+ for a in 0..steps {+ let (tl, tr, br, bl) = (corner(a, b), corner(a + 1, b), corner(a + 1, b + 1), corner(a, b + 1));+ out.extend([tl, tr, br, tl, br, bl]);+ }+ }+ out+}++/// The patch's lines at the thirds: four across (v = 0, ⅓, ⅔, 1) then four down (u likewise),+/// each sampled at `samples` + 1 points.+pub fn grid_lines(m: &Mesh, samples: usize) -> Vec<Vec<Vec2>> {+ let samples = samples.max(1);+ let line = |across: bool, k: usize| -> Vec<Vec2> {+ let fixed = k as f32 / 3.0;+ (0..=samples)+ .map(|s| {+ let t = s as f32 / samples as f32;+ if across { point(m, t, fixed) } else { point(m, fixed, t) }+ })+ .collect()+ };+ (0..4).map(|k| line(true, k)).chain((0..4).map(|k| line(false, k))).collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ fn close(a: Vec2, b: Vec2) -> bool {+ a.distance(b) < 1e-3+ }++ fn square() -> Mesh {+ over_quad([Vec2::new(100.0, 100.0), Vec2::new(400.0, 100.0), Vec2::new(400.0, 400.0), Vec2::new(100.0, 400.0)])+ }++ #[test]+ fn an_even_mesh_is_the_quad_itself() {+ let m = square();+ assert!(close(point(&m, 0.0, 0.0), Vec2::new(100.0, 100.0)));+ assert!(close(point(&m, 0.5, 0.25), Vec2::new(250.0, 175.0)));+ assert!(close(point(&m, 1.0, 1.0), Vec2::new(400.0, 400.0)));+ let (u, v) = locate(&m, Vec2::new(325.0, 160.0)).unwrap();+ assert!((u - 0.75).abs() < 1e-3 && (v - 0.2).abs() < 1e-3);+ assert_eq!(locate(&m, Vec2::new(50.0, 160.0)), None);+ }++ #[test]+ fn a_surface_drag_moves_the_point_under_the_finger_with_it() {+ let m = square();+ for (u, v) in [(0.5, 0.5), (0.5, 0.1), (0.9, 0.95), (0.2, 0.7)] {+ let delta = Vec2::new(40.0, -25.0);+ let moved = drag_surface(&m, u, v, delta);+ assert!(close(point(&moved, u, v), point(&m, u, v) + delta), "{u} {v}");+ }+ // in the middle, the four inner points move alike and the edges stay+ let moved = drag_surface(&m, 0.5, 0.5, Vec2::new(65.0, 0.0));+ let inner = moved[5] - m[5];+ assert!((inner.x - 65.0 / (4.0 * 0.375f32.powi(2))).abs() < 0.5, "{inner:?}");+ assert!(close(moved[6] - m[6], inner) && close(moved[9] - m[9], inner) && close(moved[10] - m[10], inner));+ assert!(close(moved[1], m[1]) && close(moved[4], m[4]) && close(moved[0], m[0]));+ // near the top edge, the edge's middle points take the larger share+ let moved = drag_surface(&m, 0.498, 0.1022, Vec2::new(65.0, 0.0));+ let ratio = (moved[1].x - m[1].x) / (moved[5].x - m[5].x);+ assert!((ratio - 1.975).abs() < 0.05, "{ratio}");+ assert!(close(moved[9], m[9]) && close(moved[0], m[0]));+ }++ #[test]+ fn triangles_cover_the_patch_with_their_sources() {+ let m = square();+ let source = [Vec2::new(0.0, 0.0), Vec2::new(30.0, 0.0), Vec2::new(30.0, 30.0), Vec2::new(0.0, 30.0)];+ let t = triangles(&m, source, 4);+ assert_eq!(t.len(), 4 * 4 * 6);+ assert_eq!(t.first(), Some(&[100.0, 100.0, 0.0, 0.0]));+ let lines = grid_lines(&m, 6);+ assert_eq!(lines.len(), 8);+ assert!(lines.iter().all(|l| l.len() == 7));+ }+}diff --git a/crates/engine/src/zip.rs b/crates/engine/src/zip.rsnew file mode 100644index 0000000..570aeeb--- /dev/null+++ b/crates/engine/src/zip.rs@@ -0,0 +1,211 @@+//! Zip archives: reading entries (stored or deflated) and writing deflated ones. No Zip64,+//! encryption or multi-part archives.++/// An archive read into memory: its entries by name.+pub struct ZipReader<'a> {+ bytes: &'a [u8],+ entries: Vec<Entry>,+}++#[derive(Clone)]+struct Entry {+ name: String,+ method: u16,+ compressed: usize,+ size: usize,+ crc: u32,+ local: usize,+}++/// The largest entry read: anything claiming more is refused.+const MAX_ENTRY: usize = 1 << 30;++impl<'a> ZipReader<'a> {+ /// The archive in `bytes`, if it is one.+ pub fn new(bytes: &'a [u8]) -> Option<ZipReader<'a>> {+ // the end record is in the last 64 KiB (its comment can be that long)+ let from = bytes.len().saturating_sub(22 + 0xFFFF);+ let tail = bytes.get(from..)?;+ let end =+ (0..tail.len().checked_sub(21)?).rev().find(|&i| tail.get(i..i + 4) == Some(&[0x50, 0x4B, 0x05, 0x06]))?+ + from;+ let count = usize::from(u16le(bytes, end + 10)?);+ let mut at = usize::try_from(u32le(bytes, end + 16)?).ok()?;+ let mut entries = Vec::with_capacity(count.min(65_536));+ for _ in 0..count {+ if u32le(bytes, at)? != 0x0201_4B50 {+ return None;+ }+ let method = u16le(bytes, at + 10)?;+ let crc = u32le(bytes, at + 16)?;+ let compressed = usize::try_from(u32le(bytes, at + 20)?).ok()?;+ let size = usize::try_from(u32le(bytes, at + 24)?).ok()?;+ let name_len = usize::from(u16le(bytes, at + 28)?);+ let extra = usize::from(u16le(bytes, at + 30)?);+ let comment = usize::from(u16le(bytes, at + 32)?);+ let local = usize::try_from(u32le(bytes, at + 42)?).ok()?;+ let name = String::from_utf8_lossy(bytes.get(at + 46..at + 46 + name_len)?).into_owned();+ entries.push(Entry { name, method, compressed, size, crc, local });+ at += 46 + name_len + extra + comment;+ }+ Some(ZipReader { bytes, entries })+ }++ /// Every entry's name, folders included.+ pub fn names(&self) -> impl Iterator<Item = &str> {+ self.entries.iter().map(|e| e.name.as_str())+ }++ /// The contents of entry `name`; `None` if it is missing, damaged or of a kind not read.+ pub fn read(&self, name: &str) -> Option<Vec<u8>> {+ let e = self.entries.iter().find(|e| e.name == name)?;+ if e.size > MAX_ENTRY || e.compressed > MAX_ENTRY || u32le(self.bytes, e.local)? != 0x0403_4B50 {+ return None;+ }+ let name_len = usize::from(u16le(self.bytes, e.local + 26)?);+ let extra = usize::from(u16le(self.bytes, e.local + 28)?);+ let start = e.local + 30 + name_len + extra;+ let raw = self.bytes.get(start..start.checked_add(e.compressed)?)?;+ let data = match e.method {+ 0 => raw.to_vec(),+ 8 => miniz_oxide::inflate::decompress_to_vec_with_limit(raw, e.size).ok()?,+ _ => return None,+ };+ (data.len() == e.size && crc32(&data) == e.crc).then_some(data)+ }+}++fn u16le(b: &[u8], at: usize) -> Option<u16> {+ Some(u16::from_le_bytes(b.get(at..at.checked_add(2)?)?.try_into().ok()?))+}++fn u32le(b: &[u8], at: usize) -> Option<u32> {+ Some(u32::from_le_bytes(b.get(at..at.checked_add(4)?)?.try_into().ok()?))+}++/// Writes an archive entry by entry.+#[derive(Default)]+pub struct ZipWriter {+ out: Vec<u8>,+ central: Vec<u8>,+ count: u16,+}++impl ZipWriter {+ pub fn new() -> ZipWriter {+ ZipWriter::default()+ }++ /// Adds `data` as entry `name`, deflated (or stored, if deflating doesn't make it smaller).+ pub fn add(&mut self, name: &str, data: &[u8]) {+ let crc = crc32(data);+ let deflated = miniz_oxide::deflate::compress_to_vec(data, 6);+ let (method, body): (u16, &[u8]) = if deflated.len() < data.len() { (8, &deflated) } else { (0, data) };+ let local = self.out.len() as u32;+ let name = name.as_bytes();+ let header = |sig: u32, central: bool| {+ let mut h = Vec::with_capacity(46 + name.len());+ h.extend_from_slice(&sig.to_le_bytes());+ if central {+ h.extend_from_slice(&20u16.to_le_bytes()); // made by+ }+ h.extend_from_slice(&20u16.to_le_bytes()); // needed+ h.extend_from_slice(&0x0800u16.to_le_bytes()); // names are UTF-8+ h.extend_from_slice(&method.to_le_bytes());+ h.extend_from_slice(&0u16.to_le_bytes()); // time+ h.extend_from_slice(&0x0021u16.to_le_bytes()); // date: 1980-01-01+ h.extend_from_slice(&crc.to_le_bytes());+ h.extend_from_slice(&(body.len() as u32).to_le_bytes());+ h.extend_from_slice(&(data.len() as u32).to_le_bytes());+ h.extend_from_slice(&(name.len() as u16).to_le_bytes());+ h.extend_from_slice(&0u16.to_le_bytes()); // extra+ if central {+ h.extend_from_slice(&0u16.to_le_bytes()); // comment+ h.extend_from_slice(&0u16.to_le_bytes()); // disk+ h.extend_from_slice(&0u16.to_le_bytes()); // internal attributes+ h.extend_from_slice(&0u32.to_le_bytes()); // external attributes+ h.extend_from_slice(&local.to_le_bytes());+ }+ h.extend_from_slice(name);+ h+ };+ self.out.extend_from_slice(&header(0x0403_4B50, false));+ self.out.extend_from_slice(body);+ self.central.extend_from_slice(&header(0x0201_4B50, true));+ self.count = self.count.saturating_add(1);+ }++ /// The finished archive.+ pub fn finish(mut self) -> Vec<u8> {+ let start = self.out.len() as u32;+ let size = self.central.len() as u32;+ self.out.append(&mut self.central);+ self.out.extend_from_slice(&0x0605_4B50u32.to_le_bytes());+ self.out.extend_from_slice(&[0; 4]);+ self.out.extend_from_slice(&self.count.to_le_bytes());+ self.out.extend_from_slice(&self.count.to_le_bytes());+ self.out.extend_from_slice(&size.to_le_bytes());+ self.out.extend_from_slice(&start.to_le_bytes());+ self.out.extend_from_slice(&0u16.to_le_bytes());+ self.out+ }+}++/// The CRC-32 zip uses.+pub fn crc32(data: &[u8]) -> u32 {+ const fn table() -> [u32; 256] {+ let mut t = [0u32; 256];+ let mut i = 0;+ while i < 256 {+ let mut c = i as u32;+ let mut k = 0;+ while k < 8 {+ c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 };+ k += 1;+ }+ #[allow(clippy::indexing_slicing)] // const evaluation: i is below 256+ {+ t[i] = c;+ }+ i += 1;+ }+ t+ }+ const TABLE: [u32; 256] = table();+ !data.iter().fold(!0u32, |c, &b| TABLE.get(usize::from((c as u8) ^ b)).copied().unwrap_or(0) ^ (c >> 8))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn entries_round_trip() {+ let mut w = ZipWriter::new();+ let big: Vec<u8> = (0..100_000u32).map(|i| (i % 7) as u8).collect();+ w.add("Document.archive", b"bplist00 not really");+ w.add("A1/0~0.lz4", &big);+ w.add("QuickLook/Thumbnail.png", &[]);+ let bytes = w.finish();+ let r = ZipReader::new(&bytes).unwrap();+ assert_eq!(r.names().collect::<Vec<_>>(), ["Document.archive", "A1/0~0.lz4", "QuickLook/Thumbnail.png"]);+ assert_eq!(r.read("A1/0~0.lz4").as_deref(), Some(big.as_slice()));+ assert_eq!(r.read("QuickLook/Thumbnail.png").as_deref(), Some(&[][..]));+ assert_eq!(r.read("missing"), None);+ assert_eq!(crc32(b"123456789"), 0xCBF4_3926);+ }++ #[test]+ fn damaged_archives_read_as_nothing() {+ assert!(ZipReader::new(b"PK nothing here").is_none());+ let mut w = ZipWriter::new();+ w.add("a", &[1, 2, 3, 4, 5, 6, 7, 8].repeat(100));+ let mut bytes = w.finish();+ // a flipped byte in the data fails the check+ if let Some(b) = bytes.get_mut(40) {+ *b ^= 0xFF;+ }+ let r = ZipReader::new(&bytes).unwrap();+ assert_eq!(r.read("a"), None);+ }+}diff --git a/crates/gpu/Cargo.toml b/crates/gpu/Cargo.tomlnew file mode 100644index 0000000..4b0340b--- /dev/null+++ b/crates/gpu/Cargo.toml@@ -0,0 +1,18 @@+[package]+name = "procraft-gpu"+version.workspace = true+edition.workspace = true+rust-version.workspace = true+publish.workspace = true+description = "ProCraft's GPU renderer (wgpu): layer pixels, stroke rendering, compositing and presenting the canvas"++[lints]+workspace = true++[dependencies]+procraft-engine = { workspace = true }+wgpu = { workspace = true }+bytemuck = { workspace = true }+pollster = { workspace = true }+log = { workspace = true }+thiserror = { workspace = true }diff --git a/crates/gpu/src/canvas.rs b/crates/gpu/src/canvas.rsnew file mode 100644index 0000000..387712c--- /dev/null+++ b/crates/gpu/src/canvas.rs@@ -0,0 +1,5121 @@+//! The canvas on the GPU: a texture per layer, the stroke being drawn, the composite, and the+//! undo history (pixels and document structure).+//!+//! Calls queue work; [`Canvas::render`] records and submits it in order, recomposites what+//! changed and, given a target, draws the canvas to it.++use std::collections::{HashMap, HashSet};+use std::num::NonZeroU64;+use std::sync::mpsc;++use procraft_engine::animation::{self, FrameLook};+use procraft_engine::brush::{Brush, GrainMode, Rendering, Source};+use procraft_engine::document::{BlendMode, Document, Layer, LayerId, LayerKind};+use procraft_engine::geom::{Affine, IRect};+use procraft_engine::stroke::Stamp;+use procraft_engine::textures::{self, GrayImage, TEXTURE_SIZE};++use crate::{Gpu, GpuError};++const LAYER_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;+/// Half floats, so a stroke's build-up from many faint stamps doesn't band.+const STROKE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;+/// Every draw gets its own slot in the uniform buffer (dynamic offsets are 256-byte aligned).+const SLOT: u64 = 256;+/// The Multiply blend mode's number.+const MULTIPLY_MODE: u32 = 1;++/// The largest uniform block a shader reads.+const UNIFORM_SIZE: u64 = 112;+const _: () = assert!(+ size_of::<LayerUniform>() as u64 <= UNIFORM_SIZE+ && size_of::<StampUniform>() as u64 <= UNIFORM_SIZE+ && size_of::<FilterUniform>() as u64 <= UNIFORM_SIZE,+ "a uniform block outgrew its binding"+);++/// The vertex layout of a warp mesh corner: where it goes, and where it came from (pixels).+const MESH_ATTRIBUTES: [wgpu::VertexAttribute; 2] = wgpu::vertex_attr_array![0 => Float32x2, 1 => Float32x2];++/// The vertex layout of a stamp instance (stroke stamps and the predicted tail).+const STAMP_ATTRIBUTES: [wgpu::VertexAttribute; 10] = wgpu::vertex_attr_array![+ 0 => Float32x2, 1 => Float32, 2 => Float32, 3 => Float32, 4 => Float32, 5 => Float32x2, 6 => Float32x2, 7 => Float32x4,+ 8 => Float32x4, 9 => Float32x4+];++#[repr(C)]+#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]+struct OverlayUniform {+ m0: [f32; 4],+ m1: [f32; 4],+ color: [f32; 4],+ shape: i32,+ srgb: u32,+ _pad: [u32; 2],+}+/// Undo steps kept, and the most memory their pixels may hold.+const MAX_UNDO: usize = 100;+const MAX_UNDO_BYTES: u64 = 768 << 20;++/// How a transformed layer is resampled.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Resample {+ Nearest,+ Bilinear,+ Bicubic,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum StrokeTool {+ Paint,+ Erase,+ /// Drags colour along: the layer itself changes as the stroke goes.+ Smudge,+}++/// How a stroke is drawn.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct StrokeStyle {+ pub tool: StrokeTool,+ /// sRGB, 0..1.+ pub color: [f32; 3],+ /// The stroke's opacity: its stamps build up to at most this.+ pub opacity: f32,+ /// The round tip's hardness, 0..1.+ pub hardness: f32,+ /// The layer's alpha lock when the stroke began: paint only recolours existing pixels.+ pub preserve_alpha: bool,+ /// A shape image, or none for the round tip.+ pub shape: Option<u32>,+ /// A grain image, or none.+ pub grain: Option<u32>,+ pub grain_mode: GrainMode,+ /// One grain tile on the canvas, pixels.+ pub grain_scale: f32,+ pub grain_depth: f32,+ pub rendering: Rendering,+ /// Smudge: how much of the colour it carries the brush keeps at each stamp, 0..1.+ pub pull: f32,+ /// How much the stroke's paint pools at its edges (wet edges), and burns the paint it goes+ /// over where it is thin (burnt edges), 0..1.+ pub wet_edges: f32,+ pub burnt_edges: f32,+ /// Where the stroke's coverage turns fully on or off (0..1), or none if negative.+ pub alpha_threshold: f32,+ /// The grain made lighter or darker, and of more or less contrast, −1..1.+ pub grain_brightness: f32,+ pub grain_contrast: f32,+ /// Wet mix: how much of the colour under the brush mixes into its paint, 0..1; none paints+ /// plainly.+ pub wet_pull: Option<f32>,+ /// Wet mix: how many stamps' worth of paint the brush holds; none never runs out.+ pub load: f32,+ /// Wet mix: water in the paint, 0..1: it goes on thinner.+ pub dilution: f32,+ /// Wet mix: how hard the paint goes on over what is there (less of it pulled in), its grain+ /// (the mix uneven from pixel to pixel), how blurred what it pulls in is, and how much the+ /// pull varies from stamp to stamp; each 0..1.+ pub attack: f32,+ pub grade: f32,+ pub blur: f32,+ pub wet_jitter: f32,+ /// How the stroke blends into its layer: a blend mode's number (0 is Normal, in the order of+ /// `BlendMode`).+ pub blend: u32,+ /// Wet mix: how much the blur varies from stamp to stamp, 0..1.+ pub blur_jitter: f32,+ /// How the grain combines with the shape, and the burnt edges with the stroke (blend modes'+ /// numbers; both multiply as they start).+ pub grain_blend: u32,+ pub burnt_blend: u32,+ /// The grain turned, radians.+ pub grain_rotation: f32,+ /// No grain filtering: the grain read pixel by pixel, sharp, as from a finer image.+ pub grain_sharp: bool,+ /// No shape filtering: the shape image read pixel by pixel, its edges and specks hard.+ pub shape_sharp: bool,+ /// The secondary colour (sRGB, 0..1), mixed in as far as each stamp says.+ pub secondary: [f32; 3],+ /// Drawn as a brush preview (the studio's drawing pad, the library's strokes), which draws+ /// wet edges only as a firmer rim and burns nothing.+ pub preview: bool,+}++impl StrokeStyle {+ /// Whether the stroke changes its layer as it goes (smudging, painting wet) rather than+ /// building up in the stroke texture.+ pub fn in_place(&self) -> bool {+ self.tool == StrokeTool::Smudge || (self.tool == StrokeTool::Paint && self.wet_pull.is_some())+ }++ /// A plain hard round stroke.+ pub fn new(tool: StrokeTool, color: [f32; 3], opacity: f32) -> StrokeStyle {+ StrokeStyle {+ tool,+ color,+ opacity,+ hardness: 1.0,+ preserve_alpha: false,+ shape: None,+ grain: None,+ grain_mode: GrainMode::Texturized,+ grain_scale: 256.0,+ grain_depth: 0.0,+ rendering: Rendering::BuildUp,+ pull: DEFAULT_PULL,+ wet_edges: 0.0,+ burnt_edges: 0.0,+ alpha_threshold: -1.0,+ grain_brightness: 0.0,+ grain_contrast: 0.0,+ wet_pull: None,+ load: 0.0,+ dilution: 0.0,+ attack: 0.0,+ grade: 0.0,+ blur: 0.0,+ wet_jitter: 0.0,+ blend: 0,+ blur_jitter: 0.0,+ grain_blend: MULTIPLY_MODE,+ burnt_blend: MULTIPLY_MODE,+ grain_rotation: 0.0,+ grain_sharp: false,+ shape_sharp: false,+ secondary: [1.0, 1.0, 1.0],+ preview: false,+ }+ }++ /// A stroke drawn with `brush`'s shape, grain and rendering.+ pub fn for_brush(+ brush: &Brush,+ tool: StrokeTool,+ color: [f32; 3],+ opacity: f32,+ preserve_alpha: bool,+ ) -> StrokeStyle {+ let wet = brush.mixes_wet();+ StrokeStyle {+ tool,+ color,+ opacity,+ hardness: brush.hardness,+ preserve_alpha,+ shape: brush.shape.image,+ grain: brush.grain.image.filter(|_| brush.grain.depth > 0.0),+ grain_mode: brush.grain.mode,+ grain_scale: brush.grain.scale.max(1.0),+ grain_depth: brush.grain.depth.clamp(0.0, 1.0),+ rendering: brush.rendering,+ pull: DEFAULT_PULL,+ wet_edges: brush.setting("wet_edges").clamp(0.0, 1.0),+ burnt_edges: brush.setting("burnt_edges").clamp(0.0, 1.0),+ alpha_threshold: if brush.setting("alpha_threshold") >= 0.5 {+ brush.setting("alpha_threshold_amount").clamp(0.0, 1.0)+ } else {+ -1.0+ },+ grain_brightness: brush.setting("grain_brightness").clamp(-1.0, 1.0),+ grain_contrast: brush.setting("grain_contrast").clamp(-1.0, 1.0),+ // wet mix once any of its settings is set+ wet_pull: wet.then(|| brush.setting("wet_pull").clamp(0.0, 1.0)),+ load: if wet { brush.setting("wet_charge").clamp(0.0, 1.0) } else { 0.0 },+ dilution: if wet { brush.setting("wet_dilution").clamp(0.0, 1.0) } else { 0.0 },+ attack: if wet { brush.setting("wet_attack").clamp(0.0, 1.0) } else { 0.0 },+ // the grade goes both ways; drawn yet only as how uneven the mix is+ grade: if wet { brush.setting("wet_grade").abs().clamp(0.0, 1.0) } else { 0.0 },+ blur: if wet { brush.setting("wet_blur").clamp(0.0, 1.0) } else { 0.0 },+ wet_jitter: if wet { brush.setting("wet_jitter").clamp(0.0, 1.0) } else { 0.0 },+ blend: brush.setting("blend_mode").round().clamp(0.0, BlendMode::MAX_ID as f32) as u32,+ blur_jitter: if wet { brush.setting("wet_blur_jitter").clamp(0.0, 1.0) } else { 0.0 },+ grain_blend: brush.setting("grain_blend").round().clamp(0.0, BlendMode::MAX_ID as f32) as u32,+ burnt_blend: brush.setting("burnt_blend").round().clamp(0.0, BlendMode::MAX_ID as f32) as u32,+ grain_rotation: brush.setting("grain_rotation").clamp(-1.0, 1.0) * std::f32::consts::PI,+ grain_sharp: brush.setting("grain_filtering") < 0.5,+ shape_sharp: brush.setting("shape_filtering") < 0.5,+ secondary: [1.0, 1.0, 1.0],+ preview: false,+ }+ }++ /// The grain applied to each stamp (moving), as (layer, scale, depth).+ fn moving_grain(&self) -> Option<(u32, f32, f32)> {+ self.grain.filter(|_| self.grain_mode == GrainMode::Moving).map(|g| (g, self.grain_scale, self.grain_depth))+ }++ /// The grain applied to the whole stroke, fixed to the canvas (texturized).+ fn canvas_grain(&self) -> Option<(u32, f32, f32)> {+ self.grain.filter(|_| self.grain_mode == GrainMode::Texturized).map(|g| (g, self.grain_scale, self.grain_depth))+ }+}++/// Where [`Canvas::render`] draws the canvas.+pub struct Target<'a> {+ pub view: &'a wgpu::TextureView,+ pub format: wgpu::TextureFormat,+ /// Target size in pixels.+ pub size: (u32, u32),+ /// Canvas pixels to target pixels.+ pub to_screen: Affine,+ /// Colour around the canvas, sRGB 0..1.+ pub surround: [f32; 3],+ /// Lines over that colour, if any.+ pub grid: Option<SurroundGrid>,+ /// How the selection shows, while there is one.+ pub selection: Option<SelectionLook>,+ /// Frosted panels over the target, if any.+ pub backdrop: Option<Backdrop<'a>>,+ /// The canvas's colours to the target's colour space: a matrix in linear light (none when+ /// they are the same space).+ pub convert: Option<[[f32; 3]; 3]>,+ /// Or a table taking the canvas's colours to the target's (made by [`Canvas::display_lut`]),+ /// in place of the matrix.+ pub lut: Option<&'a DisplayLut>,+}++/// A colour table on the GPU for [`Target::lut`].+pub struct DisplayLut {+ bind: wgpu::BindGroup,+}++/// Panels of frosted glass over the target: what is behind each region is blurred (Gaussian,+/// `sigma` target pixels) and drawn in its place, for a translucent panel to be drawn over.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Backdrop<'a> {+ /// Rounded rectangles in target pixels: left, top, right, bottom, corner radius, and how much+ /// the region shows (0..1, as its panel fades).+ pub regions: &'a [[f32; 6]],+ pub sigma: f32,+}++/// The backdrop's blur is this many texels wide (sigma) where it is worked out: the scene is+/// drawn that much smaller.+const BACKDROP_TEXELS: f32 = 6.0;++/// The scene drawn small for frosted panels, and the other half of its blur.+struct BackdropGpu {+ size: (u32, u32),+ format: wgpu::TextureFormat,+ views: [wgpu::TextureView; 2],+ binds: [wgpu::BindGroup; 2],+}++impl BackdropGpu {+ fn new(+ device: &wgpu::Device,+ layout: &wgpu::BindGroupLayout,+ sampler: &wgpu::Sampler,+ size: (u32, u32),+ format: wgpu::TextureFormat,+ ) -> BackdropGpu {+ let view = || {+ device+ .create_texture(&wgpu::TextureDescriptor {+ label: Some("backdrop"),+ size: extent(size.0, size.1),+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format,+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,+ view_formats: &[],+ })+ .create_view(&wgpu::TextureViewDescriptor::default())+ };+ let views = [view(), view()];+ let binds =+ [sampled_bind(device, layout, &views[0], sampler), sampled_bind(device, layout, &views[1], sampler)];+ BackdropGpu { size, format, views, binds }+ }+}++/// How the selection shows over the canvas.+#[derive(Clone, Copy, Debug, PartialEq)]+pub enum SelectionLook {+ /// Bands over what is not selected.+ Stripes(Stripes),+ /// What is selected is multiplied by a colour (sRGB).+ Tint([f32; 3]),+ /// What is selected is covered by a colour (sRGB).+ Fill([f32; 3]),+}++/// Bands over the canvas outside the selection, dark and light by turns: one pair every `period`+/// target pixels (measured across), shifted `drift` pixels, at `coverage`.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Stripes {+ pub period: f32,+ pub drift: f32,+ pub coverage: f32,+}++#[repr(C)]+#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]+struct SelectionUniform {+ m0: [f32; 4],+ m1: [f32; 4],+ v: [f32; 4],+ mode: [f32; 4],+}++/// The selection on the GPU: its coverage, and that bound for drawing the stripes.+struct SelectionGpu {+ coverage: Vec<u8>,+ view: wgpu::TextureView,+ bind: wgpu::BindGroup,+}++/// Grid lines around the canvas, fixed to the target: `width` pixels wide, every `spacing` pixels+/// across and down from `origin` (none above it), in `color` (sRGB 0..1).+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct SurroundGrid {+ pub spacing: f32,+ pub origin: [f32; 2],+ pub width: f32,+ pub color: [f32; 3],+}++/// A small premultiplied RGBA8 image (rows top to bottom).+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Thumbnail {+ pub width: u32,+ pub height: u32,+ pub rgba: Vec<u8>,+}++#[repr(C)]+#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]+struct StampInstance {+ center: [f32; 2],+ radius: f32,+ alpha: f32,+ angle: f32,+ roundness: f32,+ grain_offset: [f32; 2],+ /// −1 where the shape is mirrored on that axis, else 1.+ flip: [f32; 2],+ /// Hue (turns), saturation and lightness shifts, and room for more.+ shift: [f32; 4],+ /// A moving grain's depth and tile size as multiples of the brush's, the share of the+ /// secondary colour, and how far it fades across its width (tilt gradation).+ look: [f32; 4],+ /// How hard the paint is pressed into a moving grain and how much that counts, and room for+ /// more.+ more: [f32; 4],+}++/// A stamp's (alpha, transfer) as its instance takes them: a capped stroke keeps its transfer+/// apart for the capped pipeline, or (without one) takes it into the alpha.+fn capped_alpha(style: &StrokeStyle, capped: bool, s: &Stamp) -> (f32, f32) {+ let alpha = s.alpha.clamp(0.0, 1.0);+ let transfer = if s.transfer.is_finite() { s.transfer.clamp(0.0, 1.0) } else { 1.0 };+ match (style.rendering, capped) {+ (Rendering::Capped, true) => (alpha, transfer),+ (Rendering::Capped, false) => (alpha * transfer, 1.0),+ _ => (alpha, 1.0),+ }+}++/// How far past its size a round tip reaches, by its hardness: (scale, growth) for its drawn+/// radius, scale·r + growth. Measured for a hard tip (0.95: a stroke of diameter d is 0.971·d ++/// 1.87 px across) and a medium hard one (0.75: 1.043·d + 1.44 px), whose soft rim builds up+/// past the size along a stroke; between them in between, and no further either way.+fn round_tip_reach(hardness: f32) -> (f32, f32) {+ let t = if hardness.is_finite() { ((hardness - 0.75) / 0.2).clamp(0.0, 1.0) } else { 1.0 };+ (1.096 + (0.971 - 1.096) * t, 0.36 + (0.735 - 0.36) * t)+}++/// The radius a stamp of `radius` is drawn at in `style`, thinned `taper` of the way by a taper+/// (the round tip's rim with it: measured, a taper narrows a thin brush and a wide one to the same+/// shares of their widths).+fn drawn_radius(style: &StrokeStyle, radius: f32, taper: f32) -> f32 {+ let r = radius.max(0.0);+ if style.shape.is_some() || r <= 0.0 {+ return r;+ }+ let (scale, growth) = round_tip_reach(style.hardness);+ let taper = if taper.is_finite() { taper.clamp(0.0, 1.0) } else { 1.0 };+ r * scale + growth * taper+}++/// A stamp's mirroring and colour shift for the GPU, kept finite.+fn stamp_extras(s: &Stamp) -> ([f32; 2], [f32; 4]) {+ let flip = s.flip.map(|f| if f { -1.0 } else { 1.0 });+ let [h, sat, l] = s.shift.map(|v| if v.is_finite() { v.clamp(-1.0, 1.0) } else { 0.0 });+ (flip, [h, sat, l, 0.0])+}++#[repr(C)]+#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]+struct StampUniform {+ canvas_size: [f32; 2],+ hardness: f32,+ shape: i32,+ color: [f32; 4],+ grain: i32,+ grain_scale: f32,+ grain_depth: f32,+ grain_brightness: f32,+ grain_contrast: f32,+ grain_rotation: f32,+ /// How the grain combines with the shape (a blend mode's number).+ grain_blend: u32,+ /// 1 when the grain is read unfiltered (sharp).+ grain_sharp: u32,+ /// The secondary colour (straight sRGB), which stamps mix in as far as they say.+ secondary: [f32; 4],+ /// 1 when the shape is read unfiltered (sharp).+ shape_sharp: u32,+ _pad: [u32; 3],+}++#[repr(C)]+#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]+struct LayerUniform {+ opacity: f32,+ stroke_mode: u32,+ stroke_opacity: f32,+ blend: u32,+ clipped: u32,+ grain: i32,+ grain_scale: f32,+ grain_depth: f32,+ solid: [f32; 4],+ wet: f32,+ burnt: f32,+ threshold: f32,+ grain_brightness: f32,+ grain_contrast: f32,+ /// 1 when the layer shows through its mask, and when the stroke being drawn is on the mask.+ masked: f32,+ stroke_on_mask: f32,+ /// How the stroke blends into the layer (a blend mode's number).+ stroke_blend: u32,+ /// An onion skin's colour and how far towards it the layer goes (none at 0).+ tint: [f32; 4],+ /// The stroke's texturized grain turned, radians, and how it and the burnt edges combine+ /// with the stroke (blend modes' numbers).+ grain_rotation: f32,+ grain_blend: u32,+ burnt_blend: u32,+ /// 1 when the grain is read unfiltered (sharp).+ grain_sharp: f32,+}++impl Default for LayerUniform {+ fn default() -> LayerUniform {+ LayerUniform {+ opacity: 1.0,+ stroke_mode: STROKE_NONE,+ stroke_opacity: 0.0,+ blend: 0,+ clipped: 0,+ grain: -1,+ grain_scale: 1.0,+ grain_depth: 0.0,+ solid: [0.0; 4],+ wet: 0.0,+ burnt: 0.0,+ threshold: -1.0,+ grain_brightness: 0.0,+ grain_contrast: 0.0,+ masked: 0.0,+ stroke_on_mask: 0.0,+ stroke_blend: 0,+ tint: [0.0; 4],+ grain_rotation: 0.0,+ grain_blend: MULTIPLY_MODE,+ burnt_blend: MULTIPLY_MODE,+ grain_sharp: 0.0,+ }+ }+}++/// How a layer shows besides its own settings: Animation Assist's onion skins.+#[derive(Clone, Copy)]+struct Look {+ tint: [f32; 4],+ opacity: f32,+}++impl Look {+ const PLAIN: Look = Look { tint: [0.0; 4], opacity: 1.0 };+}++impl LayerUniform {+ /// With the stroke's look: its canvas grain, if it has one, and its edges and threshold.+ fn with_grain(self, style: Option<&StrokeStyle>) -> LayerUniform {+ let Some(s) = style else { return self };+ let look = LayerUniform {+ wet: if s.preview { -s.wet_edges } else { s.wet_edges },+ burnt: if s.preview { 0.0 } else { s.burnt_edges },+ threshold: s.alpha_threshold,+ grain_brightness: s.grain_brightness,+ grain_contrast: s.grain_contrast,+ stroke_blend: s.blend,+ grain_rotation: s.grain_rotation,+ grain_blend: s.grain_blend,+ burnt_blend: s.burnt_blend,+ grain_sharp: if s.grain_sharp { 1.0 } else { 0.0 },+ ..self+ };+ match s.canvas_grain() {+ Some((g, scale, depth)) => LayerUniform { grain: g as i32, grain_scale: scale, grain_depth: depth, ..look },+ None => look,+ }+ }+}++#[repr(C)]+#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]+struct DisplayUniform {+ m0: [f32; 4],+ m1: [f32; 4],+ /// A colour matrix's rows (linear light), the first's last number 1 to apply it.+ c0: [f32; 4],+ c1: [f32; 4],+ c2: [f32; 4],+}++impl DisplayUniform {+ /// The map `m` and target encoding `srgb`, colours moved by `convert` if there is one, or by+ /// the bound table if `lut`.+ fn new(m0: [f32; 4], m1: [f32; 4], convert: Option<[[f32; 3]; 3]>, lut: bool) -> DisplayUniform {+ let row = |r: [f32; 3], on: f32| [r[0], r[1], r[2], on];+ let table = if lut { 1.0 } else { 0.0 };+ match convert.filter(|_| !lut) {+ Some([r0, r1, r2]) => DisplayUniform { m0, m1, c0: row(r0, 1.0), c1: row(r1, 0.0), c2: row(r2, 0.0) },+ None => DisplayUniform { m0, m1, c0: [0.0; 4], c1: [0.0, 0.0, 0.0, table], c2: [0.0; 4] },+ }+ }+}++/// An encoded colour moved by a linear-light matrix (clipped), as the display shader does.+fn convert_colour(c: [f32; 3], m: Option<[[f32; 3]; 3]>) -> [f32; 3] {+ let Some(m) = m else { return c };+ use procraft_engine::profile::{apply, decode, encode};+ apply(m, c.map(decode)).map(|v| encode(v.clamp(0.0, 1.0)))+}++#[repr(C)]+#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]+struct BackdropUniform {+ v0: [f32; 4],+ v1: [f32; 4],+ v2: [f32; 4],+}++#[repr(C)]+#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]+struct TransformUniform {+ r0: [f32; 4],+ r1: [f32; 4],+ r2: [f32; 4],+ p: [f32; 4],+}++#[repr(C)]+#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]+struct SurroundUniform {+ v0: [f32; 4],+ v1: [f32; 4],+}++const STROKE_NONE: u32 = 0;+const STROKE_PAINT: u32 = 1;+const STROKE_ERASE: u32 = 2;+const STROKE_PAINT_LOCKED: u32 = 3;++/// How much of what it carries a smudge brush keeps at each stamp.+const DEFAULT_PULL: f32 = 0.93;+/// A number in 0..1 that looks random, from `n`.+fn unit_hash(n: u32) -> f32 {+ let mut x = n.wrapping_mul(0x9e37_79b9) ^ 0x85eb_ca6b;+ x ^= x >> 15;+ x = x.wrapping_mul(0x2c1b_3c6d);+ x ^= x >> 12;+ (x & 0xffff) as f32 / 65535.0+}++/// Resolution of what a smudge brush carries, cells on a side.+const SMUDGE_GRID: u32 = 32;+const SMUDGE_UNIFORM_SIZE: u64 = std::mem::size_of::<SmudgeUniform>() as u64;+/// Wet mix: the stroke's length (canvas pixels) over which paint loaded at nothing runs out, by the+/// cube root of the length (see [`wet_mixture`]).+const CHARGE_LENGTH: f32 = 33.0;++/// A wet stamp's (mixture, final mixture, pull) once the stroke has gone `length` canvas pixels:+/// the paint the brush mixes into what it carries is what its dilution leaves (by 2.4) and its+/// charge (running out by the cube root of the length), at least its attack, times `jitter`; it+/// lays down what it carries by the mixture, a share of it by the grade; the pull is the wet+/// pull's eighth root (a pull of 0.9 keeps 0.99 a stamp).+fn wet_mixture(style: &StrokeStyle, length: f32, jitter: f32) -> (f32, f32, f32) {+ let charge = if style.load > 0.0 {+ 1.0 - ((1.0 - style.load) * (length.max(0.0) / CHARGE_LENGTH).cbrt()).clamp(0.0, 1.0)+ } else {+ 0.0+ };+ let diluted = (1.0 - style.dilution.clamp(0.0, 1.0)).powf(2.4);+ let mixture = ((diluted + charge).max(style.attack.clamp(0.0, 1.0)) * jitter).clamp(0.0, 1.0);+ let pull = style.wet_pull.unwrap_or(0.0).clamp(0.0, 1.0).powf(0.125);+ // undiluted the brush only paints; otherwise over a stroke it lays down half to all of what+ // its grade says+ let grade = style.grade.clamp(0.0, 1.0);+ let laid =+ if style.dilution <= 0.0 || pull * mixture <= 0.0 { 1.0 } else { mixture * (grade + (1.0 - grade) * 0.5) };+ (mixture, laid, pull)+}++#[repr(C)]+#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]+struct SmudgeUniform {+ center: [f32; 2],+ radius: f32,+ angle: f32,+ roundness: f32,+ alpha: f32,+ pull: f32,+ hardness: f32,+ shape: i32,+ first: u32,+ preserve_alpha: u32,+ stride: u32,+ bbox: [i32; 4],+ size: [u32; 2],+ grid: u32,+ /// 1 when stamps don't build up past the strongest over a pixel (the uniform glaze).+ uniform_glaze: u32,+ /// Wet mix: the paint (straight sRGB), how much of it the brush mixes into what it carries at+ /// this stamp, and how much of what it carries it lays down.+ paint: [f32; 4],+ /// 0 smudges; 1 paints wet.+ mode: u32,+ mixture: f32,+ final_mixture: f32,+ grade: f32,+ blur: f32,+ /// The grain: a layer (-1 for none), a tile's size in pixels (negative when it moves with the+ /// stamp) and its depth.+ grain: i32,+ grain_scale: f32,+ grain_depth: f32,+ /// Where a moving grain is read from at the stamp's middle (see `Stamp::grain_offset`), and+ /// the grain turned (radians), as the stamp shader takes them.+ grain_offset: [f32; 2],+ grain_rotation: f32,+ /// 1 when the grain is read unfiltered (sharp).+ grain_sharp: f32,+ /// 1 when the shape is read unfiltered (sharp).+ shape_sharp: f32,+ /// How hard the paint is pressed into a moving grain and how much that counts (see+ /// `Stamp::grain_press`).+ grain_press: f32,+ grain_bleed: f32,+ /// 1 when the texturized grain is laid over the wet stroke once (see `grain_once`).+ grain_once: f32,+ _pad: [f32; 4],+}++/// A smudge stroke in progress: the layer as a buffer the compute passes read and write, what the+/// brush carries, and the layer as it was before the stroke (for undo and cancel).+struct Smudge {+ layer: LayerId,+ work: wgpu::Buffer,+ carry: wgpu::Buffer,+ before: wgpu::Texture,+ started: bool,+ /// Stamps laid so far (for the wetness jitter).+ stamps: u32,+ /// How far the stroke has gone (canvas pixels, from stamp to stamp) and where its last stamp+ /// was: wet paint runs out with it.+ length: f32,+ last: Option<[f32; 2]>,+ /// Wet paint with a texturized grain: the stroke without the grain, and the layer as it was,+ /// the grain laid over the change once (see `grain_once`).+ raw: Option<wgpu::Buffer>,+ orig: Option<wgpu::Buffer>,+}++/// Whether a stroke's texturized grain is laid over its wet paint once, as it ends up, rather+/// than stamp by stamp (where it would wash out as the stamps build up).+fn grain_once(style: &StrokeStyle) -> bool {+ style.wet_pull.is_some()+ && style.tool == StrokeTool::Paint+ && style.grain.is_some()+ && style.grain_mode == GrainMode::Texturized+ && style.grain_depth > 0.0+}++#[derive(Clone, Copy, Debug)]+struct ActiveStroke {+ layer: LayerId,+ style: StrokeStyle,+ bounds: IRect,+ /// Painting an adjustment on: the stamps go into the adjustment's mask, not a layer.+ pencil: bool,+}++enum Op {+ /// Stamps added to the stroke (`clear`: the stroke is redrawn from scratch).+ Stamps {+ instances: Vec<StampInstance>,+ style: StrokeStyle,+ clear: bool,+ layer: LayerId,+ /// Into the adjustment's mask instead of the stroke.+ pencil: bool,+ },+ Commit(ActiveStroke),+ Cancel,+ Undo,+ Redo,+ Clear(LayerId),+ /// Clears a layer without an undo step (scratch canvases).+ Wipe(LayerId),+ /// The document changed structurally; `before` is how it was.+ Record(Box<Document>),+ /// Layers were added as copies: (from, to) pairs.+ Duplicate {+ pairs: Vec<(LayerId, LayerId)>,+ before: Box<Document>,+ },+ /// `upper` is blended into `lower` and removed from the document.+ MergeDown {+ upper: LayerId,+ lower: LayerId,+ before: Box<Document>,+ },+ /// `uppers` (bottom first; groups drawn first) are blended into `lower` in turn, as one step,+ /// and removed from the document.+ MergeMany {+ uppers: Vec<LayerId>,+ lower: LayerId,+ before: Box<Document>,+ },+ /// Group `group` of `before` is drawn into `into`: a new layer, or (`onto`) the layer it+ /// merges into.+ Flatten {+ group: LayerId,+ into: LayerId,+ onto: bool,+ before: Box<Document>,+ },+ /// The layer is copied aside to be transformed.+ TransformBegin(LayerId),+ /// Another layer is copied aside to be transformed with the first.+ TransformAlso(LayerId),+ /// The layer is redrawn from its copy through `to_source` (layer pixels to copy pixels).+ TransformSet {+ to_source: [f32; 9],+ resample: Resample,+ },+ /// The layer is redrawn from its copy as triangles, three corners each of (where it goes,+ /// where it came from) in pixels.+ TransformMesh {+ vertices: Vec<[f32; 4]>,+ resample: Resample,+ },+ /// The next step made is named so.+ Name(String),+ /// Where the history is now is marked.+ Mark,+ /// The steps made since the mark become one.+ Collapse,+ /// Layers' pixels are replaced (premultiplied RGBA8, the canvas's size), together as one undo+ /// step, with the document as it was (`before`) when that changed too.+ Write {+ layers: Vec<(LayerId, Vec<u8>)>,+ before: Option<Box<Document>>,+ },+ /// A layer's pixels are replaced with no undo step (during an edit held with `Hold`).+ Put(LayerId, Vec<u8>),+ /// A layer's pixels are set aside: what an edit made of many changes goes back to.+ Hold(LayerId),+ /// The held pixels, and the document as it was (`before`), become one undo step (`keep`), or+ /// the pixels are put back.+ Release {+ keep: bool,+ before: Option<Box<Document>>,+ },+ /// The layer being edited is redrawn from its copy through an adjustment.+ FilterSet(Filter),+ /// The liquify field made, with no offsets.+ LiquifyBegin,+ /// The adjustment's painted-on mask made, empty.+ PencilBegin,+ /// Liquify stamps drawn into the field.+ LiquifyStamps(Vec<LiquifyStamp>),+ /// The liquify field back to no offsets.+ LiquifyClear,+ /// The transform ends: kept as one undo step, or put back.+ TransformEnd {+ commit: bool,+ },+}++/// A layer being transformed: its pixels from before, which it is redrawn from.+struct Transforming {+ layer: LayerId,+ before: wgpu::Texture,+ bind: wgpu::BindGroup,+ /// Only what the selection takes moves.+ masked: bool,+ /// The copy alone, for an adjustment's last pass to mix with.+ before_bind: wgpu::BindGroup,+}++/// An adjustment drawn into the layer being edited (begun as a transform is), from its copy.+#[derive(Clone, Copy, Debug, PartialEq)]+pub enum Filter {+ /// In luma and chroma: the chroma turned by `hue` (radians) and scaled by `saturation`, and+ /// `brightness` added to the luma.+ Hsb { hue: f32, saturation: f32, brightness: f32 },+ /// A Gaussian blur of `sigma` canvas pixels.+ Blur { sigma: f32 },+ /// Each pixel pushed away from its neighbours by `amount`.+ Sharpen { amount: f32 },+ /// Fractal noise of `kind` (0 clouds, 1 billows, 2 ridges): `amount`, `frequency` (per canvas+ /// pixel), `octaves` (1..5) and `turbulence` (how much each finer octave keeps); each channel+ /// its own when `multi`; added to the colour, or else mixed in.+ Noise { amount: f32, frequency: f32, octaves: u32, turbulence: f32, kind: u32, multi: bool, added: bool },+ /// Each pixel the mean along `along` (canvas pixels), centred on it.+ Motion { along: [f32; 2] },+ /// Each pixel streaked towards `centre` (canvas pixels) by `amount` of the way.+ Zoom { centre: [f32; 2], amount: f32 },+ /// Red and blue pulled apart: from `centre` (canvas pixels) by `amount` of the distance, less+ /// within `falloff` (0..1 of the half diagonal) of it; or else (`displace`) by `offset` (canvas+ /// pixels) everywhere. `blur` (0..1) smears the fringes along the pull; `transparency` (0..1)+ /// fades the fringes beyond the picture.+ Chromatic {+ centre: [f32; 2],+ amount: f32,+ displace: bool,+ offset: [f32; 2],+ blur: f32,+ falloff: f32,+ transparency: f32,+ },+ /// A halftone of `kind` (0 full colour, 1 screen print, 2 newspaper) with cells `pitch` canvas+ /// pixels across.+ Halftone { pitch: f32, kind: u32 },+ /// The light of a blur (`sigma`) screened over the layer: `amount`, from `threshold` up over+ /// a ramp `transition` (0..1) long, strengthened by `burn` (−0.3..1).+ Bloom { sigma: f32, amount: f32, threshold: f32, transition: f32, burn: f32 },+ /// Each channel through the curves set with [`Canvas::set_table`].+ Curves,+ /// The gradient set with [`Canvas::set_table`] by brightness, `amount` of the way.+ GradientMap { amount: f32 },+ /// Each channel (red, green, blue) shifted in its shadows, midtones and highlights (−1..1).+ ColorBalance { shadows: [f32; 3], midtones: [f32; 3], highlights: [f32; 3] },+ /// The copy moved by the liquify field (begun with [`Canvas::begin_liquify`]), `amount` of it.+ Liquify { amount: f32 },+ /// The copy from `offset` (canvas pixels) away: cloning, painted on.+ Clone { offset: [f32; 2] },+ /// A glitch of `kind` 0 artifact (blocks copied from a few blocks away), 1 wave (rows bent+ /// sideways), 2 signal (bands ghosted sideways), 3 diverge (the channels moved apart in+ /// blocks), `amount` (0..1) of it. `values` are the kind's own: artifact and signal how many and+ /// the block size (0..1), wave the amplitude and frequency (0..1), diverge the red, green and+ /// blue shifts (−1..1). `zoom` (0..1) scales the pattern; `seed` varies it.+ Glitch { kind: u32, amount: f32, values: [f32; 3], zoom: f32, seed: f32 },+}++/// How a liquify stamp moves what is under it.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum LiquifyMode {+ Push,+ TwirlRight,+ TwirlLeft,+ Pinch,+ Expand,+ Crystals,+ Edge,+ Reconstruct,+}++/// One liquify stamp: where (canvas pixels), how far the brush moved since the last one, its+/// radius and pressure (0..1), how much it scatters (distortion, 0..1), and a seed.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct LiquifyStamp {+ pub centre: [f32; 2],+ pub moved: [f32; 2],+ pub radius: f32,+ pub pressure: f32,+ pub distortion: f32,+ pub seed: f32,+ pub mode: LiquifyMode,+}++#[repr(C)]+#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]+struct LiquifyUniform {+ stamp: [f32; 4],+ move_mode: [f32; 4],+ canvas: [f32; 4],+ pad: [f32; 4],+}++/// An adjustment painted on: how much of each pixel the brush has covered (the stroke format, its+/// red channel read).+struct PencilMask {+ view: wgpu::TextureView,+ /// Where it has been painted (canvas pixels): all the adjustment can have changed.+ bounds: IRect,+}++/// The liquify field: offsets (canvas pixels) a pixel shows the copy from, and that with the copy+/// for the adjustment's last pass.+struct LiquifyField {+ view: wgpu::TextureView,+ bind: wgpu::BindGroup,+}++#[repr(C)]+#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]+struct FilterUniform {+ a: [f32; 4],+ b: [f32; 4],+ size: [f32; 4],+ c: [f32; 4],+}++struct LayerGpu {+ texture: wgpu::Texture,+ view: wgpu::TextureView,+}++/// Steps (oldest first) as one: its pixels latest first, so undoing them puts back the oldest+/// last, and the document and selection from before the first that changed them.+fn collapsed(steps: Vec<Step>) -> Step {+ let made = steps.last().map_or(0, |s| s.made);+ let name = steps.iter().rev().find_map(|s| s.name.clone());+ let mut out = Step { made, name, doc: None, pixels: Vec::new(), selection: None };+ for step in steps.into_iter().rev() {+ out.pixels.extend(step.pixels);+ if step.doc.is_some() {+ out.doc = step.doc;+ }+ if step.selection.is_some() {+ out.selection = step.selection;+ }+ }+ out+}++/// Pixels of a layer region from before an edit.+struct Snapshot {+ layer: LayerId,+ rect: IRect,+ texture: wgpu::Texture,+}++impl Snapshot {+ fn bytes(&self) -> u64 {+ u64::from(self.rect.width()) * u64::from(self.rect.height()) * 4+ }+}++/// One undoable step: the document as it was (for structural changes) and the pixels it changed.+struct Step {+ /// Which step it was ([`Canvas::steps_made`] once it was made); kept through undo and redo.+ made: u64,+ /// What it did, as undo and redo name it ("Paint stroke"), if it was named.+ name: Option<String>,+ doc: Option<Box<Document>>,+ pixels: Vec<Snapshot>,+ /// The selection to put back (its coverage, or none for nothing selected), when the step+ /// changed it.+ selection: Option<Option<Vec<u8>>>,+}++impl Step {+ fn bytes(&self) -> u64 {+ self.pixels.iter().map(Snapshot::bytes).sum()+ }+}++struct Pipelines {+ /// A 3D colour table and its sampler, for the display.+ lut_layout: wgpu::BindGroupLayout,+ /// The display's: the canvas, the uniforms and the colour table.+ display_lut_layout: wgpu::PipelineLayout,+ quad_layout: wgpu::BindGroupLayout,+ brush_layout: wgpu::BindGroupLayout,+ sampled_layout: wgpu::BindGroupLayout,+ uniform_layout: wgpu::BindGroupLayout,+ stamp: wgpu::RenderPipeline,+ stamp_max: wgpu::RenderPipeline,+ /// Stamps adding towards their transfer (dual-source blending), where the GPU has it.+ stamp_capped: Option<wgpu::RenderPipeline>,+ layer: wgpu::RenderPipeline,+ blend: wgpu::RenderPipeline,+ solid: wgpu::RenderPipeline,+ commit_paint: wgpu::RenderPipeline,+ commit_erase: wgpu::RenderPipeline,+ commit_locked: wgpu::RenderPipeline,+ thumb: wgpu::RenderPipeline,+ transform: wgpu::RenderPipeline,+ mesh: wgpu::RenderPipeline,+ /// What a transform leaves where it was (with a selection).+ transform_static: wgpu::RenderPipeline,+ transform_layout: wgpu::BindGroupLayout,+ /// Adjustments: the copy alone, and the passes.+ before_layout: wgpu::BindGroupLayout,+ /// Adjustment passes by their fragment entry.+ filters: HashMap<&'static str, wgpu::RenderPipeline>,+ /// Liquify stamps added into the field, and reconstruct's fading of it.+ liquify_add: wgpu::RenderPipeline,+ liquify_fade: wgpu::RenderPipeline,+ /// The selection's look, per target format and whether it multiplies.+ selection: HashMap<(wgpu::TextureFormat, bool), wgpu::RenderPipeline>,+ selection_module: wgpu::ShaderModule,+ smudge_layout: wgpu::BindGroupLayout,+ smudge_carry: wgpu::ComputePipeline,+ smudge_deposit: wgpu::ComputePipeline,+ display_module: wgpu::ShaderModule,+ display_pipeline_layout: wgpu::PipelineLayout,+ display: HashMap<wgpu::TextureFormat, wgpu::RenderPipeline>,+ surround_module: wgpu::ShaderModule,+ surround_pipeline_layout: wgpu::PipelineLayout,+ surround: HashMap<wgpu::TextureFormat, wgpu::RenderPipeline>,+ stamp_layout: wgpu::PipelineLayout,+ overlay_module: wgpu::ShaderModule,+ overlay: HashMap<wgpu::TextureFormat, wgpu::RenderPipeline>,+ /// Frosted panels: the blur passes and the regions drawn, per target format.+ backdrop_module: wgpu::ShaderModule,+ blur: HashMap<wgpu::TextureFormat, wgpu::RenderPipeline>,+ frost: HashMap<wgpu::TextureFormat, wgpu::RenderPipeline>,+}++pub struct Canvas {+ width: u32,+ height: u32,+ pipelines: Pipelines,+ layers: HashMap<LayerId, LayerGpu>,+ stroke_view: wgpu::TextureView,+ /// Ping-pong pair; the finished composite is always left in the first.+ composite: [wgpu::Texture; 2],+ composite_views: [wgpu::TextureView; 2],+ /// Where a group's layers are composited before the group goes onto the stack below: a pair+ /// for each depth of group (made when first needed).+ groups: Vec<([wgpu::Texture; 2], [wgpu::TextureView; 2])>,+ /// Animation Assist playing: the frame shown (alone, no onion skins).+ play_frame: Option<usize>,+ scratch: wgpu::Texture,+ scratch_view: wgpu::TextureView,+ sampler: wgpu::Sampler,+ grains_view: wgpu::TextureView,+ grain_sampler: wgpu::Sampler,+ shapes_view: wgpu::TextureView,+ shape_sampler: wgpu::Sampler,+ /// The shape and grain arrays, and which images of the user's own their spare layers hold.+ shapes: wgpu::Texture,+ grains: wgpu::Texture,+ shape_sources: SourceSlots,+ grain_sources: SourceSlots,+ /// Full coverage, stood in for the selection when there is none.+ everything: wgpu::TextureView,+ /// Where an adjustment is painted on (Pencil), instead of everywhere the selection takes.+ pencil: Option<PencilMask>,+ liquify: Option<LiquifyField>,+ /// The curves or gradient adjustments read (256 RGBA8 entries).+ table: wgpu::Texture,+ table_view: wgpu::TextureView,+ selection: Option<SelectionGpu>,+ /// Shapes, grains and the selection for the stamp shader.+ brush_bind: wgpu::BindGroup,+ /// Every texture slot bound to the stroke texture: for draws that only read the stroke.+ stroke_bind: wgpu::BindGroup,+ display_bind: wgpu::BindGroup,+ /// The table that leaves colours as they are, bound when a target has none.+ identity_lut: wgpu::BindGroup,+ uniform_buffer: wgpu::Buffer,+ uniform_bind: wgpu::BindGroup,+ uniform_slots: u64,+ stamp_buffer: wgpu::Buffer,+ stamp_capacity: u64,+ active: Option<ActiveStroke>,+ smudge: Option<Smudge>,+ /// A layer's pixels set aside by [`Canvas::hold_layer`].+ held: Option<Snapshot>,+ /// Counts the undo steps ever made, so that a change since some moment shows.+ steps_made: u64,+ /// The steps made when [`Canvas::mark_steps`] was last done.+ mark: Option<u64>,+ /// The name the next step made takes.+ next_name: Option<String>,+ smudge_params: wgpu::Buffer,+ smudge_capacity: u64,+ /// Stand-ins for a smudge's grain buffers when its stroke has none.+ smudge_spare: [wgpu::Buffer; 2],+ /// Stamps of input that hasn't happened yet (predicted), drawn over the canvas for one frame.+ prediction: Vec<StampInstance>,+ ops: Vec<Op>,+ dirty: IRect,+ undo: Vec<Step>,+ redo: Vec<Step>,+ transforming: Option<Transforming>,+ /// Other layers transformed along with it (layers picked together).+ transform_more: Vec<Transforming>,+ /// For frosted panels, made when first needed.+ backdrop: Option<BackdropGpu>,+}++const PREMULTIPLIED_OVER: wgpu::BlendState = wgpu::BlendState {+ color: wgpu::BlendComponent {+ src_factor: wgpu::BlendFactor::One,+ dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,+ operation: wgpu::BlendOperation::Add,+ },+ alpha: wgpu::BlendComponent {+ src_factor: wgpu::BlendFactor::One,+ dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,+ operation: wgpu::BlendOperation::Add,+ },+};++/// The larger of the two: stamps that don't build up (uniform glaze).+/// The target multiplied by what is drawn (its alpha kept).+const MULTIPLY: wgpu::BlendState = wgpu::BlendState {+ color: wgpu::BlendComponent {+ src_factor: wgpu::BlendFactor::Dst,+ dst_factor: wgpu::BlendFactor::Zero,+ operation: wgpu::BlendOperation::Add,+ },+ alpha: wgpu::BlendComponent {+ src_factor: wgpu::BlendFactor::Zero,+ dst_factor: wgpu::BlendFactor::One,+ operation: wgpu::BlendOperation::Add,+ },+};++/// A capped stamp: its paint (scaled by its transfer) plus what is there kept by what the stamp+/// leaves (the second colour out of the shader), so each stamp adds towards its transfer.+const TOWARDS_TRANSFER: wgpu::BlendState = wgpu::BlendState {+ color: wgpu::BlendComponent {+ src_factor: wgpu::BlendFactor::One,+ dst_factor: wgpu::BlendFactor::OneMinusSrc1,+ operation: wgpu::BlendOperation::Add,+ },+ alpha: wgpu::BlendComponent {+ src_factor: wgpu::BlendFactor::One,+ dst_factor: wgpu::BlendFactor::OneMinusSrc1Alpha,+ operation: wgpu::BlendOperation::Add,+ },+};++const MAXIMUM: wgpu::BlendState = wgpu::BlendState {+ color: wgpu::BlendComponent {+ src_factor: wgpu::BlendFactor::One,+ dst_factor: wgpu::BlendFactor::One,+ operation: wgpu::BlendOperation::Max,+ },+ alpha: wgpu::BlendComponent {+ src_factor: wgpu::BlendFactor::One,+ dst_factor: wgpu::BlendFactor::One,+ operation: wgpu::BlendOperation::Max,+ },+};++/// `dst · (1 − src.a)`: erasing.+const DESTINATION_OUT: wgpu::BlendState = wgpu::BlendState {+ color: wgpu::BlendComponent {+ src_factor: wgpu::BlendFactor::Zero,+ dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,+ operation: wgpu::BlendOperation::Add,+ },+ alpha: wgpu::BlendComponent {+ src_factor: wgpu::BlendFactor::Zero,+ dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,+ operation: wgpu::BlendOperation::Add,+ },+};++impl Canvas {+ pub fn new(gpu: &Gpu, doc: &Document) -> Result<Canvas, GpuError> {+ let (width, height) = (doc.width(), doc.height());+ let max = gpu.max_texture_size();+ if width > max || height > max {+ return Err(GpuError::TooLarge(width, height, max));+ }+ let device = &gpu.device;+ let pipelines = Pipelines::new(device);+ let stroke_texture = texture(device, "stroke", width, height, STROKE_FORMAT);+ let stroke_view = stroke_texture.create_view(&wgpu::TextureViewDescriptor::default());+ let composite = [+ texture(device, "composite", width, height, LAYER_FORMAT),+ texture(device, "composite 2", width, height, LAYER_FORMAT),+ ];+ let composite_views = [+ composite[0].create_view(&wgpu::TextureViewDescriptor::default()),+ composite[1].create_view(&wgpu::TextureViewDescriptor::default()),+ ];+ let scratch = texture(device, "scratch", width, height, LAYER_FORMAT);+ let scratch_view = scratch.create_view(&wgpu::TextureViewDescriptor::default());+ let array_view =+ wgpu::TextureViewDescriptor { dimension: Some(wgpu::TextureViewDimension::D2Array), ..Default::default() };+ let (shape_images, grain_images) = (textures::shapes(), textures::grains());+ let shapes = brush_images(gpu, "shapes", &shape_images);+ let grains = brush_images(gpu, "grains", &grain_images);+ let shapes_view = shapes.create_view(&array_view);+ let grains_view = grains.create_view(&array_view);+ let mipmapped = |label, address| {+ device.create_sampler(&wgpu::SamplerDescriptor {+ label: Some(label),+ address_mode_u: address,+ address_mode_v: address,+ mag_filter: wgpu::FilterMode::Linear,+ min_filter: wgpu::FilterMode::Linear,+ mipmap_filter: wgpu::MipmapFilterMode::Linear,+ ..Default::default()+ })+ };+ let shape_sampler = mipmapped("shape", wgpu::AddressMode::ClampToEdge);+ let grain_sampler = mipmapped("grain", wgpu::AddressMode::Repeat);+ let table = texture(device, "adjustment table", 256, 1, LAYER_FORMAT);+ let table_view = table.create_view(&wgpu::TextureViewDescriptor::default());+ let everything =+ coverage_texture(device, &gpu.queue, 1, 1, &[255]).create_view(&wgpu::TextureViewDescriptor::default());+ let brush_bind = brush_bind(+ device,+ &pipelines.brush_layout,+ [&shapes_view, &grains_view, &everything],+ [&shape_sampler, &grain_sampler],+ );+ let stroke_bind = quad_bind(device, &pipelines.quad_layout, [&stroke_view; 5], &grains_view, &grain_sampler);+ let sampler = device.create_sampler(&wgpu::SamplerDescriptor {+ label: Some("linear"),+ mag_filter: wgpu::FilterMode::Linear,+ min_filter: wgpu::FilterMode::Linear,+ ..Default::default()+ });+ let display_bind = sampled_bind(device, &pipelines.sampled_layout, &composite_views[0], &sampler);+ // two points on a side: each corner its own colour+ let corners: Vec<u8> = (0..8u8).flat_map(|i| [(i >> 2) & 1, (i >> 1) & 1, i & 1, 1].map(|c| c * 255)).collect();+ let identity_lut = lut_bind(gpu, &pipelines.lut_layout, 2, &corners);+ let uniform_slots = 64;+ let (uniform_buffer, uniform_bind) = uniforms(device, &pipelines.uniform_layout, uniform_slots);+ let stamp_capacity = 4096;+ let stamp_buffer = stamp_buffer(device, stamp_capacity);+ let mut canvas = Canvas {+ width,+ height,+ pipelines,+ layers: HashMap::new(),+ stroke_view,+ composite,+ composite_views,+ groups: Vec::new(),+ play_frame: None,+ scratch,+ scratch_view,+ sampler,+ grains_view,+ grain_sampler,+ shapes_view,+ shape_sampler,+ everything,+ pencil: None,+ liquify: None,+ table,+ table_view,+ selection: None,+ brush_bind,+ stroke_bind,+ display_bind,+ identity_lut,+ uniform_buffer,+ uniform_bind,+ uniform_slots,+ stamp_buffer,+ stamp_capacity,+ active: None,+ smudge: None,+ held: None,+ steps_made: 0,+ mark: None,+ next_name: None,+ smudge_params: smudge_params(device, 64),+ smudge_spare: [spare_buffer(device), spare_buffer(device)],+ smudge_capacity: 64,+ prediction: Vec::new(),+ ops: Vec::new(),+ dirty: IRect::from_size(width, height),+ undo: Vec::new(),+ redo: Vec::new(),+ transforming: None,+ transform_more: Vec::new(),+ backdrop: None,+ shapes,+ grains,+ shape_sources: SourceSlots::after(shape_images.len()),+ grain_sources: SourceSlots::after(grain_images.len()),+ };+ canvas.sync_layers(gpu, doc);+ Ok(canvas)+ }++ pub fn size(&self) -> (u32, u32) {+ (self.width, self.height)+ }++ /// Points `style` at `brush`'s own shape and grain images, if it has them, putting them in+ /// the arrays' spare layers first if they aren't there.+ pub fn use_sources(&mut self, gpu: &Gpu, style: &mut StrokeStyle, brush: &Brush) {+ if let Some(source) = brush.shape.source.as_ref() {+ style.shape = Some(self.shape_sources.layer(gpu, &self.shapes, source));+ }+ if let Some(source) = brush.grain.source.as_ref() {+ style.grain = Some(self.grain_sources.layer(gpu, &self.grains, source));+ }+ }++ fn full(&self) -> IRect {+ IRect::from_size(self.width, self.height)+ }++ pub fn has_stroke(&self) -> bool {+ self.active.is_some()+ }++ /// The open stroke's tool, if a stroke is open.+ pub fn stroke_tool(&self) -> Option<StrokeTool> {+ self.active.map(|a| a.style.tool)+ }++ /// Whether an undo is possible, counting queued work.+ pub fn can_undo(&self) -> bool {+ !self.undo.is_empty()+ || self.ops.iter().any(|op| {+ matches!(+ op,+ Op::Commit(_)+ | Op::Clear(_)+ | Op::Record(_)+ | Op::Duplicate { .. }+ | Op::MergeDown { .. }+ | Op::MergeMany { .. }+ | Op::Flatten { .. }+ | Op::TransformEnd { commit: true }+ | Op::Write { .. }+ | Op::Release { keep: true, .. }+ )+ })+ }++ pub fn can_redo(&self) -> bool {+ !self.redo.is_empty()+ }++ /// Names the next step made (what undo and redo call it), queued with the work that makes it.+ pub fn name_next_step(&mut self, name: &str) {+ self.ops.push(Op::Name(name.to_owned()));+ }++ /// The name of the step undo would undo next, and of the step redo would redo, as the+ /// history is after the work run so far.+ pub fn undo_name(&self) -> Option<String> {+ self.undo.last().and_then(|s| s.name.clone())+ }++ pub fn redo_name(&self) -> Option<String> {+ self.redo.last().and_then(|s| s.name.clone())+ }++ /// Marks where the history is once the queued work is done, for [`Canvas::collapse_steps`].+ pub fn mark_steps(&mut self) {+ self.end_stroke();+ self.ops.push(Op::Mark);+ }++ /// Makes the steps still to undo that were made since the mark one step, which undoes them+ /// all; the mark is used up.+ pub fn collapse_steps(&mut self) {+ self.end_stroke();+ self.ops.push(Op::Collapse);+ }++ /// How many undo steps have ever been made here (queued work not counted until drawn): it+ /// changes whenever something new is done.+ pub fn steps_made(&self) -> u64 {+ self.steps_made+ }++ /// Starts a stroke on `layer` (finishing one still open).+ pub fn begin_stroke(&mut self, layer: LayerId, style: StrokeStyle) {+ self.end_stroke();+ self.prediction.clear();+ self.active = Some(ActiveStroke { layer, style, bounds: IRect::EMPTY, pencil: false });+ }++ /// Draws more of the open stroke.+ pub fn add_stamps(&mut self, stamps: &[Stamp]) {+ self.push_stamps(stamps, false);+ }++ /// Redraws the open stroke from scratch with `stamps` (its final form, e.g. with the end taper).+ pub fn replace_stamps(&mut self, stamps: &[Stamp]) {+ self.push_stamps(stamps, true);+ }++ fn push_stamps(&mut self, stamps: &[Stamp], clear: bool) {+ let full = self.full();+ let Some(active) = self.active.as_mut() else { return };+ let mut bounds = IRect::EMPTY;+ let style = active.style;+ let capped = self.pipelines.stamp_capped.is_some();+ let instances: Vec<StampInstance> = stamps+ .iter()+ .filter(|s| s.center.is_finite() && s.radius.is_finite() && s.alpha.is_finite())+ .map(|s| {+ let radius = drawn_radius(&style, s.radius, s.taper);+ bounds = bounds.union(IRect::around(s.center, radius * std::f32::consts::SQRT_2));+ // without the capped pipeline, the transfer goes into the stamp+ let (alpha, transfer) = capped_alpha(&style, capped, s);+ StampInstance {+ center: [s.center.x, s.center.y],+ radius,+ alpha,+ angle: if s.angle.is_finite() { s.angle } else { 0.0 },+ roundness: if s.roundness.is_finite() { s.roundness.clamp(0.05, 1.0) } else { 1.0 },+ grain_offset: if s.grain_offset.is_finite() {+ [s.grain_offset.x, s.grain_offset.y]+ } else {+ [0.0; 2]+ },+ flip: stamp_extras(s).0,+ shift: stamp_extras(s).1,+ look: [s.grain_depth, s.grain_size, s.secondary, s.gradation]+ .map(|v| if v.is_finite() { v.clamp(0.0, 64.0) } else { 0.0 }),+ more: [s.grain_press, s.grain_bleed, transfer, 0.0]+ .map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }),+ }+ })+ .collect();+ let bounds = bounds.intersect(full);+ if clear {+ self.dirty = self.dirty.union(active.bounds);+ active.bounds = bounds;+ } else {+ active.bounds = active.bounds.union(bounds);+ }+ self.dirty = self.dirty.union(bounds);+ if !instances.is_empty() || clear {+ let pencil = active.pencil;+ self.ops.push(Op::Stamps {+ instances,+ style: active.style,+ clear: clear && !pencil,+ layer: active.layer,+ pencil,+ });+ }+ }++ /// Puts the open stroke into its layer (undoably).+ /// Stamps for where the input is predicted to go next: drawn over the canvas until replaced,+ /// never into the layer. Only painting strokes show them.+ pub fn set_prediction(&mut self, stamps: &[Stamp]) {+ self.prediction.clear();+ let Some(style) = self.active.map(|a| a.style).filter(|s| s.tool == StrokeTool::Paint) else { return };+ let capped = self.pipelines.stamp_capped.is_some();+ self.prediction.extend(+ stamps.iter().filter(|s| s.center.is_finite() && s.radius.is_finite() && s.alpha.is_finite()).map(|s| {+ let (alpha, transfer) = capped_alpha(&style, capped, s);+ StampInstance {+ center: [s.center.x, s.center.y],+ radius: drawn_radius(&style, s.radius, s.taper),+ alpha,+ angle: if s.angle.is_finite() { s.angle } else { 0.0 },+ roundness: if s.roundness.is_finite() { s.roundness.clamp(0.05, 1.0) } else { 1.0 },+ grain_offset: [0.0; 2],+ flip: stamp_extras(s).0,+ shift: stamp_extras(s).1,+ look: [s.grain_depth, s.grain_size, s.secondary, s.gradation]+ .map(|v| if v.is_finite() { v.clamp(0.0, 64.0) } else { 0.0 }),+ more: [s.grain_press, s.grain_bleed, transfer, 0.0]+ .map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }),+ }+ }),+ );+ }++ pub fn end_stroke(&mut self) {+ self.prediction.clear();+ if let Some(active) = self.active.take() {+ self.ops.push(Op::Commit(active));+ }+ }++ /// Drops the open stroke.+ pub fn cancel_stroke(&mut self) {+ self.prediction.clear();+ if let Some(active) = self.active.take() {+ self.dirty = self.dirty.union(active.bounds);+ self.ops.push(Op::Cancel);+ }+ }++ /// Undoes the last step; a structural step puts the document back during the next render.+ pub fn undo(&mut self) {+ self.end_stroke();+ self.ops.push(Op::Undo);+ }++ pub fn redo(&mut self) {+ self.end_stroke();+ self.ops.push(Op::Redo);+ }++ pub fn clear_layer(&mut self, layer: LayerId) {+ self.end_stroke();+ self.ops.push(Op::Clear(layer));+ }++ /// Replaces a layer's pixels (premultiplied RGBA8, the canvas's size) as one undo step; pixels+ /// of the wrong size are ignored.+ pub fn write_layer(&mut self, layer: LayerId, pixels: Vec<u8>) {+ self.write_layers(vec![(layer, pixels)]);+ }++ /// Replaces a layer's pixels with no undo step; a picture of the wrong size is left out.+ pub fn put_layer(&mut self, layer: LayerId, pixels: Vec<u8>) {+ if pixels.len() == self.width as usize * self.height as usize * 4 {+ self.ops.push(Op::Put(layer, pixels));+ self.invalidate();+ }+ }++ /// Sets a layer's pixels aside, for an edit made of many changes (with [`Canvas::put_layer`])+ /// that ends with [`Canvas::release_layer`].+ pub fn hold_layer(&mut self, layer: LayerId) {+ self.end_stroke();+ self.ops.push(Op::Hold(layer));+ }++ /// Ends a held edit: `keep` makes it one undo step back to the held pixels and `before` (the+ /// document as the edit began); otherwise the held pixels are put back.+ pub fn release_layer(&mut self, keep: bool, before: Option<Document>) {+ self.ops.push(Op::Release { keep, before: before.map(Box::new) });+ self.invalidate();+ }++ /// Replaces several layers' pixels at once, as one undo step; pictures of the wrong size are+ /// left out.+ pub fn write_layers(&mut self, layers: Vec<(LayerId, Vec<u8>)>) {+ let size = self.width as usize * self.height as usize * 4;+ let layers: Vec<(LayerId, Vec<u8>)> = layers.into_iter().filter(|(_, p)| p.len() == size).collect();+ if !layers.is_empty() {+ self.end_stroke();+ self.ops.push(Op::Write { layers, before: None });+ }+ }++ /// Replaces several layers' pixels and changes the document together, as one undo step back+ /// to the pixels and to `before` (the document as it was); pictures of the wrong size are left+ /// out.+ pub fn write_layers_and_document(&mut self, layers: Vec<(LayerId, Vec<u8>)>, before: Document) {+ let size = self.width as usize * self.height as usize * 4;+ let layers: Vec<(LayerId, Vec<u8>)> = layers.into_iter().filter(|(_, p)| p.len() == size).collect();+ self.end_stroke();+ self.ops.push(Op::Write { layers, before: Some(Box::new(before)) });+ self.invalidate();+ }++ /// Clears a layer without recording it (for scratch canvases such as brush previews).+ pub fn wipe_layer(&mut self, layer: LayerId) {+ self.end_stroke();+ self.ops.push(Op::Wipe(layer));+ }++ /// Drops the undo history (scratch canvases).+ pub fn forget_history(&mut self) {+ self.undo.clear();+ self.redo.clear();+ }++ /// The document was changed (layers added, removed, reordered, their settings...): `before`+ /// is how it was, for undo.+ pub fn record_document(&mut self, before: Document) {+ self.end_stroke();+ self.ops.push(Op::Record(Box::new(before)));+ self.invalidate();+ }++ /// `to` (already in the document) was made as a copy of `from`; `before` is the document+ /// without it.+ pub fn duplicate_layer(&mut self, from: LayerId, to: LayerId, before: Document) {+ self.duplicate_layers(vec![(from, to)], before);+ }++ /// Layers (already in the document) were made as copies, each pair (from, to), as one undo+ /// step; `before` is the document without them.+ pub fn duplicate_layers(&mut self, pairs: Vec<(LayerId, LayerId)>, before: Document) {+ self.end_stroke();+ self.ops.push(Op::Duplicate { pairs, before: Box::new(before) });+ self.invalidate();+ }++ /// Blends `upper` into `lower`; the caller removes `upper` from the document once this is+ /// queued (`before` is the document with it).+ pub fn merge_down(&mut self, upper: LayerId, lower: LayerId, before: Document) {+ self.end_stroke();+ self.ops.push(Op::MergeDown { upper, lower, before: Box::new(before) });+ self.invalidate();+ }++ /// Blends `uppers` (bottom first: layers, or groups composited first) into `lower` in turn as+ /// one undo step; the caller removes them from the document once this is queued (`before` is+ /// the document with them).+ pub fn merge_layers(&mut self, uppers: Vec<LayerId>, lower: LayerId, before: Document) {+ self.end_stroke();+ self.ops.push(Op::MergeMany { uppers, lower, before: Box::new(before) });+ self.invalidate();+ }++ /// Draws group `group` into `into`: a new layer (`onto` false, already in the document) or the+ /// layer it merges into, blended with the group's opacity and mode. `before` is the document+ /// with the group; the caller changes the document once this is queued.+ pub fn flatten_group(&mut self, group: LayerId, into: LayerId, onto: bool, before: Document) {+ self.end_stroke();+ self.ops.push(Op::Flatten { group, into, onto, before: Box::new(before) });+ self.invalidate();+ }++ /// Recomposite everything next frame (after a change to visibility, opacity, order...).+ pub fn invalidate(&mut self) {+ self.dirty = self.full();+ }++ /// Animation Assist playing: frame `frame` shows alone (none: back to drawing).+ pub fn set_play_frame(&mut self, frame: Option<usize>) {+ if self.play_frame != frame {+ self.play_frame = frame;+ self.invalidate();+ }+ }++ /// Sets the selection: one byte of coverage per canvas pixel, rows top to bottom; none (or a+ /// buffer of the wrong size) selects everything. Painting and erasing keep inside it.+ pub fn set_selection(&mut self, gpu: &Gpu, coverage: Option<&[u8]>) {+ self.put_selection(&gpu.device, &gpu.queue, coverage.map(<[u8]>::to_vec));+ }++ /// Sets the selection as [`Self::set_selection`] does, as one undo step that puts `before` back+ /// (the coverage it had, or none). Runs what is queued first, so the step falls in order.+ pub fn change_selection(+ &mut self,+ gpu: &Gpu,+ doc: &mut Document,+ coverage: Option<&[u8]>,+ before: Option<Vec<u8>>,+ ) {+ self.render(gpu, doc, None);+ self.push_step(Step { made: 0, name: None, doc: None, pixels: Vec::new(), selection: Some(before) });+ self.set_selection(gpu, coverage);+ }++ /// The selection's coverage, one byte a canvas pixel, or none when nothing is selected.+ pub fn selection(&self) -> Option<&[u8]> {+ self.selection.as_ref().map(|s| s.coverage.as_slice())+ }++ fn put_selection(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, coverage: Option<Vec<u8>>) {+ let size = self.width as usize * self.height as usize;+ self.selection = coverage.filter(|c| c.len() == size).map(|coverage| {+ let view = coverage_texture(device, queue, self.width, self.height, &coverage)+ .create_view(&wgpu::TextureViewDescriptor::default());+ let bind = sampled_bind(device, &self.pipelines.sampled_layout, &view, &self.sampler);+ SelectionGpu { coverage, view, bind }+ });+ let mask = self.selection.as_ref().map_or(&self.everything, |s| &s.view);+ self.brush_bind = brush_bind(+ device,+ &self.pipelines.brush_layout,+ [&self.shapes_view, &self.grains_view, mask],+ [&self.shape_sampler, &self.grain_sampler],+ );+ }++ /// The 256 entries (RGBA8, 1024 bytes) the curves and gradient map adjustments read: for curves+ /// the red, green and blue curves and the curve for all three; for a gradient map its colours+ /// from dark to light. Other lengths are ignored.+ pub fn set_table(&mut self, gpu: &Gpu, entries: &[u8]) {+ if entries.len() == 1024 {+ gpu.queue.write_texture(+ copy_at(&self.table, 0, 0),+ entries,+ wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(1024), rows_per_image: Some(1) },+ extent(256, 1),+ );+ }+ }++ pub fn has_selection(&self) -> bool {+ self.selection.is_some()+ }++ /// Copies `layer` aside to transform it (ending a transform still open, kept).+ pub fn begin_transform(&mut self, layer: LayerId) {+ self.end_stroke();+ if self.is_transforming() {+ self.end_transform(true);+ }+ self.ops.push(Op::TransformBegin(layer));+ }++ /// Starts transforming `layers` together (the first as [`Self::begin_transform`] does).+ pub fn begin_transform_layers(&mut self, layers: &[LayerId]) {+ let Some((first, rest)) = layers.split_first() else { return };+ self.begin_transform(*first);+ self.ops.extend(rest.iter().map(|id| Op::TransformAlso(*id)));+ }++ /// Redraws the layer being transformed from its copy: `to_source` maps layer pixel+ /// coordinates to copy pixel coordinates (3 × 3, row-major).+ pub fn set_transform(&mut self, to_source: [f32; 9], resample: Resample) {+ if to_source.iter().all(|v| v.is_finite()) {+ self.replace_placement(Op::TransformSet { to_source, resample });+ }+ }++ /// Redraws the layer being transformed from its copy as a warp: `vertices` are triangles, three+ /// corners each of (layer x, y, copy x, y) in pixels.+ pub fn set_transform_mesh(&mut self, vertices: &[[f32; 4]], resample: Resample) {+ if vertices.iter().flatten().all(|v| v.is_finite()) {+ self.replace_placement(Op::TransformMesh { vertices: vertices.to_vec(), resample });+ }+ }++ /// Starts liquifying the layer being edited (begun with [`Self::begin_transform`]): a field of+ /// no offsets, which [`Self::liquify_stamps`] draws into and [`Filter::Liquify`] shows.+ pub fn begin_liquify(&mut self) {+ self.ops.push(Op::LiquifyBegin);+ }++ /// The adjustment being edited shows only where it is painted on from now on: strokes begun with+ /// [`Self::begin_pencil_stroke`] paint where (within the selection).+ pub fn begin_pencil(&mut self) {+ self.ops.push(Op::PencilBegin);+ }++ /// Whether an adjustment is being painted on, counting queued work.+ pub fn is_pencil(&self) -> bool {+ let mut on = self.pencil.is_some();+ for op in &self.ops {+ match op {+ Op::PencilBegin => on = true,+ Op::TransformEnd { .. } => on = false,+ _ => {}+ }+ }+ on+ }++ /// A stroke that paints the adjustment on (see [`Self::begin_pencil`]); stamps are added as for+ /// any stroke and [`Self::end_stroke`] ends it.+ pub fn begin_pencil_stroke(&mut self, layer: LayerId, style: StrokeStyle) {+ self.end_stroke();+ self.prediction.clear();+ self.active = Some(ActiveStroke { layer, style, bounds: IRect::EMPTY, pencil: true });+ }++ /// Liquify stamps drawn into the field, in order.+ pub fn liquify_stamps(&mut self, stamps: &[LiquifyStamp]) {+ if !stamps.is_empty() {+ self.ops.push(Op::LiquifyStamps(stamps.to_vec()));+ }+ }++ /// The liquify field back to no offsets.+ pub fn liquify_clear(&mut self) {+ self.ops.push(Op::LiquifyClear);+ }++ /// Layer `id` copied aside to be transformed (or adjusted) from.+ fn copy_aside(+ &self,+ device: &wgpu::Device,+ encoder: &mut wgpu::CommandEncoder,+ id: LayerId,+ ) -> Option<Transforming> {+ let layer = self.layers.get(&id)?;+ let before = device.create_texture(&wgpu::TextureDescriptor {+ label: Some("transform source"),+ size: extent(self.width, self.height),+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: LAYER_FORMAT,+ usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::TEXTURE_BINDING,+ view_formats: &[],+ });+ encoder.copy_texture_to_texture(+ copy_at(&layer.texture, 0, 0),+ copy_at(&before, 0, 0),+ extent(self.width, self.height),+ );+ let view = before.create_view(&wgpu::TextureViewDescriptor::default());+ let masked = self.selection.is_some();+ let chosen = self.selection.as_ref().map_or(&self.everything, |s| &s.view);+ let bind = device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("transform source"),+ layout: &self.pipelines.transform_layout,+ entries: &[+ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&view) },+ wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&self.sampler) },+ wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(chosen) },+ ],+ });+ let before_bind = device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("adjustment copy"),+ layout: &self.pipelines.before_layout,+ entries: &[+ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&view) },+ wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&self.table_view) },+ ],+ });+ Some(Transforming { layer: id, before, bind, masked, before_bind })+ }++ /// The edit's copy and `second` bound as an adjustment's last-pass group.+ fn copy_bind_with(&self, device: &wgpu::Device, second: &wgpu::TextureView) -> wgpu::BindGroup {+ let fallback;+ let copy = match &self.transforming {+ Some(t) => {+ fallback = t.before.create_view(&wgpu::TextureViewDescriptor::default());+ &fallback+ }+ None => &self.everything,+ };+ device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("adjustment copy"),+ layout: &self.pipelines.before_layout,+ entries: &[+ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(copy) },+ wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(second) },+ ],+ })+ }++ /// Redraws the layer being edited (begun with [`Self::begin_transform`]) from its copy through+ /// `filter`; [`Self::end_transform`] keeps it or puts the layer back.+ pub fn set_filter(&mut self, filter: Filter) {+ self.replace_placement(Op::FilterSet(filter));+ }++ /// Queues a redraw of the layer being transformed; only the latest needs drawing.+ fn replace_placement(&mut self, op: Op) {+ if let Some(Op::TransformSet { .. } | Op::TransformMesh { .. } | Op::FilterSet(_)) = self.ops.last() {+ self.ops.pop();+ }+ self.ops.push(op);+ }++ /// Ends the transform: `commit` keeps it as one undo step, otherwise the layer is put back.+ pub fn end_transform(&mut self, commit: bool) {+ self.ops.push(Op::TransformEnd { commit });+ }++ /// Whether a transform is open, counting queued work.+ pub fn is_transforming(&self) -> bool {+ let mut open = self.transforming.is_some();+ for op in &self.ops {+ match op {+ Op::TransformBegin(_) => open = true,+ Op::TransformEnd { .. } => open = false,+ _ => {}+ }+ }+ open+ }++ /// Creates textures for layers that have none yet: the document's and those queued work+ /// refers to (a layer can be added, painted and merged away before a frame is drawn).+ fn sync_layers(&mut self, gpu: &Gpu, doc: &Document) {+ let mut ids: Vec<LayerId> = doc.pixel_layer_ids().collect();+ for op in &self.ops {+ match op {+ Op::Record(d)+ | Op::Duplicate { before: d, .. }+ | Op::MergeDown { before: d, .. }+ | Op::MergeMany { before: d, .. }+ | Op::Flatten { before: d, .. } => ids.extend(d.pixel_layer_ids()),+ Op::Commit(s) => ids.push(s.layer),+ Op::Clear(id) | Op::Wipe(id) | Op::TransformBegin(id) | Op::TransformAlso(id) => ids.push(*id),+ Op::Write { layers, .. } => ids.extend(layers.iter().map(|(id, _)| *id)),+ Op::Put(id, _) | Op::Hold(id) => ids.push(*id),+ Op::Release { before: Some(d), .. } => ids.extend(d.pixel_layer_ids()),+ _ => {}+ }+ if let Op::Duplicate { pairs, .. } = op {+ ids.extend(pairs.iter().flat_map(|(from, to)| [*from, *to]));+ }+ if let Op::MergeDown { upper, lower, .. } = op {+ ids.extend([*upper, *lower]);+ }+ if let Op::MergeMany { uppers, lower, .. } = op {+ ids.extend(uppers.iter().copied().chain([*lower]));+ }+ if let Op::Flatten { into, .. } = op {+ ids.push(*into);+ }+ }+ if let Some(s) = self.active {+ ids.push(s.layer);+ }+ let mut added = false;+ for id in ids {+ if self.layers.contains_key(&id) {+ continue;+ }+ let texture = texture(&gpu.device, "layer", self.width, self.height, LAYER_FORMAT);+ let view = texture.create_view(&wgpu::TextureViewDescriptor::default());+ // new textures are zeroed: transparent+ self.layers.insert(id, LayerGpu { texture, view });+ added = true;+ }+ if added {+ self.invalidate();+ }+ }++ /// Drops the textures of layers that neither the document nor the history refers to.+ fn collect_layers(&mut self, doc: &Document) {+ let mut keep: HashSet<LayerId> = doc.layer_ids().collect();+ for step in self.undo.iter().chain(self.redo.iter()) {+ if let Some(d) = &step.doc {+ keep.extend(d.layer_ids());+ }+ keep.extend(step.pixels.iter().map(|s| s.layer));+ }+ for op in &self.ops {+ if let Op::Record(d)+ | Op::Duplicate { before: d, .. }+ | Op::MergeDown { before: d, .. }+ | Op::MergeMany { before: d, .. }+ | Op::Flatten { before: d, .. }+ | Op::Release { before: Some(d), .. }+ | Op::Write { before: Some(d), .. } = op+ {+ keep.extend(d.layer_ids());+ }+ }+ self.layers.retain(|id, _| keep.contains(id));+ }++ /// Records and submits everything queued, recomposites what changed and draws to `target`.+ /// Undoing a structural step puts the earlier document into `doc`.+ pub fn render(&mut self, gpu: &Gpu, doc: &mut Document, target: Option<Target<'_>>) {+ self.sync_layers(gpu, doc);+ let device = &gpu.device;+ let flattening = self.ops.iter().filter_map(|op| match op {+ Op::Flatten { before, .. } => Some(before.max_depth()),+ _ => None,+ });+ let depth = flattening.max().unwrap_or(0);+ self.make_groups(device, depth);+ let ops = std::mem::take(&mut self.ops);++ // this frame's stamps in one upload+ let mut instances: Vec<StampInstance> = Vec::new();+ for op in &ops {+ if let Op::Stamps { instances: i, .. } = op {+ instances.extend_from_slice(i);+ }+ }+ // the predicted tail goes last, drawn with the canvas+ let predicted_first = u32::try_from(instances.len()).unwrap_or(u32::MAX);+ if target.is_some() {+ instances.extend_from_slice(&self.prediction);+ }+ let predicted = predicted_first..u32::try_from(instances.len()).unwrap_or(u32::MAX);+ let needed = instances.len() as u64;+ if needed > self.stamp_capacity {+ self.stamp_capacity = needed.next_power_of_two();+ self.stamp_buffer = stamp_buffer(device, self.stamp_capacity);+ }+ if !instances.is_empty() {+ gpu.queue.write_buffer(&self.stamp_buffer, 0, bytemuck::cast_slice(&instances));+ }++ // the display takes four slots, and frosted panels three and one for each+ let frosted = target.as_ref().and_then(|t| t.backdrop).map_or(0, |b| b.regions.len() + 3);+ let slots = (ops.len() + doc.layers().len() + 4 + frosted) as u64;+ if slots > self.uniform_slots {+ self.uniform_slots = slots.next_power_of_two();+ let (buffer, bind) = uniforms(device, &self.pipelines.uniform_layout, self.uniform_slots);+ self.uniform_buffer = buffer;+ self.uniform_bind = bind;+ }+ let smudge_count: u64 = ops+ .iter()+ .map(|op| match op {+ Op::Stamps { instances, style, .. } if style.in_place() => instances.len() as u64,+ _ => 0,+ })+ .sum();+ if smudge_count > self.smudge_capacity {+ self.smudge_capacity = smudge_count.next_power_of_two();+ self.smudge_params = smudge_params(device, self.smudge_capacity);+ }+ let mut uniforms = UniformData::default();+ let mut smudge_uniforms = UniformData::default();+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("canvas") });++ let mut next_instance = 0u32;+ let mut history_changed = false;+ for op in ops {+ match op {+ Op::Stamps { instances, style, layer, clear, .. } if style.in_place() => {+ next_instance = next_instance.saturating_add(u32::try_from(instances.len()).unwrap_or(u32::MAX));+ self.smudge_stamps(device, &mut encoder, &mut smudge_uniforms, &instances, &style, layer, clear);+ }+ Op::Stamps { instances, style, clear, pencil, .. } => {+ let count = u32::try_from(instances.len()).unwrap_or(u32::MAX);+ let first = next_instance;+ next_instance = next_instance.saturating_add(count);+ let (grain, grain_scale, grain_depth) =+ style.moving_grain().map_or((-1, 1.0, 0.0), |(g, s, d)| (g as i32, s, d));+ let offset = uniforms.push(&StampUniform {+ canvas_size: [self.width as f32, self.height as f32],+ hardness: style.hardness.clamp(0.0, 1.0),+ shape: style.shape.map_or(-1, |s| s as i32),+ color: [style.color[0], style.color[1], style.color[2], 1.0],+ grain,+ grain_scale,+ grain_depth,+ grain_brightness: style.grain_brightness,+ grain_contrast: style.grain_contrast,+ grain_rotation: style.grain_rotation,+ grain_blend: style.grain_blend,+ grain_sharp: u32::from(style.grain_sharp),+ shape_sharp: u32::from(style.shape_sharp),+ _pad: [0; 3],+ secondary: [style.secondary[0], style.secondary[1], style.secondary[2], 1.0],+ });+ let load = if clear { wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT) } else { wgpu::LoadOp::Load };+ let target = match (&self.pencil, pencil) {+ (Some(mask), true) => &mask.view,+ _ => &self.stroke_view,+ };+ let mut pass = render_pass(&mut encoder, "stamps", target, load);+ if count > 0 {+ pass.set_pipeline(match style.rendering {+ Rendering::BuildUp | Rendering::Gradual => &self.pipelines.stamp,+ Rendering::Strongest => &self.pipelines.stamp_max,+ Rendering::Capped => self.pipelines.stamp_capped.as_ref().unwrap_or(&self.pipelines.stamp),+ });+ pass.set_bind_group(0, &self.uniform_bind, &[offset]);+ pass.set_bind_group(1, &self.brush_bind, &[]);+ let start = u64::from(first) * size_of::<StampInstance>() as u64;+ let end = u64::from(next_instance) * size_of::<StampInstance>() as u64;+ pass.set_vertex_buffer(0, self.stamp_buffer.slice(start..end));+ pass.draw(0..6, 0..count);+ }+ }+ Op::Commit(stroke) if stroke.style.in_place() => {+ self.finish_smudge(device, &mut encoder, stroke.bounds, false);+ history_changed = true;+ }+ // painting an adjustment on leaves the layer to the adjustment+ Op::Commit(stroke) if stroke.pencil => {+ if let Some(mask) = self.pencil.as_mut() {+ mask.bounds = mask.bounds.union(stroke.bounds);+ }+ }+ Op::Commit(stroke) => {+ self.commit(device, &mut encoder, &mut uniforms, stroke);+ history_changed = true;+ }+ Op::Cancel if self.smudge.is_some() => {+ self.finish_smudge(device, &mut encoder, IRect::EMPTY, true);+ }+ Op::Cancel => {+ drop(render_pass(+ &mut encoder,+ "cancel",+ &self.stroke_view,+ wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),+ ));+ }+ Op::Undo => {+ if let Some(step) = self.undo.pop() {+ let inverse = self.apply_step(gpu, &mut encoder, doc, step);+ self.redo.push(inverse);+ history_changed = true;+ }+ }+ Op::Redo => {+ if let Some(step) = self.redo.pop() {+ let inverse = self.apply_step(gpu, &mut encoder, doc, step);+ self.undo.push(inverse);+ history_changed = true;+ }+ }+ Op::Mark => self.mark = Some(self.steps_made),+ Op::Name(name) => self.next_name = Some(name),+ Op::Collapse => {+ let since = self.mark.take().unwrap_or(u64::MAX);+ let first = self.undo.iter().position(|s| s.made > since).unwrap_or(self.undo.len());+ if self.undo.len() - first >= 2 {+ let steps = self.undo.split_off(first);+ self.undo.push(collapsed(steps));+ history_changed = true;+ }+ }+ Op::Clear(id) => {+ let full = self.full();+ if let Some(snapshot) = self.snapshot(device, &mut encoder, id, full) {+ self.push_step(Step {+ made: 0,+ name: None,+ doc: None,+ pixels: vec![snapshot],+ selection: None,+ });+ }+ if let Some(layer) = self.layers.get(&id) {+ drop(render_pass(+ &mut encoder,+ "clear",+ &layer.view,+ wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),+ ));+ }+ self.dirty = full;+ history_changed = true;+ }+ Op::Put(id, pixels) => {+ if let Some(layer) = self.layers.get(&id) {+ let staging = texture(device, "layer put", self.width, self.height, LAYER_FORMAT);+ gpu.queue.write_texture(+ copy_at(&staging, 0, 0),+ &pixels,+ wgpu::TexelCopyBufferLayout {+ offset: 0,+ bytes_per_row: Some(self.width * 4),+ rows_per_image: Some(self.height),+ },+ extent(self.width, self.height),+ );+ encoder.copy_texture_to_texture(+ copy_at(&staging, 0, 0),+ copy_at(&layer.texture, 0, 0),+ extent(self.width, self.height),+ );+ }+ self.dirty = self.full();+ }+ Op::Hold(id) => {+ let full = self.full();+ self.held = self.snapshot(device, &mut encoder, id, full);+ }+ Op::Release { keep, before } => {+ let held = self.held.take();+ if keep {+ if held.is_some() || before.is_some() {+ self.push_step(Step {+ made: 0,+ name: None,+ doc: before,+ pixels: held.into_iter().collect(),+ selection: None,+ });+ history_changed = true;+ }+ } else if let Some(s) = held+ && let Some(layer) = self.layers.get(&s.layer)+ {+ encoder.copy_texture_to_texture(+ copy_at(&s.texture, 0, 0),+ copy_at(&layer.texture, s.rect.x0, s.rect.y0),+ extent(s.rect.width(), s.rect.height()),+ );+ }+ self.dirty = self.full();+ }+ Op::Write { layers, before } => {+ let full = self.full();+ let snapshots: Vec<Snapshot> =+ layers.iter().filter_map(|(id, _)| self.snapshot(device, &mut encoder, *id, full)).collect();+ if !snapshots.is_empty() || before.is_some() {+ self.push_step(Step { made: 0, name: None, doc: before, pixels: snapshots, selection: None });+ }+ for (id, pixels) in layers {+ let Some(layer) = self.layers.get(&id) else { continue };+ // through a staging texture, so the snapshot above is taken first+ let staging = texture(device, "layer write", self.width, self.height, LAYER_FORMAT);+ gpu.queue.write_texture(+ copy_at(&staging, 0, 0),+ &pixels,+ wgpu::TexelCopyBufferLayout {+ offset: 0,+ bytes_per_row: Some(self.width * 4),+ rows_per_image: Some(self.height),+ },+ extent(self.width, self.height),+ );+ encoder.copy_texture_to_texture(+ copy_at(&staging, 0, 0),+ copy_at(&layer.texture, 0, 0),+ extent(self.width, self.height),+ );+ }+ self.dirty = full;+ history_changed = true;+ }+ Op::TransformBegin(id) => {+ self.transform_more.clear();+ if let Some(t) = self.copy_aside(device, &mut encoder, id) {+ self.transforming = Some(t);+ }+ }+ Op::TransformAlso(id) => {+ if let Some(t) = self.copy_aside(device, &mut encoder, id) {+ self.transform_more.push(t);+ }+ }+ Op::TransformSet { to_source: m, resample } => {+ let mut drew = false;+ for t in self.transforming.iter().chain(&self.transform_more) {+ let Some(layer) = self.layers.get(&t.layer) else { continue };+ let filter = match resample {+ Resample::Nearest => 0.0,+ Resample::Bilinear => 1.0,+ Resample::Bicubic => 2.0,+ };+ let [a, b, c, d, e, f, g, h, i] = m;+ let offset = uniforms.push(&TransformUniform {+ r0: [a, b, c, 0.0],+ r1: [d, e, f, 0.0],+ r2: [g, h, i, 0.0],+ p: [filter, self.width as f32, self.height as f32, if t.masked { 1.0 } else { 0.0 }],+ });+ let mut pass = render_pass(+ &mut encoder,+ "transform",+ &layer.view,+ wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),+ );+ if t.masked {+ pass.set_pipeline(&self.pipelines.transform_static);+ pass.set_bind_group(0, &t.bind, &[]);+ pass.set_bind_group(1, &self.uniform_bind, &[offset]);+ pass.draw(0..3, 0..1);+ }+ pass.set_pipeline(&self.pipelines.transform);+ pass.set_bind_group(0, &t.bind, &[]);+ pass.set_bind_group(1, &self.uniform_bind, &[offset]);+ pass.draw(0..3, 0..1);+ drop(pass);+ drew = true;+ }+ if drew {+ self.dirty = self.full();+ }+ }+ Op::TransformMesh { vertices, resample } => {+ let filter = match resample {+ Resample::Nearest => 0.0,+ Resample::Bilinear => 1.0,+ Resample::Bicubic => 2.0,+ };+ let bytes: &[u8] = bytemuck::cast_slice(&vertices);+ let count = u32::try_from(vertices.len()).unwrap_or(0);+ let buffer = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("warp mesh"),+ size: (bytes.len() as u64).max(16),+ usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });+ // written before this frame's commands run+ gpu.queue.write_buffer(&buffer, 0, bytes);+ let mut drew = false;+ for t in self.transforming.iter().chain(&self.transform_more) {+ let Some(layer) = self.layers.get(&t.layer) else { continue };+ let offset = uniforms.push(&TransformUniform {+ r0: [0.0; 4],+ r1: [0.0; 4],+ r2: [0.0; 4],+ p: [filter, self.width as f32, self.height as f32, if t.masked { 1.0 } else { 0.0 }],+ });+ let mut pass = render_pass(+ &mut encoder,+ "warp",+ &layer.view,+ wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),+ );+ if t.masked {+ pass.set_pipeline(&self.pipelines.transform_static);+ pass.set_bind_group(0, &t.bind, &[]);+ pass.set_bind_group(1, &self.uniform_bind, &[offset]);+ pass.draw(0..3, 0..1);+ }+ if count > 0 {+ pass.set_pipeline(&self.pipelines.mesh);+ pass.set_bind_group(0, &t.bind, &[]);+ pass.set_bind_group(1, &self.uniform_bind, &[offset]);+ pass.set_vertex_buffer(0, buffer.slice(..));+ pass.draw(0..count, 0..1);+ }+ drop(pass);+ drew = true;+ }+ if drew {+ self.dirty = self.full();+ }+ }+ Op::FilterSet(filter) => {+ self.filter(gpu, &mut encoder, &mut uniforms, filter);+ }+ Op::LiquifyBegin => {+ let field = texture(device, "liquify field", self.width, self.height, LIQUIFY_FORMAT);+ let view = field.create_view(&wgpu::TextureViewDescriptor::default());+ drop(render_pass(+ &mut encoder,+ "liquify clear",+ &view,+ wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),+ ));+ self.liquify = Some(LiquifyField { bind: self.copy_bind_with(device, &view), view });+ }+ Op::PencilBegin => {+ let mask = texture(device, "pencil mask", self.width, self.height, STROKE_FORMAT);+ let view = mask.create_view(&wgpu::TextureViewDescriptor::default());+ drop(render_pass(+ &mut encoder,+ "pencil clear",+ &view,+ wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),+ ));+ self.pencil = Some(PencilMask { view, bounds: IRect::EMPTY });+ // the edit's source now takes the mask where it took the selection+ let source = self+ .transforming+ .as_ref()+ .map(|t| t.before.create_view(&wgpu::TextureViewDescriptor::default()));+ if let Some(view) = source {+ let bind = self.adjustment_bind(device, &view, true);+ if let Some(t) = self.transforming.as_mut() {+ t.bind = bind;+ t.masked = true;+ }+ }+ }+ Op::LiquifyStamps(stamps) => {+ if let Some(field) = &self.liquify {+ let (w, h) = (self.width as f32, self.height as f32);+ let mut pass = render_pass(&mut encoder, "liquify", &field.view, wgpu::LoadOp::Load);+ for st in stamps {+ let mode = st.mode as u32 as f32;+ let offset = uniforms.push(&LiquifyUniform {+ stamp: [st.centre[0], st.centre[1], st.radius.max(1.0), st.pressure],+ move_mode: [st.moved[0], st.moved[1], mode, st.seed],+ canvas: [w, h, st.distortion, 0.0],+ pad: [0.0; 4],+ });+ let pipeline = if st.mode == LiquifyMode::Reconstruct {+ &self.pipelines.liquify_fade+ } else {+ &self.pipelines.liquify_add+ };+ pass.set_pipeline(pipeline);+ pass.set_bind_group(0, &self.uniform_bind, &[offset]);+ pass.draw(0..6, 0..1);+ }+ }+ }+ Op::LiquifyClear => {+ if let Some(field) = &self.liquify {+ drop(render_pass(+ &mut encoder,+ "liquify clear",+ &field.view,+ wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),+ ));+ }+ }+ Op::TransformEnd { commit } => {+ self.liquify = None;+ let painted = self.pencil.take().map(|p| p.bounds.intersect(self.full()));+ let more = std::mem::take(&mut self.transform_more);+ if let Some(t) = self.transforming.take() {+ if commit && let Some(rect) = painted {+ // painted on: only where it was painted changed, and nothing if nowhere+ if !rect.is_empty() {+ let texture = region_copy(device, &mut encoder, &t.before, rect);+ self.push_step(Step {+ made: 0,+ name: None,+ doc: None,+ pixels: vec![Snapshot { layer: t.layer, rect, texture }],+ selection: None,+ });+ history_changed = true;+ }+ } else if commit {+ let full = self.full();+ let pixels = std::iter::once(t)+ .chain(more)+ .map(|t| Snapshot { layer: t.layer, rect: full, texture: t.before })+ .collect();+ self.push_step(Step { made: 0, name: None, doc: None, pixels, selection: None });+ history_changed = true;+ } else {+ for t in std::iter::once(t).chain(more) {+ if let Some(layer) = self.layers.get(&t.layer) {+ encoder.copy_texture_to_texture(+ copy_at(&t.before, 0, 0),+ copy_at(&layer.texture, 0, 0),+ extent(self.width, self.height),+ );+ }+ }+ }+ self.dirty = self.full();+ }+ }+ Op::Wipe(id) => {+ if let Some(layer) = self.layers.get(&id) {+ drop(render_pass(+ &mut encoder,+ "wipe",+ &layer.view,+ wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),+ ));+ }+ self.dirty = self.full();+ }+ Op::Record(before) => {+ self.push_step(Step {+ made: 0,+ name: None,+ doc: Some(before),+ pixels: Vec::new(),+ selection: None,+ });+ self.dirty = self.full();+ history_changed = true;+ }+ Op::Duplicate { pairs, before } => {+ for (from, to) in pairs {+ if let (Some(src), Some(dst)) = (self.layers.get(&from), self.layers.get(&to)) {+ encoder.copy_texture_to_texture(+ copy_at(&src.texture, 0, 0),+ copy_at(&dst.texture, 0, 0),+ extent(self.width, self.height),+ );+ }+ }+ self.push_step(Step {+ made: 0,+ name: None,+ doc: Some(before),+ pixels: Vec::new(),+ selection: None,+ });+ self.dirty = self.full();+ history_changed = true;+ }+ Op::MergeDown { upper, lower, before } => {+ let pixels =+ self.merge(device, &mut encoder, &mut uniforms, &before, upper, lower).into_iter().collect();+ self.push_step(Step { made: 0, name: None, doc: Some(before), pixels, selection: None });+ self.dirty = self.full();+ history_changed = true;+ }+ Op::MergeMany { uppers, lower, before } => {+ let full = self.full();+ let snapshot = self.snapshot(device, &mut encoder, lower, full);+ for upper in uppers {+ if before.layer(upper).is_some_and(|l| l.kind == LayerKind::Group) {+ self.draw_group_onto(device, &mut encoder, &mut uniforms, &before, upper, lower);+ } else {+ self.blend_layer_into(device, &mut encoder, &mut uniforms, &before, upper, lower);+ }+ }+ let pixels = snapshot.into_iter().collect();+ self.push_step(Step { made: 0, name: None, doc: Some(before), pixels, selection: None });+ self.dirty = self.full();+ history_changed = true;+ }+ Op::Flatten { group, into, onto, before } => {+ let pixels = self+ .flatten(device, &mut encoder, &mut uniforms, &before, group, into, onto)+ .into_iter()+ .collect();+ self.push_step(Step { made: 0, name: None, doc: Some(before), pixels, selection: None });+ self.dirty = self.full();+ history_changed = true;+ }+ }+ }+ if history_changed {+ self.collect_layers(doc);+ }++ let dirty = self.dirty.intersect(self.full());+ self.make_groups(device, doc.max_depth());+ if !dirty.is_empty() {+ self.composite(device, doc, &mut encoder, &mut uniforms, dirty);+ }+ self.dirty = IRect::EMPTY;++ if let Some(target) = target {+ self.display(device, &mut encoder, &mut uniforms, &target, predicted);+ if let Some(backdrop) = target.backdrop.filter(|b| !b.regions.is_empty() && b.sigma > 0.0) {+ self.frost(device, &mut encoder, &mut uniforms, &target, backdrop);+ }+ }+ if !uniforms.data.is_empty() {+ gpu.queue.write_buffer(&self.uniform_buffer, 0, &uniforms.data);+ }+ if !smudge_uniforms.data.is_empty() {+ gpu.queue.write_buffer(&self.smudge_params, 0, &smudge_uniforms.data);+ }+ gpu.queue.submit([encoder.finish()]);+ }++ /// Bytes per row of a layer copied into a buffer (rows are 256-byte aligned for copies).+ fn row_bytes(&self) -> u32 {+ (self.width * 4).div_ceil(256) * 256+ }++ /// Smudges `instances` into the stroke's layer: per stamp, the brush picks up colour and lays+ /// down what it carries; then the changed pixels go back into the layer texture.+ fn smudge_stamps(+ &mut self,+ device: &wgpu::Device,+ encoder: &mut wgpu::CommandEncoder,+ params: &mut UniformData,+ instances: &[StampInstance],+ style: &StrokeStyle,+ target: LayerId,+ restart: bool,+ ) {+ let row = self.row_bytes();+ // redrawn from scratch: the stroke starts again on the layer as it was before it+ if restart+ && let (Some(smudge), Some(layer)) =+ (self.smudge.as_mut().filter(|s| s.layer == target), self.layers.get(&target))+ {+ encoder.copy_texture_to_texture(+ copy_at(&smudge.before, 0, 0),+ copy_at(&layer.texture, 0, 0),+ extent(self.width, self.height),+ );+ encoder.copy_texture_to_buffer(+ copy_at(&smudge.before, 0, 0),+ wgpu::TexelCopyBufferInfo {+ buffer: &smudge.work,+ layout: wgpu::TexelCopyBufferLayout {+ offset: 0,+ bytes_per_row: Some(row),+ rows_per_image: Some(self.height),+ },+ },+ extent(self.width, self.height),+ );+ smudge.started = false;+ smudge.stamps = 0;+ smudge.length = 0.0;+ smudge.last = None;+ if let Some(raw) = &smudge.raw {+ encoder.copy_texture_to_buffer(+ copy_at(&smudge.before, 0, 0),+ wgpu::TexelCopyBufferInfo {+ buffer: raw,+ layout: wgpu::TexelCopyBufferLayout {+ offset: 0,+ bytes_per_row: Some(row),+ rows_per_image: Some(self.height),+ },+ },+ extent(self.width, self.height),+ );+ }+ self.dirty = self.full();+ }+ if self.smudge.as_ref().is_none_or(|s| s.layer != target) {+ let Some(layer) = self.layers.get(&target) else { return };+ let work = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("smudge layer"),+ size: u64::from(row) * u64::from(self.height),+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });+ let carry = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("smudge carry"),+ size: u64::from(SMUDGE_GRID * SMUDGE_GRID) * 16,+ usage: wgpu::BufferUsages::STORAGE,+ mapped_at_creation: false,+ });+ let before = texture(device, "smudge before", self.width, self.height, LAYER_FORMAT);+ encoder.copy_texture_to_texture(+ copy_at(&layer.texture, 0, 0),+ copy_at(&before, 0, 0),+ extent(self.width, self.height),+ );+ encoder.copy_texture_to_buffer(+ copy_at(&layer.texture, 0, 0),+ wgpu::TexelCopyBufferInfo {+ buffer: &work,+ layout: wgpu::TexelCopyBufferLayout {+ offset: 0,+ bytes_per_row: Some(row),+ rows_per_image: Some(self.height),+ },+ },+ extent(self.width, self.height),+ );+ // wet paint with a texturized grain keeps the stroke without it, and the layer as it was+ let (raw, orig) = if grain_once(style) {+ let mut copy = |label| {+ let buffer = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some(label),+ size: u64::from(row) * u64::from(self.height),+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });+ encoder.copy_texture_to_buffer(+ copy_at(&layer.texture, 0, 0),+ wgpu::TexelCopyBufferInfo {+ buffer: &buffer,+ layout: wgpu::TexelCopyBufferLayout {+ offset: 0,+ bytes_per_row: Some(row),+ rows_per_image: Some(self.height),+ },+ },+ extent(self.width, self.height),+ );+ buffer+ };+ (Some(copy("smudge raw")), Some(copy("smudge orig")))+ } else {+ (None, None)+ };+ self.smudge = Some(Smudge {+ layer: target,+ work,+ carry,+ before,+ started: false,+ stamps: 0,+ length: 0.0,+ last: None,+ raw,+ orig,+ });+ }+ let Some(smudge) = self.smudge.as_mut() else { return };+ let bind = device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("smudge"),+ layout: &self.pipelines.smudge_layout,+ entries: &[+ wgpu::BindGroupEntry {+ binding: 0,+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {+ buffer: &self.smudge_params,+ offset: 0,+ size: NonZeroU64::new(SMUDGE_UNIFORM_SIZE),+ }),+ },+ wgpu::BindGroupEntry { binding: 1, resource: smudge.work.as_entire_binding() },+ wgpu::BindGroupEntry { binding: 2, resource: smudge.carry.as_entire_binding() },+ wgpu::BindGroupEntry {+ binding: 3,+ resource: smudge.raw.as_ref().unwrap_or(&self.smudge_spare[0]).as_entire_binding(),+ },+ wgpu::BindGroupEntry {+ binding: 4,+ resource: smudge.orig.as_ref().unwrap_or(&self.smudge_spare[1]).as_entire_binding(),+ },+ ],+ });+ let full = IRect::from_size(self.width, self.height);+ let mut changed = IRect::EMPTY;+ let mut pass =+ encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("smudge"), timestamp_writes: None });+ pass.set_bind_group(1, &self.brush_bind, &[]);+ for s in instances {+ let center = procraft_engine::geom::Vec2::new(s.center[0], s.center[1]);+ let bbox = IRect::around(center, s.radius * std::f32::consts::SQRT_2).intersect(full);+ if bbox.is_empty() || s.radius <= 0.0 {+ continue;+ }+ changed = changed.union(bbox);+ let wet = style.wet_pull.is_some() && style.tool == StrokeTool::Paint;+ // the paint runs out with the length the stroke has gone+ if let Some([x, y]) = smudge.last {+ smudge.length += (s.center[0] - x).hypot(s.center[1] - y);+ }+ smudge.last = Some(s.center);+ // the mixture varies from stamp to stamp by the wetness jitter+ let jitter = 1.0 - style.wet_jitter * unit_hash(smudge.stamps);+ smudge.stamps = smudge.stamps.saturating_add(1);+ let (mixture, final_mixture, wet_pull) =+ if wet { wet_mixture(style, smudge.length, jitter) } else { (0.0, 1.0, style.pull.clamp(0.0, 1.0)) };+ let moving = style.grain_mode == GrainMode::Moving;+ let offset = params.push(&SmudgeUniform {+ center: s.center,+ radius: s.radius.max(0.5),+ angle: s.angle,+ roundness: s.roundness,+ alpha: (s.alpha * style.opacity).clamp(0.0, 1.0),+ pull: wet_pull,+ hardness: style.hardness.clamp(0.0, 1.0),+ shape: style.shape.map_or(-1, |s| s as i32),+ first: u32::from(!smudge.started),+ preserve_alpha: u32::from(style.preserve_alpha),+ stride: row / 4,+ bbox: [bbox.x0, bbox.y0, bbox.x1, bbox.y1],+ size: [self.width, self.height],+ grid: SMUDGE_GRID,+ uniform_glaze: u32::from(style.rendering == Rendering::Strongest),+ paint: [style.color[0], style.color[1], style.color[2], 1.0],+ mode: u32::from(wet),+ mixture,+ final_mixture,+ grade: style.grade,+ blur: style.blur * (1.0 - style.blur_jitter * unit_hash(smudge.stamps.wrapping_add(7919))),+ grain: style.grain.map_or(-1, |g| g as i32),+ // a moving grain sized and as deep as this stamp says+ grain_scale: if moving { -style.grain_scale * s.look[1].max(0.05) } else { style.grain_scale },+ grain_depth: if moving { (style.grain_depth * s.look[0]).clamp(0.0, 1.0) } else { style.grain_depth },+ grain_offset: s.grain_offset,+ grain_rotation: style.grain_rotation,+ grain_sharp: if style.grain_sharp { 1.0 } else { 0.0 },+ shape_sharp: if style.shape_sharp { 1.0 } else { 0.0 },+ grain_press: s.more[0],+ grain_bleed: s.more[1],+ grain_once: if smudge.raw.is_some() { 1.0 } else { 0.0 },+ _pad: [0.0; 4],+ });+ smudge.started = true;+ pass.set_bind_group(0, &bind, &[offset]);+ pass.set_pipeline(&self.pipelines.smudge_carry);+ pass.dispatch_workgroups(SMUDGE_GRID.div_ceil(8), SMUDGE_GRID.div_ceil(8), 1);+ pass.set_pipeline(&self.pipelines.smudge_deposit);+ pass.dispatch_workgroups(bbox.width().div_ceil(8), bbox.height().div_ceil(8), 1);+ }+ drop(pass);+ if changed.is_empty() {+ return;+ }+ if let Some(layer) = self.layers.get(&smudge.layer) {+ let offset =+ u64::from(row) * u64::try_from(changed.y0).unwrap_or(0) + 4 * u64::try_from(changed.x0).unwrap_or(0);+ encoder.copy_buffer_to_texture(+ wgpu::TexelCopyBufferInfo {+ buffer: &smudge.work,+ layout: wgpu::TexelCopyBufferLayout {+ offset,+ bytes_per_row: Some(row),+ rows_per_image: Some(changed.height()),+ },+ },+ copy_at(&layer.texture, changed.x0, changed.y0),+ extent(changed.width(), changed.height()),+ );+ }+ self.dirty = self.dirty.union(changed);+ }++ /// Ends a smudge stroke: one undo step with the pixels it changed, or (`cancel`) puts the+ /// layer back as it was.+ fn finish_smudge(+ &mut self,+ device: &wgpu::Device,+ encoder: &mut wgpu::CommandEncoder,+ bounds: IRect,+ cancel: bool,+ ) {+ let Some(smudge) = self.smudge.take() else { return };+ let Some(layer) = self.layers.get(&smudge.layer) else { return };+ if cancel {+ encoder.copy_texture_to_texture(+ copy_at(&smudge.before, 0, 0),+ copy_at(&layer.texture, 0, 0),+ extent(self.width, self.height),+ );+ self.dirty = self.full();+ return;+ }+ let rect = bounds.intersect(self.full());+ if rect.is_empty() {+ return;+ }+ let texture = device.create_texture(&wgpu::TextureDescriptor {+ label: Some("undo"),+ size: extent(rect.width(), rect.height()),+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: LAYER_FORMAT,+ usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST,+ view_formats: &[],+ });+ encoder.copy_texture_to_texture(+ copy_at(&smudge.before, rect.x0, rect.y0),+ copy_at(&texture, 0, 0),+ extent(rect.width(), rect.height()),+ );+ self.push_step(Step {+ made: 0,+ name: None,+ doc: None,+ pixels: vec![Snapshot { layer: smudge.layer, rect, texture }],+ selection: None,+ });+ }++ fn commit(+ &mut self,+ device: &wgpu::Device,+ encoder: &mut wgpu::CommandEncoder,+ uniforms: &mut UniformData,+ stroke: ActiveStroke,+ ) {+ let rect = stroke.bounds.intersect(self.full());+ if !rect.is_empty() && self.layers.contains_key(&stroke.layer) {+ if let Some(snapshot) = self.snapshot(device, encoder, stroke.layer, rect) {+ self.push_step(Step { made: 0, name: None, doc: None, pixels: vec![snapshot], selection: None });+ }+ let opacity = stroke.style.opacity.clamp(0.0, 1.0);+ let locked = stroke.style.preserve_alpha;+ let burns = stroke.style.burnt_edges > 0.0 && !stroke.style.preview;+ match (stroke.style.tool, locked || stroke.style.blend != 0 || burns) {+ (StrokeTool::Paint, true) => {+ // recolour where the layer has alpha, or blend by a mode or burn edges (which+ // read the layer): into scratch, then back+ let offset = uniforms.push(+ &LayerUniform {+ opacity: 1.0,+ stroke_mode: if locked { STROKE_PAINT_LOCKED } else { STROKE_PAINT },+ stroke_opacity: opacity,+ ..Default::default()+ }+ .with_grain(Some(&stroke.style)),+ );+ if let Some(layer) = self.layers.get(&stroke.layer) {+ let bind =+ self.quad(device, [&layer.view, &self.stroke_view, &self.stroke_view, &self.stroke_view]);+ let mut pass = render_pass(encoder, "commit locked", &self.scratch_view, wgpu::LoadOp::Load);+ pass.set_pipeline(&self.pipelines.commit_locked);+ scissor(&mut pass, rect);+ pass.set_bind_group(0, &bind, &[]);+ pass.set_bind_group(1, &self.uniform_bind, &[offset]);+ pass.draw(0..3, 0..1);+ drop(pass);+ encoder.copy_texture_to_texture(+ copy_at(&self.scratch, rect.x0, rect.y0),+ copy_at(&layer.texture, rect.x0, rect.y0),+ extent(rect.width(), rect.height()),+ );+ }+ }+ (tool, _) => {+ let offset = uniforms.push(+ &LayerUniform { opacity: 1.0, stroke_opacity: opacity, ..Default::default() }+ .with_grain(Some(&stroke.style)),+ );+ if let Some(layer) = self.layers.get(&stroke.layer) {+ let mut pass = render_pass(encoder, "commit", &layer.view, wgpu::LoadOp::Load);+ pass.set_pipeline(match tool {+ StrokeTool::Paint | StrokeTool::Smudge => &self.pipelines.commit_paint,+ StrokeTool::Erase => &self.pipelines.commit_erase,+ });+ scissor(&mut pass, rect);+ pass.set_bind_group(0, &self.stroke_bind, &[]);+ pass.set_bind_group(1, &self.uniform_bind, &[offset]);+ pass.draw(0..3, 0..1);+ }+ }+ }+ }+ drop(render_pass(encoder, "stroke clear", &self.stroke_view, wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT)));+ self.dirty = self.dirty.union(rect);+ }++ /// Blends `upper` into `lower` with its mode, opacity and clipping (as `doc` has them).+ /// Returns `lower`'s previous pixels.+ fn merge(+ &mut self,+ device: &wgpu::Device,+ encoder: &mut wgpu::CommandEncoder,+ uniforms: &mut UniformData,+ doc: &Document,+ upper: LayerId,+ lower: LayerId,+ ) -> Option<Snapshot> {+ let snapshot = self.snapshot(device, encoder, lower, self.full())?;+ self.blend_layer_into(device, encoder, uniforms, doc, upper, lower)?;+ Some(snapshot)+ }++ /// Layer `upper` of `doc` blended into layer `lower` with its opacity, mode and clipping.+ fn blend_layer_into(+ &self,+ device: &wgpu::Device,+ encoder: &mut wgpu::CommandEncoder,+ uniforms: &mut UniformData,+ doc: &Document,+ upper: LayerId,+ lower: LayerId,+ ) -> Option<()> {+ let settings = doc.layer(upper)?;+ let clip = doc.clip_base(upper).and_then(|id| self.layers.get(&id));+ let up = self.layers.get(&upper)?;+ let uniform = LayerUniform {+ opacity: if settings.visible { settings.opacity.clamp(0.0, 1.0) } else { 0.0 },+ blend: settings.blend.id(),+ clipped: u32::from(clip.is_some()),+ ..Default::default()+ };+ self.blend_down(device, encoder, uniforms, &up.view, clip.map(|c| &c.view), uniform, lower)+ }++ /// `upper` blended into layer `lower` (through `clip`, as `uniform` says), by way of the+ /// scratch texture.+ #[allow(clippy::too_many_arguments)]+ fn blend_down(+ &self,+ device: &wgpu::Device,+ encoder: &mut wgpu::CommandEncoder,+ uniforms: &mut UniformData,+ upper: &wgpu::TextureView,+ clip: Option<&wgpu::TextureView>,+ uniform: LayerUniform,+ lower: LayerId,+ ) -> Option<()> {+ let low = self.layers.get(&lower)?;+ let offset = uniforms.push(&uniform);+ let bind = self.quad(device, [upper, &self.stroke_view, clip.unwrap_or(&self.stroke_view), &low.view]);+ let mut pass = render_pass(encoder, "merge", &self.scratch_view, wgpu::LoadOp::Load);+ pass.set_pipeline(&self.pipelines.blend);+ pass.set_bind_group(0, &bind, &[]);+ pass.set_bind_group(1, &self.uniform_bind, &[offset]);+ pass.draw(0..3, 0..1);+ drop(pass);+ encoder.copy_texture_to_texture(+ copy_at(&self.scratch, 0, 0),+ copy_at(&low.texture, 0, 0),+ extent(self.width, self.height),+ );+ Some(())+ }++ /// Group `group` of `doc` composited into layer `into`: copied into it (a new layer), or+ /// (`onto`) blended into it with the group's opacity and mode, returning what it was.+ #[allow(clippy::too_many_arguments)]+ fn flatten(+ &self,+ device: &wgpu::Device,+ encoder: &mut wgpu::CommandEncoder,+ uniforms: &mut UniformData,+ doc: &Document,+ group: LayerId,+ into: LayerId,+ onto: bool,+ ) -> Option<Snapshot> {+ let full = self.full();+ if onto {+ let snapshot = self.snapshot(device, encoder, into, full)?;+ self.draw_group_onto(device, encoder, uniforms, doc, group, into)?;+ return Some(snapshot);+ }+ self.composite_group(device, doc, encoder, uniforms, full, group)?;+ let (textures, _) = self.groups.get(doc.depth(group))?;+ let target = self.layers.get(&into)?;+ encoder.copy_texture_to_texture(+ copy_at(&textures[0], 0, 0),+ copy_at(&target.texture, 0, 0),+ extent(self.width, self.height),+ );+ None+ }++ /// Group `group` of `doc` composited and blended into layer `into` with the group's opacity+ /// and mode.+ fn draw_group_onto(+ &self,+ device: &wgpu::Device,+ encoder: &mut wgpu::CommandEncoder,+ uniforms: &mut UniformData,+ doc: &Document,+ group: LayerId,+ into: LayerId,+ ) -> Option<()> {+ let settings = doc.layer(group)?;+ let view = self.composite_group(device, doc, encoder, uniforms, self.full(), group)?;+ let uniform = LayerUniform {+ opacity: if settings.visible { settings.opacity.clamp(0.0, 1.0) } else { 0.0 },+ blend: settings.blend.id(),+ ..Default::default()+ };+ self.blend_down(device, encoder, uniforms, view, None, uniform, into)+ }++ /// Makes sure there is a pair of group textures for each of `depth` levels.+ fn make_groups(&mut self, device: &wgpu::Device, depth: usize) {+ while self.groups.len() < depth {+ let textures = [+ texture(device, "group", self.width, self.height, LAYER_FORMAT),+ texture(device, "group 2", self.width, self.height, LAYER_FORMAT),+ ];+ let views = [+ textures[0].create_view(&wgpu::TextureViewDescriptor::default()),+ textures[1].create_view(&wgpu::TextureViewDescriptor::default()),+ ];+ self.groups.push((textures, views));+ }+ }++ /// Copies a region of a layer aside.+ fn snapshot(+ &self,+ device: &wgpu::Device,+ encoder: &mut wgpu::CommandEncoder,+ id: LayerId,+ rect: IRect,+ ) -> Option<Snapshot> {+ let layer = self.layers.get(&id)?;+ let rect = rect.intersect(self.full());+ if rect.is_empty() {+ return None;+ }+ Some(Snapshot { layer: id, rect, texture: region_copy(device, encoder, &layer.texture, rect) })+ }++ /// Applies an undo or redo step and returns its inverse: the pixels and document it replaced.+ fn apply_step(&mut self, gpu: &Gpu, encoder: &mut wgpu::CommandEncoder, doc: &mut Document, step: Step) -> Step {+ let device = &gpu.device;+ let made = step.made;+ let name = step.name.clone();+ let mut pixels = Vec::with_capacity(step.pixels.len());+ for s in step.pixels {+ if let Some(current) = self.snapshot(device, encoder, s.layer, s.rect) {+ pixels.push(current);+ }+ if let Some(layer) = self.layers.get(&s.layer) {+ encoder.copy_texture_to_texture(+ copy_at(&s.texture, 0, 0),+ copy_at(&layer.texture, s.rect.x0, s.rect.y0),+ extent(s.rect.width(), s.rect.height()),+ );+ }+ self.dirty = self.dirty.union(s.rect);+ }+ let replaced = step.doc.map(|before| Box::new(std::mem::replace(doc, *before)));+ if replaced.is_some() {+ self.dirty = self.full();+ }+ let selection = step.selection.map(|before| {+ let now = self.selection.take().map(|s| s.coverage);+ self.put_selection(device, &gpu.queue, before);+ now+ });+ // put back last first, so pixels that several snapshots cover end as the first left them+ pixels.reverse();+ Step { made, name, doc: replaced, pixels, selection }+ }++ /// Draws the layer being edited from its copy through `filter`, kept to the selection.+ fn filter(&mut self, gpu: &Gpu, encoder: &mut wgpu::CommandEncoder, uniforms: &mut UniformData, filter: Filter) {+ let Some(t) = &self.transforming else { return };+ let Some(layer) = self.layers.get(&t.layer) else { return };+ let (w, h) = (self.width as f32, self.height as f32);+ let full = [w, h, if t.masked { 1.0 } else { 0.0 }, 0.0];+ let values = |a: [f32; 4], b: [f32; 4]| FilterUniform { a, b, size: full, c: [0.0; 4] };+ // most adjustments are one pass from the copy into the layer+ let (pass, uniform) = match filter {+ Filter::Hsb { hue, saturation, brightness } => {+ ("fs_hsb", values([hue, saturation, brightness, 0.0], [0.0; 4]))+ }+ Filter::Sharpen { amount } => ("fs_sharpen", values([amount, 0.0, 0.0, 0.0], [0.0; 4])),+ Filter::Noise { amount, frequency, octaves, turbulence, kind, multi, added } => {+ let flags = [kind.min(2) as f32, f32::from(u8::from(multi)), f32::from(u8::from(added)), 0.0];+ ("fs_noise", values([amount, frequency, octaves.clamp(1, 8) as f32, turbulence], flags))+ }+ Filter::Motion { along: [x, y] } => {+ let count = (x.hypot(y)).clamp(1.0, 128.0);+ ("fs_streak", values([x, y, count, 1.0], [0.0; 4]))+ }+ Filter::Zoom { centre: [x, y], amount } => ("fs_zoom", values([amount, 0.0, 0.0, 0.0], [x, y, 0.0, 0.0])),+ Filter::Chromatic { centre: [x, y], amount, displace, offset: [ox, oy], blur, falloff, transparency } => {+ // displaced, the centre's place carries the offset and the amount says so+ let (b, a) = if displace { ([ox, oy, -1.0, 0.0], 0.0) } else { ([x, y, 0.0, 0.0], amount) };+ ("fs_chroma", values([a, blur, falloff, transparency], b))+ }+ Filter::Halftone { pitch, kind } => {+ ("fs_halftone", values([pitch.max(2.0), kind.min(2) as f32, 0.0, 0.0], [0.0; 4]))+ }+ Filter::Blur { sigma } => ("fs_up", values([0.0; 4], [sigma, 0.0, 0.0, 0.0])),+ Filter::Bloom { sigma, amount, threshold, transition, burn } => {+ ("fs_bloom", values([amount, threshold, transition, burn], [sigma, 0.0, 0.0, 0.0]))+ }+ Filter::Curves => ("fs_curves", values([0.0; 4], [0.0; 4])),+ Filter::Liquify { amount } => ("fs_liquified", values([amount, 0.0, 0.0, 0.0], [0.0; 4])),+ Filter::Clone { offset: [x, y] } => ("fs_clone", values([x, y, 0.0, 0.0], [0.0; 4])),+ Filter::Glitch { kind, amount, values: [v0, v1, v2], zoom, seed } => {+ ("fs_glitch", values([kind.min(3) as f32, amount, v0, v1], [v2, zoom, seed, 0.0]))+ }+ Filter::GradientMap { amount } => ("fs_gradient", values([amount, 0.0, 0.0, 0.0], [0.0; 4])),+ Filter::ColorBalance { shadows: [s0, s1, s2], midtones: [m0, m1, m2], highlights: [h0, h1, h2] } => (+ "fs_balance",+ FilterUniform { a: [s0, s1, s2, 0.0], b: [m0, m1, m2, 0.0], size: full, c: [h0, h1, h2, 0.0] },+ ),+ };+ let blurred = match filter {+ Filter::Blur { sigma } | Filter::Bloom { sigma, .. } => self.blur_copy(gpu, encoder, uniforms, sigma),+ _ => None,+ };+ let Some(pipeline) = self.pipelines.filters.get(pass) else { return };+ let offset = uniforms.push(&uniform);+ // the last pass reads the copy, or the blurred copy, and takes the selection from the edit+ let source = blurred.as_ref().map(|view| self.adjustment_bind(&gpu.device, view, t.masked));+ let mut out = render_pass(encoder, "adjustment", &layer.view, wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT));+ out.set_pipeline(pipeline);+ out.set_bind_group(0, source.as_ref().unwrap_or(&t.bind), &[]);+ out.set_bind_group(1, &self.uniform_bind, &[offset]);+ // liquify reads its field where the others read the table+ let last = match (filter, &self.liquify) {+ (Filter::Liquify { .. }, Some(field)) => &field.bind,+ _ => &t.before_bind,+ };+ out.set_bind_group(2, last, &[]);+ out.draw(0..3, 0..1);+ drop(out);+ self.dirty = self.full();+ }++ /// `view` bound as an adjustment's source, with where it shows when `masked`: what is painted+ /// on, or else the selection.+ fn adjustment_bind(&self, device: &wgpu::Device, view: &wgpu::TextureView, masked: bool) -> wgpu::BindGroup {+ let painted = self.pencil.as_ref().map(|p| &p.view);+ let chosen =+ painted.or(self.selection.as_ref().map(|s| &s.view)).filter(|_| masked).unwrap_or(&self.everything);+ device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("adjustment pass"),+ layout: &self.pipelines.transform_layout,+ entries: &[+ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(view) },+ wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&self.sampler) },+ wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(chosen) },+ ],+ })+ }++ /// The edit's copy blurred by `sigma` canvas pixels, at a smaller size for wide blurs (halved+ /// until the blur is a few pixels wide where it runs); none when the blur is too small to do.+ fn blur_copy(+ &self,+ gpu: &Gpu,+ encoder: &mut wgpu::CommandEncoder,+ uniforms: &mut UniformData,+ sigma: f32,+ ) -> Option<wgpu::TextureView> {+ let device = &gpu.device;+ let t = self.transforming.as_ref()?;+ let (w, h) = (self.width, self.height);+ let mut scale = 1u32;+ while sigma / scale as f32 > 8.0 && scale < 32 && w / (scale * 2) > 0 && h / (scale * 2) > 0 {+ scale *= 2;+ }+ let small = |s: u32| (w.div_ceil(s).max(1), h.div_ceil(s).max(1));+ let mut pass = |encoder: &mut wgpu::CommandEncoder,+ target: &wgpu::TextureView,+ fs: &str,+ source: &wgpu::BindGroup,+ uniform: FilterUniform| {+ let Some(pipeline) = self.pipelines.filters.get(fs) else { return };+ let offset = uniforms.push(&uniform);+ let mut p = render_pass(encoder, "adjustment", target, wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT));+ p.set_pipeline(pipeline);+ p.set_bind_group(0, source, &[]);+ p.set_bind_group(1, &self.uniform_bind, &[offset]);+ p.set_bind_group(2, &t.before_bind, &[]);+ p.draw(0..3, 0..1);+ };+ let mut current: Option<wgpu::TextureView> = None;+ let mut level = 1u32;+ while level < scale {+ level *= 2;+ let (lw, lh) = small(level);+ let next = texture(device, "adjustment level", lw, lh, LAYER_FORMAT)+ .create_view(&wgpu::TextureViewDescriptor::default());+ let uniform =+ FilterUniform { a: [0.0; 4], b: [0.0; 4], size: [lw as f32, lh as f32, 0.0, 0.0], c: [0.0; 4] };+ let source = current.as_ref().map(|v| self.adjustment_bind(device, v, false));+ pass(encoder, &next, "fs_down", source.as_ref().unwrap_or(&t.bind), uniform);+ current = Some(next);+ }+ let s_sigma = sigma / scale as f32;+ if s_sigma < 0.3 {+ return current;+ }+ let (lw, lh) = small(scale);+ let reach = (s_sigma * 3.0).ceil().min(64.0);+ let size = [lw as f32, lh as f32, 0.0, 0.0];+ let across = texture(device, "adjustment across", lw, lh, LAYER_FORMAT)+ .create_view(&wgpu::TextureViewDescriptor::default());+ let down = texture(device, "adjustment down", lw, lh, LAYER_FORMAT)+ .create_view(&wgpu::TextureViewDescriptor::default());+ let source = current.as_ref().map(|v| self.adjustment_bind(device, v, false));+ pass(+ encoder,+ &across,+ "fs_blur",+ source.as_ref().unwrap_or(&t.bind),+ FilterUniform { a: [1.0, 0.0, s_sigma, reach], b: [0.0; 4], size, c: [0.0; 4] },+ );+ let source = self.adjustment_bind(device, &across, false);+ pass(+ encoder,+ &down,+ "fs_blur",+ &source,+ FilterUniform { a: [0.0, 1.0, s_sigma, reach], b: [0.0; 4], size, c: [0.0; 4] },+ );+ Some(down)+ }++ /// A new step: it joins the history and anything undone can no longer be redone.+ fn push_step(&mut self, mut step: Step) {+ self.steps_made += 1;+ step.made = self.steps_made;+ if step.name.is_none() {+ step.name = self.next_name.take();+ }+ self.redo.clear();+ self.undo.push(step);+ let mut bytes: u64 = self.undo.iter().map(Step::bytes).sum();+ while self.undo.len() > MAX_UNDO || (bytes > MAX_UNDO_BYTES && self.undo.len() > 1) {+ let dropped = self.undo.remove(0);+ bytes = bytes.saturating_sub(dropped.bytes());+ }+ }++ /// Composites the visible layers over the background inside `rect`, into `composite[0]`.+ /// Normal layers blend in place; other modes read what is below and write the other texture.+ fn composite(+ &self,+ device: &wgpu::Device,+ doc: &Document,+ encoder: &mut wgpu::CommandEncoder,+ uniforms: &mut UniformData,+ rect: IRect,+ ) {+ let [r, g, b] = doc.background;+ let solid = if doc.background_visible { [r, g, b, 1.0] } else { [0.0; 4] };+ {+ let offset = uniforms.push(&LayerUniform { opacity: 1.0, solid, ..Default::default() });+ let mut pass = render_pass(encoder, "background", &self.composite_views[0], wgpu::LoadOp::Load);+ scissor(&mut pass, rect);+ pass.set_pipeline(&self.pipelines.solid);+ pass.set_bind_group(0, &self.stroke_bind, &[]);+ pass.set_bind_group(1, &self.uniform_bind, &[offset]);+ pass.draw(0..3, 0..1);+ }+ // the stack bottom up; a group's layers go onto its depth's pair of textures first, and+ // the group onto the stack where its entry is+ let main = Stack { textures: &self.composite, views: &self.composite_views };+ let current = self.composite_members(device, doc, encoder, uniforms, rect, None, &main);+ main.settle(encoder, rect, current);+ }++ /// The members of `group` (None: the top level) bottom up onto `stack`; returns which of its+ /// textures holds the result.+ #[allow(clippy::too_many_arguments)]+ fn composite_members(+ &self,+ device: &wgpu::Device,+ doc: &Document,+ encoder: &mut wgpu::CommandEncoder,+ uniforms: &mut UniformData,+ rect: IRect,+ group: Option<LayerId>,+ stack: &Stack<'_>,+ ) -> usize {+ let mut current = 0usize;+ // Animation Assist: the top level's frames show around the current (or played) one+ let animation = if group.is_none() { doc.animation.as_ref() } else { None };+ let frames = animation.map(|_| animation::frames(doc)).unwrap_or_default();+ let focus = animation.and_then(|_| self.play_frame.or_else(|| animation::current_frame(doc)));+ for id in doc.members(group) {+ let Some(layer) = doc.layer(id) else { continue };+ let look = match (animation, focus, frames.iter().position(|f| *f == id)) {+ (Some(a), Some(c), Some(i)) => {+ match animation::look(a, i, frames.len(), c, self.play_frame.is_some()) {+ FrameLook::Shown => Look::PLAIN,+ FrameLook::Onion { color, opacity } => {+ Look { tint: [color[0], color[1], color[2], 1.0], opacity }+ }+ FrameLook::Hidden => continue,+ }+ }+ _ => Look::PLAIN,+ };+ match layer.kind {+ LayerKind::Mask => {}+ LayerKind::Paint => {+ self.composite_layer(device, doc, encoder, uniforms, rect, layer, look, stack, &mut current)+ }+ LayerKind::Group => {+ if !layer.visible || layer.opacity <= 0.0 {+ continue;+ }+ let Some(view) = self.composite_group(device, doc, encoder, uniforms, rect, id) else { continue };+ let uniform = LayerUniform {+ opacity: layer.opacity.clamp(0.0, 1.0) * look.opacity,+ blend: layer.blend.id(),+ tint: look.tint,+ ..Default::default()+ };+ self.draw_onto(+ device,+ encoder,+ uniforms,+ rect,+ view,+ None,+ &self.stroke_view,+ uniform,+ layer.blend,+ stack,+ &mut current,+ );+ }+ }+ }+ current+ }++ /// Group `id`'s members composited over transparency on the textures for its depth; returns+ /// the view holding the result.+ fn composite_group(+ &self,+ device: &wgpu::Device,+ doc: &Document,+ encoder: &mut wgpu::CommandEncoder,+ uniforms: &mut UniformData,+ rect: IRect,+ id: LayerId,+ ) -> Option<&wgpu::TextureView> {+ let (textures, views) = self.groups.get(doc.depth(id))?;+ let inner = Stack { textures, views };+ drop(render_pass(encoder, "group clear", &views[0], wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT)));+ let at = self.composite_members(device, doc, encoder, uniforms, rect, Some(id), &inner);+ inner.settle(encoder, rect, at);+ Some(&views[0])+ }++ /// One paint layer (through its mask, with the stroke being drawn on it or its mask) onto a+ /// stack whose result is in `stack.views[current]`.+ #[allow(clippy::too_many_arguments)]+ fn composite_layer(+ &self,+ device: &wgpu::Device,+ doc: &Document,+ encoder: &mut wgpu::CommandEncoder,+ uniforms: &mut UniformData,+ rect: IRect,+ layer: &Layer,+ look: Look,+ stack: &Stack<'_>,+ current: &mut usize,+ ) {+ let clip = doc.clip_base(layer.id);+ let clip_visible = clip.is_none_or(|id| doc.layer(id).is_some_and(|l| l.visible));+ if !layer.visible || !clip_visible || layer.opacity <= 0.0 {+ return;+ }+ let Some(gpu_layer) = self.layers.get(&layer.id) else { return };+ let clip_view = clip.and_then(|id| self.layers.get(&id)).map_or(&self.stroke_view, |c| &c.view);+ let mask = doc.mask_of(layer.id).filter(|m| doc.layer(*m).is_some_and(|l| l.visible));+ let mask_view = mask.and_then(|m| self.layers.get(&m)).map(|m| &m.view);+ // the stroke being drawn shows on its layer, or through the mask it is painting+ let stroke = self.active.filter(|s| (s.layer == layer.id || Some(s.layer) == mask) && !s.pencil);+ let uniform = LayerUniform {+ opacity: layer.opacity.clamp(0.0, 1.0) * look.opacity,+ tint: look.tint,+ stroke_mode: match stroke.map(|s| s.style.tool) {+ None => STROKE_NONE,+ // the stroke changes the layer itself+ _ if stroke.is_some_and(|s| s.style.in_place()) => STROKE_NONE,+ Some(StrokeTool::Paint) if stroke.is_some_and(|s| s.style.preserve_alpha) => STROKE_PAINT_LOCKED,+ Some(StrokeTool::Paint) => STROKE_PAINT,+ Some(StrokeTool::Erase) => STROKE_ERASE,+ // the smudge changes the layer itself+ Some(StrokeTool::Smudge) => STROKE_NONE,+ },+ stroke_opacity: stroke.map_or(0.0, |s| s.style.opacity.clamp(0.0, 1.0)),+ blend: layer.blend.id(),+ clipped: u32::from(clip.is_some()),+ masked: if mask_view.is_some() { 1.0 } else { 0.0 },+ stroke_on_mask: if stroke.is_some_and(|s| Some(s.layer) == mask) { 1.0 } else { 0.0 },+ ..Default::default()+ }+ .with_grain(stroke.as_ref().map(|s| &s.style));+ let mask_view = mask_view.unwrap_or(&self.stroke_view);+ self.draw_onto(+ device,+ encoder,+ uniforms,+ rect,+ &gpu_layer.view,+ Some(clip_view),+ mask_view,+ uniform,+ layer.blend,+ stack,+ current,+ );+ }++ /// `view` (a layer or a group's result) drawn onto a stack: "over" for normal, else blended+ /// with what is below into the stack's other texture.+ #[allow(clippy::too_many_arguments)]+ fn draw_onto(+ &self,+ device: &wgpu::Device,+ encoder: &mut wgpu::CommandEncoder,+ uniforms: &mut UniformData,+ rect: IRect,+ view: &wgpu::TextureView,+ clip: Option<&wgpu::TextureView>,+ mask: &wgpu::TextureView,+ uniform: LayerUniform,+ blend: BlendMode,+ stack: &Stack<'_>,+ current: &mut usize,+ ) {+ let offset = uniforms.push(&uniform);+ let clip = clip.unwrap_or(&self.stroke_view);+ let [first, second] = stack.views;+ if blend == BlendMode::Normal {+ let bind = self.quad_masked(device, [view, &self.stroke_view, clip, &self.stroke_view], mask);+ let target = if *current == 0 { first } else { second };+ let mut pass = render_pass(encoder, "layer", target, wgpu::LoadOp::Load);+ scissor(&mut pass, rect);+ pass.set_pipeline(&self.pipelines.layer);+ pass.set_bind_group(0, &bind, &[]);+ pass.set_bind_group(1, &self.uniform_bind, &[offset]);+ pass.draw(0..3, 0..1);+ } else {+ let (backdrop, target) = if *current == 0 { (first, second) } else { (second, first) };+ let bind = self.quad_masked(device, [view, &self.stroke_view, clip, backdrop], mask);+ let mut pass = render_pass(encoder, "blend", target, wgpu::LoadOp::Load);+ scissor(&mut pass, rect);+ pass.set_pipeline(&self.pipelines.blend);+ pass.set_bind_group(0, &bind, &[]);+ pass.set_bind_group(1, &self.uniform_bind, &[offset]);+ pass.draw(0..3, 0..1);+ *current = 1 - *current;+ }+ }++ fn display(+ &mut self,+ device: &wgpu::Device,+ encoder: &mut wgpu::CommandEncoder,+ uniforms: &mut UniformData,+ target: &Target<'_>,+ predicted: std::ops::Range<u32>,+ ) {+ let srgb = target.format.is_srgb();+ let Pipelines {+ display,+ display_module,+ display_pipeline_layout,+ display_lut_layout,+ surround: surround_pipelines,+ surround_module,+ surround_pipeline_layout,+ overlay,+ overlay_module,+ stamp_layout,+ selection: selection_pipelines,+ selection_module,+ ..+ } = &mut self.pipelines;+ let pipeline = display.entry(target.format).or_insert_with(|| {+ sampled_pipeline(+ device,+ display_lut_layout,+ display_module,+ "display",+ "vs_display",+ "fs_display",+ target.format,+ )+ });+ let (w, h) = (target.size.0.max(1) as f32, target.size.1.max(1) as f32);+ let to_clip = Affine { a: 2.0 / w, b: 0.0, c: 0.0, d: -2.0 / h, e: -1.0, f: 1.0 };+ let unit_to_canvas = Affine { a: self.width as f32, b: 0.0, c: 0.0, d: self.height as f32, e: 0.0, f: 0.0 };+ let m = unit_to_canvas.then(target.to_screen).then(to_clip);+ let offset = uniforms.push(&DisplayUniform::new(+ [m.a, m.b, m.c, m.d],+ [m.e, m.f, if srgb { 1.0 } else { 0.0 }, 0.0],+ target.convert,+ target.lut.is_some(),+ ));+ let surround = target.surround.map(|c| if srgb { srgb_to_linear(c) } else { c });+ let clear =+ wgpu::Color { r: f64::from(surround[0]), g: f64::from(surround[1]), b: f64::from(surround[2]), a: 1.0 };+ let grid = target.grid.map(|g| {+ let pipeline = surround_pipelines.entry(target.format).or_insert_with(|| {+ sampled_pipeline(+ device,+ surround_pipeline_layout,+ surround_module,+ "surround",+ "vs_surround",+ "fs_surround",+ target.format,+ )+ });+ let offset = uniforms.push(&SurroundUniform {+ v0: [g.spacing, g.origin[0], g.origin[1], g.width],+ v1: [g.color[0], g.color[1], g.color[2], if srgb { 1.0 } else { 0.0 }],+ });+ (&*pipeline, offset)+ });+ let mut pass = render_pass(encoder, "display", target.view, wgpu::LoadOp::Clear(clear));+ if let Some((grid_pipeline, offset)) = grid {+ pass.set_pipeline(grid_pipeline);+ pass.set_bind_group(0, &self.uniform_bind, &[offset]);+ pass.draw(0..3, 0..1);+ }+ pass.set_pipeline(pipeline);+ pass.set_bind_group(0, &self.display_bind, &[]);+ pass.set_bind_group(1, &self.uniform_bind, &[offset]);+ pass.set_bind_group(2, target.lut.map_or(&self.identity_lut, |l| &l.bind), &[]);+ pass.draw(0..6, 0..1);++ // the selection: bands over what is not selected, or what is selected tinted or covered+ if let (Some(look), Some(selection), Some(inverse)) =+ (target.selection, &self.selection, unit_to_canvas.then(target.to_screen).inverse())+ {+ let multiply = matches!(look, SelectionLook::Tint(_));+ let pipeline = selection_pipelines.entry((target.format, multiply)).or_insert_with(|| {+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some("selection"),+ layout: Some(&*display_pipeline_layout),+ vertex: wgpu::VertexState {+ module: selection_module,+ entry_point: Some("vs_selection"),+ compilation_options: Default::default(),+ buffers: &[],+ },+ primitive: wgpu::PrimitiveState::default(),+ depth_stencil: None,+ multisample: wgpu::MultisampleState::default(),+ fragment: Some(wgpu::FragmentState {+ module: selection_module,+ entry_point: Some("fs_selection"),+ compilation_options: Default::default(),+ targets: &[Some(wgpu::ColorTargetState {+ format: target.format,+ blend: Some(if multiply { MULTIPLY } else { PREMULTIPLIED_OVER }),+ write_mask: wgpu::ColorWrites::ALL,+ })],+ }),+ multiview_mask: None,+ cache: None,+ })+ });+ let i = inverse;+ let srgb_flag = if srgb { 1.0 } else { 0.0 };+ let (m1_rest, v) = match look {+ SelectionLook::Stripes(s) => ([s.period.max(1.0), s.drift], [0.0, 0.0, 0.0, s.coverage]),+ SelectionLook::Tint(c) => ([1.0, 0.0], [c[0], c[1], c[2], 1.0]),+ SelectionLook::Fill(c) => ([1.0, 0.0], [c[0], c[1], c[2], 1.0]),+ };+ let mode = match look {+ SelectionLook::Stripes(_) => 0.0,+ SelectionLook::Tint(_) => 1.0,+ SelectionLook::Fill(_) => 2.0,+ };+ let offset = uniforms.push(&SelectionUniform {+ m0: [i.a, i.b, i.c, i.d],+ m1: [i.e, i.f, m1_rest[0], m1_rest[1]],+ v,+ mode: [mode, srgb_flag, 0.0, 0.0],+ });+ pass.set_pipeline(pipeline);+ pass.set_bind_group(0, &selection.bind, &[]);+ pass.set_bind_group(1, &self.uniform_bind, &[offset]);+ pass.draw(0..3, 0..1);+ }++ // the predicted tail of a painting stroke, over the canvas+ let Some(style) = self.active.filter(|a| !a.pencil).map(|a| a.style).filter(|s| s.tool == StrokeTool::Paint)+ else {+ return;+ };+ if predicted.is_empty() {+ return;+ }+ let overlay_pipeline = overlay.entry(target.format).or_insert_with(|| {+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some("prediction"),+ layout: Some(stamp_layout),+ vertex: wgpu::VertexState {+ module: overlay_module,+ entry_point: Some("vs_overlay"),+ compilation_options: Default::default(),+ buffers: &[Some(wgpu::VertexBufferLayout {+ array_stride: size_of::<StampInstance>() as u64,+ step_mode: wgpu::VertexStepMode::Instance,+ attributes: &STAMP_ATTRIBUTES,+ })],+ },+ primitive: wgpu::PrimitiveState::default(),+ depth_stencil: None,+ multisample: wgpu::MultisampleState::default(),+ fragment: Some(wgpu::FragmentState {+ module: overlay_module,+ entry_point: Some("fs_overlay"),+ compilation_options: Default::default(),+ targets: &[Some(wgpu::ColorTargetState {+ format: target.format,+ blend: Some(PREMULTIPLIED_OVER),+ write_mask: wgpu::ColorWrites::ALL,+ })],+ }),+ multiview_mask: None,+ cache: None,+ })+ });+ let c = target.to_screen.then(to_clip);+ let offset = uniforms.push(&OverlayUniform {+ m0: [c.a, c.b, c.c, c.d],+ m1: [c.e, c.f, target.to_screen.scale_factor(), style.hardness.clamp(0.0, 1.0)],+ color: {+ let [r, g, b] = convert_colour(style.color, target.convert);+ [r, g, b, style.opacity.clamp(0.0, 1.0)]+ },+ shape: style.shape.map_or(-1, |s| s as i32),+ srgb: u32::from(srgb),+ _pad: [0; 2],+ });+ let size = size_of::<StampInstance>() as u64;+ pass.set_pipeline(overlay_pipeline);+ pass.set_bind_group(0, &self.uniform_bind, &[offset]);+ pass.set_bind_group(1, &self.brush_bind, &[]);+ pass.set_vertex_buffer(+ 0,+ self.stamp_buffer.slice(u64::from(predicted.start) * size..u64::from(predicted.end) * size),+ );+ pass.draw(0..6, 0..predicted.end - predicted.start);+ }++ /// Frosted panels: the canvas and its surround drawn again, small, blurred, and drawn into+ /// each region of the target.+ fn frost(+ &mut self,+ device: &wgpu::Device,+ encoder: &mut wgpu::CommandEncoder,+ uniforms: &mut UniformData,+ target: &Target<'_>,+ backdrop: Backdrop<'_>,+ ) {+ let k = (backdrop.sigma / BACKDROP_TEXELS).floor().clamp(1.0, 16.0);+ let size = ((target.size.0 as f32 / k).ceil() as u32, (target.size.1 as f32 / k).ceil() as u32);+ if self.backdrop.as_ref().is_none_or(|b| b.size != size || b.format != target.format) {+ self.backdrop =+ Some(BackdropGpu::new(device, &self.pipelines.sampled_layout, &self.sampler, size, target.format));+ }+ let Some(small) = self.backdrop.as_ref() else { return };+ let srgb = target.format.is_srgb();+ let Pipelines {+ display,+ display_module,+ display_pipeline_layout,+ display_lut_layout,+ backdrop_module,+ blur,+ frost,+ ..+ } = &mut self.pipelines;+ let display = display.entry(target.format).or_insert_with(|| {+ sampled_pipeline(+ device,+ display_lut_layout,+ display_module,+ "display",+ "vs_display",+ "fs_display",+ target.format,+ )+ });+ let blur = blur.entry(target.format).or_insert_with(|| {+ sampled_pipeline(+ device,+ display_pipeline_layout,+ backdrop_module,+ "blur",+ "vs_full",+ "fs_blur",+ target.format,+ )+ });+ let frost = frost.entry(target.format).or_insert_with(|| {+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some("frost"),+ layout: Some(&*display_pipeline_layout),+ vertex: wgpu::VertexState {+ module: backdrop_module,+ entry_point: Some("vs_frost"),+ compilation_options: Default::default(),+ buffers: &[],+ },+ primitive: wgpu::PrimitiveState::default(),+ depth_stencil: None,+ multisample: wgpu::MultisampleState::default(),+ fragment: Some(wgpu::FragmentState {+ module: backdrop_module,+ entry_point: Some("fs_frost"),+ compilation_options: Default::default(),+ targets: &[Some(wgpu::ColorTargetState {+ format: target.format,+ blend: Some(PREMULTIPLIED_OVER),+ write_mask: wgpu::ColorWrites::ALL,+ })],+ }),+ multiview_mask: None,+ cache: None,+ })+ });++ // the scene, small: the surround and the canvas (its grid lines and the selection's look+ // would not show through the blur)+ let (w, h) = (size.0.max(1) as f32, size.1.max(1) as f32);+ let to_clip = Affine { a: 2.0 / w, b: 0.0, c: 0.0, d: -2.0 / h, e: -1.0, f: 1.0 };+ let unit_to_canvas = Affine { a: self.width as f32, b: 0.0, c: 0.0, d: self.height as f32, e: 0.0, f: 0.0 };+ let shrink = Affine { a: 1.0 / k, b: 0.0, c: 0.0, d: 1.0 / k, e: 0.0, f: 0.0 };+ let m = unit_to_canvas.then(target.to_screen).then(shrink).then(to_clip);+ let offset = uniforms.push(&DisplayUniform::new(+ [m.a, m.b, m.c, m.d],+ [m.e, m.f, if srgb { 1.0 } else { 0.0 }, 0.0],+ target.convert,+ target.lut.is_some(),+ ));+ let surround = target.surround.map(|c| if srgb { srgb_to_linear(c) } else { c });+ let clear =+ wgpu::Color { r: f64::from(surround[0]), g: f64::from(surround[1]), b: f64::from(surround[2]), a: 1.0 };+ {+ let mut pass = render_pass(encoder, "backdrop scene", &small.views[0], wgpu::LoadOp::Clear(clear));+ pass.set_pipeline(display);+ pass.set_bind_group(0, &self.display_bind, &[]);+ pass.set_bind_group(1, &self.uniform_bind, &[offset]);+ pass.set_bind_group(2, target.lut.map_or(&self.identity_lut, |l| &l.bind), &[]);+ pass.draw(0..6, 0..1);+ }+ // blurred across, then down+ let sigma = backdrop.sigma / k;+ let radius = (sigma * 3.0).ceil().min(64.0);+ for (from, to, step) in+ [(&small.binds[0], &small.views[1], [1.0 / w, 0.0]), (&small.binds[1], &small.views[0], [0.0, 1.0 / h])]+ {+ let offset =+ uniforms.push(&BackdropUniform { v0: [step[0], step[1], sigma, radius], v1: [0.0; 4], v2: [0.0; 4] });+ let mut pass = render_pass(encoder, "backdrop blur", to, wgpu::LoadOp::Clear(clear));+ pass.set_pipeline(blur);+ pass.set_bind_group(0, from, &[]);+ pass.set_bind_group(1, &self.uniform_bind, &[offset]);+ pass.draw(0..3, 0..1);+ }+ // into each region+ let (tw, th) = (target.size.0.max(1) as f32, target.size.1.max(1) as f32);+ let mut pass = render_pass(encoder, "frost", target.view, wgpu::LoadOp::Load);+ pass.set_pipeline(frost);+ pass.set_bind_group(0, &small.binds[0], &[]);+ for &[x0, y0, x1, y1, corner, alpha] in backdrop.regions {+ if ![x0, y0, x1, y1, corner, alpha].iter().all(|v| v.is_finite()) || x1 <= x0 || y1 <= y0 || alpha <= 0.0 {+ continue;+ }+ let offset = uniforms.push(&BackdropUniform {+ v0: [x0, y0, x1, y1],+ v1: [corner, tw, th, k],+ v2: [alpha.min(1.0), 0.0, 0.0, 0.0],+ });+ pass.set_bind_group(1, &self.uniform_bind, &[offset]);+ pass.draw(0..6, 0..1);+ }+ }++ /// A layer scaled to fit `max_side` pixels (premultiplied). Runs what is queued first, then+ /// waits for the GPU.+ pub fn layer_thumbnail(+ &mut self,+ gpu: &Gpu,+ doc: &mut Document,+ id: LayerId,+ max_side: u32,+ ) -> Result<Thumbnail, GpuError> {+ self.render(gpu, doc, None);+ let full = self.full();+ // a mask is white where nothing is painted on it+ let bounds = if doc.layer(id).is_some_and(|l| l.kind == LayerKind::Mask) { ink_bounds } else { alpha_bounds };+ // where its pixels are: roughly, on a copy small enough to read back quickly but fine+ // enough (8 pixels to one) not to miss a dot, then exactly, on the region drawn+ let coarse = self.sample_layer(gpu, id, full, (self.width.max(self.height) / 8).clamp(64, 2048))?;+ let Some([x0, y0, x1, y1]) = bounds(&coarse) else { return self.sample_layer(gpu, id, full, max_side) };+ let (sx, sy) = (self.width as f32 / coarse.width as f32, self.height as f32 / coarse.height as f32);+ let rect = IRect {+ x0: ((x0 as f32 - 1.0) * sx).floor() as i32,+ y0: ((y0 as f32 - 1.0) * sy).floor() as i32,+ x1: ((x1 as f32 + 1.0) * sx).ceil() as i32,+ y1: ((y1 as f32 + 1.0) * sy).ceil() as i32,+ }+ .intersect(full);+ let fine = self.sample_layer(gpu, id, rect, max_side)?;+ Ok(match bounds(&fine) {+ Some(b) => crop(&fine, b),+ None => fine,+ })+ }++ /// `rect` of a layer box-filtered to fit `max_side` pixels (never enlarged), read back.+ fn sample_layer(&self, gpu: &Gpu, id: LayerId, rect: IRect, max_side: u32) -> Result<Thumbnail, GpuError> {+ let layer = self.layers.get(&id).ok_or_else(|| GpuError::Readback(format!("no layer {id:?}")))?;+ self.sample_view(gpu, &layer.view, rect, max_side)+ }++ /// The whole picture as composited, scaled to fit `max_side` pixels (never enlarged).+ /// Each paint layer's coverage (alpha, 0 to 255) at canvas pixel (`x`, `y`), in the+ /// document's order; none for a point off the canvas.+ pub fn alphas_at(&mut self, gpu: &Gpu, doc: &mut Document, x: u32, y: u32) -> Result<Vec<(LayerId, u8)>, GpuError> {+ if x >= self.width || y >= self.height {+ return Ok(Vec::new());+ }+ self.render(gpu, doc, None);+ let ids: Vec<LayerId> = doc+ .layers()+ .iter()+ .filter(|l| l.kind == LayerKind::Paint)+ .map(|l| l.id)+ .filter(|id| self.layers.contains_key(id))+ .collect();+ if ids.is_empty() {+ return Ok(Vec::new());+ }+ // one pixel of each layer, each in its own 256-byte row of a buffer+ let buffer = gpu.device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("layer pixels"),+ size: 256 * ids.len() as u64,+ usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });+ let mut encoder =+ gpu.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("layer pixels") });+ for (i, id) in ids.iter().enumerate() {+ let Some(layer) = self.layers.get(id) else { continue };+ encoder.copy_texture_to_buffer(+ copy_at(&layer.texture, i32::try_from(x).unwrap_or(0), i32::try_from(y).unwrap_or(0)),+ wgpu::TexelCopyBufferInfo {+ buffer: &buffer,+ layout: wgpu::TexelCopyBufferLayout {+ offset: 256 * i as u64,+ bytes_per_row: Some(256),+ rows_per_image: Some(1),+ },+ },+ extent(1, 1),+ );+ }+ gpu.queue.submit([encoder.finish()]);+ let (tx, rx) = mpsc::channel();+ buffer.slice(..).map_async(wgpu::MapMode::Read, move |r| {+ let _ = tx.send(r);+ });+ gpu.device.poll(wgpu::PollType::wait_indefinitely()).map_err(|e| GpuError::Readback(e.to_string()))?;+ rx.recv().map_err(|e| GpuError::Readback(e.to_string()))?.map_err(|e| GpuError::Readback(e.to_string()))?;+ let mapped = buffer.slice(..).get_mapped_range().map_err(|e| GpuError::Readback(e.to_string()))?;+ let out = ids.iter().enumerate().map(|(i, id)| (*id, mapped.get(256 * i + 3).copied().unwrap_or(0))).collect();+ drop(mapped);+ buffer.unmap();+ Ok(out)+ }++ /// Layer `id` over the whole canvas (not cropped to what is drawn) fitted to `max_side`, as+ /// Animation Assist's timeline shows a frame.+ pub fn layer_picture(+ &mut self,+ gpu: &Gpu,+ doc: &mut Document,+ id: LayerId,+ max_side: u32,+ ) -> Result<Thumbnail, GpuError> {+ self.render(gpu, doc, None);+ let full = self.full();+ self.sample_layer(gpu, id, full, max_side)+ }++ pub fn composite_thumbnail(&mut self, gpu: &Gpu, doc: &mut Document, max_side: u32) -> Result<Thumbnail, GpuError> {+ self.render(gpu, doc, None);+ self.sample_view(gpu, &self.composite_views[0], self.full(), max_side)+ }++ /// `rect` of a texture box-filtered to fit `max_side` pixels (never enlarged), read back.+ fn sample_view(+ &self,+ gpu: &Gpu,+ source: &wgpu::TextureView,+ rect: IRect,+ max_side: u32,+ ) -> Result<Thumbnail, GpuError> {+ let side = max_side.clamp(1, 2048) as f32;+ let (rw, rh) = (rect.width().max(1) as f32, rect.height().max(1) as f32);+ let scale = (side / rw).min(side / rh).min(1.0);+ let (w, h) = (((rw * scale).round() as u32).max(1), ((rh * scale).round() as u32).max(1));+ let small = texture(&gpu.device, "thumbnail", w, h, LAYER_FORMAT);+ let view = small.create_view(&wgpu::TextureViewDescriptor::default());+ let bind = sampled_bind(&gpu.device, &self.pipelines.sampled_layout, source, &self.sampler);+ let mut data = UniformData::default();+ // the target size and the source pixels each target pixel covers; the source rectangle+ let (cw, ch) = (self.width.max(1) as f32, self.height.max(1) as f32);+ let offset = data.push(&DisplayUniform::new(+ [w as f32, h as f32, rw / w as f32, rh / h as f32],+ [rect.x0 as f32 / cw, rect.y0 as f32 / ch, rw / cw, rh / ch],+ None,+ false,+ ));+ let mut encoder =+ gpu.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("thumbnail") });+ {+ let mut pass = render_pass(&mut encoder, "thumbnail", &view, wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT));+ pass.set_pipeline(&self.pipelines.thumb);+ pass.set_bind_group(0, &bind, &[]);+ pass.set_bind_group(1, &self.uniform_bind, &[offset]);+ pass.draw(0..3, 0..1);+ }+ gpu.queue.write_buffer(&self.uniform_buffer, 0, &data.data);+ gpu.queue.submit([encoder.finish()]);+ let rgba = read_texture(gpu, &small, w, h)?;+ Ok(Thumbnail { width: w, height: h, rgba })+ }++ /// Replaces a layer's pixels (premultiplied RGBA8, the canvas's size, rows top to bottom), for+ /// opening a saved artwork. Not an undo step.+ pub fn upload_layer(&mut self, gpu: &Gpu, id: LayerId, rgba: &[u8]) -> Result<(), GpuError> {+ let expected = self.width as usize * self.height as usize * 4;+ if rgba.len() != expected {+ return Err(GpuError::Readback(format!("layer {id:?}: {} bytes, expected {expected}", rgba.len())));+ }+ if !self.layers.contains_key(&id) {+ let texture = texture(&gpu.device, "layer", self.width, self.height, LAYER_FORMAT);+ let view = texture.create_view(&wgpu::TextureViewDescriptor::default());+ self.layers.insert(id, LayerGpu { texture, view });+ }+ let Some(layer) = self.layers.get(&id) else { return Ok(()) };+ gpu.queue.write_texture(+ copy_at(&layer.texture, 0, 0),+ rgba,+ wgpu::TexelCopyBufferLayout {+ offset: 0,+ bytes_per_row: Some(self.width * 4),+ rows_per_image: Some(self.height),+ },+ extent(self.width, self.height),+ );+ self.invalidate();+ Ok(())+ }++ /// A colour table for [`Target::lut`] from `lut` (its first three outputs, 0..1 encoded).+ pub fn display_lut(&self, gpu: &Gpu, lut: &procraft_engine::cms::Lut) -> DisplayLut {+ let rgba: Vec<u8> = lut+ .values+ .chunks(lut.outputs.max(1))+ .flat_map(|v| {+ let c = |k: usize| (v.get(k).copied().unwrap_or(0.0).clamp(0.0, 1.0) * 255.0).round() as u8;+ [c(0), c(1), c(2), 255]+ })+ .collect();+ DisplayLut { bind: lut_bind(gpu, &self.pipelines.lut_layout, lut.grid as u32, &rgba) }+ }++ /// The composite's pixels (premultiplied RGBA8, rows top to bottom). Waits for the GPU.+ pub fn read_composite(&self, gpu: &Gpu) -> Result<Vec<u8>, GpuError> {+ read_texture(gpu, &self.composite[0], self.width, self.height)+ }++ /// A layer's pixels (premultiplied RGBA8). Waits for the GPU.+ pub fn read_layer(&self, gpu: &Gpu, id: LayerId) -> Result<Vec<u8>, GpuError> {+ let layer = self.layers.get(&id).ok_or_else(|| GpuError::Readback(format!("no layer {id:?}")))?;+ read_texture(gpu, &layer.texture, self.width, self.height)+ }++ /// A bind group of four textures (layer, stroke, clip base, backdrop) plus the grains.+ fn quad(&self, device: &wgpu::Device, views: [&wgpu::TextureView; 4]) -> wgpu::BindGroup {+ let [a, b, c, d] = views;+ self.quad_masked(device, [a, b, c, d], &self.stroke_view)+ }++ /// As [`Self::quad`], with the layer's mask.+ fn quad_masked(+ &self,+ device: &wgpu::Device,+ views: [&wgpu::TextureView; 4],+ mask: &wgpu::TextureView,+ ) -> wgpu::BindGroup {+ let [a, b, c, d] = views;+ quad_bind(device, &self.pipelines.quad_layout, [a, b, c, d, mask], &self.grains_view, &self.grain_sampler)+ }++ /// Layer textures held (the document's and those the history still needs).+ pub fn layer_texture_count(&self) -> usize {+ self.layers.len()+ }+}++impl Pipelines {+ fn new(device: &wgpu::Device) -> Pipelines {+ let tex_entry = |binding| wgpu::BindGroupLayoutEntry {+ binding,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Texture {+ sample_type: wgpu::TextureSampleType::Float { filterable: false },+ view_dimension: wgpu::TextureViewDimension::D2,+ multisampled: false,+ },+ count: None,+ };+ let array_entry = |binding| wgpu::BindGroupLayoutEntry {+ binding,+ visibility: wgpu::ShaderStages::FRAGMENT.union(wgpu::ShaderStages::COMPUTE),+ ty: wgpu::BindingType::Texture {+ sample_type: wgpu::TextureSampleType::Float { filterable: true },+ view_dimension: wgpu::TextureViewDimension::D2Array,+ multisampled: false,+ },+ count: None,+ };+ let sampler_entry = |binding| wgpu::BindGroupLayoutEntry {+ binding,+ visibility: wgpu::ShaderStages::FRAGMENT.union(wgpu::ShaderStages::COMPUTE),+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),+ count: None,+ };+ let quad_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("layer, stroke, clip, backdrop, grains"),+ entries: &[+ tex_entry(0),+ tex_entry(1),+ tex_entry(2),+ tex_entry(3),+ array_entry(4),+ sampler_entry(5),+ tex_entry(6),+ ],+ });+ let brush_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("shapes, grains and the selection"),+ entries: &[+ array_entry(0),+ array_entry(1),+ sampler_entry(2),+ sampler_entry(3),+ // the selection, filtered where the stamp samples it+ wgpu::BindGroupLayoutEntry {+ binding: 4,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Texture {+ sample_type: wgpu::TextureSampleType::Float { filterable: true },+ view_dimension: wgpu::TextureViewDimension::D2,+ multisampled: false,+ },+ count: None,+ },+ ],+ });+ let sampled_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("sampled"),+ entries: &[+ wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Texture {+ sample_type: wgpu::TextureSampleType::Float { filterable: true },+ view_dimension: wgpu::TextureViewDimension::D2,+ multisampled: false,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 1,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),+ count: None,+ },+ ],+ });+ let uniform_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("uniforms"),+ entries: &[wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Uniform,+ has_dynamic_offset: true,+ min_binding_size: NonZeroU64::new(UNIFORM_SIZE),+ },+ count: None,+ }],+ });+ let module = |label, src: &str| {+ device.create_shader_module(wgpu::ShaderModuleDescriptor {+ label: Some(label),+ source: wgpu::ShaderSource::Wgsl(src.into()),+ })+ };+ let stamp_module =+ module("stamp", concat!(include_str!("shaders/blend.wgsl"), include_str!("shaders/stamp.wgsl")));+ let composite_module =+ module("composite", concat!(include_str!("shaders/blend.wgsl"), include_str!("shaders/composite.wgsl")));+ let display_module = module("display", include_str!("shaders/display.wgsl"));+ let surround_module = module("surround", include_str!("shaders/surround.wgsl"));+ let backdrop_module = module("backdrop", include_str!("shaders/backdrop.wgsl"));+ let transform_module = module("transform", include_str!("shaders/transform.wgsl"));+ let selection_module = module("selection", include_str!("shaders/selection.wgsl"));+ let layout = |label, groups: &[Option<&wgpu::BindGroupLayout>]| {+ device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {+ label: Some(label),+ bind_group_layouts: groups,+ immediate_size: 0,+ })+ };+ let stamp_layout = layout("stamp", &[Some(&uniform_layout), Some(&brush_layout)]);+ let composite_layout = layout("composite", &[Some(&quad_layout), Some(&uniform_layout)]);+ let display_pipeline_layout = layout("display", &[Some(&sampled_layout), Some(&uniform_layout)]);+ let lut_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("colour table"),+ entries: &[+ wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Texture {+ sample_type: wgpu::TextureSampleType::Float { filterable: true },+ view_dimension: wgpu::TextureViewDimension::D3,+ multisampled: false,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 1,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),+ count: None,+ },+ ],+ });+ let display_lut_layout =+ layout("display with a table", &[Some(&sampled_layout), Some(&uniform_layout), Some(&lut_layout)]);+ // a transform's copy, its sampler and the selection+ let transform_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("transform source"),+ entries: &[+ // filtered where an adjustment samples it+ wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Texture {+ sample_type: wgpu::TextureSampleType::Float { filterable: true },+ view_dimension: wgpu::TextureViewDimension::D2,+ multisampled: false,+ },+ count: None,+ },+ sampler_entry(1),+ tex_entry(2),+ ],+ });+ let transform_pipeline_layout = layout("transform", &[Some(&transform_layout), Some(&uniform_layout)]);+ let before_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("adjustment copy"),+ entries: &[tex_entry(0), tex_entry(1)],+ });+ let filter_pipeline_layout =+ layout("adjustment", &[Some(&transform_layout), Some(&uniform_layout), Some(&before_layout)]);+ let filter_module = module("filter", include_str!("shaders/filter.wgsl"));+ let filters = FILTER_PASSES+ .iter()+ .map(|&fs| {+ let pipeline = blended_pipeline(+ device,+ &filter_pipeline_layout,+ &filter_module,+ fs,+ ("vs_filter", fs),+ LAYER_FORMAT,+ None,+ );+ (fs, pipeline)+ })+ .collect();+ let liquify_module = module("liquify", include_str!("shaders/liquify.wgsl"));+ let liquify_layout = layout("liquify", &[Some(&uniform_layout)]);+ let liquify_pipeline = |label: &str, blend: wgpu::BlendState| {+ blended_pipeline(+ device,+ &liquify_layout,+ &liquify_module,+ label,+ ("vs_liquify", "fs_liquify"),+ LIQUIFY_FORMAT,+ Some(blend),+ )+ };+ let liquify_add = liquify_pipeline("liquify add", ADD);+ let liquify_fade = liquify_pipeline("liquify fade", FADE);+ let surround_pipeline_layout = layout("surround", &[Some(&uniform_layout)]);+ let storage = |binding| wgpu::BindGroupLayoutEntry {+ binding,+ visibility: wgpu::ShaderStages::COMPUTE,+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Storage { read_only: false },+ has_dynamic_offset: false,+ min_binding_size: None,+ },+ count: None,+ };+ let smudge_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("smudge"),+ entries: &[+ wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::COMPUTE,+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Uniform,+ has_dynamic_offset: true,+ min_binding_size: NonZeroU64::new(SMUDGE_UNIFORM_SIZE),+ },+ count: None,+ },+ storage(1),+ storage(2),+ storage(3),+ wgpu::BindGroupLayoutEntry {+ binding: 4,+ visibility: wgpu::ShaderStages::COMPUTE,+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Storage { read_only: true },+ has_dynamic_offset: false,+ min_binding_size: None,+ },+ count: None,+ },+ ],+ });+ let smudge_module =+ module("smudge", concat!(include_str!("shaders/blend.wgsl"), include_str!("shaders/smudge.wgsl")));+ let smudge_pipeline_layout = layout("smudge", &[Some(&smudge_layout), Some(&brush_layout)]);+ let compute = |label, entry| {+ device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {+ label: Some(label),+ layout: Some(&smudge_pipeline_layout),+ module: &smudge_module,+ entry_point: Some(entry),+ compilation_options: Default::default(),+ cache: None,+ })+ };+ let smudge_carry = compute("smudge carry", "cs_carry");+ let smudge_deposit = compute("smudge deposit", "cs_deposit");++ let overlay_module = module("overlay", include_str!("shaders/overlay.wgsl"));+ let stamp_pipeline = |label, blend| {+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some(label),+ layout: Some(&stamp_layout),+ vertex: wgpu::VertexState {+ module: &stamp_module,+ entry_point: Some("vs_stamp"),+ compilation_options: Default::default(),+ buffers: &[Some(wgpu::VertexBufferLayout {+ array_stride: size_of::<StampInstance>() as u64,+ step_mode: wgpu::VertexStepMode::Instance,+ attributes: &STAMP_ATTRIBUTES,+ })],+ },+ primitive: wgpu::PrimitiveState::default(),+ depth_stencil: None,+ multisample: wgpu::MultisampleState::default(),+ fragment: Some(wgpu::FragmentState {+ module: &stamp_module,+ entry_point: Some("fs_stamp"),+ compilation_options: Default::default(),+ targets: &[Some(wgpu::ColorTargetState {+ format: STROKE_FORMAT,+ blend: Some(blend),+ write_mask: wgpu::ColorWrites::ALL,+ })],+ }),+ multiview_mask: None,+ cache: None,+ })+ };+ let stamp = stamp_pipeline("stamp", PREMULTIPLIED_OVER);+ let stamp_max = stamp_pipeline("stamp max", MAXIMUM);+ // stamps adding towards their transfer: the paint (scaled by it) over what is there, kept+ // by what the stamp covers (a second colour out of the shader)+ let stamp_capped = device.features().contains(wgpu::Features::DUAL_SOURCE_BLENDING).then(|| {+ let capped_module = module(+ "stamp capped",+ concat!(+ "enable dual_source_blending;\n",+ include_str!("shaders/blend.wgsl"),+ include_str!("shaders/stamp.wgsl"),+ include_str!("shaders/stamp_capped.wgsl")+ ),+ );+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some("stamp capped"),+ layout: Some(&stamp_layout),+ vertex: wgpu::VertexState {+ module: &capped_module,+ entry_point: Some("vs_stamp"),+ compilation_options: Default::default(),+ buffers: &[Some(wgpu::VertexBufferLayout {+ array_stride: size_of::<StampInstance>() as u64,+ step_mode: wgpu::VertexStepMode::Instance,+ attributes: &STAMP_ATTRIBUTES,+ })],+ },+ primitive: wgpu::PrimitiveState::default(),+ depth_stencil: None,+ multisample: wgpu::MultisampleState::default(),+ fragment: Some(wgpu::FragmentState {+ module: &capped_module,+ entry_point: Some("fs_stamp_capped"),+ compilation_options: Default::default(),+ targets: &[Some(wgpu::ColorTargetState {+ format: STROKE_FORMAT,+ blend: Some(TOWARDS_TRANSFER),+ write_mask: wgpu::ColorWrites::ALL,+ })],+ }),+ multiview_mask: None,+ cache: None,+ })+ });+ let full = |label, entry, blend| {+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some(label),+ layout: Some(&composite_layout),+ vertex: wgpu::VertexState {+ module: &composite_module,+ entry_point: Some("vs_full"),+ compilation_options: Default::default(),+ buffers: &[],+ },+ primitive: wgpu::PrimitiveState::default(),+ depth_stencil: None,+ multisample: wgpu::MultisampleState::default(),+ fragment: Some(wgpu::FragmentState {+ module: &composite_module,+ entry_point: Some(entry),+ compilation_options: Default::default(),+ targets: &[Some(wgpu::ColorTargetState {+ format: LAYER_FORMAT,+ blend,+ write_mask: wgpu::ColorWrites::ALL,+ })],+ }),+ multiview_mask: None,+ cache: None,+ })+ };+ Pipelines {+ layer: full("layer", "fs_layer", Some(PREMULTIPLIED_OVER)),+ blend: full("blend", "fs_blend", None),+ solid: full("solid", "fs_solid", None),+ commit_paint: full("commit paint", "fs_commit", Some(PREMULTIPLIED_OVER)),+ commit_erase: full("commit erase", "fs_commit", Some(DESTINATION_OUT)),+ commit_locked: full("commit locked", "fs_commit_locked", None),+ transform: blended_pipeline(+ device,+ &transform_pipeline_layout,+ &transform_module,+ "transform",+ ("vs_transform", "fs_transform"),+ LAYER_FORMAT,+ Some(PREMULTIPLIED_OVER),+ ),+ transform_static: sampled_pipeline(+ device,+ &transform_pipeline_layout,+ &transform_module,+ "transform static",+ "vs_transform",+ "fs_static",+ LAYER_FORMAT,+ ),+ transform_layout,+ before_layout,+ filters,+ liquify_add,+ liquify_fade,+ mesh: device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some("warp"),+ layout: Some(&transform_pipeline_layout),+ vertex: wgpu::VertexState {+ module: &transform_module,+ entry_point: Some("vs_mesh"),+ compilation_options: Default::default(),+ buffers: &[Some(wgpu::VertexBufferLayout {+ array_stride: size_of::<[f32; 4]>() as u64,+ step_mode: wgpu::VertexStepMode::Vertex,+ attributes: &MESH_ATTRIBUTES,+ })],+ },+ primitive: wgpu::PrimitiveState::default(),+ depth_stencil: None,+ multisample: wgpu::MultisampleState::default(),+ fragment: Some(wgpu::FragmentState {+ module: &transform_module,+ entry_point: Some("fs_mesh"),+ compilation_options: Default::default(),+ targets: &[Some(wgpu::ColorTargetState {+ format: LAYER_FORMAT,+ blend: Some(PREMULTIPLIED_OVER),+ write_mask: wgpu::ColorWrites::ALL,+ })],+ }),+ multiview_mask: None,+ cache: None,+ }),+ thumb: sampled_pipeline(+ device,+ &display_pipeline_layout,+ &display_module,+ "thumbnail",+ "vs_thumb",+ "fs_thumb",+ LAYER_FORMAT,+ ),+ stamp,+ stamp_max,+ stamp_capped,+ smudge_layout,+ smudge_carry,+ smudge_deposit,+ lut_layout,+ display_lut_layout,+ quad_layout,+ brush_layout,+ sampled_layout,+ uniform_layout,+ display_module,+ display_pipeline_layout,+ display: HashMap::new(),+ surround_module,+ surround_pipeline_layout,+ surround: HashMap::new(),+ stamp_layout,+ overlay_module,+ overlay: HashMap::new(),+ selection_module,+ selection: HashMap::new(),+ backdrop_module,+ blur: HashMap::new(),+ frost: HashMap::new(),+ }+ }+}++/// The adjustment passes, by their fragment entry in `filter.wgsl`.+/// A copy of `rect` of the layer-format texture `source`, for an undo step.+fn region_copy(+ device: &wgpu::Device,+ encoder: &mut wgpu::CommandEncoder,+ source: &wgpu::Texture,+ rect: IRect,+) -> wgpu::Texture {+ let texture = device.create_texture(&wgpu::TextureDescriptor {+ label: Some("undo"),+ size: extent(rect.width(), rect.height()),+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: LAYER_FORMAT,+ usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST,+ view_formats: &[],+ });+ encoder.copy_texture_to_texture(+ copy_at(source, rect.x0, rect.y0),+ copy_at(&texture, 0, 0),+ extent(rect.width(), rect.height()),+ );+ texture+}++/// The liquify field: two half floats of offset a pixel.+const LIQUIFY_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rg16Float;++/// Added to what is there (liquify stamps into the field).+const ADD: wgpu::BlendState = wgpu::BlendState {+ color: wgpu::BlendComponent {+ src_factor: wgpu::BlendFactor::One,+ dst_factor: wgpu::BlendFactor::One,+ operation: wgpu::BlendOperation::Add,+ },+ alpha: wgpu::BlendComponent {+ src_factor: wgpu::BlendFactor::One,+ dst_factor: wgpu::BlendFactor::One,+ operation: wgpu::BlendOperation::Add,+ },+};++/// What is there kept by one minus what is drawn's alpha (reconstruct fading the field).+const FADE: wgpu::BlendState = wgpu::BlendState {+ color: wgpu::BlendComponent {+ src_factor: wgpu::BlendFactor::Zero,+ dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,+ operation: wgpu::BlendOperation::Add,+ },+ alpha: wgpu::BlendComponent {+ src_factor: wgpu::BlendFactor::Zero,+ dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,+ operation: wgpu::BlendOperation::Add,+ },+};++const FILTER_PASSES: [&str; 17] = [+ "fs_glitch",+ "fs_clone",+ "fs_liquified",+ "fs_hsb",+ "fs_down",+ "fs_blur",+ "fs_up",+ "fs_sharpen",+ "fs_noise",+ "fs_streak",+ "fs_zoom",+ "fs_chroma",+ "fs_halftone",+ "fs_bloom",+ "fs_curves",+ "fs_gradient",+ "fs_balance",+];++/// A full-screen pipeline (no vertex buffers) with its blending.+fn blended_pipeline(+ device: &wgpu::Device,+ layout: &wgpu::PipelineLayout,+ module: &wgpu::ShaderModule,+ label: &str,+ (vs, fs): (&str, &str),+ format: wgpu::TextureFormat,+ blend: Option<wgpu::BlendState>,+) -> wgpu::RenderPipeline {+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some(label),+ layout: Some(layout),+ vertex: wgpu::VertexState {+ module,+ entry_point: Some(vs),+ compilation_options: Default::default(),+ buffers: &[],+ },+ primitive: wgpu::PrimitiveState::default(),+ depth_stencil: None,+ multisample: wgpu::MultisampleState::default(),+ fragment: Some(wgpu::FragmentState {+ module,+ entry_point: Some(fs),+ compilation_options: Default::default(),+ targets: &[Some(wgpu::ColorTargetState { format, blend, write_mask: wgpu::ColorWrites::ALL })],+ }),+ multiview_mask: None,+ cache: None,+ })+}++fn sampled_pipeline(+ device: &wgpu::Device,+ layout: &wgpu::PipelineLayout,+ module: &wgpu::ShaderModule,+ label: &str,+ vs: &str,+ fs: &str,+ format: wgpu::TextureFormat,+) -> wgpu::RenderPipeline {+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some(label),+ layout: Some(layout),+ vertex: wgpu::VertexState {+ module,+ entry_point: Some(vs),+ compilation_options: Default::default(),+ buffers: &[],+ },+ primitive: wgpu::PrimitiveState::default(),+ depth_stencil: None,+ multisample: wgpu::MultisampleState::default(),+ fragment: Some(wgpu::FragmentState {+ module,+ entry_point: Some(fs),+ compilation_options: Default::default(),+ targets: &[Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL })],+ }),+ multiview_mask: None,+ cache: None,+ })+}++/// One frame's uniforms, a slot per draw.+#[derive(Default)]+struct UniformData {+ data: Vec<u8>,+}++impl UniformData {+ /// Adds `value` in the next slot and returns its dynamic offset.+ fn push<T: bytemuck::Pod>(&mut self, value: &T) -> u32 {+ let offset = self.data.len();+ self.data.extend_from_slice(bytemuck::bytes_of(value));+ self.data.resize(offset + SLOT as usize, 0);+ u32::try_from(offset).unwrap_or(0)+ }+}++fn texture(device: &wgpu::Device, label: &str, width: u32, height: u32, format: wgpu::TextureFormat) -> wgpu::Texture {+ device.create_texture(&wgpu::TextureDescriptor {+ label: Some(label),+ size: extent(width, height),+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format,+ usage: wgpu::TextureUsages::TEXTURE_BINDING+ | wgpu::TextureUsages::RENDER_ATTACHMENT+ | wgpu::TextureUsages::COPY_SRC+ | wgpu::TextureUsages::COPY_DST,+ view_formats: &[],+ })+}++/// A pair of textures layers are composited onto, the result in one of them.+/// The smallest box [x0, y0, x1, y1) around a thumbnail's pixels with any alpha.+fn alpha_bounds(t: &Thumbnail) -> Option<[u32; 4]> {+ painted_bounds(t, |[_, _, _, alpha]| alpha > 0)+}++/// Where a mask's thumbnail is painted on: what isn't white.+fn ink_bounds(t: &Thumbnail) -> Option<[u32; 4]> {+ painted_bounds(t, |[r, ..]| r < 255)+}++/// The pixels of a thumbnail that `painted` holds for, as [x0, y0, x1, y1); none if none.+fn painted_bounds(t: &Thumbnail, painted: impl Fn([u8; 4]) -> bool) -> Option<[u32; 4]> {+ let mut b: Option<[u32; 4]> = None;+ for (i, px) in t.rgba.as_chunks::<4>().0.iter().enumerate() {+ if painted(*px) {+ let (x, y) = ((i as u32) % t.width.max(1), (i as u32) / t.width.max(1));+ b = Some(match b {+ Some([x0, y0, x1, y1]) => [x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1)],+ None => [x, y, x + 1, y + 1],+ });+ }+ }+ b+}++/// Part [x0, y0, x1, y1) of a thumbnail.+fn crop(t: &Thumbnail, [x0, y0, x1, y1]: [u32; 4]) -> Thumbnail {+ let row = t.width as usize * 4;+ let mut rgba = Vec::with_capacity((x1 - x0) as usize * (y1 - y0) as usize * 4);+ for y in y0..y1 {+ let start = y as usize * row + x0 as usize * 4;+ rgba.extend_from_slice(t.rgba.get(start..start + (x1 - x0) as usize * 4).unwrap_or_default());+ }+ Thumbnail { width: x1 - x0, height: y1 - y0, rgba }+}++struct Stack<'a> {+ textures: &'a [wgpu::Texture; 2],+ views: &'a [wgpu::TextureView; 2],+}++impl Stack<'_> {+ /// Leaves the result in the first texture (where `current` says it is, within `rect`).+ fn settle(&self, encoder: &mut wgpu::CommandEncoder, rect: IRect, current: usize) {+ if current == 1 {+ let [first, second] = self.textures;+ encoder.copy_texture_to_texture(+ copy_at(second, rect.x0, rect.y0),+ copy_at(first, rect.x0, rect.y0),+ extent(rect.width(), rect.height()),+ );+ }+ }+}++fn quad_bind(+ device: &wgpu::Device,+ layout: &wgpu::BindGroupLayout,+ views: [&wgpu::TextureView; 5],+ grains: &wgpu::TextureView,+ grain_sampler: &wgpu::Sampler,+) -> wgpu::BindGroup {+ let [a, b, c, d, mask] = views;+ device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("layer, stroke, clip, backdrop, grains"),+ layout,+ entries: &[+ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(a) },+ wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(b) },+ wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(c) },+ wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(d) },+ wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(grains) },+ wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::Sampler(grain_sampler) },+ wgpu::BindGroupEntry { binding: 6, resource: wgpu::BindingResource::TextureView(mask) },+ ],+ })+}++/// How many images of the user's own each of the shape and grain arrays holds at once.+const SOURCE_SLOTS: usize = 8;++/// The spare layers of a brush image array, after the shipped images: which image of the user's+/// own each holds, and when it was last used (the longest unused gives way).+struct SourceSlots {+ first: u32,+ held: Vec<(u64, u64)>,+ clock: u64,+}++impl SourceSlots {+ fn after(shipped: usize) -> SourceSlots {+ SourceSlots { first: shipped as u32, held: Vec::new(), clock: 0 }+ }++ /// The layer of `texture` holding `source`, put there if it isn't.+ fn layer(&mut self, gpu: &Gpu, texture: &wgpu::Texture, source: &Source) -> u32 {+ self.clock += 1;+ let clock = self.clock;+ if let Some(i) = self.held.iter().position(|&(id, _)| id == source.id) {+ if let Some(slot) = self.held.get_mut(i) {+ slot.1 = clock;+ }+ return self.first + i as u32;+ }+ let i = if self.held.len() < SOURCE_SLOTS {+ self.held.push((source.id, clock));+ self.held.len() - 1+ } else {+ let oldest = self.held.iter().enumerate().min_by_key(|(_, slot)| slot.1).map_or(0, |(i, _)| i);+ if let Some(slot) = self.held.get_mut(oldest) {+ *slot = (source.id, clock);+ }+ oldest+ };+ let layer = self.first + i as u32;+ write_brush_image(gpu, texture, layer, &source.pixels);+ layer+ }+}++/// Greyscale brush images as one array texture with a full mip chain (each level a 2×2 average+/// of the one above), with [`SOURCE_SLOTS`] spare layers after them.+fn brush_images(gpu: &Gpu, label: &str, images: &[GrayImage]) -> wgpu::Texture {+ let n = TEXTURE_SIZE as u32;+ let texture = gpu.device.create_texture(&wgpu::TextureDescriptor {+ label: Some(label),+ size: wgpu::Extent3d { width: n, height: n, depth_or_array_layers: (images.len() + SOURCE_SLOTS) as u32 },+ mip_level_count: n.ilog2() + 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: wgpu::TextureFormat::R8Unorm,+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,+ view_formats: &[],+ });+ for (layer, image) in images.iter().enumerate() {+ write_brush_image(gpu, &texture, layer as u32, &image.pixels);+ }+ texture+}++/// One brush image (`TEXTURE_SIZE` square) into `layer` of `texture`, every mip level.+fn write_brush_image(gpu: &Gpu, texture: &wgpu::Texture, layer: u32, pixels: &[u8]) {+ let n = TEXTURE_SIZE as u32;+ let mut level = pixels.to_vec();+ let mut size = n;+ for mip in 0..n.ilog2() + 1 {+ gpu.queue.write_texture(+ wgpu::TexelCopyTextureInfo {+ texture,+ mip_level: mip,+ origin: wgpu::Origin3d { x: 0, y: 0, z: layer },+ aspect: wgpu::TextureAspect::All,+ },+ &level,+ wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(size), rows_per_image: Some(size) },+ wgpu::Extent3d { width: size, height: size, depth_or_array_layers: 1 },+ );+ if size > 1 {+ level = half_size(&level, size as usize);+ size /= 2;+ }+ }+}++/// A square greyscale image at half the size: each pixel the average of four.+fn half_size(pixels: &[u8], size: usize) -> Vec<u8> {+ let half = size / 2;+ let at = |x: usize, y: usize| u32::from(pixels.get(y * size + x).copied().unwrap_or(0));+ let mut out = Vec::with_capacity(half * half);+ for y in 0..half {+ for x in 0..half {+ let sum = at(2 * x, 2 * y) + at(2 * x + 1, 2 * y) + at(2 * x, 2 * y + 1) + at(2 * x + 1, 2 * y + 1);+ out.push(((sum + 2) / 4) as u8);+ }+ }+ out+}++/// The stamp shader's shapes, grains and selection, and its two samplers.+fn brush_bind(+ device: &wgpu::Device,+ layout: &wgpu::BindGroupLayout,+ [shapes, grains, mask]: [&wgpu::TextureView; 3],+ [shape_sampler, grain_sampler]: [&wgpu::Sampler; 2],+) -> wgpu::BindGroup {+ device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("shapes, grains and the selection"),+ layout,+ entries: &[+ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(shapes) },+ wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(grains) },+ wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(shape_sampler) },+ wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(grain_sampler) },+ wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(mask) },+ ],+ })+}++/// A one-channel texture of coverage, `width` × `height`, from `data` (one byte a pixel).+fn coverage_texture(device: &wgpu::Device, queue: &wgpu::Queue, width: u32, height: u32, data: &[u8]) -> wgpu::Texture {+ let texture = device.create_texture(&wgpu::TextureDescriptor {+ label: Some("selection"),+ size: extent(width, height),+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: wgpu::TextureFormat::R8Unorm,+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,+ view_formats: &[],+ });+ queue.write_texture(+ wgpu::TexelCopyTextureInfo {+ texture: &texture,+ mip_level: 0,+ origin: wgpu::Origin3d::ZERO,+ aspect: wgpu::TextureAspect::All,+ },+ data,+ wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(width), rows_per_image: Some(height) },+ extent(width, height),+ );+ texture+}++/// A 3D colour table `grid` on a side (RGBA8, blue varying fastest, then green, then red) and+/// its sampler, bound for the display.+fn lut_bind(gpu: &Gpu, layout: &wgpu::BindGroupLayout, grid: u32, rgba: &[u8]) -> wgpu::BindGroup {+ let size = wgpu::Extent3d { width: grid, height: grid, depth_or_array_layers: grid };+ let texture = gpu.device.create_texture(&wgpu::TextureDescriptor {+ label: Some("colour table"),+ size,+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D3,+ format: wgpu::TextureFormat::Rgba8Unorm,+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,+ view_formats: &[],+ });+ gpu.queue.write_texture(+ wgpu::TexelCopyTextureInfo {+ texture: &texture,+ mip_level: 0,+ origin: wgpu::Origin3d::ZERO,+ aspect: wgpu::TextureAspect::All,+ },+ rgba,+ wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(4 * grid), rows_per_image: Some(grid) },+ size,+ );+ let view = texture.create_view(&wgpu::TextureViewDescriptor::default());+ let sampler = gpu.device.create_sampler(&wgpu::SamplerDescriptor {+ label: Some("colour table"),+ mag_filter: wgpu::FilterMode::Linear,+ min_filter: wgpu::FilterMode::Linear,+ ..Default::default()+ });+ gpu.device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("colour table"),+ layout,+ entries: &[+ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&view) },+ wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&sampler) },+ ],+ })+}++fn sampled_bind(+ device: &wgpu::Device,+ layout: &wgpu::BindGroupLayout,+ view: &wgpu::TextureView,+ sampler: &wgpu::Sampler,+) -> wgpu::BindGroup {+ device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("sampled"),+ layout,+ entries: &[+ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(view) },+ wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(sampler) },+ ],+ })+}++fn uniforms(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, slots: u64) -> (wgpu::Buffer, wgpu::BindGroup) {+ let buffer = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("uniforms"),+ size: slots * SLOT,+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });+ let bind = device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("uniforms"),+ layout,+ entries: &[wgpu::BindGroupEntry {+ binding: 0,+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {+ buffer: &buffer,+ offset: 0,+ size: NonZeroU64::new(UNIFORM_SIZE),+ }),+ }],+ });+ (buffer, bind)+}++/// Uniform slots for `count` smudge stamps.+fn spare_buffer(device: &wgpu::Device) -> wgpu::Buffer {+ device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("smudge spare"),+ size: 16,+ usage: wgpu::BufferUsages::STORAGE,+ mapped_at_creation: false,+ })+}++fn smudge_params(device: &wgpu::Device, count: u64) -> wgpu::Buffer {+ device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("smudge stamps"),+ size: count.max(1) * SLOT,+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ })+}++fn stamp_buffer(device: &wgpu::Device, capacity: u64) -> wgpu::Buffer {+ device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("stamps"),+ size: capacity.max(1) * size_of::<StampInstance>() as u64,+ usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ })+}++fn render_pass<'e>(+ encoder: &'e mut wgpu::CommandEncoder,+ label: &str,+ view: &wgpu::TextureView,+ load: wgpu::LoadOp<wgpu::Color>,+) -> wgpu::RenderPass<'e> {+ encoder.begin_render_pass(&wgpu::RenderPassDescriptor {+ label: Some(label),+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {+ view,+ depth_slice: None,+ resolve_target: None,+ ops: wgpu::Operations { load, store: wgpu::StoreOp::Store },+ })],+ depth_stencil_attachment: None,+ timestamp_writes: None,+ occlusion_query_set: None,+ multiview_mask: None,+ })+}++fn scissor(pass: &mut wgpu::RenderPass<'_>, r: IRect) {+ let x = u32::try_from(r.x0).unwrap_or(0);+ let y = u32::try_from(r.y0).unwrap_or(0);+ pass.set_scissor_rect(x, y, r.width(), r.height());+}++fn extent(width: u32, height: u32) -> wgpu::Extent3d {+ wgpu::Extent3d { width: width.max(1), height: height.max(1), depth_or_array_layers: 1 }+}++fn copy_at(texture: &wgpu::Texture, x: i32, y: i32) -> wgpu::TexelCopyTextureInfo<'_> {+ wgpu::TexelCopyTextureInfo {+ texture,+ mip_level: 0,+ origin: wgpu::Origin3d { x: u32::try_from(x).unwrap_or(0), y: u32::try_from(y).unwrap_or(0), z: 0 },+ aspect: wgpu::TextureAspect::All,+ }+}++fn srgb_to_linear(c: f32) -> f32 {+ if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }+}++/// Reads a texture of 4-byte pixels back from the GPU, rows top to bottom without padding.+pub fn read_texture(gpu: &Gpu, texture: &wgpu::Texture, width: u32, height: u32) -> Result<Vec<u8>, GpuError> {+ let row = width as usize * 4;+ let padded = row.div_ceil(256) * 256;+ let buffer = gpu.device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("readback"),+ size: (padded * height as usize) as u64,+ usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });+ let mut encoder = gpu.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("readback") });+ encoder.copy_texture_to_buffer(+ copy_at(texture, 0, 0),+ wgpu::TexelCopyBufferInfo {+ buffer: &buffer,+ layout: wgpu::TexelCopyBufferLayout {+ offset: 0,+ bytes_per_row: Some(padded as u32),+ rows_per_image: Some(height),+ },+ },+ extent(width, height),+ );+ gpu.queue.submit([encoder.finish()]);+ let (tx, rx) = mpsc::channel();+ buffer.slice(..).map_async(wgpu::MapMode::Read, move |r| {+ let _ = tx.send(r);+ });+ gpu.device.poll(wgpu::PollType::wait_indefinitely()).map_err(|e| GpuError::Readback(e.to_string()))?;+ rx.recv().map_err(|e| GpuError::Readback(e.to_string()))?.map_err(|e| GpuError::Readback(e.to_string()))?;+ let mapped = buffer.slice(..).get_mapped_range().map_err(|e| GpuError::Readback(e.to_string()))?;+ let mut out = Vec::with_capacity(row * height as usize);+ for chunk in mapped.chunks(padded) {+ out.extend_from_slice(chunk.get(..row).unwrap_or(chunk));+ }+ drop(mapped);+ buffer.unmap();+ Ok(out)+}diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rsnew file mode 100644index 0000000..0fb5953--- /dev/null+++ b/crates/gpu/src/lib.rs@@ -0,0 +1,107 @@+//! ProCraft's GPU renderer (wgpu): layer pixels, stroke rendering, compositing, and drawing the+//! canvas to a window surface. Layers are premultiplied RGBA8 textures the size of the canvas.+//!+//! Every blend here uses fixed-function blending or reads from a different texture than it writes:+//! nothing relies on reading the render target in the shader (Android GPUs have no portable way).++mod canvas;++use std::sync::Arc;+use std::sync::atomic::{AtomicU64, Ordering};++pub use canvas::{+ Backdrop, Canvas, DisplayLut, Filter, LiquifyMode, LiquifyStamp, Resample, SelectionLook, Stripes, StrokeStyle,+ StrokeTool, SurroundGrid, Target, Thumbnail, read_texture,+};+pub use wgpu;++#[derive(Debug, thiserror::Error)]+pub enum GpuError {+ #[error("no suitable GPU: {0}")]+ NoAdapter(String),+ #[error("GPU device: {0}")]+ Device(String),+ #[error("canvas of {0}×{1} pixels is larger than this GPU allows ({2})")]+ TooLarge(u32, u32, u32),+ #[error("surface: {0}")]+ Surface(String),+ #[error("reading pixels back: {0}")]+ Readback(String),+}++/// The device everything renders with.+pub struct Gpu {+ pub instance: wgpu::Instance,+ pub adapter: wgpu::Adapter,+ pub device: wgpu::Device,+ pub queue: wgpu::Queue,+ errors: Arc<AtomicU64>,+}++impl Gpu {+ /// A wgpu instance for this platform: Vulkan on Android, the native API elsewhere.+ pub fn instance() -> wgpu::Instance {+ let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();+ desc.backends = if cfg!(target_os = "android") { wgpu::Backends::VULKAN } else { wgpu::Backends::PRIMARY };+ wgpu::Instance::new(desc)+ }++ /// A device for offscreen work (tests, exports).+ pub fn headless() -> Result<Gpu, GpuError> {+ Gpu::create(Gpu::instance(), None)+ }++ /// A device that can present to `surface` (made from `instance`).+ pub fn for_surface(instance: wgpu::Instance, surface: &wgpu::Surface<'_>) -> Result<Gpu, GpuError> {+ Gpu::create(instance, Some(surface))+ }++ fn create(instance: wgpu::Instance, surface: Option<&wgpu::Surface<'_>>) -> Result<Gpu, GpuError> {+ let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {+ power_preference: wgpu::PowerPreference::HighPerformance,+ force_fallback_adapter: false,+ compatible_surface: surface,+ apply_limit_buckets: false,+ }))+ .map_err(|e| GpuError::NoAdapter(e.to_string()))?;+ let info = adapter.get_info();+ log::info!("GPU: {} ({:?}, driver {})", info.name, info.backend, info.driver_info);+ let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {+ label: Some("procraft"),+ // where the GPU has it, for strokes that build up only to their transfer+ required_features: adapter.features() & wgpu::Features::DUAL_SOURCE_BLENDING,+ // the adapter's own limits, so large canvases fit where the GPU allows them+ required_limits: adapter.limits(),+ memory_hints: wgpu::MemoryHints::Performance,+ ..Default::default()+ }))+ .map_err(|e| GpuError::Device(e.to_string()))?;+ log::info!(+ "GPU capped strokes (dual-source blending): {}",+ device.features().contains(wgpu::Features::DUAL_SOURCE_BLENDING)+ );+ // a validation error must never take the app down: log it instead+ let errors = Arc::new(AtomicU64::new(0));+ let counter = Arc::clone(&errors);+ device.on_uncaptured_error(Arc::new(move |e| {+ counter.fetch_add(1, Ordering::Relaxed);+ log::error!("GPU error: {e}");+ }));+ Ok(Gpu { instance, adapter, device, queue, errors })+ }++ /// GPU validation errors so far (each one is logged); tests expect none.+ pub fn errors(&self) -> u64 {+ self.errors.load(Ordering::Relaxed)+ }++ /// Whether strokes that build up only to their transfer (the uniformed glaze) can be drawn+ /// exactly (with dual-source blending); else their transfer is taken into each stamp.+ pub fn caps_transfer(&self) -> bool {+ self.device.features().contains(wgpu::Features::DUAL_SOURCE_BLENDING)+ }++ pub fn max_texture_size(&self) -> u32 {+ self.device.limits().max_texture_dimension_2d+ }+}diff --git a/crates/gpu/src/shaders/backdrop.wgsl b/crates/gpu/src/shaders/backdrop.wgslnew file mode 100644index 0000000..53bd796--- /dev/null+++ b/crates/gpu/src/shaders/backdrop.wgsl@@ -0,0 +1,64 @@+// Frosted panels: what is behind a panel, drawn small, blurred, and put back in its place for a+// translucent panel to be drawn over.++struct BackdropUniform {+ // blur: (step x, step y in 0..1 of the source, sigma in texels, radius in texels)+ // frost: the region (left, top, right, bottom) in target pixels+ v0: vec4<f32>,+ // frost: (corner radius, target width, target height, target pixels per source texel)+ v1: vec4<f32>,+ // frost: (how much it shows, 0..1, as the panel fades in and out; unused)+ v2: vec4<f32>,+}++@group(0) @binding(0) var source: texture_2d<f32>;+@group(0) @binding(1) var smp: sampler;+@group(1) @binding(0) var<uniform> u: BackdropUniform;++@vertex+fn vs_full(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {+ let uv = vec2<f32>(f32((vi << 1u) & 2u), f32(vi & 2u));+ return vec4<f32>(uv * 2.0 - 1.0, 0.0, 1.0);+}++// One direction of a Gaussian blur, from a source the size of the target.+@fragment+fn fs_blur(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let uv = pos.xy / vec2<f32>(textureDimensions(source));+ let sigma = max(u.v0.z, 0.5);+ let radius = i32(u.v0.w);+ var sum = vec4<f32>(0.0);+ var total = 0.0;+ for (var i = -radius; i <= radius; i++) {+ let x = f32(i);+ let w = exp(-0.5 * x * x / (sigma * sigma));+ sum += textureSampleLevel(source, smp, uv + u.v0.xy * x, 0.0) * w;+ total += w;+ }+ return sum / total;+}++@vertex+fn vs_frost(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {+ var corners = array<vec2<f32>, 6>(+ vec2<f32>(0.0, 0.0), vec2<f32>(1.0, 0.0), vec2<f32>(1.0, 1.0),+ vec2<f32>(0.0, 0.0), vec2<f32>(1.0, 1.0), vec2<f32>(0.0, 1.0),+ );+ // a pixel beyond the region, for its smoothed edge+ let p = mix(u.v0.xy - 1.0, u.v0.zw + 1.0, corners[vi % 6u]);+ return vec4<f32>(p.x / u.v1.y * 2.0 - 1.0, 1.0 - p.y / u.v1.z * 2.0, 0.0, 1.0);+}++// The blurred scene inside the rounded region, its edge smoothed over a pixel.+@fragment+fn fs_frost(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let centre = (u.v0.xy + u.v0.zw) * 0.5;+ let half = max((u.v0.zw - u.v0.xy) * 0.5, vec2<f32>(0.0));+ let r = clamp(u.v1.x, 0.0, min(half.x, half.y));+ let q = abs(pos.xy - centre) - (half - vec2<f32>(r));+ let d = length(max(q, vec2<f32>(0.0))) + min(max(q.x, q.y), 0.0) - r;+ let cover = clamp(0.5 - d, 0.0, 1.0) * clamp(u.v2.x, 0.0, 1.0);+ let uv = pos.xy / (u.v1.w * vec2<f32>(textureDimensions(source)));+ let c = textureSampleLevel(source, smp, uv, 0.0);+ return vec4<f32>(c.rgb * cover, cover);+}diff --git a/crates/gpu/src/shaders/blend.wgsl b/crates/gpu/src/shaders/blend.wgslnew file mode 100644index 0000000..929997d--- /dev/null+++ b/crates/gpu/src/shaders/blend.wgsl@@ -0,0 +1,158 @@+// Blend functions on straight colour, shared by the shaders that blend (prepended to them):+// the separable and non-separable modes as usually defined for compositing, numbered as the+// layers' blend modes are.++// How much of a grain the paint takes when pressed into it at `press` (0..1): what stands above+// a level that sinks as the pen presses harder, nothing at no pressure and all of it at full,+// the grain's highest parts first.+const PRESS_SOFT: f32 = 0.08;+fn pressed_in(grain: f32, press: f32) -> f32 {+ let level = mix(1.0 + PRESS_SOFT, PRESS_SOFT, clamp(press, 0.0, 1.0));+ return smoothstep(level - PRESS_SOFT, level + PRESS_SOFT, grain);+}++// a grain read unfiltered: the grain's own images are a quarter of the size of what they stand+// for, so the finer texels a pixel would land on (four to each of ours, tied to the grain so they+// move with it) are made up around the value read+fn sharp_grain(v: f32, uv: vec2<f32>) -> f32 {+ let cell = floor(uv * 1024.0);+ let n = fract(sin(dot(cell, vec2<f32>(12.9898, 78.233))) * 43758.547);+ return clamp(v + (n - 0.5) * 0.22, 0.0, 1.0);+}++fn blend_rgb(cb: vec3<f32>, cs: vec3<f32>, mode: u32) -> vec3<f32> {+ switch (mode) {+ case 1u: { return cb * cs; }+ case 2u: { return min(cb, cs); }+ case 3u: { return vec3<f32>(burn(cb.x, cs.x), burn(cb.y, cs.y), burn(cb.z, cs.z)); }+ case 4u: { return max(cb + cs - 1.0, vec3<f32>(0.0)); }+ case 5u: { return select(cb, cs, lum(cs) < lum(cb)); }+ case 6u: { return max(cb, cs); }+ case 7u: { return cb + cs - cb * cs; }+ case 8u: { return vec3<f32>(dodge(cb.x, cs.x), dodge(cb.y, cs.y), dodge(cb.z, cs.z)); }+ case 9u: { return min(cb + cs, vec3<f32>(1.0)); }+ case 10u: { return select(cb, cs, lum(cs) > lum(cb)); }+ case 11u: { return vec3<f32>(hard(cs.x, cb.x), hard(cs.y, cb.y), hard(cs.z, cb.z)); }+ case 12u: { return vec3<f32>(soft(cb.x, cs.x), soft(cb.y, cs.y), soft(cb.z, cs.z)); }+ case 13u: { return vec3<f32>(hard(cb.x, cs.x), hard(cb.y, cs.y), hard(cb.z, cs.z)); }+ case 14u: { return vec3<f32>(vivid(cb.x, cs.x), vivid(cb.y, cs.y), vivid(cb.z, cs.z)); }+ case 15u: { return clamp(cb + 2.0 * cs - 1.0, vec3<f32>(0.0), vec3<f32>(1.0)); }+ case 16u: { return vec3<f32>(pin(cb.x, cs.x), pin(cb.y, cs.y), pin(cb.z, cs.z)); }+ case 17u: { return select(vec3<f32>(0.0), vec3<f32>(1.0), cb + cs >= vec3<f32>(1.0)); }+ case 18u: { return abs(cb - cs); }+ case 19u: { return cb + cs - 2.0 * cb * cs; }+ case 20u: { return max(cb - cs, vec3<f32>(0.0)); }+ case 21u: { return vec3<f32>(divide(cb.x, cs.x), divide(cb.y, cs.y), divide(cb.z, cs.z)); }+ case 22u: { return set_lum(set_sat(cs, sat(cb)), lum(cb)); }+ case 23u: { return set_lum(set_sat(cb, sat(cs)), lum(cb)); }+ case 24u: { return set_lum(cs, lum(cb)); }+ case 25u: { return set_lum(cb, lum(cs)); }+ // shade, on straight colour (the layers' own is in `blend`)+ case 26u: { return min(cb, cs); }+ default: { return cs; }+ }+}++fn burn(b: f32, s: f32) -> f32 {+ if (b >= 1.0) { return 1.0; }+ if (s <= 0.0) { return 0.0; }+ return 1.0 - min(1.0, (1.0 - b) / s);+}++fn dodge(b: f32, s: f32) -> f32 {+ if (b <= 0.0) { return 0.0; }+ if (s >= 1.0) { return 1.0; }+ return min(1.0, b / (1.0 - s));+}++// hard light of `s` over `b` (overlay is hard light with the two swapped)+fn hard(b: f32, s: f32) -> f32 {+ if (s <= 0.5) { return b * 2.0 * s; }+ let t = 2.0 * s - 1.0;+ return b + t - b * t;+}++fn soft(b: f32, s: f32) -> f32 {+ if (s <= 0.5) {+ return b - (1.0 - 2.0 * s) * b * (1.0 - b);+ }+ var d = sqrt(b);+ if (b <= 0.25) {+ d = ((16.0 * b - 12.0) * b + 4.0) * b;+ }+ return b + (2.0 * s - 1.0) * (d - b);+}++fn vivid(b: f32, s: f32) -> f32 {+ if (s <= 0.5) { return burn(b, 2.0 * s); }+ return dodge(b, 2.0 * (s - 0.5));+}++fn pin(b: f32, s: f32) -> f32 {+ if (s <= 0.5) { return min(b, 2.0 * s); }+ return max(b, 2.0 * s - 1.0);+}++fn divide(b: f32, s: f32) -> f32 {+ if (s <= 0.0) { return select(0.0, 1.0, b > 0.0); }+ return min(1.0, b / s);+}++fn lum(c: vec3<f32>) -> f32 {+ return dot(c, vec3<f32>(0.3, 0.59, 0.11));+}++fn clip_color(c: vec3<f32>) -> vec3<f32> {+ let l = lum(c);+ let n = min(c.x, min(c.y, c.z));+ let x = max(c.x, max(c.y, c.z));+ var r = c;+ if (n < 0.0) {+ r = l + (r - l) * l / max(l - n, 1e-6);+ }+ if (x > 1.0) {+ r = l + (r - l) * (1.0 - l) / max(x - l, 1e-6);+ }+ return r;+}++fn set_lum(c: vec3<f32>, l: f32) -> vec3<f32> {+ return clip_color(c + (l - lum(c)));+}++fn sat(c: vec3<f32>) -> f32 {+ return max(c.x, max(c.y, c.z)) - min(c.x, min(c.y, c.z));+}++fn set_sat(c: vec3<f32>, s: f32) -> vec3<f32> {+ let n = min(c.x, min(c.y, c.z));+ let x = max(c.x, max(c.y, c.z));+ if (x <= n) {+ return vec3<f32>(0.0);+ }+ return (c - n) * s / (x - n);+}++// one value blended with another: a grey through the colour blend+fn blend_value(b: f32, s: f32, mode: u32) -> f32 {+ return blend_rgb(vec3<f32>(b), vec3<f32>(s), mode).x;+}++// coverage `a` and grain `g` combined by the grain's blend mode `mode`, as deep as `depth`: two+// height-like modes of the grain's own (27: the coverage raised twelvefold, less the grain; 28:+// the same or as much again over the grain's light), normal laying the coverage over the grain,+// and every other mode by the blend mode's own rule+fn grain_combine(a: f32, g: f32, depth: f32, mode: u32) -> f32 {+ let h = 12.0 * a * depth;+ if (mode == 27u) {+ return clamp(h - g, 0.0, 1.0);+ }+ if (mode == 28u) {+ return clamp(max(h * (1.0 - g), clamp(h - g, 0.0, 1.0)), 0.0, 1.0);+ }+ var blended = g + a * (1.0 - g);+ if (mode != 0u) {+ blended = clamp(blend_value(a, g, mode), 0.0, 1.0);+ }+ return mix(a, blended, depth);+}diff --git a/crates/gpu/src/shaders/composite.wgsl b/crates/gpu/src/shaders/composite.wgslnew file mode 100644index 0000000..74baa9c--- /dev/null+++ b/crates/gpu/src/shaders/composite.wgsl@@ -0,0 +1,238 @@+// Layer compositing, blend modes and stroke commits. Every texture here is the canvas's size, so+// pixels are read with textureLoad at the fragment's own position: no filtering, no coordinates.+// Colours are premultiplied; blend modes work on straight colour (separable and non-separable+// modes as usually defined for compositing).++struct LayerUniform {+ opacity: f32,+ // 0: no stroke on this layer, 1: the stroke paints, 2: it erases, 3: it paints alpha-locked+ stroke_mode: u32,+ stroke_opacity: f32,+ blend: u32,+ // 1: multiply by the clip base's alpha+ clipped: u32,+ // the stroke's texturized grain: -1 for none, else a layer of `grains`+ grain: i32,+ grain_scale: f32,+ grain_depth: f32,+ // premultiplied colour for fs_solid+ solid: vec4<f32>,+ // the stroke's wet edges (0..1, negative as a preview draws them) and burnt edges (0..1), its+ // alpha threshold (negative for none), and its grain's brightness and contrast (-1..1)+ wet: f32,+ burnt: f32,+ threshold: f32,+ grain_brightness: f32,+ grain_contrast: f32,+ // 1: the layer shows through its mask (mask_tex); 1: the stroke being drawn is on the mask+ masked: f32,+ stroke_on_mask: f32,+ // how the stroke blends into the layer: a blend mode's number (0: normal)+ stroke_blend: u32,+ // an onion skin's colour (rgb) and how far towards it the layer goes (a)+ tint: vec4<f32>,+ // the stroke's texturized grain turned, radians, and how it and the burnt edges combine with+ // the stroke (blend modes' numbers)+ grain_rotation: f32,+ grain_blend: u32,+ burnt_blend: u32,+ // 1: the grain read unfiltered (sharp)+ grain_sharp: f32,+}++@group(0) @binding(0) var layer_tex: texture_2d<f32>;+@group(0) @binding(1) var stroke_tex: texture_2d<f32>;+@group(0) @binding(2) var clip_tex: texture_2d<f32>;+@group(0) @binding(3) var backdrop_tex: texture_2d<f32>;+@group(0) @binding(4) var grains: texture_2d_array<f32>;+@group(0) @binding(5) var grain_smp: sampler;+@group(0) @binding(6) var mask_tex: texture_2d<f32>;+@group(1) @binding(0) var<uniform> lu: LayerUniform;++// one triangle covering the target+@vertex+fn vs_full(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {+ let uv = vec2<f32>(f32((vi << 1u) & 2u), f32(vi & 2u));+ return vec4<f32>(uv * 2.0 - 1.0, 0.0, 1.0);+}++// the stroke's coverage at p moved by o, held at the edges+fn stroke_alpha(p: vec2<i32>, o: vec2<i32>) -> f32 {+ let dims = vec2<i32>(textureDimensions(stroke_tex));+ return textureLoad(stroke_tex, clamp(p + o, vec2<i32>(0), dims - 1), 0).a;+}++// a grain's value made lighter or darker and of more or less contrast+fn grain_look(g: f32) -> f32 {+ return clamp((g - 0.5) * (1.0 + lu.grain_contrast) + 0.5 + lu.grain_brightness, 0.0, 1.0);+}++// the stroke at a pixel, and how much its burnt edges show there+struct StrokePixel {+ s: vec4<f32>,+ burn: f32,+}++// the stroke at a pixel: its build-up, its edges, the paper grain fixed to the canvas, its+// threshold and its opacity+fn stroke_pixel(p: vec2<i32>) -> StrokePixel {+ var s = textureLoad(stroke_tex, p, 0);+ if (lu.wet < 0.0 && s.a > 0.0) {+ // a preview: how much of an edge the pixel is (its coverage above its neighbours' a few+ // pixels away), the edges a little stronger and the inside as it is (as measured: at+ // full, a wide brush's rim 4% stronger, its middle and a thin line unchanged)+ let d = 3;+ let around = 0.25 * (stroke_alpha(p, vec2<i32>(d, 0)) + stroke_alpha(p, vec2<i32>(-d, 0)) + stroke_alpha(p, vec2<i32>(0, d)) + stroke_alpha(p, vec2<i32>(0, -d)));+ let edge = clamp((s.a - around) * 2.0, 0.0, 1.0);+ let wet_a = min(s.a * (1.0 - lu.wet * 0.1 * edge), 1.0);+ s = s * (wet_a / s.a);+ } else if (lu.wet > 0.0 && s.a > 0.0) {+ // on the canvas the paint pools: the coverage taken through a damped wave, which rises to+ // full where the stroke is about 0.7 (a ring where it fades out) and settles back to+ // about 0.78 where it is full; faint paint fades+ let x = 4.5 * s.a;+ let pooled = 1.0 - abs(sin(x) / x);+ s = s * (mix(s.a, pooled, lu.wet) / s.a);+ }+ let built = s.a;+ if (lu.grain >= 0) {+ let at = vec2<f32>(p) + 0.5;+ let gc = cos(lu.grain_rotation);+ let gs = sin(lu.grain_rotation);+ let uv = vec2<f32>(at.x * gc - at.y * gs, at.x * gs + at.y * gc) / lu.grain_scale;+ let sharp = lu.grain_sharp > 0.5;+ let lod = select(max(log2(256.0 / lu.grain_scale), 0.0), 0.0, sharp);+ var raw = textureSampleLevel(grains, grain_smp, uv, lu.grain, lod).r;+ if (sharp) {+ raw = sharp_grain(raw, uv);+ }+ let g = grain_look(raw);+ // the coverage and the grain combined by the grain's blend mode, as deep as it says, and+ // only where the stroke is+ let a = grain_combine(s.a, g, lu.grain_depth, lu.grain_blend) * select(0.0, 1.0, s.a > 0.0);+ s = s * (a / max(s.a, 1e-6));+ }+ // burnt edges show where the stroke is thin: where its paper grain took paint away, or+ // without one wherever it is less than full+ var burn = 0.0;+ if (lu.burnt > 0.0 && built > 0.0) {+ burn = lu.burnt * select(1.0 - s.a, abs(built - s.a), lu.grain >= 0);+ }+ if (lu.threshold >= 0.0 && s.a > 0.0) {+ let on = select(0.0, 1.0, s.a > lu.threshold);+ s = s * (on / s.a);+ }+ return StrokePixel(s * lu.stroke_opacity, burn);+}++fn stroke_at(p: vec2<i32>) -> vec4<f32> {+ return stroke_pixel(p).s;+}++// burnt edges: the stroke's result `r` blended once more with the paint that was under it, by+// `w` (nothing shows where the layer was empty)+fn burnt(under: vec4<f32>, r: vec4<f32>, w: f32) -> vec4<f32> {+ if (w <= 0.0) {+ return r;+ }+ let b = blend(under, r, lu.burnt_blend);+ return mix(r, vec4<f32>(unpremultiply(b) * r.a, r.a), clamp(w, 0.0, 1.0));+}++// a layer with the stroke in progress on it applied+fn with_stroke(c0: vec4<f32>, p: vec2<i32>) -> vec4<f32> {+ var c = c0;+ if (lu.stroke_mode != 0u) {+ let px = stroke_pixel(p);+ let s = px.s;+ if (lu.stroke_mode == 1u) {+ c = burnt(c0, blend(c, s, lu.stroke_blend), px.burn);+ } else if (lu.stroke_mode == 2u) {+ c = c * (1.0 - s.a);+ } else {+ // recolour, keeping the layer's alpha+ let painted = burnt(c0, blend(c, s, lu.stroke_blend), px.burn);+ c = painted * (c.a / max(painted.a, 1e-6));+ }+ }+ return c;+}++// a layer as it composites: stroke, mask, clipping, opacity+fn layer_color(p: vec2<i32>) -> vec4<f32> {+ var c = textureLoad(layer_tex, p, 0);+ if (lu.stroke_on_mask < 0.5) {+ c = with_stroke(c, p);+ }+ if (lu.masked > 0.5) {+ // the mask shows the layer as much as it is light (and opaque)+ var m = textureLoad(mask_tex, p, 0);+ if (lu.stroke_on_mask > 0.5) {+ m = with_stroke(m, p);+ }+ c = c * clamp(dot(m.rgb, vec3<f32>(0.299, 0.587, 0.114)), 0.0, 1.0);+ }+ if (lu.clipped != 0u) {+ c = c * textureLoad(clip_tex, p, 0).a;+ }+ if (lu.tint.a > 0.0) {+ c = vec4<f32>(mix(c.rgb, lu.tint.rgb * c.a, lu.tint.a), c.a);+ }+ return c * lu.opacity;+}++// Normal layers: blended "over" by the pipeline+@fragment+fn fs_layer(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ return layer_color(vec2<i32>(pos.xy));+}++// other modes: read what is below and write the result+@fragment+fn fs_blend(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let p = vec2<i32>(pos.xy);+ return blend(textureLoad(backdrop_tex, p, 0), layer_color(p), lu.blend);+}++// the background colour (written, not blended)+@fragment+fn fs_solid() -> @location(0) vec4<f32> {+ return lu.solid;+}++// the finished stroke at its opacity: blended "over" into the layer to paint, or as+// "destination out" to erase+@fragment+fn fs_commit(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ return stroke_at(vec2<i32>(pos.xy));+}++// the finished stroke on an alpha-locked layer, or blended by a mode (written to a scratch+// texture, copied back)+@fragment+fn fs_commit_locked(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let p = vec2<i32>(pos.xy);+ return with_stroke(textureLoad(layer_tex, p, 0), p);+}++// ---- blending -------------------------------------------------------------------------------++fn unpremultiply(c: vec4<f32>) -> vec3<f32> {+ if (c.a <= 0.0) {+ return vec3<f32>(0.0);+ }+ return clamp(c.rgb / c.a, vec3<f32>(0.0), vec3<f32>(1.0));+}++// source `s` over backdrop `b` (both premultiplied) with blend function `mode`+fn blend(b: vec4<f32>, s: vec4<f32>, mode: u32) -> vec4<f32> {+ // shade: the darker of the backdrop and the source laid over it, premultiplied and alpha too+ if (mode == 26u) {+ return min(b, s + b * (1.0 - s.a));+ }+ let cb = unpremultiply(b);+ let cs = unpremultiply(s);+ let mixed = clamp(blend_rgb(cb, cs, mode), vec3<f32>(0.0), vec3<f32>(1.0));+ let rgb = s.a * (1.0 - b.a) * cs + s.a * b.a * mixed + (1.0 - s.a) * b.rgb;+ return vec4<f32>(rgb, s.a + b.a * (1.0 - s.a));+}diff --git a/crates/gpu/src/shaders/display.wgsl b/crates/gpu/src/shaders/display.wgslnew file mode 100644index 0000000..ac56746--- /dev/null+++ b/crates/gpu/src/shaders/display.wgsl@@ -0,0 +1,102 @@+// The composited canvas onto the window: a quad placed by the view (move, zoom, rotate).++struct DisplayUniform {+ // the map from the canvas's 0..1 coordinates to clip space: (a, b, c, d) ...+ m0: vec4<f32>,+ // ... (e, f), then 1 when the target encodes sRGB itself+ m1: vec4<f32>,+ // the canvas's colours to the target's, in linear light: three rows, c0.w 1 to apply them+ c0: vec4<f32>,+ c1: vec4<f32>,+ c2: vec4<f32>,+}++@group(0) @binding(0) var composite: texture_2d<f32>;+@group(0) @binding(1) var smp: sampler;+@group(1) @binding(0) var<uniform> du: DisplayUniform;+// a colour table taking the canvas's colours to the target's (the display only): red along z,+// green along y, blue along x; c1.w 1 to use it+@group(2) @binding(0) var lut: texture_3d<f32>;+@group(2) @binding(1) var lut_smp: sampler;++struct Out {+ @builtin(position) pos: vec4<f32>,+ @location(0) uv: vec2<f32>,+}++@vertex+fn vs_display(@builtin(vertex_index) vi: u32) -> Out {+ var corners = array<vec2<f32>, 6>(+ vec2<f32>(0.0, 0.0), vec2<f32>(1.0, 0.0), vec2<f32>(1.0, 1.0),+ vec2<f32>(0.0, 0.0), vec2<f32>(1.0, 1.0), vec2<f32>(0.0, 1.0),+ );+ let uv = corners[vi % 6u];+ var o: Out;+ o.pos = vec4<f32>(du.m0.x * uv.x + du.m0.z * uv.y + du.m1.x, du.m0.y * uv.x + du.m0.w * uv.y + du.m1.y, 0.0, 1.0);+ o.uv = uv;+ return o;+}++fn srgb_to_linear(c: vec3<f32>) -> vec3<f32> {+ let lo = c / 12.92;+ let hi = pow((c + 0.055) / 1.055, vec3<f32>(2.4));+ return select(hi, lo, c <= vec3<f32>(0.04045));+}++fn linear_to_srgb(c: vec3<f32>) -> vec3<f32> {+ let lo = c * 12.92;+ let hi = 1.055 * pow(c, vec3<f32>(1.0 / 2.4)) - 0.055;+ return select(hi, lo, c <= vec3<f32>(0.0031308));+}++@fragment+fn fs_display(i: Out) -> @location(0) vec4<f32> {+ let c = textureSample(composite, smp, i.uv);+ // transparent pixels (a hidden background) show as white for now+ var rgb = c.rgb + (1.0 - c.a) * vec3<f32>(1.0);+ // into the target's colour space (another profile's primaries), clipped to it+ if (du.c0.w > 0.5) {+ let lin = srgb_to_linear(rgb);+ let moved = vec3<f32>(dot(du.c0.xyz, lin), dot(du.c1.xyz, lin), dot(du.c2.xyz, lin));+ rgb = linear_to_srgb(clamp(moved, vec3<f32>(0.0), vec3<f32>(1.0)));+ }+ if (du.c1.w > 0.5) {+ // between the table's first and last points' centres+ let n = f32(textureDimensions(lut).x);+ let at = clamp(rgb, vec3<f32>(0.0), vec3<f32>(1.0)) * ((n - 1.0) / n) + 0.5 / n;+ rgb = textureSampleLevel(lut, lut_smp, at.zyx, 0.0).rgb;+ }+ if (du.m1.z > 0.5) {+ rgb = srgb_to_linear(rgb);+ }+ return vec4<f32>(rgb, 1.0);+}++// ---- thumbnails: part of a layer box-filtered down to the target ----------------------------+// du.m0 = (target width, target height, source pixels per target pixel in x, in y)+// du.m1 = the part: (left, top, width, height) in 0..1 of the layer++@vertex+fn vs_thumb(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {+ let uv = vec2<f32>(f32((vi << 1u) & 2u), f32(vi & 2u));+ return vec4<f32>(uv * 2.0 - 1.0, 0.0, 1.0);+}++@fragment+fn fs_thumb(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let uv = du.m1.xy + pos.xy / du.m0.xy * du.m1.zw;+ // one to one: the pixel itself+ if (du.m0.z <= 1.0 && du.m0.w <= 1.0) {+ return textureSampleLevel(composite, smp, uv, 0.0);+ }+ // a 4×4 grid of bilinear taps across the source pixels this pixel covers+ let step = du.m1.zw / du.m0.xy / 4.0;+ var sum = vec4<f32>(0.0);+ for (var j = 0; j < 4; j++) {+ for (var i = 0; i < 4; i++) {+ let offset = (vec2<f32>(f32(i), f32(j)) - 1.5) * step;+ sum += textureSampleLevel(composite, smp, uv + offset, 0.0);+ }+ }+ return sum / 16.0;+}diff --git a/crates/gpu/src/shaders/filter.wgsl b/crates/gpu/src/shaders/filter.wgslnew file mode 100644index 0000000..0f431bf--- /dev/null+++ b/crates/gpu/src/shaders/filter.wgsl@@ -0,0 +1,462 @@+// Adjustments: a layer redrawn from its copy through a filter, kept to the selection. The last+// pass of each mixes the filtered colour with the copy by how much the selection takes.+// Premultiplied throughout.++struct FilterUniform {+ // the filter's own values+ a: vec4<f32>,+ b: vec4<f32>,+ // (the target's width, height, 1 with a selection, unused)+ size: vec4<f32>,+ c: vec4<f32>,+}++@group(0) @binding(0) var src: texture_2d<f32>;+@group(0) @binding(1) var smp: sampler;+@group(0) @binding(2) var chosen: texture_2d<f32>;+@group(1) @binding(0) var<uniform> fu: FilterUniform;+// the layer's copy, for the last pass's mix (bound to the copy itself when the source is the copy)+@group(2) @binding(0) var before: texture_2d<f32>;+// 256 entries: the red, green and blue curves and the curve for all three (curves), or a+// gradient by brightness (gradient map)+@group(2) @binding(1) var table: texture_2d<f32>;++@vertex+fn vs_filter(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {+ let uv = vec2<f32>(f32((vi << 1u) & 2u), f32(vi & 2u));+ return vec4<f32>(uv * 2.0 - 1.0, 0.0, 1.0);+}++// how much of target pixel i the filter takes: all, or what the selection (or the painted-on mask)+// takes+fn taken(i: vec2<i32>) -> f32 {+ if (fu.size.z > 0.5) {+ return textureLoad(chosen, i, 0).r;+ }+ return 1.0;+}++// the filtered colour mixed with the copy by the selection+fn kept(i: vec2<i32>, filtered: vec4<f32>) -> vec4<f32> {+ return mix(textureLoad(before, i, 0), filtered, taken(i));+}++// luma and the two chroma differences (Rec. 601)+fn to_yuv(c: vec3<f32>) -> vec3<f32> {+ let y = dot(c, vec3<f32>(0.299, 0.587, 0.114));+ return vec3<f32>(y, (c.b - y) * 0.565, (c.r - y) * 0.713);+}++fn from_yuv(c: vec3<f32>) -> vec3<f32> {+ let r = c.x + c.z / 0.713;+ let b = c.x + c.y / 0.565;+ let g = (c.x - 0.299 * r - 0.114 * b) / 0.587;+ return vec3<f32>(r, g, b);+}++// the chroma turned by a.x (radians) and scaled by a.y, a.z added to the luma+@fragment+fn fs_hsb(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let i = vec2<i32>(pos.xy);+ let c = textureLoad(src, i, 0);+ if (c.a <= 0.0) {+ return kept(i, c);+ }+ let yuv = to_yuv(c.rgb / c.a);+ let cs = cos(fu.a.x);+ let sn = sin(fu.a.x);+ let uv = vec2<f32>(yuv.y * cs - yuv.z * sn, yuv.y * sn + yuv.z * cs) * fu.a.y;+ let rgb = clamp(from_yuv(vec3<f32>(yuv.x + fu.a.z, uv)), vec3<f32>(0.0), vec3<f32>(1.0));+ return kept(i, vec4<f32>(rgb * c.a, c.a));+}++// half the size: each target pixel the mean of the 2 × 2 under it+@fragment+fn fs_down(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let uv = pos.xy / fu.size.xy;+ return textureSampleLevel(src, smp, uv, 0.0);+}++// a Gaussian along a.xy (one pixel), sigma a.z, out to a.w pixels either side+@fragment+fn fs_blur(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let i = vec2<i32>(pos.xy);+ let dims = vec2<i32>(textureDimensions(src));+ let step = vec2<i32>(fu.a.xy);+ let sigma = max(fu.a.z, 0.01);+ let reach = i32(fu.a.w);+ var sum = vec4<f32>(0.0);+ var total = 0.0;+ for (var k = -reach; k <= reach; k++) {+ let w = exp(-f32(k * k) / (2.0 * sigma * sigma));+ let j = clamp(i + step * k, vec2<i32>(0), dims - 1);+ sum += textureLoad(src, j, 0) * w;+ total += w;+ }+ return sum / total;+}++// back to full size from the small blurred texture, kept to the selection+@fragment+fn fs_up(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let i = vec2<i32>(pos.xy);+ let uv = pos.xy / fu.size.xy;+ return kept(i, textureSampleLevel(src, smp, uv, 0.0));+}++// copy pixel i moved by o, held at the edges+fn near(i: vec2<i32>, o: vec2<i32>) -> vec4<f32> {+ let dims = vec2<i32>(textureDimensions(src));+ return textureLoad(src, clamp(i + o, vec2<i32>(0), dims - 1), 0);+}++// a premultiplied colour kept valid+fn valid(c: vec4<f32>) -> vec4<f32> {+ let a = clamp(c.a, 0.0, 1.0);+ return vec4<f32>(clamp(c.rgb, vec3<f32>(0.0), vec3<f32>(a)), a);+}++// a Laplacian sharpen: the pixel pushed away from its four neighbours by a.x+@fragment+fn fs_sharpen(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let i = vec2<i32>(pos.xy);+ let s = fu.a.x;+ let around = near(i, vec2<i32>(1, 0)) + near(i, vec2<i32>(-1, 0)) + near(i, vec2<i32>(0, 1)) + near(i, vec2<i32>(0, -1));+ return kept(i, valid((1.0 + 4.0 * s) * textureLoad(src, i, 0) - s * around));+}++// a pseudo-random gradient direction for lattice point p, varied by seed+fn gradient(p: vec2<f32>, seed: f32) -> vec2<f32> {+ let h = fract(sin(dot(p, vec2<f32>(127.1, 311.7)) + seed * 74.7) * 43758.5453);+ let t = h * 6.2831853;+ return vec2<f32>(cos(t), sin(t));+}++// smooth gradient noise at p, about -0.7..0.7+fn lattice_noise(p: vec2<f32>, seed: f32) -> f32 {+ let i = floor(p);+ let f = p - i;+ let u = f * f * f * (f * (f * 6.0 - 15.0) + 10.0);+ let a = dot(gradient(i, seed), f);+ let b = dot(gradient(i + vec2<f32>(1.0, 0.0), seed), f - vec2<f32>(1.0, 0.0));+ let c = dot(gradient(i + vec2<f32>(0.0, 1.0), seed), f - vec2<f32>(0.0, 1.0));+ let d = dot(gradient(i + vec2<f32>(1.0, 1.0), seed), f - vec2<f32>(1.0, 1.0));+ return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);+}++// one octave of noise of the kind b.x (clouds signed, billows and ridges 0..1)+fn shaped_noise(p: vec2<f32>, seed: f32) -> f32 {+ let n = lattice_noise(p, seed);+ if (fu.b.x > 1.5) {+ let r = 1.0 - abs(n) * 1.4;+ return r * r;+ }+ if (fu.b.x > 0.5) {+ return abs(n) * 1.4;+ }+ return n;+}++// fractal noise at p for channel seed s: a.y frequency per pixel, a.z octaves, a.w turbulence+fn fractal(p: vec2<f32>, s: f32) -> f32 {+ var total = 0.0;+ var weight = 1.0;+ var sum = 0.0;+ var freq = fu.a.y;+ let octaves = i32(fu.a.z);+ for (var o = 0; o < octaves; o++) {+ total += shaped_noise(p * freq, f32(o) + s) * weight;+ sum += weight;+ weight *= 0.5 + fu.a.w;+ freq *= 2.0;+ }+ return total / max(sum, 1e-4);+}++// fractal noise over the colour: a.x amount; b.x the kind, b.y 1 for each channel its own, b.z 1+// to add it (else mixed in)+@fragment+fn fs_noise(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let i = vec2<i32>(pos.xy);+ let c = textureLoad(src, i, 0);+ let one = fractal(pos.xy, 0.0);+ var n = vec3<f32>(one);+ if (fu.b.y > 0.5) {+ n = vec3<f32>(one, fractal(pos.xy, 17.0), fractal(pos.xy, 31.0));+ }+ // billows and ridges are 0..1: centred, so adding them both lightens and darkens+ if (fu.b.x > 0.5) {+ n = (n - 0.5) * 1.4;+ }+ if (fu.b.z > 0.5) {+ return kept(i, valid(vec4<f32>(c.rgb + n * fu.a.x * c.a, c.a)));+ }+ let grey = clamp(n * 0.5 + 0.5, vec3<f32>(0.0), vec3<f32>(1.0));+ return kept(i, valid(vec4<f32>(mix(c.rgb, grey * c.a, clamp(fu.a.x, 0.0, 1.0)), c.a)));+}++// samples along a line from the pixel: a.xy the line (pixels), a.z how many, a.w 1 to centre it+@fragment+fn fs_streak(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let i = vec2<i32>(pos.xy);+ let count = max(i32(fu.a.z), 1);+ let start = select(vec2<f32>(0.0), -0.5 * fu.a.xy, fu.a.w > 0.5);+ var sum = vec4<f32>(0.0);+ for (var k = 0; k < count; k++) {+ let t = (f32(k) + 0.5) / f32(count);+ let p = pos.xy + start + fu.a.xy * t;+ sum += textureSampleLevel(src, smp, p / fu.size.xy, 0.0);+ }+ return kept(i, sum / f32(count));+}++// each pixel streaked towards (b.xy, pixels) by a.x of the way there+@fragment+fn fs_zoom(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let i = vec2<i32>(pos.xy);+ let towards = (fu.b.xy - pos.xy) * fu.a.x;+ let count = clamp(i32(length(towards)), 1, 96);+ var sum = vec4<f32>(0.0);+ for (var k = 0; k < count; k++) {+ let t = (f32(k) + 0.5) / f32(count);+ sum += textureSampleLevel(src, smp, (pos.xy + towards * t) / fu.size.xy, 0.0);+ }+ return kept(i, sum / f32(count));+}++// red and blue pulled apart, smeared over a.y of the pull: from the centre (b.xy, pixels) by a.x of+// the distance and less within a.z of the half diagonal of it; or (b.z below 0) by b.xy everywhere,+// the fringes beyond the picture a.w transparent+@fragment+fn fs_chroma(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let i = vec2<i32>(pos.xy);+ var away = fu.b.xy;+ if (fu.b.z >= 0.0) {+ let reach = 0.5 * length(fu.size.xy);+ let near_centre = smoothstep(0.0, max(fu.a.z * reach, 1e-3), length(pos.xy - fu.b.xy));+ away = (pos.xy - fu.b.xy) * fu.a.x * select(1.0, near_centre, fu.a.z > 0.0);+ }+ let taps = 1 + i32(fu.a.y * 8.0);+ var red = vec4<f32>(0.0);+ var blue = vec4<f32>(0.0);+ for (var k = 0; k < taps; k++) {+ let t = 1.0 - fu.a.y * f32(k) / f32(max(taps, 1));+ red += textureSampleLevel(src, smp, (pos.xy - away * t) / fu.size.xy, 0.0);+ blue += textureSampleLevel(src, smp, (pos.xy + away * t) / fu.size.xy, 0.0);+ }+ red /= f32(taps);+ blue /= f32(taps);+ let mid = textureLoad(src, i, 0);+ let fringe = max(red.a, blue.a);+ let a = max(mid.a, fringe * (1.0 - fu.a.w * select(0.0, 1.0, fu.b.z < 0.0)));+ return kept(i, valid(vec4<f32>(red.r, mid.g, blue.b, a)));+}++// how much ink a halftone screen at `angle` (radians) with cells `pitch` pixels puts at p, for an+// ink coverage of `ink`+fn screen_dot(p: vec2<f32>, angle: f32, pitch: f32, ink: f32) -> f32 {+ let cs = cos(angle);+ let sn = sin(angle);+ let q = vec2<f32>(p.x * cs + p.y * sn, -p.x * sn + p.y * cs) / pitch;+ let d = length(fract(q) - 0.5) * pitch;+ // a dot whose area is the ink's share of the cell+ let r = sqrt(ink / 3.1415927) * pitch;+ return clamp(r - d + 0.5, 0.0, 1.0);+}++// a halftone with cells a.x pixels across, of the kind a.y: full colour (cyan, magenta, yellow and+// black screens), screen print (the colour itself in dots as big as it is dark), newspaper (black+// dots as big as the grey is dark)+@fragment+fn fs_halftone(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let i = vec2<i32>(pos.xy);+ let c = textureLoad(src, i, 0);+ if (c.a <= 0.0) {+ return kept(i, c);+ }+ let rgb = c.rgb / c.a;+ let pitch = fu.a.x;+ let deg = 0.017453292;+ let kind = i32(fu.a.y + 0.5);+ if (kind == 2) {+ let dot_ink = screen_dot(pos.xy, 45.0 * deg, pitch, 1.0 - dot(rgb, vec3<f32>(0.299, 0.587, 0.114)));+ return kept(i, vec4<f32>(vec3<f32>(1.0 - dot_ink) * c.a, c.a));+ }+ if (kind == 1) {+ let top = max(rgb.r, max(rgb.g, rgb.b));+ let ink = rgb / max(top, 1e-4);+ let cover = screen_dot(pos.xy, 45.0 * deg, pitch, clamp(1.0 - dot(rgb, vec3<f32>(0.299, 0.587, 0.114)) + 0.25 * top, 0.0, 1.0));+ return kept(i, vec4<f32>(mix(vec3<f32>(1.0), ink * top, cover) * c.a, c.a));+ }+ let k = 1.0 - max(rgb.r, max(rgb.g, rgb.b));+ let under = max(1.0 - k, 1e-4);+ let cmy = (vec3<f32>(1.0) - rgb - vec3<f32>(k)) / under;+ let dc = screen_dot(pos.xy, 15.0 * deg, pitch, cmy.x);+ let dm = screen_dot(pos.xy, 75.0 * deg, pitch, cmy.y);+ let dy = screen_dot(pos.xy, 0.0, pitch, cmy.z);+ let dk = screen_dot(pos.xy, 45.0 * deg, pitch, k);+ let printed = (vec3<f32>(1.0) - vec3<f32>(dc, dm, dy)) * (1.0 - dk);+ return kept(i, vec4<f32>(printed * c.a, c.a));+}++// the blurred copy's light over the copy: a.x how much, from brightness a.y up over a ramp a.z+// (0..1) long, made stronger by a.w (burn, -0.3..1)+@fragment+fn fs_bloom(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let i = vec2<i32>(pos.xy);+ let glow = textureSampleLevel(src, smp, pos.xy / fu.size.xy, 0.0);+ let c = textureLoad(before, i, 0);+ let low = fu.a.y * (1.0 - clamp(fu.a.z, 0.0, 1.0));+ let bright = smoothstep(low, fu.a.y + 0.02, dot(glow.rgb, vec3<f32>(0.299, 0.587, 0.114)));+ let strength = fu.a.x * (1.0 + 1.5 * fu.a.w);+ let light = glow.rgb * bright * strength;+ // screened over what is there+ let rgb = c.rgb + light * (1.0 - c.rgb);+ return kept(i, valid(vec4<f32>(rgb, max(c.a, glow.a * bright * strength))));+}++// a colour through the table at v (0..1)+fn look(v: f32) -> vec4<f32> {+ return textureLoad(table, vec2<i32>(i32(clamp(v, 0.0, 1.0) * 255.0 + 0.5), 0), 0);+}++// curves: each channel through the curve for all three, then its own+@fragment+fn fs_curves(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let i = vec2<i32>(pos.xy);+ let c = textureLoad(src, i, 0);+ if (c.a <= 0.0) {+ return kept(i, c);+ }+ let rgb = c.rgb / c.a;+ let r = look(look(rgb.r).a).r;+ let g = look(look(rgb.g).a).g;+ let b = look(look(rgb.b).a).b;+ return kept(i, vec4<f32>(vec3<f32>(r, g, b) * c.a, c.a));+}++// gradient map: the gradient's colour at the pixel's brightness, a.x of the way+@fragment+fn fs_gradient(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let i = vec2<i32>(pos.xy);+ let c = textureLoad(src, i, 0);+ if (c.a <= 0.0) {+ return kept(i, c);+ }+ let rgb = c.rgb / c.a;+ let mapped = look(dot(rgb, vec3<f32>(0.299, 0.587, 0.114))).rgb;+ return kept(i, vec4<f32>(mix(rgb, mapped, fu.a.x) * c.a, c.a));+}++// how much of each tone a channel value is: shadows, midtones, highlights+fn tones(v: f32) -> vec3<f32> {+ let sh = clamp(0.5 - 4.0 * (v - 1.0 / 3.0), 0.0, 1.0);+ let mid = clamp(0.5 + 4.0 * (v - 1.0 / 3.0), 0.0, 1.0) * clamp(0.5 - 4.0 * (v - 2.0 / 3.0), 0.0, 1.0);+ let hi = clamp(0.5 + 4.0 * (v - 2.0 / 3.0), 0.0, 1.0);+ return vec3<f32>(sh, mid, hi);+}++// colour balance: each channel shifted by its shadows (a), midtones (b) and highlights (c) values,+// as much as it is of each tone; the brightness kept+@fragment+fn fs_balance(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let i = vec2<i32>(pos.xy);+ let c = textureLoad(src, i, 0);+ if (c.a <= 0.0) {+ return kept(i, c);+ }+ let rgb = c.rgb / c.a;+ var shifted = vec3<f32>(0.0);+ for (var k = 0; k < 3; k++) {+ let w = tones(rgb[k]);+ shifted[k] = clamp(rgb[k] + 0.7 * (w.x * fu.a[k] + w.y * fu.b[k] + w.z * fu.c[k]), 0.0, 1.0);+ }+ let kept_y = to_yuv(rgb).x;+ let moved = to_yuv(shifted);+ let out = clamp(from_yuv(vec3<f32>(kept_y, moved.y, moved.z)), vec3<f32>(0.0), vec3<f32>(1.0));+ return kept(i, vec4<f32>(out * c.a, c.a));+}++// liquify: the copy from as far back as the field's offsets say, a.x of them+@fragment+fn fs_liquified(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let i = vec2<i32>(pos.xy);+ let offset = textureLoad(table, i, 0).xy * fu.a.x;+ return kept(i, textureSampleLevel(src, smp, (pos.xy - offset) / fu.size.xy, 0.0));+}++// clone: the copy from a.xy (pixels) away+@fragment+fn fs_clone(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let i = vec2<i32>(pos.xy);+ return kept(i, textureSampleLevel(src, smp, (pos.xy + fu.a.xy) / fu.size.xy, 0.0));+}++// a pseudo-random value 0..1 for cell p, varied by seed+fn cell_random(p: vec2<f32>, seed: f32) -> f32 {+ return fract(sin(dot(p, vec2<f32>(269.5, 183.3)) + seed * 91.3) * 43758.5453);+}++// the copy at canvas point p+fn copy_at(p: vec2<f32>) -> vec4<f32> {+ return textureSampleLevel(src, smp, p / fu.size.xy, 0.0);+}++// glitch: a.x the kind (artifact, wave, signal, diverge), a.y how much, a.zw and b.x the kind's+// values, b.y the zoom, b.z a seed+@fragment+fn fs_glitch(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let i = vec2<i32>(pos.xy);+ let p = pos.xy;+ let kind = i32(fu.a.x + 0.5);+ let amount = fu.a.y;+ let span = min(fu.size.x, fu.size.y);+ let scale = 0.3 + 0.7 * fu.b.y;+ let seed = fu.b.z;+ var out = textureLoad(src, i, 0);+ if (kind == 0) {+ // blocks twice as wide as tall, some copied from a few blocks away, and finer pieces+ let h = span * (0.008 + 0.12 * fu.a.w) * scale;+ let block = vec2<f32>(2.0 * h, h);+ let cell = floor(p / block);+ if (cell_random(cell, seed) < fu.a.z * amount * 0.6) {+ let jump = vec2<f32>(cell_random(cell + 1.3, seed), cell_random(cell + 7.1, seed)) - 0.5;+ out = copy_at(p + round(jump * 12.0 * amount) * block);+ }+ let piece = block / 3.0;+ let small = floor(p / piece);+ if (cell_random(small, seed + 3.0) < fu.a.z * amount * 0.15) {+ let jump = vec2<f32>(cell_random(small + 2.9, seed), cell_random(small + 5.3, seed)) - 0.5;+ out = copy_at(p + round(jump * 8.0) * piece);+ }+ } else if (kind == 1) {+ // rows bent sideways along two waves+ let k = 6.2831853 / (span * (1.25 - fu.a.w) * scale);+ let dx = amount * fu.a.z * span * 0.15 * (sin(k * p.y + seed) + 0.5 * sin(2.3 * k * p.y + 1.7 + seed));+ out = copy_at(p + vec2<f32>(dx, 0.0));+ } else if (kind == 2) {+ // bands moved sideways over the picture, their red and blue a little apart+ let h = span * (0.01 + 0.15 * fu.a.w) * scale;+ let band = floor(p.y / h);+ if (cell_random(vec2<f32>(band, 0.5), seed) < fu.a.z * amount * 0.9) {+ let dx = (cell_random(vec2<f32>(band, 3.1), seed) - 0.5) * span * 0.16 * amount;+ let moved = copy_at(p + vec2<f32>(dx, 0.0));+ let r = copy_at(p + vec2<f32>(dx * 1.04, 0.0)).r;+ let b = copy_at(p + vec2<f32>(dx * 0.96, 0.0)).b;+ out = max(out, vec4<f32>(r, moved.g, b, moved.a));+ }+ } else {+ // each channel moved its own way, block by block+ let c = span * (0.04 + 0.3 * fu.b.y);+ let cell = floor(p / c);+ let shift = vec3<f32>(fu.a.z, fu.a.w, fu.b.x) * c * 0.45 * amount;+ let along = vec3<f32>(cell_random(cell, seed), cell_random(cell + 2.0, seed), cell_random(cell + 4.0, seed));+ let across = vec3<f32>(cell_random(cell + 1.0, seed), cell_random(cell + 3.0, seed), cell_random(cell + 5.0, seed)) - 0.5;+ let red = copy_at(p - vec2<f32>(0.4 + 0.6 * along.x, 0.6 * across.x) * shift.x);+ let green = copy_at(p - vec2<f32>(0.4 + 0.6 * along.y, 0.6 * across.y) * shift.y);+ let blue = copy_at(p - vec2<f32>(0.4 + 0.6 * along.z, 0.6 * across.z) * shift.z);+ out = vec4<f32>(red.r, green.g, blue.b, max(max(red.a, green.a), blue.a));+ }+ return kept(i, valid(out));+}+diff --git a/crates/gpu/src/shaders/liquify.wgsl b/crates/gpu/src/shaders/liquify.wgslnew file mode 100644index 0000000..9d510e5--- /dev/null+++ b/crates/gpu/src/shaders/liquify.wgsl@@ -0,0 +1,79 @@+// Liquify: brush stamps drawn into a field of offsets (canvas pixels: each pixel shows the copy+// from that far back), added up as the brush moves; reconstruct pulls the offsets back to none.++struct LiquifyUniform {+ // (centre x, y, radius, pressure)+ stamp: vec4<f32>,+ // (the brush's move since its last stamp x, y, mode, seed)+ move_mode: vec4<f32>,+ // (canvas width, height, distortion, unused)+ canvas: vec4<f32>,+ pad: vec4<f32>,+}++@group(0) @binding(0) var<uniform> lu: LiquifyUniform;++struct StampOut {+ @builtin(position) pos: vec4<f32>,+ @location(0) local: vec2<f32>,+}++// a square around the stamp, in canvas pixels+@vertex+fn vs_liquify(@builtin(vertex_index) vi: u32) -> StampOut {+ var corners = array<vec2<f32>, 6>(+ vec2<f32>(-1.0, -1.0), vec2<f32>(1.0, -1.0), vec2<f32>(1.0, 1.0),+ vec2<f32>(-1.0, -1.0), vec2<f32>(1.0, 1.0), vec2<f32>(-1.0, 1.0),+ );+ let q = corners[vi % 6u];+ let p = lu.stamp.xy + q * lu.stamp.z;+ var out: StampOut;+ out.pos = vec4<f32>(p.x / lu.canvas.x * 2.0 - 1.0, 1.0 - p.y / lu.canvas.y * 2.0, 0.0, 1.0);+ out.local = q * lu.stamp.z;+ return out;+}++fn hash(p: vec2<f32>) -> f32 {+ return fract(sin(dot(p, vec2<f32>(12.9898, 78.233)) + lu.move_mode.w) * 43758.5453);+}++// what one stamp adds to the offsets at its own pixel (or, for reconstruct, how much of them goes)+@fragment+fn fs_liquify(in: StampOut) -> @location(0) vec4<f32> {+ let r = lu.stamp.z;+ let d = length(in.local) / r;+ if (d >= 1.0) {+ discard;+ }+ // soft towards the rim+ let f = (1.0 - d * d) * (1.0 - d * d) * lu.stamp.w;+ let mode = i32(lu.move_mode.z + 0.5);+ let away = in.local;+ var add = vec2<f32>(0.0);+ switch mode {+ // push: what is under the brush goes with it+ case 0: { add = lu.move_mode.xy * f; }+ // twirl right and left: turned about the centre+ case 1, 2: {+ let turn = select(-1.0, 1.0, mode == 1) * f * 0.12;+ let c = cos(turn);+ let s = sin(turn);+ add = away - vec2<f32>(away.x * c - away.y * s, away.x * s + away.y * c);+ }+ // pinch: drawn in towards the centre; expand: pushed out+ case 3: { add = -away * f * 0.08; }+ case 4: { add = away * f * 0.08; }+ // crystals: scattered+ case 5: {+ let a = hash(floor(in.pos.xy / 6.0)) * 6.2831853;+ add = vec2<f32>(cos(a), sin(a)) * f * r * 0.04;+ }+ // edge: pushed out most near the rim+ case 6: { add = normalize(away + vec2<f32>(1e-4)) * d * f * r * 0.05; }+ // reconstruct: the alpha says how much of the offsets goes+ default: { return vec4<f32>(0.0, 0.0, 0.0, clamp(f * 0.2, 0.0, 1.0)); }+ }+ // distortion scatters the stroke a little+ let jitter = (vec2<f32>(hash(in.pos.xy), hash(in.pos.yx)) - 0.5) * lu.canvas.z * f * r * 0.05;+ return vec4<f32>(add + jitter, 0.0, 1.0);+}diff --git a/crates/gpu/src/shaders/overlay.wgsl b/crates/gpu/src/shaders/overlay.wgslnew file mode 100644index 0000000..e4a88e8--- /dev/null+++ b/crates/gpu/src/shaders/overlay.wgsl@@ -0,0 +1,94 @@+// The predicted tail of the stroke being drawn: stamps straight onto the window over the canvas,+// never into the layer. They cover the gap between the latest input and where the pen already is.++struct OverlayUniform {+ // canvas pixels to clip space: (a, b, c, d) ...+ m0: vec4<f32>,+ // ... (e, f), screen pixels per canvas pixel, the round tip's hardness+ m1: vec4<f32>,+ // straight colour and the stroke's opacity+ color: vec4<f32>,+ // -1: the round tip; otherwise a layer of `shapes`+ shape: i32,+ // 1 when the target encodes sRGB itself+ srgb: u32,+ _p0: u32,+ _p1: u32,+}++@group(0) @binding(0) var<uniform> ou: OverlayUniform;+@group(1) @binding(0) var shapes: texture_2d_array<f32>;+@group(1) @binding(1) var grains: texture_2d_array<f32>;+@group(1) @binding(2) var shape_smp: sampler;+@group(1) @binding(3) var grain_smp: sampler;++struct StampIn {+ @location(0) center: vec2<f32>,+ @location(1) radius: f32,+ @location(2) alpha: f32,+ @location(3) angle: f32,+ @location(4) roundness: f32,+ @location(5) grain_offset: vec2<f32>,+}++struct Out {+ @builtin(position) pos: vec4<f32>,+ @location(0) q: vec2<f32>,+ // radius in screen pixels+ @location(1) radius: f32,+ @location(2) alpha: f32,+}++@vertex+fn vs_overlay(@builtin(vertex_index) vi: u32, inst: StampIn) -> Out {+ var corners = array<vec2<f32>, 6>(+ vec2<f32>(-1.0, -1.0), vec2<f32>(1.0, -1.0), vec2<f32>(1.0, 1.0),+ vec2<f32>(-1.0, -1.0), vec2<f32>(1.0, 1.0), vec2<f32>(-1.0, 1.0),+ );+ let zoom = max(ou.m1.z, 1e-3);+ let r = max(inst.radius, 0.25);+ let rs = r * zoom;+ // one screen pixel to spare for anti-aliasing+ let grow = (rs + 1.0) / rs;+ let q = corners[vi % 6u] * grow;+ let local = vec2<f32>(q.x * r, q.y * r * inst.roundness);+ let c = cos(inst.angle);+ let s = sin(inst.angle);+ let p = inst.center + vec2<f32>(local.x * c - local.y * s, local.x * s + local.y * c);+ var o: Out;+ o.pos = vec4<f32>(ou.m0.x * p.x + ou.m0.z * p.y + ou.m1.x, ou.m0.y * p.x + ou.m0.w * p.y + ou.m1.y, 0.0, 1.0);+ o.q = q;+ o.radius = rs;+ o.alpha = inst.alpha;+ return o;+}++fn srgb_to_linear(c: vec3<f32>) -> vec3<f32> {+ let lo = c / 12.92;+ let hi = pow((c + 0.055) / 1.055, vec3<f32>(2.4));+ return select(hi, lo, c <= vec3<f32>(0.04045));+}++@fragment+fn fs_overlay(i: Out) -> @location(0) vec4<f32> {+ let r = i.radius;+ var a = 0.0;+ if (ou.shape < 0) {+ let d = length(i.q) * r;+ let rim = clamp(r - d + 0.5, 0.0, 1.0);+ let soft = 1.0 - smoothstep(min(ou.m1.w, 0.999) * r, r + 0.5, d);+ a = min(rim, soft);+ } else {+ let uv = i.q * 0.5 + 0.5;+ let lod = max(log2(256.0 / max(2.0 * r, 1.0)), 0.0);+ let inside = all(uv >= vec2<f32>(0.0)) && all(uv <= vec2<f32>(1.0));+ a = select(0.0, textureSampleLevel(shapes, shape_smp, uv, ou.shape, lod).r, inside);+ }+ let small = min(r * 2.0, 1.0);+ a = a * small * small * i.alpha * ou.color.a;+ var rgb = ou.color.rgb;+ if (ou.srgb == 1u) {+ rgb = srgb_to_linear(rgb);+ }+ return vec4<f32>(rgb * a, a);+}diff --git a/crates/gpu/src/shaders/selection.wgsl b/crates/gpu/src/shaders/selection.wgslnew file mode 100644index 0000000..1c09f31--- /dev/null+++ b/crates/gpu/src/shaders/selection.wgsl@@ -0,0 +1,57 @@+// How the selection shows over the canvas, fixed to the window: faint diagonal bands, dark and+// light by turns, drifting over what is not selected; or what is selected multiplied by a colour+// (a tint) or covered by one.++struct SelectionUniform {+ // window pixel to the canvas's unit square: (a, b, c, d) of x' = a·x + c·y + e, y' = b·x + d·y + f+ m0: vec4<f32>,+ // (e, f, the bands' period across the window in pixels, their drift in pixels)+ m1: vec4<f32>,+ // (colour for a tint or fill, the bands' coverage)+ v: vec4<f32>,+ // (0 bands, 1 tint, 2 fill; 1 when the target encodes sRGB itself; unused)+ mode: vec4<f32>,+}++@group(0) @binding(0) var mask: texture_2d<f32>;+@group(0) @binding(1) var smp: sampler;+@group(1) @binding(0) var<uniform> su: SelectionUniform;++@vertex+fn vs_selection(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {+ let uv = vec2<f32>(f32((vi << 1u) & 2u), f32(vi & 2u));+ return vec4<f32>(uv * 2.0 - 1.0, 0.0, 1.0);+}++fn srgb_to_linear(c: vec3<f32>) -> vec3<f32> {+ let lo = c / 12.92;+ let hi = pow((c + 0.055) / 1.055, vec3<f32>(2.4));+ return select(hi, lo, c <= vec3<f32>(0.04045));+}++@fragment+fn fs_selection(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let p = pos.xy;+ let u = vec2<f32>(su.m0.x * p.x + su.m0.z * p.y + su.m1.x, su.m0.y * p.x + su.m0.w * p.y + su.m1.y);+ if (any(u < vec2<f32>(0.0)) || any(u > vec2<f32>(1.0))) {+ discard;+ }+ let selected = textureSampleLevel(mask, smp, u, 0.0).r;+ var c = su.v.rgb;+ if (su.mode.y > 0.5) {+ c = srgb_to_linear(c);+ }+ let mode = i32(su.mode.x + 0.5);+ if (mode == 1) {+ // multiplied (the pipeline blends by multiplying)+ return vec4<f32>(mix(vec3<f32>(1.0), c, selected), 1.0);+ }+ if (mode == 2) {+ return vec4<f32>(c * selected, selected);+ }+ // bands rising to the right, dark and light by turns, with soft edges+ let band = fract((p.x + p.y + su.m1.w) / su.m1.z);+ let light = smoothstep(0.09, 0.25, band) - smoothstep(0.59, 0.75, band);+ let a = (1.0 - selected) * su.v.w;+ return vec4<f32>(vec3<f32>(light * a), a);+}diff --git a/crates/gpu/src/shaders/smudge.wgsl b/crates/gpu/src/shaders/smudge.wgslnew file mode 100644index 0000000..80ae998--- /dev/null+++ b/crates/gpu/src/shaders/smudge.wgsl@@ -0,0 +1,235 @@+// Smudge: the brush carries colour. A small grid in the stamp's own frame holds what it carries;+// for each stamp, in order, it picks up some of what is under it (cs_carry) and lays what it+// carries back down under the stamp's shape (cs_deposit). The layer being smudged is a buffer of+// packed premultiplied RGBA8 pixels, read and written in place.++struct SmudgeStamp {+ center: vec2<f32>,+ radius: f32,+ angle: f32,+ roundness: f32,+ // the stamp's alpha times the tool's strength+ alpha: f32,+ // how much of what it carries the brush keeps at each stamp (the rest is picked up)+ pull: f32,+ hardness: f32,+ shape: i32,+ // 1 for the stroke's first stamp: the brush starts loaded with what is under it+ first: u32,+ preserve_alpha: u32,+ // u32 words per buffer row+ stride: u32,+ // the pixels this stamp can touch: x0, y0, x1, y1+ bbox: vec4<i32>,+ size: vec2<u32>,+ grid: u32,+ // 1: stamps over a pixel don't build up past the strongest of them (the uniform glaze)+ uniform_glaze: u32,+ // wet mix: the paint (straight colour), how much of it the brush mixes into what it carries,+ // and how much of what it carries it lays down+ paint: vec4<f32>,+ // 0 smudges; 1 paints wet+ mode: u32,+ mixture: f32,+ final_mixture: f32,+ // the mix's grade and blur (0..1), folded into the mixtures for now+ grade: f32,+ blur: f32,+ // the brush's grain: a layer of `grains` (-1: none), the size of a tile in pixels (negative+ // for a grain moving with the stamp, else fixed to the canvas) and how strongly it shows+ grain: i32,+ grain_scale: f32,+ grain_depth: f32,+ // where a moving grain is read from at the stamp's middle (see the stamp shader), and the+ // grain turned (radians)+ grain_offset: vec2<f32>,+ grain_rotation: f32,+ // 1: the grain read unfiltered (sharp)+ grain_sharp: f32,+ // 1: the shape read unfiltered (sharp)+ shape_sharp: f32,+ // how hard the paint is pressed into a moving grain, and how much that counts+ grain_press: f32,+ grain_bleed: f32,+ // 1: wet paint with a texturized grain, laid over the stroke once: `raw` holds the stroke+ // without it and `orig` the layer as it was+ grain_once: f32,+}++@group(0) @binding(0) var<uniform> st: SmudgeStamp;+@group(0) @binding(1) var<storage, read_write> work: array<u32>;+@group(0) @binding(2) var<storage, read_write> carry: array<vec4<f32>>;+@group(0) @binding(3) var<storage, read_write> raw: array<u32>;+@group(0) @binding(4) var<storage, read> orig: array<u32>;+@group(1) @binding(0) var shapes: texture_2d_array<f32>;+@group(1) @binding(1) var grains: texture_2d_array<f32>;+@group(1) @binding(2) var shape_smp: sampler;+@group(1) @binding(3) var grain_smp: sampler;++fn pixel(x: i32, y: i32) -> vec4<f32> {+ let cx = clamp(x, 0, i32(st.size.x) - 1);+ let cy = clamp(y, 0, i32(st.size.y) - 1);+ let k = u32(cy) * st.stride + u32(cx);+ // the brush picks up the stroke as it is without the grain laid over it+ if (st.grain_once > 0.5) {+ return unpack4x8unorm(raw[k]);+ }+ return unpack4x8unorm(work[k]);+}++// the layer at a canvas position (pixel centres at +0.5), bilinear+fn layer_at(q: vec2<f32>) -> vec4<f32> {+ let p = q - 0.5;+ let i = vec2<i32>(floor(p));+ let f = p - floor(p);+ let top = mix(pixel(i.x, i.y), pixel(i.x + 1, i.y), f.x);+ let bottom = mix(pixel(i.x, i.y + 1), pixel(i.x + 1, i.y + 1), f.x);+ return mix(top, bottom, f.y);+}++// stamp frame (-1..1, before roundness and rotation) to canvas+fn to_canvas(t: vec2<f32>) -> vec2<f32> {+ let local = vec2<f32>(t.x * st.radius, t.y * st.radius * st.roundness);+ let c = cos(st.angle);+ let s = sin(st.angle);+ return st.center + vec2<f32>(local.x * c - local.y * s, local.x * s + local.y * c);+}++@compute @workgroup_size(8, 8)+fn cs_carry(@builtin(global_invocation_id) id: vec3<u32>) {+ if (id.x >= st.grid || id.y >= st.grid) {+ return;+ }+ let t = (vec2<f32>(id.xy) + 0.5) / f32(st.grid) * 2.0 - 1.0;+ let under = layer_at(to_canvas(t));+ let k = id.y * st.grid + id.x;+ if (st.first == 1u) {+ carry[k] = under;+ } else {+ carry[k] = mix(under, carry[k], st.pull);+ }+ if (st.mode == 1u) {+ // wet: the brush's paint mixed into what it carries+ carry[k] = mix(carry[k], vec4<f32>(st.paint.rgb, 1.0), st.mixture);+ }+}++fn carried(t: vec2<f32>) -> vec4<f32> {+ let g = i32(st.grid);+ let p = (t * 0.5 + 0.5) * f32(st.grid) - 0.5;+ let i = vec2<i32>(floor(p));+ let f = p - floor(p);+ let x0 = clamp(i.x, 0, g - 1);+ let x1 = clamp(i.x + 1, 0, g - 1);+ let y0 = clamp(i.y, 0, g - 1);+ let y1 = clamp(i.y + 1, 0, g - 1);+ let top = mix(carry[y0 * g + x0], carry[y0 * g + x1], f.x);+ let bottom = mix(carry[y1 * g + x0], carry[y1 * g + x1], f.x);+ return mix(top, bottom, f.y);+}++fn mask(t: vec2<f32>) -> f32 {+ if (st.shape < 0) {+ let d = length(t) * st.radius;+ let rim = clamp(st.radius - d + 0.5, 0.0, 1.0);+ let soft = 1.0 - smoothstep(min(st.hardness, 0.999) * st.radius, st.radius + 0.5, d);+ return min(rim, soft);+ }+ let uv = t * 0.5 + 0.5;+ if (st.shape_sharp > 0.5) {+ // unfiltered: the texel under it+ let size = vec2<i32>(textureDimensions(shapes));+ let at = clamp(vec2<i32>(floor(uv * vec2<f32>(size))), vec2<i32>(0), size - 1);+ return textureLoad(shapes, at, st.shape, 0).r;+ }+ let lod = max(log2(256.0 / max(2.0 * st.radius, 1.0)), 0.0);+ return textureSampleLevel(shapes, shape_smp, uv, st.shape, lod).r;+}++// how much of the stamp the grain lets through at canvas point `p` (stamp frame point `t`)+fn grain_at(p: vec2<f32>) -> f32 {+ if (st.grain < 0) {+ return 1.0;+ }+ let scale = abs(st.grain_scale);+ var at = p;+ if (st.grain_scale < 0.0) {+ // a moving grain: read as far from where the stamp's middle is in it as the pixel is from+ // the middle on the canvas, so a rolling grain stays put as the stamps move over it+ at = p - st.center + st.grain_offset;+ }+ let gc = cos(st.grain_rotation);+ let gs = sin(st.grain_rotation);+ let uv = vec2<f32>(at.x * gc - at.y * gs, at.x * gs + at.y * gc) / scale;+ let sharp = st.grain_sharp > 0.5;+ var g = textureSampleLevel(grains, grain_smp, uv, st.grain, select(max(log2(256.0 / scale), 0.0), 0.0, sharp)).r;+ if (sharp) {+ g = sharp_grain(g, uv);+ }+ if (st.grain_bleed > 0.0) {+ // pressed in as far as the pressure's bleed says+ g = mix(g, pressed_in(g, st.grain_press), st.grain_bleed);+ }+ return mix(1.0, g, st.grain_depth);+}++@compute @workgroup_size(8, 8)+fn cs_deposit(@builtin(global_invocation_id) id: vec3<u32>) {+ let p = st.bbox.xy + vec2<i32>(id.xy);+ if (p.x >= st.bbox.z || p.y >= st.bbox.w || p.x < 0 || p.y < 0 || p.x >= i32(st.size.x) || p.y >= i32(st.size.y)) {+ return;+ }+ // into the stamp's frame+ let d = vec2<f32>(p) + 0.5 - st.center;+ let c = cos(st.angle);+ let s = sin(st.angle);+ let local = vec2<f32>(d.x * c + d.y * s, -d.x * s + d.y * c);+ let t = vec2<f32>(local.x / st.radius, local.y / (st.radius * st.roundness));+ if (abs(t.x) > 1.0 || abs(t.y) > 1.0) {+ return;+ }+ let shape = mask(t);+ if (shape * st.alpha <= 0.0) {+ return;+ }+ // the grain lets each stamp through as far as it stands: stamps over a pixel build up past+ // it towards full, the grain showing while they are few or light (unless it is laid over the+ // stroke once)+ let once = st.grain_once > 0.5;+ let g = select(grain_at(vec2<f32>(p) + 0.5), 1.0, once);+ let m = shape * st.alpha;+ let k = u32(p.y) * st.stride + u32(p.x);+ let w = select(unpack4x8unorm(work[k]), unpack4x8unorm(raw[k]), once);+ // smudging: the grain lets less of what is carried through+ var out = mix(w, carried(t), m * g);+ if (st.mode == 1u) {+ // wet: what it carries (its paint and what it picked up, alpha and all), as much as the+ // final mixture lays down, over what is there, as far as the stamp covers+ let laid = carried(t) * st.final_mixture;+ out = mix(w, laid + w * (1.0 - laid.a), m * g);+ }+ if (st.preserve_alpha == 1u) {+ out = out * (w.a / max(out.a, 1e-6));+ }+ // rounded to 8 bits up or down at random, in proportion to the remainder, so that faint stamps+ // add up as they should instead of rounding away+ let h = dither(u32(p.x), u32(p.y), bitcast<u32>(st.center.x) ^ (bitcast<u32>(st.center.y) * 2654435761u));+ if (once) {+ // the stroke kept without the grain; shown with the grain over its change to the layer+ raw[k] = pack4x8unorm(clamp(out + (h - 0.5) / 255.0, vec4<f32>(0.0), vec4<f32>(1.0)));+ let was = unpack4x8unorm(orig[k]);+ let shown = was + (out - was) * grain_at(vec2<f32>(p) + 0.5);+ work[k] = pack4x8unorm(clamp(shown + (h - 0.5) / 255.0, vec4<f32>(0.0), vec4<f32>(1.0)));+ return;+ }+ work[k] = pack4x8unorm(clamp(out + (h - 0.5) / 255.0, vec4<f32>(0.0), vec4<f32>(1.0)));+}++// a number in 0..1 that looks random, from three+fn dither(a: u32, b: u32, c: u32) -> f32 {+ var h = a * 747796405u + b * 2891336453u + c * 277803737u;+ h = (h ^ (h >> 16u)) * 2246822519u;+ h = (h ^ (h >> 13u)) * 3266489917u;+ h = h ^ (h >> 16u);+ return f32(h >> 8u) / 16777216.0;+}diff --git a/crates/gpu/src/shaders/stamp.wgsl b/crates/gpu/src/shaders/stamp.wgslnew file mode 100644index 0000000..a745548--- /dev/null+++ b/crates/gpu/src/shaders/stamp.wgsl@@ -0,0 +1,198 @@+// Brush stamps into the stroke texture: one instanced quad per stamp, turned and squashed as the+// stamp says, with the round tip or a shape image, and a moving grain if the brush has one.+// Written premultiplied; the pipeline blends them "over" (light glaze) or keeps the maximum+// (uniform glaze).++struct StampUniform {+ canvas_size: vec2<f32>,+ hardness: f32,+ // -1: the round tip; otherwise a layer of `shapes`+ shape: i32,+ // straight sRGB colour+ color: vec4<f32>,+ // -1: no moving grain; otherwise a layer of `grains`+ grain: i32,+ grain_scale: f32,+ grain_depth: f32,+ grain_brightness: f32,+ grain_contrast: f32,+ // the grain turned, radians, and how it combines with the shape (a blend mode's number)+ grain_rotation: f32,+ grain_blend: u32,+ // 1: the grain read unfiltered (sharp)+ grain_sharp: u32,+ // the secondary colour (straight sRGB), mixed in as far as each stamp says+ secondary: vec4<f32>,+ // 1: the shape read unfiltered (sharp)+ shape_sharp: u32,+}++@group(0) @binding(0) var<uniform> su: StampUniform;+@group(1) @binding(0) var shapes: texture_2d_array<f32>;+@group(1) @binding(1) var grains: texture_2d_array<f32>;+@group(1) @binding(2) var shape_smp: sampler;+@group(1) @binding(3) var grain_smp: sampler;+// how much of each canvas pixel is selected (all of it without a selection)+@group(1) @binding(4) var selected: texture_2d<f32>;++struct StampIn {+ @location(0) center: vec2<f32>,+ @location(1) radius: f32,+ @location(2) alpha: f32,+ @location(3) angle: f32,+ @location(4) roundness: f32,+ @location(5) grain_offset: vec2<f32>,+ @location(6) flip: vec2<f32>,+ @location(7) shift: vec4<f32>,+ // a moving grain's depth and tile size as multiples of the brush's; the secondary colour's share+ @location(8) look: vec4<f32>,+ // how far the paint fills a moving grain in, and room for more+ @location(9) more: vec4<f32>,+}++struct StampOut {+ @builtin(position) pos: vec4<f32>,+ // position in the stamp's own frame, in radii (the shape spans -1..1)+ @location(0) q: vec2<f32>,+ @location(1) radius: f32,+ @location(2) alpha: f32,+ // where a moving grain is read from: the stamp's middle in it, plus the point's place from+ // there on the canvas (the grain never turns or squashes with the stamp)+ @location(3) grain_at: vec2<f32>,+ @location(4) flip: vec2<f32>,+ @location(5) shift: vec3<f32>,+ // how hard the paint is pressed into a moving grain, and how much that counts+ @location(8) grain_press: f32,+ @location(10) grain_bleed: f32,+ @location(6) look: vec4<f32>,+ // what light pressure lets through: the most a capped stroke builds up to+ @location(7) transfer: f32,+}++@vertex+fn vs_stamp(@builtin(vertex_index) vi: u32, inst: StampIn) -> StampOut {+ var corners = array<vec2<f32>, 6>(+ vec2<f32>(-1.0, -1.0), vec2<f32>(1.0, -1.0), vec2<f32>(1.0, 1.0),+ vec2<f32>(-1.0, -1.0), vec2<f32>(1.0, 1.0), vec2<f32>(-1.0, 1.0),+ );+ let r = max(inst.radius, 0.25);+ // one pixel to spare for anti-aliasing+ let grow = (r + 1.0) / r;+ let q = corners[vi % 6u] * grow;+ let local = vec2<f32>(q.x * r, q.y * r * inst.roundness);+ let c = cos(inst.angle);+ let s = sin(inst.angle);+ let p = inst.center + vec2<f32>(local.x * c - local.y * s, local.x * s + local.y * c);+ var o: StampOut;+ o.pos = vec4<f32>(p.x / su.canvas_size.x * 2.0 - 1.0, 1.0 - p.y / su.canvas_size.y * 2.0, 0.0, 1.0);+ o.q = q;+ o.radius = r;+ o.alpha = inst.alpha;+ o.grain_at = inst.grain_offset + (p - inst.center);+ o.flip = inst.flip;+ o.shift = inst.shift.xyz;+ o.look = inst.look;+ o.grain_press = inst.more.x;+ o.grain_bleed = inst.more.y;+ o.transfer = inst.more.z;+ return o;+}++// hue (0..1), saturation and lightness of a colour, and back+fn to_hsl(c: vec3<f32>) -> vec3<f32> {+ let hi = max(c.r, max(c.g, c.b));+ let lo = min(c.r, min(c.g, c.b));+ let l = (hi + lo) * 0.5;+ let d = hi - lo;+ if (d <= 1e-5) {+ return vec3<f32>(0.0, 0.0, l);+ }+ let s = d / (1.0 - abs(2.0 * l - 1.0) + 1e-5);+ var h = 0.0;+ if (hi == c.r) {+ h = (c.g - c.b) / d;+ } else if (hi == c.g) {+ h = (c.b - c.r) / d + 2.0;+ } else {+ h = (c.r - c.g) / d + 4.0;+ }+ return vec3<f32>(fract(h / 6.0), clamp(s, 0.0, 1.0), l);+}++fn from_hsl(c: vec3<f32>) -> vec3<f32> {+ let k = vec3<f32>(0.0, 2.0 / 3.0, 1.0 / 3.0);+ let p = abs(fract(vec3<f32>(c.x) + k) * 6.0 - 3.0);+ let rgb = clamp(p - 1.0, vec3<f32>(0.0), vec3<f32>(1.0));+ let chroma = (1.0 - abs(2.0 * c.z - 1.0)) * c.y;+ return c.z + chroma * (rgb - 0.5);+}++// the shape image's texel under `uv`, unfiltered+fn shape_texel(uv: vec2<f32>, layer: i32) -> f32 {+ let size = vec2<i32>(textureDimensions(shapes));+ let at = clamp(vec2<i32>(floor(uv * vec2<f32>(size))), vec2<i32>(0), size - 1);+ return textureLoad(shapes, at, layer, 0).r;+}++@fragment+fn fs_stamp(i: StampOut) -> @location(0) vec4<f32> {+ return stamp_paint(i);+}++// a stamp's premultiplied paint at a pixel+fn stamp_paint(i: StampOut) -> vec4<f32> {+ let r = i.radius;+ var a = 0.0;+ if (su.shape < 0) {+ let d = length(i.q) * r;+ // a one-pixel anti-aliased rim, and the brush's own falloff from hardness·r outwards+ let rim = clamp(r - d + 0.5, 0.0, 1.0);+ let soft = 1.0 - smoothstep(min(su.hardness, 0.999) * r, r + 0.5, d);+ a = min(rim, soft);+ } else {+ let uv = i.q * i.flip * 0.5 + 0.5;+ // the mip level that matches the stamp's size on the canvas+ let lod = max(log2(256.0 / max(2.0 * r, 1.0)), 0.0);+ let inside = all(uv >= vec2<f32>(0.0)) && all(uv <= vec2<f32>(1.0));+ var s = textureSampleLevel(shapes, shape_smp, uv, su.shape, lod).r;+ if (su.shape_sharp == 1u) {+ s = shape_texel(uv, su.shape);+ }+ a = select(0.0, s, inside);+ }+ if (su.grain >= 0) {+ let scale = su.grain_scale * i.look.y;+ let gc = cos(su.grain_rotation);+ let gs = sin(su.grain_rotation);+ let at = i.grain_at;+ let g_uv = vec2<f32>(at.x * gc - at.y * gs, at.x * gs + at.y * gc) / scale;+ let sharp = su.grain_sharp == 1u;+ let g_lod = select(max(log2(256.0 / scale), 0.0), 0.0, sharp);+ var raw = textureSampleLevel(grains, grain_smp, g_uv, su.grain, g_lod).r;+ if (sharp) {+ raw = sharp_grain(raw, g_uv);+ }+ var g = clamp((raw - 0.5) * (1.0 + su.grain_contrast) + 0.5 + su.grain_brightness, 0.0, 1.0);+ if (i.grain_bleed > 0.0) {+ // pressed in as far as the pressure's bleed says+ g = mix(g, pressed_in(g, i.grain_press), i.grain_bleed);+ }+ // combined with the shape by the grain's blend mode, as deep as it says, inside the shape+ a = grain_combine(a, g, clamp(su.grain_depth * i.look.x, 0.0, 1.0), su.grain_blend) * select(0.0, 1.0, a > 0.0);+ }+ // a leaning pen shades it across its width, strongest at its leading edge+ if (i.look.w > 0.0) {+ a = a * (1.0 - i.look.w * clamp(0.5 - 0.5 * i.q.x, 0.0, 1.0));+ }+ // a stamp smaller than a pixel covers only part of it+ let small = min(r * 2.0, 1.0);+ // paint keeps inside the selection+ let inside_selection = textureSampleLevel(selected, shape_smp, i.pos.xy / su.canvas_size, 0.0).r;+ a = a * small * small * i.alpha * inside_selection;+ var color = mix(su.color.rgb, su.secondary.rgb, i.look.z);+ if (any(i.shift != vec3<f32>(0.0))) {+ let hsl = to_hsl(color);+ color = from_hsl(vec3<f32>(fract(hsl.x + i.shift.x + 1.0), clamp(hsl.y + i.shift.y, 0.0, 1.0), clamp(hsl.z + i.shift.z, 0.0, 1.0)));+ }+ return vec4<f32>(color * a, a);+}diff --git a/crates/gpu/src/shaders/stamp_capped.wgsl b/crates/gpu/src/shaders/stamp_capped.wgslnew file mode 100644index 0000000..c17fca6--- /dev/null+++ b/crates/gpu/src/shaders/stamp_capped.wgsl@@ -0,0 +1,18 @@++// A capped stamp (the uniformed glaze): its paint scaled by its transfer over what is there, kept+// by what the stamp leaves, so the stroke builds up towards the transfer and never past it.+// Appended to stamp.wgsl in a module that enables dual-source blending.++struct CappedOut {+ @location(0) @blend_src(0) paint: vec4<f32>,+ @location(0) @blend_src(1) keep: vec4<f32>,+}++@fragment+fn fs_stamp_capped(i: StampOut) -> CappedOut {+ let s = stamp_paint(i);+ var o: CappedOut;+ o.paint = s * clamp(i.transfer, 0.0, 1.0);+ o.keep = vec4<f32>(s.a);+ return o;+}diff --git a/crates/gpu/src/shaders/surround.wgsl b/crates/gpu/src/shaders/surround.wgslnew file mode 100644index 0000000..4025f25--- /dev/null+++ b/crates/gpu/src/shaders/surround.wgsl@@ -0,0 +1,38 @@+// Grid lines over the colour around the canvas, fixed to the window.++struct SurroundUniform {+ // (spacing, origin x, origin y, line width), in target pixels+ v0: vec4<f32>,+ // (line colour, 1 when the target encodes sRGB itself)+ v1: vec4<f32>,+}++@group(0) @binding(0) var<uniform> su: SurroundUniform;++@vertex+fn vs_surround(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {+ let uv = vec2<f32>(f32((vi << 1u) & 2u), f32(vi & 2u));+ return vec4<f32>(uv * 2.0 - 1.0, 0.0, 1.0);+}++fn srgb_to_linear(c: vec3<f32>) -> vec3<f32> {+ let lo = c / 12.92;+ let hi = pow((c + 0.055) / 1.055, vec3<f32>(2.4));+ return select(hi, lo, c <= vec3<f32>(0.04045));+}++@fragment+fn fs_surround(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let p = pos.xy - su.v0.yz;+ let s = su.v0.x;+ // how far this pixel's centre is from the nearest line across and down+ let d = abs(p - round(p / s) * s);+ if (p.y < 0.0 || min(d.x, d.y) >= su.v0.w * 0.5) {+ discard;+ }+ var rgb = su.v1.rgb;+ if (su.v1.w > 0.5) {+ rgb = srgb_to_linear(rgb);+ }+ return vec4<f32>(rgb, 1.0);+}diff --git a/crates/gpu/src/shaders/transform.wgsl b/crates/gpu/src/shaders/transform.wgslnew file mode 100644index 0000000..329f305--- /dev/null+++ b/crates/gpu/src/shaders/transform.wgsl@@ -0,0 +1,121 @@+// A layer redrawn from its copy: through a projective map (each layer pixel looks up where it+// came from in the copy), or as a mesh of triangles each carrying where its corners came from+// (a warp). Either way the copy is filtered there (nearest, bilinear or bicubic). With a+// selection only what it selects moves, over what it leaves where it was. Premultiplied+// throughout.++struct TransformUniform {+ // the map from layer pixel coordinates to copy pixel coordinates, row by row (3 × 3)+ r0: vec4<f32>,+ r1: vec4<f32>,+ r2: vec4<f32>,+ // (filter: 0 nearest, 1 bilinear, 2 bicubic, the copy's width, height, 1 with a selection)+ p: vec4<f32>,+}++@group(0) @binding(0) var src: texture_2d<f32>;+@group(0) @binding(1) var smp: sampler;+// how much of each pixel the selection takes (read only with a selection)+@group(0) @binding(2) var chosen: texture_2d<f32>;+@group(1) @binding(0) var<uniform> tu: TransformUniform;++@vertex+fn vs_transform(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {+ let uv = vec2<f32>(f32((vi << 1u) & 2u), f32(vi & 2u));+ return vec4<f32>(uv * 2.0 - 1.0, 0.0, 1.0);+}++// how much of copy pixel i moves: all of it, or what the selection takes+fn moving(i: vec2<i32>) -> f32 {+ if (tu.p.w > 0.5) {+ return textureLoad(chosen, i, 0).r;+ }+ return 1.0;+}++// what moves of a copy pixel, transparent outside the copy+fn texel(i: vec2<i32>) -> vec4<f32> {+ let size = vec2<i32>(i32(tu.p.y), i32(tu.p.z));+ if (i.x < 0 || i.y < 0 || i.x >= size.x || i.y >= size.y) {+ return vec4<f32>(0.0);+ }+ return textureLoad(src, i, 0) * moving(i);+}++// what stays where it was: the copy where the selection does not take it+@fragment+fn fs_static(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let i = vec2<i32>(pos.xy);+ return textureLoad(src, i, 0) * (1.0 - moving(i));+}++// Catmull-Rom weights for the four taps around a fraction t+fn cubic(t: f32) -> vec4<f32> {+ let t2 = t * t;+ let t3 = t2 * t;+ return vec4<f32>(+ -0.5 * t3 + t2 - 0.5 * t,+ 1.5 * t3 - 2.5 * t2 + 1.0,+ -1.5 * t3 + 2.0 * t2 + 0.5 * t,+ 0.5 * t3 - 0.5 * t2,+ );+}++// the copy filtered at copy coordinate s (pixel centres at +0.5)+fn filtered(s: vec2<f32>) -> vec4<f32> {+ let kind = i32(tu.p.x);+ if (kind == 0) {+ return texel(vec2<i32>(floor(s)));+ }+ let c = s - 0.5;+ let base = vec2<i32>(floor(c));+ let f = c - floor(c);+ if (kind == 1) {+ let top = mix(texel(base), texel(base + vec2<i32>(1, 0)), f.x);+ let bottom = mix(texel(base + vec2<i32>(0, 1)), texel(base + vec2<i32>(1, 1)), f.x);+ return mix(top, bottom, f.y);+ }+ let wx = cubic(f.x);+ let wy = cubic(f.y);+ var sum = vec4<f32>(0.0);+ for (var j = 0; j < 4; j++) {+ var row = vec4<f32>(0.0);+ for (var i = 0; i < 4; i++) {+ row += wx[i] * texel(base + vec2<i32>(i - 1, j - 1));+ }+ sum += wy[j] * row;+ }+ // the cubic can overshoot: keep it a valid premultiplied colour+ let a = clamp(sum.a, 0.0, 1.0);+ return vec4<f32>(clamp(sum.rgb, vec3<f32>(0.0), vec3<f32>(a)), a);+}++@fragment+fn fs_transform(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {+ let h = vec3<f32>(pos.x, pos.y, 1.0);+ let w = dot(tu.r2.xyz, h);+ if (w <= 1e-6) {+ return vec4<f32>(0.0);+ }+ return filtered(vec2<f32>(dot(tu.r0.xyz, h), dot(tu.r1.xyz, h)) / w);+}++struct MeshOut {+ @builtin(position) pos: vec4<f32>,+ @location(0) origin: vec2<f32>,+}++// a mesh corner: where it goes in the layer and where it came from in the copy (pixels)+@vertex+fn vs_mesh(@location(0) at: vec2<f32>, @location(1) origin: vec2<f32>) -> MeshOut {+ let size = tu.p.yz;+ var out: MeshOut;+ out.pos = vec4<f32>(at.x / size.x * 2.0 - 1.0, 1.0 - at.y / size.y * 2.0, 0.0, 1.0);+ out.origin = origin;+ return out;+}++@fragment+fn fs_mesh(in: MeshOut) -> @location(0) vec4<f32> {+ return filtered(in.origin);+}diff --git a/crates/gpu/tests/canvas.rs b/crates/gpu/tests/canvas.rsnew file mode 100644index 0000000..571cabe--- /dev/null+++ b/crates/gpu/tests/canvas.rs@@ -0,0 +1,1185 @@+//! The canvas on a real GPU (skipped where the machine has none).+#![allow(clippy::unwrap_used, clippy::indexing_slicing)]++use procraft_engine::brush::{Brush, Rendering, Taper};+use procraft_engine::document::Document;+use procraft_engine::geom::{Homography, Vec2};+use procraft_engine::input::{Pointer, Sample};+use procraft_engine::profile::Profile;+use procraft_engine::stroke::{Stamp, StrokeBuilder};+use procraft_engine::view::View;+use procraft_gpu::{Backdrop, Canvas, Gpu, Resample, StrokeStyle, StrokeTool, SurroundGrid, Target, wgpu};++fn gpu() -> Option<Gpu> {+ match Gpu::headless() {+ Ok(g) => Some(g),+ Err(e) => {+ eprintln!("skipped: {e}");+ None+ }+ }+}++/// Fails the test if the GPU reported validation errors by its end.+struct NoErrors<'a>(&'a Gpu);++impl Drop for NoErrors<'_> {+ fn drop(&mut self) {+ if !std::thread::panicking() {+ assert_eq!(self.0.errors(), 0, "GPU validation errors");+ }+ }+}++fn style(tool: StrokeTool, opacity: f32) -> StrokeStyle {+ StrokeStyle::new(tool, [0.0; 3], opacity)+}++fn pixel(px: &[u8], width: u32, x: u32, y: u32) -> [u8; 4] {+ let i = ((y * width + x) * 4) as usize;+ [px[i], px[i + 1], px[i + 2], px[i + 3]]+}++fn dot(at: Vec2, radius: f32) -> Stamp {+ Stamp::round(at, radius, 1.0)+}++#[test]+fn paint_undo_redo() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let mut doc = Document::new(64, 64);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ canvas.render(&gpu, &mut doc, None);+ assert_eq!(pixel(&canvas.read_composite(&gpu).unwrap(), 64, 32, 32), [255, 255, 255, 255]);++ canvas.begin_stroke(doc.current(), style(StrokeTool::Paint, 1.0));+ canvas.add_stamps(&[dot(Vec2::new(32.0, 32.0), 8.0)]);+ canvas.render(&gpu, &mut doc, None);+ // drawn live, before the stroke ends+ assert_eq!(pixel(&canvas.read_composite(&gpu).unwrap(), 64, 32, 32), [0, 0, 0, 255]);+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);+ let px = canvas.read_composite(&gpu).unwrap();+ assert_eq!(pixel(&px, 64, 32, 32), [0, 0, 0, 255]);+ assert_eq!(pixel(&px, 64, 2, 2), [255, 255, 255, 255]);+ assert_eq!(pixel(&canvas.read_layer(&gpu, doc.current()).unwrap(), 64, 32, 32), [0, 0, 0, 255]);+ assert!(canvas.can_undo());++ canvas.undo();+ canvas.render(&gpu, &mut doc, None);+ assert_eq!(pixel(&canvas.read_composite(&gpu).unwrap(), 64, 32, 32), [255, 255, 255, 255]);+ assert!(canvas.can_redo());+ canvas.redo();+ canvas.render(&gpu, &mut doc, None);+ assert_eq!(pixel(&canvas.read_composite(&gpu).unwrap(), 64, 32, 32), [0, 0, 0, 255]);+}++#[test]+fn stroke_opacity_caps_build_up() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let mut doc = Document::new(64, 64);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ canvas.begin_stroke(doc.current(), style(StrokeTool::Paint, 0.5));+ // forty overlapping stamps: the stroke still only reaches its opacity+ let stamps: Vec<Stamp> = (0..40).map(|i| dot(Vec2::new(30.0 + i as f32 * 0.1, 32.0), 10.0)).collect();+ canvas.add_stamps(&stamps);+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);+ let [r, g, b, a] = pixel(&canvas.read_composite(&gpu).unwrap(), 64, 32, 32);+ assert!((126..=129).contains(&r) && r == g && g == b && a == 255, "got {r} {g} {b} {a}");+}++#[test]+fn erase_and_cancel() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let mut doc = Document::new(64, 64);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ canvas.begin_stroke(doc.current(), style(StrokeTool::Paint, 1.0));+ canvas.add_stamps(&[dot(Vec2::new(32.0, 32.0), 12.0)]);+ canvas.end_stroke();+ canvas.begin_stroke(doc.current(), style(StrokeTool::Erase, 1.0));+ canvas.add_stamps(&[dot(Vec2::new(32.0, 32.0), 4.0)]);+ canvas.render(&gpu, &mut doc, None);+ // the eraser shows while it is drawn+ assert_eq!(pixel(&canvas.read_composite(&gpu).unwrap(), 64, 32, 32), [255, 255, 255, 255]);+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);+ let layer = canvas.read_layer(&gpu, doc.current()).unwrap();+ assert_eq!(pixel(&layer, 64, 32, 32)[3], 0);+ assert_eq!(pixel(&layer, 64, 32, 24), [0, 0, 0, 255]);++ canvas.begin_stroke(doc.current(), style(StrokeTool::Paint, 1.0));+ canvas.add_stamps(&[dot(Vec2::new(5.0, 5.0), 3.0)]);+ canvas.cancel_stroke();+ canvas.render(&gpu, &mut doc, None);+ assert_eq!(pixel(&canvas.read_composite(&gpu).unwrap(), 64, 5, 5), [255, 255, 255, 255]);+}++#[test]+fn a_built_stroke_with_taper_and_clear() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let mut doc = Document::new(200, 100);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ let brush = Brush {+ streamline: 0.0,+ pen_taper: Taper { start: 0.0, end: 0.3, size: 1.0, opacity: 0.0 },+ ..Brush::round_pen()+ };+ let mut stroke = StrokeBuilder::new(brush, 12.0, Pointer::Stylus);+ canvas.begin_stroke(doc.current(), style(StrokeTool::Paint, 1.0));+ let samples: Vec<Sample> =+ (0..=20).map(|i| Sample::at(Vec2::new(10.0 + i as f32 * 9.0, 50.0), 1.0, i as f64 * 8.0)).collect();+ canvas.add_stamps(&stroke.add(&samples));+ canvas.replace_stamps(&stroke.finish());+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);+ let px = canvas.read_composite(&gpu).unwrap();+ // full width in the middle, tapered to nothing at the end+ assert_eq!(pixel(&px, 200, 60, 55), [0, 0, 0, 255]);+ assert_eq!(pixel(&px, 200, 188, 55), [255, 255, 255, 255]);++ canvas.clear_layer(doc.current());+ canvas.render(&gpu, &mut doc, None);+ assert_eq!(pixel(&canvas.read_composite(&gpu).unwrap(), 200, 60, 50), [255, 255, 255, 255]);+ canvas.undo();+ canvas.render(&gpu, &mut doc, None);+ assert_eq!(pixel(&canvas.read_composite(&gpu).unwrap(), 200, 60, 50), [0, 0, 0, 255]);+}++#[test]+fn draws_to_a_target_through_the_view() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let mut doc = Document::new(100, 100);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ canvas.begin_stroke(doc.current(), style(StrokeTool::Paint, 1.0));+ canvas.add_stamps(&[dot(Vec2::new(25.0, 25.0), 10.0)]);+ canvas.end_stroke();+ let format = wgpu::TextureFormat::Rgba8Unorm;+ let target = gpu.device.create_texture(&wgpu::TextureDescriptor {+ label: None,+ size: wgpu::Extent3d { width: 200, height: 100, depth_or_array_layers: 1 },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format,+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,+ view_formats: &[],+ });+ let view = target.create_view(&Default::default());+ // the canvas fits the middle 100×100 of a 200×100 target+ let to_screen = View::fit((100, 100), (200, 100)).to_screen();+ canvas.render(+ &gpu,+ &mut doc,+ Some(Target {+ view: &view,+ format,+ size: (200, 100),+ to_screen,+ surround: [0.2, 0.2, 0.2],+ grid: None,+ selection: None,+ backdrop: None,+ convert: None,+ lut: None,+ }),+ );+ let px = read(&gpu, &target, 200, 100);+ assert_eq!(pixel(&px, 200, 10, 50), [51, 51, 51, 255], "surround");+ assert_eq!(pixel(&px, 200, 75, 25), [0, 0, 0, 255], "the dot");+ assert_eq!(pixel(&px, 200, 125, 75), [255, 255, 255, 255], "canvas");+}++#[test]+fn the_surround_grid_is_fixed_to_the_target() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let mut doc = Document::new(10, 10);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ let format = wgpu::TextureFormat::Rgba8Unorm;+ let target = gpu.device.create_texture(&wgpu::TextureDescriptor {+ label: None,+ size: wgpu::Extent3d { width: 100, height: 100, depth_or_array_layers: 1 },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format,+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,+ view_formats: &[],+ });+ let view = target.create_view(&Default::default());+ // a tiny canvas in the top-left corner, the rest surround with a line every 20 px from y = 10+ let to_screen = View::fit((10, 10), (10, 10)).to_screen();+ let grid = SurroundGrid { spacing: 20.0, origin: [0.0, 10.0], width: 2.0, color: [1.0, 0.0, 0.0] };+ canvas.render(+ &gpu,+ &mut doc,+ Some(Target {+ view: &view,+ format,+ size: (100, 100),+ to_screen,+ surround: [0.2, 0.2, 0.2],+ grid: Some(grid),+ selection: None,+ backdrop: None,+ convert: None,+ lut: None,+ }),+ );+ let px = read(&gpu, &target, 100, 100);+ assert_eq!(pixel(&px, 100, 40, 30), [255, 0, 0, 255], "on a line across and down");+ assert_eq!(pixel(&px, 100, 39, 55), [255, 0, 0, 255], "on a line down, the pixel left of it");+ assert_eq!(pixel(&px, 100, 50, 45), [51, 51, 51, 255], "between lines");+ assert_eq!(pixel(&px, 100, 50, 5), [51, 51, 51, 255], "above the origin");+ assert_eq!(pixel(&px, 100, 5, 5), [255, 255, 255, 255], "the canvas covers the grid");+}++#[test]+fn a_frosted_region_shows_what_is_behind_it_blurred() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let mut doc = Document::new(100, 100);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ let format = wgpu::TextureFormat::Rgba8Unorm;+ let target = gpu.device.create_texture(&wgpu::TextureDescriptor {+ label: None,+ size: wgpu::Extent3d { width: 400, height: 100, depth_or_array_layers: 1 },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format,+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,+ view_formats: &[],+ });+ let view = target.create_view(&Default::default());+ // the white canvas on the left quarter, the dark surround right of it from x = 100, and a+ // region across that edge+ let to_screen = View::fit((100, 100), (100, 100)).to_screen();+ let regions = [[40.0, 10.0, 300.0, 90.0, 12.0, 1.0]];+ canvas.render(+ &gpu,+ &mut doc,+ Some(Target {+ view: &view,+ format,+ size: (400, 100),+ to_screen,+ surround: [0.0, 0.0, 0.0],+ grid: None,+ selection: None,+ backdrop: Some(Backdrop { regions: ®ions, sigma: 24.0 }),+ convert: None,+ lut: None,+ }),+ );+ let px = read(&gpu, &target, 400, 100);+ let red = |x: u32, y: u32| pixel(&px, 400, x, y)[0];+ // outside the region: as it was+ assert_eq!(red(20, 50), 255, "canvas left of the region");+ assert_eq!(red(350, 50), 0, "surround right of the region");+ assert_eq!(red(70, 5), 255, "canvas above the region");+ // inside: the edge spread out, falling from white to dark across it+ let (a, b, c, d) = (red(50, 50), red(90, 50), red(110, 50), red(150, 50));+ assert!(a > b && b > c && c > d, "{a} {b} {c} {d}");+ assert!((150..250).contains(&b) && (5..105).contains(&c), "{b} {c}");+ assert!(red(250, 50) < 3 && a > 240, "far from the edge: {}", red(250, 50));+ // the rounded corner leaves the canvas as it was+ assert_eq!(red(41, 11), 255);+}++#[test]+fn the_canvas_is_shown_in_the_targets_colour_space() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let mut doc = Document::new(10, 10);+ doc.background = [1.0, 0.0, 0.0];+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ let format = wgpu::TextureFormat::Rgba8Unorm;+ let target = gpu.device.create_texture(&wgpu::TextureDescriptor {+ label: None,+ size: wgpu::Extent3d { width: 10, height: 10, depth_or_array_layers: 1 },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format,+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,+ view_formats: &[],+ });+ let view = target.create_view(&Default::default());+ // an sRGB canvas on a Display P3 screen: its red is P3's (234, 51, 35)+ let convert = Some(Profile::Srgb.matrix_to(Profile::DisplayP3));+ canvas.render(+ &gpu,+ &mut doc,+ Some(Target {+ view: &view,+ format,+ size: (10, 10),+ to_screen: View::fit((10, 10), (10, 10)).to_screen(),+ surround: [0.0; 3],+ grid: None,+ selection: None,+ backdrop: None,+ convert,+ lut: None,+ }),+ );+ let px = read(&gpu, &target, 10, 10);+ let [r, g, b, _] = pixel(&px, 10, 5, 5);+ assert!(r.abs_diff(234) <= 1 && g.abs_diff(51) <= 1 && b.abs_diff(35) <= 1, "{r} {g} {b}");+}++#[test]+fn a_colour_table_moves_the_canvas_colours() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let mut doc = Document::new(10, 10);+ doc.background = [1.0, 0.25, 0.0];+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ let format = wgpu::TextureFormat::Rgba8Unorm;+ let target = gpu.device.create_texture(&wgpu::TextureDescriptor {+ label: None,+ size: wgpu::Extent3d { width: 10, height: 10, depth_or_array_layers: 1 },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format,+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,+ view_formats: &[],+ });+ let view = target.create_view(&Default::default());+ // a table turning each colour round (red to green to blue to red) and inverting it+ let grid = 17;+ let mut values = Vec::new();+ for r in 0..grid {+ for g in 0..grid {+ for b in 0..grid {+ let v = |i: usize| 1.0 - i as f32 / (grid - 1) as f32;+ values.extend([v(b), v(r), v(g)]);+ }+ }+ }+ let lut = canvas.display_lut(&gpu, &procraft_engine::cms::Lut { grid, outputs: 3, values });+ canvas.render(+ &gpu,+ &mut doc,+ Some(Target {+ view: &view,+ format,+ size: (10, 10),+ to_screen: View::fit((10, 10), (10, 10)).to_screen(),+ surround: [0.0; 3],+ grid: None,+ selection: None,+ backdrop: None,+ convert: None,+ lut: Some(&lut),+ }),+ );+ let px = read(&gpu, &target, 10, 10);+ let [r, g, b, _] = pixel(&px, 10, 5, 5);+ // (1, 0.25, 0) becomes (1 - 0, 1 - 1, 1 - 0.25)+ assert!(r >= 254 && g <= 1 && b.abs_diff(191) <= 2, "{r} {g} {b}");+}++fn read(gpu: &Gpu, texture: &wgpu::Texture, width: u32, height: u32) -> Vec<u8> {+ let padded = (width * 4).div_ceil(256) * 256;+ let buffer = gpu.device.create_buffer(&wgpu::BufferDescriptor {+ label: None,+ size: u64::from(padded * height),+ usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });+ let mut encoder = gpu.device.create_command_encoder(&Default::default());+ encoder.copy_texture_to_buffer(+ texture.as_image_copy(),+ wgpu::TexelCopyBufferInfo {+ buffer: &buffer,+ layout: wgpu::TexelCopyBufferLayout {+ offset: 0,+ bytes_per_row: Some(padded),+ rows_per_image: Some(height),+ },+ },+ wgpu::Extent3d { width, height, depth_or_array_layers: 1 },+ );+ gpu.queue.submit([encoder.finish()]);+ buffer.slice(..).map_async(wgpu::MapMode::Read, |_| {});+ gpu.device.poll(wgpu::PollType::wait_indefinitely()).unwrap();+ let mapped = buffer.slice(..).get_mapped_range().unwrap();+ mapped.chunks(padded as usize).flat_map(|row| row[..(width * 4) as usize].to_vec()).collect()+}++#[test]+fn the_predicted_tail_shows_but_never_paints() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let mut doc = Document::new(100, 100);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ let format = wgpu::TextureFormat::Rgba8Unorm;+ let target = gpu.device.create_texture(&wgpu::TextureDescriptor {+ label: None,+ size: wgpu::Extent3d { width: 100, height: 100, depth_or_array_layers: 1 },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format,+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,+ view_formats: &[],+ });+ let view = target.create_view(&Default::default());+ let to_screen = View::fit((100, 100), (100, 100)).to_screen();+ let frame = |canvas: &mut Canvas, doc: &mut Document| {+ canvas.render(+ &gpu,+ doc,+ Some(Target {+ view: &view,+ format,+ size: (100, 100),+ to_screen,+ surround: [0.0; 3],+ grid: None,+ selection: None,+ backdrop: None,+ convert: None,+ lut: None,+ }),+ );+ read(&gpu, &target, 100, 100)+ };+ canvas.begin_stroke(doc.current(), style(StrokeTool::Paint, 1.0));+ canvas.add_stamps(&[dot(Vec2::new(20.0, 50.0), 5.0)]);+ canvas.set_prediction(&[dot(Vec2::new(80.0, 50.0), 5.0)]);+ let px = frame(&mut canvas, &mut doc);+ assert_eq!(pixel(&px, 100, 20, 50), [0, 0, 0, 255], "the stroke");+ assert_eq!(pixel(&px, 100, 80, 50), [0, 0, 0, 255], "the predicted tail");+ assert_eq!(pixel(&canvas.read_composite(&gpu).unwrap(), 100, 80, 50), [255, 255, 255, 255], "not in the canvas");+ canvas.end_stroke();+ let px = frame(&mut canvas, &mut doc);+ assert_eq!(pixel(&px, 100, 80, 50), [255, 255, 255, 255], "gone when the stroke ends");+ assert_eq!(pixel(&px, 100, 20, 50), [0, 0, 0, 255]);+}++#[test]+fn a_transform_moves_the_layer_and_undoes_as_one_step() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let mut doc = Document::new(64, 64);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ let layer = doc.current();+ canvas.begin_stroke(layer, style(StrokeTool::Paint, 1.0));+ canvas.add_stamps(&[dot(Vec2::new(16.0, 16.0), 4.0)]);+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);++ let at = |x: f32, y: f32| {+ [Vec2::new(x, y), Vec2::new(x + 64.0, y), Vec2::new(x + 64.0, y + 64.0), Vec2::new(x, y + 64.0)]+ };+ // moved 20 right and 10 down: each layer pixel comes from 20 left and 10 up+ let to_source = Homography::quad_to_quad(at(20.0, 10.0), at(0.0, 0.0)).unwrap().to_f32();+ canvas.begin_transform(layer);+ assert!(canvas.is_transforming());+ canvas.set_transform(to_source, Resample::Nearest);+ canvas.render(&gpu, &mut doc, None);+ let px = canvas.read_layer(&gpu, layer).unwrap();+ assert_eq!(pixel(&px, 64, 36, 26), [0, 0, 0, 255]);+ assert_eq!(pixel(&px, 64, 16, 16)[3], 0);+ // redrawn from the copy each time, so moving it again does not lose what left the canvas+ canvas.set_transform(Homography::quad_to_quad(at(60.0, 0.0), at(0.0, 0.0)).unwrap().to_f32(), Resample::Bilinear);+ canvas.set_transform(to_source, Resample::Bicubic);+ canvas.end_transform(true);+ canvas.render(&gpu, &mut doc, None);+ assert!(!canvas.is_transforming());+ let px = canvas.read_layer(&gpu, layer).unwrap();+ assert_eq!(pixel(&px, 64, 36, 26), [0, 0, 0, 255]);+ assert_eq!(pixel(&px, 64, 16, 16)[3], 0);++ canvas.undo();+ canvas.render(&gpu, &mut doc, None);+ let px = canvas.read_layer(&gpu, layer).unwrap();+ assert_eq!(pixel(&px, 64, 16, 16), [0, 0, 0, 255]);+ assert_eq!(pixel(&px, 64, 36, 26)[3], 0);+ canvas.redo();+ canvas.render(&gpu, &mut doc, None);+ assert_eq!(pixel(&canvas.read_layer(&gpu, layer).unwrap(), 64, 36, 26), [0, 0, 0, 255]);++ // cancelled: put back, with no new step+ canvas.undo();+ canvas.begin_transform(layer);+ canvas.set_transform(to_source, Resample::Nearest);+ canvas.end_transform(false);+ canvas.render(&gpu, &mut doc, None);+ let px = canvas.read_layer(&gpu, layer).unwrap();+ assert_eq!(pixel(&px, 64, 16, 16), [0, 0, 0, 255]);+ assert_eq!(pixel(&px, 64, 36, 26)[3], 0);+ canvas.undo();+ canvas.render(&gpu, &mut doc, None);+ assert_eq!(pixel(&canvas.read_layer(&gpu, layer).unwrap(), 64, 16, 16)[3], 0);+}++#[test]+fn a_warp_mesh_redraws_the_layer_from_its_copy() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let mut doc = Document::new(64, 64);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ let layer = doc.current();+ canvas.begin_stroke(layer, style(StrokeTool::Paint, 1.0));+ canvas.add_stamps(&[dot(Vec2::new(16.0, 16.0), 4.0)]);+ canvas.end_stroke();+ canvas.begin_transform(layer);+ // the copy's top-left 32 × 32 drawn 20 right and 10 down, as two triangles+ let corner = |x: f32, y: f32| [x + 20.0, y + 10.0, x, y];+ let mesh = [+ corner(0.0, 0.0),+ corner(32.0, 0.0),+ corner(32.0, 32.0),+ corner(0.0, 0.0),+ corner(32.0, 32.0),+ corner(0.0, 32.0),+ ];+ canvas.set_transform_mesh(&mesh, Resample::Nearest);+ canvas.render(&gpu, &mut doc, None);+ let px = canvas.read_layer(&gpu, layer).unwrap();+ assert_eq!(pixel(&px, 64, 36, 26), [0, 0, 0, 255]);+ assert_eq!(pixel(&px, 64, 16, 16)[3], 0);+ canvas.end_transform(true);+ canvas.undo();+ canvas.render(&gpu, &mut doc, None);+ assert_eq!(pixel(&canvas.read_layer(&gpu, layer).unwrap(), 64, 16, 16), [0, 0, 0, 255]);+}++#[test]+fn a_selection_keeps_paint_inside_and_stripes_the_rest() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let mut doc = Document::new(64, 64);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ // the left half selected+ let coverage: Vec<u8> = (0..64 * 64).map(|i| if i % 64 < 32 { 255 } else { 0 }).collect();+ canvas.set_selection(&gpu, Some(&coverage));+ assert!(canvas.has_selection());+ canvas.begin_stroke(doc.current(), style(StrokeTool::Paint, 1.0));+ canvas.add_stamps(&[dot(Vec2::new(32.0, 32.0), 12.0)]);+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);+ let px = canvas.read_layer(&gpu, doc.current()).unwrap();+ assert_eq!(pixel(&px, 64, 26, 32), [0, 0, 0, 255]);+ assert_eq!(pixel(&px, 64, 38, 32)[3], 0);++ // white canvas shown 1:1: bands of grey over the right half only+ let format = wgpu::TextureFormat::Rgba8Unorm;+ let texture = gpu.device.create_texture(&wgpu::TextureDescriptor {+ label: None,+ size: wgpu::Extent3d { width: 64, height: 64, depth_or_array_layers: 1 },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format,+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,+ view_formats: &[],+ });+ let view = texture.create_view(&Default::default());+ let stripes = procraft_gpu::Stripes { period: 8.0, drift: 0.0, coverage: 0.5 };+ let to_screen = procraft_engine::geom::Affine::IDENTITY;+ canvas.render(+ &gpu,+ &mut doc,+ Some(Target {+ view: &view,+ format,+ size: (64, 64),+ to_screen,+ surround: [0.0; 3],+ grid: None,+ selection: Some(procraft_gpu::SelectionLook::Stripes(stripes)),+ backdrop: None,+ convert: None,+ lut: None,+ }),+ );+ let shown = read(&gpu, &texture, 64, 64);+ let row: Vec<u8> = (32..48).map(|x| pixel(&shown, 64, x, 50)[0]).collect();+ // over white the dark bands show at half coverage, the light ones not at all+ assert!(row.contains(&255) && row.iter().any(|&v| (120..=135).contains(&v)), "{row:?}");+ assert!((0..16).all(|x| pixel(&shown, 64, x, 50)[0] == 255));+ canvas.set_selection(&gpu, None);+ assert!(!canvas.has_selection());+}++#[test]+fn adjustments_redraw_the_layer_and_keep_to_the_selection() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let mut doc = Document::new(64, 64);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ let layer = doc.current();+ // a red square across the middle+ let mut red = StrokeStyle::new(StrokeTool::Paint, [1.0, 0.0, 0.0], 1.0);+ red.hardness = 1.0;+ canvas.begin_stroke(layer, red);+ canvas.add_stamps(&[dot(Vec2::new(32.0, 32.0), 20.0)]);+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);++ // no chroma left: the grey of red's luma+ canvas.begin_transform(layer);+ canvas.set_filter(procraft_gpu::Filter::Hsb { hue: 0.0, saturation: 0.0, brightness: 0.0 });+ canvas.render(&gpu, &mut doc, None);+ let [r, g, b, a] = pixel(&canvas.read_layer(&gpu, layer).unwrap(), 64, 32, 32);+ assert!(r.abs_diff(g) <= 1 && g.abs_diff(b) <= 1 && r.abs_diff(76) <= 2 && a == 255, "{r} {g} {b}");+ // half a turn: the opposite of red+ canvas.set_filter(procraft_gpu::Filter::Hsb { hue: std::f32::consts::PI, saturation: 1.0, brightness: 0.0 });+ canvas.render(&gpu, &mut doc, None);+ let [r, g, b, _] = pixel(&canvas.read_layer(&gpu, layer).unwrap(), 64, 32, 32);+ assert!(g > r && b > r, "{r} {g} {b}");+ // put back+ canvas.end_transform(false);+ canvas.render(&gpu, &mut doc, None);+ assert_eq!(pixel(&canvas.read_layer(&gpu, layer).unwrap(), 64, 32, 32), [255, 0, 0, 255]);++ // blurred, with the left half selected: only the left half softens+ let coverage: Vec<u8> = (0..64 * 64).map(|i| if i % 64 < 32 { 255 } else { 0 }).collect();+ canvas.set_selection(&gpu, Some(&coverage));+ canvas.begin_transform(layer);+ canvas.set_filter(procraft_gpu::Filter::Blur { sigma: 6.0 });+ canvas.render(&gpu, &mut doc, None);+ let px = canvas.read_layer(&gpu, layer).unwrap();+ // the left edge of the disc spreads outwards, the right edge stays sharp+ assert!(pixel(&px, 64, 9, 32)[3] > 10, "{:?}", pixel(&px, 64, 9, 32));+ assert_eq!(pixel(&px, 64, 53, 32)[3], 0);+ assert_eq!(pixel(&px, 64, 50, 32), [255, 0, 0, 255]);+ canvas.end_transform(true);+ canvas.render(&gpu, &mut doc, None);+ assert!(canvas.can_undo());+ canvas.undo();+ canvas.render(&gpu, &mut doc, None);+ assert_eq!(pixel(&canvas.read_layer(&gpu, layer).unwrap(), 64, 9, 32)[3], 0);+ // a wide blur runs at a smaller size+ canvas.begin_transform(layer);+ canvas.set_filter(procraft_gpu::Filter::Blur { sigma: 60.0 });+ canvas.end_transform(true);+ canvas.render(&gpu, &mut doc, None);+}++#[test]+fn every_adjustment_draws_and_changes_the_layer() {+ use procraft_gpu::Filter;+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let mut doc = Document::new(64, 64);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ let layer = doc.current();+ let mut grey = StrokeStyle::new(StrokeTool::Paint, [0.5, 0.5, 0.5], 1.0);+ grey.hardness = 1.0;+ canvas.begin_stroke(layer, grey);+ canvas.add_stamps(&[dot(Vec2::new(32.0, 32.0), 14.0)]);+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);+ let original = canvas.read_layer(&gpu, layer).unwrap();+ let filters = [+ Filter::Sharpen { amount: 1.0 },+ Filter::Noise { amount: 1.0, frequency: 0.45, octaves: 3, turbulence: 0.2, kind: 0, multi: false, added: true },+ Filter::Noise { amount: 1.0, frequency: 0.2, octaves: 2, turbulence: 0.2, kind: 1, multi: true, added: false },+ Filter::Noise { amount: 1.0, frequency: 0.2, octaves: 1, turbulence: 0.2, kind: 2, multi: false, added: true },+ Filter::Motion { along: [20.0, 0.0] },+ Filter::Zoom { centre: [0.0, 0.0], amount: 0.3 },+ Filter::Chromatic {+ centre: [0.0, 0.0],+ amount: 0.2,+ displace: false,+ offset: [0.0; 2],+ blur: 0.5,+ falloff: 0.2,+ transparency: 0.0,+ },+ Filter::Chromatic {+ centre: [0.0, 0.0],+ amount: 0.0,+ displace: true,+ offset: [6.0, 2.0],+ blur: 0.3,+ falloff: 0.0,+ transparency: 0.5,+ },+ Filter::Halftone { pitch: 8.0, kind: 0 },+ Filter::Halftone { pitch: 8.0, kind: 1 },+ Filter::Halftone { pitch: 8.0, kind: 2 },+ Filter::Bloom { sigma: 6.0, amount: 1.0, threshold: 0.0, transition: 1.0, burn: 0.15 },+ Filter::Glitch { kind: 0, amount: 1.0, values: [1.0, 0.3, 0.0], zoom: 1.0, seed: 0.5 },+ Filter::Glitch { kind: 1, amount: 1.0, values: [1.0, 0.5, 0.0], zoom: 0.2, seed: 0.5 },+ Filter::Glitch { kind: 2, amount: 1.0, values: [1.0, 0.3, 0.0], zoom: 1.0, seed: 0.5 },+ Filter::Glitch { kind: 3, amount: 1.0, values: [1.0, -0.5, 0.8], zoom: 0.5, seed: 0.5 },+ ];+ for f in filters {+ canvas.begin_transform(layer);+ canvas.set_filter(f);+ canvas.render(&gpu, &mut doc, None);+ let px = canvas.read_layer(&gpu, layer).unwrap();+ assert_ne!(px, original, "{f:?} changed nothing");+ canvas.end_transform(false);+ canvas.render(&gpu, &mut doc, None);+ assert_eq!(canvas.read_layer(&gpu, layer).unwrap(), original, "{f:?} was not put back");+ }+}++#[test]+fn curves_gradient_maps_and_colour_balance_draw() {+ use procraft_gpu::Filter;+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let mut doc = Document::new(32, 32);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ let layer = doc.current();+ let mut grey = StrokeStyle::new(StrokeTool::Paint, [0.5, 0.5, 0.5], 1.0);+ grey.hardness = 1.0;+ canvas.begin_stroke(layer, grey);+ canvas.add_stamps(&[dot(Vec2::new(16.0, 16.0), 12.0)]);+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);+ // every channel to full: white+ let table: Vec<u8> = (0..256).flat_map(|_| [255u8, 255, 255, 255]).collect();+ canvas.set_table(&gpu, &table);+ canvas.begin_transform(layer);+ canvas.set_filter(Filter::Curves);+ canvas.render(&gpu, &mut doc, None);+ assert_eq!(pixel(&canvas.read_layer(&gpu, layer).unwrap(), 32, 16, 16), [255, 255, 255, 255]);+ // a red gradient, all the way+ let red: Vec<u8> = (0..256).flat_map(|_| [255u8, 0, 0, 255]).collect();+ canvas.set_table(&gpu, &red);+ canvas.set_filter(Filter::GradientMap { amount: 1.0 });+ canvas.render(&gpu, &mut doc, None);+ assert_eq!(pixel(&canvas.read_layer(&gpu, layer).unwrap(), 32, 16, 16), [255, 0, 0, 255]);+ // more red in the midtones: redder, as bright+ canvas.set_filter(Filter::ColorBalance { shadows: [0.0; 3], midtones: [1.0, 0.0, 0.0], highlights: [0.0; 3] });+ canvas.render(&gpu, &mut doc, None);+ let [r, g, _, _] = pixel(&canvas.read_layer(&gpu, layer).unwrap(), 32, 16, 16);+ assert!(r > g + 40, "{r} {g}");+ canvas.end_transform(false);+ canvas.render(&gpu, &mut doc, None);+}++#[test]+fn liquify_pushes_paint_along_and_reconstructs() {+ use procraft_gpu::{Filter, LiquifyMode, LiquifyStamp};+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let mut doc = Document::new(64, 64);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ let layer = doc.current();+ canvas.begin_stroke(layer, style(StrokeTool::Paint, 1.0));+ canvas.add_stamps(&[dot(Vec2::new(20.0, 32.0), 6.0)]);+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);+ canvas.begin_transform(layer);+ canvas.begin_liquify();+ // pushed 10 to the right, in small steps+ let push = |x: f32| LiquifyStamp {+ centre: [x, 32.0],+ moved: [2.0, 0.0],+ radius: 20.0,+ pressure: 1.0,+ distortion: 0.0,+ seed: 0.0,+ mode: LiquifyMode::Push,+ };+ canvas.liquify_stamps(&[push(20.0), push(22.0), push(24.0), push(26.0), push(28.0)]);+ canvas.set_filter(Filter::Liquify { amount: 1.0 });+ canvas.render(&gpu, &mut doc, None);+ let px = canvas.read_layer(&gpu, layer).unwrap();+ assert!(pixel(&px, 64, 28, 32)[3] > 200, "{:?}", pixel(&px, 64, 28, 32));+ assert!(pixel(&px, 64, 15, 32)[3] < 50, "{:?}", pixel(&px, 64, 15, 32));+ // reconstructed many times over: back where it was+ let back = LiquifyStamp { mode: LiquifyMode::Reconstruct, ..push(26.0) };+ canvas.liquify_stamps(&vec![back; 60]);+ canvas.set_filter(Filter::Liquify { amount: 1.0 });+ canvas.render(&gpu, &mut doc, None);+ let px = canvas.read_layer(&gpu, layer).unwrap();+ assert!(pixel(&px, 64, 15, 32)[3] > 200, "{:?}", pixel(&px, 64, 15, 32));+ canvas.liquify_clear();+ canvas.end_transform(true);+ canvas.render(&gpu, &mut doc, None);+}++#[test]+fn an_adjustment_painted_on_shows_only_where_painted_and_clone_copies() {+ use procraft_gpu::Filter;+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let mut doc = Document::new(64, 64);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ let layer = doc.current();+ let mut red = StrokeStyle::new(StrokeTool::Paint, [1.0, 0.0, 0.0], 1.0);+ red.hardness = 1.0;+ canvas.begin_stroke(layer, red);+ canvas.add_stamps(&[dot(Vec2::new(16.0, 32.0), 10.0)]);+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);++ // brightness down everywhere, but painted on only at the left+ canvas.begin_transform(layer);+ canvas.begin_pencil();+ assert!(canvas.is_pencil());+ let mut white = StrokeStyle::new(StrokeTool::Paint, [1.0, 1.0, 1.0], 1.0);+ white.hardness = 1.0;+ canvas.begin_pencil_stroke(layer, white);+ canvas.add_stamps(&[dot(Vec2::new(10.0, 32.0), 4.0)]);+ canvas.end_stroke();+ canvas.set_filter(Filter::Hsb { hue: 0.0, saturation: 1.0, brightness: -1.0 });+ canvas.render(&gpu, &mut doc, None);+ let px = canvas.read_layer(&gpu, layer).unwrap();+ assert_eq!(pixel(&px, 64, 10, 32), [0, 0, 0, 255]);+ assert_eq!(pixel(&px, 64, 22, 32), [255, 0, 0, 255]);+ // clone: the red copied from 30 to the left onto where it is painted+ canvas.set_filter(Filter::Clone { offset: [6.0, 0.0] });+ canvas.begin_pencil_stroke(layer, white);+ canvas.add_stamps(&[dot(Vec2::new(10.0, 32.0), 4.0)]);+ canvas.end_stroke();+ canvas.set_filter(Filter::Clone { offset: [6.0, 0.0] });+ canvas.render(&gpu, &mut doc, None);+ canvas.end_transform(true);+ canvas.render(&gpu, &mut doc, None);+ assert!(!canvas.is_pencil());+ assert!(canvas.can_undo());+}++#[test]+fn a_stamps_colour_shift_turns_its_hue() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let mut doc = Document::new(64, 64);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ canvas.begin_stroke(doc.current(), StrokeStyle::new(StrokeTool::Paint, [1.0, 0.0, 0.0], 1.0));+ let mut turned = dot(Vec2::new(20.0, 32.0), 6.0);+ turned.shift = [0.5, 0.0, 0.0];+ let mut lighter = dot(Vec2::new(44.0, 32.0), 6.0);+ lighter.shift = [0.0, 0.0, 0.5];+ canvas.add_stamps(&[turned, lighter]);+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);+ let px = canvas.read_composite(&gpu).unwrap();+ // half a turn from red is cyan; half lighter is white+ assert_eq!(pixel(&px, 64, 20, 32), [0, 255, 255, 255]);+ assert_eq!(pixel(&px, 64, 44, 32), [255, 255, 255, 255]);+}++#[test]+fn wet_edges_pool_on_the_canvas_and_a_threshold_hardens() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let draw = |style: StrokeStyle| {+ let mut doc = Document::new(64, 64);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ canvas.begin_stroke(doc.current(), style);+ let mut soft = dot(Vec2::new(32.0, 32.0), 20.0);+ soft.alpha = 1.0;+ canvas.add_stamps(&[soft]);+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);+ canvas.read_composite(&gpu).unwrap()+ };+ let plain = StrokeStyle { hardness: 0.3, ..style(StrokeTool::Paint, 1.0) };+ let base = draw(plain);+ // on the canvas the full middle settles back to about 0.78 and a full ring forms where the+ // dot fades through about 0.7+ let wet = draw(StrokeStyle { wet_edges: 1.0, ..plain });+ let middle = pixel(&wet, 64, 32, 32)[0];+ assert!((45..=65).contains(&middle), "{middle}");+ let ring = (12..32).map(|x| pixel(&wet, 64, x, 32)[0]).min().unwrap();+ assert!(ring <= 3, "{ring}");+ // a preview leaves the middle as it was and makes the edge at most a little stronger (darker)+ let preview = draw(StrokeStyle { wet_edges: 1.0, preview: true, ..plain });+ assert!(pixel(&preview, 64, 32, 32)[0].abs_diff(pixel(&base, 64, 32, 32)[0]) <= 2);+ for x in 12..32 {+ let (w, b) = (pixel(&preview, 64, x, 32)[0], pixel(&base, 64, x, 32)[0]);+ assert!(w <= b && b - w <= 25, "{x}: {w} {b}");+ }+ // a threshold turns the soft edge either fully on or off+ let hard = draw(StrokeStyle { alpha_threshold: 0.5, ..plain });+ for x in 12..52 {+ let v = pixel(&hard, 64, x, 32)[0];+ assert!(!(2..=253).contains(&v), "{x}: {v}");+ }+}++#[test]+fn a_capped_stroke_builds_up_to_its_transfer() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let mut doc = Document::new(64, 64);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ canvas.begin_stroke(doc.current(), StrokeStyle { rendering: Rendering::Capped, ..style(StrokeTool::Paint, 1.0) });+ // forty full stamps letting half through: black over white stops at half+ let stamps: Vec<Stamp> = (0..40).map(|_| Stamp { transfer: 0.5, ..dot(Vec2::new(32.0, 32.0), 10.0) }).collect();+ canvas.add_stamps(&stamps);+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);+ let middle = pixel(&canvas.read_composite(&gpu).unwrap(), 64, 32, 32)[0];+ if gpu.caps_transfer() {+ assert!((120..=135).contains(&middle), "{middle}");+ } else {+ // without dual-source blending each stamp takes its transfer and they build up+ assert!(middle < 10, "{middle}");+ }+}++#[test]+fn burnt_edges_burn_only_the_paint_under_a_thin_stroke() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let orange = StrokeStyle::new(StrokeTool::Paint, [0.86, 0.6, 0.42], 1.0);+ // burnt edges as given, or (negative) as much in a preview+ let draw = |burnt_edges: f32| {+ let mut doc = Document::new(64, 64);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ // an orange band down the middle+ canvas.begin_stroke(doc.current(), orange);+ canvas.add_stamps(&(0..64).map(|y| dot(Vec2::new(32.0, y as f32), 8.0)).collect::<Vec<_>>());+ canvas.end_stroke();+ // a soft orange dot across it and off it+ let preview = burnt_edges < 0.0;+ canvas.begin_stroke(+ doc.current(),+ StrokeStyle { hardness: 0.3, burnt_edges: burnt_edges.abs(), preview, ..orange },+ );+ canvas.add_stamps(&[dot(Vec2::new(32.0, 32.0), 20.0)]);+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);+ canvas.read_layer(&gpu, doc.current()).unwrap()+ };+ let (base, burnt) = (draw(0.0), draw(1.0));+ // over the band, where the dot is thin, its paint is burnt darker+ let (b, p) = (pixel(&burnt, 64, 32, 47), pixel(&base, 64, 32, 47));+ assert!(b[1] + 10 < p[1], "{b:?} {p:?}");+ // off the band nothing burns, and the band away from the dot is as it was+ for (x, y) in [(47, 32), (50, 40), (32, 4)] {+ let (b, p) = (pixel(&burnt, 64, x, y), pixel(&base, 64, x, y));+ assert!(b.iter().zip(p).all(|(b, p)| b.abs_diff(p) <= 1), "{x},{y}: {b:?} {p:?}");+ }+ // a preview burns nothing+ let preview = draw(-1.0);+ assert_eq!(pixel(&preview, 64, 32, 47), pixel(&base, 64, 32, 47));+}++#[test]+fn wet_paint_mixes_with_what_is_under_it() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let mut doc = Document::new(64, 64);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ // a grey band down the middle+ canvas.begin_stroke(doc.current(), StrokeStyle::new(StrokeTool::Paint, [0.5, 0.5, 0.5], 1.0));+ canvas.add_stamps(&(0..64).map(|y| dot(Vec2::new(32.0, y as f32), 8.0)).collect::<Vec<_>>());+ canvas.end_stroke();+ // white across it, wet (half water) with a strong pull: over the grey it mixes, and off it+ // the watery paint it carries goes on thin+ let wet = StrokeStyle {+ wet_pull: Some(0.85),+ dilution: 0.5,+ ..StrokeStyle::new(StrokeTool::Paint, [1.0, 1.0, 1.0], 1.0)+ };+ canvas.begin_stroke(doc.current(), wet);+ canvas.add_stamps(+ &(0..120).map(|i| Stamp::round(Vec2::new(4.0 + i as f32 * 0.5, 32.0), 4.0, 0.5)).collect::<Vec<_>>(),+ );+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);+ let layer = canvas.read_layer(&gpu, doc.current()).unwrap();+ let over = pixel(&layer, 64, 32, 32);+ assert!(over[0] > 135 && over[0] < 250, "mixed over the band: {over:?}");+ let past = pixel(&layer, 64, 50, 32);+ assert!(past[3] > 10 && past[3] < 220, "thin past the band: {past:?}");+ // as one undo step+ canvas.undo();+ canvas.render(&gpu, &mut doc, None);+ let back = pixel(&canvas.read_layer(&gpu, doc.current()).unwrap(), 64, 32, 32);+ assert!((126..=130).contains(&back[0]), "{back:?}");+}++#[test]+fn a_wet_stroke_redrawn_whole_is_laid_once() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ // faint stamps along a line, drawn live and then redrawn whole (as a stroke's end does), or+ // only drawn whole: the same paint either way, the faint stamps adding up as they should+ let stamps: Vec<Stamp> = (0..200).map(|i| Stamp::round(Vec2::new(4.0 + i as f32 * 0.3, 32.0), 6.0, 0.01)).collect();+ let paint = |live: bool| {+ let mut doc = Document::new(64, 64);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ let wet = StrokeStyle { wet_pull: Some(0.0), ..StrokeStyle::new(StrokeTool::Paint, [1.0, 1.0, 1.0], 1.0) };+ canvas.begin_stroke(doc.current(), wet);+ if live {+ canvas.add_stamps(&stamps);+ }+ canvas.replace_stamps(&stamps);+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);+ pixel(&canvas.read_layer(&gpu, doc.current()).unwrap(), 64, 32, 32)[3]+ };+ let (once, redrawn) = (paint(false), paint(true));+ assert!(once.abs_diff(redrawn) <= 2, "{once} {redrawn}");+ // about 40 stamps over the middle at 1% each+ let expected = 255.0 * (1.0 - 0.99f32.powf(12.0 * 1.0 / 0.3));+ assert!((f32::from(once) - expected).abs() < 8.0, "{once} {expected}");+}++#[test]+fn wet_paint_thins_as_its_charge_runs_out() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ // all water, loaded at a half: along an empty layer the paint goes on thinner as it goes+ let mut doc = Document::new(64, 64);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ let wet = StrokeStyle {+ wet_pull: Some(0.75),+ dilution: 1.0,+ load: 0.5,+ ..StrokeStyle::new(StrokeTool::Paint, [1.0, 1.0, 1.0], 1.0)+ };+ canvas.begin_stroke(doc.current(), wet);+ canvas.add_stamps(+ &(0..140).map(|i| Stamp::round(Vec2::new(4.0 + i as f32 * 0.4, 32.0), 4.0, 0.1)).collect::<Vec<_>>(),+ );+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);+ let layer = canvas.read_layer(&gpu, doc.current()).unwrap();+ let (start, end) = (pixel(&layer, 64, 10, 32), pixel(&layer, 64, 54, 32));+ assert!(end[3] > 0 && end[3] + 20 < start[3], "{start:?} {end:?}");+}++#[test]+fn wet_attack_puts_more_paint_over_what_is_there() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let glaze = |attack: f32| {+ let mut doc = Document::new(64, 64);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ canvas.begin_stroke(doc.current(), StrokeStyle::new(StrokeTool::Paint, [0.5, 0.5, 0.5], 1.0));+ canvas.add_stamps(&(0..64).map(|y| dot(Vec2::new(32.0, y as f32), 8.0)).collect::<Vec<_>>());+ canvas.end_stroke();+ // all water, so the paint goes on only as far as the attack puts it+ let wet = StrokeStyle {+ wet_pull: Some(0.85),+ dilution: 1.0,+ attack,+ ..StrokeStyle::new(StrokeTool::Paint, [1.0, 1.0, 1.0], 1.0)+ };+ canvas.begin_stroke(doc.current(), wet);+ canvas.add_stamps(+ &(0..60).map(|i| Stamp::round(Vec2::new(10.0 + i as f32 * 0.7, 32.0), 4.0, 0.5)).collect::<Vec<_>>(),+ );+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);+ pixel(&canvas.read_layer(&gpu, doc.current()).unwrap(), 64, 32, 32)[0]+ };+ let soft = glaze(0.0);+ let hard = glaze(1.0);+ assert!(hard > soft, "attack {hard} vs none {soft}");+ assert!(hard >= 250);+}++#[test]+fn a_stroke_blends_into_its_layer_by_its_mode() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let mut doc = Document::new(64, 64);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ // a blue band down the middle, a mid grey one across the top+ canvas.begin_stroke(doc.current(), StrokeStyle::new(StrokeTool::Paint, [0.0, 0.0, 1.0], 1.0));+ canvas.add_stamps(&(0..64).map(|y| dot(Vec2::new(32.0, y as f32), 8.0)).collect::<Vec<_>>());+ canvas.end_stroke();+ canvas.begin_stroke(doc.current(), StrokeStyle::new(StrokeTool::Paint, [0.5, 0.5, 0.5], 1.0));+ canvas.add_stamps(&(0..64).map(|x| dot(Vec2::new(x as f32, 6.0), 4.0)).collect::<Vec<_>>());+ canvas.end_stroke();+ // red multiplied across the blue: black over it, red off it+ let multiply = StrokeStyle { blend: 1, ..StrokeStyle::new(StrokeTool::Paint, [1.0, 0.0, 0.0], 1.0) };+ canvas.begin_stroke(doc.current(), multiply);+ canvas.add_stamps(&(0..64).map(|x| dot(Vec2::new(x as f32, 40.0), 4.0)).collect::<Vec<_>>());+ canvas.end_stroke();+ // grey added to the grey: white+ let add = StrokeStyle { blend: 9, ..StrokeStyle::new(StrokeTool::Paint, [0.5, 0.5, 0.5], 1.0) };+ canvas.begin_stroke(doc.current(), add);+ canvas.add_stamps(&(0..20).map(|x| dot(Vec2::new(x as f32, 6.0), 4.0)).collect::<Vec<_>>());+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);+ let layer = canvas.read_layer(&gpu, doc.current()).unwrap();+ let over = pixel(&layer, 64, 32, 40);+ assert!(over[0] < 8 && over[2] < 8 && over[3] == 255, "multiplied: {over:?}");+ let off = pixel(&layer, 64, 10, 40);+ assert!(off[0] > 248 && off[2] < 8, "red where nothing was: {off:?}");+ let added = pixel(&layer, 64, 10, 6);+ assert!(added[0] > 248 && added[1] > 248, "added: {added:?}");+ let plain = pixel(&layer, 64, 40, 6);+ assert!((120..=136).contains(&plain[0]), "grey not reached: {plain:?}");+}++#[test]+fn stamps_mix_in_the_secondary_colour() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ let mut doc = Document::new(64, 64);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ let style = StrokeStyle { secondary: [0.0, 0.0, 1.0], ..StrokeStyle::new(StrokeTool::Paint, [1.0, 0.0, 0.0], 1.0) };+ canvas.begin_stroke(doc.current(), style);+ canvas.add_stamps(&[dot(Vec2::new(16.0, 32.0), 6.0), Stamp { secondary: 1.0, ..dot(Vec2::new(48.0, 32.0), 6.0) }]);+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);+ let layer = canvas.read_layer(&gpu, doc.current()).unwrap();+ assert_eq!(pixel(&layer, 64, 16, 32), [255, 0, 0, 255]);+ assert_eq!(pixel(&layer, 64, 48, 32), [0, 0, 255, 255]);+}++#[test]+fn the_grain_combines_with_the_stroke_by_its_blend_mode() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ // a half-strong dot over the paper grain, the grain multiplied or screened+ let cover = |grain_blend: u32| {+ let mut doc = Document::new(64, 64);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ let style = StrokeStyle {+ grain: Some(0),+ grain_depth: 1.0,+ grain_scale: 64.0,+ grain_blend,+ ..StrokeStyle::new(StrokeTool::Paint, [1.0, 1.0, 1.0], 1.0)+ };+ canvas.begin_stroke(doc.current(), style);+ canvas.add_stamps(&[Stamp::round(Vec2::new(32.0, 32.0), 20.0, 0.5)]);+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);+ let layer = canvas.read_layer(&gpu, doc.current()).unwrap();+ (24..40).map(|x| u32::from(pixel(&layer, 64, x, 32)[3])).sum::<u32>()+ };+ let (multiplied, screened) = (cover(1), cover(7));+ assert!(screened > multiplied + 16 * 40, "multiply {multiplied}, screen {screened}");+}++#[test]+fn a_tapered_round_tip_thins_its_rim_too() {+ let Some(gpu) = gpu() else { return };+ let _check = NoErrors(&gpu);+ // the same small stamp, as drawn and as a taper thinned a bigger one to: the tapered one+ // drawn as the whole stamp scaled down, its rim thinner+ let width = |taper: f32| {+ let mut doc = Document::new(64, 64);+ let mut canvas = Canvas::new(&gpu, &doc).unwrap();+ let mut s = style(StrokeTool::Paint, 1.0);+ s.hardness = 0.95;+ canvas.begin_stroke(doc.current(), s);+ canvas.add_stamps(&[Stamp { taper, ..dot(Vec2::new(32.0, 32.0), 2.0) }]);+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);+ let px = canvas.read_composite(&gpu).unwrap();+ (0..64).filter(|&x| pixel(&px, 64, x, 32)[0] < 128).count()+ };+ let (whole, tapered) = (width(1.0), width(0.2));+ assert!(tapered < whole, "{tapered} {whole}");+}diff --git a/crates/gpu/tests/layers.rs b/crates/gpu/tests/layers.rsnew file mode 100644index 0000000..44dc82b--- /dev/null+++ b/crates/gpu/tests/layers.rs@@ -0,0 +1,318 @@+//! Layers on a real GPU: blend modes, clipping, alpha lock, merge, duplicate, delete and their+//! undo (skipped where the machine has none).+#![allow(clippy::unwrap_used, clippy::indexing_slicing)]++use procraft_engine::document::{BlendMode, Document, LayerId};+use procraft_engine::geom::Vec2;+use procraft_engine::stroke::Stamp;+use procraft_gpu::{Canvas, Gpu, StrokeStyle, StrokeTool};++const W: u32 = 16;++fn setup() -> Option<(Gpu, Document, Canvas)> {+ let gpu = match Gpu::headless() {+ Ok(g) => g,+ Err(e) => {+ eprintln!("skipped: {e}");+ return None;+ }+ };+ let doc = Document::new(W, W);+ let canvas = Canvas::new(&gpu, &doc).unwrap();+ Some((gpu, doc, canvas))+}++fn paint(canvas: &mut Canvas, doc: &Document, layer: LayerId, rgb: [u8; 3], at: Vec2, radius: f32, tool: StrokeTool) {+ let color = rgb.map(|c| f32::from(c) / 255.0);+ let preserve_alpha = doc.layer(layer).is_some_and(|l| l.alpha_lock);+ canvas.begin_stroke(layer, StrokeStyle { preserve_alpha, ..StrokeStyle::new(tool, color, 1.0) });+ canvas.add_stamps(&[Stamp::round(at, radius, 1.0)]);+ canvas.end_stroke();+}++/// Covers the whole canvas.+fn fill(canvas: &mut Canvas, doc: &Document, layer: LayerId, rgb: [u8; 3]) {+ paint(canvas, doc, layer, rgb, Vec2::new(8.0, 8.0), 100.0, StrokeTool::Paint);+}++fn composite_at(gpu: &Gpu, doc: &mut Document, canvas: &mut Canvas, x: u32, y: u32) -> [u8; 4] {+ canvas.render(gpu, doc, None);+ assert_eq!(gpu.errors(), 0, "GPU validation errors");+ let px = canvas.read_composite(gpu).unwrap();+ let i = ((y * W + x) * 4) as usize;+ [px[i], px[i + 1], px[i + 2], px[i + 3]]+}++fn layer_at(gpu: &Gpu, doc: &mut Document, canvas: &mut Canvas, id: LayerId, x: u32, y: u32) -> [u8; 4] {+ canvas.render(gpu, doc, None);+ assert_eq!(gpu.errors(), 0, "GPU validation errors");+ let px = canvas.read_layer(gpu, id).unwrap();+ let i = ((y * W + x) * 4) as usize;+ [px[i], px[i + 1], px[i + 2], px[i + 3]]+}++/// The usual compositing definitions on 0..1 values, for opaque colours.+fn reference(mode: BlendMode, b: f32, s: f32) -> f32 {+ match mode {+ BlendMode::Multiply => b * s,+ BlendMode::Screen => b + s - b * s,+ BlendMode::Darken => b.min(s),+ BlendMode::Lighten => b.max(s),+ BlendMode::Difference => (b - s).abs(),+ BlendMode::Exclusion => b + s - 2.0 * b * s,+ BlendMode::Add => (b + s).min(1.0),+ BlendMode::Subtract => (b - s).max(0.0),+ BlendMode::LinearBurn => (b + s - 1.0).max(0.0),+ BlendMode::Overlay => {+ if b <= 0.5 {+ s * 2.0 * b+ } else {+ let t = 2.0 * b - 1.0;+ s + t - s * t+ }+ }+ _ => s,+ }+}++#[test]+fn separable_blend_modes_match_the_definitions() {+ let Some((gpu, mut doc, mut canvas)) = setup() else { return };+ let bottom = doc.current();+ let top = doc.add_layer();+ let (b, s) = ([200u8, 90, 30], [60u8, 140, 250]);+ fill(&mut canvas, &doc, bottom, b);+ fill(&mut canvas, &doc, top, s);+ for mode in [+ BlendMode::Multiply,+ BlendMode::Screen,+ BlendMode::Darken,+ BlendMode::Lighten,+ BlendMode::Difference,+ BlendMode::Exclusion,+ BlendMode::Add,+ BlendMode::Subtract,+ BlendMode::LinearBurn,+ BlendMode::Overlay,+ BlendMode::Normal,+ ] {+ doc.set_blend(top, mode);+ canvas.invalidate();+ let got = composite_at(&gpu, &mut doc, &mut canvas, 8, 8);+ for c in 0..3 {+ let want = (reference(mode, f32::from(b[c]) / 255.0, f32::from(s[c]) / 255.0) * 255.0).round() as i32;+ assert!((i32::from(got[c]) - want).abs() <= 2, "{mode:?} channel {c}: got {} want {want}", got[c]);+ }+ assert_eq!(got[3], 255);+ }+}++#[test]+fn shade_darkens_and_shows_nothing_over_clear() {+ let Some((gpu, mut doc, mut canvas)) = setup() else { return };+ let bottom = doc.current();+ let top = doc.add_layer();+ let (b, s) = ([200u8, 90, 30], [60u8, 140, 250]);+ fill(&mut canvas, &doc, bottom, b);+ fill(&mut canvas, &doc, top, s);+ doc.set_blend(top, BlendMode::Shade);+ canvas.invalidate();+ let got = composite_at(&gpu, &mut doc, &mut canvas, 8, 8);+ for c in 0..3 {+ assert!((i32::from(got[c]) - i32::from(b[c].min(s[c]))).abs() <= 2, "channel {c}: {got:?}");+ }+ // with nothing below it, a shaded layer adds nothing+ doc.set_visible(bottom, false);+ doc.background_visible = false;+ canvas.invalidate();+ let got = composite_at(&gpu, &mut doc, &mut canvas, 8, 8);+ assert!(got[3] <= 1, "{got:?}");+}++#[test]+fn colour_modes_keep_the_backdrop_lightness() {+ let Some((gpu, mut doc, mut canvas)) = setup() else { return };+ let bottom = doc.current();+ let top = doc.add_layer();+ fill(&mut canvas, &doc, bottom, [128, 128, 128]);+ fill(&mut canvas, &doc, top, [255, 0, 0]);+ doc.set_blend(top, BlendMode::Color);+ let [r, g, b, _] = composite_at(&gpu, &mut doc, &mut canvas, 8, 8);+ // red hue at grey's lightness: reddish, and about as light (0.3 r + 0.59 g + 0.11 b ≈ 128)+ assert!(r > g && r > b, "{r} {g} {b}");+ let lum = 0.3 * f32::from(r) + 0.59 * f32::from(g) + 0.11 * f32::from(b);+ assert!((lum - 128.0).abs() < 4.0, "lum {lum}");+ doc.set_blend(top, BlendMode::Luminosity);+ canvas.invalidate();+ let [r, g, b, _] = composite_at(&gpu, &mut doc, &mut canvas, 8, 8);+ assert!(r == g && g == b, "grey stays grey: {r} {g} {b}");+}++#[test]+fn opacity_visibility_and_clipping() {+ let Some((gpu, mut doc, mut canvas)) = setup() else { return };+ let base = doc.current();+ let clipped = doc.add_layer();+ // the base covers the left part only; the clipped layer covers everything+ paint(&mut canvas, &doc, base, [0, 0, 255], Vec2::new(2.0, 8.0), 4.0, StrokeTool::Paint);+ fill(&mut canvas, &doc, clipped, [255, 0, 0]);+ doc.set_clipped(clipped, true);+ canvas.invalidate();+ assert_eq!(composite_at(&gpu, &mut doc, &mut canvas, 2, 8), [255, 0, 0, 255]);+ assert_eq!(composite_at(&gpu, &mut doc, &mut canvas, 14, 8), [255, 255, 255, 255], "clipped away");+ doc.set_opacity(clipped, 0.5);+ canvas.invalidate();+ let [r, _, b, _] = composite_at(&gpu, &mut doc, &mut canvas, 2, 8);+ assert!((126..=129).contains(&r) && (126..=129).contains(&b), "half red over blue: {r} {b}");+ // hiding the base hides what is clipped to it+ doc.set_visible(base, false);+ canvas.invalidate();+ assert_eq!(composite_at(&gpu, &mut doc, &mut canvas, 2, 8), [255, 255, 255, 255]);+}++#[test]+fn alpha_lock_recolours_only_painted_pixels() {+ let Some((gpu, mut doc, mut canvas)) = setup() else { return };+ let layer = doc.current();+ paint(&mut canvas, &doc, layer, [0, 0, 0], Vec2::new(4.0, 4.0), 3.0, StrokeTool::Paint);+ doc.set_alpha_lock(layer, true);+ fill(&mut canvas, &doc, layer, [255, 0, 0]);+ assert_eq!(layer_at(&gpu, &mut doc, &mut canvas, layer, 4, 4), [255, 0, 0, 255]);+ assert_eq!(layer_at(&gpu, &mut doc, &mut canvas, layer, 12, 12)[3], 0, "outside stays empty");+}++#[test]+fn merge_down_and_undo() {+ let Some((gpu, mut doc, mut canvas)) = setup() else { return };+ let lower = doc.current();+ let upper = doc.add_layer();+ fill(&mut canvas, &doc, lower, [200, 200, 200]);+ fill(&mut canvas, &doc, upper, [100, 50, 0]);+ doc.set_blend(upper, BlendMode::Multiply);+ let before = doc.clone();+ canvas.merge_down(upper, lower, before);+ assert!(doc.finish_merge_down(upper));+ assert_eq!(doc.layers().len(), 1);+ let merged = layer_at(&gpu, &mut doc, &mut canvas, lower, 8, 8);+ assert_eq!(merged[..3], [78, 39, 0], "200 × 100 / 255 and so on");+ // the composite is unchanged by merging+ assert_eq!(composite_at(&gpu, &mut doc, &mut canvas, 8, 8)[..3], [78, 39, 0]);++ canvas.undo();+ assert_eq!(layer_at(&gpu, &mut doc, &mut canvas, lower, 8, 8), [200, 200, 200, 255]);+ assert_eq!(doc.layers().len(), 2);+ assert_eq!(layer_at(&gpu, &mut doc, &mut canvas, upper, 8, 8), [100, 50, 0, 255]);+ canvas.redo();+ canvas.render(&gpu, &mut doc, None);+ assert_eq!(doc.layers().len(), 1);+}++#[test]+fn duplicate_delete_and_undo_keep_pixels() {+ let Some((gpu, mut doc, mut canvas)) = setup() else { return };+ let a = doc.current();+ paint(&mut canvas, &doc, a, [0, 255, 0], Vec2::new(8.0, 8.0), 3.0, StrokeTool::Paint);+ let before = doc.clone();+ let b = doc.duplicate_layer(a).unwrap();+ canvas.duplicate_layer(a, b, before);+ assert_eq!(layer_at(&gpu, &mut doc, &mut canvas, b, 8, 8), [0, 255, 0, 255]);++ let before = doc.clone();+ assert!(doc.delete_layer(a));+ canvas.record_document(before);+ canvas.render(&gpu, &mut doc, None);+ assert_eq!(doc.layers().len(), 1);+ // the deleted layer's pixels are kept while undo can bring it back+ assert_eq!(canvas.layer_texture_count(), 2);+ canvas.undo();+ canvas.render(&gpu, &mut doc, None);+ assert_eq!(doc.layers().len(), 2);+ assert_eq!(layer_at(&gpu, &mut doc, &mut canvas, a, 8, 8), [0, 255, 0, 255]);+}++#[test]+fn thumbnails_are_scaled_layers() {+ let Some((gpu, mut doc, mut canvas)) = setup() else { return };+ let a = doc.current();+ fill(&mut canvas, &doc, a, [10, 20, 30]);+ let t = canvas.layer_thumbnail(&gpu, &mut doc, a, 8).unwrap();+ assert_eq!((t.width, t.height), (8, 8));+ assert_eq!(t.rgba.len(), 8 * 8 * 4);+ assert_eq!(t.rgba[..4], [10, 20, 30, 255]);+}++#[test]+fn a_thumbnail_shows_what_is_drawn_never_enlarged() {+ let Some((gpu, mut doc, mut canvas)) = setup() else { return };+ let a = doc.current();+ // a 2 x 3 block near a corner of the 16 x 16 layer+ let mut pixels = vec![0u8; 16 * 16 * 4];+ for (x, y) in [(12, 1), (13, 1), (12, 2), (13, 2), (12, 3), (13, 3)] {+ pixels[(y * 16 + x) * 4..(y * 16 + x) * 4 + 4].copy_from_slice(&[0, 0, 255, 255]);+ }+ canvas.write_layer(a, pixels);+ let t = canvas.layer_thumbnail(&gpu, &mut doc, a, 8).unwrap();+ assert_eq!((t.width, t.height), (2, 3));+ assert!(t.rgba.chunks(4).all(|p| p[3] > 0));+ // an empty layer: the whole canvas, fitted+ let b = doc.add_layer();+ let t = canvas.layer_thumbnail(&gpu, &mut doc, b, 8).unwrap();+ assert_eq!((t.width, t.height), (8, 8));+}++#[test]+fn smudge_drags_colour_and_undoes() {+ let Some((gpu, mut doc, mut canvas)) = setup() else { return };+ let layer = doc.current();+ // red on the left half, blue on the right+ paint(&mut canvas, &doc, layer, [255, 0, 0], Vec2::new(-92.0, 8.0), 100.0, StrokeTool::Paint);+ paint(&mut canvas, &doc, layer, [0, 0, 255], Vec2::new(108.0, 8.0), 100.0, StrokeTool::Paint);+ let before = layer_at(&gpu, &mut doc, &mut canvas, layer, 11, 8);+ assert_eq!(before[..3], [0, 0, 255]);+ // drag from the red into the blue+ let stamps: Vec<Stamp> = (0..30).map(|i| Stamp::round(Vec2::new(2.0 + i as f32 * 0.4, 8.0), 4.0, 1.0)).collect();+ canvas.begin_stroke(layer, StrokeStyle::new(StrokeTool::Smudge, [0.0; 3], 1.0));+ canvas.add_stamps(&stamps);+ let during = layer_at(&gpu, &mut doc, &mut canvas, layer, 11, 8);+ assert!(during[0] > 60, "red carried into the blue: {during:?}");+ canvas.end_stroke();+ canvas.render(&gpu, &mut doc, None);+ assert!(canvas.can_undo());+ canvas.undo();+ assert_eq!(layer_at(&gpu, &mut doc, &mut canvas, layer, 11, 8), before);++ // a cancelled smudge leaves the layer as it was+ canvas.begin_stroke(layer, StrokeStyle::new(StrokeTool::Smudge, [0.0; 3], 1.0));+ canvas.add_stamps(&stamps);+ canvas.render(&gpu, &mut doc, None);+ canvas.cancel_stroke();+ assert_eq!(layer_at(&gpu, &mut doc, &mut canvas, layer, 11, 8), before);+}++#[test]+fn a_held_edit_is_one_undo_step_or_put_back() {+ let Some((gpu, mut doc, mut canvas)) = setup() else { return };+ let a = doc.current();+ fill(&mut canvas, &doc, a, [10, 20, 30]);+ canvas.render(&gpu, &mut doc, None);+ let steps = |c: &Canvas| c.can_undo();+ assert!(steps(&canvas));+ // many puts, kept: one step back to the fill+ let before = doc.clone();+ canvas.hold_layer(a);+ for v in [100u8, 150, 200] {+ canvas.put_layer(a, [v, v, v, 255].repeat((W * W) as usize));+ }+ canvas.release_layer(true, Some(before));+ canvas.render(&gpu, &mut doc, None);+ assert_eq!(layer_at(&gpu, &mut doc, &mut canvas, a, 3, 3), [200, 200, 200, 255]);+ canvas.undo();+ canvas.render(&gpu, &mut doc, None);+ assert_eq!(layer_at(&gpu, &mut doc, &mut canvas, a, 3, 3), [10, 20, 30, 255]);+ // put back: as if nothing happened+ canvas.hold_layer(a);+ canvas.put_layer(a, [9, 9, 9, 255].repeat((W * W) as usize));+ canvas.release_layer(false, None);+ canvas.render(&gpu, &mut doc, None);+ assert_eq!(layer_at(&gpu, &mut doc, &mut canvas, a, 3, 3), [10, 20, 30, 255]);+}diff --git a/rustfmt.toml b/rustfmt.tomlnew file mode 100644index 0000000..c775577--- /dev/null+++ b/rustfmt.toml@@ -0,0 +1,2 @@+max_width = 120+use_small_heuristics = "Max"