A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.
TypeScript animationcartoonclip-studio-paintcollaborativedesktop-appdigital-paintingdrawing-appillustrationmangamultiplayeropen-sourcerusttaurithreejswebglwebtoon
rust transit
sora96a55755fc4a
diff --git a/.gitignore b/.gitignoreindex 88214d7..f00fb5b 100644--- a/.gitignore+++ b/.gitignore@@ -32,3 +32,7 @@ dist-ssr*.pem.env.env.*++# Rust Cargo workspace build artifacts+/target+diff --git a/src-tauri/Cargo.lock b/Cargo.locksimilarity index 83%rename from src-tauri/Cargo.lockrename to Cargo.lockindex e2a60e5..4d4df29 100644--- a/src-tauri/Cargo.lock+++ b/Cargo.lock@@ -10,11 +10,12 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"[[package]]name = "ahash"-version = "0.8.12"+version = "0.8.15"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"+checksum = "3019c0b8d883a8a17df3129e417ef463c087807d245e8881a31d583dee1c0519"dependencies = ["cfg-if",+ "getrandom 0.4.3","once_cell","version_check","zerocopy",@@ -44,6 +45,12 @@ dependencies = ["alloc-no-stdlib",]+[[package]]+name = "allocator-api2"+version = "0.2.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "57b212daf2e827b1ccdd778b7eb48ba433e58cb0e4f27b43cd6b7a608425a014"+[[package]]name = "android_system_properties"version = "0.1.6"@@ -55,9 +62,15 @@ dependencies = [[[package]]name = "anyhow"-version = "1.0.104"+version = "1.0.105"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902"++[[package]]+name = "arrayvec"+version = "0.7.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"+checksum = "47a64a0fd06e123e9e3cf3ad01432af17dcab8185e8023edcf184fe696f9675d"[[package]]name = "async-broadcast"@@ -85,9 +98,9 @@ dependencies = [[[package]]name = "async-executor"-version = "1.14.0"+version = "1.14.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"+checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37"dependencies = ["async-task","concurrent-queue",@@ -117,9 +130,9 @@ dependencies = [[[package]]name = "async-lock"-version = "3.4.2"+version = "3.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"+checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f"dependencies = ["event-listener","event-listener-strategy",@@ -146,13 +159,13 @@ dependencies = [[[package]]name = "async-recursion"-version = "1.1.1"+version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11"+checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451"dependencies = ["proc-macro2","quote",- "syn 2.0.119",+ "syn 3.0.10",][[package]]@@ -187,14 +200,14 @@ checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"dependencies = ["proc-macro2","quote",- "syn 3.0.6",+ "syn 3.0.10",][[package]]name = "atk"-version = "0.18.2"+version = "0.19.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b"+checksum = "780a62f5d3373a8461bdc9258527bd03fe9299779446681199005712b24cc1d7"dependencies = ["atk-sys","glib",@@ -203,14 +216,14 @@ dependencies = [[[package]]name = "atk-sys"-version = "0.18.2"+version = "0.19.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086"+checksum = "56fd0f13d1dedae306538653b8e42034a2260d1ac3ee920e7a5c31475d7184a5"dependencies = ["glib-sys","gobject-sys","libc",- "system-deps",+ "system-deps 9.0.1",][[package]]@@ -303,11 +316,11 @@ checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"[[package]]name = "bit-set"-version = "0.8.0"+version = "0.10.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"+checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d"dependencies = [- "bit-vec 0.8.0",+ "bit-vec 0.9.1",][[package]]@@ -321,9 +334,9 @@ dependencies = [[[package]]name = "bit-vec"-version = "0.8.0"+version = "0.9.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"+checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"[[package]]name = "bit-vec"@@ -331,12 +344,6 @@ version = "0.10.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72503af1e72be411d74ca45cd6b309878fcb35354e252fc2a3a8bda3a97082a0"-[[package]]-name = "bitflags"-version = "1.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"-[[package]]name = "bitflags"version = "2.13.2"@@ -399,9 +406,9 @@ dependencies = [[[package]]name = "brotli-decompressor"-version = "6.3.2"+version = "6.4.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cc031cd87c6529082b0b65c604e86af0ed7744841b17ccfe60b1e31fa606179e"+checksum = "50986a054f56ca3e15382f3c09abee2bf494c00311b238daae118a06bc1c15f1"dependencies = ["alloc-no-stdlib","alloc-stdlib",@@ -418,54 +425,66 @@ dependencies = [[[package]]name = "bumpalo"-version = "3.20.3"+version = "3.20.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"+checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db"[[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.10",+][[package]]name = "byteorder"-version = "1.5.0"+version = "1.5.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"+checksum = "34fb07aac3b9f547c7af8dc897dfe73c10847b6c71130c364bdd7891d979c816"[[package]]name = "bytes"-version = "1.12.1"+version = "1.12.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"+checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c"dependencies = ["serde",][[package]]name = "cairo-rs"-version = "0.18.5"+version = "0.22.11"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2"+checksum = "62bf7f026ae17fe688938438ec1da2b69f69832f1428a17258f6ee9a7f6e1815"dependencies = [- "bitflags 2.13.2",+ "bitflags","cairo-sys-rs","glib","libc",- "once_cell",- "thiserror 1.0.69",][[package]]name = "cairo-sys-rs"-version = "0.18.2"+version = "0.22.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51"+checksum = "ee548131103ad8f698c6725669647b9c757b3b66992dd6a026037596417bee21"dependencies = ["glib-sys","libc",- "system-deps",+ "system-deps 9.0.1",][[package]]@@ -479,18 +498,19 @@ dependencies = [[[package]]name = "cargo-platform"-version = "0.1.9"+version = "0.3.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea"+checksum = "dd0061da739915fae12ea00e16397555ed4371a6bb285431aab930f61b0aa4ba"dependencies = ["serde",+ "serde_core",][[package]]name = "cargo_metadata"-version = "0.19.2"+version = "0.23.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dd5eb614ed4c27c5d706420e4320fbe3216ab31fa1c33cd8246ac36dae4479ba"+checksum = "ef987d17b0a113becdd19d3d0022d04d7ef41f9efe4f3fb63ac44ba61df3ade9"dependencies = ["camino","cargo-platform",@@ -508,14 +528,14 @@ checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9"dependencies = ["semver","serde",- "toml 1.1.6+spec-1.1.0",+ "toml",][[package]]name = "cc"-version = "1.4.7"+version = "1.12.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "54413ede23c2daf518f35156dfde027feb2374004d63bd497f983c8db9c0e313"+checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66"dependencies = ["find-msvc-tools","shlex",@@ -540,9 +560,9 @@ dependencies = [[[package]]name = "cfg-expr"-version = "0.15.8"+version = "0.20.11"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02"+checksum = "edd44d82755fb9210fb10d9daf8dd7e522da0efe1d5f263cffc5db07725663ff"dependencies = ["smallvec","target-lexicon",@@ -572,11 +592,20 @@ dependencies = ["windows-link 0.2.1",]+[[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 = "combine"-version = "4.6.8"+version = "4.6.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e"+checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92"dependencies = ["bytes","memchr",@@ -593,24 +622,24 @@ dependencies = [[[package]]name = "const-oid"-version = "0.10.2"+version = "0.10.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"+checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"[[package]]name = "constant_time_eq"-version = "0.6.1"+version = "0.6.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9"+checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7"dependencies = ["rustversion",][[package]]name = "cookie"-version = "0.18.2"+version = "0.18.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87"+checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a"dependencies = ["time","version_check",@@ -648,7 +677,7 @@ version = "0.25.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97"dependencies = [- "bitflags 2.13.2",+ "bitflags","core-foundation 0.10.1","core-graphics-types","foreign-types",@@ -661,7 +690,7 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"dependencies = [- "bitflags 2.13.2",+ "bitflags","core-foundation 0.10.1","libc",]@@ -686,9 +715,9 @@ dependencies = [[[package]]name = "crc32fast"-version = "1.5.2"+version = "1.5.6"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78"+checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945"dependencies = ["cfg-if",]@@ -727,6 +756,12 @@ version = "0.8.23"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"+[[package]]+name = "crunchy"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"+[[package]]name = "crypto-common"version = "0.1.7"@@ -746,19 +781,6 @@ dependencies = ["hybrid-array",]-[[package]]-name = "cssparser"-version = "0.37.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8c9cdaae01d5ed7882b04d795e7f752f46ff52d2fa3b50a20d28c464510bba98"-dependencies = [- "cssparser-macros",- "dtoa-short",- "itoa",- "phf 0.13.1",- "smallvec",-]-[[package]]name = "cssparser"version = "0.38.0"@@ -768,7 +790,7 @@ dependencies = ["cssparser-macros","dtoa-short","itoa",- "phf 0.14.0",+ "phf","smallvec",]@@ -779,7 +801,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d045de693cb712d0b22c6a64be5b953f67b3ce00ab5ad3dd5d8b441886ab8e1a"dependencies = ["quote",- "syn 3.0.6",+ "syn 3.0.10",][[package]]@@ -811,7 +833,7 @@ dependencies = ["proc-macro2","quote","strsim",- "syn 3.0.6",+ "syn 3.0.10",][[package]]@@ -822,7 +844,7 @@ checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"dependencies = ["darling_core","quote",- "syn 3.0.6",+ "syn 3.0.10",][[package]]@@ -842,42 +864,11 @@ dependencies = ["windows-sys 0.61.2",]-[[package]]-name = "defmt"-version = "1.1.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1"-dependencies = [- "bitflags 1.3.2",- "defmt-macros",-]--[[package]]-name = "defmt-macros"-version = "1.1.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8"-dependencies = [- "defmt-parser",- "proc-macro2",- "quote",- "syn 2.0.119",-]--[[package]]-name = "defmt-parser"-version = "1.0.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e"-dependencies = [- "thiserror 2.0.21",-]-[[package]]name = "deranged"-version = "0.5.8"+version = "0.5.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"+checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"dependencies = ["serde_core",]@@ -942,7 +933,7 @@ dependencies = ["libc","option-ext","redox_users",- "windows-sys 0.61.2",+ "windows-sys 0.101.0",][[package]]@@ -951,7 +942,7 @@ version = "0.3.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"dependencies = [- "bitflags 2.13.2",+ "bitflags","block2","libc","objc2",@@ -965,7 +956,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"dependencies = ["proc-macro2","quote",- "syn 3.0.6",+ "syn 3.0.10",][[package]]@@ -992,32 +983,26 @@ dependencies = [][[package]]-name = "dom_query"-version = "0.28.0"+name = "document-features"+version = "0.2.12"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fac5fca71e65e94cc718a6e2af65d6e0f9c6027751c2aa562fbb5087fda639bc"+checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"dependencies = [- "bit-set 0.8.0",- "cssparser 0.37.0",- "foldhash",- "html5ever 0.39.0",- "precomputed-hash",- "selectors 0.38.0",- "tendril",+ "litrs",][[package]]name = "dom_query"-version = "0.29.0"+version = "0.30.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "498c698ac51127148a3984450e51fca7f01805a91d7a1f7a24af0a5f761e3385"+checksum = "b35b4f772a1a8b88e5545a67c2d3a62a93d4edccc5a68f2145fe52e39c96d275"dependencies = ["bit-set 0.11.1",- "cssparser 0.38.0",+ "cssparser","foldhash",- "html5ever 0.40.1",+ "html5ever","precomputed-hash",- "selectors 0.41.0",+ "selectors","tendril",]@@ -1065,14 +1050,14 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"[[package]]name = "embed-resource"-version = "3.0.11"+version = "3.0.12"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fbfdaacccebec3b28e4866b8973543c7647797db5ada1bdab552e48fe665fbbd"+checksum = "6168487b5e7eb2673e6efe1200b1848016e436a6ca0b8031bf04bd9d493a249f"dependencies = ["cc","memchr","rustc_version",- "toml 1.1.6+spec-1.1.0",+ "toml","vswhom","winreg",]@@ -1112,15 +1097,15 @@ dependencies = [[[package]]name = "equivalent"-version = "1.0.2"+version = "1.0.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"+checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"[[package]]name = "erased-serde"-version = "0.4.10"+version = "0.4.11"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec"+checksum = "1e59b668157f32d3459d4bd634861a06ffa2503a461ca5f0916b9f0252605e66"dependencies = ["serde","serde_core",@@ -1129,9 +1114,9 @@ dependencies = [[[package]]name = "errno"-version = "0.3.14"+version = "0.3.15"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"+checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"dependencies = ["libc","windows-sys 0.61.2",@@ -1206,15 +1191,15 @@ dependencies = [[[package]]name = "find-msvc-tools"-version = "0.1.13"+version = "0.1.16"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ef25905e51abafe4dcea6c15fec58c57b601cdbd0ee53d22ea1d3016c587d39b"+checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8"[[package]]name = "flate2"-version = "1.1.10"+version = "1.1.11"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"+checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"dependencies = ["crc32fast","miniz_oxide 0.9.1",@@ -1251,7 +1236,7 @@ checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225"dependencies = ["proc-macro2","quote",- "syn 3.0.6",+ "syn 3.0.10",][[package]]@@ -1262,9 +1247,9 @@ checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"[[package]]name = "form_urlencoded"-version = "1.2.2"+version = "1.2.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"+checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"dependencies = ["percent-encoding",]@@ -1322,7 +1307,7 @@ checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"dependencies = ["proc-macro2","quote",- "syn 3.0.6",+ "syn 3.0.10",][[package]]@@ -1355,9 +1340,9 @@ dependencies = [[[package]]name = "gdk"-version = "0.18.2"+version = "0.19.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d9f245958c627ac99d8e529166f9823fb3b838d1d41fd2b297af3075093c2691"+checksum = "50b79a7fa8b0e9fe6c77118e48cc00a23eb41052c190434d9cda7746418efca6"dependencies = ["cairo-rs","gdk-pixbuf",@@ -1370,35 +1355,34 @@ dependencies = [[[package]]name = "gdk-pixbuf"-version = "0.18.5"+version = "0.22.11"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec"+checksum = "aabb44971913eb9f7bf6747f6e88889386007d8ce8cfd1ca2735751b664e7079"dependencies = ["gdk-pixbuf-sys","gio","glib","libc",- "once_cell",][[package]]name = "gdk-pixbuf-sys"-version = "0.18.0"+version = "0.22.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7"+checksum = "9d5209294ba3775f9b650bf78bfadeba4332089f2329b3e2f6ce0a4957a45bff"dependencies = ["gio-sys","glib-sys","gobject-sys","libc",- "system-deps",+ "system-deps 9.0.1",][[package]]name = "gdk-sys"-version = "0.18.2"+version = "0.19.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7"+checksum = "463ac2e2f204918dcaeb3c34810bd7fe94448d2b8d4fa13a5ab45a4fc3e88e50"dependencies = ["cairo-sys-rs","gdk-pixbuf-sys",@@ -1408,28 +1392,28 @@ dependencies = ["libc","pango-sys","pkg-config",- "system-deps",+ "system-deps 9.0.1",][[package]]name = "gdkwayland-sys"-version = "0.18.2"+version = "0.19.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "140071d506d223f7572b9f09b5e155afbd77428cd5cc7af8f2694c41d98dfe69"+checksum = "82559ece0c0952519a3513ecd90638e5db59e00c851f1d3ea05ac7ff2a46942e"dependencies = ["gdk-sys","glib-sys","gobject-sys","libc","pkg-config",- "system-deps",+ "system-deps 9.0.1",][[package]]name = "gdkx11"-version = "0.18.2"+version = "0.19.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3caa00e14351bebbc8183b3c36690327eb77c49abc2268dd4bd36b856db3fbfe"+checksum = "bad7a698a74652ddba8dc348f9933f6f209fbcf3ab318f2c1fd72c6b2fa99505"dependencies = ["gdk","gdkx11-sys",@@ -1441,14 +1425,15 @@ dependencies = [[[package]]name = "gdkx11-sys"-version = "0.18.2"+version = "0.19.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6e2e7445fe01ac26f11601db260dd8608fe172514eb63b3b5e261ea6b0f4428d"+checksum = "a103facf2056ce28125a49501f98beb01d1e3c9477257a8e05cfc5d3d677709e"dependencies = [+ "cairo-sys-rs","gdk-sys","glib-sys","libc",- "system-deps",+ "system-deps 9.0.1","x11",]@@ -1500,9 +1485,9 @@ dependencies = [[[package]]name = "gio"-version = "0.18.4"+version = "0.22.11"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d4fc8f532f87b79cbc51a79748f16a6828fb784be93145a322fa14d06d354c73"+checksum = "536990682bab3b8bf68a78d298ccae69702a114290b096edf2bec6eb2e4013b3"dependencies = ["futures-channel","futures-core",@@ -1511,32 +1496,30 @@ dependencies = ["gio-sys","glib","libc",- "once_cell","pin-project-lite","smallvec",- "thiserror 1.0.69",][[package]]name = "gio-sys"-version = "0.18.1"+version = "0.22.11"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2"+checksum = "b9c253490f9a475047f109bf6ccb68c407e9d186b7bfab01849188f4e669e669"dependencies = ["glib-sys","gobject-sys","libc",- "system-deps",- "winapi",+ "system-deps 9.0.1",+ "windows-sys 0.61.2",][[package]]name = "glib"-version = "0.18.5"+version = "0.22.11"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5"+checksum = "c9c4cbf1972a07741ae5ce9b23a582a90efc69745fc713f8b037b8d962f604da"dependencies = [- "bitflags 2.13.2",+ "bitflags","futures-channel","futures-core","futures-executor",@@ -1548,33 +1531,29 @@ dependencies = ["gobject-sys","libc","memchr",- "once_cell","smallvec",- "thiserror 1.0.69",][[package]]name = "glib-macros"-version = "0.18.5"+version = "0.22.11"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc"+checksum = "d4014e54e2049108c93cf278b64e89f490849402e09b455a25dfa2098cc35093"dependencies = [- "heck 0.4.1",- "proc-macro-crate 2.0.2",- "proc-macro-error",+ "heck","proc-macro2","quote",- "syn 2.0.119",+ "syn 3.0.10",][[package]]name = "glib-sys"-version = "0.18.1"+version = "0.22.11"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898"+checksum = "8b01e8b94529c2698b98f765b887f1e001b76195c1e25d1139aa9336019e745d"dependencies = ["libc",- "system-deps",+ "system-deps 9.0.1",][[package]]@@ -1585,20 +1564,33 @@ checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"[[package]]name = "gobject-sys"-version = "0.18.0"+version = "0.22.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44"+checksum = "07595c9ba696bd9819cb6a8df39f08078f3dd679508fe052dd558492c2053834"dependencies = ["glib-sys","libc",- "system-deps",+ "system-deps 9.0.1",+]++[[package]]+name = "gpu-allocator"+version = "0.28.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795"+dependencies = [+ "hashbrown 0.16.1",+ "log",+ "presser",+ "thiserror 2.0.21",+ "windows",][[package]]name = "gtk"-version = "0.18.2"+version = "0.19.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fd56fb197bfc42bd5d2751f4f017d44ff59fbb58140c6b49f9b3b2bdab08506a"+checksum = "a86cafafc177054a1d555a0b302044d2b5f82e1c1e23d152a7ba252dc6bfced0"dependencies = ["atk","cairo-rs",@@ -1617,9 +1609,9 @@ dependencies = [[[package]]name = "gtk-sys"-version = "0.18.2"+version = "0.19.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8f29a1c21c59553eb7dd40e918be54dccd60c52b049b75119d5d96ce6b624414"+checksum = "a0e6f055c4a2ce6598b32373595b0c9985f1c7cc448afe4f09fee33fb738b488"dependencies = ["atk-sys","cairo-sys-rs",@@ -1630,20 +1622,31 @@ dependencies = ["gobject-sys","libc","pango-sys",- "system-deps",+ "system-deps 9.0.1",][[package]]name = "gtk3-macros"-version = "0.18.2"+version = "0.19.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "52ff3c5b21f14f0736fed6dcfc0bfb4225ebf5725f3c0209edeec181e4d73e9d"+checksum = "5fcce21fcb0c4c4fc48bab8d4eee5aacdb361f85d234756430e6e793bd3d95cf"dependencies = [- "proc-macro-crate 1.3.1",- "proc-macro-error",+ "proc-macro-crate","proc-macro2","quote",- "syn 2.0.119",+ "syn 3.0.10",+]++[[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]]@@ -1663,9 +1666,23 @@ dependencies = [[[package]]name = "hashbrown"-version = "0.17.1"+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.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"+checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc"+dependencies = [+ "foldhash",+][[package]]name = "hashlink"@@ -1676,12 +1693,6 @@ dependencies = ["hashbrown 0.14.5",]-[[package]]-name = "heck"-version = "0.4.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"-[[package]]name = "heck"version = "0.5.0"@@ -1700,16 +1711,6 @@ version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"-[[package]]-name = "html5ever"-version = "0.39.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8"-dependencies = [- "log",- "markup5ever 0.39.0",-]-[[package]]name = "html5ever"version = "0.40.1"@@ -1717,15 +1718,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "456a1a377e608e555d22ddab27ac0114bc7a7b4199078108e34c2aeae6c9b130"dependencies = ["log",- "markup5ever 0.40.0",+ "markup5ever","memchr",][[package]]name = "http"-version = "1.5.0"+version = "1.6.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"+checksum = "a07dc2d082802d1782faa5b3c8ac252f3a4fc89f51e76c3f37dc2d1a5b857c05"dependencies = ["bytes","itoa",@@ -1783,13 +1784,12 @@ dependencies = [[[package]]name = "hyper"-version = "1.11.1"+version = "1.13.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43"+checksum = "229c6ff5584df4c6becbfe00567128bac768c8cd32ebc8a8366bd81ed072e8f3"dependencies = ["atomic-waker","bytes",- "futures-channel","futures-core","http","http-body",@@ -1855,7 +1855,7 @@ dependencies = ["js-sys","log","wasm-bindgen",- "windows-core 0.62.2",+ "windows-core",][[package]]@@ -1879,9 +1879,9 @@ dependencies = [[[package]]name = "icu_collections"-version = "2.3.0"+version = "2.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"+checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd"dependencies = ["displaydoc","potential_utf",@@ -1893,9 +1893,9 @@ dependencies = [[[package]]name = "icu_locale_core"-version = "2.3.0"+version = "2.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"+checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0"dependencies = ["displaydoc","litemap",@@ -1906,9 +1906,9 @@ dependencies = [[[package]]name = "icu_normalizer"-version = "2.3.0"+version = "2.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f"+checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599"dependencies = ["icu_collections","icu_normalizer_data",@@ -1920,15 +1920,15 @@ dependencies = [[[package]]name = "icu_normalizer_data"-version = "2.3.0"+version = "2.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"+checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc"[[package]]name = "icu_properties"-version = "2.3.0"+version = "2.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148"+checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f"dependencies = ["displaydoc","icu_collections",@@ -1941,15 +1941,15 @@ dependencies = [[[package]]name = "icu_properties_data"-version = "2.3.0"+version = "2.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa"+checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf"[[package]]name = "icu_provider"-version = "2.3.1"+version = "2.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"+checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514"dependencies = ["displaydoc","icu_locale_core",@@ -2005,7 +2005,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"dependencies = ["equivalent",- "hashbrown 0.17.1",+ "hashbrown 0.17.2","serde","serde_core",]@@ -2019,18 +2019,42 @@ dependencies = ["cfb",]+[[package]]+name = "ink-engine"+version = "0.1.0"+dependencies = [+ "bytemuck",+ "crc32fast",+ "crossbeam-channel",+ "flate2",+ "half",+ "lz4_flex",+ "parking_lot",+ "pollster",+ "rayon",+ "rtrb",+ "serde",+ "serde_json",+ "wgpu",+ "windows-sys 0.59.0",+]+[[package]]name = "ink-studio"version = "1.2.2"dependencies = ["axum",+ "crossbeam-channel","flate2","futures-util","getrandom 0.2.17","hex",+ "ink-engine","lz4_flex","mime_guess",+ "parking_lot","rayon",+ "rtrb","rusqlite","rust-embed","serde",@@ -2045,15 +2069,16 @@ dependencies = ["tokio","tower-http 0.5.2","webview2-com",- "windows-core 0.62.2",+ "windows",+ "windows-core","windows-sys 0.59.0",][[package]]name = "ipnet"-version = "2.12.2"+version = "2.12.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"+checksum = "007d6e6b91097094791302ccc6cd0588e0700ddac5c6829035bcd71eff4dc433"[[package]]name = "is-docker"@@ -2076,43 +2101,58 @@ dependencies = [[[package]]name = "itoa"-version = "1.0.18"+version = "1.0.19"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"+checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"[[package]]name = "javascriptcore-rs"-version = "1.1.2"+version = "2.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc"+checksum = "3806310bf87dd1858b0cd99dad0c49efb06ee56d346e77385d89e7f8db04f5d0"dependencies = [- "bitflags 1.3.2",+ "bitflags","glib","javascriptcore-rs-sys",][[package]]name = "javascriptcore-rs-sys"-version = "1.1.1"+version = "2.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124"+checksum = "2844fb472dd4f76e43a15ee27d2f140b9113adeab21403be084fb653d7a704f9"dependencies = ["glib-sys","gobject-sys","libc",- "system-deps",+ "system-deps 9.0.1",+]++[[package]]+name = "jiff"+version = "0.2.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "175dc66334db3b9ab9985bf8b61cfed50dc16d20964bb47f9e479adcae984a7f"+dependencies = [+ "jiff-core 0.1.8",+ "jiff-static 0.2.46",+ "jiff-tzdb-platform 0.1.3",+ "log",+ "portable-atomic",+ "portable-atomic-util",+ "serde_core",+ "windows-link 0.2.1",][[package]]name = "jiff"-version = "0.2.37"+version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0ab1baf72f08796de0260609515130699b890ac25f30e610ad894bc5856cafdb"+checksum = "379ed44bd4e16d3926160e2b3a78b79ca0952ef5c037f124f554842ba272ef92"dependencies = [- "defmt",- "jiff-core",- "jiff-static",- "jiff-tzdb-platform",+ "jiff-core 1.1.0",+ "jiff-static 1.1.0",+ "jiff-tzdb-platform 1.0.0","log","portable-atomic","portable-atomic-util",@@ -2122,31 +2162,57 @@ dependencies = [[[package]]name = "jiff-core"-version = "0.1.1"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e599b80292e597019b8b3e392de3f4bea2959ddfb8c7dff60e035e9e311a2c1b"+dependencies = [+ "log",+]++[[package]]+name = "jiff-core"+version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c"+checksum = "0df46fc314b4f458aee614afcd8676ed6cb3637413aa359d47d2646cbc038b79"dependencies = [- "defmt","log",][[package]]name = "jiff-static"-version = "0.2.37"+version = "0.2.46"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "378268a1116ad67ae6228701118ac9f491d78fda38a40a1f1a9e1348de6f7212"+checksum = "c7b1af7547d47354bc438d797e3854601bde8f8d185780c5ba4ab27afa54f1ba"dependencies = [- "jiff-core",+ "jiff-core 0.1.8","proc-macro2","quote","syn 2.0.119",]+[[package]]+name = "jiff-static"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27b729c549d3efb5855b3c80b0ee8ee1850d56330a127382fe2760965741c1f3"+dependencies = [+ "jiff-core 1.1.0",+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]+[[package]]name = "jiff-tzdb"-version = "0.1.8"+version = "0.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0980fca2cc272465bd60e82397607ba9f33add9e48defd77923301bbd03808f2"++[[package]]+name = "jiff-tzdb"+version = "1.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "142bd39932ad231f10513df9ab62661fead8719872150b7ad02a2df79f4e141e"+checksum = "12e71a1b68a875a44a33bb7a1dd84392cb77145a3367a552a3cfe6a4f5cf3afc"[[package]]name = "jiff-tzdb-platform"@@ -2154,7 +2220,16 @@ version = "0.1.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8"dependencies = [- "jiff-tzdb",+ "jiff-tzdb 0.1.10",+]++[[package]]+name = "jiff-tzdb-platform"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc65b284afcfa8f6cf189c7274c805505314a7ab975c60e1f548bff56525420e"+dependencies = [+ "jiff-tzdb 1.0.0",][[package]]@@ -2233,9 +2308,9 @@ dependencies = [[[package]]name = "js-sys"-version = "0.3.105"+version = "0.3.107"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e"+checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a"dependencies = ["cfg-if","futures-util",@@ -2244,9 +2319,9 @@ dependencies = [[[package]]name = "json-patch"-version = "4.2.0"+version = "5.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7421438de105a0827e44fadd05377727847d717c80ce29a229f85fd04c427b72"+checksum = "aa295c8f71b9bad32d060e0e145f96dcba0cc6c6171e129646140d1c96b05617"dependencies = ["jsonptr","serde",@@ -2256,9 +2331,9 @@ dependencies = [[[package]]name = "jsonptr"-version = "0.7.1"+version = "0.8.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a5a3cc660ba5d72bce0b3bb295bf20847ccbb40fd423f3f05b61273672e561fe"+checksum = "72c22d99362c7aac7d77efab6b49c2181674b165d7e6e7c755b3432ded64bf51"dependencies = ["serde","serde_json",@@ -2270,39 +2345,35 @@ version = "0.8.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0fbe853b403ae61a04233030ae8a79d94975281ed9770a1f9e246732b534b28d"dependencies = [- "bitflags 2.13.2",+ "bitflags","serde",][[package]]name = "libappindicator"-version = "0.9.0"+version = "0.10.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "03589b9607c868cc7ae54c0b2a22c8dc03dd41692d48f2d7df73615c6a95dc0a"+checksum = "f57fd42f20edd22ee374ebcedda7bdecd1d5d1e76f11880d9ff2898ed2150d76"dependencies = [- "glib","gtk",- "gtk-sys","libappindicator-sys",- "log",][[package]]name = "libappindicator-sys"-version = "0.9.0"+version = "0.10.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6e9ec52138abedcc58dc17a7c6c0c00a2bdb4f3427c7f63fa97fd0d859155caf"+checksum = "0b76d3d67eb285f611b14654cd097f52eb7e83acc2b59913147f8ac695b61149"dependencies = ["gtk-sys",- "libloading",- "once_cell",+ "libloading 0.9.1",][[package]]name = "libc"-version = "0.2.189"+version = "0.2.191"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"[[package]]name = "libdbus-sys"@@ -2315,14 +2386,30 @@ dependencies = [[[package]]name = "libloading"-version = "0.7.4"+version = "0.8.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f"+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"dependencies = ["cfg-if",- "winapi",+ "windows-link 0.2.1",+]++[[package]]+name = "libloading"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a1832accd5a4ca2795ace4d05d15c4039be15b62d3b950eff99746a990e3cc10"+dependencies = [+ "cfg-if",+ "windows-link 0.2.1",]+[[package]]+name = "libm"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"+[[package]]name = "libredox"version = "0.1.25"@@ -2361,6 +2448,12 @@ version = "0.8.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"+[[package]]+name = "litrs"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "02b614978e47ce529faee66579f2b2fe19c94aa96d910a6a9a8043b2b02d8175"+[[package]]name = "lock_api"version = "0.4.14"@@ -2372,30 +2465,19 @@ dependencies = [[[package]]name = "log"-version = "0.4.34"+version = "0.4.35"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"+checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"[[package]]name = "lz4_flex"-version = "0.11.6"+version = "0.11.7"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "373f5eceeeab7925e0c1098212f2fbc4d416adec9d35051a6ab251e824c1854a"+checksum = "13591d77a9b6d941f7e6fcade7f9dfd9e801308752bde50c0a9bb5852778c22c"dependencies = ["twox-hash",]-[[package]]-name = "markup5ever"-version = "0.39.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de"-dependencies = [- "log",- "tendril",- "web_atoms 0.2.6",-]-[[package]]name = "markup5ever"version = "0.40.0"@@ -2404,7 +2486,7 @@ checksum = "0ab3dc68ac4a0f5719e560136778c1ee716e296030d75dbd4484e37e39e3a842"dependencies = ["log","tendril",- "web_atoms 0.3.0",+ "web_atoms",][[package]]@@ -2430,9 +2512,9 @@ dependencies = [[[package]]name = "mime"-version = "0.3.17"+version = "0.3.18"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"+checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1"[[package]]name = "mime_guess"@@ -2472,9 +2554,9 @@ dependencies = [[[package]]name = "mio"-version = "1.2.3"+version = "1.2.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8"+checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a"dependencies = ["libc","wasi",@@ -2483,32 +2565,69 @@ dependencies = [[[package]]name = "muda"-version = "0.20.0"+version = "0.22.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cca139e57da4383727f189e43e66e84fa372347027fc996f9f1a007ec0a37996"+checksum = "a775675be5389020a44c56efbdf3bbea8b97f47dfdd325e6c5c5213797a7e0aa"dependencies = ["crossbeam-channel","dpi","gtk","keyboard-types",+ "libc","objc2","objc2-app-kit","objc2-core-foundation","objc2-foundation",- "once_cell","png","serde","thiserror 2.0.21","windows-sys 0.61.2",]+[[package]]+name = "naga"+version = "30.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd0dd362bf26c0ffdd143df6da66a25d287e196eff482f117771010b207ad163"+dependencies = [+ "arrayvec",+ "bit-set 0.10.0",+ "bitflags",+ "cfg-if",+ "cfg_aliases",+ "codespan-reporting",+ "half",+ "hashbrown 0.17.2",+ "indexmap 2.14.2",+ "libm",+ "log",+ "naga-types",+ "num-traits",+ "once_cell",+ "rustc-hash 1.1.0",+ "thiserror 2.0.21",+ "unicode-ident",+]++[[package]]+name = "naga-types"+version = "30.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "14474170feb673cfb18b3565111a9869797cc1d290fb9ec969c53f5e1e231c6d"+dependencies = [+ "hashbrown 0.17.2",+ "indexmap 2.14.2",+ "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 2.13.2",+ "bitflags","jni-sys 0.3.1","log","ndk-sys",@@ -2544,7 +2663,7 @@ version = "0.32.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "77730ed34f01f4990cb2ea67fec715ecebc6fab9a6396cf83c5529b13f581bdc"dependencies = [- "bitflags 2.13.2",+ "bitflags","cfg-if","cfg_aliases","libc",@@ -2563,6 +2682,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"dependencies = ["autocfg",+ "libm",][[package]]@@ -2581,7 +2701,7 @@ version = "0.7.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"dependencies = [- "proc-macro-crate 3.5.0",+ "proc-macro-crate","proc-macro2","quote","syn 2.0.119",@@ -2589,9 +2709,9 @@ dependencies = [[[package]]name = "objc2"-version = "0.6.4"+version = "0.6.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f"+checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"dependencies = ["objc2-encode","objc2-exception-helper",@@ -2603,7 +2723,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"dependencies = [- "bitflags 2.13.2",+ "bitflags","block2","objc2","objc2-core-foundation",@@ -2617,7 +2737,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c"dependencies = [- "bitflags 2.13.2",+ "bitflags","objc2","objc2-foundation",]@@ -2638,7 +2758,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"dependencies = [- "bitflags 2.13.2",+ "bitflags","dispatch2","objc2",]@@ -2649,7 +2769,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"dependencies = [- "bitflags 2.13.2",+ "bitflags","dispatch2","objc2","objc2-core-foundation",@@ -2682,7 +2802,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d"dependencies = [- "bitflags 2.13.2",+ "bitflags","objc2","objc2-core-foundation","objc2-core-graphics",@@ -2709,7 +2829,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"dependencies = [- "bitflags 2.13.2",+ "bitflags","block2","libc","objc2",@@ -2722,7 +2842,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"dependencies = [- "bitflags 2.13.2",+ "bitflags","objc2","objc2-core-foundation",]@@ -2733,7 +2853,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0"dependencies = [- "bitflags 2.13.2",+ "bitflags","objc2","objc2-app-kit","objc2-foundation",@@ -2745,7 +2865,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"dependencies = [- "bitflags 2.13.2",+ "bitflags","objc2","objc2-core-foundation","objc2-foundation",@@ -2757,7 +2877,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22"dependencies = [- "bitflags 2.13.2",+ "bitflags","block2","objc2","objc2-cloud-kit",@@ -2788,7 +2908,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b2e5aaab980c433cf470df9d7af96a7b46a9d892d521a2cbbb2f8a4c16751e7f"dependencies = [- "bitflags 2.13.2",+ "bitflags","block2","objc2","objc2-app-kit",@@ -2804,9 +2924,9 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"[[package]]name = "open"-version = "5.4.4"+version = "5.4.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "aa576c76302b7b808eecc68061e67336c47833ef9d22caa74dda10fa9675eebc"+checksum = "8d8c8b8e725ad26404d6896eb2f064294a0a7b4f1d9120210d85544684c4ca95"dependencies = ["dunce","is-wsl",@@ -2825,6 +2945,15 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"+[[package]]+name = "ordered-float"+version = "5.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab"+dependencies = [+ "num-traits",+]+[[package]]name = "ordered-stream"version = "0.2.0"@@ -2851,27 +2980,25 @@ dependencies = [[[package]]name = "pango"-version = "0.18.3"+version = "0.22.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4"+checksum = "0b2022dbbd82e1c42bd950a6f1df9b98c796e725dce5ec275e03cbf9772e4efa"dependencies = ["gio","glib",- "libc",- "once_cell","pango-sys",][[package]]name = "pango-sys"-version = "0.18.0"+version = "0.22.11"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5"+checksum = "dd6be7bdb6cde4c49703315c1818a14382ce500dce57179a8d05f1c5efe4955f"dependencies = ["glib-sys","gobject-sys","libc",- "system-deps",+ "system-deps 9.0.1",][[package]]@@ -2909,56 +3036,25 @@ version = "2.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"-[[package]]-name = "phf"-version = "0.13.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"-dependencies = [- "phf_macros 0.13.1",- "phf_shared 0.13.1",- "serde",-]-[[package]]name = "phf"version = "0.14.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6"dependencies = [- "phf_macros 0.14.0",- "phf_shared 0.14.0",+ "phf_macros",+ "phf_shared","serde",]-[[package]]-name = "phf_codegen"-version = "0.13.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1"-dependencies = [- "phf_generator 0.13.1",- "phf_shared 0.13.1",-]-[[package]]name = "phf_codegen"version = "0.14.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "41b585a510fb76fdebead6897982ef2a03a21d8e6cbcca904999742a4afc6ffe"dependencies = [- "phf_generator 0.14.0",- "phf_shared 0.14.0",-]--[[package]]-name = "phf_generator"-version = "0.13.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"-dependencies = [- "fastrand",- "phf_shared 0.13.1",+ "phf_generator",+ "phf_shared",][[package]]@@ -2968,20 +3064,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100"dependencies = ["fastrand",- "phf_shared 0.14.0",-]--[[package]]-name = "phf_macros"-version = "0.13.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"-dependencies = [- "phf_generator 0.13.1",- "phf_shared 0.13.1",- "proc-macro2",- "quote",- "syn 2.0.119",+ "phf_shared",][[package]]@@ -2990,22 +3073,13 @@ version = "0.14.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085"dependencies = [- "phf_generator 0.14.0",- "phf_shared 0.14.0",+ "phf_generator",+ "phf_shared","proc-macro2","quote","syn 2.0.119",]-[[package]]-name = "phf_shared"-version = "0.13.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"-dependencies = [- "siphasher",-]-[[package]]name = "phf_shared"version = "0.14.0"@@ -3017,9 +3091,9 @@ dependencies = [[[package]]name = "pin-project-lite"-version = "0.2.17"+version = "0.2.18"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"+checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752"[[package]]name = "piper"@@ -3040,9 +3114,9 @@ checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"[[package]]name = "plist"-version = "1.10.1"+version = "1.10.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2896bade328c13f7042a297ea5ac5b0951f6cf989dea5f32c2fd98da398195cb"+checksum = "cb7a42747bbcc4374e6922a15040dccacf720e4ce48a77e668f7116b9aa19a0a"dependencies = ["base64 0.23.1","indexmap 2.14.2",@@ -3057,7 +3131,7 @@ version = "0.18.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"dependencies = [- "bitflags 2.13.2",+ "bitflags","crc32fast","fdeflate","flate2",@@ -3078,6 +3152,12 @@ dependencies = ["windows-sys 0.61.2",]+[[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"@@ -3104,9 +3184,9 @@ dependencies = [[[package]]name = "powerfmt"-version = "0.2.0"+version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"+checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"[[package]]name = "ppv-lite86"@@ -3124,24 +3204,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"[[package]]-name = "proc-macro-crate"-version = "1.3.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919"-dependencies = [- "once_cell",- "toml_edit 0.19.15",-]--[[package]]-name = "proc-macro-crate"-version = "2.0.2"+name = "presser"+version = "0.3.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b00f26d3400549137f92511a46ac1cd8ce37cb5598a96d382381458b992a5d24"-dependencies = [- "toml_datetime 0.6.3",- "toml_edit 0.20.2",-]+checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"[[package]]name = "proc-macro-crate"@@ -3149,31 +3215,7 @@ version = "3.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"dependencies = [- "toml_edit 0.25.15+spec-1.1.0",-]--[[package]]-name = "proc-macro-error"-version = "1.0.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"-dependencies = [- "proc-macro-error-attr",- "proc-macro2",- "quote",- "syn 1.0.109",- "version_check",-]--[[package]]-name = "proc-macro-error-attr"-version = "1.0.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"-dependencies = [- "proc-macro2",- "quote",- "version_check",+ "toml_edit",][[package]]@@ -3185,6 +3227,12 @@ dependencies = ["unicode-ident",]+[[package]]+name = "profiling"+version = "1.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5"+[[package]]name = "quick-xml"version = "0.42.0"@@ -3245,6 +3293,12 @@ dependencies = ["getrandom 0.2.17",]+[[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"@@ -3277,7 +3331,7 @@ version = "0.5.18"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"dependencies = [- "bitflags 2.13.2",+ "bitflags",][[package]]@@ -3307,14 +3361,14 @@ checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a"dependencies = ["proc-macro2","quote",- "syn 3.0.6",+ "syn 3.0.10",][[package]]name = "regex"-version = "1.13.1"+version = "1.13.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"+checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857"dependencies = ["aho-corasick","memchr",@@ -3324,9 +3378,9 @@ dependencies = [[[package]]name = "regex-automata"-version = "0.4.18"+version = "0.4.19"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"+checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"dependencies = ["aho-corasick","memchr",@@ -3335,9 +3389,15 @@ dependencies = [[[package]]name = "regex-syntax"-version = "0.8.11"+version = "0.8.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"++[[package]]+name = "renderdoc-sys"+version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"+checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"[[package]]name = "reqwest"@@ -3392,13 +3452,19 @@ dependencies = ["windows-sys 0.52.0",]+[[package]]+name = "rtrb"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5974e397833d890f2f74963408e0d4a6cd8eda2f6a445ae06750291b5d7a997e"+[[package]]name = "rusqlite"version = "0.32.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"dependencies = [- "bitflags 2.13.2",+ "bitflags","fallible-iterator","fallible-streaming-iterator","hashlink",@@ -3408,9 +3474,9 @@ dependencies = [[[package]]name = "rust-embed"-version = "8.12.0"+version = "8.14.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e9e7760e252aaba7b09f4be00e36476cf585bdb68a53552ac954cdf504ab4bc9"+checksum = "e98f580cf7a2863aeb6827800283f52cbe6fb3f3bb7c1843783f903c16dcb8ad"dependencies = ["rust-embed-impl","rust-embed-utils",@@ -3419,9 +3485,9 @@ dependencies = [[[package]]name = "rust-embed-impl"-version = "8.12.0"+version = "8.14.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3bcfc4d6f53af43755f7a723e4b6b8794fcce052a178dd8c6c1dadc5f5343097"+checksum = "a93e2f69cf224a6c7df7509aa5ba4a23f56828ee41b040e92ac8762371eb9ba7"dependencies = ["mime_guess","proc-macro2",@@ -3433,14 +3499,20 @@ dependencies = [[[package]]name = "rust-embed-utils"-version = "8.12.0"+version = "8.14.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "42ffa149f6aa81b58a5b3011d01a857c4ed12c7a732d2c51947a4c7c692185f0"+checksum = "915e33dccbe7deb2b8a342dc4c517503fe85e0230ddbae40a4fb0220493dad9b"dependencies = [- "sha2 0.11.0",+ "sha2 0.11.3","walkdir",]+[[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"@@ -3458,11 +3530,11 @@ dependencies = [[[package]]name = "rustix"-version = "1.1.5"+version = "1.1.6"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"+checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"dependencies = [- "bitflags 2.13.2",+ "bitflags","errno","libc","linux-raw-sys",@@ -3601,9 +3673,9 @@ dependencies = [[[package]]name = "schemars"-version = "1.2.2"+version = "1.2.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "687274d293b6cdc6e73e0fee520bf2049650090d7164f87672d212a3c530cf4a"+checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e"dependencies = ["dyn-clone","ref-cast",@@ -3635,7 +3707,7 @@ version = "3.7.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"dependencies = [- "bitflags 2.13.2",+ "bitflags","core-foundation 0.10.1","core-foundation-sys","libc",@@ -3652,39 +3724,20 @@ dependencies = ["libc",]-[[package]]-name = "selectors"-version = "0.38.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8adfa1c298912827b8a28b223b3b874357397ae706e6190acd9bf28cee99114d"-dependencies = [- "bitflags 2.13.2",- "cssparser 0.37.0",- "derive_more",- "log",- "new_debug_unreachable",- "phf 0.13.1",- "phf_codegen 0.13.1",- "precomputed-hash",- "rustc-hash",- "servo_arc 0.4.3",- "smallvec",-]-[[package]]name = "selectors"version = "0.41.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8322aebea94a6cc288ff884e8a49bdbceef60206c400c6c46d22e62fc4fd91a6"dependencies = [- "bitflags 2.13.2",- "cssparser 0.38.0",+ "bitflags",+ "cssparser","derive_more","log","new_debug_unreachable","precomputed-hash",- "rustc-hash",- "servo_arc 0.5.0",+ "rustc-hash 2.1.3",+ "servo_arc","smallvec",]@@ -3737,7 +3790,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"dependencies = ["proc-macro2","quote",- "syn 3.0.6",+ "syn 3.0.10",][[package]]@@ -3753,9 +3806,9 @@ dependencies = [[[package]]name = "serde_json"-version = "1.0.151"+version = "1.0.154"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"+checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"dependencies = ["itoa","memchr",@@ -3783,23 +3836,14 @@ checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906"dependencies = ["proc-macro2","quote",- "syn 3.0.6",+ "syn 3.0.10",][[package]]name = "serde_spanned"-version = "0.6.9"+version = "1.1.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"-dependencies = [- "serde",-]--[[package]]-name = "serde_spanned"-version = "1.1.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26"+checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"dependencies = ["serde_core",]@@ -3818,9 +3862,9 @@ dependencies = [[[package]]name = "serde_with"-version = "3.23.0"+version = "3.25.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "935177bb8c0cd8ca1a4e6d1a2ac8988bea69cab4f9d3a31311e012ad27868ea4"+checksum = "56cb1ca7c93ae63d6439b5250f6b6b040f7e121f32e5dd2f5d523dd4149b3204"dependencies = ["base64 0.23.1","bs58",@@ -3828,9 +3872,10 @@ dependencies = ["hex","indexmap 1.9.3","indexmap 2.14.2",- "jiff",+ "jiff 0.2.46",+ "jiff 1.1.0","schemars 0.9.0",- "schemars 1.2.2",+ "schemars 1.2.3","serde_core","serde_json","serde_with_macros",@@ -3839,14 +3884,14 @@ dependencies = [[[package]]name = "serde_with_macros"-version = "3.23.0"+version = "3.25.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1d607aa01a3cb0ad757d6fd216136910db3c97b102fe686585689615a02dbcdc"+checksum = "cff15a7c864bbec77d9586ca6822bc7c369bdf19e9243134a62b0b51ce26b31f"dependencies = ["darling","proc-macro2","quote",- "syn 3.0.6",+ "syn 3.0.10",][[package]]@@ -3871,15 +3916,6 @@ dependencies = ["syn 2.0.119",]-[[package]]-name = "servo_arc"-version = "0.4.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "170fb83ab34de17dc69aa7c67482b22218ddb85da56546f9bd6b929e32a05930"-dependencies = [- "stable_deref_trait",-]-[[package]]name = "servo_arc"version = "0.5.0"@@ -3913,9 +3949,9 @@ dependencies = [[[package]]name = "sha2"-version = "0.11.0"+version = "0.11.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"+checksum = "820083d430c52864bf834423fc988cbcf61685d6f9d22a765a64e3f6cfe3521c"dependencies = ["cfg-if","cpufeatures 0.3.1",@@ -3962,9 +3998,9 @@ checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"[[package]]name = "siphasher"-version = "1.0.3"+version = "1.0.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649"+checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"[[package]]name = "slab"@@ -3974,9 +4010,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"[[package]]name = "smallvec"-version = "1.16.1"+version = "1.16.6"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891"+checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59"[[package]]name = "socket2"@@ -4012,9 +4048,9 @@ dependencies = [[[package]]name = "soup3"-version = "0.5.0"+version = "0.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "471f924a40f31251afc77450e781cb26d55c0b650842efafc9c6cbd2f7cc4f9f"+checksum = "92d38b59ff6d302538efd337e15d04d61c5b909ec223c60ae4061d74605a962a"dependencies = ["futures-channel","gio",@@ -4025,15 +4061,15 @@ dependencies = [[[package]]name = "soup3-sys"-version = "0.5.0"+version = "0.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7ebe8950a680a12f24f15ebe1bf70db7af98ad242d9db43596ad3108aab86c27"+checksum = "79d5d25225bb06f83b78ff8cc35973b56d45fcdd21af6ed6d2bbd67f5a6f9bea"dependencies = ["gio-sys","glib-sys","gobject-sys","libc",- "system-deps",+ "system-deps 7.0.8",][[package]]@@ -4043,22 +4079,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"[[package]]-name = "static_vcruntime"-version = "3.0.0"+name = "static_assertions"+version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ff7589a1859b09232522bb9edf076ca7fcf14ded96685d3fa629db73023ffbb7"+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"[[package]]-name = "string_cache"-version = "0.9.0"+name = "static_vcruntime"+version = "3.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901"-dependencies = [- "new_debug_unreachable",- "parking_lot",- "phf_shared 0.13.1",- "precomputed-hash",-]+checksum = "ff7589a1859b09232522bb9edf076ca7fcf14ded96685d3fa629db73023ffbb7"[[package]]name = "string_cache"@@ -4068,30 +4098,18 @@ checksum = "ffa8a5dbe8b3f0bbe29d4c3225daafaeead63afdc1b65fc4c01a1384166038e6"dependencies = ["new_debug_unreachable","parking_lot",- "phf_shared 0.14.0",+ "phf_shared","precomputed-hash",]-[[package]]-name = "string_cache_codegen"-version = "0.6.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69"-dependencies = [- "phf_generator 0.13.1",- "phf_shared 0.13.1",- "proc-macro2",- "quote",-]-[[package]]name = "string_cache_codegen"version = "0.11.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "928dcdf75e47626b3617a976ec205d9f057584c371c1f23b782129268d0e6edc"dependencies = [- "phf_generator 0.14.0",- "phf_shared 0.14.0",+ "phf_generator",+ "phf_shared","proc-macro2","quote",]@@ -4119,16 +4137,6 @@ dependencies = ["serde_json",]-[[package]]-name = "syn"-version = "1.0.109"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"-dependencies = [- "proc-macro2",- "unicode-ident",-]-[[package]]name = "syn"version = "2.0.119"@@ -4142,9 +4150,9 @@ dependencies = [[[package]]name = "syn"-version = "3.0.6"+version = "3.0.10"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"+checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"dependencies = ["proc-macro2","quote",@@ -4168,7 +4176,7 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"dependencies = ["proc-macro2","quote",- "syn 3.0.6",+ "syn 3.0.10",][[package]]@@ -4177,7 +4185,7 @@ version = "0.7.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b"dependencies = [- "bitflags 2.13.2",+ "bitflags","core-foundation 0.9.4","system-configuration-sys",]@@ -4194,24 +4202,38 @@ dependencies = [[[package]]name = "system-deps"-version = "6.2.2"+version = "7.0.8"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349"+checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7"dependencies = ["cfg-expr",- "heck 0.5.0",+ "heck","pkg-config",- "toml 0.8.2",+ "toml",+ "version-compare",+]++[[package]]+name = "system-deps"+version = "9.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db551ad38aac61d5e0343e0eeeb0163be3115c4e23b6a025959570ee0c03c67d"+dependencies = [+ "cfg-expr",+ "heck",+ "pkg-config",+ "toml","version-compare",][[package]]name = "tao"-version = "0.37.3"+version = "0.38.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "02ca9c0ce2a2fd70dc4ef4449ca5e8d30e6fa0db111cd8008594602a06a68371"+checksum = "018765afffb658648fbdfa825af8f117ceee0499296811802d8359663932e7b7"dependencies = [- "bitflags 2.13.2",+ "async-channel",+ "bitflags","block2","core-foundation 0.10.1","core-graphics",@@ -4239,8 +4261,8 @@ dependencies = ["tao-macros","unicode-segmentation","url",- "windows 0.62.2",- "windows-core 0.62.2",+ "windows",+ "windows-core","windows-version","x11-dl",]@@ -4269,15 +4291,15 @@ dependencies = [[[package]]name = "target-lexicon"-version = "0.12.16"+version = "0.13.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"+checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"[[package]]name = "tauri"-version = "2.12.7"+version = "2.13.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "30fbfbb9dc9a2697b0e96d909ddc295fb18d2d82a58ed542ab8d9eba2edbe6da"+checksum = "ad570590a6620bd7a767910958cdc581308bef2ccae4a2b794f0347aa5169b75"dependencies = ["anyhow","bytes",@@ -4288,7 +4310,7 @@ dependencies = ["getrandom 0.3.4","glob","gtk",- "heck 0.5.0",+ "heck","http","jni 0.21.1","libc",@@ -4321,24 +4343,21 @@ dependencies = ["webkit2gtk","webview2-com","window-vibrancy",- "windows 0.62.2",+ "windows",][[package]]name = "tauri-build"-version = "2.7.6"+version = "2.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "73d80784e874fa117b9b00a6680cf2f9b8a51bbd14406bea980cf8f328b00646"+checksum = "97cc0781e9d66f684d7150507d5423fc05322312ddfd12f24c30e833cf183153"dependencies = ["anyhow","cargo_toml","dirs","glob",- "heck 0.5.0","json-patch",- "schemars 0.8.22","semver",- "serde","serde_json","static_vcruntime","strsim",@@ -4349,9 +4368,9 @@ dependencies = [[[package]]name = "tauri-codegen"-version = "2.7.6"+version = "2.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c5dc6caab4da5646f57648f39b794bae118f0dd4a4305eeb8c892966171f4852"+checksum = "96c0e6d4ad77790f6da7ac445f1a8908211785e5324bb6a9662582f3ac127231"dependencies = ["base64 0.23.1","brotli",@@ -4362,25 +4381,22 @@ dependencies = ["proc-macro2","quote","semver",- "serde","serde_json",- "sha2 0.11.0",+ "sha2 0.11.3","syn 2.0.119","tauri-utils","thiserror 2.0.21",- "time",- "url","uuid","walkdir",][[package]]name = "tauri-macros"-version = "2.7.6"+version = "2.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2831c5da8603a96b1efc0b650c2cb6decc69b6cda257d815fe70c7f5be53818e"+checksum = "564854181dbca954a49e852140be2d810c4fc3e882538e8f530bb197bd69cfec"dependencies = [- "heck 0.5.0",+ "heck","proc-macro2","quote","syn 2.0.119",@@ -4390,9 +4406,9 @@ dependencies = [[[package]]name = "tauri-plugin"-version = "2.7.4"+version = "2.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6c18076d9b04211cb4899387aab97497e8edd0d02cd21710623afcdde27145d1"+checksum = "7ace389bb5d5ac6379af1e50981a7860e254157c8d333627473a2c9d23134047"dependencies = ["anyhow","glob",@@ -4406,9 +4422,9 @@ dependencies = [[[package]]name = "tauri-plugin-opener"-version = "2.5.5"+version = "2.7.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "60d60366174b745b4ef5824b8bbc1c457fd08f0ce101ff643c0a49181a9f4e91"+checksum = "54592c6718b42ab198bf11bda6a428a3553ca2f2f8e506df56f6a063ec328331"dependencies = ["dunce","glob",@@ -4422,7 +4438,7 @@ dependencies = ["tauri-plugin","thiserror 2.0.21","url",- "windows 0.61.3",+ "windows","zbus",]@@ -4488,9 +4504,9 @@ dependencies = [[[package]]name = "tauri-runtime"-version = "2.12.4"+version = "2.13.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "60c2b14bd5265b63993cdc34ad526fb836e0fd0cf64a4634a895db0784844d5e"+checksum = "33ebc9c0fc7a10f26169edd4adcc8798030cd025b2621791fe7f7e0330105c68"dependencies = ["cookie","dpi",@@ -4508,14 +4524,14 @@ dependencies = ["url","webkit2gtk","webview2-com",- "windows 0.62.2",+ "windows",][[package]]name = "tauri-runtime-wry"-version = "2.12.5"+version = "2.13.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b8c14a025255cc9816d401635035075b09b6cc9973b7b8fd7b8fcb8753f30f92"+checksum = "34a8d0c102664aaec2d2bfc4e8c4375e253a4192f574bb4352517c152643c6a8"dependencies = ["gtk","http",@@ -4532,21 +4548,21 @@ dependencies = ["url","webkit2gtk","webview2-com",- "windows 0.62.2",+ "windows","wry",][[package]]name = "tauri-utils"-version = "2.10.4"+version = "2.11.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "28d1d33d4453c5df0bf1672dbc7ada69d8ed74f56a4316d964a4aa73d4ecd3ad"+checksum = "4b3bb2217a2c5632f25a375c305f5a1f9b3beaa7b0614a21e79f297b6b3cbc92"dependencies = ["anyhow","brotli","cargo_metadata","ctor",- "dom_query 0.28.0",+ "dom_query","dunce","glob","http",@@ -4554,7 +4570,7 @@ dependencies = ["json-patch","log","memchr",- "phf 0.13.1",+ "phf","plist","proc-macro2","quote",@@ -4567,7 +4583,7 @@ dependencies = ["serde_with","swift-rs","thiserror 2.0.21",- "toml 1.1.6+spec-1.1.0",+ "toml","url","urlpattern","uuid",@@ -4576,13 +4592,13 @@ dependencies = [[[package]]name = "tauri-winres"-version = "0.3.6"+version = "0.3.7"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cc65d45c68858bfe420dd29e834b5d15dbecf8a07a8a16cf4d532c7b1f69d4b6"+checksum = "c52bb6904475a6ca662f15ef787f18ade61d5740a1ee12c45d3b748efdb6f796"dependencies = ["dunce","embed-resource",- "toml 1.1.6+spec-1.1.0",+ "toml",][[package]]@@ -4644,7 +4660,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"dependencies = ["proc-macro2","quote",- "syn 3.0.6",+ "syn 3.0.10",][[package]]@@ -4679,9 +4695,9 @@ dependencies = [[[package]]name = "tinystr"-version = "0.8.4"+version = "0.8.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643"+checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a"dependencies = ["displaydoc","zerovec",@@ -4695,9 +4711,9 @@ checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"[[package]]name = "tokio"-version = "1.53.1"+version = "1.54.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed"+checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"dependencies = ["bytes","libc",@@ -4718,7 +4734,7 @@ checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"dependencies = ["proc-macro2","quote",- "syn 3.0.6",+ "syn 3.0.10",][[package]]@@ -4745,9 +4761,9 @@ dependencies = [[[package]]name = "tokio-util"-version = "0.7.19"+version = "0.7.20"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52"+checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b"dependencies = ["bytes","futures-core",@@ -4758,99 +4774,54 @@ dependencies = [[[package]]name = "toml"-version = "0.8.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d"-dependencies = [- "serde",- "serde_spanned 0.6.9",- "toml_datetime 0.6.3",- "toml_edit 0.20.2",-]--[[package]]-name = "toml"-version = "1.1.6+spec-1.1.0"+version = "1.2.3+spec-1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a"+checksum = "26b1f26e9485c1fa43ee89fe76e9f3fb9e2e52bb227f8594b4d687496b83d073"dependencies = ["indexmap 2.14.2","serde_core",- "serde_spanned 1.1.1",- "toml_datetime 1.1.1+spec-1.1.0",+ "serde_spanned",+ "toml_datetime","toml_parser","toml_writer",- "winnow 1.0.4",-]--[[package]]-name = "toml_datetime"-version = "0.6.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b"-dependencies = [- "serde",+ "winnow",][[package]]name = "toml_datetime"-version = "1.1.1+spec-1.1.0"+version = "1.1.3+spec-1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"+checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"dependencies = ["serde_core",][[package]]name = "toml_edit"-version = "0.19.15"+version = "0.25.21+spec-1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421"+checksum = "88497dab46de5bf343ec66b05c251e48c6213f3e9170c70a70a823f7abe886a4"dependencies = ["indexmap 2.14.2",- "toml_datetime 0.6.3",- "winnow 0.5.40",-]--[[package]]-name = "toml_edit"-version = "0.20.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338"-dependencies = [- "indexmap 2.14.2",- "serde",- "serde_spanned 0.6.9",- "toml_datetime 0.6.3",- "winnow 0.5.40",-]--[[package]]-name = "toml_edit"-version = "0.25.15+spec-1.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614"-dependencies = [- "indexmap 2.14.2",- "toml_datetime 1.1.1+spec-1.1.0",+ "toml_datetime","toml_parser",- "winnow 1.0.4",+ "winnow",][[package]]name = "toml_parser"-version = "1.1.3+spec-1.1.0"+version = "1.1.7+spec-1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56"+checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a"dependencies = [- "winnow 1.0.4",+ "winnow",][[package]]name = "toml_writer"-version = "1.1.2+spec-1.1.0"+version = "1.2.0+spec-1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"+checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"[[package]]name = "tower"@@ -4874,7 +4845,7 @@ version = "0.5.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1e9cd434a998747dd2c4276bc96ee2e0c7a2eadf3cae88e52be55a05fa9053f5"dependencies = [- "bitflags 2.13.2",+ "bitflags","bytes","futures-util","http",@@ -4899,7 +4870,7 @@ version = "0.6.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"dependencies = [- "bitflags 2.13.2",+ "bitflags","bytes","futures-util","http",@@ -4957,9 +4928,9 @@ dependencies = [[[package]]name = "tray-icon"-version = "0.25.1"+version = "0.27.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b2b9c52859a94554803ccd4a24b98f74148ebc73b90676d783f3490b1bff9d72"+checksum = "19886363e700addca09f3787a1394eda88a80c89b9305f96effb9ea5ce09146d"dependencies = ["crossbeam-channel","dirs",@@ -4970,7 +4941,6 @@ dependencies = ["objc2-core-foundation","objc2-core-graphics","objc2-foundation",- "once_cell","png","serde","thiserror 2.0.21",@@ -5038,15 +5008,15 @@ dependencies = [[[package]]name = "unicase"-version = "2.9.0"+version = "2.10.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"+checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f"[[package]]name = "unicode-ident"-version = "1.0.26"+version = "1.0.27"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"[[package]]name = "unicode-segmentation"@@ -5054,6 +5024,12 @@ version = "1.13.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"+[[package]]+name = "unicode-width"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557"+[[package]]name = "untrusted"version = "0.9.0"@@ -5062,9 +5038,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"[[package]]name = "url"-version = "2.5.8"+version = "2.5.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"+checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a"dependencies = ["form_urlencoded","idna",@@ -5093,15 +5069,24 @@ checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"[[package]]name = "utf8_iter"-version = "1.0.4"+version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"+checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0"+dependencies = [+ "utf_types",+]++[[package]]+name = "utf_types"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6"[[package]]name = "uuid"-version = "1.26.1"+version = "1.29.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce"+checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64"dependencies = ["getrandom 0.4.3","js-sys",@@ -5149,9 +5134,9 @@ dependencies = [[[package]]name = "walkdir"-version = "2.5.0"+version = "2.5.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"+checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403"dependencies = ["same-file","winapi-util",@@ -5159,9 +5144,9 @@ dependencies = [[[package]]name = "want"-version = "0.3.1"+version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"+checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b"dependencies = ["try-lock",]@@ -5183,12 +5168,11 @@ dependencies = [[[package]]name = "wasm-bindgen"-version = "0.2.128"+version = "0.2.130"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf"+checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c"dependencies = ["cfg-if",- "once_cell","rustversion","wasm-bindgen-macro","wasm-bindgen-shared",@@ -5196,19 +5180,20 @@ dependencies = [[[package]]name = "wasm-bindgen-futures"-version = "0.4.78"+version = "0.4.80"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6ef4c5d3d2cdf5c54f4231181768f5510842e350db025faf1f7163b1030ed928"+checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501"dependencies = ["js-sys",+ "tokio","wasm-bindgen",][[package]]name = "wasm-bindgen-macro"-version = "0.2.128"+version = "0.2.130"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed"+checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9"dependencies = ["quote","wasm-bindgen-macro-support",@@ -5216,22 +5201,22 @@ dependencies = [[[package]]name = "wasm-bindgen-macro-support"-version = "0.2.128"+version = "0.2.130"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a"+checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a"dependencies = ["bumpalo","proc-macro2","quote",- "syn 3.0.6",+ "syn 3.0.10","wasm-bindgen-shared",][[package]]name = "wasm-bindgen-shared"-version = "0.2.128"+version = "0.2.130"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e"+checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e"dependencies = ["unicode-ident",]@@ -5251,9 +5236,9 @@ dependencies = [[[package]]name = "web-sys"-version = "0.3.105"+version = "0.3.107"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9fbddc4a036f00ec4f18c83445bd3115cb306a91da554919a099d9222fe4a7f8"+checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88"dependencies = ["js-sys","wasm-bindgen",@@ -5269,37 +5254,25 @@ dependencies = ["wasm-bindgen",]-[[package]]-name = "web_atoms"-version = "0.2.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ba8b815c1b593dc0baf78dd0f4fc8fdb2de53198fb1163738093e9a311c33fb3"-dependencies = [- "phf 0.13.1",- "phf_codegen 0.13.1",- "string_cache 0.9.0",- "string_cache_codegen 0.6.1",-]-[[package]]name = "web_atoms"version = "0.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7572660c8890448ba236b7376f27e389c6a7e1c70195622faced601f855c0ada"dependencies = [- "phf 0.14.0",- "phf_codegen 0.14.0",- "string_cache 0.11.0",- "string_cache_codegen 0.11.2",+ "phf",+ "phf_codegen",+ "string_cache",+ "string_cache_codegen",][[package]]name = "webkit2gtk"-version = "2.0.2"+version = "3.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a1027150013530fb2eaf806408df88461ae4815a45c541c8975e61d6f2fc4793"+checksum = "d10c534cfa5ce140449e4317116730d99f11dad6fbbb9fbd50e12eec44a01570"dependencies = [- "bitflags 1.3.2",+ "bitflags","cairo-rs","gdk","gdk-sys",@@ -5319,11 +5292,11 @@ dependencies = [[[package]]name = "webkit2gtk-sys"-version = "2.0.2"+version = "3.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "916a5f65c2ef0dfe12fff695960a2ec3d4565359fdbb2e9943c974e06c734ea5"+checksum = "8b1f9b6c0d50840d7299df258bab498aaac1eb4fe10e0bdd327b9d175dec0f5a"dependencies = [- "bitflags 1.3.2",+ "bitflags","cairo-sys-rs","gdk-sys","gio-sys",@@ -5334,7 +5307,7 @@ dependencies = ["libc","pkg-config","soup3-sys",- "system-deps",+ "system-deps 9.0.1",][[package]]@@ -5354,8 +5327,8 @@ checksum = "3f89fca7a704cee10dcb3654c1dbb8941d1783132f1917358af75bec37a7d7e6"dependencies = ["webview2-com-macros","webview2-com-sys",- "windows 0.62.2",- "windows-core 0.62.2",+ "windows",+ "windows-core",][[package]]@@ -5376,8 +5349,139 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b3a07132775117d6065853d9d1178157b8c90e228de47129d6bce2c7edebedfb"dependencies = ["thiserror 2.0.21",- "windows 0.62.2",- "windows-core 0.62.2",+ "windows",+ "windows-core",+]++[[package]]+name = "wgpu"+version = "30.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "146fc3d654250e6207921a66c87534c621bc886c70df83dcf466c1d66813810e"+dependencies = [+ "arrayvec",+ "bitflags",+ "bytemuck",+ "cfg-if",+ "cfg_aliases",+ "document-features",+ "hashbrown 0.17.2",+ "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.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ad661da2ee99f208c30090b585284b2ab5b8bf2358ddf2d2215592808ec62f1a"+dependencies = [+ "arrayvec",+ "bit-set 0.10.0",+ "bit-vec 0.9.1",+ "bitflags",+ "bytemuck",+ "cfg_aliases",+ "document-features",+ "hashbrown 0.17.2",+ "indexmap 2.14.2",+ "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.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1331b08fa2362c5d454eccc4448e6e4f01eccfea569a00e310adbfc4415f2bdc"+dependencies = [+ "wgpu-hal",+]++[[package]]+name = "wgpu-hal"+version = "30.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a57452fe453658e141aafdb09de1028afa498805fab518238ddf372a518813ff"+dependencies = [+ "arrayvec",+ "bit-set 0.10.0",+ "bitflags",+ "bytemuck",+ "cfg-if",+ "cfg_aliases",+ "gpu-allocator",+ "hashbrown 0.17.2",+ "libloading 0.8.9",+ "log",+ "naga",+ "naga-types",+ "once_cell",+ "ordered-float",+ "parking_lot",+ "portable-atomic",+ "portable-atomic-util",+ "profiling",+ "range-alloc",+ "raw-window-handle",+ "renderdoc-sys",+ "static_assertions",+ "thiserror 2.0.21",+ "wgpu-naga-bridge",+ "wgpu-types",+ "windows",+ "windows-core",+]++[[package]]+name = "wgpu-naga-bridge"+version = "30.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "44a62ead68aad7cd40ac9e2cd2b8ec64f32dfbad2765f429b9fb74b8b735869f"+dependencies = [+ "naga",+ "wgpu-types",+]++[[package]]+name = "wgpu-types"+version = "30.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a9f6ee0bd50f5ab79fb8c25e3f33afb27126f034af4ba5909c7a0967058659e6"+dependencies = [+ "bitflags",+ "bytemuck",+ "js-sys",+ "log",+ "naga-types",+ "raw-window-handle",+ "static_assertions",+ "web-sys",][[package]]@@ -5427,38 +5531,16 @@ dependencies = ["windows-version",]-[[package]]-name = "windows"-version = "0.61.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893"-dependencies = [- "windows-collections 0.2.0",- "windows-core 0.61.2",- "windows-future 0.2.1",- "windows-link 0.1.3",- "windows-numerics 0.2.0",-]-[[package]]name = "windows"version = "0.62.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"dependencies = [- "windows-collections 0.3.2",- "windows-core 0.62.2",- "windows-future 0.3.2",- "windows-numerics 0.3.1",-]--[[package]]-name = "windows-collections"-version = "0.2.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8"-dependencies = [- "windows-core 0.61.2",+ "windows-collections",+ "windows-core",+ "windows-future",+ "windows-numerics",][[package]]@@ -5467,20 +5549,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"dependencies = [- "windows-core 0.62.2",-]--[[package]]-name = "windows-core"-version = "0.61.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3"-dependencies = [- "windows-implement",- "windows-interface",- "windows-link 0.1.3",- "windows-result 0.3.4",- "windows-strings 0.4.2",+ "windows-core",][[package]]@@ -5492,19 +5561,8 @@ dependencies = ["windows-implement","windows-interface","windows-link 0.2.1",- "windows-result 0.4.1",- "windows-strings 0.5.1",-]--[[package]]-name = "windows-future"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e"-dependencies = [- "windows-core 0.61.2",- "windows-link 0.1.3",- "windows-threading 0.1.0",+ "windows-result",+ "windows-strings",][[package]]@@ -5513,9 +5571,9 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"dependencies = [- "windows-core 0.62.2",+ "windows-core","windows-link 0.2.1",- "windows-threading 0.2.1",+ "windows-threading",][[package]]@@ -5540,12 +5598,6 @@ dependencies = ["syn 2.0.119",]-[[package]]-name = "windows-link"-version = "0.1.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a"-[[package]]name = "windows-link"version = "0.2.1"@@ -5553,14 +5605,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"[[package]]-name = "windows-numerics"-version = "0.2.0"+name = "windows-link"+version = "0.101.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1"-dependencies = [- "windows-core 0.61.2",- "windows-link 0.1.3",-]+checksum = "f4e57b2aae53a240c62b65069a63eaf8d5fa747f5d0d8e670c5210a98847bce4"[[package]]name = "windows-numerics"@@ -5568,7 +5616,7 @@ version = "0.3.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"dependencies = [- "windows-core 0.62.2",+ "windows-core","windows-link 0.2.1",]@@ -5579,17 +5627,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"dependencies = ["windows-link 0.2.1",- "windows-result 0.4.1",- "windows-strings 0.5.1",-]--[[package]]-name = "windows-result"-version = "0.3.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6"-dependencies = [- "windows-link 0.1.3",+ "windows-result",+ "windows-strings",][[package]]@@ -5601,15 +5640,6 @@ dependencies = ["windows-link 0.2.1",]-[[package]]-name = "windows-strings"-version = "0.4.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57"-dependencies = [- "windows-link 0.1.3",-]-[[package]]name = "windows-strings"version = "0.5.1"@@ -5655,6 +5685,15 @@ dependencies = ["windows-link 0.2.1",]+[[package]]+name = "windows-sys"+version = "0.101.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eed2df9f5f458664c87437f6758f0d93085b06433bf66b2b84c23c19f3d2012c"+dependencies = [+ "windows-link 0.101.0",+]+[[package]]name = "windows-targets"version = "0.42.2"@@ -5686,15 +5725,6 @@ dependencies = ["windows_x86_64_msvc 0.52.6",]-[[package]]-name = "windows-threading"-version = "0.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6"-dependencies = [- "windows-link 0.1.3",-]-[[package]]name = "windows-threading"version = "0.2.1"@@ -5805,30 +5835,21 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"[[package]]name = "winnow"-version = "0.5.40"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876"-dependencies = [- "memchr",-]--[[package]]-name = "winnow"-version = "1.0.4"+version = "1.0.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"+checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"dependencies = ["memchr",][[package]]name = "winreg"-version = "0.55.0"+version = "0.56.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97"+checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10"dependencies = ["cfg-if",- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]@@ -5845,16 +5866,16 @@ checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"[[package]]name = "wry"-version = "0.57.3"+version = "0.58.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ceb43f824178e8110e3181bfd478359c43b041452a9560d321bd8d121e468f86"+checksum = "a9fadb3ce0a4ec6f7acddf364af8bbf14f5a1e532e5d5eed3b8141cdd3b3a774"dependencies = ["base64 0.23.1","block2","cookie","crossbeam-channel","dirs",- "dom_query 0.29.0",+ "dom_query","dpi","dunce","gdkx11",@@ -5872,7 +5893,7 @@ dependencies = ["objc2-web-kit","percent-encoding","raw-window-handle",- "sha2 0.10.9",+ "sha2 0.11.3","soup3","tao-macros","thiserror 2.0.21",@@ -5880,8 +5901,8 @@ dependencies = ["webkit2gtk","webkit2gtk-sys","webview2-com",- "windows 0.62.2",- "windows-core 0.62.2",+ "windows",+ "windows-core","windows-version","x11-dl",]@@ -5909,9 +5930,9 @@ dependencies = [[[package]]name = "xattr"-version = "1.6.1"+version = "1.7.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"+checksum = "963d6fab92d5504b971dc8bd90ca743c2575e590bc8071ea5bc571598667ae08"dependencies = ["libc","rustix",@@ -5919,9 +5940,9 @@ dependencies = [[[package]]name = "yoke"-version = "0.8.3"+version = "0.8.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"+checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3"dependencies = ["stable_deref_trait","yoke-derive",@@ -5930,13 +5951,13 @@ dependencies = [[[package]]name = "yoke-derive"-version = "0.8.3"+version = "0.8.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78"+checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"dependencies = ["proc-macro2","quote",- "syn 3.0.6",+ "syn 3.0.10","synstructure",]@@ -5969,7 +5990,7 @@ dependencies = ["uds_windows","uuid","windows-sys 0.61.2",- "winnow 1.0.4",+ "winnow","zbus_macros","zbus_names","zvariant",@@ -5981,10 +6002,10 @@ version = "5.19.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40"dependencies = [- "proc-macro-crate 3.5.0",+ "proc-macro-crate","proc-macro2","quote",- "syn 3.0.6",+ "syn 3.0.10","zbus_names","zvariant","zvariant_utils",@@ -5992,38 +6013,38 @@ dependencies = [[[package]]name = "zbus_names"-version = "4.3.4"+version = "4.3.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e"+checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd"dependencies = ["serde",- "winnow 1.0.4",+ "winnow","zvariant",][[package]]name = "zcheapstr"-version = "1.1.0"+version = "1.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473"+checksum = "2da34e7164b75d803c3197b86e6cf61b874106fbd472c5082575a8bc5fbd0907"dependencies = ["serde",][[package]]name = "zerocopy"-version = "0.8.58"+version = "0.8.66"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c17e8fafad82b542ff3717217ecdc736231b59e387768c9630123b4ce4d2db44"+checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a"dependencies = ["zerocopy-derive",][[package]]name = "zerocopy-derive"-version = "0.8.58"+version = "0.8.66"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "595f56e044df4f46a0c9a626f65c3d99eb8488f7e8a8baa12dd76326d9710bf2"+checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94"dependencies = ["proc-macro2","quote",@@ -6047,7 +6068,7 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"dependencies = ["proc-macro2","quote",- "syn 3.0.6",+ "syn 3.0.10","synstructure",]@@ -6084,9 +6105,9 @@ dependencies = [[[package]]name = "zerovec"-version = "0.11.8"+version = "0.11.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8"+checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40"dependencies = ["yoke","zerofrom",@@ -6095,20 +6116,20 @@ dependencies = [[[package]]name = "zerovec-derive"-version = "0.11.6"+version = "0.11.7"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da"+checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a"dependencies = ["proc-macro2","quote",- "syn 3.0.6",+ "syn 3.0.10",][[package]]name = "zip"-version = "9.8.1"+version = "9.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a9534624d547e3f516ecde0ed9a70d37788f01d340efcfdd03bf3ea8e163c1d0"+checksum = "07db37dec4a7c468df4723fba4cadb4822d1d0f10dbea367100b6a6881b2a9c9"dependencies = ["constant_time_eq","crc32fast",@@ -6124,9 +6145,9 @@ dependencies = [[[package]]name = "zlib-rs"-version = "0.6.8"+version = "0.6.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"+checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac"[[package]]name = "zmij"@@ -6136,14 +6157,14 @@ checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"[[package]]name = "zvariant"-version = "5.15.0"+version = "5.15.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c1d34c27cc6cdd1f458427519dd6b8612f7b7e3f7b9a0b2355d041dda9869147"+checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7"dependencies = ["endi","enumflags2","serde",- "winnow 1.0.4",+ "winnow","zcheapstr","zvariant_derive","zvariant_utils",@@ -6151,14 +6172,14 @@ dependencies = [[[package]]name = "zvariant_derive"-version = "5.15.0"+version = "5.15.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "864155e69b4352db0c7f374917bf45d1e0c8d17659c8b3dbf9795f3673f8c497"+checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d"dependencies = [- "proc-macro-crate 3.5.0",+ "proc-macro-crate","proc-macro2","quote",- "syn 3.0.6",+ "syn 3.0.10","zvariant_utils",]@@ -6171,6 +6192,6 @@ dependencies = ["proc-macro2","quote","serde",- "syn 3.0.6",- "winnow 1.0.4",+ "syn 3.0.10",+ "winnow",]diff --git a/Cargo.toml b/Cargo.tomlnew file mode 100644index 0000000..9f1636d--- /dev/null+++ b/Cargo.toml@@ -0,0 +1,18 @@+[workspace]+resolver = "2"+members = [+ "crates/ink-engine",+ "src-tauri",+]+default-members = [+ "crates/ink-engine",+ "src-tauri",+]++# Read the optimization guideline for more details: https://tauri.app/concept/size/#cargo-configuration+[profile.release]+codegen-units = 1+lto = true+opt-level = 3+panic = "abort"+strip = truediff --git a/crates/ink-engine/Cargo.toml b/crates/ink-engine/Cargo.tomlnew file mode 100644index 0000000..eb6e8b5--- /dev/null+++ b/crates/ink-engine/Cargo.toml@@ -0,0 +1,27 @@+[package]+name = "ink-engine"+version = "0.1.0"+edition = "2021"+description = "Decoupled native Windows wgpu (DX12) digital painting engine for InkStudio"+license = "GPL-3.0"++[dependencies]+bytemuck = { version = "1.21", features = ["derive"] }+crc32fast = "1.5"+crossbeam-channel = "0.5"+flate2 = "1.0"+half = "2.7"+lz4_flex = "0.11"+parking_lot = "0.12"+pollster = "0.4"+rayon = "1.10"+rtrb = "0.4"+serde = { version = "1", features = ["derive"] }+serde_json = "1"+wgpu = { version = "30", default-features = false, features = ["std", "parking_lot", "dx12", "wgsl"] }++[target.'cfg(target_os = "windows")'.dependencies]+windows-sys = { version = "0.59", features = [+ "Win32_System_Performance",+ "Win32_System_Threading",+] }diff --git a/crates/ink-engine/src/camera.rs b/crates/ink-engine/src/camera.rsnew file mode 100644index 0000000..09acfd7--- /dev/null+++ b/crates/ink-engine/src/camera.rs@@ -0,0 +1,427 @@+//! Exact 2D affine canvas camera math & native 120–240 Hz navigation controller.+//!+//! Matches `formatArtboardTransform` (`src/components/canvasArea/types.ts`),+//! `screenToCanvas` / `canvasToScreen` (`src/utils/canvasUtils.ts`), and+//! `useCanvasNavigation.ts` pixel-for-pixel.++use crate::types::{CameraState, NativeNavGesture};++pub const MIN_ZOOM: f32 = 0.01;+pub const MAX_ZOOM: f32 = 32.0;+pub const ROTATION_CENTER_DAMP_RADIUS: f32 = 64.0;++#[inline]+pub fn clamp_zoom(zoom: f32) -> f32 {+ if !zoom.is_finite() {+ 1.0+ } else {+ zoom.clamp(MIN_ZOOM, MAX_ZOOM)+ }+}++/// Transforms a document-space point `(doc_x, doc_y)` into viewport-local CSS pixels,+/// matching `canvasToScreen` in `src/utils/canvasUtils.ts` and `formatArtboardTransform`.+#[inline]+pub fn doc_to_viewport_css(+ doc_x: f32,+ doc_y: f32,+ doc_width: f32,+ doc_height: f32,+ cam: &CameraState,+) -> (f32, f32) {+ let fx = if cam.flip_x { -1.0 } else { 1.0 };+ let fy = if cam.flip_y { -1.0 } else { 1.0 };++ let dx = (doc_x - doc_width * 0.5) * fx;+ let dy = (doc_y - doc_height * 0.5) * fy;++ let rad = cam.rotation.to_radians();+ let (sin, cos) = rad.sin_cos();++ let rx = cam.zoom * (dx * cos - dy * sin);+ let ry = cam.zoom * (dx * sin + dy * cos);++ (cam.pan_x + rx, cam.pan_y + ry)+}++/// Transforms viewport-local CSS pixels `(vx, vy)` into document-space pixels,+/// matching `screenToCanvasInto` in `src/utils/canvasUtils.ts` pixel-for-pixel.+#[inline]+pub fn viewport_css_to_doc(+ vx: f32,+ vy: f32,+ doc_width: f32,+ doc_height: f32,+ cam: &CameraState,+) -> (f32, f32) {+ let rx = vx - cam.pan_x;+ let ry = vy - cam.pan_y;++ let rad = cam.rotation.to_radians();+ let (sin, cos) = rad.sin_cos();++ let unrot_x = rx * cos + ry * sin;+ let unrot_y = -rx * sin + ry * cos;++ let fx = if cam.flip_x { -1.0 } else { 1.0 };+ let fy = if cam.flip_y { -1.0 } else { 1.0 };+ let safe_zoom = cam.zoom.max(MIN_ZOOM);++ (+ doc_width * 0.5 + (fx * unrot_x) / safe_zoom,+ doc_height * 0.5 + (fy * unrot_y) / safe_zoom,+ )+}++/// Continuous, branch-cut-free signed angular delta (degrees) around `center` with+/// smoothstep radial damping inside `ROTATION_CENTER_DAMP_RADIUS` (64px).+/// Matches `computeSmoothRotationDelta` in `src/hooks/useCanvasNavigation.ts`.+pub fn compute_smooth_rotation_delta(+ prev_x: f32,+ prev_y: f32,+ cur_x: f32,+ cur_y: f32,+ center_x: f32,+ center_y: f32,+) -> f32 {+ let v1x = prev_x - center_x;+ let v1y = prev_y - center_y;+ let v2x = cur_x - center_x;+ let v2y = cur_y - center_y;++ let r1 = v1x.hypot(v1y);+ let r2 = v2x.hypot(v2y);+ if r1 < 1e-4 || r2 < 1e-4 {+ return 0.0;+ }++ let cross = v1x * v2y - v1y * v2x;+ let dot = v1x * v2x + v1y * v2y;+ let raw_deg = cross.atan2(dot).to_degrees();++ let min_r = r1.min(r2);+ if min_r >= ROTATION_CENTER_DAMP_RADIUS {+ return raw_deg;+ }+ let t = (min_r / ROTATION_CENTER_DAMP_RADIUS).clamp(0.0, 1.0);+ let smooth_gain = t * t * (3.0 - 2.0 * t);+ raw_deg * smooth_gain+}++#[derive(Debug, Clone)]+enum ActiveGestureState {+ Pan {+ start_css_x: f32,+ start_css_y: f32,+ start_pan_x: f32,+ start_pan_y: f32,+ },+ Rotate {+ last_css_x: f32,+ last_css_y: f32,+ start_rotation: f32,+ total_delta_deg: f32,+ start_pan_x: f32,+ start_pan_y: f32,+ center_x: f32,+ center_y: f32,+ },+ ZoomDrag {+ start_css_x: f32,+ anchor_x: f32,+ anchor_y: f32,+ start_zoom: f32,+ start_pan_x: f32,+ start_pan_y: f32,+ },+}++/// Stateful native camera navigation controller executed directly on the engine thread.+#[derive(Debug, Default)]+pub struct NativeCameraNavigator {+ active: Option<ActiveGestureState>,+}++impl NativeCameraNavigator {+ #[inline]+ pub fn is_active(&self) -> bool {+ self.active.is_some()+ }++ pub fn cancel(&mut self) {+ self.active = None;+ }++ pub fn begin(+ &mut self,+ gesture: NativeNavGesture,+ local_css_x: f32,+ local_css_y: f32,+ viewport_css_w: f32,+ viewport_css_h: f32,+ cam: &CameraState,+ ) {+ self.active = Some(match gesture {+ NativeNavGesture::Pan => ActiveGestureState::Pan {+ start_css_x: local_css_x,+ start_css_y: local_css_y,+ start_pan_x: cam.pan_x,+ start_pan_y: cam.pan_y,+ },+ NativeNavGesture::Rotate => ActiveGestureState::Rotate {+ last_css_x: local_css_x,+ last_css_y: local_css_y,+ start_rotation: cam.rotation,+ total_delta_deg: 0.0,+ start_pan_x: cam.pan_x,+ start_pan_y: cam.pan_y,+ center_x: viewport_css_w * 0.5,+ center_y: viewport_css_h * 0.5,+ },+ NativeNavGesture::ZoomDrag => ActiveGestureState::ZoomDrag {+ start_css_x: local_css_x,+ anchor_x: local_css_x,+ anchor_y: local_css_y,+ start_zoom: clamp_zoom(cam.zoom),+ start_pan_x: cam.pan_x,+ start_pan_y: cam.pan_y,+ },+ });+ }++ /// Updates camera in-place for a drag motion. Returns `true` if the camera changed.+ pub fn update(+ &mut self,+ local_css_x: f32,+ local_css_y: f32,+ snap_15_deg: bool,+ is_webtoon_mode: bool,+ cam: &mut CameraState,+ ) -> bool {+ let Some(state) = self.active.as_mut() else {+ return false;+ };++ match state {+ ActiveGestureState::Pan {+ start_css_x,+ start_css_y,+ start_pan_x,+ start_pan_y,+ } => {+ let dx = local_css_x - *start_css_x;+ let dy = local_css_y - *start_css_y;+ cam.pan_x = if is_webtoon_mode {+ *start_pan_x+ } else {+ *start_pan_x + dx+ };+ cam.pan_y = *start_pan_y + dy;+ true+ }+ ActiveGestureState::Rotate {+ last_css_x,+ last_css_y,+ start_rotation,+ total_delta_deg,+ start_pan_x,+ start_pan_y,+ center_x,+ center_y,+ } => {+ let diff = compute_smooth_rotation_delta(+ *last_css_x,+ *last_css_y,+ local_css_x,+ local_css_y,+ *center_x,+ *center_y,+ );+ *last_css_x = local_css_x;+ *last_css_y = local_css_y;+ *total_delta_deg += diff;++ let mut next_rot = *start_rotation + *total_delta_deg;+ if snap_15_deg {+ next_rot = (next_rot / 15.0).round() * 15.0;+ }+ let d_rad = (next_rot - *start_rotation).to_radians();+ let (sin, cos) = d_rad.sin_cos();+ let rx = *start_pan_x - *center_x;+ let ry = *start_pan_y - *center_y;+ cam.rotation = next_rot;+ cam.pan_x = *center_x + rx * cos - ry * sin;+ cam.pan_y = *center_y + rx * sin + ry * cos;+ true+ }+ ActiveGestureState::ZoomDrag {+ start_css_x,+ anchor_x,+ anchor_y,+ start_zoom,+ start_pan_x,+ start_pan_y,+ } => {+ let dx = local_css_x - *start_css_x;+ let next_zoom = clamp_zoom(*start_zoom * (dx * 0.007).exp());+ let ratio = next_zoom / (*start_zoom).max(MIN_ZOOM);+ cam.zoom = next_zoom;+ cam.pan_x = *anchor_x - (*anchor_x - *start_pan_x) * ratio;+ cam.pan_y = *anchor_y - (*anchor_y - *start_pan_y) * ratio;+ true+ }+ }+ }++ pub fn end(&mut self) -> bool {+ self.active.take().is_some()+ }++ /// Applies mouse-wheel zoom anchored at `(anchor_css_x, anchor_css_y)`.+ /// Matches `useCanvasNavigation.ts` (`Math.exp(-delta * 0.0018)`).+ pub fn apply_wheel_zoom(+ anchor_css_x: f32,+ anchor_css_y: f32,+ delta_y: f32,+ cam: &mut CameraState,+ ) -> bool {+ let current_zoom = clamp_zoom(cam.zoom);+ let factor = (-delta_y * 0.0018).exp();+ let next_zoom = clamp_zoom(current_zoom * factor);+ if (next_zoom - current_zoom).abs() <= 1e-5 {+ return false;+ }+ let ratio = next_zoom / current_zoom;+ cam.pan_x = anchor_css_x - (anchor_css_x - cam.pan_x) * ratio;+ cam.pan_y = anchor_css_y - (anchor_css_y - cam.pan_y) * ratio;+ cam.zoom = next_zoom;+ true+ }++ /// Applies mouse-wheel scroll panning (used when wheel mode is `scroll` or Webtoon mode).+ pub fn apply_wheel_scroll(+ delta_x: f32,+ delta_y: f32,+ shift_held: bool,+ is_webtoon_mode: bool,+ cam: &mut CameraState,+ ) -> bool {+ let scroll_x = if shift_held { delta_y } else { delta_x };+ let scroll_y = if shift_held { 0.0 } else { delta_y };+ if scroll_x.abs() < 1e-5 && scroll_y.abs() < 1e-5 {+ return false;+ }+ if !is_webtoon_mode {+ cam.pan_x -= scroll_x;+ }+ cam.pan_y -= scroll_y;+ true+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_camera_roundtrip_matches_format_artboard_transform_all_combinations() {+ let doc_w = 2400.0;+ let doc_h = 1600.0;+ let cases = [+ CameraState {+ pan_x: 640.0,+ pan_y: 420.0,+ zoom: 1.0,+ rotation: 0.0,+ flip_x: false,+ flip_y: false,+ },+ CameraState {+ pan_x: 512.5,+ pan_y: 384.25,+ zoom: 2.75,+ rotation: 37.5,+ flip_x: true,+ flip_y: false,+ },+ CameraState {+ pan_x: -120.0,+ pan_y: 890.0,+ zoom: 0.15,+ rotation: -142.25,+ flip_x: false,+ flip_y: true,+ },+ CameraState {+ pan_x: 1024.0,+ pan_y: 768.0,+ zoom: 16.0,+ rotation: 180.0,+ flip_x: true,+ flip_y: true,+ },+ ];++ let points = [+ (0.0, 0.0),+ (doc_w, doc_h),+ (doc_w * 0.5, doc_h * 0.5),+ (317.25, 1189.75),+ ];++ for cam in &cases {+ for &(dx, dy) in &points {+ let (vx, vy) = doc_to_viewport_css(dx, dy, doc_w, doc_h, cam);+ let (rx, ry) = viewport_css_to_doc(vx, vy, doc_w, doc_h, cam);+ assert!(+ (rx - dx).abs() < 1e-3 && (ry - dy).abs() < 1e-3,+ "roundtrip mismatch for cam={cam:?} pt=({dx},{dy}) -> ({vx},{vy}) -> ({rx},{ry})"+ );+ }+ }+ }++ #[test]+ fn test_document_center_maps_to_pan() {+ let cam = CameraState {+ pan_x: 412.5,+ pan_y: 298.75,+ zoom: 3.5,+ rotation: 63.0,+ flip_x: true,+ flip_y: true,+ };+ let (vx, vy) = doc_to_viewport_css(1000.0, 500.0, 2000.0, 1000.0, &cam);+ assert!((vx - 412.5).abs() < 1e-4);+ assert!((vy - 298.75).abs() < 1e-4);+ }++ #[test]+ fn test_wheel_zoom_preserves_anchor_point_in_document_space() {+ let mut cam = CameraState {+ pan_x: 500.0,+ pan_y: 350.0,+ zoom: 1.25,+ rotation: 22.0,+ flip_x: true,+ flip_y: false,+ };+ let anchor_x = 610.0;+ let anchor_y = 240.0;+ let before = viewport_css_to_doc(anchor_x, anchor_y, 1920.0, 1080.0, &cam);+ assert!(NativeCameraNavigator::apply_wheel_zoom(+ anchor_x, anchor_y, -120.0, &mut cam+ ));+ let after = viewport_css_to_doc(anchor_x, anchor_y, 1920.0, 1080.0, &cam);+ assert!((before.0 - after.0).abs() < 1e-3);+ assert!((before.1 - after.1).abs() < 1e-3);+ }++ #[test]+ fn test_smooth_rotation_delta_damps_near_center() {+ let far = compute_smooth_rotation_delta(200.0, 0.0, 0.0, 200.0, 0.0, 0.0);+ assert!((far - 90.0).abs() < 1e-3);+ let near = compute_smooth_rotation_delta(16.0, 0.0, 0.0, 16.0, 0.0, 0.0);+ assert!(near > 0.0 && near < far * 0.3);+ }+}diff --git a/crates/ink-engine/src/clock.rs b/crates/ink-engine/src/clock.rsnew file mode 100644index 0000000..110d475--- /dev/null+++ b/crates/ink-engine/src/clock.rs@@ -0,0 +1,35 @@+//! Monotonic high-resolution QPC clock in milliseconds, sharing the exact same+//! timebase as `src-tauri/src/tablet_input.rs` for accurate input-to-present telemetry.++#[cfg(target_os = "windows")]+pub fn now_ms() -> f64 {+ use std::sync::LazyLock;+ use windows_sys::Win32::System::Performance::{+ QueryPerformanceCounter, QueryPerformanceFrequency,+ };++ static FREQ_PER_MS: LazyLock<f64> = LazyLock::new(|| unsafe {+ let mut f = 0i64;+ QueryPerformanceFrequency(&mut f);+ if f > 0 {+ f as f64 / 1000.0+ } else {+ 1.0+ }+ });++ unsafe {+ let mut now = 0i64;+ QueryPerformanceCounter(&mut now);+ (now as f64) / *FREQ_PER_MS+ }+}++#[cfg(not(target_os = "windows"))]+pub fn now_ms() -> f64 {+ use std::sync::LazyLock;+ use std::time::Instant;++ static EPOCH: LazyLock<Instant> = LazyLock::new(Instant::now);+ EPOCH.elapsed().as_secs_f64() * 1000.0+}diff --git a/crates/ink-engine/src/document/doc.rs b/crates/ink-engine/src/document/doc.rsnew file mode 100644index 0000000..3fd1e84--- /dev/null+++ b/crates/ink-engine/src/document/doc.rs@@ -0,0 +1,1666 @@+//! Single InkStudio Document owning its layer tree, sparse raster/mask tile grids,+//! and Copy-on-Write Undo/Redo stack.++use super::types::{+ BlendMode, CanvasColorMode, CanvasDimensions, DocumentId, DocumentMetaSnapshot,+ ExpressionColor, LayerId, LayerNodeMeta, LayerPropsPatch, LayerType,+};+use crate::history::{+ format_time_hms, next_history_id, unix_now_ms, AppliedHistoryChange, CanvasResizeDelta,+ HistoryEntry, HistoryItemMeta, HistoryStack, LayerTreeMutation, SelectiveUndoOutcome,+};+use crate::io::compositor_cpu;+use crate::io::png_codec;+use crate::memory::ScratchBackend;+use crate::tiles::{+ parse_hex_rgba8, CowTileDelta, RectI32, SparseLayerGrid, TileCoord, TileData, TileFormat,+ TileKind,+};+use std::collections::{HashMap, HashSet};+use std::sync::Arc;++/// A single layer node in the document tree combining metadata + sparse raster/mask tiles.+#[derive(Debug, Clone)]+pub struct LayerNode {+ pub meta: LayerNodeMeta,+ pub grid: SparseLayerGrid,+}++impl LayerNode {+ pub fn new(meta: LayerNodeMeta, format: TileFormat) -> Self {+ let mut grid = SparseLayerGrid::new(format);+ grid.has_mask = meta.has_mask;+ Self { meta, grid }+ }++ /// O(1) Copy-on-Write clone (duplicates metadata + shares `Arc<TileData>` tile refs).+ pub fn clone_cow(&self, new_id: impl Into<String>, new_name: impl Into<String>) -> Self {+ let mut meta = self.meta.clone();+ meta.id = new_id.into();+ meta.name = new_name.into();+ Self {+ meta,+ grid: self.grid.clone_cow(),+ }+ }+}++/// Complete in-memory document state inside `ink-engine`.+#[derive(Debug)]+pub struct Document {+ pub id: DocumentId,+ pub name: String,+ pub dimensions: CanvasDimensions,+ pub color_mode: CanvasColorMode,+ pub default_tone_frequency: f32,+ /// Top-to-bottom ordered layer stack matching React `layers: LayerItem[]`.+ pub layers: Vec<LayerNode>,+ pub active_layer_id: Option<LayerId>,+ pub history: HistoryStack,+ pub perspective_ruler: Option<serde_json::Value>,+ pub straight_ruler: Option<serde_json::Value>,+ pub animation_timeline: Option<serde_json::Value>,+ pub timelapse: Option<serde_json::Value>,+ pub work_time_ms: u64,+ pub preview_data_url: Option<String>,+ pub dirty_for_render: bool,+ pub last_accessed_ms: u64,+}++impl Document {+ /// Creates a brand new blank document with `Layer 1` (empty, 0 tiles!) and `Background`+ /// (zero-allocation `SolidColor` tiles when non-transparent).+ pub fn new_blank(+ id: impl Into<String>,+ name: impl Into<String>,+ dimensions: CanvasDimensions,+ color_mode: CanvasColorMode,+ background_hex: &str,+ default_tone_frequency: f32,+ max_history_steps: usize,+ ) -> Self {+ let doc_id_str = id.into();+ let now = unix_now_ms();+ let bg_id = format!("layer-bg-{doc_id_str}");+ let top_id = format!("layer-1-{doc_id_str}");++ let top_expr = match color_mode {+ CanvasColorMode::Monochrome => ExpressionColor::Monochrome,+ CanvasColorMode::Grayscale => ExpressionColor::Gray,+ CanvasColorMode::Color => ExpressionColor::Color,+ };+ let top_fmt = match color_mode {+ CanvasColorMode::Monochrome => TileFormat::Monochrome1Bit,+ _ => TileFormat::Color32Bit,+ };++ let mut top_meta = LayerNodeMeta::new_raster(&top_id, "Layer 1");+ top_meta.tone_frequency = Some(default_tone_frequency.clamp(20.0, 85.0));+ top_meta.expression_color = Some(top_expr);+ let top_node = LayerNode::new(top_meta, top_fmt);++ let mut bg_meta = LayerNodeMeta::new_raster(&bg_id, "Background");+ bg_meta.locked = true;+ bg_meta.expression_color = None;+ bg_meta.mono_threshold = None;+ bg_meta.mono_express_black = None;+ bg_meta.mono_express_white = None;+ let mut bg_node = LayerNode::new(bg_meta, TileFormat::Color32Bit);++ if let Some(bg_rgba) = parse_hex_rgba8(background_hex) {+ if bg_rgba[3] > 0 {+ bg_node+ .grid+ .fill_solid_layer(dimensions.width, dimensions.height, bg_rgba);+ }+ } else {+ bg_node+ .grid+ .fill_solid_layer(dimensions.width, dimensions.height, [255, 255, 255, 255]);+ }++ let mut doc = Self {+ id: doc_id_str,+ name: name.into(),+ dimensions,+ color_mode,+ default_tone_frequency: default_tone_frequency.clamp(20.0, 85.0),+ layers: vec![top_node, bg_node],+ active_layer_id: Some(top_id.clone()),+ history: HistoryStack::new(max_history_steps),+ perspective_ruler: None,+ straight_ruler: None,+ animation_timeline: None,+ timelapse: None,+ work_time_ms: 0,+ preview_data_url: None,+ dirty_for_render: true,+ last_accessed_ms: now,+ };++ // Generate tiny 64×64 PNG thumbnail for the background layer immediately+ if let Ok(bg_thumb) = doc.generate_layer_thumbnail_data_url(&bg_id, 64, 64, None) {+ if let Some(bg) = doc.layer_mut(&bg_id) {+ bg.meta.thumbnail_url = Some(bg_thumb);+ }+ }+ doc.history+ .reset_with_initial("New Document", Some(top_id), String::new());+ doc+ }++ /// Creates a document hydrated from already-assembled layers (e.g. `.ink`, `.clip`, `.psd`).+ #[allow(clippy::too_many_arguments)]+ pub fn from_layers(+ id: impl Into<String>,+ name: impl Into<String>,+ dimensions: CanvasDimensions,+ color_mode: CanvasColorMode,+ layers: Vec<LayerNode>,+ active_layer_id: Option<LayerId>,+ max_history_steps: usize,+ ) -> Self {+ let now = unix_now_ms();+ let resolved_active = active_layer_id.or_else(|| {+ layers+ .iter()+ .find(|l| l.meta.layer_type == LayerType::Raster)+ .or_else(|| layers.first())+ .map(|l| l.meta.id.clone())+ });+ let mut history = HistoryStack::new(max_history_steps);+ history.reset_with_initial("Open Document", resolved_active.clone(), String::new());+ Self {+ id: id.into(),+ name: name.into(),+ dimensions,+ color_mode,+ default_tone_frequency: 60.0,+ layers,+ active_layer_id: resolved_active,+ history,+ perspective_ruler: None,+ straight_ruler: None,+ animation_timeline: None,+ timelapse: None,+ work_time_ms: 0,+ preview_data_url: None,+ dirty_for_render: true,+ last_accessed_ms: now,+ }+ }++ #[inline]+ pub fn touch(&mut self) {+ self.last_accessed_ms = unix_now_ms();+ }++ pub fn layer(&self, layer_id: &str) -> Option<&LayerNode> {+ self.layers.iter().find(|l| l.meta.id == layer_id)+ }++ pub fn layer_mut(&mut self, layer_id: &str) -> Option<&mut LayerNode> {+ self.layers.iter_mut().find(|l| l.meta.id == layer_id)+ }++ pub fn layer_index(&self, layer_id: &str) -> Option<usize> {+ self.layers.iter().position(|l| l.meta.id == layer_id)+ }++ pub fn active_layer(&self) -> Option<&LayerNode> {+ let id = self.active_layer_id.as_deref()?;+ self.layer(id)+ }++ pub fn is_background_layer_id(layer_id: &str) -> bool {+ layer_id == "layer-bg" || layer_id.starts_with("layer-bg-")+ }++ /// Computes effective visibility walking up the folder parent chain.+ pub fn is_layer_effectively_visible(&self, layer_id: &str) -> bool {+ let mut cur_id = Some(layer_id);+ let mut depth = 0usize;+ while let Some(id) = cur_id {+ if depth > 64 {+ break;+ }+ depth += 1;+ let Some(node) = self.layer(id) else {+ break;+ };+ if !node.meta.visible {+ return false;+ }+ cur_id = node.meta.parent_id.as_deref();+ }+ true+ }++ /// Computes effective opacity walking up the folder parent chain.+ pub fn effective_opacity(&self, layer_id: &str) -> f32 {+ let mut alpha = 1.0f32;+ let mut cur_id = Some(layer_id);+ let mut depth = 0usize;+ while let Some(id) = cur_id {+ if depth > 64 {+ break;+ }+ depth += 1;+ let Some(node) = self.layer(id) else {+ break;+ };+ alpha *= node.meta.opacity.clamp(0.0, 1.0);+ cur_id = node.meta.parent_id.as_deref();+ }+ alpha+ }++ /// Builds a compact metadata snapshot for React (ZERO full-res pixel buffers!).+ pub fn snapshot_meta(&self) -> DocumentMetaSnapshot {+ DocumentMetaSnapshot {+ id: self.id.clone(),+ name: self.name.clone(),+ dimensions: self.dimensions,+ color_mode: self.color_mode,+ layers: self.layers.iter().map(|l| l.meta.clone()).collect(),+ active_layer_id: self.active_layer_id.clone(),+ history: self.history.snapshot(),+ preview_data_url: self.preview_data_url.clone(),+ perspective_ruler: self.perspective_ruler.clone(),+ straight_ruler: self.straight_ruler.clone(),+ animation_timeline: self.animation_timeline.clone(),+ timelapse: self.timelapse.clone(),+ work_time_ms: self.work_time_ms,+ }+ }++ #[allow(clippy::too_many_arguments)]+ fn record_tree_history(+ &mut self,+ action_type: &str,+ label: impl Into<String>,+ target_layer_id: Option<LayerId>,+ before_layers: Vec<LayerNodeMeta>,+ before_active: Option<LayerId>,+ before_grids: Vec<(LayerId, SparseLayerGrid)>,+ after_grids: Vec<(LayerId, SparseLayerGrid)>,+ tile_deltas: Vec<CowTileDelta>,+ coalesce_key: Option<String>,+ ) {+ let now = unix_now_ms();+ let after_layers: Vec<LayerNodeMeta> = self.layers.iter().map(|l| l.meta.clone()).collect();+ let after_active = self.active_layer_id.clone();+ self.history.push(HistoryEntry {+ meta: HistoryItemMeta {+ id: next_history_id("hist", now),+ action_type: action_type.to_string(),+ label: label.into(),+ timestamp: now,+ time_formatted: format_time_hms(now),+ thumbnail_url: target_layer_id+ .as_deref()+ .and_then(|id| self.layer(id))+ .and_then(|l| l.meta.thumbnail_url.clone())+ .unwrap_or_default(),+ layer_id: target_layer_id,+ undone: false,+ },+ tile_deltas,+ layer_tree_delta: Some(LayerTreeMutation {+ before_layers,+ after_layers,+ before_active_layer_id: before_active,+ after_active_layer_id: after_active,+ before_grids,+ after_grids,+ coalesce_key,+ }),+ canvas_resize_delta: None,+ document_state_delta: None,+ peer_id: None,+ stroke_id: None,+ is_mask_edit: false,+ });+ }++ /// Adds a new layer (raster, folder, frame-folder, vector, text, balloon, adjustment)+ /// and records an atomic CoW undo step.+ pub fn add_layer(+ &mut self,+ layer_meta: LayerNodeMeta,+ insert_index: Option<usize>,+ select_new: bool,+ record_history: bool,+ ) -> LayerNodeMeta {+ let before_layers: Vec<LayerNodeMeta> =+ self.layers.iter().map(|l| l.meta.clone()).collect();+ let before_active = self.active_layer_id.clone();++ let fmt = match layer_meta.expression_color {+ Some(ExpressionColor::Monochrome) => TileFormat::Monochrome1Bit,+ Some(ExpressionColor::Gray) => TileFormat::Grayscale8Bit,+ _ => TileFormat::Color32Bit,+ };+ let id = layer_meta.id.clone();+ let node = LayerNode::new(layer_meta.clone(), fmt);++ let idx = insert_index+ .unwrap_or_else(|| {+ self.active_layer_id+ .as_deref()+ .and_then(|aid| self.layer_index(aid))+ .unwrap_or(0)+ })+ .min(self.layers.len());++ if let Some(existing_idx) = self.layer_index(&id) {+ self.layers[existing_idx].meta = layer_meta.clone();+ } else {+ self.layers.insert(idx, node);+ }++ if select_new {+ self.active_layer_id = Some(id.clone());+ }+ self.dirty_for_render = true;++ if record_history {+ self.record_tree_history(+ "layer",+ format!("Add {}", layer_meta.name),+ Some(id),+ before_layers,+ before_active,+ Vec::new(),+ Vec::new(),+ Vec::new(),+ None,+ );+ }+ layer_meta+ }++ /// Deletes a layer (and any descendant layers if it is a folder), retaining O(1) CoW grid+ /// snapshots in history so Undo restores every pixel instantaneously.+ pub fn delete_layer(&mut self, layer_id: &str, record_history: bool) -> Result<Vec<LayerId>, String> {+ let Some(_) = self.layer_index(layer_id) else {+ return Err(format!("Layer not found: {layer_id}"));+ };+ let before_layers: Vec<LayerNodeMeta> =+ self.layers.iter().map(|l| l.meta.clone()).collect();+ let before_active = self.active_layer_id.clone();++ let to_remove = self.collect_subtree_ids(layer_id);+ let remove_set: HashSet<&str> = to_remove.iter().map(|s| s.as_str()).collect();+ let mut removed_grids = Vec::new();+ for l in &self.layers {+ if remove_set.contains(l.meta.id.as_str()) {+ removed_grids.push((l.meta.id.clone(), l.grid.clone_cow()));+ }+ }+ let target_name = self+ .layer(layer_id)+ .map(|l| l.meta.name.clone())+ .unwrap_or_else(|| "Layer".to_string());++ self.layers.retain(|l| !remove_set.contains(l.meta.id.as_str()));++ if self+ .active_layer_id+ .as_deref()+ .map(|aid| remove_set.contains(aid))+ .unwrap_or(true)+ {+ self.active_layer_id = self+ .layers+ .iter()+ .find(|l| l.meta.layer_type == LayerType::Raster)+ .or_else(|| self.layers.first())+ .map(|l| l.meta.id.clone());+ }+ self.dirty_for_render = true;++ if record_history {+ self.record_tree_history(+ "layer",+ format!("Delete {target_name}"),+ self.active_layer_id.clone(),+ before_layers,+ before_active,+ removed_grids,+ Vec::new(),+ Vec::new(),+ None,+ );+ }+ Ok(to_remove)+ }++ /// O(1) Copy-on-Write layer duplication (untouched tiles share `Arc<TileData>`!).+ pub fn duplicate_layer(+ &mut self,+ src_layer_id: &str,+ new_layer_id: impl Into<String>,+ record_history: bool,+ ) -> Result<LayerNodeMeta, String> {+ let Some(idx) = self.layer_index(src_layer_id) else {+ return Err(format!("Source layer not found: {src_layer_id}"));+ };+ let before_layers: Vec<LayerNodeMeta> =+ self.layers.iter().map(|l| l.meta.clone()).collect();+ let before_active = self.active_layer_id.clone();++ let new_id = new_layer_id.into();+ let new_name = format!("{} Copy", self.layers[idx].meta.name);+ let cloned = self.layers[idx].clone_cow(new_id.clone(), new_name);+ let after_grid = (new_id.clone(), cloned.grid.clone_cow());+ let cloned_meta = cloned.meta.clone();++ self.layers.insert(idx, cloned);+ self.active_layer_id = Some(new_id.clone());+ self.dirty_for_render = true;++ if record_history {+ self.record_tree_history(+ "layer",+ format!("Duplicate {}", cloned_meta.name),+ Some(new_id),+ before_layers,+ before_active,+ Vec::new(),+ vec![after_grid],+ Vec::new(),+ None,+ );+ }+ Ok(cloned_meta)+ }++ /// Applies a partial property update (opacity, visibility, blend mode, clipping, screentone,+ /// layer color, expression color, mask flags, etc.) with optional slider `coalesce_key`.+ pub fn update_layer_props(+ &mut self,+ layer_id: &str,+ patch: LayerPropsPatch,+ scratch: Option<&dyn ScratchBackend>,+ ) -> Result<LayerNodeMeta, String> {+ let before_layers: Vec<LayerNodeMeta> =+ self.layers.iter().map(|l| l.meta.clone()).collect();+ let before_active = self.active_layer_id.clone();++ let Some(node) = self.layer_mut(layer_id) else {+ return Err(format!("Layer not found: {layer_id}"));+ };++ let mut tile_deltas = Vec::new();+ let mut visual_changed = false;++ if let Some(name) = patch.name {+ node.meta.name = name;+ }+ if let Some(v) = patch.visible {+ node.meta.visible = v;+ visual_changed = true;+ }+ if let Some(op) = patch.opacity {+ node.meta.opacity = op.clamp(0.0, 1.0);+ visual_changed = true;+ }+ if let Some(bm) = patch.blend_mode {+ node.meta.blend_mode = bm;+ visual_changed = true;+ }+ if let Some(l) = patch.locked {+ node.meta.locked = l;+ }+ if let Some(al) = patch.alpha_locked {+ node.meta.alpha_locked = Some(al);+ }+ if let Some(cl) = patch.clipped {+ node.meta.clipped = Some(cl);+ visual_changed = true;+ }+ if let Some(col) = patch.collapsed {+ node.meta.collapsed = Some(col);+ }+ if let Some(pid) = patch.parent_id {+ node.meta.parent_id = pid;+ visual_changed = true;+ }+ if let Some(r) = patch.is_reference {+ node.meta.is_reference = Some(r);+ }+ if let Some(lbl) = patch.color_label {+ node.meta.color_label = Some(lbl);+ }+ if let Some(v) = patch.is_tone_layer {+ node.meta.is_tone_layer = Some(v);+ visual_changed = true;+ }+ if let Some(v) = patch.tone_enabled {+ node.meta.tone_enabled = Some(v);+ visual_changed = true;+ }+ if let Some(v) = patch.tone_frequency {+ node.meta.tone_frequency = Some(v);+ visual_changed = true;+ }+ if let Some(v) = patch.tone_angle {+ node.meta.tone_angle = Some(v);+ visual_changed = true;+ }+ if let Some(v) = patch.tone_dot_shape {+ node.meta.tone_dot_shape = Some(v);+ visual_changed = true;+ }+ if let Some(v) = patch.tone_density {+ node.meta.tone_density = Some(v);+ visual_changed = true;+ }+ if let Some(v) = patch.tone_density_type {+ node.meta.tone_density_type = Some(v);+ visual_changed = true;+ }+ if let Some(v) = patch.layer_color_enabled {+ node.meta.layer_color_enabled = Some(v);+ visual_changed = true;+ }+ if let Some(v) = patch.layer_color {+ node.meta.layer_color = Some(v);+ visual_changed = true;+ }+ if let Some(v) = patch.layer_sub_color {+ node.meta.layer_sub_color = Some(v);+ visual_changed = true;+ }+ if let Some(v) = patch.mono_threshold {+ node.meta.mono_threshold = Some(v);+ visual_changed = true;+ }+ if let Some(v) = patch.mono_express_black {+ node.meta.mono_express_black = Some(v);+ visual_changed = true;+ }+ if let Some(v) = patch.mono_express_white {+ node.meta.mono_express_white = Some(v);+ visual_changed = true;+ }+ if let Some(v) = patch.mask_enabled {+ node.meta.mask_enabled = Some(v);+ visual_changed = true;+ }+ if let Some(v) = patch.mask_linked {+ node.meta.mask_linked = Some(v);+ }+ if let Some(v) = patch.adjustment_data {+ node.meta.adjustment_data = Some(v);+ visual_changed = true;+ }+ if let Some(v) = patch.styles {+ node.meta.styles = Some(v);+ visual_changed = true;+ }+ if let Some(v) = patch.comic_frames {+ node.meta.comic_frames = Some(v);+ visual_changed = true;+ }+ if let Some(v) = patch.text_data {+ node.meta.text_data = Some(v);+ visual_changed = true;+ }+ if let Some(v) = patch.balloon_data {+ node.meta.balloon_data = Some(v);+ visual_changed = true;+ }+ if let Some(v) = patch.vector_strokes {+ node.meta.vector_strokes = Some(v);+ visual_changed = true;+ }+ if let Some(expr) = patch.expression_color {+ node.meta.expression_color = Some(expr);+ let target_fmt = expr.to_tile_format();+ if node.grid.format != target_fmt && node.meta.layer_type.has_tiles() {+ let before_snap = node.grid.snapshot_all_cow(TileKind::Raster);+ let threshold = node.meta.mono_threshold.unwrap_or(128);+ node.grid+ .convert_format(target_fmt, threshold, true, scratch)?;+ tile_deltas =+ node.grid+ .diff_from_full_snapshot(layer_id, TileKind::Raster, &before_snap);+ }+ visual_changed = true;+ }++ let updated_meta = node.meta.clone();+ if visual_changed {+ self.dirty_for_render = true;+ }++ if patch.record_history.unwrap_or(true) {+ let label = patch+ .history_label+ .unwrap_or_else(|| format!("Update {}", updated_meta.name));+ self.record_tree_history(+ "layer",+ label,+ Some(layer_id.to_string()),+ before_layers,+ before_active,+ Vec::new(),+ Vec::new(),+ tile_deltas,+ patch.coalesce_key,+ );+ }++ Ok(updated_meta)+ }++ /// Reorders layers (and optionally updates `parent_id`s) to match `ordered_ids`.+ pub fn reorder_layers(+ &mut self,+ ordered_ids: &[LayerId],+ parent_overrides: Option<&HashMap<LayerId, Option<LayerId>>>,+ record_history: bool,+ ) -> Result<(), String> {+ let before_layers: Vec<LayerNodeMeta> =+ self.layers.iter().map(|l| l.meta.clone()).collect();+ let before_active = self.active_layer_id.clone();++ let mut by_id: HashMap<LayerId, LayerNode> = self+ .layers+ .drain(..)+ .map(|l| (l.meta.id.clone(), l))+ .collect();++ let mut reordered = Vec::with_capacity(by_id.len());+ for id in ordered_ids {+ if let Some(mut node) = by_id.remove(id) {+ if let Some(overrides) = parent_overrides {+ if let Some(new_parent) = overrides.get(id) {+ node.meta.parent_id = new_parent.clone();+ }+ }+ reordered.push(node);+ }+ }+ // Preserve any remaining layers not mentioned in ordered_ids safely at the end+ for (_, node) in by_id {+ reordered.push(node);+ }+ self.layers = reordered;+ self.dirty_for_render = true;++ if record_history {+ self.record_tree_history(+ "layer",+ "Reorder Layers",+ self.active_layer_id.clone(),+ before_layers,+ before_active,+ Vec::new(),+ Vec::new(),+ Vec::new(),+ None,+ );+ }+ Ok(())+ }++ /// Synchronizes full layer metadata list from React (preserving existing Rust `SparseLayerGrid`+ /// tile stores for every matching layer ID!). Used when complex React tree ops (grouping,+ /// collab sync, special layer updates) mutate layer structure.+ pub fn sync_layers_metadata(+ &mut self,+ incoming_layers: Vec<LayerNodeMeta>,+ active_layer_id: Option<LayerId>,+ ) {+ let mut existing_grids: HashMap<LayerId, SparseLayerGrid> = self+ .layers+ .drain(..)+ .map(|l| (l.meta.id, l.grid))+ .collect();++ self.layers = incoming_layers+ .into_iter()+ .map(|meta| {+ let fmt = match meta.expression_color {+ Some(ExpressionColor::Monochrome) => TileFormat::Monochrome1Bit,+ Some(ExpressionColor::Gray) => TileFormat::Grayscale8Bit,+ _ => TileFormat::Color32Bit,+ };+ let mut grid = existing_grids+ .remove(&meta.id)+ .unwrap_or_else(|| SparseLayerGrid::new(fmt));+ if meta.has_mask && !grid.has_mask {+ grid.init_mask(255);+ }+ LayerNode { meta, grid }+ })+ .collect();++ if let Some(aid) = active_layer_id {+ self.active_layer_id = Some(aid);+ }+ self.dirty_for_render = true;+ }++ /// Clears a raster layer (or fills solid white for background layers) with atomic CoW undo.+ pub fn clear_layer(&mut self, layer_id: &str, record_history: bool) -> Result<(), String> {+ let is_bg = Self::is_background_layer_id(layer_id);+ let dims = self.dimensions;+ let Some(node) = self.layer_mut(layer_id) else {+ return Err(format!("Layer not found: {layer_id}"));+ };+ let before_snap = node.grid.snapshot_all_cow(TileKind::Raster);+ if is_bg {+ node.grid+ .fill_solid_layer(dims.width, dims.height, [255, 255, 255, 255]);+ } else {+ node.grid.clear_raster();+ }+ let deltas = node+ .grid+ .diff_from_full_snapshot(layer_id, TileKind::Raster, &before_snap);+ self.dirty_for_render = true;++ if record_history && !deltas.is_empty() {+ let now = unix_now_ms();+ self.history.push(HistoryEntry {+ meta: HistoryItemMeta {+ id: next_history_id("hist", now),+ action_type: "clear".to_string(),+ label: "Clear Layer".to_string(),+ timestamp: now,+ time_formatted: format_time_hms(now),+ thumbnail_url: String::new(),+ layer_id: Some(layer_id.to_string()),+ undone: false,+ },+ tile_deltas: deltas,+ layer_tree_delta: None,+ canvas_resize_delta: None,+ document_state_delta: None,+ peer_id: None,+ stroke_id: None,+ is_mask_edit: false,+ });+ }+ Ok(())+ }++ /// Attaches a non-destructive 8-bit layer mask (zero tiles allocated for default reveal-all!).+ pub fn add_layer_mask(+ &mut self,+ layer_id: &str,+ default_value: u8,+ record_history: bool,+ ) -> Result<LayerNodeMeta, String> {+ let before_layers: Vec<LayerNodeMeta> =+ self.layers.iter().map(|l| l.meta.clone()).collect();+ let before_active = self.active_layer_id.clone();++ let Some(node) = self.layer_mut(layer_id) else {+ return Err(format!("Layer not found: {layer_id}"));+ };+ node.grid.init_mask(default_value);+ node.meta.has_mask = true;+ node.meta.mask_enabled = Some(true);+ node.meta.mask_linked = Some(true);+ node.meta.mask_version = Some(node.grid.layer_version);+ let updated = node.meta.clone();+ self.dirty_for_render = true;++ if record_history {+ self.record_tree_history(+ "layer",+ "Add Layer Mask",+ Some(layer_id.to_string()),+ before_layers,+ before_active,+ Vec::new(),+ Vec::new(),+ Vec::new(),+ None,+ );+ }+ Ok(updated)+ }++ /// Removes (or permanently applies) a layer's non-destructive 8-bit mask.+ pub fn remove_layer_mask(+ &mut self,+ layer_id: &str,+ apply_to_raster: bool,+ record_history: bool,+ scratch: Option<&dyn ScratchBackend>,+ ) -> Result<LayerNodeMeta, String> {+ let before_layers: Vec<LayerNodeMeta> =+ self.layers.iter().map(|l| l.meta.clone()).collect();+ let before_active = self.active_layer_id.clone();+ let dims = self.dimensions;++ let Some(node) = self.layer_mut(layer_id) else {+ return Err(format!("Layer not found: {layer_id}"));+ };+ let before_grid = (layer_id.to_string(), node.grid.clone_cow());++ if apply_to_raster && node.grid.has_mask {+ let mut rgba = node.grid.read_rgba8_rect(+ RectI32::new(0, 0, dims.width, dims.height),+ false,+ scratch,+ )?;+ let mask = node.grid.read_mask8_rect(+ RectI32::new(0, 0, dims.width, dims.height),+ scratch,+ )?;+ for (px, &m) in rgba.chunks_exact_mut(4).zip(mask.iter()) {+ px[3] = ((u32::from(px[3]) * u32::from(m) + 127) / 255) as u8;+ }+ let thresh = node.meta.mono_threshold.unwrap_or(128);+ node.grid.write_rgba8_rect(+ &rgba,+ RectI32::new(0, 0, dims.width, dims.height),+ thresh,+ scratch,+ )?;+ }++ node.grid.remove_mask();+ node.meta.has_mask = false;+ node.meta.mask_enabled = None;+ node.meta.mask_linked = None;+ node.meta.mask_thumbnail_url = None;+ let after_grid = (layer_id.to_string(), node.grid.clone_cow());+ let updated = node.meta.clone();+ self.dirty_for_render = true;++ if record_history {+ self.record_tree_history(+ "layer",+ if apply_to_raster {+ "Apply Layer Mask"+ } else {+ "Delete Layer Mask"+ },+ Some(layer_id.to_string()),+ before_layers,+ before_active,+ vec![before_grid],+ vec![after_grid],+ Vec::new(),+ None,+ );+ }+ Ok(updated)+ }++ /// Merges `src_layer_id` down onto the nearest raster layer below it in Rust,+ /// recording atomic CoW undo deltas for both removed and destination layers.+ pub fn merge_down(+ &mut self,+ src_layer_id: &str,+ scratch: Option<&dyn ScratchBackend>,+ ) -> Result<(LayerId, LayerId), String> {+ let Some(src_idx) = self.layer_index(src_layer_id) else {+ return Err(format!("Layer not found: {src_layer_id}"));+ };+ if self.layers[src_idx].meta.layer_type != LayerType::Raster+ || self.layers[src_idx].meta.locked+ {+ return Err("Source layer cannot be merged down".to_string());+ }+ let dst_idx = ((src_idx + 1)..self.layers.len())+ .find(|&i| self.layers[i].meta.layer_type == LayerType::Raster)+ .ok_or_else(|| "No raster layer below to merge into".to_string())?;+ if self.layers[dst_idx].meta.locked {+ return Err("Destination layer is locked".to_string());+ }++ let before_layers: Vec<LayerNodeMeta> =+ self.layers.iter().map(|l| l.meta.clone()).collect();+ let before_active = self.active_layer_id.clone();++ let src_id = self.layers[src_idx].meta.id.clone();+ let dst_id = self.layers[dst_idx].meta.id.clone();+ let src_before_grid = (src_id.clone(), self.layers[src_idx].grid.clone_cow());+ let dst_before_snap = self.layers[dst_idx].grid.snapshot_all_cow(TileKind::Raster);++ let w = self.dimensions.width;+ let h = self.dimensions.height;+ let rect = RectI32::new(0, 0, w, h);++ let src_visible = self.layers[src_idx].meta.visible;+ let src_opacity = self.layers[src_idx].meta.opacity.clamp(0.0, 1.0);+ if src_visible && src_opacity > 0.001 && !self.layers[src_idx].grid.tiles.is_empty() {+ let mut src_rgba = self.layers[src_idx].grid.read_rgba8_rect(rect, false, scratch)?;+ if self.layers[src_idx].grid.has_mask+ && self.layers[src_idx].meta.mask_enabled.unwrap_or(true)+ {+ let mask = self.layers[src_idx].grid.read_mask8_rect(rect, scratch)?;+ for (px, &m) in src_rgba.chunks_exact_mut(4).zip(mask.iter()) {+ px[3] = ((u32::from(px[3]) * u32::from(m) + 127) / 255) as u8;+ }+ }+ let mut dst_rgba = self.layers[dst_idx].grid.read_rgba8_rect(rect, false, scratch)?;+ let blend_mode = self.layers[src_idx].meta.blend_mode;+ compositor_cpu::blend_rgba8_over(&mut dst_rgba, &src_rgba, src_opacity, blend_mode);+ let thresh = self.layers[dst_idx].meta.mono_threshold.unwrap_or(128);+ self.layers[dst_idx]+ .grid+ .write_rgba8_rect(&dst_rgba, rect, thresh, scratch)?;+ }++ let dst_deltas = self.layers[dst_idx].grid.diff_from_full_snapshot(+ &dst_id,+ TileKind::Raster,+ &dst_before_snap,+ );++ self.layers.remove(src_idx);+ self.active_layer_id = Some(dst_id.clone());+ self.dirty_for_render = true;++ self.record_tree_history(+ "layer",+ "Merge Down",+ Some(dst_id.clone()),+ before_layers,+ before_active,+ vec![src_before_grid],+ Vec::new(),+ dst_deltas,+ None,+ );+ Ok((dst_id, src_id))+ }++ /// Flattens a folder layer and all of its descendants into a single raster layer in-place+ /// with an atomic CoW undo step.+ pub fn merge_folder(+ &mut self,+ folder_id: &str,+ new_layer_id: impl Into<LayerId>,+ scratch: Option<&dyn ScratchBackend>,+ ) -> Result<LayerNodeMeta, String> {+ let Some(folder_idx) = self.layer_index(folder_id) else {+ return Err(format!("Folder not found: {folder_id}"));+ };+ if self.layers[folder_idx].meta.layer_type != LayerType::Folder {+ return Err(format!("Layer {folder_id} is not a folder"));+ }++ let before_layers: Vec<LayerNodeMeta> =+ self.layers.iter().map(|l| l.meta.clone()).collect();+ let before_active = self.active_layer_id.clone();++ // Collect folder + all recursive descendants+ let mut to_remove = HashSet::new();+ to_remove.insert(folder_id.to_string());+ let mut changed = true;+ while changed {+ changed = false;+ for l in &self.layers {+ if !to_remove.contains(&l.meta.id) {+ if let Some(ref pid) = l.meta.parent_id {+ if to_remove.contains(pid) {+ to_remove.insert(l.meta.id.clone());+ changed = true;+ }+ }+ }+ }+ }++ let folder_meta = self.layers[folder_idx].meta.clone();+ let w = self.dimensions.width;+ let h = self.dimensions.height;+ let rect = RectI32::new(0, 0, w, h);++ // Composite visible descendant raster layers bottom-to-top+ let mut merged_rgba = vec![0u8; (w as usize) * (h as usize) * 4];+ for layer in self.layers.iter().rev() {+ if !to_remove.contains(&layer.meta.id)+ || layer.meta.id == folder_id+ || !layer.meta.layer_type.has_tiles()+ || !layer.meta.visible+ {+ continue;+ }+ let op = layer.meta.opacity.clamp(0.0, 1.0);+ if op <= 0.001 || layer.grid.tiles.is_empty() {+ continue;+ }+ let mut src_rgba = layer.grid.read_rgba8_rect(rect, false, scratch)?;+ if layer.grid.has_mask && layer.meta.mask_enabled.unwrap_or(true) {+ let mask = layer.grid.read_mask8_rect(rect, scratch)?;+ for (px, &m) in src_rgba.chunks_exact_mut(4).zip(mask.iter()) {+ px[3] = ((u32::from(px[3]) * u32::from(m) + 127) / 255) as u8;+ }+ }+ compositor_cpu::blend_rgba8_over(&mut merged_rgba, &src_rgba, op, layer.meta.blend_mode);+ }++ // Preserve folder mask if present+ let mut new_grid = SparseLayerGrid::new(TileFormat::Color32Bit);+ new_grid.write_rgba8_rect(&merged_rgba, rect, 128, scratch)?;+ if self.layers[folder_idx].grid.has_mask {+ new_grid.has_mask = true;+ new_grid.mask_default_value = self.layers[folder_idx].grid.mask_default_value;+ new_grid.mask_tiles = self.layers[folder_idx].grid.mask_tiles.clone();+ }++ let new_id = new_layer_id.into();+ let mut new_meta = LayerNodeMeta::new_raster(new_id.clone(), folder_meta.name.clone());+ new_meta.visible = folder_meta.visible;+ new_meta.opacity = folder_meta.opacity;+ new_meta.blend_mode = folder_meta.blend_mode;+ new_meta.clipped = folder_meta.clipped;+ new_meta.parent_id = folder_meta.parent_id.clone();+ new_meta.has_mask = folder_meta.has_mask;+ new_meta.mask_enabled = folder_meta.mask_enabled;+ new_meta.mask_linked = folder_meta.mask_linked;++ let mut removed_grids = Vec::new();+ for l in &self.layers {+ if to_remove.contains(&l.meta.id) {+ removed_grids.push((l.meta.id.clone(), l.grid.clone_cow()));+ }+ }+ let after_grid = (new_id.clone(), new_grid.clone_cow());+ let new_node = LayerNode {+ meta: new_meta.clone(),+ grid: new_grid,+ };++ // Replace folder position and remove all descendants+ let mut next_layers = Vec::with_capacity(self.layers.len() - to_remove.len() + 1);+ for (i, l) in self.layers.drain(..).enumerate() {+ if i == folder_idx {+ next_layers.push(new_node.clone_cow(new_id.clone(), new_meta.name.clone()));+ }+ if !to_remove.contains(&l.meta.id) {+ next_layers.push(l);+ }+ }+ self.layers = next_layers;+ self.active_layer_id = Some(new_id.clone());+ self.dirty_for_render = true;++ self.record_tree_history(+ "layer",+ format!("Merge Folder {}", folder_meta.name),+ Some(new_id),+ before_layers,+ before_active,+ removed_grids,+ vec![after_grid],+ Vec::new(),+ None,+ );+ Ok(new_meta)+ }++ /// Ingests raw RGBA8 (or 8-bit mask) dirty rectangle bytes directly into a layer's sparse tiles+ /// (for UI-edited layers such as text, speech balloons, 3D bakes, or vector re-renders).+ #[allow(clippy::too_many_arguments)]+ pub fn ingest_dirty_rect(+ &mut self,+ layer_id: &str,+ rect: RectI32,+ bytes: &[u8],+ is_mask: bool,+ record_history: bool,+ action_type: &str,+ label: &str,+ peer_id: Option<String>,+ stroke_id: Option<String>,+ scratch: Option<&dyn ScratchBackend>,+ ) -> Result<Vec<TileCoord>, String> {+ let Some(node) = self.layer_mut(layer_id) else {+ return Err(format!("Layer not found: {layer_id}"));+ };+ let kind = if is_mask {+ TileKind::Mask+ } else {+ TileKind::Raster+ };+ let before_snap = node.grid.snapshot_all_cow(kind);+ let touched = if is_mask {+ // Accept either 1-byte/px alpha or 4-byte/px RGBA8 mask buffers transparently+ let px_count = (rect.width as usize) * (rect.height as usize);+ if bytes.len() == px_count {+ node.grid.write_mask8_rect(bytes, rect, scratch)?+ } else if bytes.len() == px_count * 4 {+ let mut mask8 = vec![0u8; px_count];+ crate::tiles::pack_rgba8_to_mask8(bytes, &mut mask8);+ node.grid.write_mask8_rect(&mask8, rect, scratch)?+ } else {+ return Err(format!(+ "Mask dirty rect length mismatch: expected {px_count} or {}, got {}",+ px_count * 4,+ bytes.len()+ ));+ }+ } else {+ let thresh = node.meta.mono_threshold.unwrap_or(128);+ node.grid.write_rgba8_rect(bytes, rect, thresh, scratch)?+ };++ if is_mask {+ node.meta.has_mask = true;+ node.meta.mask_version = Some(node.grid.layer_version);+ }++ // Bump remote_epoch on tiles mutated by remote collaboration peers+ let is_remote = peer_id+ .as_deref()+ .map(|p| !p.is_empty() && p != "local")+ .unwrap_or(false);+ if is_remote {+ for &c in &touched {+ let ep = node.grid.remote_epochs.entry(c).or_insert(0);+ *ep = ep.saturating_add(1);+ }+ }++ let deltas = node.grid.diff_from_full_snapshot(layer_id, kind, &before_snap);+ self.dirty_for_render = true;++ if record_history && !deltas.is_empty() {+ let now = unix_now_ms();+ self.history.push(HistoryEntry {+ meta: HistoryItemMeta {+ id: next_history_id("hist", now),+ action_type: action_type.to_string(),+ label: label.to_string(),+ timestamp: now,+ time_formatted: format_time_hms(now),+ thumbnail_url: String::new(),+ layer_id: Some(layer_id.to_string()),+ undone: false,+ },+ tile_deltas: deltas,+ layer_tree_delta: None,+ canvas_resize_delta: None,+ document_state_delta: None,+ peer_id,+ stroke_id,+ is_mask_edit: is_mask,+ });+ }+ Ok(touched)+ }++ /// Commits a batch of already-computed CoW tile deltas (e.g. from a live native DX12 brush stroke)+ /// into the history stack and returns the new history entry ID.+ pub fn record_stroke_deltas(+ &mut self,+ layer_id: &str,+ action_type: &str,+ label: &str,+ tile_deltas: Vec<CowTileDelta>,+ peer_id: Option<String>,+ stroke_id: Option<String>,+ ) -> Option<String> {+ if tile_deltas.is_empty() {+ return None;+ }+ let now = unix_now_ms();+ let entry_id = next_history_id("hist", now);+ self.history.push(HistoryEntry {+ meta: HistoryItemMeta {+ id: entry_id.clone(),+ action_type: action_type.to_string(),+ label: label.to_string(),+ timestamp: now,+ time_formatted: format_time_hms(now),+ thumbnail_url: String::new(),+ layer_id: Some(layer_id.to_string()),+ undone: false,+ },+ tile_deltas,+ layer_tree_delta: None,+ canvas_resize_delta: None,+ document_state_delta: None,+ peer_id,+ stroke_id,+ is_mask_edit: false,+ });+ self.dirty_for_render = true;+ Some(entry_id)+ }++ /// Resizes or crops the entire document across all layers with an atomic CoW undo step.+ #[allow(clippy::too_many_arguments)]+ pub fn resize_canvas(+ &mut self,+ new_dims: CanvasDimensions,+ offset_x: i32,+ offset_y: i32,+ scale_content: bool,+ bg_hex: &str,+ record_history: bool,+ scratch: Option<&dyn ScratchBackend>,+ ) -> Result<(), String> {+ if new_dims.width == 0 || new_dims.height == 0 {+ return Err("Invalid target canvas dimensions".to_string());+ }+ let old_dims = self.dimensions;+ let bg_rgba = parse_hex_rgba8(bg_hex);++ let before_grids: Vec<(LayerId, SparseLayerGrid)> = self+ .layers+ .iter()+ .map(|l| (l.meta.id.clone(), l.grid.clone_cow()))+ .collect();++ for node in &mut self.layers {+ if !node.meta.layer_type.has_tiles() && !node.grid.has_mask {+ continue;+ }+ let bg_fill = if Self::is_background_layer_id(&node.meta.id) {+ bg_rgba+ } else {+ None+ };+ node.grid.resize_and_crop(+ old_dims.width,+ old_dims.height,+ new_dims.width,+ new_dims.height,+ offset_x,+ offset_y,+ scale_content,+ bg_fill,+ scratch,+ )?;+ }++ let after_grids: Vec<(LayerId, SparseLayerGrid)> = self+ .layers+ .iter()+ .map(|l| (l.meta.id.clone(), l.grid.clone_cow()))+ .collect();++ self.dimensions = new_dims;+ self.dirty_for_render = true;++ if record_history {+ let now = unix_now_ms();+ let label = if scale_content {+ format!("Resize Canvas ({} × {})", new_dims.width, new_dims.height)+ } else {+ format!("Crop / Resize Canvas ({} × {})", new_dims.width, new_dims.height)+ };+ self.history.push(HistoryEntry {+ meta: HistoryItemMeta {+ id: next_history_id("hist", now),+ action_type: "canvas-resize".to_string(),+ label,+ timestamp: now,+ time_formatted: format_time_hms(now),+ thumbnail_url: String::new(),+ layer_id: self.active_layer_id.clone(),+ undone: false,+ },+ tile_deltas: Vec::new(),+ layer_tree_delta: None,+ canvas_resize_delta: Some(CanvasResizeDelta {+ before_dimensions: old_dims,+ after_dimensions: new_dims,+ before_grids,+ after_grids,+ }),+ document_state_delta: None,+ peer_id: None,+ stroke_id: None,+ is_mask_edit: false,+ });+ }++ Ok(())+ }++ /// Performs linear Undo by 1 step.+ pub fn undo(&mut self) -> AppliedHistoryChange {+ let cur = self.history.index();+ if cur <= 0 {+ return AppliedHistoryChange {+ changed_layer_ids: HashSet::new(),+ dimensions_changed: false,+ layers_changed: false,+ document_state_delta: None,+ };+ }+ self.jump_to_history((cur - 1) as usize)+ }++ /// Performs linear Redo by 1 step.+ pub fn redo(&mut self) -> AppliedHistoryChange {+ let cur = self.history.index();+ if cur < 0 || ((cur + 1) as usize) >= self.history.len() {+ return AppliedHistoryChange {+ changed_layer_ids: HashSet::new(),+ dimensions_changed: false,+ layers_changed: false,+ document_state_delta: None,+ };+ }+ self.jump_to_history((cur + 1) as usize)+ }++ /// Jumps to an arbitrary history index applying CoW tile & layer tree deltas in O(touched tiles).+ pub fn jump_to_history(&mut self, target_index: usize) -> AppliedHistoryChange {+ let steps = self.history.plan_jump(target_index);+ let mut changed_layers = HashSet::new();+ let mut dimensions_changed = false;+ let mut layers_changed = false;+ let mut last_doc_delta = None;++ for (entry_idx, is_undo) in steps {+ let entry = self.history.entries()[entry_idx].clone();+ let sub = self.apply_history_entry(&entry, is_undo, false);+ changed_layers.extend(sub.0.changed_layer_ids);+ dimensions_changed |= sub.0.dimensions_changed;+ layers_changed |= sub.0.layers_changed;+ if sub.0.document_state_delta.is_some() {+ last_doc_delta = sub.0.document_state_delta;+ }+ }++ if !changed_layers.is_empty() || dimensions_changed || layers_changed {+ self.dirty_for_render = true;+ }++ AppliedHistoryChange {+ changed_layer_ids: changed_layers,+ dimensions_changed,+ layers_changed,+ document_state_delta: last_doc_delta,+ }+ }++ /// Collaborative selective undo: marks matching peer/stroke entry as an `undone` tombstone+ /// without splicing out other peers' strokes, skipping contested tiles whose `remote_epoch`+ /// advanced after the stroke was recorded.+ pub fn selective_undo(+ &mut self,+ peer_id: Option<&str>,+ stroke_id: Option<&str>,+ ) -> SelectiveUndoOutcome {+ let Some(idx) = self.history.find_and_mark_selective_undo(peer_id, stroke_id) else {+ return SelectiveUndoOutcome {+ applied: false,+ stroke_id: stroke_id.map(|s| s.to_string()),+ layer_id: None,+ contested_tile_count: 0,+ preserved_peer_edits: false,+ history: self.history.snapshot(),+ };+ };++ let entry = self.history.entries()[idx].clone();+ let (_, contested) = self.apply_history_entry(&entry, true, true);+ self.dirty_for_render = true;++ SelectiveUndoOutcome {+ applied: true,+ stroke_id: entry.stroke_id.clone(),+ layer_id: entry.meta.layer_id.clone(),+ contested_tile_count: contested,+ preserved_peer_edits: contested > 0,+ history: self.history.snapshot(),+ }+ }++ /// Collaborative selective redo: unmarks the most recent undone tombstone for `peer_id`+ /// and reapplies its uncontested tile deltas.+ pub fn selective_redo(&mut self, peer_id: Option<&str>) -> SelectiveUndoOutcome {+ let Some(idx) = self.history.find_and_unmark_selective_redo(peer_id) else {+ return SelectiveUndoOutcome {+ applied: false,+ stroke_id: None,+ layer_id: None,+ contested_tile_count: 0,+ preserved_peer_edits: false,+ history: self.history.snapshot(),+ };+ };++ let entry = self.history.entries()[idx].clone();+ let (_, contested) = self.apply_history_entry(&entry, false, true);+ self.dirty_for_render = true;++ SelectiveUndoOutcome {+ applied: true,+ stroke_id: entry.stroke_id.clone(),+ layer_id: entry.meta.layer_id.clone(),+ contested_tile_count: contested,+ preserved_peer_edits: contested > 0,+ history: self.history.snapshot(),+ }+ }++ fn apply_history_entry(+ &mut self,+ entry: &HistoryEntry,+ is_undo: bool,+ conflict_aware: bool,+ ) -> (AppliedHistoryChange, usize) {+ let mut changed_layer_ids = HashSet::new();+ let mut dimensions_changed = false;+ let mut layers_changed = false;+ let mut contested_tiles = 0usize;++ // 1. Canvas resize / crop restoration+ if let Some(ref cr) = entry.canvas_resize_delta {+ self.dimensions = if is_undo {+ cr.before_dimensions+ } else {+ cr.after_dimensions+ };+ let grids = if is_undo {+ &cr.before_grids+ } else {+ &cr.after_grids+ };+ for (lid, grid_snap) in grids {+ if let Some(node) = self.layer_mut(lid) {+ node.grid = grid_snap.clone_cow();+ node.grid.mark_all_lods_dirty();+ changed_layer_ids.insert(lid.clone());+ }+ }+ dimensions_changed = true;+ }++ // 2. Layer tree mutation restoration (add, delete, reorder, properties, merge, masks)+ if let Some(ref lt) = entry.layer_tree_delta {+ let target_metas = if is_undo {+ <.before_layers+ } else {+ <.after_layers+ };+ let restored_grids_map: HashMap<&str, &SparseLayerGrid> = (if is_undo {+ <.before_grids+ } else {+ <.after_grids+ })+ .iter()+ .map(|(id, g)| (id.as_str(), g))+ .collect();++ let mut existing_grids: HashMap<LayerId, SparseLayerGrid> = self+ .layers+ .drain(..)+ .map(|l| (l.meta.id, l.grid))+ .collect();++ self.layers = target_metas+ .iter()+ .map(|meta| {+ let grid = if let Some(snap) = restored_grids_map.get(meta.id.as_str()) {+ let mut g = snap.clone_cow();+ g.mark_all_lods_dirty();+ g+ } else if let Some(existing) = existing_grids.remove(&meta.id) {+ existing+ } else {+ let fmt = meta+ .expression_color+ .map(|e| e.to_tile_format())+ .unwrap_or(TileFormat::Color32Bit);+ SparseLayerGrid::new(fmt)+ };+ changed_layer_ids.insert(meta.id.clone());+ LayerNode {+ meta: meta.clone(),+ grid,+ }+ })+ .collect();++ self.active_layer_id = if is_undo {+ lt.before_active_layer_id.clone()+ } else {+ lt.after_active_layer_id.clone()+ };+ layers_changed = true;+ }++ // 3. CoW raster & mask tile deltas+ for delta in &entry.tile_deltas {+ if let Some(node) = self.layer_mut(&delta.layer_id) {+ if conflict_aware {+ let live_epoch = node+ .grid+ .remote_epochs+ .get(&delta.coord)+ .copied()+ .unwrap_or(0);+ if live_epoch > delta.remote_epoch {+ contested_tiles += 1;+ continue;+ }+ }+ node.grid.apply_delta(delta, is_undo);+ if delta.kind == TileKind::Mask {+ node.meta.mask_version = Some(node.grid.layer_version);+ }+ changed_layer_ids.insert(delta.layer_id.clone());+ }+ }++ (+ AppliedHistoryChange {+ changed_layer_ids,+ dimensions_changed,+ layers_changed,+ document_state_delta: entry.document_state_delta.clone(),+ },+ contested_tiles,+ )+ }++ fn collect_subtree_ids(&self, root_id: &str) -> Vec<LayerId> {+ let mut out = vec![root_id.to_string()];+ let mut idx = 0;+ while idx < out.len() {+ let parent = out[idx].clone();+ for l in &self.layers {+ if l.meta.parent_id.as_deref() == Some(parent.as_str())+ && !out.contains(&l.meta.id)+ {+ out.push(l.meta.id.clone());+ }+ }+ idx += 1;+ }+ out+ }++ /// Generates a 64×64 (or custom size) RGBA8 PNG thumbnail data URL directly from Rust tiles.+ pub fn generate_layer_thumbnail_data_url(+ &self,+ layer_id: &str,+ max_w: u32,+ max_h: u32,+ scratch: Option<&dyn ScratchBackend>,+ ) -> Result<String, String> {+ let Some(node) = self.layer(layer_id) else {+ return Err(format!("Layer not found: {layer_id}"));+ };+ let (tw, th, rgba) = compositor_cpu::render_layer_thumbnail_rgba(+ node,+ self.dimensions.width,+ self.dimensions.height,+ max_w,+ max_h,+ scratch,+ )?;+ let png = png_codec::encode_rgba8_to_png(tw, th, &rgba)?;+ Ok(png_codec::png_bytes_to_data_url(&png))+ }++ /// Generates a 64×64 PNG thumbnail data URL for a layer's non-destructive 8-bit mask.+ pub fn generate_mask_thumbnail_data_url(+ &self,+ layer_id: &str,+ max_w: u32,+ max_h: u32,+ scratch: Option<&dyn ScratchBackend>,+ ) -> Result<Option<String>, String> {+ let Some(node) = self.layer(layer_id) else {+ return Err(format!("Layer not found: {layer_id}"));+ };+ if !node.grid.has_mask {+ return Ok(None);+ }+ let (tw, th, rgba) = compositor_cpu::render_mask_thumbnail_rgba(+ node,+ self.dimensions.width,+ self.dimensions.height,+ max_w,+ max_h,+ scratch,+ )?;+ let png = png_codec::encode_rgba8_to_png(tw, th, &rgba)?;+ Ok(Some(png_codec::png_bytes_to_data_url(&png)))+ }++ /// Renders a flattened preview PNG of all visible layers (used for `.ink` `preview.png`,+ /// Recent Documents, crash recovery thumbnails, and timelapse frame capture!).+ pub fn render_flattened_png(+ &self,+ max_dim: u32,+ fill_white_bg: bool,+ scratch: Option<&dyn ScratchBackend>,+ ) -> Result<(u32, u32, Vec<u8>), String> {+ let (w, h, rgba) = compositor_cpu::composite_document_downscaled_rgba(+ self,+ max_dim,+ fill_white_bg,+ scratch,+ )?;+ let png = png_codec::encode_rgba8_to_png(w, h, &rgba)?;+ Ok((w, h, png))+ }++ /// Collects all `Arc<TileData>` references in this document (layers + history).+ pub fn collect_all_tile_refs<'a>(&'a self, out: &mut Vec<&'a Arc<TileData>>) {+ for l in &self.layers {+ out.extend(l.grid.tiles.values());+ out.extend(l.grid.mask_tiles.values());+ }+ self.history.collect_tile_refs(out);+ }++ /// Helper: returns the active layer's blend mode or Normal.+ pub fn active_blend_mode(&self) -> BlendMode {+ self.active_layer()+ .map(|l| l.meta.blend_mode)+ .unwrap_or(BlendMode::Normal)+ }+}diff --git a/crates/ink-engine/src/document/manager.rs b/crates/ink-engine/src/document/manager.rsnew file mode 100644index 0000000..ec78f4d--- /dev/null+++ b/crates/ink-engine/src/document/manager.rs@@ -0,0 +1,318 @@+//! Multi-tab `DocumentManager` keyed by `DocumentId` with instant O(1) tab switching+//! and cooperative L2 LZ4 RAM / L3 Scratch Disk memory budgeting across all open tabs.++use super::doc::Document;+use super::types::{+ CanvasColorMode, CanvasDimensions, DocumentId, DocumentMetaSnapshot,+};+use crate::memory::tiered::ManagedTileSlot;+use crate::memory::{+ EvictionContext, InMemoryScratchBackend, MemoryBudgetConfig, MemoryStats, ScratchBackend,+ TieredMemoryManager, ViewportFrustum,+};+use crate::tiles::TileKind;+use serde::{Deserialize, Serialize};+use std::collections::{HashMap, HashSet};+use std::sync::Arc;++#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct MemoryPurgeOutcome {+ pub lz4_compressed_tiles: usize,+ pub disk_paged_tiles: usize,+ pub freed_bytes: u64,+ pub stats: MemoryStats,+}++/// Central Rust multi-tab document store — single source of truth for all open documents.+pub struct DocumentManager {+ documents: HashMap<DocumentId, Document>,+ active_doc_id: Option<DocumentId>,+ memory: TieredMemoryManager,+ frustum: Option<ViewportFrustum>,+}++impl Default for DocumentManager {+ fn default() -> Self {+ Self::new(+ MemoryBudgetConfig::default(),+ Arc::new(InMemoryScratchBackend::new()),+ )+ }+}++impl DocumentManager {+ pub fn new(config: MemoryBudgetConfig, scratch: Arc<dyn ScratchBackend>) -> Self {+ Self {+ documents: HashMap::new(),+ active_doc_id: None,+ memory: TieredMemoryManager::new(config, scratch),+ frustum: None,+ }+ }++ pub fn scratch_backend(&self) -> &Arc<dyn ScratchBackend> {+ self.memory.scratch()+ }++ pub fn scratch_ref(&self) -> &dyn ScratchBackend {+ self.memory.scratch_ref()+ }++ pub fn budget_config(&self) -> MemoryBudgetConfig {+ self.memory.config+ }++ pub fn set_memory_budget(&mut self, config: MemoryBudgetConfig) -> Result<MemoryStats, String> {+ self.memory.set_budget(config);+ for doc in self.documents.values_mut() {+ doc.history.set_max_steps(config.max_history_steps);+ }+ let _ = self.enforce_memory_budget()?;+ Ok(self.memory_stats())+ }++ pub fn set_viewport_frustum(&mut self, frustum: Option<ViewportFrustum>) {+ self.frustum = frustum;+ }++ pub fn active_document_id(&self) -> Option<&str> {+ self.active_doc_id.as_deref()+ }++ pub fn active_document(&self) -> Option<&Document> {+ let id = self.active_doc_id.as_deref()?;+ self.documents.get(id)+ }++ pub fn active_document_mut(&mut self) -> Option<&mut Document> {+ let id = self.active_doc_id.as_deref()?.to_string();+ self.documents.get_mut(&id)+ }++ pub fn get_document(&self, doc_id: &str) -> Option<&Document> {+ self.documents.get(doc_id)+ }++ pub fn get_document_mut(&mut self, doc_id: &str) -> Option<&mut Document> {+ self.documents.get_mut(doc_id)+ }++ pub fn document_ids(&self) -> Vec<DocumentId> {+ self.documents.keys().cloned().collect()+ }++ /// Creates a new blank document tab and activates it immediately.+ #[allow(clippy::too_many_arguments)]+ pub fn create_document(+ &mut self,+ doc_id: impl Into<String>,+ name: impl Into<String>,+ dimensions: CanvasDimensions,+ color_mode: CanvasColorMode,+ background_hex: &str,+ default_tone_frequency: f32,+ ) -> DocumentMetaSnapshot {+ let id = doc_id.into();+ let doc = Document::new_blank(+ id.clone(),+ name,+ dimensions,+ color_mode,+ background_hex,+ default_tone_frequency,+ self.memory.config.max_history_steps,+ );+ let snap = doc.snapshot_meta();+ self.documents.insert(id.clone(), doc);+ self.switch_document_internal(Some(&id));+ snap+ }++ /// Inserts an already-hydrated document (from `.ink` / `.clip` / `.psd` / crash recovery)+ /// and activates it immediately.+ pub fn insert_and_activate(&mut self, doc: Document) -> DocumentMetaSnapshot {+ let id = doc.id.clone();+ let snap = doc.snapshot_meta();+ self.documents.insert(id.clone(), doc);+ self.switch_document_internal(Some(&id));+ let _ = self.enforce_memory_budget();+ snap+ }++ /// Switches the active document tab in O(1) without clearing or re-uploading pixels.+ /// Optionally compresses the previous tab's raw tiles into L2 LZ4 RAM to save memory.+ pub fn switch_document(&mut self, doc_id: &str) -> Result<DocumentMetaSnapshot, String> {+ if !self.documents.contains_key(doc_id) {+ return Err(format!("Document not found: {doc_id}"));+ }+ self.switch_document_internal(Some(doc_id));+ let doc = self+ .documents+ .get_mut(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ doc.touch();+ doc.dirty_for_render = true;+ Ok(doc.snapshot_meta())+ }++ fn switch_document_internal(&mut self, next_id: Option<&str>) {+ let prev_id = self.active_doc_id.clone();+ if let Some(ref pid) = prev_id {+ if Some(pid.as_str()) != next_id && self.memory.config.offload_inactive_tabs {+ // Compress previous tab's raw tiles into L2 LZ4 RAM in-process (instant, zero disk stall)+ if let Some(prev_doc) = self.documents.get_mut(pid) {+ let mut slots = Vec::new();+ for layer in &mut prev_doc.layers {+ let lid = layer.meta.id.as_str();+ for (&coord, tile) in &mut layer.grid.tiles {+ slots.push(ManagedTileSlot {+ doc_id: pid.as_str(),+ layer_id: lid,+ kind: TileKind::Raster,+ coord,+ tile,+ });+ }+ for (&coord, tile) in &mut layer.grid.mask_tiles {+ slots.push(ManagedTileSlot {+ doc_id: pid.as_str(),+ layer_id: lid,+ kind: TileKind::Mask,+ coord,+ tile,+ });+ }+ }+ let _ = self.memory.compress_all_to_lz4(slots);+ }+ }+ }+ self.active_doc_id = next_id.map(|s| s.to_string());+ }++ /// Closes a document tab, freeing all its tiles and deleting its L3 scratch session.+ pub fn close_document(&mut self, doc_id: &str) -> bool {+ let removed = self.documents.remove(doc_id).is_some();+ if self.active_doc_id.as_deref() == Some(doc_id) {+ self.active_doc_id = self.documents.keys().next().cloned();+ }+ let _ = self.memory.scratch_ref().clear_session(doc_id);+ removed+ }++ /// Computes deduplicated live tiered memory statistics across all open documents.+ pub fn memory_stats(&self) -> MemoryStats {+ let mut refs = Vec::new();+ let mut history_count = 0u64;+ for doc in self.documents.values() {+ doc.collect_all_tile_refs(&mut refs);+ history_count += doc.history.len() as u64;+ }+ self.memory+ .compute_stats(refs, history_count, self.documents.len() as u32)+ }++ fn build_eviction_context(&self) -> EvictionContext {+ let mut hidden_layers = HashSet::new();+ for (doc_id, doc) in &self.documents {+ for layer in &doc.layers {+ if !doc.is_layer_effectively_visible(&layer.meta.id) {+ hidden_layers.insert((doc_id.clone(), layer.meta.id.clone()));+ }+ }+ }+ let active_layer_id = self+ .active_document()+ .and_then(|d| d.active_layer_id.clone());+ EvictionContext {+ active_doc_id: self.active_doc_id.clone(),+ active_layer_id,+ frustum: self.frustum,+ hidden_layers,+ }+ }++ /// Enforces the shared CPU RAM budget across all open documents (L2 LZ4 -> L3 Scratch Disk).+ pub fn enforce_memory_budget(&mut self) -> Result<(usize, usize, u64), String> {+ let ctx = self.build_eviction_context();+ let mut slots = Vec::new();+ for (doc_id, doc) in &mut self.documents {+ let did = doc_id.as_str();+ for layer in &mut doc.layers {+ let lid = layer.meta.id.as_str();+ for (&coord, tile) in &mut layer.grid.tiles {+ slots.push(ManagedTileSlot {+ doc_id: did,+ layer_id: lid,+ kind: TileKind::Raster,+ coord,+ tile,+ });+ }+ for (&coord, tile) in &mut layer.grid.mask_tiles {+ slots.push(ManagedTileSlot {+ doc_id: did,+ layer_id: lid,+ kind: TileKind::Mask,+ coord,+ tile,+ });+ }+ }+ }+ self.memory.enforce_budget(slots, &ctx)+ }++ /// Explicitly purges tile memory (compressing active tab to L2 LZ4 and offloading inactive+ /// tabs to L3 Scratch Disk).+ pub fn purge_memory(&mut self, include_active_to_disk: bool) -> Result<MemoryPurgeOutcome, String> {+ let active_id = self.active_doc_id.clone();+ let mut lz4_count = 0usize;+ let mut disk_count = 0usize;+ let mut freed = 0u64;++ for (doc_id, doc) in &mut self.documents {+ let is_active = active_id.as_deref() == Some(doc_id.as_str());+ let did = doc_id.as_str();+ let mut slots = Vec::new();+ for layer in &mut doc.layers {+ let lid = layer.meta.id.as_str();+ for (&coord, tile) in &mut layer.grid.tiles {+ slots.push(ManagedTileSlot {+ doc_id: did,+ layer_id: lid,+ kind: TileKind::Raster,+ coord,+ tile,+ });+ }+ for (&coord, tile) in &mut layer.grid.mask_tiles {+ slots.push(ManagedTileSlot {+ doc_id: did,+ layer_id: lid,+ kind: TileKind::Mask,+ coord,+ tile,+ });+ }+ }+ if !is_active || include_active_to_disk {+ let (d_cnt, d_freed) = self.memory.evict_all_to_disk(slots)?;+ disk_count += d_cnt;+ freed += d_freed;+ } else {+ let (c_cnt, c_freed) = self.memory.compress_all_to_lz4(slots);+ lz4_count += c_cnt;+ freed += c_freed;+ }+ }++ Ok(MemoryPurgeOutcome {+ lz4_compressed_tiles: lz4_count,+ disk_paged_tiles: disk_count,+ freed_bytes: freed,+ stats: self.memory_stats(),+ })+ }+}diff --git a/crates/ink-engine/src/document/mod.rs b/crates/ink-engine/src/document/mod.rsnew file mode 100644index 0000000..b7e0689--- /dev/null+++ b/crates/ink-engine/src/document/mod.rs@@ -0,0 +1,14 @@+//! Document tree, layer metadata, and multi-tab `DocumentManager` — the single source of+//! truth for all documents, layers, masks, raster tiles, and CoW history in Rust.++pub mod doc;+pub mod manager;+pub mod types;++pub use doc::{Document, LayerNode};+pub use manager::{DocumentManager, MemoryPurgeOutcome};+pub use types::{+ BlendMode, CanvasColorMode, CanvasDimensions, ComicFrame, DocumentId, DocumentMetaSnapshot,+ ExpressionColor, LayerColorLabel, LayerId, LayerNodeMeta, LayerPropsPatch, LayerType, Point2D,+ ToneDensityType, ToneDotShape,+};diff --git a/crates/ink-engine/src/document/types.rs b/crates/ink-engine/src/document/types.rsnew file mode 100644index 0000000..e0d1288--- /dev/null+++ b/crates/ink-engine/src/document/types.rs@@ -0,0 +1,501 @@+//! Strongly-typed InkStudio document & layer hierarchy metadata matching `src/types/editor.ts`.+//!+//! Serializes directly to React's camelCase JSON shape (`LayerItem`, `CanvasDimensions`, etc.)+//! without ever sending full-resolution raster or mask buffers over IPC.++use crate::history::HistoryStateSnapshot;+use crate::tiles::TileFormat;+use serde::{Deserialize, Serialize};++pub type DocumentId = String;+pub type LayerId = String;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct CanvasDimensions {+ pub width: u32,+ pub height: u32,+ #[serde(default = "default_dpi")]+ pub dpi: u32,+}++fn default_dpi() -> u32 {+ 300+}++impl Default for CanvasDimensions {+ fn default() -> Self {+ Self {+ width: 1920,+ height: 1080,+ dpi: 300,+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum CanvasColorMode {+ #[default]+ Color,+ Grayscale,+ Monochrome,+}++impl CanvasColorMode {+ pub fn from_str_lossy(s: &str) -> Self {+ match s.to_ascii_lowercase().as_str() {+ "grayscale" | "gray" => Self::Grayscale,+ "monochrome" | "mono" => Self::Monochrome,+ _ => Self::Color,+ }+ }++ pub fn as_str(self) -> &'static str {+ match self {+ Self::Color => "color",+ Self::Grayscale => "grayscale",+ Self::Monochrome => "monochrome",+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum ExpressionColor {+ #[default]+ Color,+ Gray,+ Monochrome,+}++impl ExpressionColor {+ pub fn from_str_lossy(s: &str) -> Self {+ match s.to_ascii_lowercase().as_str() {+ "gray" | "grayscale" => Self::Gray,+ "monochrome" | "mono" => Self::Monochrome,+ _ => Self::Color,+ }+ }++ pub fn to_tile_format(self) -> TileFormat {+ match self {+ Self::Monochrome => TileFormat::Monochrome1Bit,+ Self::Gray => TileFormat::Grayscale8Bit,+ Self::Color => TileFormat::Color32Bit,+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum LayerType {+ #[default]+ Raster,+ Folder,+ FrameFolder,+ Vector,+ Frame,+ Adjustment,+ Text,+ Balloon,+}++impl LayerType {+ pub fn from_str_lossy(s: &str) -> Self {+ match s {+ "folder" => Self::Folder,+ "frame-folder" => Self::FrameFolder,+ "vector" => Self::Vector,+ "frame" => Self::Frame,+ "adjustment" => Self::Adjustment,+ "text" => Self::Text,+ "balloon" => Self::Balloon,+ _ => Self::Raster,+ }+ }++ #[inline]+ pub fn is_folder_like(self) -> bool {+ matches!(self, Self::Folder | Self::FrameFolder)+ }++ #[inline]+ pub fn has_tiles(self) -> bool {+ matches!(+ self,+ Self::Raster | Self::Vector | Self::Frame | Self::Text | Self::Balloon+ )+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum BlendMode {+ #[default]+ Normal,+ Multiply,+ Screen,+ Overlay,+ Darken,+ Lighten,+ ColorDodge,+ ColorBurn,+ HardLight,+ SoftLight,+ Difference,+ Exclusion,+ PassThrough,+ LinearBurn,+ AddGlow,+ ColorDodgeGlow,+ Divide,+ VividLight,+ LinearLight,+ PinLight,+ HardMix,+ Subtract,+ DarkerColor,+ LighterColor,+ Hue,+ Saturation,+ Color,+ Luminosity,+}++impl BlendMode {+ pub fn from_str_lossy(s: &str) -> Self {+ match s {+ "multiply" => Self::Multiply,+ "screen" => Self::Screen,+ "overlay" => Self::Overlay,+ "darken" => Self::Darken,+ "lighten" => Self::Lighten,+ "color-dodge" => Self::ColorDodge,+ "color-burn" => Self::ColorBurn,+ "hard-light" => Self::HardLight,+ "soft-light" => Self::SoftLight,+ "difference" => Self::Difference,+ "exclusion" => Self::Exclusion,+ "pass-through" => Self::PassThrough,+ "linear-burn" => Self::LinearBurn,+ "add-glow" => Self::AddGlow,+ "color-dodge-glow" => Self::ColorDodgeGlow,+ "divide" => Self::Divide,+ "vivid-light" => Self::VividLight,+ "linear-light" => Self::LinearLight,+ "pin-light" => Self::PinLight,+ "hard-mix" => Self::HardMix,+ "subtract" => Self::Subtract,+ "darker-color" => Self::DarkerColor,+ "lighter-color" => Self::LighterColor,+ "hue" => Self::Hue,+ "saturation" => Self::Saturation,+ "color" => Self::Color,+ "luminosity" => Self::Luminosity,+ _ => Self::Normal,+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum LayerColorLabel {+ #[default]+ None,+ Red,+ Orange,+ Yellow,+ Green,+ Cyan,+ Blue,+ Purple,+ Gray,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum ToneDotShape {+ #[default]+ Circle,+ Euclidean,+ Line,+ Diamond,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum ToneDensityType {+ Specified,+ #[default]+ Image,+}++#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]+pub struct Point2D {+ pub x: f64,+ pub y: f64,+}++/// Comic panel border / clipping polygon matching `ComicFrame` in `src/types/editor.ts`.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ComicFrame {+ pub id: String,+ pub layer_id: String,+ pub polygon: Vec<Point2D>,+ pub border_width: f32,+ pub gutter_vertical: f32,+ pub gutter_horizontal: f32,+ pub clip_children: bool,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub fill_background: Option<bool>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub fill_color: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub stroke_color: Option<String>,+}++fn default_true() -> bool {+ true+}++fn default_opacity() -> f32 {+ 1.0+}++/// Complete InkStudio layer metadata matching `LayerItem` in `src/types/editor.ts`.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct LayerNodeMeta {+ pub id: LayerId,+ pub name: String,+ #[serde(rename = "type", default)]+ pub layer_type: LayerType,+ #[serde(default = "default_true")]+ pub visible: bool,+ #[serde(default = "default_opacity")]+ pub opacity: f32,+ #[serde(default)]+ pub blend_mode: BlendMode,+ #[serde(default)]+ pub locked: bool,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub alpha_locked: Option<bool>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub clipped: Option<bool>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub collapsed: Option<bool>,+ #[serde(default)]+ pub parent_id: Option<LayerId>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub thumbnail_url: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub is_reference: Option<bool>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub color_label: Option<LayerColorLabel>,++ // Screentone (CSP Tone Effect)+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub is_tone_layer: Option<bool>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub tone_enabled: Option<bool>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub tone_frequency: Option<f32>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub tone_angle: Option<f32>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub tone_dot_shape: Option<ToneDotShape>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub tone_density: Option<f32>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub tone_density_type: Option<ToneDensityType>,++ // Layer Color Tint (CSP Layer Color)+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub layer_color_enabled: Option<bool>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub layer_color: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub layer_sub_color: Option<String>,++ // Expression Color+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub expression_color: Option<ExpressionColor>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub mono_threshold: Option<u8>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub mono_express_black: Option<bool>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub mono_express_white: Option<bool>,++ // Non-destructive 8-bit Layer Mask metadata (mask pixels live exclusively in Rust `mask_tiles`)+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub has_mask: bool,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub mask_version: Option<u64>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub mask_enabled: Option<bool>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub mask_linked: Option<bool>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub mask_thumbnail_url: Option<String>,++ // Rich non-destructive layer payloads (preserved losslessly for UI + `.ink` serialization)+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub adjustment_data: Option<serde_json::Value>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub styles: Option<serde_json::Value>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub vector_strokes: Option<serde_json::Value>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub comic_frames: Option<Vec<ComicFrame>>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub text_data: Option<serde_json::Value>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub balloon_data: Option<serde_json::Value>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub balloons: Option<serde_json::Value>,++ // Collaborative ownership metadata+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub owner_peer_id: Option<serde_json::Value>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub owner_peer_name: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub reserved_by_peer_id: Option<serde_json::Value>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub reserved_by_peer_name: Option<String>,+}++impl LayerNodeMeta {+ pub fn new_raster(id: impl Into<String>, name: impl Into<String>) -> Self {+ Self {+ id: id.into(),+ name: name.into(),+ layer_type: LayerType::Raster,+ visible: true,+ opacity: 1.0,+ blend_mode: BlendMode::Normal,+ locked: false,+ alpha_locked: Some(false),+ clipped: Some(false),+ collapsed: Some(false),+ parent_id: None,+ thumbnail_url: Some(String::new()),+ is_reference: None,+ color_label: None,+ is_tone_layer: None,+ tone_enabled: None,+ tone_frequency: None,+ tone_angle: None,+ tone_dot_shape: None,+ tone_density: None,+ tone_density_type: None,+ layer_color_enabled: None,+ layer_color: None,+ layer_sub_color: None,+ expression_color: Some(ExpressionColor::Color),+ mono_threshold: Some(128),+ mono_express_black: Some(true),+ mono_express_white: Some(true),+ has_mask: false,+ mask_version: None,+ mask_enabled: None,+ mask_linked: None,+ mask_thumbnail_url: None,+ adjustment_data: None,+ styles: None,+ vector_strokes: None,+ comic_frames: None,+ text_data: None,+ balloon_data: None,+ balloons: None,+ owner_peer_id: None,+ owner_peer_name: None,+ reserved_by_peer_id: None,+ reserved_by_peer_name: None,+ }+ }++ pub fn new_folder(id: impl Into<String>, name: impl Into<String>) -> Self {+ let mut meta = Self::new_raster(id, name);+ meta.layer_type = LayerType::Folder;+ meta.blend_mode = BlendMode::PassThrough;+ meta.expression_color = None;+ meta.mono_threshold = None;+ meta.mono_express_black = None;+ meta.mono_express_white = None;+ meta+ }+}++/// Partial property update sent from React layer panel / sliders to Rust.+#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct LayerPropsPatch {+ pub name: Option<String>,+ pub visible: Option<bool>,+ pub opacity: Option<f32>,+ pub blend_mode: Option<BlendMode>,+ pub locked: Option<bool>,+ pub alpha_locked: Option<bool>,+ pub clipped: Option<bool>,+ pub collapsed: Option<bool>,+ pub parent_id: Option<Option<LayerId>>,+ pub is_reference: Option<bool>,+ pub color_label: Option<LayerColorLabel>,+ pub is_tone_layer: Option<bool>,+ pub tone_enabled: Option<bool>,+ pub tone_frequency: Option<f32>,+ pub tone_angle: Option<f32>,+ pub tone_dot_shape: Option<ToneDotShape>,+ pub tone_density: Option<f32>,+ pub tone_density_type: Option<ToneDensityType>,+ pub layer_color_enabled: Option<bool>,+ pub layer_color: Option<String>,+ pub layer_sub_color: Option<String>,+ pub expression_color: Option<ExpressionColor>,+ pub mono_threshold: Option<u8>,+ pub mono_express_black: Option<bool>,+ pub mono_express_white: Option<bool>,+ pub mask_enabled: Option<bool>,+ pub mask_linked: Option<bool>,+ pub adjustment_data: Option<serde_json::Value>,+ pub styles: Option<serde_json::Value>,+ pub comic_frames: Option<Vec<ComicFrame>>,+ pub text_data: Option<serde_json::Value>,+ pub balloon_data: Option<serde_json::Value>,+ pub vector_strokes: Option<serde_json::Value>,+ /// Optional coalesce key for slider drags (`opacity:layer-1`, `tone-freq:layer-1`, etc.).+ pub coalesce_key: Option<String>,+ /// Optional custom history label.+ pub history_label: Option<String>,+ /// Set false to suppress recording a history step (e.g. UI-only folder collapse).+ pub record_history: Option<bool>,+}++/// Compact document snapshot returned from Rust to React (metadata + tiny thumbnails only!).+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DocumentMetaSnapshot {+ pub id: DocumentId,+ pub name: String,+ pub dimensions: CanvasDimensions,+ pub color_mode: CanvasColorMode,+ pub layers: Vec<LayerNodeMeta>,+ pub active_layer_id: Option<LayerId>,+ pub history: HistoryStateSnapshot,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub preview_data_url: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub perspective_ruler: Option<serde_json::Value>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub straight_ruler: Option<serde_json::Value>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub animation_timeline: Option<serde_json::Value>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub timelapse: Option<serde_json::Value>,+ #[serde(default)]+ pub work_time_ms: u64,+}diff --git a/crates/ink-engine/src/engine.rs b/crates/ink-engine/src/engine.rsnew file mode 100644index 0000000..e6e3aba--- /dev/null+++ b/crates/ink-engine/src/engine.rs@@ -0,0 +1,1289 @@+//! Dedicated high-priority engine/render thread with wake-on-input scheduling,+//! zero-IPC ring buffer ingestion, native camera navigation, and throttled event emission.++use crate::camera::{clamp_zoom, viewport_css_to_doc, NativeCameraNavigator};+use crate::clock;+use crate::document::DocumentManager;+use crate::gpu::{GpuRenderer, RenderOutcome};+use crate::hit_test::SharedHitTest;+use crate::memory::{+ GpuPoolStats, InMemoryScratchBackend, MemoryBudgetConfig, ScratchBackend,+};+use crate::ring::{create_input_rings, InputConsumers, InputProducers, WakeSignal};+use crate::stroke::{DabInstance, StrokeDabGenerator};+use crate::tiles::{RectI32, TileKind};+use crate::types::{+ BrushParams, CameraState, CursorConfig, EngineCommand, EngineDiagnostics, EngineEvent,+ InteractionPolicy, NativeInputSample, NativeNavEvent, SurfaceTarget, ThumbnailUpdate,+ ViewportRect, WheelNavMode,+};+use crossbeam_channel::{Receiver, Sender};+use parking_lot::RwLock;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex};+use std::thread::JoinHandle;+use std::time::Duration;++/// Initial configuration when spawning an `ink-engine` instance.+pub struct EngineConfig {+ pub doc_width: u32,+ pub doc_height: u32,+ pub show_checkerboard: bool,+ pub matte_color: [f32; 4],+ pub memory_budget: MemoryBudgetConfig,+ pub scratch_backend: Option<Arc<dyn ScratchBackend>>,+}++impl Default for EngineConfig {+ fn default() -> Self {+ Self {+ doc_width: 1920,+ doc_height: 1080,+ show_checkerboard: true,+ matte_color: [0.086, 0.086, 0.086, 1.0], // #161616 default Graphite Atelier matte+ memory_budget: MemoryBudgetConfig::default(),+ scratch_backend: None,+ }+ }+}++/// Thread-safe handle to a running `ink-engine` instance.+///+/// The host sends control commands via [`send_command`], shares [`hit_test`] directly with+/// native input hooks, mutates documents via [`documents`], and consumes throttled+/// [`EngineEvent`]s via [`events`].+pub struct EngineHandle {+ cmd_tx: Sender<EngineCommand>,+ event_rx: Receiver<EngineEvent>,+ wake: Arc<WakeSignal>,+ hit_test: SharedHitTest,+ documents: Arc<RwLock<DocumentManager>>,+ gpu_pool_stats: Arc<RwLock<GpuPoolStats>>,+ diagnostics: Arc<Mutex<EngineDiagnostics>>,+ running: Arc<AtomicBool>,+ thread: Mutex<Option<JoinHandle<()>>>,+}++impl EngineHandle {+ /// Spawns the dedicated DX12 engine thread and returns `(EngineHandle, InputProducers)`.+ ///+ /// `InputProducers` carries three wait-free SPSC `rtrb` producers (`wintab`, `winink`, `nav`)+ /// so each OS input thread pushes samples directly into `ink-engine` with zero locks and zero IPC.+ pub fn spawn(+ target: SurfaceTarget,+ mut config: EngineConfig,+ ) -> Result<(Self, InputProducers), String> {+ let wake = WakeSignal::new();+ let (producers, consumers) = create_input_rings(&wake);+ let (cmd_tx, cmd_rx) = crossbeam_channel::unbounded::<EngineCommand>();+ let (event_tx, event_rx) = crossbeam_channel::bounded::<EngineEvent>(128);+ let hit_test = SharedHitTest::new();+ let scratch: Arc<dyn ScratchBackend> = config+ .scratch_backend+ .take()+ .unwrap_or_else(|| Arc::new(InMemoryScratchBackend::new()));+ let vram_budget = config.memory_budget.vram_budget_bytes;+ let documents = Arc::new(RwLock::new(DocumentManager::new(+ config.memory_budget,+ scratch,+ )));+ let gpu_pool_stats = Arc::new(RwLock::new(GpuPoolStats::default()));+ let diagnostics = Arc::new(Mutex::new(EngineDiagnostics {+ doc_width: config.doc_width,+ doc_height: config.doc_height,+ gpu_vram_budget_bytes: vram_budget,+ ..Default::default()+ }));+ let running = Arc::new(AtomicBool::new(true));++ let (init_tx, init_rx) = crossbeam_channel::bounded::<Result<EngineDiagnostics, String>>(1);++ let wake_thread = Arc::clone(&wake);+ let hit_test_thread = hit_test.clone();+ let docs_thread = Arc::clone(&documents);+ let pool_stats_thread = Arc::clone(&gpu_pool_stats);+ let diag_thread = Arc::clone(&diagnostics);+ let running_thread = Arc::clone(&running);++ let handle = std::thread::Builder::new()+ .name("inkstudio-gpu-engine".to_string())+ .spawn(move || {+ elevate_render_thread_priority();++ let renderer = match GpuRenderer::new_with_vram(+ target,+ config.doc_width,+ config.doc_height,+ vram_budget,+ ) {+ Ok(r) => r,+ Err(err) => {+ running_thread.store(false, Ordering::SeqCst);+ let _ = init_tx.send(Err(err));+ return;+ }+ };++ let pool_stats = renderer.gpu_pool_stats();+ *pool_stats_thread.write() = pool_stats;++ let initial_diag = EngineDiagnostics {+ ready: true,+ adapter_name: renderer.adapter_name().to_string(),+ backend: "DX12".to_string(),+ present_mode: renderer.present_mode_label().to_string(),+ doc_width: config.doc_width,+ doc_height: config.doc_height,+ max_frame_latency: 1,+ composition_mode: renderer.composition_mode_label().to_string(),+ gpu_vram_used_bytes: pool_stats.used_bytes,+ gpu_vram_budget_bytes: pool_stats.capacity_bytes,+ gpu_tiles_resident: pool_stats.slots_used,+ gpu_tiles_capacity: pool_stats.slots_capacity,+ ..Default::default()+ };+ if let Ok(mut g) = diag_thread.lock() {+ *g = initial_diag.clone();+ }+ let _ = event_tx.try_send(EngineEvent::Diagnostics(initial_diag.clone()));+ let _ = init_tx.send(Ok(initial_diag));++ let mut state = EngineThreadState::new(+ renderer,+ config,+ consumers,+ cmd_rx,+ event_tx,+ wake_thread,+ hit_test_thread,+ docs_thread,+ pool_stats_thread,+ diag_thread,+ running_thread,+ );+ state.run_loop();+ })+ .map_err(|e| format!("Failed to spawn ink-engine thread: {e}"))?;++ match init_rx.recv_timeout(Duration::from_secs(10)) {+ Ok(Ok(_diag)) => Ok((+ Self {+ cmd_tx,+ event_rx,+ wake,+ hit_test,+ documents,+ gpu_pool_stats,+ diagnostics,+ running,+ thread: Mutex::new(Some(handle)),+ },+ producers,+ )),+ Ok(Err(e)) => {+ let _ = handle.join();+ Err(e)+ }+ Err(_) => {+ running.store(false, Ordering::SeqCst);+ let _ = handle.join();+ Err("Timed out initializing wgpu DX12 engine thread".to_string())+ }+ }+ }++ /// Sends a typed command to the engine thread and immediately wakes it.+ pub fn send_command(&self, cmd: EngineCommand) {+ // Mirror hit-test state synchronously so input hooks observe viewport/occlusion updates+ // immediately without waiting for the render thread to dequeue the command channel.+ match &cmd {+ EngineCommand::SetViewport(vp) => self.hit_test.set_viewport(*vp),+ EngineCommand::SetOccludedRects(rects) => self.hit_test.set_occluded_rects(rects.clone()),+ EngineCommand::SetVisible(vis) => self.hit_test.set_visible(*vis),+ EngineCommand::SetInteractionPolicy(policy) => self.hit_test.set_policy(*policy),+ _ => {}+ }+ let _ = self.cmd_tx.send(cmd);+ self.wake.wake();+ }++ pub fn hit_test(&self) -> SharedHitTest {+ self.hit_test.clone()+ }++ /// Returns a shared thread-safe handle to the multi-tab Rust [`DocumentManager`].+ pub fn documents(&self) -> Arc<RwLock<DocumentManager>> {+ Arc::clone(&self.documents)+ }++ /// Returns the latest L1 GPU VRAM tile atlas telemetry snapshot.+ pub fn gpu_pool_stats(&self) -> GpuPoolStats {+ *self.gpu_pool_stats.read()+ }++ pub fn events(&self) -> &Receiver<EngineEvent> {+ &self.event_rx+ }++ pub fn diagnostics(&self) -> EngineDiagnostics {+ self.diagnostics+ .lock()+ .map(|g| g.clone())+ .unwrap_or_default()+ }++ pub fn is_running(&self) -> bool {+ self.running.load(Ordering::Relaxed)+ }++ /// Gracefully stops and joins the engine thread so the `wgpu::Surface` is dropped+ /// strictly BEFORE the host tears down its DirectComposition visual tree.+ pub fn shutdown(&self) {+ self.running.store(false, Ordering::SeqCst);+ let _ = self.cmd_tx.send(EngineCommand::Shutdown);+ self.wake.wake();+ if let Ok(mut guard) = self.thread.lock() {+ if let Some(handle) = guard.take() {+ let _ = handle.join();+ }+ }+ }+}++impl Drop for EngineHandle {+ fn drop(&mut self) {+ self.shutdown();+ }+}++#[cfg(target_os = "windows")]+fn elevate_render_thread_priority() {+ use windows_sys::Win32::System::Threading::{+ GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL,+ };+ unsafe {+ SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);+ }+}++#[cfg(not(target_os = "windows"))]+fn elevate_render_thread_priority() {}++struct EngineThreadState {+ renderer: GpuRenderer,+ consumers: InputConsumers,+ cmd_rx: Receiver<EngineCommand>,+ event_tx: Sender<EngineEvent>,+ wake: Arc<WakeSignal>,+ hit_test: SharedHitTest,+ documents: Arc<RwLock<DocumentManager>>,+ shared_pool_stats: Arc<RwLock<GpuPoolStats>>,+ shared_diag: Arc<Mutex<EngineDiagnostics>>,+ running: Arc<AtomicBool>,++ viewport: ViewportRect,+ visible: bool,+ show_checkerboard: bool,+ matte_color: [f32; 4],+ camera: CameraState,+ cursor_cfg: CursorConfig,+ brush_params: BrushParams,+ policy: InteractionPolicy,++ navigator: NativeCameraNavigator,+ stroke_gen: StrokeDabGenerator,+ pending_dabs: Vec<DabInstance>,+ stroke_accum_dabs: Vec<DabInstance>,+ stroke_accum_eraser: bool,+ merged_samples: Vec<NativeInputSample>,++ cursor_local_phys: Option<(f32, f32)>,+ cursor_over_occluded: bool,+ last_tablet_sample_ms: f64,++ // Throttling & telemetry+ dirty: bool,+ pending_doc_sync: bool,+ pending_camera_emit: bool,+ pending_camera_commit: bool,+ last_camera_emit_ms: f64,+ last_diag_emit_ms: f64,+ last_pointer_stat_ms: f64,+ latest_pointer_doc: Option<(i32, i32)>,+ latest_pointer_pressure: f32,+ pointer_stat_dirty: bool,++ newest_input_timestamp_ms: f64,+ ema_frame_time_ms: f32,+ ema_input_latency_ms: f32,+ fps_window_start_ms: f64,+ fps_window_frames: u32,+ measured_fps: f32,+ total_frames: u64,+ active_stroke_dabs: u64,+ device_lost_recoveries: u32,+}++impl EngineThreadState {+ #[allow(clippy::too_many_arguments)]+ fn new(+ renderer: GpuRenderer,+ config: EngineConfig,+ consumers: InputConsumers,+ cmd_rx: Receiver<EngineCommand>,+ event_tx: Sender<EngineEvent>,+ wake: Arc<WakeSignal>,+ hit_test: SharedHitTest,+ documents: Arc<RwLock<DocumentManager>>,+ shared_pool_stats: Arc<RwLock<GpuPoolStats>>,+ shared_diag: Arc<Mutex<EngineDiagnostics>>,+ running: Arc<AtomicBool>,+ ) -> Self {+ let now = clock::now_ms();+ Self {+ renderer,+ consumers,+ cmd_rx,+ event_tx,+ wake,+ hit_test,+ documents,+ shared_pool_stats,+ shared_diag,+ running,+ viewport: ViewportRect::default(),+ visible: false,+ show_checkerboard: config.show_checkerboard,+ matte_color: config.matte_color,+ camera: CameraState::default(),+ cursor_cfg: CursorConfig::default(),+ brush_params: BrushParams::default(),+ policy: InteractionPolicy::default(),+ navigator: NativeCameraNavigator::default(),+ stroke_gen: StrokeDabGenerator::default(),+ pending_dabs: Vec::with_capacity(256),+ stroke_accum_dabs: Vec::with_capacity(512),+ stroke_accum_eraser: false,+ merged_samples: Vec::with_capacity(128),+ cursor_local_phys: None,+ cursor_over_occluded: false,+ last_tablet_sample_ms: 0.0,+ dirty: false,+ pending_doc_sync: false,+ pending_camera_emit: false,+ pending_camera_commit: false,+ last_camera_emit_ms: 0.0,+ last_diag_emit_ms: now,+ last_pointer_stat_ms: 0.0,+ latest_pointer_doc: None,+ latest_pointer_pressure: 0.0,+ pointer_stat_dirty: false,+ newest_input_timestamp_ms: 0.0,+ ema_frame_time_ms: 0.0,+ ema_input_latency_ms: 0.0,+ fps_window_start_ms: now,+ fps_window_frames: 0,+ measured_fps: 0.0,+ total_frames: 0,+ active_stroke_dabs: 0,+ device_lost_recoveries: 0,+ }+ }++ fn sync_active_document_if_needed(&mut self) {+ if !self.pending_doc_sync {+ return;+ }+ self.pending_doc_sync = false;+ let mut mgr = self.documents.write();+ let scratch = Arc::clone(mgr.scratch_backend());+ if let Some(doc) = mgr.active_document_mut() {+ if let Err(err) = self.renderer.sync_document(doc, Some(scratch.as_ref())) {+ eprintln!("[ink-engine] sync_document failed: {err}");+ }+ *self.shared_pool_stats.write() = self.renderer.gpu_pool_stats();+ self.dirty = true;+ }+ }++ /// Commits accumulated live GPU brush dabs directly into the active editable layer's+ /// sparse tile store + CoW Undo/Redo stack, then syncs the composited result back to GPU.+ fn commit_active_stroke(&mut self) {+ if self.stroke_accum_dabs.is_empty() {+ return;+ }+ let dabs = std::mem::take(&mut self.stroke_accum_dabs);+ let is_eraser = self.stroke_accum_eraser;++ let mut min_x = f32::INFINITY;+ let mut min_y = f32::INFINITY;+ let mut max_x = f32::NEG_INFINITY;+ let mut max_y = f32::NEG_INFINITY;+ for d in &dabs {+ let ext = d.radius_doc.max(0.5) + 2.0;+ min_x = min_x.min(d.center_doc[0] - ext);+ min_y = min_y.min(d.center_doc[1] - ext);+ max_x = max_x.max(d.center_doc[0] + ext);+ max_y = max_y.max(d.center_doc[1] + ext);+ }++ let committed_info = {+ let mut mgr = self.documents.write();+ let scratch = Arc::clone(mgr.scratch_backend());+ let Some(doc) = mgr.active_document_mut() else {+ return;+ };+ let doc_w = doc.dimensions.width as i32;+ let doc_h = doc.dimensions.height as i32;+ let x0 = (min_x.floor() as i32).clamp(0, doc_w);+ let y0 = (min_y.floor() as i32).clamp(0, doc_h);+ let x1 = (max_x.ceil() as i32).clamp(0, doc_w);+ let y1 = (max_y.ceil() as i32).clamp(0, doc_h);+ if x1 <= x0 || y1 <= y0 {+ return;+ }+ let rw = (x1 - x0) as u32;+ let rh = (y1 - y0) as u32;+ let rect = RectI32::new(x0, y0, rw, rh);++ let Some(layer_id) = doc.active_layer_id.clone() else {+ return;+ };+ let (is_editable, alpha_locked, mono_thresh) = match doc.layer(&layer_id) {+ Some(l) => (+ l.meta.layer_type.has_tiles() && !l.meta.locked,+ l.meta.alpha_locked.unwrap_or(false),+ l.meta.mono_threshold.unwrap_or(128),+ ),+ None => return,+ };+ if !is_editable {+ // Re-sync GPU texture to clear preview dabs drawn over a locked/non-raster layer+ self.pending_doc_sync = true;+ return;+ }++ let Some(layer) = doc.layer_mut(&layer_id) else {+ return;+ };+ let before_snap = layer.grid.snapshot_all_cow(TileKind::Raster);+ let Ok(mut buf) = layer.grid.read_rgba8_rect(rect, false, Some(scratch.as_ref()))+ else {+ return;+ };++ rasterize_dabs_into_rgba8(&mut buf, x0, y0, rw, rh, &dabs, is_eraser, alpha_locked);+ if layer+ .grid+ .write_rgba8_rect(&buf, rect, mono_thresh, Some(scratch.as_ref()))+ .is_err()+ {+ return;+ }++ let deltas = layer+ .grid+ .diff_from_full_snapshot(&layer_id, TileKind::Raster, &before_snap);+ if deltas.is_empty() {+ self.pending_doc_sync = true;+ return;+ }++ let (action_type, label) = if is_eraser {+ ("erase", "Erase")+ } else {+ ("brush", "Brush Stroke")+ };+ let entry_id = doc.record_stroke_deltas(+ &layer_id,+ action_type,+ label,+ deltas,+ Some("local".to_string()),+ None,+ );++ let thumb = doc+ .generate_layer_thumbnail_data_url(&layer_id, 64, 64, Some(scratch.as_ref()))+ .ok();+ if let Some(ref url) = thumb {+ if let Some(l) = doc.layer_mut(&layer_id) {+ l.meta.thumbnail_url = Some(url.clone());+ }+ }++ let doc_id = doc.id.clone();+ let hist_snap = doc.history.snapshot();++ // Sync straight into DX12 texture & L1 tile pool+ if let Err(err) = self.renderer.sync_document(doc, Some(scratch.as_ref())) {+ eprintln!("[ink-engine] post-stroke sync_document failed: {err}");+ }+ *self.shared_pool_stats.write() = self.renderer.gpu_pool_stats();+ self.dirty = true;++ // Enforce RAM budget opportunistically after stroke commits+ let _ = mgr.enforce_memory_budget();++ Some((doc_id, layer_id, entry_id, hist_snap, thumb))+ };++ if let Some((doc_id, layer_id, entry_id, history, thumb)) = committed_info {+ if let Some(eid) = entry_id {+ let _ = self.event_tx.try_send(EngineEvent::StrokeCommitted {+ doc_id: doc_id.clone(),+ layer_id: layer_id.clone(),+ entry_id: eid,+ });+ }+ let _ = self.event_tx.try_send(EngineEvent::HistoryChanged {+ doc_id: doc_id.clone(),+ history,+ });+ if thumb.is_some() {+ let _ = self.event_tx.try_send(EngineEvent::ThumbnailsUpdated {+ doc_id,+ updates: vec![ThumbnailUpdate {+ layer_id,+ thumbnail_url: thumb,+ mask_thumbnail_url: None,+ }],+ });+ }+ }+ }++ fn run_loop(&mut self) {+ while self.running.load(Ordering::Relaxed) {+ if !self.drain_commands() {+ break;+ }+ self.sync_active_document_if_needed();+ self.drain_tablet_rings();+ self.drain_nav_ring();+ self.sync_active_document_if_needed();++ let now = clock::now_ms();++ if self.dirty && self.visible && self.viewport.width_px > 0 && self.viewport.height_px > 0+ {+ self.render_and_present(now);+ } else if !self.pending_dabs.is_empty() {+ // Avoid unbounded dab growth if minimized/hidden+ self.pending_dabs.clear();+ }++ self.flush_throttled_events(clock::now_ms());++ // Sleep immediately when idle (0% GPU/CPU usage); wake instantly on any input or command.+ if !self.dirty && !self.pending_camera_emit && !self.pending_camera_commit {+ self.wake.wait_timeout(Duration::from_millis(50));+ } else if !self.dirty {+ // Pending throttled camera sync commit: wake shortly to flush+ self.wake.wait_timeout(Duration::from_millis(8));+ }+ }+ self.running.store(false, Ordering::SeqCst);+ }++ fn drain_commands(&mut self) -> bool {+ while let Ok(cmd) = self.cmd_rx.try_recv() {+ match cmd {+ EngineCommand::SetViewport(vp) => {+ if self.viewport != vp {+ self.viewport = vp;+ self.dirty = true;+ }+ }+ EngineCommand::SetOccludedRects(_) => {+ // Already updated in SharedHitTest synchronously; re-evaluate hover cursor occlusion+ if let Some((lx, ly)) = self.cursor_local_phys {+ let px = lx + self.viewport.x_px as f32;+ let py = ly + self.viewport.y_px as f32;+ let occluded = !self.hit_test.is_unoccluded_canvas_point(px, py);+ if occluded != self.cursor_over_occluded {+ self.cursor_over_occluded = occluded;+ self.dirty = true;+ }+ }+ }+ EngineCommand::SetDocumentSize {+ width,+ height,+ show_checkerboard,+ } => {+ self.show_checkerboard = show_checkerboard;+ let has_active_doc = self.documents.read().active_document().is_some();+ if has_active_doc {+ self.pending_doc_sync = true;+ } else {+ self.renderer.set_document_size(width, height);+ }+ self.stroke_gen.reset();+ self.pending_dabs.clear();+ self.stroke_accum_dabs.clear();+ self.active_stroke_dabs = 0;+ self.dirty = true;+ }+ EngineCommand::SetShowCheckerboard(show) => {+ if self.show_checkerboard != show {+ self.show_checkerboard = show;+ self.dirty = true;+ }+ }+ EngineCommand::SetMatteColor(color) => {+ if self.matte_color != color {+ self.matte_color = color;+ self.dirty = true;+ }+ }+ EngineCommand::SetCamera(cam) => {+ let sanitized = CameraState {+ zoom: clamp_zoom(cam.zoom),+ ..cam+ };+ if self.camera != sanitized {+ self.camera = sanitized;+ self.dirty = true;+ }+ }+ EngineCommand::SetCursorConfig(cfg) => {+ if self.cursor_cfg != cfg {+ self.cursor_cfg = cfg;+ self.dirty = true;+ }+ }+ EngineCommand::SetBrushParams(params) => {+ self.brush_params = params;+ }+ EngineCommand::SetInteractionPolicy(policy) => {+ let tool_changed = self.policy.active_tool != policy.active_tool;+ self.policy = policy;+ if (!policy.native_stroke_enabled+ || !policy.active_tool.is_native_stroke_tool()+ || policy.modal_open)+ && self.stroke_gen.is_active()+ {+ self.stroke_gen.end();+ }+ if tool_changed || policy.modal_open {+ self.dirty = true;+ }+ }+ EngineCommand::SetVisible(vis) => {+ if self.visible != vis {+ self.visible = vis;+ if !vis {+ self.stroke_gen.end();+ self.navigator.cancel();+ self.cursor_local_phys = None;+ } else {+ self.dirty = true;+ }+ }+ }+ EngineCommand::ClearCanvas => {+ self.stroke_gen.reset();+ self.pending_dabs.clear();+ self.stroke_accum_dabs.clear();+ self.active_stroke_dabs = 0;+ let cleared_doc = {+ let mut mgr = self.documents.write();+ if let Some(doc) = mgr.active_document_mut() {+ if let Some(aid) = doc.active_layer_id.clone() {+ let _ = doc.clear_layer(&aid, true);+ }+ true+ } else {+ false+ }+ };+ if cleared_doc {+ self.pending_doc_sync = true;+ } else {+ self.renderer.clear_canvas();+ }+ self.dirty = true;+ }+ EngineCommand::SyncActiveDocument => {+ self.pending_doc_sync = true;+ self.dirty = true;+ }+ EngineCommand::SetVramBudget(budget_bytes) => {+ self.renderer.set_vram_budget(budget_bytes);+ *self.shared_pool_stats.write() = self.renderer.gpu_pool_stats();+ self.pending_doc_sync = true;+ }+ EngineCommand::FlushGpuPool => {+ self.renderer.flush_gpu_pool();+ *self.shared_pool_stats.write() = self.renderer.gpu_pool_stats();+ }+ EngineCommand::NotifySurfaceInvalidated => {+ self.renderer.force_reconfigure();+ self.dirty = true;+ }+ EngineCommand::Shutdown => {+ return false;+ }+ }+ }+ true+ }++ fn drain_tablet_rings(&mut self) {+ self.merged_samples.clear();+ while let Ok(s) = self.consumers.wintab.pop() {+ self.merged_samples.push(s);+ }+ while let Ok(s) = self.consumers.winink.pop() {+ self.merged_samples.push(s);+ }+ if self.merged_samples.is_empty() {+ return;+ }+ if self.merged_samples.len() > 1 {+ self.merged_samples.sort_by(|a, b| {+ a.timestamp_ms+ .partial_cmp(&b.timestamp_ms)+ .unwrap_or(std::cmp::Ordering::Equal)+ });+ }++ let samples = std::mem::take(&mut self.merged_samples);+ for sample in &samples {+ self.process_tablet_sample(*sample);+ }+ self.merged_samples = samples;+ }++ fn process_tablet_sample(&mut self, sample: NativeInputSample) {+ self.last_tablet_sample_ms = sample.timestamp_ms;+ if sample.timestamp_ms > self.newest_input_timestamp_ms {+ self.newest_input_timestamp_ms = sample.timestamp_ms;+ }++ if sample.phase == 4 {+ // Stylus left proximity+ if self.stroke_gen.is_active() {+ self.stroke_gen.end();+ }+ if self.cursor_local_phys.is_some() {+ self.cursor_local_phys = None;+ self.dirty = true;+ }+ self.latest_pointer_doc = None;+ self.latest_pointer_pressure = 0.0;+ self.pointer_stat_dirty = true;+ return;+ }++ let in_unoccluded = self+ .hit_test+ .is_unoccluded_canvas_point(sample.phys_x, sample.phys_y);++ // Update native GPU brush cursor ring position from live physical coordinates+ if self.viewport.contains_phys(sample.phys_x, sample.phys_y) {+ let local_phys = self.viewport.phys_to_local_phys(sample.phys_x, sample.phys_y);+ self.cursor_local_phys = Some(local_phys);+ self.cursor_over_occluded = !in_unoccluded;+ self.dirty = true;+ } else if self.cursor_local_phys.is_some() {+ self.cursor_local_phys = None;+ self.dirty = true;+ }++ let (local_css_x, local_css_y) =+ self.viewport.phys_to_local_css(sample.phys_x, sample.phys_y);+ let (doc_w, doc_h) = self.renderer.doc_size();+ let (doc_x, doc_y) = viewport_css_to_doc(+ local_css_x,+ local_css_y,+ doc_w as f32,+ doc_h as f32,+ &self.camera,+ );++ self.latest_pointer_doc = Some((doc_x.round() as i32, doc_y.round() as i32));+ self.latest_pointer_pressure = sample.pressure;+ self.pointer_stat_dirty = true;++ // Do not paint while a native camera navigation drag is active+ if self.navigator.is_active() {+ if self.stroke_gen.is_active() {+ self.stroke_gen.end();+ }+ return;+ }++ match sample.phase {+ 1 => {+ // Pen down: only start native GPU stroke if unoccluded + native stroke tool active+ if self+ .hit_test+ .should_capture_native_stroke(sample.phys_x, sample.phys_y)+ {+ let inverted_eraser = (sample.buttons & 8) != 0;+ self.active_stroke_dabs = 0;+ self.stroke_accum_dabs.clear();+ let before = self.pending_dabs.len();+ self.stroke_gen.begin(+ doc_x,+ doc_y,+ sample.pressure,+ inverted_eraser,+ &self.brush_params,+ &mut self.pending_dabs,+ );+ self.stroke_accum_eraser = self.stroke_gen.stroke_is_eraser();+ self.stroke_accum_dabs+ .extend_from_slice(&self.pending_dabs[before..]);+ self.active_stroke_dabs += (self.pending_dabs.len() - before) as u64;+ self.dirty = true;+ }+ }+ 2 => {+ // Pen drag: continue active stroke even if pen moves past canvas edges (CSP-style)+ if self.stroke_gen.is_active() {+ let before = self.pending_dabs.len();+ self.stroke_gen.push_move(+ doc_x,+ doc_y,+ sample.pressure,+ &self.brush_params,+ &mut self.pending_dabs,+ );+ self.stroke_accum_dabs+ .extend_from_slice(&self.pending_dabs[before..]);+ self.active_stroke_dabs += (self.pending_dabs.len() - before) as u64;+ self.dirty = true;+ }+ }+ 3 if self.stroke_gen.is_active() => {+ // Pen up: commit stroke into active layer SparseLayerGrid + CoW Undo/Redo+ self.stroke_gen.end();+ self.commit_active_stroke();+ self.dirty = true;+ }+ _ => {}+ }+ }++ fn drain_nav_ring(&mut self) {+ while let Ok(evt) = self.consumers.nav.pop() {+ match evt {+ NativeNavEvent::Hover {+ phys_x,+ phys_y,+ timestamp_ms,+ } => {+ // Defer cursor updates to active stylus packets if a stylus was just active (< 120ms)+ if timestamp_ms - self.last_tablet_sample_ms < 120.0 {+ continue;+ }+ if timestamp_ms > self.newest_input_timestamp_ms {+ self.newest_input_timestamp_ms = timestamp_ms;+ }+ let in_vp = self.viewport.contains_phys(phys_x, phys_y);+ let in_unoccluded = self.hit_test.is_unoccluded_canvas_point(phys_x, phys_y);+ if in_vp {+ let local_phys = self.viewport.phys_to_local_phys(phys_x, phys_y);+ self.cursor_local_phys = Some(local_phys);+ self.cursor_over_occluded = !in_unoccluded;+ let (lx, ly) = self.viewport.phys_to_local_css(phys_x, phys_y);+ let (doc_w, doc_h) = self.renderer.doc_size();+ let (dx, dy) =+ viewport_css_to_doc(lx, ly, doc_w as f32, doc_h as f32, &self.camera);+ self.latest_pointer_doc = Some((dx.round() as i32, dy.round() as i32));+ self.latest_pointer_pressure = 0.0;+ self.pointer_stat_dirty = true;+ self.dirty = true;+ } else if self.cursor_local_phys.is_some() {+ self.cursor_local_phys = None;+ self.latest_pointer_doc = None;+ self.pointer_stat_dirty = true;+ self.dirty = true;+ }+ }+ NativeNavEvent::HoverLeave => {+ if self.cursor_local_phys.is_some() {+ self.cursor_local_phys = None;+ self.latest_pointer_doc = None;+ self.pointer_stat_dirty = true;+ self.dirty = true;+ }+ }+ NativeNavEvent::GestureStart {+ gesture,+ phys_x,+ phys_y,+ timestamp_ms,+ } => {+ if timestamp_ms > self.newest_input_timestamp_ms {+ self.newest_input_timestamp_ms = timestamp_ms;+ }+ if self.stroke_gen.is_active() {+ self.stroke_gen.end();+ }+ let (lx, ly) = self.viewport.phys_to_local_css(phys_x, phys_y);+ self.navigator.begin(+ gesture,+ lx,+ ly,+ self.viewport.css_width(),+ self.viewport.css_height(),+ &self.camera,+ );+ self.dirty = true;+ }+ NativeNavEvent::GestureMove {+ phys_x,+ phys_y,+ snap_15_deg,+ timestamp_ms,+ } => {+ if timestamp_ms > self.newest_input_timestamp_ms {+ self.newest_input_timestamp_ms = timestamp_ms;+ }+ let (lx, ly) = self.viewport.phys_to_local_css(phys_x, phys_y);+ if self.navigator.update(+ lx,+ ly,+ snap_15_deg,+ self.policy.is_webtoon_mode,+ &mut self.camera,+ ) {+ self.dirty = true;+ self.pending_camera_emit = true;+ }+ }+ NativeNavEvent::GestureEnd { timestamp_ms } => {+ if timestamp_ms > self.newest_input_timestamp_ms {+ self.newest_input_timestamp_ms = timestamp_ms;+ }+ if self.navigator.end() {+ self.pending_camera_emit = true;+ self.pending_camera_commit = true;+ self.dirty = true;+ }+ }+ NativeNavEvent::Wheel {+ phys_x,+ phys_y,+ delta_x,+ delta_y,+ ctrl_held,+ shift_held,+ timestamp_ms,+ } => {+ if timestamp_ms > self.newest_input_timestamp_ms {+ self.newest_input_timestamp_ms = timestamp_ms;+ }+ let (lx, ly) = self.viewport.phys_to_local_css(phys_x, phys_y);+ let changed = if (self.policy.wheel_mode == WheelNavMode::Scroll+ || self.policy.is_webtoon_mode)+ && !ctrl_held+ {+ NativeCameraNavigator::apply_wheel_scroll(+ delta_x,+ delta_y,+ shift_held,+ self.policy.is_webtoon_mode,+ &mut self.camera,+ )+ } else {+ NativeCameraNavigator::apply_wheel_zoom(lx, ly, delta_y, &mut self.camera)+ };+ if changed {+ self.dirty = true;+ self.pending_camera_emit = true;+ self.pending_camera_commit = true;+ }+ }+ NativeNavEvent::MouseDraw {+ phys_x,+ phys_y,+ phase,+ timestamp_ms,+ } => {+ // Suppress synthetic WinTab mouse messages while stylus was just active+ if timestamp_ms - self.last_tablet_sample_ms < 250.0 {+ continue;+ }+ self.process_tablet_sample(NativeInputSample {+ phys_x,+ phys_y,+ pressure: if phase == 3 { 0.0 } else { 0.75 },+ tilt_x: 0.0,+ tilt_y: 0.0,+ twist: 0.0,+ timestamp_ms,+ buttons: if phase == 3 { 0 } else { 1 },+ phase,+ backend: 3,+ });+ }+ }+ }+ }++ fn render_and_present(&mut self, frame_start_ms: f64) {+ let cursor_suppressed =+ self.cursor_over_occluded || self.navigator.is_active() || self.policy.modal_open;+ let dabs_are_eraser = self.stroke_gen.stroke_is_eraser();++ let outcome = self.renderer.render_frame(+ &self.viewport,+ &self.camera,+ self.show_checkerboard,+ self.matte_color,+ &self.pending_dabs,+ dabs_are_eraser,+ &self.cursor_cfg,+ self.cursor_local_phys,+ cursor_suppressed,+ );++ match outcome {+ RenderOutcome::Presented => {+ self.pending_dabs.clear();+ self.dirty = false;++ let after_ms = clock::now_ms();+ let frame_ms = (after_ms - frame_start_ms).max(0.01) as f32;+ self.ema_frame_time_ms = if self.ema_frame_time_ms <= 0.001 {+ frame_ms+ } else {+ self.ema_frame_time_ms * 0.8 + frame_ms * 0.2+ };++ if self.newest_input_timestamp_ms > 0.0 {+ let lat = (after_ms - self.newest_input_timestamp_ms) as f32;+ if (0.0..500.0).contains(&lat) {+ self.ema_input_latency_ms = if self.ema_input_latency_ms <= 0.001 {+ lat+ } else {+ self.ema_input_latency_ms * 0.75 + lat * 0.25+ };+ }+ self.newest_input_timestamp_ms = 0.0;+ }++ self.total_frames = self.total_frames.saturating_add(1);+ self.fps_window_frames = self.fps_window_frames.saturating_add(1);+ let window_elapsed = after_ms - self.fps_window_start_ms;+ if window_elapsed >= 250.0 {+ self.measured_fps =+ (self.fps_window_frames as f64 / (window_elapsed / 1000.0)) as f32;+ self.fps_window_frames = 0;+ self.fps_window_start_ms = after_ms;+ }+ }+ RenderOutcome::Skipped => {+ // Window occluded or minimized — keep pending dabs if any or yield briefly+ self.dirty = false;+ }+ RenderOutcome::NeedsReconfigure => {+ self.renderer.force_reconfigure();+ // Keep dirty=true so next loop iteration renders immediately+ }+ RenderOutcome::DeviceLost => {+ self.recover_from_device_lost();+ }+ }+ }++ fn recover_from_device_lost(&mut self) {+ let (doc_w, doc_h) = self.renderer.doc_size();+ let vram_budget = self.renderer.vram_budget_bytes();+ let target = self.renderer.surface_target_for_recovery();+ match GpuRenderer::new_with_vram(target, doc_w, doc_h, vram_budget) {+ Ok(mut fresh) => {+ if self.viewport.width_px > 0 && self.viewport.height_px > 0 {+ fresh.resize_surface(self.viewport.width_px, self.viewport.height_px);+ }+ self.renderer = fresh;+ *self.shared_pool_stats.write() = self.renderer.gpu_pool_stats();+ self.device_lost_recoveries = self.device_lost_recoveries.saturating_add(1);+ // Re-upload full document state from Rust CPU/LZ4/Scratch truth after TDR+ self.pending_doc_sync = true;+ self.dirty = true;+ }+ Err(_) => {+ // Back off briefly if GPU driver is still resetting (TDR)+ std::thread::sleep(Duration::from_millis(100));+ }+ }+ }++ fn flush_throttled_events(&mut self, now_ms: f64) {+ // 1. Throttled camera sync (~60 Hz during active pan/zoom/rotate, immediate on commit)+ if self.pending_camera_emit+ && (self.pending_camera_commit || now_ms - self.last_camera_emit_ms >= 16.0)+ {+ let commit = self.pending_camera_commit;+ self.pending_camera_emit = false;+ self.pending_camera_commit = false;+ self.last_camera_emit_ms = now_ms;+ let _ = self.event_tx.try_send(EngineEvent::CameraChanged {+ camera: self.camera,+ commit,+ });+ }++ // 2. Throttled StatusBar pointer coordinate/pressure (~30 Hz)+ if self.pointer_stat_dirty && now_ms - self.last_pointer_stat_ms >= 33.0 {+ self.pointer_stat_dirty = false;+ self.last_pointer_stat_ms = now_ms;+ let (doc_x, doc_y) = match self.latest_pointer_doc {+ Some((x, y)) => (Some(x), Some(y)),+ None => (None, None),+ };+ let _ = self.event_tx.try_send(EngineEvent::PointerStat {+ doc_x,+ doc_y,+ pressure: self.latest_pointer_pressure,+ });+ }++ // 3. Throttled GPU diagnostics (~4 Hz)+ if now_ms - self.last_diag_emit_ms >= 250.0 {+ self.last_diag_emit_ms = now_ms;+ // Decay displayed FPS to 0 if no frames rendered in the last 600ms (idle wake-on-input)+ let fps = if now_ms - self.fps_window_start_ms > 600.0 && self.fps_window_frames == 0 {+ 0.0+ } else {+ self.measured_fps+ };+ let (sw, sh) = self.renderer.swapchain_size();+ let (dw, dh) = self.renderer.doc_size();+ let pool_stats = self.renderer.gpu_pool_stats();+ *self.shared_pool_stats.write() = pool_stats;+ let diag = EngineDiagnostics {+ ready: true,+ adapter_name: self.renderer.adapter_name().to_string(),+ backend: "DX12".to_string(),+ present_mode: self.renderer.present_mode_label().to_string(),+ fps,+ frame_time_ms: self.ema_frame_time_ms,+ input_to_present_ms: self.ema_input_latency_ms,+ swapchain_width: sw,+ swapchain_height: sh,+ doc_width: dw,+ doc_height: dh,+ active_stroke_dabs: self.active_stroke_dabs,+ total_frames_rendered: self.total_frames,+ device_lost_recoveries: self.device_lost_recoveries,+ max_frame_latency: 1,+ composition_mode: self.renderer.composition_mode_label().to_string(),+ gpu_vram_used_bytes: pool_stats.used_bytes,+ gpu_vram_budget_bytes: pool_stats.capacity_bytes,+ gpu_tiles_resident: pool_stats.slots_used,+ gpu_tiles_capacity: pool_stats.slots_capacity,+ };+ if let Ok(mut g) = self.shared_diag.lock() {+ *g = diag.clone();+ }+ let _ = self.event_tx.try_send(EngineEvent::Diagnostics(diag));+ }+ }+}++/// CPU fallback rasterizer matching `DAB_SHADER_WGSL` so Phase 2 native DX12 strokes commit+/// cleanly onto the active layer's `SparseLayerGrid` + CoW Undo/Redo history without baking+/// underlying layers into the active layer.+#[allow(clippy::too_many_arguments)]+fn rasterize_dabs_into_rgba8(+ buf: &mut [u8],+ rect_x: i32,+ rect_y: i32,+ rect_w: u32,+ rect_h: u32,+ dabs: &[DabInstance],+ is_eraser: bool,+ alpha_locked: bool,+) {+ let rw = rect_w as i32;+ let rh = rect_h as i32;+ for d in dabs {+ let r = d.radius_doc.max(0.35);+ let h = d.hardness.clamp(0.0, 1.0);+ let inner_r = r * h * 0.96;+ let aa_edge = (r - inner_r).max(0.75);+ let edge0 = (r - aa_edge).max(0.0);+ let edge1 = r + 0.5;+ let span = (edge1 - edge0).max(1e-5);++ let cx = d.center_doc[0];+ let cy = d.center_doc[1];+ let sr = d.color_rgba[0].clamp(0.0, 1.0);+ let sg = d.color_rgba[1].clamp(0.0, 1.0);+ let sb = d.color_rgba[2].clamp(0.0, 1.0);+ let sa_base = d.color_rgba[3].clamp(0.0, 1.0);++ let min_px = ((cx - r - 1.0).floor() as i32 - rect_x).clamp(0, rw);+ let max_px = ((cx + r + 1.5).ceil() as i32 - rect_x).clamp(0, rw);+ let min_py = ((cy - r - 1.0).floor() as i32 - rect_y).clamp(0, rh);+ let max_py = ((cy + r + 1.5).ceil() as i32 - rect_y).clamp(0, rh);++ for ly in min_py..max_py {+ let dy = (rect_y + ly) as f32 + 0.5 - cy;+ let row_off = (ly as usize) * (rect_w as usize);+ for lx in min_px..max_px {+ let dx = (rect_x + lx) as f32 + 0.5 - cx;+ let dist = (dx * dx + dy * dy).sqrt();+ if dist > r + 1.0 {+ continue;+ }+ let t = ((dist - edge0) / span).clamp(0.0, 1.0);+ let falloff = 1.0 - (t * t * (3.0 - 2.0 * t));+ let sa = (sa_base * falloff).clamp(0.0, 1.0);+ if sa < 0.002 {+ continue;+ }+ let idx = (row_off + lx as usize) * 4;+ if is_eraser {+ if alpha_locked {+ continue;+ }+ let da = buf[idx + 3] as f32 / 255.0;+ let na = (da * (1.0 - sa)).clamp(0.0, 1.0);+ buf[idx + 3] = (na * 255.0 + 0.5) as u8;+ if buf[idx + 3] == 0 {+ buf[idx] = 0;+ buf[idx + 1] = 0;+ buf[idx + 2] = 0;+ }+ } else {+ let da = buf[idx + 3] as f32 / 255.0;+ if alpha_locked && da <= 0.001 {+ continue;+ }+ let dr = buf[idx] as f32 / 255.0;+ let dg = buf[idx + 1] as f32 / 255.0;+ let db = buf[idx + 2] as f32 / 255.0;+ if alpha_locked {+ let out_r = sr * sa + dr * (1.0 - sa);+ let out_g = sg * sa + dg * (1.0 - sa);+ let out_b = sb * sa + db * (1.0 - sa);+ buf[idx] = (out_r * 255.0 + 0.5).clamp(0.0, 255.0) as u8;+ buf[idx + 1] = (out_g * 255.0 + 0.5).clamp(0.0, 255.0) as u8;+ buf[idx + 2] = (out_b * 255.0 + 0.5).clamp(0.0, 255.0) as u8;+ } else {+ let out_a = sa + da * (1.0 - sa);+ if out_a <= 1e-5 {+ continue;+ }+ let inv = 1.0 / out_a;+ let out_r = (sr * sa + dr * da * (1.0 - sa)) * inv;+ let out_g = (sg * sa + dg * da * (1.0 - sa)) * inv;+ let out_b = (sb * sa + db * da * (1.0 - sa)) * inv;+ buf[idx] = (out_r * 255.0 + 0.5).clamp(0.0, 255.0) as u8;+ buf[idx + 1] = (out_g * 255.0 + 0.5).clamp(0.0, 255.0) as u8;+ buf[idx + 2] = (out_b * 255.0 + 0.5).clamp(0.0, 255.0) as u8;+ buf[idx + 3] = (out_a * 255.0 + 0.5).clamp(0.0, 255.0) as u8;+ }+ }+ }+ }+ }+}diff --git a/crates/ink-engine/src/gpu.rs b/crates/ink-engine/src/gpu.rsnew file mode 100644index 0000000..af7787d--- /dev/null+++ b/crates/ink-engine/src/gpu.rs@@ -0,0 +1,1314 @@+//! `wgpu` 30.x DirectX 12 GPU renderer for InkStudio.+//!+//! Renders into a Windows DirectComposition visual (`IDCompositionVisual` via+//! `wgpu::SurfaceTargetUnsafe::CompositionVisual`) using a DXGI flip-model+//! composition swapchain with `SetMaximumFrameLatency(1)` + waitable frame latency object.+//! Also supports headless offscreen rendering for automated GPU tests.++use crate::document::Document;+use crate::io::compositor_cpu;+use crate::memory::{GpuPoolStats, GpuTileKey, GpuTilePool, ScratchBackend};+use crate::shaders::{CURSOR_SHADER_WGSL, DAB_SHADER_WGSL, VIEWPORT_SHADER_WGSL};+use crate::stroke::DabInstance;+use crate::tiles::TileCoord;+use crate::types::{CameraState, CursorConfig, SurfaceTarget, ViewportRect};+use bytemuck::{Pod, Zeroable};+use std::borrow::Cow;+use std::ffi::c_void;+use std::sync::Arc;++#[repr(C)]+#[derive(Debug, Clone, Copy, Pod, Zeroable)]+struct ViewportUniforms {+ viewport_size_phys: [f32; 2],+ doc_size: [f32; 2],+ pan_css: [f32; 2],+ zoom: f32,+ rotation_rad: f32,+ flip: [f32; 2],+ dpr: f32,+ show_checkerboard: u32,+ matte_color: [f32; 4],+}++#[repr(C)]+#[derive(Debug, Clone, Copy, Pod, Zeroable)]+struct DabUniforms {+ doc_size: [f32; 2],+ _pad: [f32; 2],+}++#[repr(C)]+#[derive(Debug, Clone, Copy, Pod, Zeroable)]+struct CursorUniforms {+ viewport_size_phys: [f32; 2],+ center_phys: [f32; 2],+ half_extents_phys: [f32; 2],+ angle_rad: f32,+ dpr: f32,+ is_square: u32,+ visible: u32,+ _pad: [u32; 2],+}++pub enum RenderOutcome {+ Presented,+ Skipped,+ NeedsReconfigure,+ DeviceLost,+}++enum OutputTarget {+ Surface {+ surface: wgpu::Surface<'static>,+ config: wgpu::SurfaceConfiguration,+ configured: bool,+ visual_ptr: usize,+ on_configured: Arc<dyn Fn() + Send + Sync>,+ },+ Headless {+ texture: wgpu::Texture,+ view: wgpu::TextureView,+ width: u32,+ height: u32,+ format: wgpu::TextureFormat,+ },+}++pub struct GpuRenderer {+ instance: wgpu::Instance,+ adapter: wgpu::Adapter,+ device: wgpu::Device,+ queue: wgpu::Queue,+ output: OutputTarget,++ adapter_name: String,+ present_mode_label: String,+ composition_mode_label: String,++ // Document canvas surface (single Rgba8Unorm GPU texture for Phase 1 PoC)+ doc_width: u32,+ doc_height: u32,+ doc_texture: wgpu::Texture,+ doc_view: wgpu::TextureView,++ // Viewport compositor pipeline+ viewport_uniform_buf: wgpu::Buffer,+ viewport_bgl: wgpu::BindGroupLayout,+ viewport_bind_group: wgpu::BindGroup,+ viewport_pipeline: wgpu::RenderPipeline,+ doc_sampler_linear: wgpu::Sampler,+ doc_sampler_nearest: wgpu::Sampler,++ // GPU PoC dab brush pipelines (paint & erase)+ dab_uniform_buf: wgpu::Buffer,+ dab_bind_group: wgpu::BindGroup,+ dab_paint_pipeline: wgpu::RenderPipeline,+ dab_erase_pipeline: wgpu::RenderPipeline,+ dab_instance_buf: wgpu::Buffer,+ dab_instance_capacity: usize,++ // GPU brush cursor ring pipeline+ cursor_uniform_buf: wgpu::Buffer,+ cursor_bind_group: wgpu::BindGroup,+ cursor_pipeline: wgpu::RenderPipeline,++ // Phase 2: L1 GPU VRAM Rgba16Float tile atlas pool + compute mipmap pyramid+ tile_pool: GpuTilePool,+ vram_budget_bytes: u64,+}++impl GpuRenderer {+ pub fn new(target: SurfaceTarget, doc_width: u32, doc_height: u32) -> Result<Self, String> {+ Self::new_with_vram(target, doc_width, doc_height, 256 * 1024 * 1024)+ }++ pub fn new_with_vram(+ target: SurfaceTarget,+ doc_width: u32,+ doc_height: u32,+ vram_budget_bytes: u64,+ ) -> Result<Self, String> {+ let instance = Self::create_dx12_instance();++ let (raw_surface, visual_ptr_opt, on_configured_opt, headless_dims) = match target {+ SurfaceTarget::CompositionVisual {+ visual_ptr,+ on_configured,+ } => {+ if visual_ptr == 0 {+ return Err("Null DirectComposition visual pointer".to_string());+ }+ let surface = unsafe {+ instance.create_surface_unsafe(wgpu::SurfaceTargetUnsafe::CompositionVisual(+ visual_ptr as *mut c_void,+ ))+ }+ .map_err(|e| format!("Failed to create wgpu DX12 composition surface: {e}"))?;+ (Some(surface), Some(visual_ptr), Some(on_configured), None)+ }+ SurfaceTarget::Headless { width, height } => (None, None, None, Some((width.max(1), height.max(1)))),+ };++ let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {+ power_preference: wgpu::PowerPreference::HighPerformance,+ force_fallback_adapter: false,+ compatible_surface: raw_surface.as_ref(),+ apply_limit_buckets: false,+ }))+ .map_err(|e| format!("Failed to request DX12 GPU adapter: {e}"))?;++ let adapter_info = adapter.get_info();+ let adapter_name = if adapter_info.name.is_empty() {+ "DX12 GPU".to_string()+ } else {+ adapter_info.name.clone()+ };++ let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {+ label: Some("ink-engine-dx12-device"),+ required_features: wgpu::Features::empty(),+ required_limits: wgpu::Limits::default().using_resolution(adapter.limits()),+ memory_hints: wgpu::MemoryHints::Performance,+ ..Default::default()+ }))+ .map_err(|e| format!("Failed to create DX12 wgpu device: {e}"))?;++ let (output, surface_format, present_mode_label, composition_mode_label) =+ if let Some(surface) = raw_surface {+ let caps = surface.get_capabilities(&adapter);+ let format = Self::pick_surface_format(&caps.formats);+ let present_mode = Self::pick_present_mode(&caps.present_modes);+ let alpha_mode = Self::pick_alpha_mode(&caps.alpha_modes);++ let config = wgpu::SurfaceConfiguration {+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT,+ format,+ color_space: wgpu::SurfaceColorSpace::Srgb,+ width: 1,+ height: 1,+ present_mode,+ desired_maximum_frame_latency: 1,+ alpha_mode,+ view_formats: vec![],+ };++ let pm_label = format!("{present_mode:?}");+ (+ OutputTarget::Surface {+ surface,+ config,+ configured: false,+ visual_ptr: visual_ptr_opt.unwrap_or(0),+ on_configured: on_configured_opt.unwrap_or_else(|| Arc::new(|| {})),+ },+ format,+ pm_label,+ "DirectComposition (DX12 Flip-Discard)".to_string(),+ )+ } else {+ let (w, h) = headless_dims.unwrap_or((64, 64));+ let format = wgpu::TextureFormat::Bgra8Unorm;+ let texture = device.create_texture(&wgpu::TextureDescriptor {+ label: Some("ink-engine-headless-target"),+ size: wgpu::Extent3d {+ width: w,+ height: h,+ 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(&wgpu::TextureViewDescriptor::default());+ (+ OutputTarget::Headless {+ texture,+ view,+ width: w,+ height: h,+ format,+ },+ format,+ "Headless".to_string(),+ "Headless DX12".to_string(),+ )+ };++ let max_dim = device.limits().max_texture_dimension_2d.min(16384);+ let doc_w = doc_width.clamp(1, max_dim);+ let doc_h = doc_height.clamp(1, max_dim);+ let (doc_texture, doc_view) = Self::create_doc_texture(&device, doc_w, doc_h);++ let doc_sampler_linear = device.create_sampler(&wgpu::SamplerDescriptor {+ label: Some("ink-doc-sampler-linear"),+ address_mode_u: wgpu::AddressMode::ClampToEdge,+ address_mode_v: wgpu::AddressMode::ClampToEdge,+ mag_filter: wgpu::FilterMode::Linear,+ min_filter: wgpu::FilterMode::Linear,+ mipmap_filter: wgpu::MipmapFilterMode::Nearest,+ ..Default::default()+ });+ let doc_sampler_nearest = device.create_sampler(&wgpu::SamplerDescriptor {+ label: Some("ink-doc-sampler-nearest"),+ address_mode_u: wgpu::AddressMode::ClampToEdge,+ address_mode_v: wgpu::AddressMode::ClampToEdge,+ mag_filter: wgpu::FilterMode::Nearest,+ min_filter: wgpu::FilterMode::Nearest,+ mipmap_filter: wgpu::MipmapFilterMode::Nearest,+ ..Default::default()+ });++ // --- Viewport Compositor Pipeline ---+ let viewport_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("ink-viewport-uniforms"),+ size: std::mem::size_of::<ViewportUniforms>() as u64,+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });+ let viewport_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("ink-viewport-bgl"),+ entries: &[+ wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Uniform,+ has_dynamic_offset: false,+ min_binding_size: None,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 1,+ 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: 2,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 3,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::NonFiltering),+ count: None,+ },+ ],+ });+ let viewport_bind_group = Self::create_viewport_bind_group(+ &device,+ &viewport_bgl,+ &viewport_uniform_buf,+ &doc_view,+ &doc_sampler_linear,+ &doc_sampler_nearest,+ );+ let viewport_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {+ label: Some("ink-viewport-shader"),+ source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(VIEWPORT_SHADER_WGSL)),+ });+ let viewport_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {+ label: Some("ink-viewport-pl"),+ bind_group_layouts: &[Some(&viewport_bgl)],+ immediate_size: 0,+ });+ let viewport_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some("ink-viewport-pipeline"),+ layout: Some(&viewport_pl),+ vertex: wgpu::VertexState {+ module: &viewport_shader,+ entry_point: Some("vs_main"),+ buffers: &[],+ compilation_options: Default::default(),+ },+ fragment: Some(wgpu::FragmentState {+ module: &viewport_shader,+ entry_point: Some("fs_main"),+ targets: &[Some(wgpu::ColorTargetState {+ format: surface_format,+ blend: None,+ write_mask: wgpu::ColorWrites::ALL,+ })],+ compilation_options: Default::default(),+ }),+ primitive: wgpu::PrimitiveState {+ topology: wgpu::PrimitiveTopology::TriangleList,+ ..Default::default()+ },+ depth_stencil: None,+ multisample: wgpu::MultisampleState::default(),+ multiview_mask: None,+ cache: None,+ });++ // --- GPU Dab Test Brush Pipelines ---+ let dab_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("ink-dab-uniforms"),+ size: std::mem::size_of::<DabUniforms>() as u64,+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });+ let dab_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("ink-dab-bgl"),+ entries: &[wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::VERTEX,+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Uniform,+ has_dynamic_offset: false,+ min_binding_size: None,+ },+ count: None,+ }],+ });+ let dab_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("ink-dab-bg"),+ layout: &dab_bgl,+ entries: &[wgpu::BindGroupEntry {+ binding: 0,+ resource: dab_uniform_buf.as_entire_binding(),+ }],+ });+ let dab_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {+ label: Some("ink-dab-shader"),+ source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(DAB_SHADER_WGSL)),+ });+ let dab_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {+ label: Some("ink-dab-pl"),+ bind_group_layouts: &[Some(&dab_bgl)],+ immediate_size: 0,+ });+ let dab_instance_layout = wgpu::VertexBufferLayout {+ array_stride: std::mem::size_of::<DabInstance>() as wgpu::BufferAddress,+ step_mode: wgpu::VertexStepMode::Instance,+ attributes: &[+ wgpu::VertexAttribute {+ offset: 0,+ shader_location: 0,+ format: wgpu::VertexFormat::Float32x2,+ },+ wgpu::VertexAttribute {+ offset: 8,+ shader_location: 1,+ format: wgpu::VertexFormat::Float32,+ },+ wgpu::VertexAttribute {+ offset: 12,+ shader_location: 2,+ format: wgpu::VertexFormat::Float32,+ },+ wgpu::VertexAttribute {+ offset: 16,+ shader_location: 3,+ format: wgpu::VertexFormat::Float32x4,+ },+ ],+ };+ let dab_paint_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some("ink-dab-paint-pipeline"),+ layout: Some(&dab_pl),+ vertex: wgpu::VertexState {+ module: &dab_shader,+ entry_point: Some("vs_main"),+ buffers: &[Some(dab_instance_layout.clone())],+ compilation_options: Default::default(),+ },+ fragment: Some(wgpu::FragmentState {+ module: &dab_shader,+ entry_point: Some("fs_main"),+ targets: &[Some(wgpu::ColorTargetState {+ format: wgpu::TextureFormat::Rgba8Unorm,+ blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),+ write_mask: wgpu::ColorWrites::ALL,+ })],+ compilation_options: Default::default(),+ }),+ primitive: wgpu::PrimitiveState::default(),+ depth_stencil: None,+ multisample: wgpu::MultisampleState::default(),+ multiview_mask: None,+ cache: None,+ });+ let dab_erase_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some("ink-dab-erase-pipeline"),+ layout: Some(&dab_pl),+ vertex: wgpu::VertexState {+ module: &dab_shader,+ entry_point: Some("vs_main"),+ buffers: &[Some(dab_instance_layout)],+ compilation_options: Default::default(),+ },+ fragment: Some(wgpu::FragmentState {+ module: &dab_shader,+ entry_point: Some("fs_main"),+ targets: &[Some(wgpu::ColorTargetState {+ format: wgpu::TextureFormat::Rgba8Unorm,+ blend: Some(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,+ },+ }),+ write_mask: wgpu::ColorWrites::ALL,+ })],+ compilation_options: Default::default(),+ }),+ primitive: wgpu::PrimitiveState::default(),+ depth_stencil: None,+ multisample: wgpu::MultisampleState::default(),+ multiview_mask: None,+ cache: None,+ });++ let dab_instance_capacity = 2048usize;+ let dab_instance_buf = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("ink-dab-instances"),+ size: (dab_instance_capacity * std::mem::size_of::<DabInstance>()) as u64,+ usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });++ // --- GPU Brush Cursor Pipeline ---+ let cursor_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("ink-cursor-uniforms"),+ size: std::mem::size_of::<CursorUniforms>() as u64,+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });+ let cursor_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("ink-cursor-bgl"),+ entries: &[wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Uniform,+ has_dynamic_offset: false,+ min_binding_size: None,+ },+ count: None,+ }],+ });+ let cursor_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("ink-cursor-bg"),+ layout: &cursor_bgl,+ entries: &[wgpu::BindGroupEntry {+ binding: 0,+ resource: cursor_uniform_buf.as_entire_binding(),+ }],+ });+ let cursor_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {+ label: Some("ink-cursor-shader"),+ source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(CURSOR_SHADER_WGSL)),+ });+ let cursor_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {+ label: Some("ink-cursor-pl"),+ bind_group_layouts: &[Some(&cursor_bgl)],+ immediate_size: 0,+ });+ let cursor_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some("ink-cursor-pipeline"),+ layout: Some(&cursor_pl),+ vertex: wgpu::VertexState {+ module: &cursor_shader,+ entry_point: Some("vs_main"),+ buffers: &[],+ compilation_options: Default::default(),+ },+ fragment: Some(wgpu::FragmentState {+ module: &cursor_shader,+ entry_point: Some("fs_main"),+ targets: &[Some(wgpu::ColorTargetState {+ format: surface_format,+ blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),+ write_mask: wgpu::ColorWrites::ALL,+ })],+ compilation_options: Default::default(),+ }),+ primitive: wgpu::PrimitiveState::default(),+ depth_stencil: None,+ multisample: wgpu::MultisampleState::default(),+ multiview_mask: None,+ cache: None,+ });++ let tile_pool = GpuTilePool::new(&device, vram_budget_bytes);++ let mut renderer = Self {+ instance,+ adapter,+ device,+ queue,+ output,+ adapter_name,+ present_mode_label,+ composition_mode_label,+ doc_width: doc_w,+ doc_height: doc_h,+ doc_texture,+ doc_view,+ viewport_uniform_buf,+ viewport_bgl,+ viewport_bind_group,+ viewport_pipeline,+ doc_sampler_linear,+ doc_sampler_nearest,+ dab_uniform_buf,+ dab_bind_group,+ dab_paint_pipeline,+ dab_erase_pipeline,+ dab_instance_buf,+ dab_instance_capacity,+ cursor_uniform_buf,+ cursor_bind_group,+ cursor_pipeline,+ tile_pool,+ vram_budget_bytes,+ };+ renderer.clear_canvas();+ Ok(renderer)+ }++ fn create_dx12_instance() -> wgpu::Instance {+ let flags = if std::env::var_os("INK_ENGINE_GPU_VALIDATION").is_some() {+ wgpu::InstanceFlags::VALIDATION+ } else {+ wgpu::InstanceFlags::empty()+ };++ let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();+ desc.backends = wgpu::Backends::DX12;+ desc.flags = flags;+ desc.backend_options = wgpu::BackendOptions {+ dx12: wgpu::Dx12BackendOptions {+ shader_compiler: wgpu::Dx12Compiler::Auto,+ presentation_system: wgpu::Dx12SwapchainKind::DxgiFromVisual,+ latency_waitable_object: wgpu::Dx12UseFrameLatencyWaitableObject::Wait,+ ..Default::default()+ },+ ..Default::default()+ };+ wgpu::Instance::new(desc)+ }++ fn pick_surface_format(formats: &[wgpu::TextureFormat]) -> wgpu::TextureFormat {+ // Prefer linear-pass-through Bgra8Unorm so CSS sRGB colors match identically+ for &preferred in &[+ wgpu::TextureFormat::Bgra8Unorm,+ wgpu::TextureFormat::Rgba8Unorm,+ wgpu::TextureFormat::Bgra8UnormSrgb,+ wgpu::TextureFormat::Rgba8UnormSrgb,+ ] {+ if formats.contains(&preferred) {+ return preferred;+ }+ }+ formats+ .first()+ .copied()+ .unwrap_or(wgpu::TextureFormat::Bgra8Unorm)+ }++ fn pick_present_mode(modes: &[wgpu::PresentMode]) -> wgpu::PresentMode {+ if modes.contains(&wgpu::PresentMode::Mailbox) {+ wgpu::PresentMode::Mailbox+ } else {+ wgpu::PresentMode::Fifo+ }+ }++ fn pick_alpha_mode(modes: &[wgpu::CompositeAlphaMode]) -> wgpu::CompositeAlphaMode {+ // CreateSwapChainForComposition requires explicit Opaque (DXGI_ALPHA_MODE_IGNORE)+ // or PreMultiplied (DXGI_ALPHA_MODE_PREMULTIPLIED) — never Auto/Inherit (UNSPECIFIED).+ if modes.contains(&wgpu::CompositeAlphaMode::Opaque) {+ wgpu::CompositeAlphaMode::Opaque+ } else if modes.contains(&wgpu::CompositeAlphaMode::PreMultiplied) {+ wgpu::CompositeAlphaMode::PreMultiplied+ } else {+ modes+ .first()+ .copied()+ .unwrap_or(wgpu::CompositeAlphaMode::PreMultiplied)+ }+ }++ fn create_doc_texture(+ device: &wgpu::Device,+ width: u32,+ height: u32,+ ) -> (wgpu::Texture, wgpu::TextureView) {+ let texture = device.create_texture(&wgpu::TextureDescriptor {+ label: Some("ink-poc-canvas-texture"),+ size: wgpu::Extent3d {+ width: width.max(1),+ height: height.max(1),+ depth_or_array_layers: 1,+ },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: wgpu::TextureFormat::Rgba8Unorm,+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT+ | wgpu::TextureUsages::TEXTURE_BINDING+ | wgpu::TextureUsages::COPY_DST+ | wgpu::TextureUsages::COPY_SRC,+ view_formats: &[],+ });+ let view = texture.create_view(&wgpu::TextureViewDescriptor::default());+ (texture, view)+ }++ fn create_viewport_bind_group(+ device: &wgpu::Device,+ layout: &wgpu::BindGroupLayout,+ uniform_buf: &wgpu::Buffer,+ doc_view: &wgpu::TextureView,+ linear_sampler: &wgpu::Sampler,+ nearest_sampler: &wgpu::Sampler,+ ) -> wgpu::BindGroup {+ device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("ink-viewport-bg"),+ layout,+ entries: &[+ wgpu::BindGroupEntry {+ binding: 0,+ resource: uniform_buf.as_entire_binding(),+ },+ wgpu::BindGroupEntry {+ binding: 1,+ resource: wgpu::BindingResource::TextureView(doc_view),+ },+ wgpu::BindGroupEntry {+ binding: 2,+ resource: wgpu::BindingResource::Sampler(linear_sampler),+ },+ wgpu::BindGroupEntry {+ binding: 3,+ resource: wgpu::BindingResource::Sampler(nearest_sampler),+ },+ ],+ })+ }++ pub fn adapter_name(&self) -> &str {+ &self.adapter_name+ }++ pub fn present_mode_label(&self) -> &str {+ &self.present_mode_label+ }++ pub fn composition_mode_label(&self) -> &str {+ &self.composition_mode_label+ }++ pub fn swapchain_size(&self) -> (u32, u32) {+ match &self.output {+ OutputTarget::Surface {+ config, configured, ..+ } => {+ if *configured {+ (config.width, config.height)+ } else {+ (0, 0)+ }+ }+ OutputTarget::Headless { width, height, .. } => (*width, *height),+ }+ }++ pub fn doc_size(&self) -> (u32, u32) {+ (self.doc_width, self.doc_height)+ }++ pub fn device(&self) -> &wgpu::Device {+ &self.device+ }++ pub fn queue(&self) -> &wgpu::Queue {+ &self.queue+ }++ pub fn tile_pool(&self) -> &GpuTilePool {+ &self.tile_pool+ }++ pub fn tile_pool_mut(&mut self) -> &mut GpuTilePool {+ &mut self.tile_pool+ }++ pub fn gpu_pool_stats(&self) -> GpuPoolStats {+ self.tile_pool.stats()+ }++ pub fn vram_budget_bytes(&self) -> u64 {+ self.vram_budget_bytes+ }++ pub fn set_vram_budget(&mut self, budget_bytes: u64) {+ let clamped = budget_bytes.max(16 * 512 * 1024);+ if clamped != self.vram_budget_bytes {+ self.vram_budget_bytes = clamped;+ self.tile_pool = GpuTilePool::new(&self.device, clamped);+ }+ }++ pub fn flush_gpu_pool(&mut self) {+ self.tile_pool.flush_all();+ }++ /// Synchronizes an entire Rust `Document` into GPU VRAM:+ /// 1. Ensures active visible LOD 0 tiles and 8-bit masks are uploaded into the L1+ /// `Rgba16Float` / `R8Unorm` `GpuTilePool` texture arrays.+ /// 2. Dispatches the WGSL compute mipmap shader (`cs_downsample`) for dirty LOD 1..3 tiles.+ /// 3. Composites the document into the display `doc_texture` (premultiplied RGBA8) so the+ /// viewport shader renders the multi-layer document cleanly.+ pub fn sync_document(+ &mut self,+ doc: &mut Document,+ scratch: Option<&dyn ScratchBackend>,+ ) -> Result<(), String> {+ let max_dim = self.device.limits().max_texture_dimension_2d.min(16384);+ let target_w = doc.dimensions.width.clamp(1, max_dim);+ let target_h = doc.dimensions.height.clamp(1, max_dim);+ if self.doc_width != target_w || self.doc_height != target_h {+ self.set_document_size(target_w, target_h);+ }++ self.tile_pool.begin_frame();+ let doc_id = doc.id.clone();++ // 1. Upload visible layers' tiles into L1 Rgba16Float atlas + generate dirty compute mipmaps+ let visible_ids: Vec<String> = doc+ .layers+ .iter()+ .filter(|l| l.meta.layer_type.has_tiles() && doc.is_layer_effectively_visible(&l.meta.id))+ .map(|l| l.meta.id.clone())+ .collect();++ for layer_id in &visible_ids {+ let Some(layer) = doc.layer_mut(layer_id) else {+ continue;+ };++ // Upload LOD 0 raster tiles (version-checked; skips unchanged tiles in O(1))+ for (&coord, tile_arc) in &layer.grid.tiles {+ let key = GpuTileKey {+ doc_id: doc_id.clone(),+ layer_id: layer_id.clone(),+ lod: 0,+ coord,+ };+ let _ = self+ .tile_pool+ .ensure_tile_uploaded(&self.queue, key, tile_arc, scratch);+ }++ // Upload 8-bit mask tiles into compact R8Unorm mask array+ if layer.grid.has_mask && layer.meta.mask_enabled.unwrap_or(true) {+ for (&coord, mask_arc) in &layer.grid.mask_tiles {+ let key = GpuTileKey {+ doc_id: doc_id.clone(),+ layer_id: layer_id.clone(),+ lod: 0,+ coord,+ };+ let _ = self+ .tile_pool+ .ensure_mask_uploaded(&self.queue, key, mask_arc, scratch);+ }+ }++ // Regenerate dirty GPU compute mipmap pyramid levels LOD 1 -> 2 -> 3+ let ver = layer.grid.layer_version;+ for lod_idx in 0..3usize {+ let target_lod = (lod_idx + 1) as u8;+ let dirty_coords: Vec<TileCoord> =+ layer.grid.dirty_lods[lod_idx].drain().collect();+ for parent_coord in dirty_coords {+ let cx = parent_coord.tx * 2;+ let cy = parent_coord.ty * 2;+ let child_coords = [+ TileCoord::new(cx, cy),+ TileCoord::new(cx + 1, cy),+ TileCoord::new(cx, cy + 1),+ TileCoord::new(cx + 1, cy + 1),+ ];+ let mut child_slots = [None; 4];+ let mut any_child = false;+ for (qi, cc) in child_coords.iter().enumerate() {+ let ckey = GpuTileKey {+ doc_id: doc_id.clone(),+ layer_id: layer_id.clone(),+ lod: target_lod - 1,+ coord: *cc,+ };+ if let Some(slot) = self.tile_pool.get_slot(&ckey) {+ child_slots[qi] = Some(slot);+ any_child = true;+ }+ }+ if any_child {+ let pkey = GpuTileKey {+ doc_id: doc_id.clone(),+ layer_id: layer_id.clone(),+ lod: target_lod,+ coord: parent_coord,+ };+ self.tile_pool.generate_mipmap_tile(+ &self.device,+ &self.queue,+ pkey,+ child_slots,+ ver,+ );+ }+ }+ }+ }++ // 2. Composite document RGBA8 and upload premultiplied to display doc_texture+ let (upload_w, upload_h, mut rgba) =+ if doc.dimensions.width == target_w && doc.dimensions.height == target_h {+ (+ target_w,+ target_h,+ compositor_cpu::composite_document_full_rgba(doc, scratch)?,+ )+ } else {+ compositor_cpu::composite_document_downscaled_rgba(+ doc,+ target_w.max(target_h),+ false,+ scratch,+ )?+ };+ if self.doc_width != upload_w || self.doc_height != upload_h {+ self.set_document_size(upload_w, upload_h);+ }++ // VIEWPORT_SHADER_WGSL expects premultiplied RGBA+ for px in rgba.chunks_exact_mut(4) {+ let a = px[3] as u32;+ if a == 0 {+ px[0] = 0;+ px[1] = 0;+ px[2] = 0;+ } else if a < 255 {+ px[0] = ((px[0] as u32 * a + 127) / 255) as u8;+ px[1] = ((px[1] as u32 * a + 127) / 255) as u8;+ px[2] = ((px[2] as u32 * a + 127) / 255) as u8;+ }+ }++ let expected_len = (upload_w as usize) * (upload_h as usize) * 4;+ if rgba.len() == expected_len {+ self.queue.write_texture(+ wgpu::TexelCopyTextureInfo {+ texture: &self.doc_texture,+ mip_level: 0,+ origin: wgpu::Origin3d::ZERO,+ aspect: wgpu::TextureAspect::All,+ },+ &rgba,+ wgpu::TexelCopyBufferLayout {+ offset: 0,+ bytes_per_row: Some(upload_w * 4),+ rows_per_image: Some(upload_h),+ },+ wgpu::Extent3d {+ width: upload_w,+ height: upload_h,+ depth_or_array_layers: 1,+ },+ );+ }++ doc.dirty_for_render = false;+ Ok(())+ }++ pub fn surface_target_for_recovery(&self) -> SurfaceTarget {+ match &self.output {+ OutputTarget::Surface {+ visual_ptr,+ on_configured,+ ..+ } => SurfaceTarget::CompositionVisual {+ visual_ptr: *visual_ptr,+ on_configured: Arc::clone(on_configured),+ },+ OutputTarget::Headless { width, height, .. } => SurfaceTarget::Headless {+ width: *width,+ height: *height,+ },+ }+ }++ pub fn resize_surface(&mut self, width: u32, height: u32) {+ if width == 0 || height == 0 {+ return;+ }+ let max_dim = self.device.limits().max_texture_dimension_2d.min(16384);+ let w = width.clamp(1, max_dim);+ let h = height.clamp(1, max_dim);++ match &mut self.output {+ OutputTarget::Surface {+ surface,+ config,+ configured,+ on_configured,+ ..+ } => {+ if *configured && config.width == w && config.height == h {+ return;+ }+ config.width = w;+ config.height = h;+ surface.configure(&self.device, config);+ *configured = true;+ // Critical for SurfaceTargetUnsafe::CompositionVisual:+ // wgpu-hal calls visual.SetContent(swapchain) inside configure(),+ // and the DirectComposition host must call IDCompositionDevice::Commit().+ (on_configured)();+ }+ OutputTarget::Headless {+ texture,+ view,+ width: cur_w,+ height: cur_h,+ format,+ } => {+ if *cur_w == w && *cur_h == h {+ return;+ }+ *cur_w = w;+ *cur_h = h;+ *texture = self.device.create_texture(&wgpu::TextureDescriptor {+ label: Some("ink-engine-headless-target"),+ size: wgpu::Extent3d {+ width: w,+ height: h,+ depth_or_array_layers: 1,+ },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: *format,+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,+ view_formats: &[],+ });+ *view = texture.create_view(&wgpu::TextureViewDescriptor::default());+ }+ }+ }++ pub fn force_reconfigure(&mut self) {+ if let OutputTarget::Surface {+ surface,+ config,+ configured,+ on_configured,+ ..+ } = &mut self.output+ {+ if config.width > 0 && config.height > 0 {+ surface.configure(&self.device, config);+ *configured = true;+ (on_configured)();+ }+ }+ }++ pub fn set_document_size(&mut self, width: u32, height: u32) {+ let max_dim = self.device.limits().max_texture_dimension_2d.min(16384);+ let w = width.clamp(1, max_dim);+ let h = height.clamp(1, max_dim);+ if self.doc_width == w && self.doc_height == h {+ return;+ }+ self.doc_width = w;+ self.doc_height = h;+ let (tex, view) = Self::create_doc_texture(&self.device, w, h);+ self.doc_texture = tex;+ self.doc_view = view;+ self.viewport_bind_group = Self::create_viewport_bind_group(+ &self.device,+ &self.viewport_bgl,+ &self.viewport_uniform_buf,+ &self.doc_view,+ &self.doc_sampler_linear,+ &self.doc_sampler_nearest,+ );+ self.clear_canvas();+ }++ pub fn clear_canvas(&mut self) {+ let mut encoder = self+ .device+ .create_command_encoder(&wgpu::CommandEncoderDescriptor {+ label: Some("ink-clear-canvas"),+ });+ {+ let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {+ label: Some("ink-clear-canvas-pass"),+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {+ view: &self.doc_view,+ depth_slice: None,+ resolve_target: None,+ ops: wgpu::Operations {+ load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),+ store: wgpu::StoreOp::Store,+ },+ })],+ depth_stencil_attachment: None,+ timestamp_writes: None,+ occlusion_query_set: None,+ multiview_mask: None,+ });+ }+ self.queue.submit(Some(encoder.finish()));+ }++ fn ensure_dab_capacity(&mut self, needed: usize) {+ if needed <= self.dab_instance_capacity {+ return;+ }+ let next_cap = needed.next_power_of_two().max(2048);+ self.dab_instance_buf = self.device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("ink-dab-instances"),+ size: (next_cap * std::mem::size_of::<DabInstance>()) as u64,+ usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });+ self.dab_instance_capacity = next_cap;+ }++ #[allow(clippy::too_many_arguments)]+ pub fn render_frame(+ &mut self,+ viewport: &ViewportRect,+ camera: &CameraState,+ show_checkerboard: bool,+ matte_color: [f32; 4],+ pending_dabs: &[DabInstance],+ dabs_are_eraser: bool,+ cursor_cfg: &CursorConfig,+ cursor_local_phys: Option<(f32, f32)>,+ cursor_suppressed: bool,+ ) -> RenderOutcome {+ if viewport.width_px == 0 || viewport.height_px == 0 {+ return RenderOutcome::Skipped;+ }++ // Ensure swapchain matches physical viewport cutout bounds+ self.resize_surface(viewport.width_px, viewport.height_px);++ let (vp_w, vp_h) = self.swapchain_size();+ if vp_w == 0 || vp_h == 0 {+ return RenderOutcome::Skipped;+ }++ // Upload pending brush dab instances if any+ if !pending_dabs.is_empty() {+ self.ensure_dab_capacity(pending_dabs.len());+ let dab_uniforms = DabUniforms {+ doc_size: [self.doc_width as f32, self.doc_height as f32],+ _pad: [0.0, 0.0],+ };+ self.queue+ .write_buffer(&self.dab_uniform_buf, 0, bytemuck::bytes_of(&dab_uniforms));+ self.queue+ .write_buffer(&self.dab_instance_buf, 0, bytemuck::cast_slice(pending_dabs));+ }++ // Upload viewport uniforms (exact match to formatArtboardTransform)+ let vp_uniforms = ViewportUniforms {+ viewport_size_phys: [vp_w as f32, vp_h as f32],+ doc_size: [self.doc_width as f32, self.doc_height as f32],+ pan_css: [camera.pan_x, camera.pan_y],+ zoom: camera.zoom.max(0.01),+ rotation_rad: camera.rotation.to_radians(),+ flip: [+ if camera.flip_x { -1.0 } else { 1.0 },+ if camera.flip_y { -1.0 } else { 1.0 },+ ],+ dpr: viewport.safe_dpr(),+ show_checkerboard: u32::from(show_checkerboard),+ matte_color,+ };+ self.queue.write_buffer(+ &self.viewport_uniform_buf,+ 0,+ bytemuck::bytes_of(&vp_uniforms),+ );++ // Upload GPU brush cursor ring uniforms+ let dpr = viewport.safe_dpr();+ let show_cursor = cursor_cfg.visible && !cursor_suppressed && cursor_local_phys.is_some();+ let (cx_phys, cy_phys) = cursor_local_phys.unwrap_or((-1000.0, -1000.0));+ let diam_css = (cursor_cfg.size * camera.zoom.max(0.01)).max(4.0);+ let thick = cursor_cfg.thickness_ratio.clamp(0.05, 1.0);+ let (w_css, h_css) = if cursor_cfg.thickness_vertical {+ (diam_css * thick, diam_css)+ } else {+ (diam_css, diam_css * thick)+ };+ let flip_sign = if camera.flip_x ^ camera.flip_y { -1.0 } else { 1.0 };+ let total_angle_rad = (camera.rotation + flip_sign * cursor_cfg.tip_angle_deg).to_radians();++ let cursor_uniforms = CursorUniforms {+ viewport_size_phys: [vp_w as f32, vp_h as f32],+ center_phys: [cx_phys, cy_phys],+ half_extents_phys: [(w_css * 0.5 * dpr).max(2.0), (h_css * 0.5 * dpr).max(2.0)],+ angle_rad: total_angle_rad,+ dpr,+ is_square: u32::from(cursor_cfg.is_square),+ visible: u32::from(show_cursor),+ _pad: [0, 0],+ };+ self.queue.write_buffer(+ &self.cursor_uniform_buf,+ 0,+ bytemuck::bytes_of(&cursor_uniforms),+ );++ // Acquire swapchain frame (waits on DXGI waitable latency object = 1)+ let acquired_surface_tex = match &self.output {+ OutputTarget::Surface {+ surface,+ configured,+ ..+ } => {+ if !*configured {+ return RenderOutcome::NeedsReconfigure;+ }+ match surface.get_current_texture() {+ wgpu::CurrentSurfaceTexture::Success(tex)+ | wgpu::CurrentSurfaceTexture::Suboptimal(tex) => Some(tex),+ wgpu::CurrentSurfaceTexture::Timeout+ | wgpu::CurrentSurfaceTexture::Occluded => return RenderOutcome::Skipped,+ wgpu::CurrentSurfaceTexture::Outdated => {+ return RenderOutcome::NeedsReconfigure;+ }+ wgpu::CurrentSurfaceTexture::Lost+ | wgpu::CurrentSurfaceTexture::Validation => {+ return RenderOutcome::DeviceLost;+ }+ }+ }+ OutputTarget::Headless { .. } => None,+ };++ let surface_view_owned;+ let target_view: &wgpu::TextureView = match (&acquired_surface_tex, &self.output) {+ (Some(tex), _) => {+ surface_view_owned = tex+ .texture+ .create_view(&wgpu::TextureViewDescriptor::default());+ &surface_view_owned+ }+ (None, OutputTarget::Headless { view, .. }) => view,+ _ => return RenderOutcome::Skipped,+ };++ let mut encoder = self+ .device+ .create_command_encoder(&wgpu::CommandEncoderDescriptor {+ label: Some("ink-frame-encoder"),+ });++ // Pass 1: Stamp new brush dabs into the GPU document canvas texture+ if !pending_dabs.is_empty() {+ let mut dab_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {+ label: Some("ink-dab-pass"),+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {+ view: &self.doc_view,+ depth_slice: None,+ resolve_target: None,+ ops: wgpu::Operations {+ load: wgpu::LoadOp::Load,+ store: wgpu::StoreOp::Store,+ },+ })],+ depth_stencil_attachment: None,+ timestamp_writes: None,+ occlusion_query_set: None,+ multiview_mask: None,+ });+ dab_pass.set_pipeline(if dabs_are_eraser {+ &self.dab_erase_pipeline+ } else {+ &self.dab_paint_pipeline+ });+ dab_pass.set_bind_group(0, &self.dab_bind_group, &[]);+ dab_pass.set_vertex_buffer(0, self.dab_instance_buf.slice(..));+ dab_pass.draw(0..6, 0..(pending_dabs.len() as u32));+ }++ // Pass 2: Composite matte + artboard shadow/border + checkerboard + doc texture + GPU cursor+ {+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {+ label: Some("ink-viewport-composite-pass"),+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {+ view: target_view,+ depth_slice: None,+ resolve_target: None,+ ops: wgpu::Operations {+ load: wgpu::LoadOp::Clear(wgpu::Color {+ r: matte_color[0] as f64,+ g: matte_color[1] as f64,+ b: matte_color[2] as f64,+ a: 1.0,+ }),+ store: wgpu::StoreOp::Store,+ },+ })],+ depth_stencil_attachment: None,+ timestamp_writes: None,+ occlusion_query_set: None,+ multiview_mask: None,+ });++ pass.set_pipeline(&self.viewport_pipeline);+ pass.set_bind_group(0, &self.viewport_bind_group, &[]);+ pass.draw(0..3, 0..1);++ if show_cursor {+ pass.set_pipeline(&self.cursor_pipeline);+ pass.set_bind_group(0, &self.cursor_bind_group, &[]);+ pass.draw(0..6, 0..1);+ }+ }++ self.queue.submit(Some(encoder.finish()));++ if let Some(frame) = acquired_surface_tex {+ self.queue.present(frame);+ } else {+ let _ = self.device.poll(wgpu::PollType::wait_indefinitely());+ }++ // Keep references alive through instance/adapter fields+ let _ = (&self.instance, &self.adapter, &self.doc_texture);++ RenderOutcome::Presented+ }+}diff --git a/crates/ink-engine/src/history/mod.rs b/crates/ink-engine/src/history/mod.rsnew file mode 100644index 0000000..f4d680a--- /dev/null+++ b/crates/ink-engine/src/history/mod.rs@@ -0,0 +1,517 @@+//! Copy-on-Write (`Arc<TileData>`) Undo/Redo & Collaborative Selective Undo Engine.+//!+//! All raster & mask tile snapshots live exclusively in Rust via `Arc<TileData>` so+//! untouched tiles cost O(1) memory and undo/redo swaps pointers instantaneously.+//! Only compact [`HistoryItemMeta`] structs are ever serialized to React.++use crate::document::types::{CanvasDimensions, LayerId, LayerNodeMeta};+use crate::tiles::{CowTileDelta, SparseLayerGrid, TileKind};+use serde::{Deserialize, Serialize};+use std::collections::HashSet;+use std::sync::atomic::{AtomicU64, Ordering};++static NEXT_HISTORY_SEQ: AtomicU64 = AtomicU64::new(1);++pub fn next_history_id(prefix: &str, now_ms: u64) -> String {+ let seq = NEXT_HISTORY_SEQ.fetch_add(1, Ordering::Relaxed);+ format!("{prefix}-{now_ms}-{seq}")+}++/// Formats epoch milliseconds as `HH:MM:SS` (UTC-local compact label for History panel).+pub fn format_time_hms(timestamp_ms: u64) -> String {+ let total_secs = timestamp_ms / 1000;+ let secs = total_secs % 60;+ let mins = (total_secs / 60) % 60;+ let hours = (total_secs / 3600) % 24;+ format!("{hours:02}:{mins:02}:{secs:02}")+}++/// Current epoch timestamp in milliseconds.+pub fn unix_now_ms() -> u64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_millis() as u64)+ .unwrap_or(0)+}++/// Compact history entry metadata sent across IPC to React (NEVER carries full-res pixel buffers!).+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct HistoryItemMeta {+ pub id: String,+ #[serde(rename = "type")]+ pub action_type: String,+ pub label: String,+ pub timestamp: u64,+ pub time_formatted: String,+ pub thumbnail_url: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub layer_id: Option<LayerId>,+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub undone: bool,+}++/// Compact history state payload returned to React after any history mutation.+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct HistoryStateSnapshot {+ pub entries: Vec<HistoryItemMeta>,+ pub index: i32,+ pub can_undo: bool,+ pub can_redo: bool,+}++/// CoW snapshot of a layer tree mutation (add, delete, reorder, merge, properties, masks).+#[derive(Debug, Clone)]+pub struct LayerTreeMutation {+ pub before_layers: Vec<LayerNodeMeta>,+ pub after_layers: Vec<LayerNodeMeta>,+ pub before_active_layer_id: Option<LayerId>,+ pub after_active_layer_id: Option<LayerId>,+ /// O(1) CoW grid snapshots of layers removed or modified structurally before the op.+ pub before_grids: Vec<(LayerId, SparseLayerGrid)>,+ /// O(1) CoW grid snapshots of layers added or modified structurally after the op.+ pub after_grids: Vec<(LayerId, SparseLayerGrid)>,+ /// Optional key to coalesce rapid continuous slider edits (opacity, screentone, etc.)+ /// within an 800 ms window into a single undo entry.+ pub coalesce_key: Option<String>,+}++/// Atomic CoW delta for document-wide canvas resize/crop operations.+#[derive(Debug, Clone)]+pub struct CanvasResizeDelta {+ pub before_dimensions: CanvasDimensions,+ pub after_dimensions: CanvasDimensions,+ pub before_grids: Vec<(LayerId, SparseLayerGrid)>,+ pub after_grids: Vec<(LayerId, SparseLayerGrid)>,+}++/// Full Rust-side CoW history entry (kept strictly in Rust memory; only `meta` crosses IPC).+#[derive(Debug, Clone)]+pub struct HistoryEntry {+ pub meta: HistoryItemMeta,+ pub tile_deltas: Vec<CowTileDelta>,+ pub layer_tree_delta: Option<LayerTreeMutation>,+ pub canvas_resize_delta: Option<CanvasResizeDelta>,+ /// Arbitrary non-raster document state delta (rulers, animation, selection) for UI sync.+ pub document_state_delta: Option<serde_json::Value>,+ pub peer_id: Option<String>,+ pub stroke_id: Option<String>,+ pub is_mask_edit: bool,+}++/// Result returned from collaborative selective undo/redo.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SelectiveUndoOutcome {+ pub applied: bool,+ pub stroke_id: Option<String>,+ pub layer_id: Option<LayerId>,+ pub contested_tile_count: usize,+ pub preserved_peer_edits: bool,+ pub history: HistoryStateSnapshot,+}++/// Result of applying an undo/redo/jump step on a document.+#[derive(Debug, Clone)]+pub struct AppliedHistoryChange {+ pub changed_layer_ids: HashSet<LayerId>,+ pub dimensions_changed: bool,+ pub layers_changed: bool,+ pub document_state_delta: Option<serde_json::Value>,+}++/// Per-document Copy-on-Write Undo/Redo stack supporting linear history, slider coalescing,+/// and collaborative selective undo/redo tombstones.+#[derive(Debug, Clone)]+pub struct HistoryStack {+ entries: Vec<HistoryEntry>,+ index: isize,+ local_redo_stack: Vec<String>,+ max_steps: usize,+}++impl Default for HistoryStack {+ fn default() -> Self {+ Self::new(50)+ }+}++impl HistoryStack {+ pub fn new(max_steps: usize) -> Self {+ Self {+ entries: Vec::new(),+ index: -1,+ local_redo_stack: Vec::new(),+ max_steps: max_steps.clamp(10, 200),+ }+ }++ pub fn set_max_steps(&mut self, max_steps: usize) {+ self.max_steps = max_steps.clamp(10, 200);+ self.enforce_max_steps();+ }++ pub fn max_steps(&self) -> usize {+ self.max_steps+ }++ pub fn len(&self) -> usize {+ self.entries.len()+ }++ pub fn is_empty(&self) -> bool {+ self.entries.is_empty()+ }++ pub fn index(&self) -> isize {+ self.index+ }++ pub fn entries(&self) -> &[HistoryEntry] {+ &self.entries+ }++ pub fn entries_mut(&mut self) -> &mut [HistoryEntry] {+ &mut self.entries+ }++ /// Resets the history stack with a single `"initial"` baseline entry.+ pub fn reset_with_initial(+ &mut self,+ label: impl Into<String>,+ layer_id: Option<LayerId>,+ thumbnail_url: String,+ ) {+ let now = unix_now_ms();+ self.entries.clear();+ self.local_redo_stack.clear();+ self.entries.push(HistoryEntry {+ meta: HistoryItemMeta {+ id: next_history_id("hist-init", now),+ action_type: "initial".to_string(),+ label: label.into(),+ timestamp: now,+ time_formatted: format_time_hms(now),+ thumbnail_url,+ layer_id,+ undone: false,+ },+ tile_deltas: Vec::new(),+ layer_tree_delta: None,+ canvas_resize_delta: None,+ document_state_delta: None,+ peer_id: None,+ stroke_id: None,+ is_mask_edit: false,+ });+ self.index = 0;+ }++ /// Ensures an initial entry exists before pushing edits.+ pub fn ensure_initial(&mut self, layer_id: Option<LayerId>) {+ if self.entries.is_empty() {+ self.reset_with_initial("New Document", layer_id, String::new());+ }+ }++ /// Pushes a new CoW history entry, honoring slider `coalesce_key` (800ms window),+ /// linear redo-branch truncation for local edits, non-destructive append for remote peers,+ /// and `max_steps` eviction.+ pub fn push(&mut self, entry: HistoryEntry) {+ if self.entries.is_empty() && entry.meta.action_type != "initial" {+ self.ensure_initial(entry.meta.layer_id.clone());+ }++ let is_remote = entry+ .peer_id+ .as_deref()+ .map(|p| !p.is_empty() && p != "local")+ .unwrap_or(false);++ // Coalesce rapid continuous property slider edits (<= 800ms window)+ if !is_remote+ && entry.tile_deltas.is_empty()+ && entry.canvas_resize_delta.is_none()+ && self.index >= 0+ && (self.index as usize) + 1 == self.entries.len()+ {+ if let Some(ref incoming_tree) = entry.layer_tree_delta {+ if let Some(ref key) = incoming_tree.coalesce_key {+ let top = &mut self.entries[self.index as usize];+ let same_key = top+ .layer_tree_delta+ .as_ref()+ .and_then(|t| t.coalesce_key.as_deref())+ == Some(key.as_str());+ if same_key+ && top.tile_deltas.is_empty()+ && entry.meta.timestamp.saturating_sub(top.meta.timestamp) <= 800+ {+ top.meta.label = entry.meta.label;+ top.meta.timestamp = entry.meta.timestamp;+ top.meta.time_formatted = entry.meta.time_formatted;+ if let Some(ref mut top_tree) = top.layer_tree_delta {+ top_tree.after_layers = incoming_tree.after_layers.clone();+ top_tree.after_active_layer_id =+ incoming_tree.after_active_layer_id.clone();+ top_tree.after_grids = incoming_tree.after_grids.clone();+ }+ return;+ }+ }+ }+ }++ if is_remote {+ // Remote steps append without discarding local user's collaborative redo stack+ self.entries.push(entry);+ self.index = self.entries.len() as isize - 1;+ } else {+ self.local_redo_stack.clear();+ let keep_len = (self.index + 1).max(0) as usize;+ if keep_len < self.entries.len() {+ self.entries.truncate(keep_len);+ }+ // Drop any previously selectively-undone local tombstones when local user draws anew+ self.entries.retain(|it| {+ let is_local = it+ .peer_id+ .as_deref()+ .map(|p| p.is_empty() || p == "local")+ .unwrap_or(true);+ !(it.meta.undone && is_local)+ });+ self.entries.push(entry);+ self.index = self.entries.len() as isize - 1;+ }++ self.enforce_max_steps();+ }++ fn enforce_max_steps(&mut self) {+ while self.entries.len() > self.max_steps {+ let removed = self.entries.remove(0);+ if !self.local_redo_stack.is_empty() {+ self.local_redo_stack.retain(|id| id != &removed.meta.id);+ }+ self.index = (self.index - 1).max(0);+ }+ if self.entries.is_empty() {+ self.index = -1;+ } else if self.index >= self.entries.len() as isize {+ self.index = self.entries.len() as isize - 1;+ }+ }++ /// Returns true if a collaborative selective-undo tombstone or remote peer is present.+ fn has_selective_state(&self) -> bool {+ !self.local_redo_stack.is_empty()+ || self.entries.iter().any(|e| {+ e.meta.undone+ || e.peer_id+ .as_deref()+ .map(|p| !p.is_empty() && p != "local")+ .unwrap_or(false)+ })+ }++ /// Builds compact metadata snapshot for React UI (zero pixel buffers!).+ pub fn snapshot(&self) -> HistoryStateSnapshot {+ let len = self.entries.len();+ let idx = self.index;+ let (can_undo, can_redo) = if self.has_selective_state() {+ let max_i = idx.min(len as isize - 1);+ let has_undoable_local = if max_i >= 1 {+ (1..=max_i as usize).rev().any(|i| {+ let e = &self.entries[i];+ let is_local = e+ .peer_id+ .as_deref()+ .map(|p| p.is_empty() || p == "local")+ .unwrap_or(true);+ e.meta.action_type != "initial" && !e.meta.undone && is_local+ })+ } else {+ false+ };+ let has_forward_local = idx >= 0+ && ((idx + 1) as usize) < len+ && self.entries[(idx + 1) as usize]+ .peer_id+ .as_deref()+ .map(|p| p.is_empty() || p == "local")+ .unwrap_or(true);+ (+ has_undoable_local,+ !self.local_redo_stack.is_empty() || has_forward_local,+ )+ } else {+ (idx > 0, idx >= 0 && ((idx + 1) as usize) < len)+ };++ HistoryStateSnapshot {+ entries: self.entries.iter().map(|e| e.meta.clone()).collect(),+ index: idx as i32,+ can_undo,+ can_redo,+ }+ }++ /// Advances or rewinds `index` to `target_index`, returning the ordered list of+ /// `(entry_index, is_undo)` transitions to apply to the document.+ pub fn plan_jump(&mut self, target_index: usize) -> Vec<(usize, bool)> {+ if self.entries.is_empty() || target_index >= self.entries.len() {+ return Vec::new();+ }+ let cur = self.index.max(0) as usize;+ if target_index == cur {+ return Vec::new();+ }+ let mut steps = Vec::new();+ if target_index < cur {+ for i in ((target_index + 1)..=cur).rev() {+ steps.push((i, true));+ }+ } else {+ for i in (cur + 1)..=target_index {+ steps.push((i, false));+ }+ }+ self.index = target_index as isize;+ steps+ }++ /// Finds the target entry index for collaborative selective undo without splicing it out.+ /// Marks the entry `undone = true` (tombstone) and records it on `local_redo_stack` if local.+ pub fn find_and_mark_selective_undo(+ &mut self,+ peer_id: Option<&str>,+ stroke_id: Option<&str>,+ ) -> Option<usize> {+ if self.entries.is_empty() || self.index < 1 {+ return None;+ }+ let max_i = (self.index as usize).min(self.entries.len() - 1);+ let is_local_req = peer_id.map(|p| p.is_empty() || p == "local").unwrap_or(true);++ let mut target_idx = None;+ // 1. Exact stroke_id match when provided+ if let Some(sid) = stroke_id {+ for i in (1..=max_i).rev() {+ let e = &self.entries[i];+ if e.meta.action_type != "initial"+ && !e.meta.undone+ && e.stroke_id.as_deref() == Some(sid)+ {+ target_idx = Some(i);+ break;+ }+ }+ }++ // 2. Fallback to most recent active step matching peer_id+ if target_idx.is_none() && stroke_id.is_none() {+ for i in (1..=max_i).rev() {+ let e = &self.entries[i];+ if e.meta.action_type == "initial" || e.meta.undone {+ continue;+ }+ let matches = match peer_id {+ None => true,+ Some("local") | Some("") => e+ .peer_id+ .as_deref()+ .map(|p| p.is_empty() || p == "local")+ .unwrap_or(true),+ Some(pid) => e.peer_id.as_deref() == Some(pid),+ };+ if matches {+ target_idx = Some(i);+ break;+ }+ }+ }++ let idx = target_idx?;+ self.entries[idx].meta.undone = true;+ if is_local_req {+ self.local_redo_stack.push(self.entries[idx].meta.id.clone());+ }+ Some(idx)+ }++ /// Finds and unmarks the most recent selectively-undone tombstone for `peer_id`.+ pub fn find_and_unmark_selective_redo(&mut self, peer_id: Option<&str>) -> Option<usize> {+ let is_local_req = peer_id.map(|p| p.is_empty() || p == "local").unwrap_or(true);+ if is_local_req {+ while let Some(candidate_id) = self.local_redo_stack.pop() {+ if let Some(idx) = self+ .entries+ .iter()+ .position(|e| e.meta.id == candidate_id && e.meta.undone)+ {+ self.entries[idx].meta.undone = false;+ return Some(idx);+ }+ }+ }+ // Fallback scan for remote peer or unstacked tombstone+ let idx = self.entries.iter().rposition(|e| {+ if !e.meta.undone {+ return false;+ }+ match peer_id {+ None => true,+ Some("local") | Some("") => e+ .peer_id+ .as_deref()+ .map(|p| p.is_empty() || p == "local")+ .unwrap_or(true),+ Some(pid) => e.peer_id.as_deref() == Some(pid),+ }+ })?;+ self.entries[idx].meta.undone = false;+ Some(idx)+ }++ /// Updates the thumbnail URL on the most recent matching history entry (called asynchronously+ /// after background thumbnail generation).+ pub fn update_entry_thumbnail(&mut self, entry_id: &str, thumbnail_url: String) {+ if let Some(e) = self.entries.iter_mut().rev().find(|e| e.meta.id == entry_id) {+ e.meta.thumbnail_url = thumbnail_url;+ }+ }++ /// Collects references to every `Arc<TileData>` retained by this history stack (for accurate+ /// deduplicated memory accounting).+ pub fn collect_tile_refs<'a>(&'a self, out: &mut Vec<&'a std::sync::Arc<crate::tiles::TileData>>) {+ for e in &self.entries {+ for d in &e.tile_deltas {+ if let Some(ref b) = d.before {+ out.push(b);+ }+ if let Some(ref a) = d.after {+ out.push(a);+ }+ }+ if let Some(ref lt) = e.layer_tree_delta {+ for (_, g) in lt.before_grids.iter().chain(lt.after_grids.iter()) {+ out.extend(g.tiles.values());+ out.extend(g.mask_tiles.values());+ }+ }+ if let Some(ref cr) = e.canvas_resize_delta {+ for (_, g) in cr.before_grids.iter().chain(cr.after_grids.iter()) {+ out.extend(g.tiles.values());+ out.extend(g.mask_tiles.values());+ }+ }+ }+ }++ /// Utility: returns whether a tile delta touches raster vs mask plane.+ pub fn delta_touches_mask(delta: &CowTileDelta) -> bool {+ delta.kind == TileKind::Mask+ }+}diff --git a/crates/ink-engine/src/hit_test.rs b/crates/ink-engine/src/hit_test.rsnew file mode 100644index 0000000..bf34b01--- /dev/null+++ b/crates/ink-engine/src/hit_test.rs@@ -0,0 +1,229 @@+//! Thread-safe physical-pixel hit-test region and UI occlusion mask.+//!+//! Shared between the native input hooks (`tablet_input.rs`, Win32 nav hook) and+//! `ink-engine` so pointer-down routing happens in-process with zero IPC latency.++use crate::types::{InteractionPolicy, UiRect, ViewportRect};+use std::sync::{Arc, RwLock};++#[derive(Debug, Clone, Default)]+pub struct HitTestState {+ pub viewport: ViewportRect,+ pub occluded_rects: Vec<UiRect>,+ pub visible: bool,+ pub policy: InteractionPolicy,+}++impl HitTestState {+ /// Returns `true` if `(phys_x, phys_y)` lands inside the visible canvas viewport+ /// and is NOT covered by any occluded UI element (modal, popover, floating panel,+ /// `FloatingBrushPill`, context menu, etc.).+ #[inline]+ pub fn is_unoccluded_canvas_point(&self, phys_x: f32, phys_y: f32) -> bool {+ if !self.visible || self.policy.modal_open || self.policy.workspace_interacting {+ return false;+ }+ if !self.viewport.contains_phys(phys_x, phys_y) {+ return false;+ }+ for rect in &self.occluded_rects {+ if rect.contains(phys_x, phys_y) {+ return false;+ }+ }+ true+ }++ /// Returns `true` if a stylus/pointer-down at `(phys_x, phys_y)` should be captured+ /// natively by `ink-engine` for zero-IPC brush/eraser rendering.+ #[inline]+ pub fn should_capture_native_stroke(&self, phys_x: f32, phys_y: f32) -> bool {+ self.policy.native_stroke_enabled+ && self.policy.active_tool.is_native_stroke_tool()+ && self.is_unoccluded_canvas_point(phys_x, phys_y)+ }++ /// Returns `true` if a navigation wheel/drag event at `(phys_x, phys_y)` should+ /// drive native 120–240 Hz GPU camera navigation directly in Rust.+ #[inline]+ pub fn should_capture_native_nav(&self, phys_x: f32, phys_y: f32) -> bool {+ !self.policy.text_input_focused && self.is_unoccluded_canvas_point(phys_x, phys_y)+ }+}++/// Shared concurrent snapshot of viewport bounds, occlusion rects, and interaction policy.+#[derive(Debug, Clone, Default)]+pub struct SharedHitTest {+ inner: Arc<RwLock<HitTestState>>,+}++impl SharedHitTest {+ pub fn new() -> Self {+ Self::default()+ }++ pub fn set_viewport(&self, viewport: ViewportRect) {+ if let Ok(mut guard) = self.inner.write() {+ guard.viewport = viewport;+ }+ }++ pub fn set_occluded_rects(&self, rects: Vec<UiRect>) {+ if let Ok(mut guard) = self.inner.write() {+ guard.occluded_rects = rects;+ }+ }++ pub fn set_visible(&self, visible: bool) {+ if let Ok(mut guard) = self.inner.write() {+ guard.visible = visible;+ }+ }++ pub fn set_policy(&self, policy: InteractionPolicy) {+ if let Ok(mut guard) = self.inner.write() {+ guard.policy = policy;+ }+ }++ pub fn snapshot(&self) -> HitTestState {+ self.inner+ .read()+ .map(|g| g.clone())+ .unwrap_or_default()+ }++ #[inline]+ pub fn is_unoccluded_canvas_point(&self, phys_x: f32, phys_y: f32) -> bool {+ self.inner+ .read()+ .map(|g| g.is_unoccluded_canvas_point(phys_x, phys_y))+ .unwrap_or(false)+ }++ #[inline]+ pub fn should_capture_native_stroke(&self, phys_x: f32, phys_y: f32) -> bool {+ self.inner+ .read()+ .map(|g| g.should_capture_native_stroke(phys_x, phys_y))+ .unwrap_or(false)+ }++ #[inline]+ pub fn should_capture_native_nav(&self, phys_x: f32, phys_y: f32) -> bool {+ self.inner+ .read()+ .map(|g| g.should_capture_native_nav(phys_x, phys_y))+ .unwrap_or(false)+ }++ #[inline]+ pub fn wheel_mode(&self) -> crate::types::WheelNavMode {+ self.inner+ .read()+ .map(|g| g.policy.wheel_mode)+ .unwrap_or_default()+ }++ #[inline]+ pub fn text_input_focused(&self) -> bool {+ self.inner+ .read()+ .map(|g| g.policy.text_input_focused)+ .unwrap_or(false)+ }++ /// Non-blocking hit-test helpers for low-level Win32 hooks (`WH_MOUSE_LL`) that must+ /// return within microseconds and never contend on a write lock.+ #[inline]+ pub fn try_is_unoccluded_canvas_point(&self, phys_x: f32, phys_y: f32) -> bool {+ self.inner+ .try_read()+ .map(|g| g.is_unoccluded_canvas_point(phys_x, phys_y))+ .unwrap_or(false)+ }++ #[inline]+ pub fn try_should_capture_native_stroke(&self, phys_x: f32, phys_y: f32) -> bool {+ self.inner+ .try_read()+ .map(|g| g.should_capture_native_stroke(phys_x, phys_y))+ .unwrap_or(false)+ }++ #[inline]+ pub fn try_should_capture_native_nav(&self, phys_x: f32, phys_y: f32) -> bool {+ self.inner+ .try_read()+ .map(|g| g.should_capture_native_nav(phys_x, phys_y))+ .unwrap_or(false)+ }++ #[inline]+ pub fn try_wheel_mode(&self) -> crate::types::WheelNavMode {+ self.inner+ .try_read()+ .map(|g| g.policy.wheel_mode)+ .unwrap_or_default()+ }++ #[inline]+ pub fn try_text_input_focused(&self) -> bool {+ self.inner+ .try_read()+ .map(|g| g.policy.text_input_focused)+ .unwrap_or(false)+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::types::NativeToolKind;++ #[test]+ fn test_occlusion_mask_blocks_floating_ui_and_allows_canvas() {+ let ht = SharedHitTest::new();+ ht.set_visible(true);+ ht.set_viewport(ViewportRect {+ x_px: 200,+ y_px: 80,+ width_px: 1000,+ height_px: 700,+ dpr: 1.5,+ });+ // FloatingBrushPill on left edge of canvas viewport+ ht.set_occluded_rects(vec![UiRect {+ x: 212.0,+ y: 280.0,+ width: 48.0,+ height: 260.0,+ }]);++ // Inside unoccluded canvas -> allowed+ assert!(ht.should_capture_native_stroke(600.0, 400.0));+ // Inside FloatingBrushPill -> blocked+ assert!(!ht.should_capture_native_stroke(230.0, 350.0));+ // Outside viewport (left dock) -> blocked+ assert!(!ht.should_capture_native_stroke(100.0, 400.0));++ // Non-native tool (e.g. text/pen) -> stroke blocked, nav still allowed+ ht.set_policy(InteractionPolicy {+ active_tool: NativeToolKind::Other,+ native_stroke_enabled: true,+ ..Default::default()+ });+ assert!(!ht.should_capture_native_stroke(600.0, 400.0));+ assert!(ht.should_capture_native_nav(600.0, 400.0));++ // Modal open -> both blocked+ ht.set_policy(InteractionPolicy {+ active_tool: NativeToolKind::Brush,+ native_stroke_enabled: true,+ modal_open: true,+ ..Default::default()+ });+ assert!(!ht.should_capture_native_stroke(600.0, 400.0));+ assert!(!ht.should_capture_native_nav(600.0, 400.0));+ }+}diff --git a/crates/ink-engine/src/io/compositor_cpu.rs b/crates/ink-engine/src/io/compositor_cpu.rsnew file mode 100644index 0000000..0eb9036--- /dev/null+++ b/crates/ink-engine/src/io/compositor_cpu.rs@@ -0,0 +1,513 @@+//! Sparse-tile software compositor for 64×64 layer/mask thumbnails, `.ink` previews,+//! timelapse keyframes (`720p`/`1080p`/`2k`/`4k`), and CPU layer merges.+//!+//! Operates directly on populated sparse tiles without allocating full-resolution canvases+//! when rendering downscaled thumbnails or previews.++use crate::document::{BlendMode, Document, LayerNode, LayerType};+use crate::memory::ScratchBackend;+use crate::tiles::{parse_hex_rgba8, RectI32, TileStorage, TILE_SIZE, TILE_SIZE_I32};++#[inline]+fn blend_channel(mode: BlendMode, cb: f32, cs: f32) -> f32 {+ match mode {+ BlendMode::Normal | BlendMode::PassThrough => cs,+ BlendMode::Multiply => cb * cs,+ BlendMode::Screen => cb + cs - cb * cs,+ BlendMode::Overlay => {+ if cb <= 0.5 {+ 2.0 * cb * cs+ } else {+ 1.0 - 2.0 * (1.0 - cb) * (1.0 - cs)+ }+ }+ BlendMode::Darken | BlendMode::DarkerColor => cb.min(cs),+ BlendMode::Lighten | BlendMode::LighterColor => cb.max(cs),+ BlendMode::ColorDodge | BlendMode::ColorDodgeGlow => {+ if cs >= 0.999 {+ 1.0+ } else {+ (cb / (1.0 - cs)).min(1.0)+ }+ }+ BlendMode::ColorBurn => {+ if cs <= 0.001 {+ 0.0+ } else {+ (1.0 - ((1.0 - cb) / cs).min(1.0)).max(0.0)+ }+ }+ BlendMode::LinearBurn => (cb + cs - 1.0).max(0.0),+ BlendMode::AddGlow => (cb + cs).min(1.0),+ BlendMode::HardLight => {+ if cs <= 0.5 {+ 2.0 * cb * cs+ } else {+ 1.0 - 2.0 * (1.0 - cb) * (1.0 - cs)+ }+ }+ BlendMode::SoftLight => {+ if cs <= 0.5 {+ cb - (1.0 - 2.0 * cs) * cb * (1.0 - cb)+ } else {+ let d = if cb <= 0.25 {+ ((16.0 * cb - 12.0) * cb + 4.0) * cb+ } else {+ cb.sqrt()+ };+ cb + (2.0 * cs - 1.0) * (d - cb)+ }+ }+ BlendMode::Difference => (cb - cs).abs(),+ BlendMode::Exclusion => cb + cs - 2.0 * cb * cs,+ BlendMode::Subtract => (cb - cs).max(0.0),+ BlendMode::Divide => {+ if cs <= 0.001 {+ 1.0+ } else {+ (cb / cs).min(1.0)+ }+ }+ BlendMode::VividLight => {+ if cs <= 0.5 {+ let s2 = (2.0 * cs).max(0.001);+ (1.0 - (1.0 - cb) / s2).clamp(0.0, 1.0)+ } else {+ let s2 = (2.0 * (1.0 - cs)).max(0.001);+ (cb / s2).clamp(0.0, 1.0)+ }+ }+ BlendMode::LinearLight => (cb + 2.0 * cs - 1.0).clamp(0.0, 1.0),+ BlendMode::PinLight => {+ if cs <= 0.5 {+ cb.min(2.0 * cs)+ } else {+ cb.max(2.0 * cs - 1.0)+ }+ }+ BlendMode::HardMix => {+ if cb + cs >= 1.0 {+ 1.0+ } else {+ 0.0+ }+ }+ BlendMode::Hue | BlendMode::Saturation | BlendMode::Color | BlendMode::Luminosity => cs,+ }+}++/// Composites straight-alpha `src` over straight-alpha `dst` using `opacity` and `blend_mode`.+pub fn blend_rgba8_over(dst: &mut [u8], src: &[u8], opacity: f32, mode: BlendMode) {+ let op = opacity.clamp(0.0, 1.0);+ if op <= 0.001 {+ return;+ }+ for (d, s) in dst.chunks_exact_mut(4).zip(src.chunks_exact(4)) {+ let sa = (s[3] as f32 / 255.0) * op;+ if sa <= 0.001 {+ continue;+ }+ let da = d[3] as f32 / 255.0;+ let sr = s[0] as f32 / 255.0;+ let sg = s[1] as f32 / 255.0;+ let sb = s[2] as f32 / 255.0;++ if da <= 0.001 {+ d[0] = s[0];+ d[1] = s[1];+ d[2] = s[2];+ d[3] = (sa * 255.0 + 0.5).clamp(0.0, 255.0) as u8;+ continue;+ }++ let dr = d[0] as f32 / 255.0;+ let dg = d[1] as f32 / 255.0;+ let db = d[2] as f32 / 255.0;++ let br = blend_channel(mode, dr, sr);+ let bg = blend_channel(mode, dg, sg);+ let bb = blend_channel(mode, db, sb);++ let out_a = sa + da * (1.0 - sa);+ if out_a <= 1e-5 {+ d.fill(0);+ continue;+ }++ // Standard W3C Compositing & Blending Level 1 formula+ let cr = (1.0 - sa) * da * dr + (1.0 - da) * sa * sr + da * sa * br;+ let cg = (1.0 - sa) * da * dg + (1.0 - da) * sa * sg + da * sa * bg;+ let cb = (1.0 - sa) * da * db + (1.0 - da) * sa * sb + da * sa * bb;++ d[0] = ((cr / out_a) * 255.0 + 0.5).clamp(0.0, 255.0) as u8;+ d[1] = ((cg / out_a) * 255.0 + 0.5).clamp(0.0, 255.0) as u8;+ d[2] = ((cb / out_a) * 255.0 + 0.5).clamp(0.0, 255.0) as u8;+ d[3] = (out_a * 255.0 + 0.5).clamp(0.0, 255.0) as u8;+ }+}++/// Computes aspect-ratio-preserving thumbnail dimensions fitting within `(max_w, max_h)`.+pub fn fit_thumbnail_dims(doc_w: u32, doc_h: u32, max_w: u32, max_h: u32) -> (u32, u32) {+ let dw = doc_w.max(1) as f64;+ let dh = doc_h.max(1) as f64;+ let scale = (max_w.max(1) as f64 / dw).min(max_h.max(1) as f64 / dh).min(1.0);+ let tw = (dw * scale).round().max(1.0) as u32;+ let th = (dh * scale).round().max(1.0) as u32;+ (tw, th)+}++/// Renders a downscaled RGBA8 thumbnail directly from a layer's populated sparse tiles+/// (zero full-canvas intermediate buffer!).+pub fn render_layer_thumbnail_rgba(+ layer: &LayerNode,+ doc_w: u32,+ doc_h: u32,+ max_w: u32,+ max_h: u32,+ scratch: Option<&dyn ScratchBackend>,+) -> Result<(u32, u32, Vec<u8>), String> {+ let (tw, th) = fit_thumbnail_dims(doc_w, doc_h, max_w, max_h);+ let mut out = vec![0u8; (tw as usize) * (th as usize) * 4];+ if layer.grid.tiles.is_empty() || doc_w == 0 || doc_h == 0 {+ return Ok((tw, th, out));+ }++ let tint = if layer.meta.layer_color_enabled.unwrap_or(false) {+ let primary = layer+ .meta+ .layer_color+ .as_deref()+ .and_then(parse_hex_rgba8)+ .unwrap_or([28, 115, 194, 255]);+ let sub = layer+ .meta+ .layer_sub_color+ .as_deref()+ .and_then(parse_hex_rgba8)+ .unwrap_or([255, 255, 255, 255]);+ Some((primary, sub))+ } else {+ None+ };++ let scale_x = tw as f64 / doc_w as f64;+ let scale_y = th as f64 / doc_h as f64;++ // Accumulate premultiplied RGBA + coverage weight per thumbnail pixel directly from populated tiles+ let pixel_count = (tw as usize) * (th as usize);+ let mut acc_r = vec![0.0f32; pixel_count];+ let mut acc_g = vec![0.0f32; pixel_count];+ let mut acc_b = vec![0.0f32; pixel_count];+ let mut acc_a = vec![0.0f32; pixel_count];+ let mut acc_w = vec![0.0f32; pixel_count];++ for (&coord, tile) in &layer.grid.tiles {+ let tile_x0 = coord.tx * TILE_SIZE_I32;+ let tile_y0 = coord.ty * TILE_SIZE_I32;+ let tile_x1 = tile_x0 + TILE_SIZE_I32;+ let tile_y1 = tile_y0 + TILE_SIZE_I32;+ if tile_x1 <= 0 || tile_y1 <= 0 || tile_x0 >= doc_w as i32 || tile_y0 >= doc_h as i32 {+ continue;+ }++ let start_lx = (-tile_x0).max(0) as usize;+ let start_ly = (-tile_y0).max(0) as usize;+ let end_lx = (doc_w as i32 - tile_x0).min(TILE_SIZE_I32) as usize;+ let end_ly = (doc_h as i32 - tile_y0).min(TILE_SIZE_I32) as usize;+ if start_lx >= end_lx || start_ly >= end_ly {+ continue;+ }++ // Stride sampling for huge canvases (keeps 600 DPI 70MP thumbnail under 1ms!)+ let stride_x = ((doc_w as usize) / (tw as usize * 2)).max(1);+ let stride_y = ((doc_h as usize) / (th as usize * 2)).max(1);++ if let TileStorage::SolidColor { rgba8, .. } = tile.storage {+ if rgba8[3] == 0 {+ continue;+ }+ let c = apply_layer_color_tint(rgba8, tint);+ let a = c[3] as f32 / 255.0;+ let pr = (c[0] as f32 / 255.0) * a;+ let pg = (c[1] as f32 / 255.0) * a;+ let pb = (c[2] as f32 / 255.0) * a;++ let ty_start = (((tile_y0 + start_ly as i32) as f64) * scale_y).floor().max(0.0) as usize;+ let ty_end = (((tile_y0 + end_ly as i32) as f64) * scale_y)+ .ceil()+ .min(th as f64) as usize;+ let tx_start = (((tile_x0 + start_lx as i32) as f64) * scale_x).floor().max(0.0) as usize;+ let tx_end = (((tile_x0 + end_lx as i32) as f64) * scale_x)+ .ceil()+ .min(tw as f64) as usize;+ for py in ty_start..ty_end {+ for px in tx_start..tx_end {+ let idx = py * (tw as usize) + px;+ acc_r[idx] += pr;+ acc_g[idx] += pg;+ acc_b[idx] += pb;+ acc_a[idx] += a;+ acc_w[idx] += 1.0;+ }+ }+ continue;+ }++ let tile_rgba = tile.to_rgba8(scratch, false)?;+ let mut ly = start_ly;+ while ly < end_ly {+ let doc_y = (tile_y0 + ly as i32) as f64;+ let py = (doc_y * scale_y).floor().clamp(0.0, (th - 1) as f64) as usize;+ let mut lx = start_lx;+ while lx < end_lx {+ let doc_x = (tile_x0 + lx as i32) as f64;+ let px = (doc_x * scale_x).floor().clamp(0.0, (tw - 1) as f64) as usize;+ let off = (ly * TILE_SIZE + lx) * 4;+ let raw_px = [+ tile_rgba[off],+ tile_rgba[off + 1],+ tile_rgba[off + 2],+ tile_rgba[off + 3],+ ];+ let idx = py * (tw as usize) + px;+ acc_w[idx] += 1.0;+ if raw_px[3] > 0 {+ let c = apply_layer_color_tint(raw_px, tint);+ let a = c[3] as f32 / 255.0;+ acc_r[idx] += (c[0] as f32 / 255.0) * a;+ acc_g[idx] += (c[1] as f32 / 255.0) * a;+ acc_b[idx] += (c[2] as f32 / 255.0) * a;+ acc_a[idx] += a;+ }+ lx += stride_x;+ }+ ly += stride_y;+ }+ }++ for i in 0..pixel_count {+ let w = acc_w[i];+ if w <= 0.0 || acc_a[i] <= 1e-4 {+ continue;+ }+ let avg_a = (acc_a[i] / w).clamp(0.0, 1.0);+ let off = i * 4;+ out[off] = ((acc_r[i] / acc_a[i]) * 255.0 + 0.5).clamp(0.0, 255.0) as u8;+ out[off + 1] = ((acc_g[i] / acc_a[i]) * 255.0 + 0.5).clamp(0.0, 255.0) as u8;+ out[off + 2] = ((acc_b[i] / acc_a[i]) * 255.0 + 0.5).clamp(0.0, 255.0) as u8;+ out[off + 3] = (avg_a * 255.0 + 0.5).clamp(0.0, 255.0) as u8;+ }++ Ok((tw, th, out))+}++/// Renders a downscaled RGBA8 thumbnail of a layer's non-destructive 8-bit mask.+pub fn render_mask_thumbnail_rgba(+ layer: &LayerNode,+ doc_w: u32,+ doc_h: u32,+ max_w: u32,+ max_h: u32,+ scratch: Option<&dyn ScratchBackend>,+) -> Result<(u32, u32, Vec<u8>), String> {+ let (tw, th) = fit_thumbnail_dims(doc_w, doc_h, max_w, max_h);+ let mut out = vec![0u8; (tw as usize) * (th as usize) * 4];+ for py in 0..th {+ let doc_y = ((py as f64 + 0.5) * (doc_h as f64 / th as f64))+ .floor()+ .clamp(0.0, (doc_h.saturating_sub(1)) as f64) as i32;+ for px in 0..tw {+ let doc_x = ((px as f64 + 0.5) * (doc_w as f64 / tw as f64))+ .floor()+ .clamp(0.0, (doc_w.saturating_sub(1)) as f64) as i32;+ let v = layer.grid.get_mask_alpha(doc_x, doc_y, scratch);+ let off = ((py * tw + px) as usize) * 4;+ out[off] = v;+ out[off + 1] = v;+ out[off + 2] = v;+ out[off + 3] = 255;+ }+ }+ Ok((tw, th, out))+}++/// Composites all visible layers of `doc` into a downscaled RGBA8 buffer fitting within `max_dim`+/// (with even dimensions when `max_dim >= 2` for video/timelapse encoder friendliness).+pub fn composite_document_downscaled_rgba(+ doc: &Document,+ max_dim: u32,+ fill_white_bg: bool,+ scratch: Option<&dyn ScratchBackend>,+) -> Result<(u32, u32, Vec<u8>), String> {+ let (out_w, out_h) = fit_thumbnail_dims(+ doc.dimensions.width,+ doc.dimensions.height,+ max_dim,+ max_dim,+ );+ let mut canvas = vec![0u8; (out_w as usize) * (out_h as usize) * 4];+ if fill_white_bg {+ for px in canvas.chunks_exact_mut(4) {+ px.copy_from_slice(&[255, 255, 255, 255]);+ }+ }++ // Iterate bottom-to-top (reverse of InkStudio's top-to-bottom stack)+ let mut last_base_alpha: Option<Vec<u8>> = None;+ for layer in doc.layers.iter().rev() {+ if layer.meta.layer_type.is_folder_like() || layer.meta.layer_type == LayerType::Adjustment+ {+ continue;+ }+ if !doc.is_layer_effectively_visible(&layer.meta.id) {+ if !layer.meta.clipped.unwrap_or(false) {+ last_base_alpha = None;+ }+ continue;+ }+ let eff_opacity = doc.effective_opacity(&layer.meta.id);+ if eff_opacity <= 0.001 || layer.grid.tiles.is_empty() {+ if !layer.meta.clipped.unwrap_or(false) {+ last_base_alpha = Some(vec![0u8; (out_w as usize) * (out_h as usize)]);+ }+ continue;+ }++ let (_, _, mut layer_rgba) = render_layer_thumbnail_rgba(+ layer,+ doc.dimensions.width,+ doc.dimensions.height,+ out_w,+ out_h,+ scratch,+ )?;++ // Apply non-destructive 8-bit layer mask+ if layer.grid.has_mask && layer.meta.mask_enabled.unwrap_or(true) {+ let (_, _, mask_rgba) = render_mask_thumbnail_rgba(+ layer,+ doc.dimensions.width,+ doc.dimensions.height,+ out_w,+ out_h,+ scratch,+ )?;+ for (px, mpx) in layer_rgba+ .chunks_exact_mut(4)+ .zip(mask_rgba.chunks_exact(4))+ {+ px[3] = ((u32::from(px[3]) * u32::from(mpx[0]) + 127) / 255) as u8;+ }+ }++ // Clip to base layer alpha if `clipped == true`+ if layer.meta.clipped.unwrap_or(false) {+ if let Some(ref base_a) = last_base_alpha {+ for (px, &ba) in layer_rgba.chunks_exact_mut(4).zip(base_a.iter()) {+ px[3] = ((u32::from(px[3]) * u32::from(ba) + 127) / 255) as u8;+ }+ } else {+ continue;+ }+ } else {+ last_base_alpha = Some(+ layer_rgba+ .chunks_exact(4)+ .map(|px| px[3])+ .collect(),+ );+ }++ blend_rgba8_over(&mut canvas, &layer_rgba, eff_opacity, layer.meta.blend_mode);+ }++ Ok((out_w, out_h, canvas))+}++/// Composites a full-resolution RGBA8 document buffer (used for exact rendering sync & tests).+pub fn composite_document_full_rgba(+ doc: &Document,+ scratch: Option<&dyn ScratchBackend>,+) -> Result<Vec<u8>, String> {+ let w = doc.dimensions.width;+ let h = doc.dimensions.height;+ let rect = RectI32::new(0, 0, w, h);+ let mut out = vec![0u8; (w as usize) * (h as usize) * 4];+ let mut last_base_alpha: Option<Vec<u8>> = None;++ for layer in doc.layers.iter().rev() {+ if layer.meta.layer_type.is_folder_like() || layer.meta.layer_type == LayerType::Adjustment+ {+ continue;+ }+ if !doc.is_layer_effectively_visible(&layer.meta.id) {+ if !layer.meta.clipped.unwrap_or(false) {+ last_base_alpha = None;+ }+ continue;+ }+ let eff_opacity = doc.effective_opacity(&layer.meta.id);+ if eff_opacity <= 0.001 || layer.grid.tiles.is_empty() {+ if !layer.meta.clipped.unwrap_or(false) {+ last_base_alpha = Some(vec![0u8; (w as usize) * (h as usize)]);+ }+ continue;+ }++ let mut layer_rgba = layer.grid.read_rgba8_rect(rect, false, scratch)?;+ if layer.meta.layer_color_enabled.unwrap_or(false) {+ let primary = layer+ .meta+ .layer_color+ .as_deref()+ .and_then(parse_hex_rgba8)+ .unwrap_or([28, 115, 194, 255]);+ let sub = layer+ .meta+ .layer_sub_color+ .as_deref()+ .and_then(parse_hex_rgba8)+ .unwrap_or([255, 255, 255, 255]);+ for px in layer_rgba.chunks_exact_mut(4) {+ if px[3] > 0 {+ let c = apply_layer_color_tint([px[0], px[1], px[2], px[3]], Some((primary, sub)));+ px.copy_from_slice(&c);+ }+ }+ }+ if layer.grid.has_mask && layer.meta.mask_enabled.unwrap_or(true) {+ let mask = layer.grid.read_mask8_rect(rect, scratch)?;+ for (px, &m) in layer_rgba.chunks_exact_mut(4).zip(mask.iter()) {+ px[3] = ((u32::from(px[3]) * u32::from(m) + 127) / 255) as u8;+ }+ }+ if layer.meta.clipped.unwrap_or(false) {+ if let Some(ref base_a) = last_base_alpha {+ for (px, &ba) in layer_rgba.chunks_exact_mut(4).zip(base_a.iter()) {+ px[3] = ((u32::from(px[3]) * u32::from(ba) + 127) / 255) as u8;+ }+ } else {+ continue;+ }+ } else {+ last_base_alpha = Some(layer_rgba.chunks_exact(4).map(|px| px[3]).collect());+ }++ blend_rgba8_over(&mut out, &layer_rgba, eff_opacity, layer.meta.blend_mode);+ }++ Ok(out)+}++#[inline]+fn apply_layer_color_tint(px: [u8; 4], tint: Option<([u8; 4], [u8; 4])>) -> [u8; 4] {+ let Some((primary, sub)) = tint else {+ return px;+ };+ let lum = (u32::from(px[0]) * 299 + u32::from(px[1]) * 587 + u32::from(px[2]) * 114) as f32+ / 255_000.0;+ let r = (primary[0] as f32 * (1.0 - lum) + sub[0] as f32 * lum + 0.5).clamp(0.0, 255.0) as u8;+ let g = (primary[1] as f32 * (1.0 - lum) + sub[1] as f32 * lum + 0.5).clamp(0.0, 255.0) as u8;+ let b = (primary[2] as f32 * (1.0 - lum) + sub[2] as f32 * lum + 0.5).clamp(0.0, 255.0) as u8;+ [r, g, b, px[3]]+}diff --git a/crates/ink-engine/src/io/ink_format.rs b/crates/ink-engine/src/io/ink_format.rsnew file mode 100644index 0000000..b6eb29c--- /dev/null+++ b/crates/ink-engine/src/io/ink_format.rs@@ -0,0 +1,780 @@+//! Direct Rust `.ink` v2 binary ZIP serializer and parser — reading and writing directly+//! from `ink-engine`'s sparse tile grids with Rayon multi-core parallel DEFLATE compression+//! and zero JS pixel transfers.+//!+//! 100% wire-compatible with InkStudio `.ink` v2 format (`src/utils/saveManager/inkSerialize.ts`+//! & `inkParse.ts`):+//! - `manifest.json`+//! - `preview.png` (stored without re-deflation)+//! - `tiles/<safeKey>/<tx>_<ty>.bin` (`[format:u8][version:u32 LE][dataLen:u32 LE][rawTileBytes]`)+//! - `masks/<safeKey>.bin` (`[width:u32 LE][height:u32 LE][alpha8Bytes]`)++use crate::document::{+ CanvasColorMode, CanvasDimensions, Document, ExpressionColor, LayerNode, LayerNodeMeta,+};+use crate::history::unix_now_ms;+use crate::io::png_codec;+use crate::memory::ScratchBackend;+use crate::tiles::{+ reserve_tile_version, RectI32, SparseLayerGrid, TileCoord, TileData, TileFormat, TileKind,+ TILE_SIZE,+};+use flate2::read::DeflateDecoder;+use flate2::write::DeflateEncoder;+use flate2::Compression;+use rayon::prelude::*;+use serde::{Deserialize, Serialize};+use std::collections::{HashMap, HashSet};+use std::io::{Read, Write};+use std::sync::Arc;++const TILE_BINARY_HEADER_BYTES: usize = 9;+const MASK_BINARY_HEADER_BYTES: usize = 8;+const MAX_MANIFEST_BYTES: usize = 64 * 1024 * 1024;+const MAX_DOCUMENT_DIM: u32 = 65536;+const MAX_TILE_ENTRIES: usize = 120_000;+const PREVIEW_MAX_DIM: u32 = 512;++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+struct PreviewManifestRef {+ path: String,+ width: u32,+ height: u32,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+struct MaskManifestMeta {+ width: u32,+ height: u32,+ format: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+struct InkProjectManifest {+ format: String,+ app: String,+ version: String,+ tile_size: usize,+ name: String,+ dimensions: CanvasDimensions,+ color_mode: CanvasColorMode,+ layers: Vec<LayerNodeMeta>,+ #[serde(default)]+ layer_formats: HashMap<String, TileFormat>,+ #[serde(default)]+ layer_tile_keys: HashMap<String, String>,+ #[serde(default)]+ masks_meta: HashMap<String, MaskManifestMeta>,+ #[serde(default)]+ perspective_ruler: Option<serde_json::Value>,+ #[serde(default)]+ animation_timeline: Option<serde_json::Value>,+ #[serde(default)]+ timelapse: Option<serde_json::Value>,+ #[serde(default)]+ work_time_ms: u64,+ #[serde(default)]+ preview: Option<PreviewManifestRef>,+ #[serde(default)]+ saved_at: u64,+}++/// Result of direct Rust `.ink` serialization.+#[derive(Debug, Clone)]+pub struct SerializedInkResult {+ pub bytes: Vec<u8>,+ pub preview_png: Option<Vec<u8>>,+ pub preview_data_url: Option<String>,+ pub tile_count: usize,+ pub mask_count: usize,+}++fn to_safe_zip_key(raw_id: &str, used: &mut HashSet<String>) -> String {+ let mut base: String = raw_id+ .chars()+ .map(|c| {+ if c.is_ascii_alphanumeric() || c == '.' || c == '_' || c == '-' {+ c+ } else {+ '_'+ }+ })+ .collect();+ if base.is_empty() || base == "." || base == ".." {+ base = "layer".to_string();+ }+ while base.contains("..") {+ base = base.replace("..", "_");+ }+ let mut candidate = base.clone();+ let mut suffix = 1u32;+ while !used.insert(candidate.clone()) {+ candidate = format!("{base}_{suffix}");+ suffix += 1;+ }+ candidate+}++fn is_safe_zip_path(path: &str) -> bool {+ if path.is_empty() || path.contains('\0') || path.contains('\\') || path.starts_with('/') {+ return false;+ }+ for seg in path.split('/') {+ if seg.is_empty() || seg == "." || seg == ".." {+ return false;+ }+ }+ true+}++struct PreparedZipEntry {+ name: String,+ compression_method: u16, // 0 = Store, 8 = Deflate+ crc32: u32,+ uncompressed_len: u32,+ compressed_data: Vec<u8>,+}++fn prepare_zip_entry(name: String, raw: &[u8], deflate_level: Option<u32>) -> Result<PreparedZipEntry, String> {+ let uncompressed_len = u32::try_from(raw.len())+ .map_err(|_| format!("ZIP entry {name} exceeds 4 GB limit"))?;+ let crc32 = crc32fast::hash(raw);+ let (compression_method, compressed_data) = if let Some(lvl) = deflate_level {+ let mut enc = DeflateEncoder::new(Vec::with_capacity(raw.len() / 2 + 32), Compression::new(lvl));+ enc.write_all(raw)+ .map_err(|e| format!("Failed to deflate ZIP entry {name}: {e}"))?;+ let data = enc+ .finish()+ .map_err(|e| format!("Failed to finalize ZIP entry {name}: {e}"))?;+ (8u16, data)+ } else {+ (0u16, raw.to_vec())+ };+ Ok(PreparedZipEntry {+ name,+ compression_method,+ crc32,+ uncompressed_len,+ compressed_data,+ })+}++/// Assembles pre-compressed entries into a standards-compliant ZIP archive.+fn assemble_zip(entries: Vec<PreparedZipEntry>) -> Result<Vec<u8>, String> {+ let est_size: usize = entries+ .iter()+ .map(|e| 96 + e.name.len() * 2 + e.compressed_data.len())+ .sum::<usize>()+ + 64;+ let mut out = Vec::with_capacity(est_size);+ let mut cd_records: Vec<(u32, PreparedZipEntry)> = Vec::with_capacity(entries.len());++ for entry in entries {+ let local_offset = u32::try_from(out.len())+ .map_err(|_| "ZIP archive exceeds 4 GB standard offset limit".to_string())?;+ let name_bytes = entry.name.as_bytes();+ let name_len = u16::try_from(name_bytes.len())+ .map_err(|_| "ZIP entry filename too long".to_string())?;+ let comp_len = u32::try_from(entry.compressed_data.len())+ .map_err(|_| "ZIP compressed entry exceeds 4 GB".to_string())?;++ // Local file header (30 bytes + name)+ out.extend_from_slice(&0x0403_4B50u32.to_le_bytes()); // PK\x03\x04+ out.extend_from_slice(&20u16.to_le_bytes()); // version needed 2.0+ out.extend_from_slice(&0x0800u16.to_le_bytes()); // UTF-8 filename flag+ out.extend_from_slice(&entry.compression_method.to_le_bytes());+ out.extend_from_slice(&0u16.to_le_bytes()); // mod time+ out.extend_from_slice(&0u16.to_le_bytes()); // mod date+ out.extend_from_slice(&entry.crc32.to_le_bytes());+ out.extend_from_slice(&comp_len.to_le_bytes());+ out.extend_from_slice(&entry.uncompressed_len.to_le_bytes());+ out.extend_from_slice(&name_len.to_le_bytes());+ out.extend_from_slice(&0u16.to_le_bytes()); // extra len+ out.extend_from_slice(name_bytes);+ out.extend_from_slice(&entry.compressed_data);++ cd_records.push((local_offset, entry));+ }++ let cd_offset = u32::try_from(out.len())+ .map_err(|_| "ZIP central directory exceeds 4 GB offset limit".to_string())?;+ let entry_count = u16::try_from(cd_records.len())+ .map_err(|_| "ZIP entry count exceeds 65535 limit".to_string())?;++ for (local_offset, entry) in &cd_records {+ let name_bytes = entry.name.as_bytes();+ let name_len = name_bytes.len() as u16;+ let comp_len = entry.compressed_data.len() as u32;++ // Central directory header (46 bytes + name)+ out.extend_from_slice(&0x0201_4B50u32.to_le_bytes()); // PK\x01\x02+ out.extend_from_slice(&20u16.to_le_bytes()); // version made by+ out.extend_from_slice(&20u16.to_le_bytes()); // version needed+ out.extend_from_slice(&0x0800u16.to_le_bytes()); // UTF-8 flag+ out.extend_from_slice(&entry.compression_method.to_le_bytes());+ out.extend_from_slice(&0u16.to_le_bytes()); // mod time+ out.extend_from_slice(&0u16.to_le_bytes()); // mod date+ out.extend_from_slice(&entry.crc32.to_le_bytes());+ out.extend_from_slice(&comp_len.to_le_bytes());+ out.extend_from_slice(&entry.uncompressed_len.to_le_bytes());+ out.extend_from_slice(&name_len.to_le_bytes());+ out.extend_from_slice(&0u16.to_le_bytes()); // extra len+ out.extend_from_slice(&0u16.to_le_bytes()); // comment len+ out.extend_from_slice(&0u16.to_le_bytes()); // disk number+ out.extend_from_slice(&0u16.to_le_bytes()); // internal attrs+ out.extend_from_slice(&0u32.to_le_bytes()); // external attrs+ out.extend_from_slice(&local_offset.to_le_bytes());+ out.extend_from_slice(name_bytes);+ }++ let cd_size = (out.len() as u32).saturating_sub(cd_offset);++ // End of Central Directory (22 bytes)+ out.extend_from_slice(&0x0605_4B50u32.to_le_bytes()); // PK\x05\x06+ out.extend_from_slice(&0u16.to_le_bytes()); // disk num+ out.extend_from_slice(&0u16.to_le_bytes()); // cd start disk+ out.extend_from_slice(&entry_count.to_le_bytes());+ out.extend_from_slice(&entry_count.to_le_bytes());+ out.extend_from_slice(&cd_size.to_le_bytes());+ out.extend_from_slice(&cd_offset.to_le_bytes());+ out.extend_from_slice(&0u16.to_le_bytes()); // comment len++ Ok(out)+}++#[derive(Debug, Clone)]+struct ParsedZipEntryRef<'a> {+ name: String,+ compression_method: u16,+ crc32: u32,+ uncompressed_len: usize,+ compressed_slice: &'a [u8],+}++fn parse_zip_directory(bytes: &[u8]) -> Result<Vec<ParsedZipEntryRef<'_>>, String> {+ if bytes.len() < 22 {+ return Err("Invalid .ink ZIP archive: file too short".to_string());+ }+ // Locate EOCD signature `PK\x05\x06` from the back (max 65557 bytes)+ let search_start = bytes.len().saturating_sub(65557);+ let mut eocd_pos = None;+ for pos in (search_start..=bytes.len() - 22).rev() {+ if &bytes[pos..pos + 4] == b"PK\x05\x06" {+ let comment_len = u16::from_le_bytes([bytes[pos + 20], bytes[pos + 21]]) as usize;+ if pos + 22 + comment_len == bytes.len() {+ eocd_pos = Some(pos);+ break;+ }+ }+ }+ let eocd = eocd_pos.ok_or_else(|| "Invalid .ink ZIP archive: missing EOCD".to_string())?;+ let total_entries = u16::from_le_bytes([bytes[eocd + 10], bytes[eocd + 11]]) as usize;+ let cd_size = u32::from_le_bytes(bytes[eocd + 12..eocd + 16].try_into().unwrap()) as usize;+ let cd_offset = u32::from_le_bytes(bytes[eocd + 16..eocd + 20].try_into().unwrap()) as usize;++ if cd_offset.checked_add(cd_size).is_none_or(|end| end > eocd) {+ return Err("Invalid .ink ZIP archive: corrupt central directory bounds".to_string());+ }++ let mut entries = Vec::with_capacity(total_entries);+ let mut pos = cd_offset;+ let cd_end = cd_offset + cd_size;++ while pos < cd_end {+ if pos + 46 > cd_end || &bytes[pos..pos + 4] != b"PK\x01\x02" {+ return Err("Invalid .ink ZIP archive: corrupt central directory header".to_string());+ }+ let method = u16::from_le_bytes([bytes[pos + 10], bytes[pos + 11]]);+ let crc32 = u32::from_le_bytes(bytes[pos + 16..pos + 20].try_into().unwrap());+ let comp_len = u32::from_le_bytes(bytes[pos + 20..pos + 24].try_into().unwrap()) as usize;+ let uncomp_len =+ u32::from_le_bytes(bytes[pos + 24..pos + 28].try_into().unwrap()) as usize;+ let name_len = u16::from_le_bytes([bytes[pos + 28], bytes[pos + 29]]) as usize;+ let extra_len = u16::from_le_bytes([bytes[pos + 30], bytes[pos + 31]]) as usize;+ let comment_len = u16::from_le_bytes([bytes[pos + 32], bytes[pos + 33]]) as usize;+ let local_off =+ u32::from_le_bytes(bytes[pos + 42..pos + 46].try_into().unwrap()) as usize;++ let name_start = pos + 46;+ let name_end = name_start + name_len;+ if name_end + extra_len + comment_len > cd_end {+ return Err("Invalid .ink ZIP archive: truncated entry metadata".to_string());+ }+ let name = std::str::from_utf8(&bytes[name_start..name_end])+ .map_err(|_| "Invalid UTF-8 filename in .ink archive".to_string())?+ .to_string();+ if !is_safe_zip_path(&name) {+ return Err(format!("Unsafe archive path in .ink file: \"{name}\""));+ }++ // Read local file header to compute exact compressed payload slice+ if local_off + 30 > bytes.len() || &bytes[local_off..local_off + 4] != b"PK\x03\x04" {+ return Err(format!("Corrupt local file header for entry \"{name}\""));+ }+ let lh_name_len =+ u16::from_le_bytes([bytes[local_off + 26], bytes[local_off + 27]]) as usize;+ let lh_extra_len =+ u16::from_le_bytes([bytes[local_off + 28], bytes[local_off + 29]]) as usize;+ let data_start = local_off + 30 + lh_name_len + lh_extra_len;+ let data_end = data_start+ .checked_add(comp_len)+ .filter(|&end| end <= bytes.len())+ .ok_or_else(|| format!("Truncated payload for entry \"{name}\""))?;++ entries.push(ParsedZipEntryRef {+ name,+ compression_method: method,+ crc32,+ uncompressed_len: uncomp_len,+ compressed_slice: &bytes[data_start..data_end],+ });++ pos = name_end + extra_len + comment_len;+ }++ Ok(entries)+}++fn inflate_zip_entry(entry: &ParsedZipEntryRef<'_>, max_bytes: usize) -> Result<Vec<u8>, String> {+ if entry.uncompressed_len > max_bytes {+ return Err(format!(+ "Entry \"{}\" exceeds safety size limit ({} > {})",+ entry.name, entry.uncompressed_len, max_bytes+ ));+ }+ let raw = match entry.compression_method {+ 0 => entry.compressed_slice.to_vec(),+ 8 => {+ let mut decoder = DeflateDecoder::new(entry.compressed_slice);+ let mut out = Vec::with_capacity(entry.uncompressed_len.min(max_bytes));+ let mut limited = decoder.by_ref().take((max_bytes + 1) as u64);+ limited+ .read_to_end(&mut out)+ .map_err(|e| format!("Failed to inflate entry \"{}\": {e}", entry.name))?;+ if out.len() > max_bytes {+ return Err(format!("Decompressed entry \"{}\" exceeded safety cap", entry.name));+ }+ out+ }+ other => {+ return Err(format!(+ "Unsupported ZIP compression method {} for \"{}\"",+ other, entry.name+ ))+ }+ };+ let actual_crc = crc32fast::hash(&raw);+ if entry.crc32 != 0 && actual_crc != entry.crc32 {+ return Err(format!("CRC32 mismatch in .ink entry \"{}\"", entry.name));+ }+ Ok(raw)+}++/// Fast preview-only extraction from `.ink` ZIP bytes (does not inflate any tile entries).+pub fn extract_ink_preview(zip_bytes: &[u8]) -> Option<Vec<u8>> {+ let entries = parse_zip_directory(zip_bytes).ok()?;+ let preview = entries.iter().find(|e| e.name == "preview.png")?;+ inflate_zip_entry(preview, 16 * 1024 * 1024).ok()+}++/// Serializes `doc` directly from Rust's sparse tile grids into a `.ink` v2 ZIP archive+/// using Rayon multi-core parallel DEFLATE compression (zero JS pixel IPC!).+pub fn serialize_ink_document(+ doc: &Document,+ compression_level: u32,+ scratch: Option<&dyn ScratchBackend>,+) -> Result<SerializedInkResult, String> {+ let level = compression_level.min(6);+ let mut used_keys = HashSet::new();+ let mut layer_tile_keys = HashMap::new();+ let mut layer_formats = HashMap::new();+ let mut masks_meta = HashMap::new();++ struct TileWorkItem {+ zip_path: String,+ storage_format: TileFormat,+ mono_threshold: u8,+ tile: Arc<TileData>,+ }++ let mut tile_work: Vec<TileWorkItem> = Vec::new();+ let mut mask_work: Vec<(String, u32, u32, Vec<u8>)> = Vec::new();+ let mut manifest_layers: Vec<LayerNodeMeta> = Vec::with_capacity(doc.layers.len());++ for layer in &doc.layers {+ let safe_key = to_safe_zip_key(&layer.meta.id, &mut used_keys);+ layer_tile_keys.insert(layer.meta.id.clone(), safe_key.clone());++ if layer.meta.layer_type.has_tiles() {+ let io_fmt = layer.grid.format.io_storage_format();+ layer_formats.insert(layer.meta.id.clone(), io_fmt);+ let thresh = layer.meta.mono_threshold.unwrap_or(128);+ for (&coord, tile_arc) in &layer.grid.tiles {+ tile_work.push(TileWorkItem {+ zip_path: format!("tiles/{safe_key}/{}_{}.bin", coord.tx, coord.ty),+ storage_format: io_fmt,+ mono_threshold: thresh,+ tile: Arc::clone(tile_arc),+ });+ }+ }++ if layer.grid.has_mask && doc.dimensions.width > 0 && doc.dimensions.height > 0 {+ let mask_bytes = layer.grid.read_mask8_rect(+ RectI32::new(0, 0, doc.dimensions.width, doc.dimensions.height),+ scratch,+ )?;+ masks_meta.insert(+ layer.meta.id.clone(),+ MaskManifestMeta {+ width: doc.dimensions.width,+ height: doc.dimensions.height,+ format: "alpha-8bit".to_string(),+ },+ );+ mask_work.push((+ format!("masks/{safe_key}.bin"),+ doc.dimensions.width,+ doc.dimensions.height,+ mask_bytes,+ ));+ }++ manifest_layers.push(layer.meta.clone());+ }++ let tile_count = tile_work.len();+ let mask_count = mask_work.len();++ // Generate preview.png directly in Rust from live tiles+ let preview = doc+ .render_flattened_png(PREVIEW_MAX_DIM, true, scratch)+ .ok();++ // Parallel-encode and deflate all tiles via Rayon+ let tile_entries: Result<Vec<PreparedZipEntry>, String> = tile_work+ .into_par_iter()+ .map(|item| {+ let raw = item.tile.to_format_raw(+ item.storage_format,+ item.mono_threshold,+ true, // Bayer-dither Rgba16Float -> Rgba8 on save boundary+ scratch,+ )?;+ let mut record = Vec::with_capacity(TILE_BINARY_HEADER_BYTES + raw.len());+ record.push(item.storage_format.to_ink_byte());+ record.extend_from_slice(&(item.tile.version as u32).to_le_bytes());+ record.extend_from_slice(&(raw.len() as u32).to_le_bytes());+ record.extend_from_slice(&raw);+ prepare_zip_entry(item.zip_path, &record, Some(level))+ })+ .collect();+ let tile_entries = tile_entries?;++ // Parallel-encode and deflate all masks via Rayon+ let mask_entries: Result<Vec<PreparedZipEntry>, String> = mask_work+ .into_par_iter()+ .map(|(path, mw, mh, alpha)| {+ let mut record = Vec::with_capacity(MASK_BINARY_HEADER_BYTES + alpha.len());+ record.extend_from_slice(&mw.to_le_bytes());+ record.extend_from_slice(&mh.to_le_bytes());+ record.extend_from_slice(&alpha);+ prepare_zip_entry(path, &record, Some(level))+ })+ .collect();+ let mask_entries = mask_entries?;++ let (preview_manifest, preview_png, preview_data_url) = if let Some((pw, ph, png_bytes)) = preview+ {+ let data_url = png_codec::png_bytes_to_data_url(&png_bytes);+ (+ Some(PreviewManifestRef {+ path: "preview.png".to_string(),+ width: pw,+ height: ph,+ }),+ Some(png_bytes),+ Some(data_url),+ )+ } else {+ (None, None, None)+ };++ let manifest = InkProjectManifest {+ format: "ink-v2".to_string(),+ app: "Ink Studio".to_string(),+ version: "2.0".to_string(),+ tile_size: TILE_SIZE,+ name: doc.name.clone(),+ dimensions: doc.dimensions,+ color_mode: doc.color_mode,+ layers: manifest_layers,+ layer_formats,+ layer_tile_keys,+ masks_meta,+ perspective_ruler: doc.perspective_ruler.clone(),+ animation_timeline: doc.animation_timeline.clone(),+ timelapse: doc.timelapse.clone(),+ work_time_ms: doc.work_time_ms,+ preview: preview_manifest,+ saved_at: unix_now_ms(),+ };+ let manifest_bytes = serde_json::to_vec(&manifest)+ .map_err(|e| format!("Failed to serialize .ink manifest.json: {e}"))?;++ let mut all_entries = Vec::with_capacity(2 + tile_entries.len() + mask_entries.len());+ if let Some(ref png_bytes) = preview_png {+ all_entries.push(prepare_zip_entry("preview.png".to_string(), png_bytes, None)?);+ }+ all_entries.extend(tile_entries);+ all_entries.extend(mask_entries);+ all_entries.push(prepare_zip_entry(+ "manifest.json".to_string(),+ &manifest_bytes,+ Some(6),+ )?);++ let zip_bytes = assemble_zip(all_entries)?;+ Ok(SerializedInkResult {+ bytes: zip_bytes,+ preview_png,+ preview_data_url,+ tile_count,+ mask_count,+ })+}++/// Parses a `.ink` v2 ZIP archive directly into a Rust [`Document`] with parallel Rayon tile+/// decompression, zero-copy hydration, and parallel 64×64 thumbnail generation!+pub fn parse_ink_document(+ zip_bytes: &[u8],+ doc_id: impl Into<String>,+ fallback_name: &str,+ max_history_steps: usize,+) -> Result<Document, String> {+ let entries = parse_zip_directory(zip_bytes)?;+ let manifest_entry = entries+ .iter()+ .find(|e| e.name == "manifest.json")+ .ok_or_else(|| "Invalid .ink project: missing manifest.json".to_string())?;+ let manifest_raw = inflate_zip_entry(manifest_entry, MAX_MANIFEST_BYTES)?;+ let manifest: InkProjectManifest = serde_json::from_slice(&manifest_raw)+ .map_err(|e| format!("Invalid .ink manifest.json: {e}"))?;++ let width = manifest.dimensions.width;+ let height = manifest.dimensions.height;+ if width == 0 || height == 0 || width > MAX_DOCUMENT_DIM || height > MAX_DOCUMENT_DIM {+ return Err(format!("Invalid .ink dimensions: {width}x{height}"));+ }++ // Build reverse safeKey -> layerId mapping+ let mut key_to_layer_id: HashMap<String, String> = HashMap::new();+ for (lid, safe_key) in &manifest.layer_tile_keys {+ if !safe_key.is_empty() {+ key_to_layer_id.insert(safe_key.clone(), lid.clone());+ }+ }+ for layer in &manifest.layers {+ key_to_layer_id+ .entry(layer.id.clone())+ .or_insert_with(|| layer.id.clone());+ }++ // Classify tile & mask ZIP entries+ let mut tile_refs: Vec<(&ParsedZipEntryRef<'_>, String, i32, i32)> = Vec::new();+ let mut mask_refs: Vec<(&ParsedZipEntryRef<'_>, String)> = Vec::new();++ for entry in &entries {+ if let Some(rest) = entry.name.strip_prefix("tiles/") {+ if let Some((safe_key, file_part)) = rest.split_once('/') {+ if let Some(stem) = file_part.strip_suffix(".bin") {+ if let Some((tx_s, ty_s)) = stem.split_once('_') {+ if let (Ok(tx), Ok(ty), Some(lid)) = (+ tx_s.parse::<i32>(),+ ty_s.parse::<i32>(),+ key_to_layer_id.get(safe_key),+ ) {+ tile_refs.push((entry, lid.clone(), tx, ty));+ }+ }+ }+ }+ } else if let Some(rest) = entry.name.strip_prefix("masks/") {+ if let Some(safe_key) = rest.strip_suffix(".bin") {+ if let Some(lid) = key_to_layer_id.get(safe_key) {+ mask_refs.push((entry, lid.clone()));+ }+ }+ }+ }++ if tile_refs.len() > MAX_TILE_ENTRIES {+ return Err(format!(+ "Invalid .ink project: tile count {} exceeds limit",+ tile_refs.len()+ ));+ }++ // Parallel-inflate and decode all tiles via Rayon+ let decoded_tiles: Result<Vec<(String, TileCoord, TileData)>, String> = tile_refs+ .into_par_iter()+ .map(|(entry, layer_id, tx, ty)| {+ let payload = inflate_zip_entry(entry, 4 * 1024 * 1024)?;+ if payload.len() < TILE_BINARY_HEADER_BYTES {+ return Err(format!(+ "Corrupted .ink tile ({layer_id} {tx}_{ty}): truncated header"+ ));+ }+ let fmt = TileFormat::from_ink_byte(payload[0]).ok_or_else(|| {+ format!(+ "Corrupted .ink tile ({layer_id} {tx}_{ty}): unknown format {}",+ payload[0]+ )+ })?;+ let version = u32::from_le_bytes(payload[1..5].try_into().unwrap()) as u64;+ let data_len = u32::from_le_bytes(payload[5..9].try_into().unwrap()) as usize;+ let expected = fmt.byte_size();+ if data_len != expected || payload.len() != TILE_BINARY_HEADER_BYTES + expected {+ return Err(format!(+ "Corrupted .ink tile ({layer_id} {tx}_{ty}): length mismatch"+ ));+ }+ let mut td = TileData::from_raw_auto_compact(+ fmt,+ TileKind::Raster,+ payload[TILE_BINARY_HEADER_BYTES..].to_vec(),+ );+ if version > 0 {+ td.version = version;+ reserve_tile_version(version);+ }+ Ok((layer_id, TileCoord::new(tx, ty), td))+ })+ .collect();+ let decoded_tiles = decoded_tiles?;++ // Parallel-inflate and decode all masks via Rayon+ type DecodedMaskEntry = (String, u32, u32, Vec<u8>);+ let decoded_masks: Result<Vec<DecodedMaskEntry>, String> = mask_refs+ .into_par_iter()+ .map(|(entry, layer_id)| {+ let payload = inflate_zip_entry(entry, 128 * 1024 * 1024)?;+ if payload.len() < MASK_BINARY_HEADER_BYTES {+ return Err(format!("Corrupted .ink mask ({layer_id}): truncated header"));+ }+ let mw = u32::from_le_bytes(payload[0..4].try_into().unwrap());+ let mh = u32::from_le_bytes(payload[4..8].try_into().unwrap());+ let expected = (mw as usize)+ .checked_mul(mh as usize)+ .ok_or_else(|| "Mask dimensions overflow".to_string())?;+ if payload.len() != MASK_BINARY_HEADER_BYTES + expected {+ return Err(format!("Corrupted .ink mask ({layer_id}): length mismatch"));+ }+ Ok((+ layer_id,+ mw,+ mh,+ payload[MASK_BINARY_HEADER_BYTES..].to_vec(),+ ))+ })+ .collect();+ let decoded_masks = decoded_masks?;++ // Group decoded tiles & masks by layer ID+ let mut tiles_by_layer: HashMap<String, Vec<(TileCoord, TileData)>> = HashMap::new();+ for (lid, coord, td) in decoded_tiles {+ tiles_by_layer.entry(lid).or_default().push((coord, td));+ }+ let mut masks_by_layer: HashMap<String, (u32, u32, Vec<u8>)> = HashMap::new();+ for (lid, mw, mh, data) in decoded_masks {+ masks_by_layer.insert(lid, (mw, mh, data));+ }++ // Assemble LayerNodes and generate 64×64 thumbnails in parallel+ let nodes: Vec<LayerNode> = manifest+ .layers+ .into_par_iter()+ .map(|mut meta| {+ let fmt = manifest+ .layer_formats+ .get(&meta.id)+ .copied()+ .or_else(|| meta.expression_color.map(ExpressionColor::to_tile_format))+ .unwrap_or(TileFormat::Color32Bit);+ let mut grid = SparseLayerGrid::new(fmt);+ if let Some(layer_tiles) = tiles_by_layer.get(&meta.id) {+ if let Some((_, first)) = layer_tiles.first() {+ grid.format = first.format;+ }+ for (coord, td) in layer_tiles {+ grid.set_tile(*coord, Arc::new(td.clone()));+ }+ }+ if let Some((mw, mh, mask_bytes)) = masks_by_layer.get(&meta.id) {+ grid.init_mask(255);+ let _ = grid.write_mask8_rect(mask_bytes, RectI32::new(0, 0, *mw, *mh), None);+ meta.has_mask = true;+ if meta.mask_enabled.is_none() {+ meta.mask_enabled = Some(true);+ }+ if meta.mask_linked.is_none() {+ meta.mask_linked = Some(true);+ }+ meta.mask_version = Some(grid.layer_version);+ }++ let mut node = LayerNode { meta, grid };+ if node.meta.layer_type.has_tiles() {+ if let Ok((tw, th, rgba)) = crate::io::compositor_cpu::render_layer_thumbnail_rgba(+ &node, width, height, 64, 64, None,+ ) {+ if let Ok(png) = png_codec::encode_rgba8_to_png(tw, th, &rgba) {+ node.meta.thumbnail_url = Some(png_codec::png_bytes_to_data_url(&png));+ }+ }+ }+ if node.grid.has_mask {+ if let Ok((tw, th, rgba)) = crate::io::compositor_cpu::render_mask_thumbnail_rgba(+ &node, width, height, 64, 64, None,+ ) {+ if let Ok(png) = png_codec::encode_rgba8_to_png(tw, th, &rgba) {+ node.meta.mask_thumbnail_url = Some(png_codec::png_bytes_to_data_url(&png));+ }+ }+ }+ node+ })+ .collect();++ let preview_data_url = entries+ .iter()+ .find(|e| e.name == "preview.png")+ .and_then(|e| inflate_zip_entry(e, 16 * 1024 * 1024).ok())+ .map(|png| png_codec::png_bytes_to_data_url(&png));++ let doc_name = if manifest.name.trim().is_empty() {+ fallback_name.to_string()+ } else {+ manifest.name+ };++ let mut doc = Document::from_layers(+ doc_id,+ doc_name,+ manifest.dimensions,+ manifest.color_mode,+ nodes,+ None,+ max_history_steps,+ );+ doc.perspective_ruler = manifest.perspective_ruler;+ doc.animation_timeline = manifest.animation_timeline;+ doc.timelapse = manifest.timelapse;+ doc.work_time_ms = manifest.work_time_ms;+ doc.preview_data_url = preview_data_url;++ Ok(doc)+}diff --git a/crates/ink-engine/src/io/mod.rs b/crates/ink-engine/src/io/mod.rsnew file mode 100644index 0000000..0103934--- /dev/null+++ b/crates/ink-engine/src/io/mod.rs@@ -0,0 +1,17 @@+//! Zero-copy Rust document I/O (`.ink` v2 parallel ZIP save/load), pure-Rust PNG thumbnail &+//! preview encoding, software tile compositor (for thumbnails/previews/timelapse/merges),+//! and in-process crash recovery WAL/checkpoint codecs.++pub mod compositor_cpu;+pub mod ink_format;+pub mod png_codec;+pub mod wal;++pub use ink_format::{+ extract_ink_preview, parse_ink_document, serialize_ink_document, SerializedInkResult,+};+pub use png_codec::{encode_rgba8_to_png, png_bytes_to_data_url, to_base64};+pub use wal::{+ encode_cow_deltas_to_wal_payload, encode_document_checkpoint, replay_recovery_into_document,+ WalRawEntry,+};diff --git a/crates/ink-engine/src/io/png_codec.rs b/crates/ink-engine/src/io/png_codec.rsnew file mode 100644index 0000000..f025543--- /dev/null+++ b/crates/ink-engine/src/io/png_codec.rs@@ -0,0 +1,102 @@+//! Pure-Rust fast lossless RGBA8 PNG encoder & base64 data-URL utilities+//! for 64×64 layer/mask thumbnails, `.ink` previews, and timelapse keyframes.++use flate2::write::ZlibEncoder;+use flate2::Compression;+use std::io::Write;++const PNG_SIG: &[u8; 8] = &[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];++fn write_png_chunk(out: &mut Vec<u8>, chunk_type: &[u8; 4], data: &[u8]) -> Result<(), String> {+ let len = u32::try_from(data.len()).map_err(|_| "PNG chunk exceeds 4 GB".to_string())?;+ out.extend_from_slice(&len.to_be_bytes());+ out.extend_from_slice(chunk_type);+ out.extend_from_slice(data);+ let mut hasher = crc32fast::Hasher::new();+ hasher.update(chunk_type);+ hasher.update(data);+ out.extend_from_slice(&hasher.finalize().to_be_bytes());+ Ok(())+}++/// Encodes an RGBA8 image buffer into a valid lossless PNG using Sub row filtering + fast zlib.+pub fn encode_rgba8_to_png(width: u32, height: u32, rgba: &[u8]) -> Result<Vec<u8>, String> {+ if width == 0 || height == 0 || width > 16384 || height > 16384 {+ return Err(format!("Invalid PNG dimensions: {width}x{height}"));+ }+ let row_bytes = (width as usize)+ .checked_mul(4)+ .ok_or_else(|| "PNG row stride overflow".to_string())?;+ let expected = row_bytes+ .checked_mul(height as usize)+ .ok_or_else(|| "PNG buffer size overflow".to_string())?;+ if rgba.len() != expected {+ return Err(format!(+ "PNG RGBA buffer mismatch: expected {expected}, got {}",+ rgba.len()+ ));+ }++ let mut encoder = ZlibEncoder::new(Vec::with_capacity(expected / 4 + 128), Compression::fast());+ let mut filtered_row = vec![0u8; 1 + row_bytes];+ filtered_row[0] = 1; // PNG Sub filter (bpp = 4)+ for y in 0..(height as usize) {+ let row = &rgba[y * row_bytes..(y + 1) * row_bytes];+ for i in 0..row_bytes {+ let left = if i >= 4 { row[i - 4] } else { 0 };+ filtered_row[1 + i] = row[i].wrapping_sub(left);+ }+ encoder+ .write_all(&filtered_row)+ .map_err(|e| format!("PNG zlib write error: {e}"))?;+ }+ let idat = encoder+ .finish()+ .map_err(|e| format!("PNG zlib finish error: {e}"))?;++ let mut out = Vec::with_capacity(64 + idat.len());+ out.extend_from_slice(PNG_SIG);+ let mut ihdr = [0u8; 13];+ ihdr[0..4].copy_from_slice(&width.to_be_bytes());+ ihdr[4..8].copy_from_slice(&height.to_be_bytes());+ ihdr[8] = 8; // 8-bit depth+ ihdr[9] = 6; // RGBA+ ihdr[10] = 0; // deflate+ ihdr[11] = 0; // adaptive filtering+ ihdr[12] = 0; // non-interlaced+ write_png_chunk(&mut out, b"IHDR", &ihdr)?;+ write_png_chunk(&mut out, b"IDAT", &idat)?;+ write_png_chunk(&mut out, b"IEND", &[])?;+ Ok(out)+}++/// Standard RFC-4648 Base64 encoder for inline `data:image/png;base64,...` thumbnails.+pub fn to_base64(data: &[u8]) -> String {+ const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";+ let mut out = String::with_capacity(data.len().div_ceil(3) * 4);+ for chunk in data.chunks(3) {+ let b0 = chunk[0];+ let b1 = if chunk.len() > 1 { chunk[1] } else { 0 };+ let b2 = if chunk.len() > 2 { chunk[2] } else { 0 };+ out.push(TABLE[(b0 >> 2) as usize] as char);+ out.push(TABLE[(((b0 & 0x03) << 4) | (b1 >> 4)) as usize] as char);+ if chunk.len() > 1 {+ out.push(TABLE[(((b1 & 0x0F) << 2) | (b2 >> 6)) as usize] as char);+ } else {+ out.push('=');+ }+ if chunk.len() > 2 {+ out.push(TABLE[(b2 & 0x3F) as usize] as char);+ } else {+ out.push('=');+ }+ }+ out+}++pub fn png_bytes_to_data_url(png: &[u8]) -> String {+ if png.is_empty() {+ return String::new();+ }+ format!("data:image/png;base64,{}", to_base64(png))+}diff --git a/crates/ink-engine/src/io/wal.rs b/crates/ink-engine/src/io/wal.rsnew file mode 100644index 0000000..fb6892f--- /dev/null+++ b/crates/ink-engine/src/io/wal.rs@@ -0,0 +1,541 @@+//! Direct Rust Crash Recovery WAL (`TD v1`) & Checkpoint (`INKG v1`) binary codecs.+//!+//! Produces wire-compatible payloads consumed directly in-process by `src-tauri/src/recovery.rs`+//! (zero JS serialization or IPC pixel transfers!).++use crate::document::{+ CanvasColorMode, CanvasDimensions, Document, ExpressionColor, LayerNode, LayerNodeMeta,+};+use crate::memory::ScratchBackend;+use crate::tiles::{+ reserve_tile_version, CowTileDelta, SparseLayerGrid, TileCoord, TileData, TileFormat, TileKind,+};+use flate2::read::DeflateDecoder;+use flate2::write::DeflateEncoder;+use flate2::Compression;+use serde::{Deserialize, Serialize};+use std::collections::HashMap;+use std::io::{Read, Write};+use std::sync::Arc;++pub const WAL_ENTRY_STROKE_TILE_DELTA: u8 = 1;+pub const WAL_ENTRY_VECTOR_STROKE: u8 = 2;+pub const WAL_ENTRY_LAYER_MUTATION: u8 = 3;++const MAX_DECOMPRESSED_BYTES: usize = 512 * 1024 * 1024;++#[derive(Debug, Clone)]+pub struct WalRawEntry {+ pub entry_type: u8,+ pub payload: Vec<u8>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+struct RecoveryManifest {+ session_id: String,+ document_name: String,+ width: u32,+ height: u32,+ #[serde(default = "default_dpi")]+ dpi: u32,+ #[serde(default)]+ color_mode: CanvasColorMode,+ #[serde(default)]+ layers: Vec<LayerNodeMeta>,+ #[serde(default)]+ active_layer_id: Option<String>,+ #[serde(default)]+ timestamp: u64,+ #[serde(default)]+ work_time_ms: u64,+ #[serde(default)]+ timelapse: Option<serde_json::Value>,+}++fn default_dpi() -> u32 {+ 300+}++#[derive(Debug, Clone, Deserialize)]+#[serde(rename_all = "camelCase")]+struct LayerMutationWalPayload {+ #[serde(default)]+ layers: Vec<LayerNodeMeta>,+ #[serde(default)]+ active_layer_id: Option<String>,+}++fn deflate_fast(raw: &[u8]) -> Result<Vec<u8>, String> {+ let mut enc = DeflateEncoder::new(Vec::with_capacity(raw.len() / 3 + 32), Compression::fast());+ enc.write_all(raw)+ .map_err(|e| format!("WAL deflate error: {e}"))?;+ enc.finish()+ .map_err(|e| format!("WAL deflate finish error: {e}"))+}++fn inflate_or_raw(bytes: &[u8], expected_magic: &[u8]) -> Result<Vec<u8>, String> {+ if bytes.starts_with(expected_magic) {+ return Ok(bytes.to_vec());+ }+ let mut dec = DeflateDecoder::new(bytes);+ let mut out = Vec::new();+ let mut limited = dec.by_ref().take((MAX_DECOMPRESSED_BYTES + 1) as u64);+ limited+ .read_to_end(&mut out)+ .map_err(|e| format!("WAL inflate error: {e}"))?;+ if out.len() > MAX_DECOMPRESSED_BYTES {+ return Err("WAL payload exceeded safety ceiling".to_string());+ }+ Ok(out)+}++/// Encodes CoW tile deltas directly into deflate-compressed `TD v1` WAL frame payload bytes+/// (`['T','D'][1u8][count:u32 LE] ([keyLen:u16][key][fmt:u8][hasBefore:u8][len?][bytes?][hasAfter:u8][len?][bytes?])*`).+pub fn encode_cow_deltas_to_wal_payload(+ deltas: &[CowTileDelta],+ scratch: Option<&dyn ScratchBackend>,+) -> Result<Vec<u8>, String> {+ let mut raw = Vec::with_capacity(7 + deltas.len() * 64);+ raw.extend_from_slice(b"TD");+ raw.push(1u8);+ raw.extend_from_slice(&(deltas.len() as u32).to_le_bytes());++ for d in deltas {+ let key = match d.kind {+ TileKind::Raster => format!("{}:{}:{}", d.layer_id, d.coord.tx, d.coord.ty),+ TileKind::Mask => format!("{}__mask:{}:{}", d.layer_id, d.coord.tx, d.coord.ty),+ };+ let key_bytes = key.as_bytes();+ raw.extend_from_slice(&(key_bytes.len() as u16).to_le_bytes());+ raw.extend_from_slice(key_bytes);++ let fmt = d+ .after+ .as_ref()+ .or(d.before.as_ref())+ .map(|t| t.format.io_storage_format())+ .unwrap_or(TileFormat::Color32Bit);+ raw.push(fmt.to_ink_byte());++ if let Some(ref before) = d.before {+ let bytes = before.to_format_raw(fmt, 128, true, scratch)?;+ raw.push(1);+ raw.extend_from_slice(&(bytes.len() as u32).to_le_bytes());+ raw.extend_from_slice(&bytes);+ } else {+ raw.push(0);+ }++ if let Some(ref after) = d.after {+ let bytes = after.to_format_raw(fmt, 128, true, scratch)?;+ raw.push(1);+ raw.extend_from_slice(&(bytes.len() as u32).to_le_bytes());+ raw.extend_from_slice(&bytes);+ } else {+ raw.push(0);+ }+ }++ deflate_fast(&raw)+}++/// Encodes an entire [`Document`] into a recovery checkpoint tuple:+/// `(manifest_json, deflate(INKG v1 snapshot), thumbnail_png)`.+pub fn encode_document_checkpoint(+ doc: &Document,+ scratch: Option<&dyn ScratchBackend>,+) -> Result<(String, Vec<u8>, Vec<u8>), String> {+ let mut inkg = Vec::with_capacity(16 * 1024);+ inkg.extend_from_slice(b"INKG");+ inkg.push(1u8); // version 1++ // Layer formats section+ let format_entries: Vec<(&str, TileFormat)> = doc+ .layers+ .iter()+ .filter(|l| l.meta.layer_type.has_tiles())+ .map(|l| (l.meta.id.as_str(), l.grid.format.io_storage_format()))+ .collect();+ inkg.extend_from_slice(&(format_entries.len() as u32).to_le_bytes());+ for (lid, fmt) in &format_entries {+ let kb = lid.as_bytes();+ inkg.extend_from_slice(&(kb.len() as u16).to_le_bytes());+ inkg.extend_from_slice(kb);+ inkg.push(fmt.to_ink_byte());+ }++ // Tiles section (raster tiles + mask tiles encoded under `<layerId>__mask`)+ let mut tile_count = 0u32;+ let count_pos = inkg.len();+ inkg.extend_from_slice(&0u32.to_le_bytes());++ for layer in &doc.layers {+ let io_fmt = layer.grid.format.io_storage_format();+ let thresh = layer.meta.mono_threshold.unwrap_or(128);+ let kb = layer.meta.id.as_bytes();+ for (&coord, tile) in &layer.grid.tiles {+ let raw = tile.to_format_raw(io_fmt, thresh, true, scratch)?;+ inkg.extend_from_slice(&(kb.len() as u16).to_le_bytes());+ inkg.extend_from_slice(kb);+ inkg.extend_from_slice(&coord.tx.to_le_bytes());+ inkg.extend_from_slice(&coord.ty.to_le_bytes());+ inkg.push(io_fmt.to_ink_byte());+ inkg.extend_from_slice(&(tile.version as u32).to_le_bytes());+ inkg.extend_from_slice(&(raw.len() as u32).to_le_bytes());+ inkg.extend_from_slice(&raw);+ tile_count += 1;+ }+ if layer.grid.has_mask {+ let mask_key = format!("{}__mask", layer.meta.id);+ let mkb = mask_key.as_bytes();+ for (&coord, tile) in &layer.grid.mask_tiles {+ let raw = tile.materialize_raw(scratch)?;+ inkg.extend_from_slice(&(mkb.len() as u16).to_le_bytes());+ inkg.extend_from_slice(mkb);+ inkg.extend_from_slice(&coord.tx.to_le_bytes());+ inkg.extend_from_slice(&coord.ty.to_le_bytes());+ inkg.push(TileFormat::Grayscale8Bit.to_ink_byte());+ inkg.extend_from_slice(&(tile.version as u32).to_le_bytes());+ inkg.extend_from_slice(&(raw.len() as u32).to_le_bytes());+ inkg.extend_from_slice(&raw);+ tile_count += 1;+ }+ }+ }+ inkg[count_pos..count_pos + 4].copy_from_slice(&tile_count.to_le_bytes());++ let compressed_snapshot = deflate_fast(&inkg)?;++ let manifest = RecoveryManifest {+ session_id: doc.id.clone(),+ document_name: doc.name.clone(),+ width: doc.dimensions.width,+ height: doc.dimensions.height,+ dpi: doc.dimensions.dpi,+ color_mode: doc.color_mode,+ layers: doc+ .layers+ .iter()+ .map(|l| {+ let mut m = l.meta.clone();+ m.thumbnail_url = None;+ m.mask_thumbnail_url = None;+ m+ })+ .collect(),+ active_layer_id: doc.active_layer_id.clone(),+ timestamp: crate::history::unix_now_ms(),+ work_time_ms: doc.work_time_ms,+ timelapse: doc.timelapse.clone(),+ };+ let manifest_json = serde_json::to_string(&manifest)+ .map_err(|e| format!("Failed to serialize recovery manifest: {e}"))?;++ let thumbnail_png = doc+ .render_flattened_png(256, true, scratch)+ .map(|(_, _, png)| png)+ .unwrap_or_default();++ Ok((manifest_json, compressed_snapshot, thumbnail_png))+}++/// Replays a recovery manifest, optional `INKG v1` base snapshot, and `journal.wal` frames+/// directly into a hydrated Rust [`Document`]. Returns `(doc, strokes_replayed, mutations_replayed)`.+pub fn replay_recovery_into_document(+ doc_id: impl Into<String>,+ manifest_json: &str,+ base_snapshot: Option<&[u8]>,+ wal_entries: &[WalRawEntry],+ max_history_steps: usize,+) -> Result<(Document, usize, usize), String> {+ let manifest: RecoveryManifest = serde_json::from_str(manifest_json)+ .map_err(|e| format!("Failed to parse recovery manifest: {e}"))?;++ let dims = CanvasDimensions {+ width: manifest.width.max(1),+ height: manifest.height.max(1),+ dpi: manifest.dpi.max(1),+ };++ let mut grids_by_layer: HashMap<String, SparseLayerGrid> = HashMap::new();+ for l in &manifest.layers {+ let fmt = l+ .expression_color+ .map(ExpressionColor::to_tile_format)+ .unwrap_or(TileFormat::Color32Bit);+ let mut g = SparseLayerGrid::new(fmt);+ if l.has_mask {+ g.init_mask(255);+ }+ grids_by_layer.insert(l.id.clone(), g);+ }++ // 1. Hydrate optional INKG v1 base snapshot+ if let Some(snap_bytes) = base_snapshot {+ if !snap_bytes.is_empty() {+ let inkg = inflate_or_raw(snap_bytes, b"INKG")?;+ apply_inkg_snapshot(&inkg, &mut grids_by_layer)?;+ }+ }++ let mut current_layers = manifest.layers;+ let mut active_layer_id = manifest.active_layer_id;+ let mut strokes_replayed = 0usize;+ let mut mutations_replayed = 0usize;++ // 2. Replay WAL entries chronologically+ for entry in wal_entries {+ match entry.entry_type {+ WAL_ENTRY_STROKE_TILE_DELTA => {+ if let Ok(raw_td) = inflate_or_raw(&entry.payload, b"TD") {+ if apply_td_wal_frame(&raw_td, &mut grids_by_layer).is_ok() {+ strokes_replayed += 1;+ }+ }+ }+ WAL_ENTRY_LAYER_MUTATION => {+ if let Ok(raw_json) = inflate_or_raw(&entry.payload, b"{") {+ if let Ok(mut_payload) =+ serde_json::from_slice::<LayerMutationWalPayload>(&raw_json)+ {+ if !mut_payload.layers.is_empty() {+ current_layers = mut_payload.layers;+ if mut_payload.active_layer_id.is_some() {+ active_layer_id = mut_payload.active_layer_id;+ }+ mutations_replayed += 1;+ }+ }+ }+ }+ _ => {}+ }+ }++ let nodes: Vec<LayerNode> = current_layers+ .into_iter()+ .map(|meta| {+ let fmt = meta+ .expression_color+ .map(ExpressionColor::to_tile_format)+ .unwrap_or(TileFormat::Color32Bit);+ let grid = grids_by_layer+ .remove(&meta.id)+ .unwrap_or_else(|| SparseLayerGrid::new(fmt));+ LayerNode { meta, grid }+ })+ .collect();++ let mut doc = Document::from_layers(+ doc_id,+ manifest.document_name,+ dims,+ manifest.color_mode,+ nodes,+ active_layer_id,+ max_history_steps,+ );+ doc.work_time_ms = manifest.work_time_ms;+ doc.timelapse = manifest.timelapse;+ Ok((doc, strokes_replayed, mutations_replayed))+}++fn apply_inkg_snapshot(+ buf: &[u8],+ grids: &mut HashMap<String, SparseLayerGrid>,+) -> Result<(), String> {+ if buf.len() < 9 || &buf[0..4] != b"INKG" || buf[4] != 1 {+ return Err("Invalid INKG v1 snapshot header".to_string());+ }+ let mut off = 5usize;+ let fmt_count = u32::from_le_bytes(buf[off..off + 4].try_into().unwrap()) as usize;+ off += 4;+ for _ in 0..fmt_count {+ if off + 2 > buf.len() {+ return Err("Truncated INKG format table".to_string());+ }+ let klen = u16::from_le_bytes(buf[off..off + 2].try_into().unwrap()) as usize;+ off += 2;+ if off + klen + 1 > buf.len() {+ return Err("Truncated INKG format entry".to_string());+ }+ let lid = std::str::from_utf8(&buf[off..off + klen])+ .map_err(|_| "Invalid UTF-8 layer ID in INKG".to_string())?+ .to_string();+ off += klen;+ let fmt = TileFormat::from_ink_byte(buf[off]).unwrap_or(TileFormat::Color32Bit);+ off += 1;+ grids+ .entry(lid)+ .or_insert_with(|| SparseLayerGrid::new(fmt))+ .format = fmt;+ }++ if off + 4 > buf.len() {+ return Err("Truncated INKG tile count".to_string());+ }+ let tile_count = u32::from_le_bytes(buf[off..off + 4].try_into().unwrap()) as usize;+ off += 4;++ for _ in 0..tile_count {+ if off + 2 > buf.len() {+ return Err("Truncated INKG tile key length".to_string());+ }+ let klen = u16::from_le_bytes(buf[off..off + 2].try_into().unwrap()) as usize;+ off += 2;+ if off + klen + 17 > buf.len() {+ return Err("Truncated INKG tile metadata".to_string());+ }+ let raw_lid = std::str::from_utf8(&buf[off..off + klen])+ .map_err(|_| "Invalid UTF-8 layer ID in INKG tile".to_string())?;+ off += klen;+ let tx = i32::from_le_bytes(buf[off..off + 4].try_into().unwrap());+ let ty = i32::from_le_bytes(buf[off + 4..off + 8].try_into().unwrap());+ let fmt = TileFormat::from_ink_byte(buf[off + 8]).unwrap_or(TileFormat::Color32Bit);+ let version = u32::from_le_bytes(buf[off + 9..off + 13].try_into().unwrap()) as u64;+ let dlen = u32::from_le_bytes(buf[off + 13..off + 17].try_into().unwrap()) as usize;+ off += 17;+ if off + dlen > buf.len() {+ return Err("Truncated INKG tile data".to_string());+ }+ let data = buf[off..off + dlen].to_vec();+ off += dlen;++ if dlen != fmt.byte_size() {+ continue;+ }+ let coord = TileCoord::new(tx, ty);+ if let Some(real_lid) = raw_lid.strip_suffix("__mask") {+ let g = grids+ .entry(real_lid.to_string())+ .or_insert_with(|| SparseLayerGrid::new(TileFormat::Color32Bit));+ let mut td = TileData::from_raw_auto_compact(TileFormat::Grayscale8Bit, TileKind::Mask, data);+ if version > 0 {+ td.version = version;+ reserve_tile_version(version);+ }+ g.set_mask_tile(coord, Arc::new(td));+ } else {+ let g = grids+ .entry(raw_lid.to_string())+ .or_insert_with(|| SparseLayerGrid::new(fmt));+ let mut td = TileData::from_raw_auto_compact(fmt, TileKind::Raster, data);+ if version > 0 {+ td.version = version;+ reserve_tile_version(version);+ }+ g.set_tile(coord, Arc::new(td));+ }+ }+ Ok(())+}++fn apply_td_wal_frame(+ buf: &[u8],+ grids: &mut HashMap<String, SparseLayerGrid>,+) -> Result<(), String> {+ if buf.len() < 7 || &buf[0..2] != b"TD" || buf[2] != 1 {+ return Err("Invalid TD v1 WAL frame".to_string());+ }+ let count = u32::from_le_bytes(buf[3..7].try_into().unwrap()) as usize;+ let mut off = 7usize;++ for _ in 0..count {+ if off + 2 > buf.len() {+ return Err("Truncated TD key len".to_string());+ }+ let klen = u16::from_le_bytes(buf[off..off + 2].try_into().unwrap()) as usize;+ off += 2;+ if off + klen + 2 > buf.len() {+ return Err("Truncated TD key".to_string());+ }+ let key = std::str::from_utf8(&buf[off..off + klen])+ .map_err(|_| "Invalid UTF-8 key in TD WAL".to_string())?;+ off += klen;+ let fmt = TileFormat::from_ink_byte(buf[off]).unwrap_or(TileFormat::Color32Bit);+ off += 1;++ let has_before = buf[off];+ off += 1;+ if has_before == 1 {+ if off + 4 > buf.len() {+ return Err("Truncated TD before len".to_string());+ }+ let blen = u32::from_le_bytes(buf[off..off + 4].try_into().unwrap()) as usize;+ off += 4;+ if off + blen > buf.len() {+ return Err("Truncated TD before data".to_string());+ }+ off += blen;+ }++ if off >= buf.len() {+ return Err("Truncated TD after flag".to_string());+ }+ let has_after = buf[off];+ off += 1;+ let after_data = if has_after == 1 {+ if off + 4 > buf.len() {+ return Err("Truncated TD after len".to_string());+ }+ let alen = u32::from_le_bytes(buf[off..off + 4].try_into().unwrap()) as usize;+ off += 4;+ if off + alen > buf.len() {+ return Err("Truncated TD after data".to_string());+ }+ let d = buf[off..off + alen].to_vec();+ off += alen;+ Some(d)+ } else {+ None+ };++ // Key format: `layerId:tx:ty` or `layerId__mask:tx:ty`+ let parts: Vec<&str> = key.rsplitn(3, ':').collect();+ if parts.len() != 3 {+ continue;+ }+ let (Ok(ty), Ok(tx)) = (parts[0].parse::<i32>(), parts[1].parse::<i32>()) else {+ continue;+ };+ let raw_lid = parts[2];+ let coord = TileCoord::new(tx, ty);++ if let Some(real_lid) = raw_lid.strip_suffix("__mask") {+ let g = grids+ .entry(real_lid.to_string())+ .or_insert_with(|| SparseLayerGrid::new(TileFormat::Color32Bit));+ if let Some(d) = after_data {+ if d.len() == TileFormat::Grayscale8Bit.byte_size() {+ g.set_mask_tile(+ coord,+ Arc::new(TileData::from_raw_auto_compact(+ TileFormat::Grayscale8Bit,+ TileKind::Mask,+ d,+ )),+ );+ }+ } else {+ g.remove_mask_tile(coord);+ }+ } else {+ let g = grids+ .entry(raw_lid.to_string())+ .or_insert_with(|| SparseLayerGrid::new(fmt));+ if let Some(d) = after_data {+ if d.len() == fmt.byte_size() {+ g.set_tile(+ coord,+ Arc::new(TileData::from_raw_auto_compact(fmt, TileKind::Raster, d)),+ );+ }+ } else {+ g.remove_tile(coord);+ }+ }+ }++ Ok(())+}diff --git a/crates/ink-engine/src/lib.rs b/crates/ink-engine/src/lib.rsnew file mode 100644index 0000000..08d4518--- /dev/null+++ b/crates/ink-engine/src/lib.rs@@ -0,0 +1,181 @@+//! `ink-engine`: Decoupled native Windows `wgpu` (DX12) digital painting engine.+//!+//! Strictly free of `tauri`, `wry`, `tao`, or WebView2 dependencies. Accepts raw GPU+//! surface targets (`IDCompositionVisual` or headless), lock-free SPSC `rtrb` input rings,+//! and typed [`EngineCommand`]s.++pub mod camera;+pub mod clock;+pub mod document;+pub mod engine;+pub mod gpu;+pub mod history;+pub mod hit_test;+pub mod io;+pub mod memory;+pub mod ring;+pub mod shaders;+pub mod stroke;+pub mod tiles;+pub mod types;++#[cfg(test)]+mod phase2_tests;++pub use camera::{+ clamp_zoom, compute_smooth_rotation_delta, doc_to_viewport_css, viewport_css_to_doc,+ NativeCameraNavigator, MAX_ZOOM, MIN_ZOOM,+};+pub use document::{+ BlendMode, CanvasColorMode, CanvasDimensions, ComicFrame, Document, DocumentId,+ DocumentManager, DocumentMetaSnapshot, ExpressionColor, LayerColorLabel, LayerId, LayerNode,+ LayerNodeMeta, LayerPropsPatch, LayerType, ToneDensityType, ToneDotShape,+};+pub use engine::{EngineConfig, EngineHandle};+pub use history::{+ AppliedHistoryChange, CanvasResizeDelta, HistoryEntry, HistoryItemMeta, HistoryStack,+ HistoryStateSnapshot, LayerTreeMutation, SelectiveUndoOutcome,+};+pub use hit_test::{HitTestState, SharedHitTest};+pub use memory::{+ EvictionContext, FileScratchBackend, GpuPoolStats, GpuTilePool, InMemoryScratchBackend,+ MemoryBudgetConfig, MemoryStats, ScratchBackend, ScratchTileWrite, TieredMemoryManager,+ ViewportFrustum,+};+pub use ring::{InputProducers, NavRingProducer, TabletRingProducer, WakeSignal};+pub use stroke::{DabInstance, StrokeDabGenerator};+pub use tiles::{+ CowTileDelta, RectI32, SparseLayerGrid, TileCoord, TileData, TileFormat, TileKey, TileKind,+ TileStorage, TILE_PIXELS, TILE_SIZE,+};+pub use types::{+ BrushParams, CameraState, CursorConfig, EngineCommand, EngineDiagnostics, EngineEvent,+ InteractionPolicy, NativeInputSample, NativeNavEvent, NativeNavGesture, NativeToolKind,+ SurfaceTarget, ThumbnailUpdate, UiRect, ViewportRect, WheelNavMode,+};++#[cfg(test)]+mod tests {+ use super::*;+ use std::time::Duration;++ #[test]+ fn test_headless_dx12_engine_vertical_slice_stroke_and_camera() {+ let (handle, mut producers) = match EngineHandle::spawn(+ SurfaceTarget::Headless {+ width: 320,+ height: 240,+ },+ EngineConfig {+ doc_width: 512,+ doc_height: 512,+ show_checkerboard: true,+ matte_color: [0.086, 0.086, 0.086, 1.0],+ ..Default::default()+ },+ ) {+ Ok(pair) => pair,+ Err(err) => {+ // Allow headless CI environments without a DX12 adapter to report gracefully+ eprintln!("Skipping DX12 headless test (no adapter available): {err}");+ return;+ }+ };++ handle.send_command(EngineCommand::SetVisible(true));+ handle.send_command(EngineCommand::SetViewport(ViewportRect {+ x_px: 0,+ y_px: 0,+ width_px: 320,+ height_px: 240,+ dpr: 1.0,+ }));+ handle.send_command(EngineCommand::SetCamera(CameraState {+ pan_x: 160.0,+ pan_y: 120.0,+ zoom: 0.5,+ rotation: 0.0,+ flip_x: false,+ flip_y: false,+ }));++ let now = clock::now_ms();+ // Push a complete stylus stroke through the lock-free SPSC WinTab ring+ assert_eq!(+ producers.wintab.push_batch(&[+ NativeInputSample {+ phys_x: 120.0,+ phys_y: 100.0,+ pressure: 0.4,+ tilt_x: 0.0,+ tilt_y: 0.0,+ twist: 0.0,+ timestamp_ms: now,+ buttons: 1,+ phase: 1,+ backend: 1,+ },+ NativeInputSample {+ phys_x: 200.0,+ phys_y: 140.0,+ pressure: 0.9,+ tilt_x: 0.0,+ tilt_y: 0.0,+ twist: 0.0,+ timestamp_ms: now + 4.0,+ buttons: 1,+ phase: 2,+ backend: 1,+ },+ NativeInputSample {+ phys_x: 200.0,+ phys_y: 140.0,+ pressure: 0.0,+ tilt_x: 0.0,+ tilt_y: 0.0,+ twist: 0.0,+ timestamp_ms: now + 8.0,+ buttons: 0,+ phase: 3,+ backend: 1,+ },+ ]),+ 3+ );++ // Push a native wheel zoom event through the SPSC nav ring+ assert!(producers.nav.push(NativeNavEvent::Wheel {+ phys_x: 160.0,+ phys_y: 120.0,+ delta_x: 0.0,+ delta_y: -120.0,+ ctrl_held: false,+ shift_held: false,+ timestamp_ms: now + 10.0,+ }));++ // Wait for at least one rendered frame and camera sync event+ let mut saw_camera_zoom = false;+ let deadline = std::time::Instant::now() + Duration::from_secs(3);+ while std::time::Instant::now() < deadline {+ if let Ok(EngineEvent::CameraChanged { camera, .. }) =+ handle.events().recv_timeout(Duration::from_millis(50))+ {+ if camera.zoom > 0.55 {+ saw_camera_zoom = true;+ }+ }+ let d = handle.diagnostics();+ if d.total_frames_rendered >= 1 && saw_camera_zoom {+ break;+ }+ }++ let diag = handle.diagnostics();+ assert!(diag.ready);+ assert_eq!(diag.backend, "DX12");+ assert!(saw_camera_zoom, "native wheel zoom should emit CameraChanged");+ handle.shutdown();+ assert!(!handle.is_running());+ }+}diff --git a/crates/ink-engine/src/memory/gpu_pool.rs b/crates/ink-engine/src/memory/gpu_pool.rsnew file mode 100644index 0000000..d30c043--- /dev/null+++ b/crates/ink-engine/src/memory/gpu_pool.rs@@ -0,0 +1,752 @@+//! L1 GPU VRAM Tile Atlas Pool (`Rgba16Float` `Texture2DArray`) with LRU Eviction+//! and WGSL Compute Mipmap Pyramid Generator (LOD 0 -> 1 -> 2 -> 3).+//!+//! All GPU working tiles are stored in `wgpu::TextureFormat::Rgba16Float` (`256×256`, 512 KB/slot)+//! so blending, filtering, and zoomed-out mipmaps execute with zero 8-bit banding.++use crate::memory::ScratchBackend;+use crate::tiles::{TileCoord, TileData, BYTES_16F, TILE_SIZE};+use bytemuck::{Pod, Zeroable};+use std::borrow::Cow;+use std::collections::HashMap;++/// WGSL Compute Shader for 2×2 premultiplied-alpha box-filtered mipmap downsampling+/// (`4 child Rgba16Float tiles at LOD k-1 -> 1 parent Rgba16Float tile at LOD k`).+///+/// Writes into a dedicated `256×256` `rgba16float` storage scratch texture (avoiding+/// simultaneous read+write hazards on the atlas array), followed by an L2-speed VRAM copy+/// into the target atlas slice.+pub const MIPMAP_COMPUTE_WGSL: &str = r#"+struct MipmapParams {+ // Atlas slice indices for the 4 child quadrants (TL, TR, BL, BR).+ // Negative value (< 0) indicates an unallocated/transparent quadrant.+ child_slots: vec4<i32>,+ _pad: vec4<u32>,+};++@group(0) @binding(0) var<uniform> params: MipmapParams;+@group(0) @binding(1) var atlas_src: texture_2d_array<f32>;+@group(0) @binding(2) var dst_tile: texture_storage_2d<rgba16float, write>;++@compute @workgroup_size(16, 16, 1)+fn cs_downsample(@builtin(global_invocation_id) gid: vec3<u32>) {+ if (gid.x >= 256u || gid.y >= 256u) {+ return;+ }++ let qx = gid.x >> 7u; // 0 (left) or 1 (right)+ let qy = gid.y >> 7u; // 0 (top) or 1 (bottom)+ let q_idx = qy * 2u + qx;++ var child_slot: i32 = -1;+ switch (q_idx) {+ case 0u: { child_slot = params.child_slots.x; }+ case 1u: { child_slot = params.child_slots.y; }+ case 2u: { child_slot = params.child_slots.z; }+ default: { child_slot = params.child_slots.w; }+ }++ if (child_slot < 0) {+ textureStore(dst_tile, vec2<i32>(i32(gid.x), i32(gid.y)), vec4<f32>(0.0));+ return;+ }++ let local_x = i32((gid.x & 127u) << 1u);+ let local_y = i32((gid.y & 127u) << 1u);++ let p00 = textureLoad(atlas_src, vec2<i32>(local_x, local_y), child_slot, 0);+ let p10 = textureLoad(atlas_src, vec2<i32>(local_x + 1, local_y), child_slot, 0);+ let p01 = textureLoad(atlas_src, vec2<i32>(local_x, local_y + 1), child_slot, 0);+ let p11 = textureLoad(atlas_src, vec2<i32>(local_x + 1, local_y + 1), child_slot, 0);++ // Alpha-weighted (premultiplied) box filter prevents dark halos around anti-aliased ink+ let a0 = p00.a;+ let a1 = p10.a;+ let a2 = p01.a;+ let a3 = p11.a;+ let sum_a = a0 + a1 + a2 + a3;++ var out_px: vec4<f32>;+ if (sum_a <= 1e-5) {+ out_px = vec4<f32>(0.0);+ } else {+ let rgb = (p00.rgb * a0 + p10.rgb * a1 + p01.rgb * a2 + p11.rgb * a3) / sum_a;+ out_px = vec4<f32>(clamp(rgb, vec3<f32>(0.0), vec3<f32>(1.0)), clamp(sum_a * 0.25, 0.0, 1.0));+ }++ textureStore(dst_tile, vec2<i32>(i32(gid.x), i32(gid.y)), out_px);+}+"#;++#[repr(C)]+#[derive(Debug, Clone, Copy, Pod, Zeroable)]+struct MipmapUniforms {+ child_slots: [i32; 4],+ _pad: [u32; 4],+}++/// Key identifying a single GPU-resident tile slice inside the L1 VRAM atlas.+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+pub struct GpuTileKey {+ pub doc_id: String,+ pub layer_id: String,+ pub lod: u8,+ pub coord: TileCoord,+}++#[derive(Debug, Clone)]+struct SlotRecord {+ key: Option<GpuTileKey>,+ version: u64,+ last_used_frame: u64,+}++/// Live L1 GPU VRAM tile atlas telemetry.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub struct GpuPoolStats {+ pub slots_used: u32,+ pub slots_capacity: u32,+ pub used_bytes: u64,+ pub capacity_bytes: u64,+ pub evictions: u64,+ pub mipmaps_generated: u64,+}++/// L1 GPU VRAM tiled atlas (`256×256×N` `Rgba16Float`) + LRU allocator + compute mipmap generator.+pub struct GpuTilePool {+ atlas_texture: wgpu::Texture,+ atlas_array_view: wgpu::TextureView,+ capacity: u32,++ // Dedicated 256×256 Rgba16Float storage target for compute mipmap output (512 KB)+ mipmap_scratch_tex: wgpu::Texture,+ mipmap_uniform_buf: wgpu::Buffer,+ mipmap_bind_group: wgpu::BindGroup,+ mipmap_pipeline: wgpu::ComputePipeline,++ // Compact R8Unorm 2D array pool for non-destructive 8-bit layer mask tiles (64 KB/slot)+ mask_atlas_texture: wgpu::Texture,+ mask_atlas_view: wgpu::TextureView,+ mask_capacity: u32,+ mask_slots: Vec<SlotRecord>,+ mask_key_to_slot: HashMap<GpuTileKey, u32>,++ slots: Vec<SlotRecord>,+ key_to_slot: HashMap<GpuTileKey, u32>,+ frame_counter: u64,+ evictions: u64,+ mipmaps_generated: u64,+}++impl GpuTilePool {+ /// Creates a new L1 GPU VRAM tile atlas sized for `vram_budget_bytes` (clamped safely to+ /// hardware `max_texture_array_layers`, minimum 16 slots so small test pools always work).+ pub fn new(device: &wgpu::Device, vram_budget_bytes: u64) -> Self {+ let max_layers = device.limits().max_texture_array_layers.max(16);+ let desired_slots = (vram_budget_bytes / BYTES_16F as u64).clamp(16, max_layers as u64) as u32;+ let capacity = desired_slots.min(max_layers);+ let mask_capacity = (capacity / 4).clamp(16, max_layers);++ let (atlas_texture, atlas_array_view) = Self::create_atlas_texture(device, capacity);+ let (mask_atlas_texture, mask_atlas_view) = Self::create_mask_atlas(device, mask_capacity);++ let mipmap_scratch_tex = device.create_texture(&wgpu::TextureDescriptor {+ label: Some("ink-mipmap-scratch-rgba16f"),+ size: wgpu::Extent3d {+ width: TILE_SIZE as u32,+ height: TILE_SIZE as u32,+ depth_or_array_layers: 1,+ },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: wgpu::TextureFormat::Rgba16Float,+ usage: wgpu::TextureUsages::STORAGE_BINDING+ | wgpu::TextureUsages::COPY_SRC+ | wgpu::TextureUsages::TEXTURE_BINDING,+ view_formats: &[],+ });+ let mipmap_scratch_view =+ mipmap_scratch_tex.create_view(&wgpu::TextureViewDescriptor::default());++ let mipmap_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("ink-mipmap-uniforms"),+ size: std::mem::size_of::<MipmapUniforms>() as u64,+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });++ let mipmap_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("ink-mipmap-bgl"),+ entries: &[+ wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::COMPUTE,+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Uniform,+ has_dynamic_offset: false,+ min_binding_size: None,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 1,+ visibility: wgpu::ShaderStages::COMPUTE,+ ty: wgpu::BindingType::Texture {+ sample_type: wgpu::TextureSampleType::Float { filterable: false },+ view_dimension: wgpu::TextureViewDimension::D2Array,+ multisampled: false,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 2,+ visibility: wgpu::ShaderStages::COMPUTE,+ ty: wgpu::BindingType::StorageTexture {+ access: wgpu::StorageTextureAccess::WriteOnly,+ format: wgpu::TextureFormat::Rgba16Float,+ view_dimension: wgpu::TextureViewDimension::D2,+ },+ count: None,+ },+ ],+ });++ let mipmap_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("ink-mipmap-bg"),+ layout: &mipmap_bgl,+ entries: &[+ wgpu::BindGroupEntry {+ binding: 0,+ resource: mipmap_uniform_buf.as_entire_binding(),+ },+ wgpu::BindGroupEntry {+ binding: 1,+ resource: wgpu::BindingResource::TextureView(&atlas_array_view),+ },+ wgpu::BindGroupEntry {+ binding: 2,+ resource: wgpu::BindingResource::TextureView(&mipmap_scratch_view),+ },+ ],+ });++ let mipmap_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {+ label: Some("ink-mipmap-compute-shader"),+ source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(MIPMAP_COMPUTE_WGSL)),+ });+ let mipmap_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {+ label: Some("ink-mipmap-pl"),+ bind_group_layouts: &[Some(&mipmap_bgl)],+ immediate_size: 0,+ });+ let mipmap_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {+ label: Some("ink-mipmap-compute-pipeline"),+ layout: Some(&mipmap_pl),+ module: &mipmap_shader,+ entry_point: Some("cs_downsample"),+ compilation_options: Default::default(),+ cache: None,+ });++ let slots = (0..capacity)+ .map(|_| SlotRecord {+ key: None,+ version: 0,+ last_used_frame: 0,+ })+ .collect();+ let mask_slots = (0..mask_capacity)+ .map(|_| SlotRecord {+ key: None,+ version: 0,+ last_used_frame: 0,+ })+ .collect();++ Self {+ atlas_texture,+ atlas_array_view,+ capacity,+ mipmap_scratch_tex,+ mipmap_uniform_buf,+ mipmap_bind_group,+ mipmap_pipeline,+ mask_atlas_texture,+ mask_atlas_view,+ mask_capacity,+ mask_slots,+ mask_key_to_slot: HashMap::with_capacity(mask_capacity as usize),+ slots,+ key_to_slot: HashMap::with_capacity(capacity as usize),+ frame_counter: 1,+ evictions: 0,+ mipmaps_generated: 0,+ }+ }++ fn create_atlas_texture(+ device: &wgpu::Device,+ capacity: u32,+ ) -> (wgpu::Texture, wgpu::TextureView) {+ let texture = device.create_texture(&wgpu::TextureDescriptor {+ label: Some("ink-l1-tile-atlas-rgba16f"),+ size: wgpu::Extent3d {+ width: TILE_SIZE as u32,+ height: TILE_SIZE as u32,+ depth_or_array_layers: capacity,+ },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: wgpu::TextureFormat::Rgba16Float,+ usage: wgpu::TextureUsages::TEXTURE_BINDING+ | wgpu::TextureUsages::COPY_DST+ | wgpu::TextureUsages::COPY_SRC+ | wgpu::TextureUsages::RENDER_ATTACHMENT,+ view_formats: &[],+ });+ let view = texture.create_view(&wgpu::TextureViewDescriptor {+ label: Some("ink-l1-tile-atlas-view"),+ dimension: Some(wgpu::TextureViewDimension::D2Array),+ ..Default::default()+ });+ (texture, view)+ }++ fn create_mask_atlas(+ device: &wgpu::Device,+ capacity: u32,+ ) -> (wgpu::Texture, wgpu::TextureView) {+ let texture = device.create_texture(&wgpu::TextureDescriptor {+ label: Some("ink-l1-mask-atlas-r8"),+ size: wgpu::Extent3d {+ width: TILE_SIZE as u32,+ height: TILE_SIZE as u32,+ depth_or_array_layers: capacity,+ },+ 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: &[],+ });+ let view = texture.create_view(&wgpu::TextureViewDescriptor {+ label: Some("ink-l1-mask-atlas-view"),+ dimension: Some(wgpu::TextureViewDimension::D2Array),+ ..Default::default()+ });+ (texture, view)+ }++ #[inline]+ pub fn begin_frame(&mut self) {+ self.frame_counter = self.frame_counter.saturating_add(1);+ }++ #[inline]+ pub fn atlas_texture(&self) -> &wgpu::Texture {+ &self.atlas_texture+ }++ #[inline]+ pub fn atlas_view(&self) -> &wgpu::TextureView {+ &self.atlas_array_view+ }++ #[inline]+ pub fn mask_atlas_view(&self) -> &wgpu::TextureView {+ &self.mask_atlas_view+ }++ #[inline]+ pub fn capacity(&self) -> u32 {+ self.capacity+ }++ pub fn stats(&self) -> GpuPoolStats {+ let used = self.key_to_slot.len() as u32;+ GpuPoolStats {+ slots_used: used,+ slots_capacity: self.capacity,+ used_bytes: used as u64 * BYTES_16F as u64+ + self.mask_key_to_slot.len() as u64 * (TILE_SIZE * TILE_SIZE) as u64,+ capacity_bytes: self.capacity as u64 * BYTES_16F as u64+ + self.mask_capacity as u64 * (TILE_SIZE * TILE_SIZE) as u64,+ evictions: self.evictions,+ mipmaps_generated: self.mipmaps_generated,+ }+ }++ /// Looks up a resident GPU tile slot and touches its LRU timestamp.+ pub fn get_slot(&mut self, key: &GpuTileKey) -> Option<u32> {+ let &slot = self.key_to_slot.get(key)?;+ self.slots[slot as usize].last_used_frame = self.frame_counter;+ Some(slot)+ }++ /// Allocates a free slot or evicts the least-recently-used slot from the L1 VRAM pool.+ pub fn acquire_slot(&mut self, key: GpuTileKey, version: u64) -> u32 {+ if let Some(&existing) = self.key_to_slot.get(&key) {+ let rec = &mut self.slots[existing as usize];+ rec.version = version;+ rec.last_used_frame = self.frame_counter;+ return existing;+ }++ // First look for an empty slot+ for (i, rec) in self.slots.iter_mut().enumerate() {+ if rec.key.is_none() {+ rec.key = Some(key.clone());+ rec.version = version;+ rec.last_used_frame = self.frame_counter;+ self.key_to_slot.insert(key, i as u32);+ return i as u32;+ }+ }++ // Pool full -> evict the strictly least-recently-used slot+ let mut victim_idx = 0usize;+ let mut oldest_frame = u64::MAX;+ for (i, rec) in self.slots.iter().enumerate() {+ if rec.last_used_frame < oldest_frame {+ oldest_frame = rec.last_used_frame;+ victim_idx = i;+ }+ }++ if let Some(old_key) = self.slots[victim_idx].key.take() {+ self.key_to_slot.remove(&old_key);+ self.evictions = self.evictions.saturating_add(1);+ }+ self.slots[victim_idx] = SlotRecord {+ key: Some(key.clone()),+ version,+ last_used_frame: self.frame_counter,+ };+ self.key_to_slot.insert(key, victim_idx as u32);+ victim_idx as u32+ }++ /// Ensures a CPU/L2/L3 [`TileData`] is uploaded to an L1 VRAM `Rgba16Float` slot,+ /// skipping redundant GPU uploads when `version` matches.+ pub fn ensure_tile_uploaded(+ &mut self,+ queue: &wgpu::Queue,+ key: GpuTileKey,+ tile: &TileData,+ scratch: Option<&dyn ScratchBackend>,+ ) -> Result<u32, String> {+ if let Some(&slot) = self.key_to_slot.get(&key) {+ let rec = &mut self.slots[slot as usize];+ rec.last_used_frame = self.frame_counter;+ if rec.version == tile.version {+ return Ok(slot);+ }+ }++ let rgba16f = tile.to_rgba16f(scratch)?;+ let slot = self.acquire_slot(key, tile.version);+ self.upload_rgba16f_slot(queue, slot, &rgba16f);+ Ok(slot)+ }++ /// Directly writes 524,288 bytes of `Rgba16Float` pixel data into `slot`.+ pub fn upload_rgba16f_slot(&self, queue: &wgpu::Queue, slot: u32, rgba16f: &[u8]) {+ debug_assert_eq!(rgba16f.len(), BYTES_16F);+ queue.write_texture(+ wgpu::TexelCopyTextureInfo {+ texture: &self.atlas_texture,+ mip_level: 0,+ origin: wgpu::Origin3d {+ x: 0,+ y: 0,+ z: slot,+ },+ aspect: wgpu::TextureAspect::All,+ },+ rgba16f,+ wgpu::TexelCopyBufferLayout {+ offset: 0,+ bytes_per_row: Some((TILE_SIZE * 8) as u32), // 2048 bytes (multiple of 256)+ rows_per_image: Some(TILE_SIZE as u32),+ },+ wgpu::Extent3d {+ width: TILE_SIZE as u32,+ height: TILE_SIZE as u32,+ depth_or_array_layers: 1,+ },+ );+ }++ /// Uploads an 8-bit mask tile (`65,536` bytes) into the compact `R8Unorm` mask atlas.+ pub fn ensure_mask_uploaded(+ &mut self,+ queue: &wgpu::Queue,+ key: GpuTileKey,+ tile: &TileData,+ scratch: Option<&dyn ScratchBackend>,+ ) -> Result<u32, String> {+ if let Some(&slot) = self.mask_key_to_slot.get(&key) {+ let rec = &mut self.mask_slots[slot as usize];+ rec.last_used_frame = self.frame_counter;+ if rec.version == tile.version {+ return Ok(slot);+ }+ }+ let raw_mask = tile.materialize_raw(scratch)?;+ let slot = self.acquire_mask_slot(key, tile.version);+ queue.write_texture(+ wgpu::TexelCopyTextureInfo {+ texture: &self.mask_atlas_texture,+ mip_level: 0,+ origin: wgpu::Origin3d {+ x: 0,+ y: 0,+ z: slot,+ },+ aspect: wgpu::TextureAspect::All,+ },+ &raw_mask,+ wgpu::TexelCopyBufferLayout {+ offset: 0,+ bytes_per_row: Some(TILE_SIZE as u32), // 256 bytes (exact alignment!)+ rows_per_image: Some(TILE_SIZE as u32),+ },+ wgpu::Extent3d {+ width: TILE_SIZE as u32,+ height: TILE_SIZE as u32,+ depth_or_array_layers: 1,+ },+ );+ Ok(slot)+ }++ fn acquire_mask_slot(&mut self, key: GpuTileKey, version: u64) -> u32 {+ if let Some(&existing) = self.mask_key_to_slot.get(&key) {+ let rec = &mut self.mask_slots[existing as usize];+ rec.version = version;+ rec.last_used_frame = self.frame_counter;+ return existing;+ }+ for (i, rec) in self.mask_slots.iter_mut().enumerate() {+ if rec.key.is_none() {+ rec.key = Some(key.clone());+ rec.version = version;+ rec.last_used_frame = self.frame_counter;+ self.mask_key_to_slot.insert(key, i as u32);+ return i as u32;+ }+ }+ let mut victim = 0usize;+ let mut oldest = u64::MAX;+ for (i, rec) in self.mask_slots.iter().enumerate() {+ if rec.last_used_frame < oldest {+ oldest = rec.last_used_frame;+ victim = i;+ }+ }+ if let Some(old) = self.mask_slots[victim].key.take() {+ self.mask_key_to_slot.remove(&old);+ }+ self.mask_slots[victim] = SlotRecord {+ key: Some(key.clone()),+ version,+ last_used_frame: self.frame_counter,+ };+ self.mask_key_to_slot.insert(key, victim as u32);+ victim as u32+ }++ /// Generates a parent mipmap tile (LOD `target_lod` in `1..=3`) on the GPU using the+ /// `cs_downsample` compute shader from up to 4 child atlas slots `(TL, TR, BL, BR)`.+ ///+ /// Pass `None` for any unallocated/empty child quadrant. Returns the destination atlas slot.+ pub fn generate_mipmap_tile(+ &mut self,+ device: &wgpu::Device,+ queue: &wgpu::Queue,+ parent_key: GpuTileKey,+ child_slots: [Option<u32>; 4],+ version: u64,+ ) -> u32 {+ let dst_slot = self.acquire_slot(parent_key, version);+ let uniforms = MipmapUniforms {+ child_slots: [+ child_slots[0].map(|s| s as i32).unwrap_or(-1),+ child_slots[1].map(|s| s as i32).unwrap_or(-1),+ child_slots[2].map(|s| s as i32).unwrap_or(-1),+ child_slots[3].map(|s| s as i32).unwrap_or(-1),+ ],+ _pad: [0; 4],+ };+ queue.write_buffer(&self.mipmap_uniform_buf, 0, bytemuck::bytes_of(&uniforms));++ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {+ label: Some("ink-mipmap-compute-encoder"),+ });++ {+ let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {+ label: Some("ink-mipmap-compute-pass"),+ timestamp_writes: None,+ });+ pass.set_pipeline(&self.mipmap_pipeline);+ pass.set_bind_group(0, &self.mipmap_bind_group, &[]);+ // 256 / 16 = 16 workgroups along X and Y+ pass.dispatch_workgroups(16, 16, 1);+ }++ // Copy compute output from scratch 2D texture into destination atlas slice+ encoder.copy_texture_to_texture(+ wgpu::TexelCopyTextureInfo {+ texture: &self.mipmap_scratch_tex,+ mip_level: 0,+ origin: wgpu::Origin3d::ZERO,+ aspect: wgpu::TextureAspect::All,+ },+ wgpu::TexelCopyTextureInfo {+ texture: &self.atlas_texture,+ mip_level: 0,+ origin: wgpu::Origin3d {+ x: 0,+ y: 0,+ z: dst_slot,+ },+ aspect: wgpu::TextureAspect::All,+ },+ wgpu::Extent3d {+ width: TILE_SIZE as u32,+ height: TILE_SIZE as u32,+ depth_or_array_layers: 1,+ },+ );++ queue.submit(Some(encoder.finish()));+ self.mipmaps_generated = self.mipmaps_generated.saturating_add(1);+ dst_slot+ }++ /// Reads back a `256×256` `Rgba16Float` atlas slice (524,288 bytes) from GPU VRAM into CPU memory.+ pub fn readback_slot_rgba16f(+ &self,+ device: &wgpu::Device,+ queue: &wgpu::Queue,+ slot: u32,+ ) -> Result<Vec<u8>, String> {+ let staging = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("ink-tile-readback-staging"),+ size: BYTES_16F as u64,+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,+ mapped_at_creation: false,+ });++ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {+ label: Some("ink-tile-readback-encoder"),+ });+ encoder.copy_texture_to_buffer(+ wgpu::TexelCopyTextureInfo {+ texture: &self.atlas_texture,+ mip_level: 0,+ origin: wgpu::Origin3d {+ x: 0,+ y: 0,+ z: slot,+ },+ aspect: wgpu::TextureAspect::All,+ },+ wgpu::TexelCopyBufferInfo {+ buffer: &staging,+ layout: wgpu::TexelCopyBufferLayout {+ offset: 0,+ bytes_per_row: Some((TILE_SIZE * 8) as u32), // 2048 bytes (aligned to 256)+ rows_per_image: Some(TILE_SIZE as u32),+ },+ },+ wgpu::Extent3d {+ width: TILE_SIZE as u32,+ height: TILE_SIZE as u32,+ depth_or_array_layers: 1,+ },+ );+ queue.submit(Some(encoder.finish()));++ let slice = staging.slice(..);+ let (tx, rx) = std::sync::mpsc::channel();+ slice.map_async(wgpu::MapMode::Read, move |res| {+ let _ = tx.send(res);+ });+ let _ = device.poll(wgpu::PollType::wait_indefinitely());+ rx.recv()+ .map_err(|_| "GPU readback channel closed".to_string())?+ .map_err(|e| format!("GPU readback map_async failed: {e}"))?;++ let data = slice+ .get_mapped_range()+ .map_err(|e| format!("GPU readback get_mapped_range failed: {e}"))?+ .to_vec();+ staging.unmap();+ Ok(data)+ }++ /// Invalidates all cached VRAM slices belonging to a document.+ pub fn invalidate_document(&mut self, doc_id: &str) {+ self.key_to_slot.retain(|k, &mut slot| {+ if k.doc_id == doc_id {+ self.slots[slot as usize].key = None;+ self.slots[slot as usize].version = 0;+ false+ } else {+ true+ }+ });+ self.mask_key_to_slot.retain(|k, &mut slot| {+ if k.doc_id == doc_id {+ self.mask_slots[slot as usize].key = None;+ self.mask_slots[slot as usize].version = 0;+ false+ } else {+ true+ }+ });+ }++ /// Invalidates all cached VRAM slices belonging to a specific layer.+ pub fn invalidate_layer(&mut self, doc_id: &str, layer_id: &str) {+ self.key_to_slot.retain(|k, &mut slot| {+ if k.doc_id == doc_id && k.layer_id == layer_id {+ self.slots[slot as usize].key = None;+ self.slots[slot as usize].version = 0;+ false+ } else {+ true+ }+ });+ self.mask_key_to_slot.retain(|k, &mut slot| {+ if k.doc_id == doc_id && k.layer_id == layer_id {+ self.mask_slots[slot as usize].key = None;+ self.mask_slots[slot as usize].version = 0;+ false+ } else {+ true+ }+ });+ }++ /// Flushes all resident slots (e.g. explicit GPU cache purge).+ pub fn flush_all(&mut self) {+ self.key_to_slot.clear();+ for rec in &mut self.slots {+ rec.key = None;+ rec.version = 0;+ rec.last_used_frame = 0;+ }+ self.mask_key_to_slot.clear();+ for rec in &mut self.mask_slots {+ rec.key = None;+ rec.version = 0;+ rec.last_used_frame = 0;+ }+ }+}diff --git a/crates/ink-engine/src/memory/mod.rs b/crates/ink-engine/src/memory/mod.rsnew file mode 100644index 0000000..df855da--- /dev/null+++ b/crates/ink-engine/src/memory/mod.rs@@ -0,0 +1,12 @@+//! Tiered memory management across L1 (GPU VRAM `Rgba16Float` `Texture2DArray` pool),+//! L2 (CPU RAM LZ4-compressed cold tiles), and L3 (in-process scratch disk).++pub mod gpu_pool;+pub mod scratch;+pub mod tiered;++pub use gpu_pool::{GpuPoolStats, GpuTileKey, GpuTilePool, MIPMAP_COMPUTE_WGSL};+pub use scratch::{FileScratchBackend, InMemoryScratchBackend, ScratchBackend, ScratchTileWrite};+pub use tiered::{+ EvictionContext, MemoryBudgetConfig, MemoryStats, TieredMemoryManager, ViewportFrustum,+};diff --git a/crates/ink-engine/src/memory/scratch.rs b/crates/ink-engine/src/memory/scratch.rsnew file mode 100644index 0000000..4f87623--- /dev/null+++ b/crates/ink-engine/src/memory/scratch.rs@@ -0,0 +1,190 @@+//! Decoupled L3 Scratch Disk backend trait & pure-Rust implementations.+//!+//! `crates/ink-engine` has zero Tauri dependencies: the desktop host (`src-tauri`)+//! supplies an in-process adapter directly wrapping `src-tauri/src/scratch_disk.rs`+//! (zero Tauri IPC!), while pure unit/headless tests use [`InMemoryScratchBackend`]+//! or [`FileScratchBackend`].++use parking_lot::RwLock;+use std::collections::HashMap;+use std::path::PathBuf;++/// Single uncompressed tile payload written to L3 scratch storage.+#[derive(Debug, Clone)]+pub struct ScratchTileWrite {+ pub layer_key: String,+ pub tx: i32,+ pub ty: i32,+ pub data: Vec<u8>,+}++/// Thread-safe, synchronous in-process L3 scratch disk storage contract.+pub trait ScratchBackend: Send + Sync {+ fn init_session(&self, session_id: &str) -> Result<(), String>;+ fn write_tiles(&self, session_id: &str, tiles: Vec<ScratchTileWrite>) -> Result<usize, String>;+ fn read_tile(+ &self,+ session_id: &str,+ layer_key: &str,+ tx: i32,+ ty: i32,+ ) -> Result<Vec<u8>, String>;+ fn clear_session(&self, session_id: &str) -> Result<(), String>;+}++type ScratchTileKey = (String, String, i32, i32);++/// Fast in-memory LZ4-backed scratch disk used by unit tests and headless engine instances.+#[derive(Default)]+pub struct InMemoryScratchBackend {+ /// `(session_id, layer_key, tx, ty) -> lz4_flex::compress_prepend_size(raw)`+ store: RwLock<HashMap<ScratchTileKey, Vec<u8>>>,+}++impl InMemoryScratchBackend {+ pub fn new() -> Self {+ Self::default()+ }++ pub fn tile_count(&self) -> usize {+ self.store.read().len()+ }++ pub fn compressed_bytes(&self) -> usize {+ self.store.read().values().map(|v| v.len()).sum()+ }+}++impl ScratchBackend for InMemoryScratchBackend {+ fn init_session(&self, _session_id: &str) -> Result<(), String> {+ Ok(())+ }++ fn write_tiles(&self, session_id: &str, tiles: Vec<ScratchTileWrite>) -> Result<usize, String> {+ let count = tiles.len();+ let mut guard = self.store.write();+ for t in tiles {+ let compressed = lz4_flex::compress_prepend_size(&t.data);+ guard.insert((session_id.to_string(), t.layer_key, t.tx, t.ty), compressed);+ }+ Ok(count)+ }++ fn read_tile(+ &self,+ session_id: &str,+ layer_key: &str,+ tx: i32,+ ty: i32,+ ) -> Result<Vec<u8>, String> {+ let guard = self.store.read();+ let compressed = guard+ .get(&(session_id.to_string(), layer_key.to_string(), tx, ty))+ .ok_or_else(|| {+ format!(+ "Tile not found in InMemoryScratchBackend (session={session_id}, layer={layer_key}, [{tx},{ty}])"+ )+ })?;+ lz4_flex::decompress_size_prepended(compressed)+ .map_err(|e| format!("Failed to decompress scratch tile: {e}"))+ }++ fn clear_session(&self, session_id: &str) -> Result<(), String> {+ let mut guard = self.store.write();+ guard.retain(|(sid, _, _, _), _| sid != session_id);+ Ok(())+ }+}++/// Standalone filesystem-backed scratch disk for pure-Rust / non-Tauri hosts.+pub struct FileScratchBackend {+ base_dir: PathBuf,+ use_lz4: bool,+}++impl FileScratchBackend {+ pub fn new(base_dir: PathBuf, use_lz4: bool) -> Self {+ Self { base_dir, use_lz4 }+ }++ fn sanitize(raw: &str) -> String {+ let s: String = raw+ .chars()+ .map(|c| {+ if c.is_ascii_alphanumeric() || c == '-' || c == '_' {+ c+ } else {+ '_'+ }+ })+ .collect();+ if s.is_empty() {+ "default".to_string()+ } else {+ s+ }+ }++ fn tile_path(&self, session_id: &str, layer_key: &str, tx: i32, ty: i32) -> PathBuf {+ self.base_dir+ .join(Self::sanitize(session_id))+ .join(format!("{}_{}_{}.tile", Self::sanitize(layer_key), tx, ty))+ }+}++impl ScratchBackend for FileScratchBackend {+ fn init_session(&self, session_id: &str) -> Result<(), String> {+ let dir = self.base_dir.join(Self::sanitize(session_id));+ std::fs::create_dir_all(&dir)+ .map_err(|e| format!("Failed to create scratch session dir: {e}"))+ }++ fn write_tiles(&self, session_id: &str, tiles: Vec<ScratchTileWrite>) -> Result<usize, String> {+ self.init_session(session_id)?;+ let count = tiles.len();+ for t in tiles {+ let path = self.tile_path(session_id, &t.layer_key, t.tx, t.ty);+ let mut payload = Vec::with_capacity(t.data.len() + 1);+ if self.use_lz4 {+ payload.push(1);+ payload.extend_from_slice(&lz4_flex::compress_prepend_size(&t.data));+ } else {+ payload.push(0);+ payload.extend_from_slice(&t.data);+ }+ std::fs::write(&path, &payload)+ .map_err(|e| format!("Failed to write scratch tile {}: {e}", path.display()))?;+ }+ Ok(count)+ }++ fn read_tile(+ &self,+ session_id: &str,+ layer_key: &str,+ tx: i32,+ ty: i32,+ ) -> Result<Vec<u8>, String> {+ let path = self.tile_path(session_id, layer_key, tx, ty);+ let bytes = std::fs::read(&path)+ .map_err(|e| format!("Failed to read scratch tile {}: {e}", path.display()))?;+ let (&flag, rest) = bytes+ .split_first()+ .ok_or_else(|| "Corrupt empty scratch tile file".to_string())?;+ if flag == 1 {+ lz4_flex::decompress_size_prepended(rest)+ .map_err(|e| format!("Failed to LZ4-decompress scratch tile: {e}"))+ } else {+ Ok(rest.to_vec())+ }+ }++ fn clear_session(&self, session_id: &str) -> Result<(), String> {+ let dir = self.base_dir.join(Self::sanitize(session_id));+ if dir.exists() {+ std::fs::remove_dir_all(&dir)+ .map_err(|e| format!("Failed to remove scratch dir {}: {e}", dir.display()))?;+ }+ Ok(())+ }+}diff --git a/crates/ink-engine/src/memory/tiered.rs b/crates/ink-engine/src/memory/tiered.rsnew file mode 100644index 0000000..fb11c63--- /dev/null+++ b/crates/ink-engine/src/memory/tiered.rs@@ -0,0 +1,390 @@+//! Tiered RAM / LZ4 / Scratch Disk Memory Manager.+//!+//! Enforces configured RAM budgets across all open documents using a 4-tier frustum-aware LRU+//! eviction policy:+//! 1. **L2 Demotion (Raw -> LZ4 RAM):** Cold tiles are LZ4-compressed in place via `lz4_flex`,+//! reclaiming 5–20× memory with zero disk I/O.+//! 2. **L3 Eviction (LZ4/Raw -> Scratch Disk):** When compressed RAM still exceeds the budget,+//! lowest-priority tiles are written directly in-process to [`ScratchBackend`].++use super::scratch::ScratchBackend;+use crate::tiles::{pixel_to_tile_coord, TileCoord, TileData, TileKind, TileStorage};+use serde::{Deserialize, Serialize};+use std::collections::{HashMap, HashSet};+use std::sync::Arc;++/// Viewport bounding box in document pixel coordinates for frustum-aware eviction.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ViewportFrustum {+ pub min_x: i32,+ pub min_y: i32,+ pub max_x: i32,+ pub max_y: i32,+}++/// Runtime memory and history budget configuration mirrored from `performanceManager`.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct MemoryBudgetConfig {+ /// Hard CPU RAM budget for tile data across all open documents (default 1024 MB).+ pub ram_budget_bytes: u64,+ /// Target L1 GPU VRAM tile atlas budget (default 128 MB = 256 `Rgba16Float` slots).+ pub vram_budget_bytes: u64,+ /// Maximum history steps retained per document (clamped 10..=200, default 50).+ pub max_history_steps: usize,+ /// Whether inactive document tabs should eagerly compress to L2/L3 on tab switch.+ pub offload_inactive_tabs: bool,+}++impl Default for MemoryBudgetConfig {+ fn default() -> Self {+ Self {+ ram_budget_bytes: 1024 * 1024 * 1024,+ vram_budget_bytes: 128 * 1024 * 1024,+ max_history_steps: 50,+ offload_inactive_tabs: true,+ }+ }+}++/// Live tiered memory statistics surfaced to React's Performance settings & HUD.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct MemoryStats {+ pub ram_raw_bytes: u64,+ pub ram_lz4_bytes: u64,+ pub ram_total_bytes: u64,+ pub ram_budget_bytes: u64,+ pub disk_paged_tiles: u64,+ pub disk_paged_logical_bytes: u64,+ pub vram_used_bytes: u64,+ pub vram_budget_bytes: u64,+ pub vram_slots_used: u32,+ pub vram_slots_capacity: u32,+ pub solid_tile_count: u64,+ pub raw_tile_count: u64,+ pub lz4_tile_count: u64,+ pub total_tile_count: u64,+ pub history_entry_count: u64,+ pub open_document_count: u32,+}++/// Snapshot of active document/layer/frustum state used to prioritize tile eviction.+#[derive(Debug, Clone, Default)]+pub struct EvictionContext {+ pub active_doc_id: Option<String>,+ pub active_layer_id: Option<String>,+ pub frustum: Option<ViewportFrustum>,+ pub hidden_layers: HashSet<(String, String)>, // (doc_id, layer_id)+}++/// Mutable tile reference item passed into [`TieredMemoryManager::enforce_budget`].+pub struct ManagedTileSlot<'a> {+ pub doc_id: &'a str,+ pub layer_id: &'a str,+ pub kind: TileKind,+ pub coord: TileCoord,+ pub tile: &'a mut Arc<TileData>,+}++/// Coordinates L2 LZ4 RAM compression and L3 Scratch Disk paging.+pub struct TieredMemoryManager {+ pub config: MemoryBudgetConfig,+ scratch: Arc<dyn ScratchBackend>,+}++impl TieredMemoryManager {+ pub fn new(config: MemoryBudgetConfig, scratch: Arc<dyn ScratchBackend>) -> Self {+ Self { config, scratch }+ }++ pub fn scratch(&self) -> &Arc<dyn ScratchBackend> {+ &self.scratch+ }++ pub fn scratch_ref(&self) -> &dyn ScratchBackend {+ self.scratch.as_ref()+ }++ pub fn set_budget(&mut self, config: MemoryBudgetConfig) {+ self.config = config;+ }++ /// Computes live memory statistics across a slice of tile references (deduplicating shared CoW `Arc`s+ /// by pointer address so Copy-on-Write snapshots are never double-counted!).+ pub fn compute_stats<'a, I>(+ &self,+ tiles: I,+ history_entry_count: u64,+ open_document_count: u32,+ ) -> MemoryStats+ where+ I: IntoIterator<Item = &'a Arc<TileData>>,+ {+ let mut seen_ptrs: HashSet<*const TileData> = HashSet::new();+ let mut stats = MemoryStats {+ ram_budget_bytes: self.config.ram_budget_bytes,+ vram_budget_bytes: self.config.vram_budget_bytes,+ history_entry_count,+ open_document_count,+ ..Default::default()+ };++ for arc in tiles {+ let ptr = Arc::as_ptr(arc);+ if !seen_ptrs.insert(ptr) {+ continue;+ }+ stats.total_tile_count += 1;+ match &arc.storage {+ TileStorage::SolidColor { .. } => {+ stats.solid_tile_count += 1;+ }+ TileStorage::Raw(v) => {+ stats.raw_tile_count += 1;+ stats.ram_raw_bytes += v.len() as u64;+ }+ TileStorage::CompressedLz4 { compressed, .. } => {+ stats.lz4_tile_count += 1;+ stats.ram_lz4_bytes += compressed.len() as u64;+ }+ TileStorage::PagedToDisk {+ uncompressed_len, ..+ } => {+ stats.disk_paged_tiles += 1;+ stats.disk_paged_logical_bytes += *uncompressed_len as u64;+ }+ }+ }+ stats.ram_total_bytes = stats.ram_raw_bytes + stats.ram_lz4_bytes;+ stats+ }++ /// Enforces `ram_budget_bytes` across all supplied tiles:+ /// - Pass 1 (L2): Compresses lowest-priority `Raw` tiles to `CompressedLz4` (or `SolidColor`)+ /// when total RAM exceeds `soft_target` (80% of budget).+ /// - Pass 2 (L3): Pages lowest-priority remaining `Raw` / `CompressedLz4` tiles to scratch disk+ /// when total RAM still exceeds `ram_budget_bytes` (down to 90% of budget).+ ///+ /// Returns `(lz4_compressed_count, disk_paged_count, bytes_freed)`.+ pub fn enforce_budget(+ &self,+ mut slots: Vec<ManagedTileSlot<'_>>,+ ctx: &EvictionContext,+ ) -> Result<(usize, usize, u64), String> {+ let budget = self.config.ram_budget_bytes.max(1);+ let soft_limit = (budget * 4) / 5; // 80% triggers fast L2 LZ4 compression+ let target_after_evict = (budget * 9) / 10; // 90% target after L3 paging++ let mut total_ram = Self::unique_ram_bytes(&slots);+ if total_ram <= soft_limit {+ return Ok((0, 0, 0));+ }++ // Score every slot by 4-tier frustum-aware LRU priority+ let mut order: Vec<(usize, u8, i64, u64)> = slots+ .iter()+ .enumerate()+ .filter(|(_, s)| s.tile.ram_bytes() > 0)+ .map(|(idx, s)| {+ let (tier, dist) = Self::score_slot(s, ctx);+ (idx, tier, dist, s.tile.last_access_seq)+ })+ .collect();++ order.sort_by(|a, b| {+ a.1.cmp(&b.1)+ .then_with(|| b.2.cmp(&a.2)) // Farthest outside frustum first+ .then_with(|| a.3.cmp(&b.3)) // Oldest access sequence first+ });++ let mut lz4_count = 0usize;+ let mut disk_count = 0usize;+ let mut freed_total = 0u64;++ // Pass 1: Demote Raw -> L2 LZ4 RAM (fast, zero disk I/O)+ for &(idx, _, _, _) in &order {+ if total_ram <= soft_limit {+ break;+ }+ let slot = &mut slots[idx];+ if !matches!(slot.tile.storage, TileStorage::Raw(_)) {+ continue;+ }+ // Only mutate in-place when uniquely owned or make CoW copy (still shrinks total unique RAM+ // if the old Arc is no longer held elsewhere).+ let td = Arc::make_mut(slot.tile);+ let freed = td.demote_to_lz4() as u64;+ if freed > 0 {+ lz4_count += 1;+ freed_total += freed;+ total_ram = total_ram.saturating_sub(freed);+ }+ }++ total_ram = Self::unique_ram_bytes(&slots);+ if total_ram <= budget {+ return Ok((lz4_count, disk_count, freed_total));+ }++ // Pass 2: Demote L2/Raw -> L3 Scratch Disk (in-process zero-IPC write!)+ // Group writes by session_id for batched disk I/O+ let mut to_page: Vec<usize> = Vec::new();+ let mut projected = total_ram;+ for &(idx, _, _, _) in &order {+ if projected <= target_after_evict {+ break;+ }+ let ram = slots[idx].tile.ram_bytes() as u64;+ if ram == 0 {+ continue;+ }+ to_page.push(idx);+ projected = projected.saturating_sub(ram);+ }++ if !to_page.is_empty() {+ let mut initialized_sessions: HashSet<&str> = HashSet::new();+ for idx in to_page {+ let slot = &mut slots[idx];+ if initialized_sessions.insert(slot.doc_id) {+ self.scratch.init_session(slot.doc_id)?;+ }+ let layer_key = match slot.kind {+ TileKind::Raster => slot.layer_id.to_string(),+ TileKind::Mask => format!("{}__mask", slot.layer_id),+ };+ let td = Arc::make_mut(slot.tile);+ let freed = td.demote_to_disk(+ slot.doc_id,+ &layer_key,+ slot.coord,+ self.scratch.as_ref(),+ )? as u64;+ if freed > 0 {+ disk_count += 1;+ freed_total += freed;+ }+ }+ }++ Ok((lz4_count, disk_count, freed_total))+ }++ /// Compresses all `Raw` tiles in `slots` to L2 LZ4 RAM (e.g. when switching away from a tab).+ pub fn compress_all_to_lz4(&self, mut slots: Vec<ManagedTileSlot<'_>>) -> (usize, u64) {+ let mut count = 0usize;+ let mut freed = 0u64;+ for slot in &mut slots {+ if matches!(slot.tile.storage, TileStorage::Raw(_)) {+ let td = Arc::make_mut(slot.tile);+ let f = td.demote_to_lz4() as u64;+ if f > 0 {+ count += 1;+ freed += f;+ }+ }+ }+ (count, freed)+ }++ /// Pages all eligible tiles in `slots` to L3 Scratch Disk (explicit memory purge / tab offload).+ pub fn evict_all_to_disk(+ &self,+ mut slots: Vec<ManagedTileSlot<'_>>,+ ) -> Result<(usize, u64), String> {+ let mut count = 0usize;+ let mut freed = 0u64;+ let mut initialized: HashSet<String> = HashSet::new();+ for slot in &mut slots {+ if slot.tile.ram_bytes() == 0 {+ continue;+ }+ if initialized.insert(slot.doc_id.to_string()) {+ self.scratch.init_session(slot.doc_id)?;+ }+ let layer_key = match slot.kind {+ TileKind::Raster => slot.layer_id.to_string(),+ TileKind::Mask => format!("{}__mask", slot.layer_id),+ };+ let td = Arc::make_mut(slot.tile);+ let f = td.demote_to_disk(+ slot.doc_id,+ &layer_key,+ slot.coord,+ self.scratch.as_ref(),+ )? as u64;+ if f > 0 {+ count += 1;+ freed += f;+ }+ }+ Ok((count, freed))+ }++ fn unique_ram_bytes(slots: &[ManagedTileSlot<'_>]) -> u64 {+ let mut seen: HashMap<*const TileData, usize> = HashMap::with_capacity(slots.len());+ for s in slots {+ seen.entry(Arc::as_ptr(s.tile))+ .or_insert_with(|| s.tile.ram_bytes());+ }+ seen.values().map(|&b| b as u64).sum()+ }++ fn score_slot(slot: &ManagedTileSlot<'_>, ctx: &EvictionContext) -> (u8, i64) {+ let is_active_doc = ctx+ .active_doc_id+ .as_deref()+ .map(|id| id == slot.doc_id)+ .unwrap_or(true);+ if !is_active_doc {+ return (0, i64::MAX / 2);+ }+ let is_hidden = ctx+ .hidden_layers+ .contains(&(slot.doc_id.to_string(), slot.layer_id.to_string()));+ if is_hidden {+ return (0, 0);+ }++ let frustum_dist = if let Some(f) = ctx.frustum {+ let min_tx = pixel_to_tile_coord(f.min_x, 0);+ let max_tx = pixel_to_tile_coord(f.max_x, 0);+ let min_ty = pixel_to_tile_coord(f.min_y, 0);+ let max_ty = pixel_to_tile_coord(f.max_y, 0);+ let dx = if slot.coord.tx < min_tx {+ (min_tx - slot.coord.tx) as i64+ } else if slot.coord.tx > max_tx {+ (slot.coord.tx - max_tx) as i64+ } else {+ 0+ };+ let dy = if slot.coord.ty < min_ty {+ (min_ty - slot.coord.ty) as i64+ } else if slot.coord.ty > max_ty {+ (slot.coord.ty - max_ty) as i64+ } else {+ 0+ };+ dx * dx + dy * dy+ } else {+ 0+ };++ if frustum_dist > 0 {+ return (1, frustum_dist);+ }++ let is_active_layer = ctx+ .active_layer_id+ .as_deref()+ .map(|id| id == slot.layer_id)+ .unwrap_or(false);+ if is_active_layer {+ (3, 0)+ } else {+ (2, 0)+ }+ }+}diff --git a/crates/ink-engine/src/phase2_tests.rs b/crates/ink-engine/src/phase2_tests.rsnew file mode 100644index 0000000..4d1c64b--- /dev/null+++ b/crates/ink-engine/src/phase2_tests.rs@@ -0,0 +1,918 @@+//! Comprehensive Phase 2 Rust unit & headless DX12 GPU verification suite.++use crate::document::{+ BlendMode, CanvasColorMode, CanvasDimensions, Document, DocumentManager, ExpressionColor,+ LayerNodeMeta, LayerPropsPatch,+};+use crate::io::{+ encode_cow_deltas_to_wal_payload, encode_document_checkpoint, parse_ink_document,+ replay_recovery_into_document, serialize_ink_document, WalRawEntry,+};+use crate::memory::{+ FileScratchBackend, GpuTileKey, GpuTilePool, InMemoryScratchBackend, MemoryBudgetConfig,+ ScratchBackend,+};+use crate::tiles::{+ pack_rgba8_to_1bit, pack_rgba8_to_8bit, rgba16f_to_rgba8_dithered, rgba16f_to_rgba8_lossless,+ rgba8_to_rgba16f, unpack_1bit_to_rgba8, unpack_8bit_to_rgba8, RectI32, SparseLayerGrid,+ TileCoord, TileData, TileFormat, TileKind, TileStorage, BYTES_16F, BYTES_1BIT, BYTES_32BIT,+ BYTES_8BIT, TILE_PIXELS, TILE_SIZE,+};+use crate::gpu::GpuRenderer;+use crate::SurfaceTarget;+use half::f16;+use std::sync::Arc;++#[test]+fn test_sparse_virtual_tiles_solid_color_and_compaction() {+ let mut grid = SparseLayerGrid::new(TileFormat::Color32Bit);+ assert_eq!(grid.tiles.len(), 0);++ // 4K solid white fill uses SolidColor tiles with ZERO 256 KB raw buffers allocated!+ grid.fill_solid_layer(4096, 4096, [255, 255, 255, 255]);+ assert_eq!(grid.tiles.len(), 16 * 16);+ for tile in grid.tiles.values() {+ assert!(matches!(+ tile.storage,+ TileStorage::SolidColor {+ rgba8: [255, 255, 255, 255],+ ..+ }+ ));+ assert_eq!(tile.ram_bytes(), 0);+ }++ // Mutate a single pixel at (10, 10) -> promotes ONLY tile (0,0) to Raw+ let red_px = [220u8, 30, 40, 255];+ let touched = grid+ .write_rgba8_rect(&red_px, RectI32::new(10, 10, 1, 1), 128, None)+ .expect("write failed");+ assert_eq!(touched, vec![TileCoord::new(0, 0)]);+ assert!(matches!(+ grid.tiles.get(&TileCoord::new(0, 0)).unwrap().storage,+ TileStorage::Raw(_)+ ));+ // Neighbor tile (1, 0) remains zero-allocation SolidColor+ assert!(matches!(+ grid.tiles.get(&TileCoord::new(1, 0)).unwrap().storage,+ TileStorage::SolidColor {+ rgba8: [255, 255, 255, 255],+ ..+ }+ ));++ // Read back exact pixel+ let read = grid+ .read_rgba8_rect(RectI32::new(10, 10, 1, 1), false, None)+ .expect("read failed");+ assert_eq!(read, red_px);++ // Paint the entire (0,0) tile transparent -> tile is pruned from sparse map completely+ let clear_tile = vec![0u8; BYTES_32BIT];+ grid.write_rgba8_rect(&clear_tile, RectI32::new(0, 0, 256, 256), 128, None)+ .expect("clear write failed");+ assert!(!grid.tiles.contains_key(&TileCoord::new(0, 0)));++ // Paint tile (2,2) solid blue -> auto-compacts back to zero-allocation SolidColor+ let mut blue_tile = vec![0u8; BYTES_32BIT];+ for px in blue_tile.chunks_exact_mut(4) {+ px.copy_from_slice(&[10, 80, 240, 255]);+ }+ grid.write_rgba8_rect(&blue_tile, RectI32::new(512, 512, 256, 256), 128, None)+ .expect("solid blue write failed");+ assert!(matches!(+ grid.tiles.get(&TileCoord::new(2, 2)).unwrap().storage,+ TileStorage::SolidColor {+ rgba8: [10, 80, 240, 255],+ ..+ }+ ));+}++#[test]+fn test_pixel_format_conversions_1bit_8bit_32bit_16f_and_bayer_dithering() {+ assert_eq!(TileFormat::Monochrome1Bit.byte_size(), BYTES_1BIT);+ assert_eq!(TileFormat::Grayscale8Bit.byte_size(), BYTES_8BIT);+ assert_eq!(TileFormat::Color32Bit.byte_size(), BYTES_32BIT);+ assert_eq!(TileFormat::Rgba16Float.byte_size(), BYTES_16F);++ // 1. Lossless Color32Bit <-> Rgba16Float round-trip for ALL 256 channel intensities+ let mut rgba_in = vec![0u8; BYTES_32BIT];+ for i in 0..TILE_PIXELS {+ let v = (i & 255) as u8;+ rgba_in[i * 4] = v;+ rgba_in[i * 4 + 1] = 255 - v;+ rgba_in[i * 4 + 2] = v.wrapping_mul(3);+ rgba_in[i * 4 + 3] = 255;+ }+ let mut f16_buf = vec![0u8; BYTES_16F];+ rgba8_to_rgba16f(&rgba_in, &mut f16_buf);+ let mut rgba_out = vec![0u8; BYTES_32BIT];+ rgba16f_to_rgba8_lossless(&f16_buf, &mut rgba_out);+ assert_eq!(rgba_in, rgba_out, "Color32Bit <-> Rgba16Float must be bit-exact lossless");++ // 2. Bayer 4x4 ordered dithering preserves exact 0 and 255 endpoints while dithering mid-values+ let mut grad_f16 = vec![0u8; BYTES_16F];+ for i in 0..TILE_PIXELS {+ let off = i * 8;+ let x = i % TILE_SIZE;+ let val = if x == 0 {+ 0.0f32+ } else if x == 1 {+ 1.0f32+ } else {+ // Exact half-step 127.5 / 255.0 where Bayer dithering produces balanced 127/128 pattern+ 127.5 / 255.0+ };+ let h = f16::from_f32(val).to_le_bytes();+ let one = f16::from_f32(1.0).to_le_bytes();+ grad_f16[off..off + 2].copy_from_slice(&h);+ grad_f16[off + 2..off + 4].copy_from_slice(&h);+ grad_f16[off + 4..off + 6].copy_from_slice(&h);+ grad_f16[off + 6..off + 8].copy_from_slice(&one);+ }+ let mut dithered = vec![0u8; BYTES_32BIT];+ rgba16f_to_rgba8_dithered(&grad_f16, &mut dithered);+ // Exact 0 and 255 endpoints never get dither noise+ for y in 0..TILE_SIZE {+ assert_eq!(dithered[(y * TILE_SIZE) * 4], 0);+ assert_eq!(dithered[(y * TILE_SIZE + 1) * 4], 255);+ }+ // Mid-step region contains both 127 and 128 (anti-banding dithering active)+ let mut c127 = 0usize;+ let mut c128 = 0usize;+ for y in 0..16 {+ for x in 2..18 {+ let r = dithered[(y * TILE_SIZE + x) * 4];+ if r == 127 {+ c127 += 1;+ } else if r == 128 {+ c128 += 1;+ }+ }+ }+ assert!(c127 > 50 && c128 > 50, "Expected balanced Bayer 4x4 dither (127={c127}, 128={c128})");++ // 3. Grayscale8Bit pack/unpack (matches pixelCodec.ts: BT.601 luma, 0 -> transparent, v -> [v,v,v,255])+ let mut gray_raw = vec![0u8; BYTES_8BIT];+ pack_rgba8_to_8bit(&rgba_in, &mut gray_raw);+ let mut gray_rgba = vec![0u8; BYTES_32BIT];+ unpack_8bit_to_rgba8(&gray_raw, &mut gray_rgba);+ // Pixel (0,0) had R=0, G=255, B=0, A=255 -> luma = (255*587 + 500)/1000 = 150 -> [150, 150, 150, 255]+ assert_eq!(&gray_rgba[0..4], &[150, 150, 150, 255]);++ // 4. Monochrome1Bit pack/unpack+ let mut mono_in = vec![0u8; BYTES_32BIT];+ // Mark first 8 pixels alternating opaque black ink & transparent+ for x in 0..8 {+ if x % 2 == 0 {+ mono_in[x * 4..x * 4 + 4].copy_from_slice(&[0, 0, 0, 255]);+ }+ }+ let mut mono_raw = vec![0u8; BYTES_1BIT];+ pack_rgba8_to_1bit(&mono_in, &mut mono_raw, 128);+ let mut mono_out = vec![0u8; BYTES_32BIT];+ unpack_1bit_to_rgba8(&mono_raw, &mut mono_out, [0, 0, 0, 255], [0, 0, 0, 0]);+ for x in 0..8 {+ let expected = if x % 2 == 0 { [0, 0, 0, 255] } else { [0, 0, 0, 0] };+ assert_eq!(&mono_out[x * 4..x * 4 + 4], &expected);+ }+}++#[test]+fn test_per_layer_non_destructive_mask_tiles_and_apply_undo() {+ let mut doc = Document::new_blank(+ "doc-mask",+ "Mask Test",+ CanvasDimensions {+ width: 512,+ height: 512,+ dpi: 300,+ },+ CanvasColorMode::Color,+ "#ffffff",+ 60.0,+ 50,+ );+ let top_id = doc.active_layer_id.clone().unwrap();++ // Paint a 16x16 opaque red square on Layer 1+ let mut red_rect = vec![0u8; 16 * 16 * 4];+ for px in red_rect.chunks_exact_mut(4) {+ px.copy_from_slice(&[255, 0, 0, 255]);+ }+ doc.ingest_dirty_rect(+ &top_id,+ RectI32::new(0, 0, 16, 16),+ &red_rect,+ false,+ true,+ "brush",+ "Red Square",+ None,+ None,+ None,+ )+ .expect("ingest raster failed");++ // Add reveal-all mask -> ZERO mask tiles allocated!+ doc.add_layer_mask(&top_id, 255, true)+ .expect("add_layer_mask failed");+ assert!(doc.layer(&top_id).unwrap().grid.has_mask);+ assert_eq!(doc.layer(&top_id).unwrap().grid.mask_tiles.len(), 0);++ // Mask out left half (8x16 -> alpha 0)+ let zero_mask = vec![0u8; 8 * 16];+ doc.ingest_dirty_rect(+ &top_id,+ RectI32::new(0, 0, 8, 16),+ &zero_mask,+ true,+ true,+ "mask",+ "Paint Mask",+ None,+ None,+ None,+ )+ .expect("ingest mask failed");+ assert_eq!(doc.layer(&top_id).unwrap().grid.mask_tiles.len(), 1);++ // Apply mask permanently onto raster+ doc.remove_layer_mask(&top_id, true, true, None)+ .expect("apply mask failed");+ assert!(!doc.layer(&top_id).unwrap().grid.has_mask);++ let px_masked = doc+ .layer(&top_id)+ .unwrap()+ .grid+ .read_rgba8_rect(RectI32::new(2, 2, 1, 1), false, None)+ .unwrap();+ let px_visible = doc+ .layer(&top_id)+ .unwrap()+ .grid+ .read_rgba8_rect(RectI32::new(10, 2, 1, 1), false, None)+ .unwrap();+ assert_eq!(px_masked[3], 0, "Masked pixel alpha must become 0 after apply");+ assert_eq!(px_visible, [255, 0, 0, 255], "Unmasked pixel must stay opaque red");++ // Undo apply mask -> mask & full red square both restored!+ doc.undo();+ assert!(doc.layer(&top_id).unwrap().grid.has_mask);+ let px_restored = doc+ .layer(&top_id)+ .unwrap()+ .grid+ .read_rgba8_rect(RectI32::new(2, 2, 1, 1), false, None)+ .unwrap();+ assert_eq!(px_restored, [255, 0, 0, 255]);+}++#[test]+fn test_cow_arc_sharing_undo_redo_coalescing_and_canvas_resize() {+ let mut doc = Document::new_blank(+ "doc-cow",+ "CoW Test",+ CanvasDimensions {+ width: 512,+ height: 512,+ dpi: 300,+ },+ CanvasColorMode::Color,+ "#ffffff",+ 60.0,+ 50,+ );+ let layer_id = doc.active_layer_id.clone().unwrap();++ // Paint 2 distinct tiles: (0,0) and (1,0)+ let green = [0u8, 200, 50, 255];+ let blue = [0u8, 80, 255, 255];+ doc.ingest_dirty_rect(+ &layer_id,+ RectI32::new(10, 10, 1, 1),+ &green,+ false,+ true,+ "brush",+ "Green Dot",+ None,+ None,+ None,+ )+ .unwrap();+ doc.ingest_dirty_rect(+ &layer_id,+ RectI32::new(300, 10, 1, 1),+ &blue,+ false,+ true,+ "brush",+ "Blue Dot",+ None,+ None,+ None,+ )+ .unwrap();++ // Duplicate layer -> O(1) Arc pointer sharing on BOTH tiles!+ doc.duplicate_layer(&layer_id, "layer-dup", true).unwrap();+ let orig_t0 = Arc::clone(doc.layer(&layer_id).unwrap().grid.tiles.get(&TileCoord::new(0, 0)).unwrap());+ let dup_t0 = Arc::clone(doc.layer("layer-dup").unwrap().grid.tiles.get(&TileCoord::new(0, 0)).unwrap());+ let orig_t1 = Arc::clone(doc.layer(&layer_id).unwrap().grid.tiles.get(&TileCoord::new(1, 0)).unwrap());+ let dup_t1 = Arc::clone(doc.layer("layer-dup").unwrap().grid.tiles.get(&TileCoord::new(1, 0)).unwrap());+ assert!(Arc::ptr_eq(&orig_t0, &dup_t0), "CoW duplicate must share untouched tile (0,0)");+ assert!(Arc::ptr_eq(&orig_t1, &dup_t1), "CoW duplicate must share untouched tile (1,0)");++ // Mutate ONLY tile (0,0) on duplicate -> (0,0) clones, (1,0) STAYS shared!+ doc.ingest_dirty_rect(+ "layer-dup",+ RectI32::new(12, 12, 1, 1),+ &[255, 255, 0, 255],+ false,+ true,+ "brush",+ "Yellow Dot",+ None,+ None,+ None,+ )+ .unwrap();+ let dup_t0_after = doc.layer("layer-dup").unwrap().grid.tiles.get(&TileCoord::new(0, 0)).unwrap();+ let dup_t1_after = doc.layer("layer-dup").unwrap().grid.tiles.get(&TileCoord::new(1, 0)).unwrap();+ assert!(!Arc::ptr_eq(&orig_t0, dup_t0_after), "Mutated tile (0,0) must split via CoW");+ assert!(Arc::ptr_eq(&orig_t1, dup_t1_after), "Untouched tile (1,0) must stay shared");++ // Slider coalesce_key: 3 rapid opacity updates collapse into 1 history entry+ let hist_before_slider = doc.history.len();+ for op in [0.8f32, 0.6, 0.4] {+ doc.update_layer_props(+ "layer-dup",+ LayerPropsPatch {+ opacity: Some(op),+ coalesce_key: Some("opacity:layer-dup".to_string()),+ record_history: Some(true),+ ..Default::default()+ },+ None,+ )+ .unwrap();+ }+ assert_eq!(doc.history.len(), hist_before_slider + 1, "Rapid slider edits must coalesce");+ assert!((doc.layer("layer-dup").unwrap().meta.opacity - 0.4).abs() < 1e-4);++ // Undo slider -> restores full 1.0 opacity in one step+ doc.undo();+ assert!((doc.layer("layer-dup").unwrap().meta.opacity - 1.0).abs() < 1e-4);+ doc.redo();+ assert!((doc.layer("layer-dup").unwrap().meta.opacity - 0.4).abs() < 1e-4);++ // Canvas resize/crop with offset + atomic undo/redo+ doc.resize_canvas(+ CanvasDimensions {+ width: 256,+ height: 256,+ dpi: 300,+ },+ -10,+ -10,+ false,+ "#ffffff",+ true,+ None,+ )+ .unwrap();+ assert_eq!(doc.dimensions.width, 256);+ // Original green dot at (10,10) shifted by (-10,-10) is now at (0,0)!+ let shifted = doc+ .layer(&layer_id)+ .unwrap()+ .grid+ .read_rgba8_rect(RectI32::new(0, 0, 1, 1), false, None)+ .unwrap();+ assert_eq!(shifted, green);++ // Undo canvas resize restores 512x512 and green dot back at (10,10)+ doc.undo();+ assert_eq!(doc.dimensions.width, 512);+ let orig_pos = doc+ .layer(&layer_id)+ .unwrap()+ .grid+ .read_rgba8_rect(RectI32::new(10, 10, 1, 1), false, None)+ .unwrap();+ assert_eq!(orig_pos, green);+}++#[test]+fn test_collaborative_selective_undo_tombstones_and_conflict_protection() {+ let mut doc = Document::new_blank(+ "doc-collab",+ "Collab Room",+ CanvasDimensions {+ width: 512,+ height: 512,+ dpi: 300,+ },+ CanvasColorMode::Color,+ "#ffffff",+ 60.0,+ 50,+ );+ let lid = doc.active_layer_id.clone().unwrap();++ // 1. Local peer paints uncontested tile (0,0) and soon-to-be-contested tile (1,0)+ doc.ingest_dirty_rect(+ &lid,+ RectI32::new(20, 20, 1, 1),+ &[255, 0, 0, 255],+ false,+ true,+ "brush",+ "Local Stroke 1",+ Some("local".to_string()),+ Some("stroke-local-1".to_string()),+ None,+ )+ .unwrap();++ // 2. Local peer paints tile (1,0) at (300, 20)+ doc.ingest_dirty_rect(+ &lid,+ RectI32::new(300, 20, 1, 1),+ &[0, 255, 0, 255],+ false,+ true,+ "brush",+ "Local Stroke 2",+ Some("local".to_string()),+ Some("stroke-local-2".to_string()),+ None,+ )+ .unwrap();++ // 3. Remote peer "peer-alice" paints on tile (1,0) at (305, 20) — bumps remote_epoch on (1,0)!+ doc.ingest_dirty_rect(+ &lid,+ RectI32::new(305, 20, 1, 1),+ &[0, 0, 255, 255],+ false,+ true,+ "brush",+ "Alice Stroke",+ Some("peer-alice".to_string()),+ Some("stroke-alice-1".to_string()),+ None,+ )+ .unwrap();++ // Selective undo of local's stroke-local-2 on contested tile (1,0) MUST preserve Alice's edit!+ let outcome_contested = doc.selective_undo(Some("local"), Some("stroke-local-2"));+ assert!(outcome_contested.applied);+ assert!(outcome_contested.preserved_peer_edits);+ assert_eq!(outcome_contested.contested_tile_count, 1);+ let alice_px = doc+ .layer(&lid)+ .unwrap()+ .grid+ .read_rgba8_rect(RectI32::new(305, 20, 1, 1), false, None)+ .unwrap();+ assert_eq!(alice_px, [0, 0, 255, 255], "Alice's pixel on contested tile must be preserved");++ // Selective undo of local's uncontested stroke-local-1 on tile (0,0) reverts cleanly!+ let outcome_clean = doc.selective_undo(Some("local"), Some("stroke-local-1"));+ assert!(outcome_clean.applied);+ assert!(!outcome_clean.preserved_peer_edits);+ let reverted_px = doc+ .layer(&lid)+ .unwrap()+ .grid+ .read_rgba8_rect(RectI32::new(20, 20, 1, 1), false, None)+ .unwrap();+ assert_eq!(reverted_px[3], 0, "Uncontested tile must revert to transparent");++ // Selective redo reapplies local's uncontested stroke+ let redo_outcome = doc.selective_redo(Some("local"));+ assert!(redo_outcome.applied);+ let restored_px = doc+ .layer(&lid)+ .unwrap()+ .grid+ .read_rgba8_rect(RectI32::new(20, 20, 1, 1), false, None)+ .unwrap();+ assert_eq!(restored_px, [255, 0, 0, 255]);+}++#[test]+fn test_tiered_memory_lru_to_lz4_ram_to_scratch_disk_roundtrip() {+ let temp_dir = std::env::temp_dir().join(format!(+ "ink_engine_tiered_test_{}",+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ let scratch: Arc<dyn ScratchBackend> =+ Arc::new(FileScratchBackend::new(temp_dir.clone(), true));++ // Tight 200 KB RAM budget to trigger both L2 LZ4 compression AND L3 Scratch Disk paging!+ let mut mgr = DocumentManager::new(+ MemoryBudgetConfig {+ ram_budget_bytes: 200 * 1024,+ vram_budget_bytes: 32 * 1024 * 1024,+ max_history_steps: 20,+ offload_inactive_tabs: true,+ },+ Arc::clone(&scratch),+ );++ mgr.create_document(+ "tab-1",+ "Tab 1",+ CanvasDimensions {+ width: 1024,+ height: 1024,+ dpi: 300,+ },+ CanvasColorMode::Color,+ "#ffffff",+ 60.0,+ );++ // Write pseudo-random (harder to compress) tile data across 4 tiles = 1 MB raw (> 200 KB budget!)+ let mut expected_samples: Vec<(i32, i32, [u8; 4])> = Vec::new();+ {+ let doc = mgr.get_document_mut("tab-1").unwrap();+ let lid = doc.active_layer_id.clone().unwrap();+ for ty in 0..2 {+ for tx in 0..2 {+ let mut tile_buf = vec![0u8; BYTES_32BIT];+ let mut seed = (tx as u32 * 7919 + ty as u32 * 104729 + 17) as u64;+ for b in &mut tile_buf {+ seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);+ *b = ((seed >> 33) & 0xff) as u8;+ }+ // Force alpha opaque so tile isn't sparse-pruned+ for px in tile_buf.chunks_exact_mut(4) {+ px[3] = 255;+ }+ expected_samples.push((+ tx * 256 + 7,+ ty * 256 + 13,+ [+ tile_buf[(13 * 256 + 7) * 4],+ tile_buf[(13 * 256 + 7) * 4 + 1],+ tile_buf[(13 * 256 + 7) * 4 + 2],+ 255,+ ],+ ));+ doc.ingest_dirty_rect(+ &lid,+ RectI32::new(tx * 256, ty * 256, 256, 256),+ &tile_buf,+ false,+ false,+ "brush",+ "Noise",+ None,+ None,+ Some(scratch.as_ref()),+ )+ .unwrap();+ }+ }+ }++ let before_stats = mgr.memory_stats();+ assert!(before_stats.ram_total_bytes >= 4 * BYTES_32BIT as u64);++ // Open Tab 2 -> switches away from Tab 1 (triggers L2 LZ4 compression of inactive tab)+ mgr.create_document(+ "tab-2",+ "Tab 2",+ CanvasDimensions {+ width: 512,+ height: 512,+ dpi: 300,+ },+ CanvasColorMode::Color,+ "#ffffff",+ 60.0,+ );++ // Enforce tight 200 KB budget -> pushes inactive tab-1's incompressible tiles to L3 Scratch Disk!+ let (_lz4_cnt, disk_cnt, freed) = mgr.enforce_memory_budget().expect("enforce_budget failed");+ let after_stats = mgr.memory_stats();+ assert!(disk_cnt > 0 || after_stats.disk_paged_tiles > 0, "Expected tiles paged to L3 scratch disk");+ assert!(freed > 0 && after_stats.ram_total_bytes < before_stats.ram_total_bytes);++ // Switch back to Tab 1 and verify EVERY pixel promotes bit-exact from L3 Scratch Disk!+ mgr.switch_document("tab-1").unwrap();+ let doc1 = mgr.get_document("tab-1").unwrap();+ let lid = doc1.active_layer_id.as_deref().unwrap();+ for (x, y, expected_px) in expected_samples {+ let got = doc1+ .layer(lid)+ .unwrap()+ .grid+ .read_rgba8_rect(RectI32::new(x, y, 1, 1), false, Some(scratch.as_ref()))+ .expect("L3 scratch readback failed");+ assert_eq!(got, expected_px, "L3 scratch disk round-trip pixel mismatch at ({x},{y})");+ }++ // Close documents cleans up scratch sessions+ assert!(mgr.close_document("tab-1"));+ assert!(mgr.close_document("tab-2"));+ let _ = std::fs::remove_dir_all(&temp_dir);+}++#[test]+fn test_headless_dx12_gpu_tile_pool_lru_and_compute_mipmap_pyramid() {+ let mut renderer = match GpuRenderer::new_with_vram(+ SurfaceTarget::Headless {+ width: 256,+ height: 256,+ },+ 512,+ 512,+ 16 * BYTES_16F as u64, // Small 16-slot L1 pool to verify LRU eviction cleanly+ ) {+ Ok(r) => r,+ Err(err) => {+ eprintln!("Skipping headless DX12 GpuTilePool test (no adapter): {err}");+ return;+ }+ };++ let make_solid_tile = |rgba: [u8; 4]| TileData::new_solid(TileFormat::Color32Bit, TileKind::Raster, rgba);+ let t_tl = make_solid_tile([255, 0, 0, 255]); // Red+ let t_tr = make_solid_tile([0, 255, 0, 255]); // Green+ let t_bl = make_solid_tile([0, 0, 255, 255]); // Blue+ let t_br = make_solid_tile([255, 255, 255, 255]); // White++ let device = renderer.device().clone();+ let queue = renderer.queue().clone();+ let mut pool = GpuTilePool::new(&device, 16 * BYTES_16F as u64);+ assert_eq!(pool.capacity(), 16);++ pool.begin_frame();+ let s_tl = pool+ .ensure_tile_uploaded(+ &queue,+ GpuTileKey {+ doc_id: "d1".into(),+ layer_id: "l1".into(),+ lod: 0,+ coord: TileCoord::new(0, 0),+ },+ &t_tl,+ None,+ )+ .unwrap();+ let s_tr = pool+ .ensure_tile_uploaded(+ &queue,+ GpuTileKey {+ doc_id: "d1".into(),+ layer_id: "l1".into(),+ lod: 0,+ coord: TileCoord::new(1, 0),+ },+ &t_tr,+ None,+ )+ .unwrap();+ let s_bl = pool+ .ensure_tile_uploaded(+ &queue,+ GpuTileKey {+ doc_id: "d1".into(),+ layer_id: "l1".into(),+ lod: 0,+ coord: TileCoord::new(0, 1),+ },+ &t_bl,+ None,+ )+ .unwrap();+ let s_br = pool+ .ensure_tile_uploaded(+ &queue,+ GpuTileKey {+ doc_id: "d1".into(),+ layer_id: "l1".into(),+ lod: 0,+ coord: TileCoord::new(1, 1),+ },+ &t_br,+ None,+ )+ .unwrap();++ // Dispatch WGSL compute mipmap shader (4 LOD 0 quadrants -> 1 LOD 1 parent tile)+ let lod1_slot = pool.generate_mipmap_tile(+ &device,+ &queue,+ GpuTileKey {+ doc_id: "d1".into(),+ layer_id: "l1".into(),+ lod: 1,+ coord: TileCoord::new(0, 0),+ },+ [Some(s_tl), Some(s_tr), Some(s_bl), Some(s_br)],+ 1,+ );+ assert_eq!(pool.stats().mipmaps_generated, 1);++ // Read back the LOD 1 Rgba16Float slice from DX12 GPU VRAM and verify all 4 quadrants!+ let lod1_f16 = pool+ .readback_slot_rgba16f(&device, &queue, lod1_slot)+ .expect("GPU readback failed");+ let mut lod1_rgba8 = vec![0u8; BYTES_32BIT];+ rgba16f_to_rgba8_lossless(&lod1_f16, &mut lod1_rgba8);++ let px_at = |x: usize, y: usize| -> [u8; 4] {+ let o = (y * TILE_SIZE + x) * 4;+ [lod1_rgba8[o], lod1_rgba8[o + 1], lod1_rgba8[o + 2], lod1_rgba8[o + 3]]+ };+ assert_eq!(px_at(32, 32), [255, 0, 0, 255], "LOD 1 TL quadrant must be Red");+ assert_eq!(px_at(192, 32), [0, 255, 0, 255], "LOD 1 TR quadrant must be Green");+ assert_eq!(px_at(32, 192), [0, 0, 255, 255], "LOD 1 BL quadrant must be Blue");+ assert_eq!(px_at(192, 192), [255, 255, 255, 255], "LOD 1 BR quadrant must be White");++ // Verify LRU eviction triggers cleanly when exceeding the 16-slot VRAM capacity+ for i in 0..20i32 {+ pool.begin_frame();+ let _ = pool+ .ensure_tile_uploaded(+ &queue,+ GpuTileKey {+ doc_id: "d1".into(),+ layer_id: "l_evict".into(),+ lod: 0,+ coord: TileCoord::new(i, 0),+ },+ &t_tl,+ None,+ )+ .unwrap();+ }+ let st = pool.stats();+ assert_eq!(st.slots_used, 16);+ assert!(st.evictions >= 9, "Expected LRU evictions when exceeding 16 slots, got {}", st.evictions);++ // Also verify GpuRenderer::sync_document uploads dirty tiles + compute mipmaps + display texture+ let mut doc = Document::new_blank(+ "doc-gpu-sync",+ "GPU Sync",+ CanvasDimensions {+ width: 512,+ height: 512,+ dpi: 300,+ },+ CanvasColorMode::Color,+ "#ffffff",+ 60.0,+ 20,+ );+ renderer+ .sync_document(&mut doc, Some(&InMemoryScratchBackend::new()))+ .expect("GpuRenderer::sync_document failed");+ assert!(!doc.dirty_for_render);+ assert!(renderer.gpu_pool_stats().slots_used > 0);+}++#[test]+fn test_zero_copy_ink_roundtrip_wal_recovery_and_timelapse_png() {+ let mut doc = Document::new_blank(+ "doc-io",+ "Manga Page 01",+ CanvasDimensions {+ width: 512,+ height: 512,+ dpi: 600,+ },+ CanvasColorMode::Color,+ "#ffffff",+ 60.0,+ 50,+ );++ // Add a monochrome ink layer inside a folder+ let folder = LayerNodeMeta::new_folder("folder-ink", "Inks");+ doc.add_layer(folder, Some(0), false, true);++ let mut mono_meta = LayerNodeMeta::new_raster("layer-mono", "Lineart");+ mono_meta.parent_id = Some("folder-ink".to_string());+ mono_meta.expression_color = Some(ExpressionColor::Monochrome);+ mono_meta.blend_mode = BlendMode::Multiply;+ mono_meta.opacity = 0.85;+ doc.add_layer(mono_meta, Some(1), true, true);++ // Paint black stroke into monochrome layer + add partial mask+ let mut ink_box = vec![0u8; 32 * 32 * 4];+ for px in ink_box.chunks_exact_mut(4) {+ px.copy_from_slice(&[0, 0, 0, 255]);+ }+ doc.ingest_dirty_rect(+ "layer-mono",+ RectI32::new(64, 64, 32, 32),+ &ink_box,+ false,+ true,+ "brush",+ "Ink Box",+ None,+ None,+ None,+ )+ .unwrap();+ doc.add_layer_mask("layer-mono", 255, true).unwrap();+ doc.ingest_dirty_rect(+ "layer-mono",+ RectI32::new(64, 64, 16, 32),+ &vec![128u8; 16 * 32],+ true,+ true,+ "mask",+ "Half Mask",+ None,+ None,+ None,+ )+ .unwrap();++ // 1. Parallel .ink v2 ZIP save & reload round-trip+ let saved = serialize_ink_document(&doc, 1, None).expect("serialize_ink_document failed");+ assert!(saved.bytes.starts_with(b"PK\x03\x04"));+ assert!(saved.preview_png.as_ref().map(|p| p.starts_with(b"\x89PNG")).unwrap_or(false));+ assert!(saved.tile_count >= 5); // 4 bg + 1 mono+ assert_eq!(saved.mask_count, 1);++ let reloaded = parse_ink_document(&saved.bytes, "doc-io-reload", "Manga Page 01", 50)+ .expect("parse_ink_document failed");+ assert_eq!(reloaded.dimensions, doc.dimensions);+ assert_eq!(reloaded.layers.len(), doc.layers.len());+ let mono_reloaded = reloaded.layer("layer-mono").expect("missing mono layer");+ assert_eq!(mono_reloaded.meta.expression_color, Some(ExpressionColor::Monochrome));+ assert_eq!(mono_reloaded.meta.blend_mode, BlendMode::Multiply);+ assert!(mono_reloaded.grid.has_mask);+ assert!(mono_reloaded.meta.thumbnail_url.is_some());+ assert!(mono_reloaded.meta.mask_thumbnail_url.is_some());++ let ink_px = mono_reloaded+ .grid+ .read_rgba8_rect(RectI32::new(70, 70, 1, 1), false, None)+ .unwrap();+ assert_eq!(ink_px, [0, 0, 0, 255]);+ let mask_px = mono_reloaded+ .grid+ .read_mask8_rect(RectI32::new(70, 70, 1, 1), None)+ .unwrap();+ assert_eq!(mask_px, vec![128u8]);++ // 2. Crash recovery checkpoint (INKG v1) + WAL tile delta (TD v1) replay+ let (manifest_json, checkpoint_bytes, thumb_png) =+ encode_document_checkpoint(&doc, None).expect("encode_document_checkpoint failed");+ assert!(thumb_png.starts_with(b"\x89PNG"));++ // Record an extra stroke AFTER checkpoint as a WAL entry+ let top_layer = doc.layer("layer-mono").unwrap();+ let before_snap = top_layer.grid.snapshot_all_cow(TileKind::Raster);+ let mut after_grid = top_layer.grid.clone_cow();+ after_grid+ .write_rgba8_rect(&[0, 0, 0, 255], RectI32::new(200, 200, 1, 1), 128, None)+ .unwrap();+ let wal_deltas = after_grid.diff_from_full_snapshot("layer-mono", TileKind::Raster, &before_snap);+ let wal_payload =+ encode_cow_deltas_to_wal_payload(&wal_deltas, None).expect("WAL encode failed");++ let (recovered, strokes_replayed, _) = replay_recovery_into_document(+ "doc-recovered",+ &manifest_json,+ Some(&checkpoint_bytes),+ &[WalRawEntry {+ entry_type: 1,+ payload: wal_payload,+ }],+ 50,+ )+ .expect("replay_recovery_into_document failed");+ assert_eq!(strokes_replayed, 1);+ let wal_px = recovered+ .layer("layer-mono")+ .unwrap()+ .grid+ .read_rgba8_rect(RectI32::new(200, 200, 1, 1), false, None)+ .unwrap();+ assert_eq!(wal_px, [0, 0, 0, 255], "Post-checkpoint WAL stroke must replay accurately");++ // 3. Flattened PNG timelapse frame generation+ let (fw, fh, png) = doc+ .render_flattened_png(256, true, None)+ .expect("render_flattened_png failed");+ assert_eq!((fw, fh), (256, 256));+ assert!(png.starts_with(b"\x89PNG"));+}diff --git a/crates/ink-engine/src/ring.rs b/crates/ink-engine/src/ring.rsnew file mode 100644index 0000000..4721555--- /dev/null+++ b/crates/ink-engine/src/ring.rs@@ -0,0 +1,206 @@+//! Lock-free wait-free SPSC (`rtrb`) input ring buffers and immediate wake signaling.+//!+//! Separate dedicated SPSC rings are provided for:+//! - WinTab high-priority thread (`wintab`)+//! - Windows Ink UI-thread `WM_POINTER` hook (`winink`)+//! - Native mouse/wheel navigation & hover hook (`nav`)+//!+//! Each producer lives exclusively on its owning OS thread (zero mutexes on the hot path!).++use crate::types::{NativeInputSample, NativeNavEvent};+use rtrb::{Consumer, Producer, RingBuffer};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Condvar, Mutex};+use std::time::Duration;++pub const TABLET_RING_CAPACITY: usize = 4096;+pub const NAV_RING_CAPACITY: usize = 1024;++/// Low-latency wake-on-input signal for the dedicated render thread.+/// Avoids locking the mutex on the producer hot path if a wakeup is already latched.+#[derive(Debug, Default)]+pub struct WakeSignal {+ pending: AtomicBool,+ mutex: Mutex<()>,+ cvar: Condvar,+}++impl WakeSignal {+ pub fn new() -> Arc<Self> {+ Arc::new(Self::default())+ }++ /// Signals the engine thread immediately. Lock-free fast path when already awake/pending.+ #[inline]+ pub fn wake(&self) {+ if !self.pending.swap(true, Ordering::AcqRel) {+ // Brief lock ensures the waiting thread cannot miss the notification between+ // checking `pending` and entering `cvar.wait`.+ let _guard = self.mutex.lock();+ self.cvar.notify_one();+ }+ }++ /// Blocks until `wake()` is called or `timeout` elapses. Returns `true` if woken.+ pub fn wait_timeout(&self, timeout: Duration) -> bool {+ if self.pending.swap(false, Ordering::AcqRel) {+ return true;+ }+ let Ok(guard) = self.mutex.lock() else {+ return false;+ };+ if self.pending.swap(false, Ordering::AcqRel) {+ return true;+ }+ let (_guard, _) = match self.cvar.wait_timeout(guard, timeout) {+ Ok(res) => res,+ Err(poisoned) => poisoned.into_inner(),+ };+ self.pending.swap(false, Ordering::AcqRel)+ }+}++/// Wait-free SPSC producer wrapper for pushing `NativeInputSample`s into `ink-engine`.+pub struct TabletRingProducer {+ producer: Producer<NativeInputSample>,+ wake: Arc<WakeSignal>,+}++impl TabletRingProducer {+ /// Pushes a single sample without blocking or allocating. Silently drops only if the+ /// 4096-sample ring overflows (e.g. >16 seconds of uninterrupted stalls).+ #[inline]+ pub fn push(&mut self, sample: NativeInputSample) -> bool {+ let ok = self.producer.push(sample).is_ok();+ if ok {+ self.wake.wake();+ }+ ok+ }++ /// Pushes a slice of samples and triggers a single wake signal at the end of the burst.+ #[inline]+ pub fn push_batch(&mut self, samples: &[NativeInputSample]) -> usize {+ let mut pushed = 0;+ for &s in samples {+ if self.producer.push(s).is_ok() {+ pushed += 1;+ } else {+ break;+ }+ }+ if pushed > 0 {+ self.wake.wake();+ }+ pushed+ }+}++/// Wait-free SPSC producer wrapper for pushing `NativeNavEvent`s into `ink-engine`.+pub struct NavRingProducer {+ producer: Producer<NativeNavEvent>,+ wake: Arc<WakeSignal>,+}++impl NavRingProducer {+ #[inline]+ pub fn push(&mut self, event: NativeNavEvent) -> bool {+ let ok = self.producer.push(event).is_ok();+ if ok {+ self.wake.wake();+ }+ ok+ }+}++/// All producer handles returned to the host when creating an engine instance.+pub struct InputProducers {+ pub wintab: TabletRingProducer,+ pub winink: TabletRingProducer,+ pub nav: NavRingProducer,+}++/// Consumer ends owned exclusively by the dedicated engine/render thread.+pub(crate) struct InputConsumers {+ pub wintab: Consumer<NativeInputSample>,+ pub winink: Consumer<NativeInputSample>,+ pub nav: Consumer<NativeNavEvent>,+}++pub(crate) fn create_input_rings(wake: &Arc<WakeSignal>) -> (InputProducers, InputConsumers) {+ let (wt_tx, wt_rx) = RingBuffer::new(TABLET_RING_CAPACITY);+ let (ink_tx, ink_rx) = RingBuffer::new(TABLET_RING_CAPACITY);+ let (nav_tx, nav_rx) = RingBuffer::new(NAV_RING_CAPACITY);++ (+ InputProducers {+ wintab: TabletRingProducer {+ producer: wt_tx,+ wake: Arc::clone(wake),+ },+ winink: TabletRingProducer {+ producer: ink_tx,+ wake: Arc::clone(wake),+ },+ nav: NavRingProducer {+ producer: nav_tx,+ wake: Arc::clone(wake),+ },+ },+ InputConsumers {+ wintab: wt_rx,+ winink: ink_rx,+ nav: nav_rx,+ },+ )+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_spsc_tablet_ring_fifo_order_and_wake() {+ let wake = WakeSignal::new();+ let (mut producers, mut consumers) = create_input_rings(&wake);++ let batch = [+ NativeInputSample {+ phys_x: 100.5,+ phys_y: 200.25,+ pressure: 0.2,+ tilt_x: 1.0,+ tilt_y: -2.0,+ twist: 0.0,+ timestamp_ms: 10.0,+ buttons: 1,+ phase: 1,+ backend: 1,+ },+ NativeInputSample {+ phys_x: 105.0,+ phys_y: 204.5,+ pressure: 0.85,+ tilt_x: 2.0,+ tilt_y: -1.0,+ twist: 15.0,+ timestamp_ms: 14.0,+ buttons: 1,+ phase: 2,+ backend: 1,+ },+ ];++ assert_eq!(producers.wintab.push_batch(&batch), 2);+ assert!(wake.wait_timeout(Duration::from_millis(5)));++ let s0 = consumers.wintab.pop().expect("first sample");+ let s1 = consumers.wintab.pop().expect("second sample");+ assert!(consumers.wintab.pop().is_err());++ assert_eq!(s0.phase, 1);+ assert!((s0.phys_x - 100.5).abs() < 1e-4);+ assert_eq!(s1.phase, 2);+ assert!((s1.pressure - 0.85).abs() < 1e-4);+ }+}diff --git a/crates/ink-engine/src/shaders.rs b/crates/ink-engine/src/shaders.rsnew file mode 100644index 0000000..44474e0--- /dev/null+++ b/crates/ink-engine/src/shaders.rs@@ -0,0 +1,279 @@+//! WGSL shaders for the Phase 1 wgpu (DX12) engine:+//! 1. Viewport compositor (canvas matte, artboard 1px border + drop shadow,+//! 16px document-space checkerboard, document texture composite).+//! 2. Instanced GPU brush dab rasterizer (soft/hard anti-aliased circular dabs).+//! 3. Analytic SDF dual-tone GPU brush outline cursor ring.++pub const VIEWPORT_SHADER_WGSL: &str = r#"+struct ViewportUniforms {+ viewport_size_phys: vec2<f32>,+ doc_size: vec2<f32>,+ pan_css: vec2<f32>,+ zoom: f32,+ rotation_rad: f32,+ flip: vec2<f32>,+ dpr: f32,+ show_checkerboard: u32,+ matte_color: vec4<f32>,+};++@group(0) @binding(0) var<uniform> u: ViewportUniforms;+@group(0) @binding(1) var doc_tex: texture_2d<f32>;+@group(0) @binding(2) var doc_sampler_linear: sampler;+@group(0) @binding(3) var doc_sampler_nearest: sampler;++struct VsOut {+ @builtin(position) pos: vec4<f32>,+};++@vertex+fn vs_main(@builtin(vertex_index) vid: u32) -> VsOut {+ // Fullscreen triangle covering NDC [-1, 1] x [-1, 1]+ let x = f32((vid << 1u) & 2u) * 2.0 - 1.0;+ let y = 1.0 - f32(vid & 2u) * 2.0;+ var out: VsOut;+ out.pos = vec4<f32>(x, y, 0.0, 1.0);+ return out;+}++fn phys_to_doc(phys: vec2<f32>) -> vec2<f32> {+ let safe_dpr = max(0.05, u.dpr);+ let safe_zoom = max(0.01, u.zoom);+ let css = phys / safe_dpr;+ let rel = css - u.pan_css;+ let c = cos(u.rotation_rad);+ let s = sin(u.rotation_rad);+ let unrot = vec2<f32>(+ rel.x * c + rel.y * s,+ -rel.x * s + rel.y * c,+ );+ return u.doc_size * 0.5 + (unrot * u.flip) / safe_zoom;+}++@fragment+fn fs_main(in: VsOut) -> @location(0) vec4<f32> {+ // in.pos.xy is in physical swapchain pixel centers (top-left origin)+ let doc_coord = phys_to_doc(in.pos.xy);+ let safe_zoom = max(0.01, u.zoom);++ // Distance outside [0, doc_size] in document pixels+ let outside_doc = max(vec2<f32>(0.0), max(-doc_coord, doc_coord - u.doc_size));+ if (outside_doc.x > 0.0 || outside_doc.y > 0.0) {+ let outside_css_px = outside_doc * safe_zoom;+ let border_dist = max(outside_css_px.x, outside_css_px.y);+ if (border_dist <= 1.0) {+ // Crisp 1px dark artboard border matching coreShaders.ts+ return vec4<f32>(0.086, 0.086, 0.086, 1.0);+ }++ // Soft drop shadow offset 10 CSS px downward in viewport space+ let shadow_doc = phys_to_doc(in.pos.xy - vec2<f32>(0.0, 10.0 * max(0.05, u.dpr)));+ let shadow_outside = max(vec2<f32>(0.0), max(-shadow_doc, shadow_doc - u.doc_size));+ let shadow_dist = length(shadow_outside * safe_zoom);+ let shadow_a = 0.55 * exp(-(shadow_dist * shadow_dist) / 520.0) * smoothstep(48.0, 0.0, shadow_dist);+ let matte = u.matte_color.rgb;+ let shaded = matte * (1.0 - shadow_a);+ return vec4<f32>(shaded, 1.0);+ }++ // Artboard background: 16px document-space checkerboard or crisp white paper+ var bg_rgb: vec3<f32>;+ if (u.show_checkerboard != 0u) {+ let check_coord = floor(doc_coord / 16.0);+ let check = abs((check_coord.x + check_coord.y) - 2.0 * floor((check_coord.x + check_coord.y) * 0.5));+ bg_rgb = select(vec3<f32>(0.125), vec3<f32>(0.157), check > 0.5);+ } else {+ bg_rgb = vec3<f32>(1.0, 1.0, 1.0);+ }++ let uv = clamp(doc_coord / max(vec2<f32>(1.0), u.doc_size), vec2<f32>(0.0), vec2<f32>(1.0));+ let sample_linear = textureSample(doc_tex, doc_sampler_linear, uv);+ let sample_nearest = textureSample(doc_tex, doc_sampler_nearest, uv);+ // Use crisp nearest-neighbor pixel grid when zoomed in >= 400% (manga/pixel precision)+ let layer_premul = select(sample_linear, sample_nearest, safe_zoom >= 4.0);++ // Premultiplied source-over onto opaque artboard background+ let out_rgb = clamp(layer_premul.rgb + bg_rgb * (1.0 - layer_premul.a), vec3<f32>(0.0), vec3<f32>(1.0));+ return vec4<f32>(out_rgb, 1.0);+}+"#;++pub const DAB_SHADER_WGSL: &str = r#"+struct DabUniforms {+ doc_size: vec2<f32>,+ _pad: vec2<f32>,+};++@group(0) @binding(0) var<uniform> u: DabUniforms;++struct DabInstance {+ @location(0) center_doc: vec2<f32>,+ @location(1) radius_doc: f32,+ @location(2) hardness: f32,+ @location(3) color_rgba: vec4<f32>,+};++struct VsOut {+ @builtin(position) pos: vec4<f32>,+ @location(0) local_pos: vec2<f32>,+ @location(1) radius_doc: f32,+ @location(2) hardness: f32,+ @location(3) color_rgba: vec4<f32>,+};++@vertex+fn vs_main(@builtin(vertex_index) vid: u32, inst: DabInstance) -> VsOut {+ // 6-vertex quad covering [-1, 1] x [-1, 1] padded by 1.5px for anti-aliasing+ var corner: vec2<f32>;+ switch (vid) {+ case 0u: { corner = vec2<f32>(-1.0, -1.0); }+ case 1u: { corner = vec2<f32>( 1.0, -1.0); }+ case 2u: { corner = vec2<f32>(-1.0, 1.0); }+ case 3u: { corner = vec2<f32>(-1.0, 1.0); }+ case 4u: { corner = vec2<f32>( 1.0, -1.0); }+ default: { corner = vec2<f32>( 1.0, 1.0); }+ }++ let extent = inst.radius_doc + 1.5;+ let local_px = corner * extent;+ let doc_px = inst.center_doc + local_px;+ let ndc = vec2<f32>(+ (doc_px.x / max(1.0, u.doc_size.x)) * 2.0 - 1.0,+ 1.0 - (doc_px.y / max(1.0, u.doc_size.y)) * 2.0,+ );++ var out: VsOut;+ out.pos = vec4<f32>(ndc, 0.0, 1.0);+ out.local_pos = local_px;+ out.radius_doc = inst.radius_doc;+ out.hardness = inst.hardness;+ out.color_rgba = inst.color_rgba;+ return out;+}++@fragment+fn fs_main(in: VsOut) -> @location(0) vec4<f32> {+ let dist = length(in.local_pos);+ let r = max(0.35, in.radius_doc);+ if (dist > r + 1.0) {+ discard;+ }++ let h = clamp(in.hardness, 0.0, 1.0);+ // Inner solid plateau + smooth radial feather + 1px anti-aliased edge+ let inner_r = r * h * 0.96;+ let aa_edge = max(0.75, r - inner_r);+ let falloff = 1.0 - smoothstep(max(0.0, r - aa_edge), r + 0.5, dist);+ let alpha = clamp(in.color_rgba.a * falloff, 0.0, 1.0);+ if (alpha < 0.002) {+ discard;+ }++ // Premultiplied RGBA output for clean alpha compositing & destination-out erasing+ return vec4<f32>(in.color_rgba.rgb * alpha, alpha);+}+"#;++pub const CURSOR_SHADER_WGSL: &str = r#"+struct CursorUniforms {+ viewport_size_phys: vec2<f32>,+ center_phys: vec2<f32>,+ half_extents_phys: vec2<f32>,+ angle_rad: f32,+ dpr: f32,+ is_square: u32,+ visible: u32,+ _pad: vec2<u32>,+};++@group(0) @binding(0) var<uniform> u: CursorUniforms;++struct VsOut {+ @builtin(position) pos: vec4<f32>,+ @location(0) local_phys: vec2<f32>,+};++@vertex+fn vs_main(@builtin(vertex_index) vid: u32) -> VsOut {+ var corner: vec2<f32>;+ switch (vid) {+ case 0u: { corner = vec2<f32>(-1.0, -1.0); }+ case 1u: { corner = vec2<f32>( 1.0, -1.0); }+ case 2u: { corner = vec2<f32>(-1.0, 1.0); }+ case 3u: { corner = vec2<f32>(-1.0, 1.0); }+ case 4u: { corner = vec2<f32>( 1.0, -1.0); }+ default: { corner = vec2<f32>( 1.0, 1.0); }+ }++ var out: VsOut;+ if (u.visible == 0u) {+ out.pos = vec4<f32>(-2.0, -2.0, 0.0, 1.0);+ out.local_phys = vec2<f32>(0.0);+ return out;+ }++ let pad = 6.0 * max(1.0, u.dpr);+ let box_half = u.half_extents_phys + vec2<f32>(pad, pad);+ let local_p = corner * box_half;++ let c = cos(u.angle_rad);+ let s = sin(u.angle_rad);+ let rot_p = vec2<f32>(+ local_p.x * c - local_p.y * s,+ local_p.x * s + local_p.y * c,+ );+ let screen_p = u.center_phys + rot_p;+ let ndc = vec2<f32>(+ (screen_p.x / max(1.0, u.viewport_size_phys.x)) * 2.0 - 1.0,+ 1.0 - (screen_p.y / max(1.0, u.viewport_size_phys.y)) * 2.0,+ );++ out.pos = vec4<f32>(ndc, 0.0, 1.0);+ out.local_phys = local_p;+ return out;+}++@fragment+fn fs_main(in: VsOut) -> @location(0) vec4<f32> {+ if (u.visible == 0u) {+ discard;+ }++ let dpr = max(1.0, u.dpr);+ let half_ext = max(vec2<f32>(1.5 * dpr), u.half_extents_phys);++ var sd: f32;+ if (u.is_square != 0u) {+ let q = abs(in.local_phys) - half_ext;+ sd = length(max(q, vec2<f32>(0.0))) + min(max(q.x, q.y), 0.0);+ } else {+ // Gradient-normalized ellipse SDF for uniform stroke width across eccentricities+ let p = in.local_phys;+ let inv = vec2<f32>(1.0) / half_ext;+ let k0 = length(p * inv);+ let k1 = length(p * inv * inv);+ if (k1 < 1e-6) {+ sd = -min(half_ext.x, half_ext.y);+ } else {+ sd = k0 * (k0 - 1.0) / k1;+ }+ }++ let abs_d = abs(sd);+ let aa = 0.85;+ let white_half_w = 1.35 * dpr;+ let black_half_w = 0.55 * dpr;++ let white_cov = 1.0 - smoothstep(white_half_w - aa, white_half_w + aa, abs_d);+ let black_cov = 1.0 - smoothstep(black_half_w - aa, black_half_w + aa, abs_d);++ let total_alpha = clamp(white_cov * 0.88, 0.0, 1.0);+ if (total_alpha < 0.005) {+ discard;+ }++ // Crisp black inner line over white outer halo (high visibility on light & dark art)+ let rgb = mix(vec3<f32>(1.0, 1.0, 1.0), vec3<f32>(0.05, 0.05, 0.06), black_cov);+ return vec4<f32>(rgb * total_alpha, total_alpha);+}+"#;diff --git a/crates/ink-engine/src/stroke.rs b/crates/ink-engine/src/stroke.rsnew file mode 100644index 0000000..7f5fcc4--- /dev/null+++ b/crates/ink-engine/src/stroke.rs@@ -0,0 +1,206 @@+//! Phase 1 PoC stroke spacing interpolator for GPU dab rasterization.+//!+//! Converts live `NativeInputSample` points into evenly spaced document-space GPU dabs+//! with pressure-sensitive radius/opacity and sub-pixel continuity across 250+ Hz bursts.++use crate::types::BrushParams;+use bytemuck::{Pod, Zeroable};++/// GPU vertex-instance payload for a single brush dab (`32 bytes`, 16-byte aligned).+#[repr(C)]+#[derive(Debug, Clone, Copy, Pod, Zeroable)]+pub struct DabInstance {+ pub center_doc: [f32; 2],+ pub radius_doc: f32,+ pub hardness: f32,+ pub color_rgba: [f32; 4],+}++#[derive(Debug, Default)]+pub struct StrokeDabGenerator {+ active: bool,+ last_doc_x: f32,+ last_doc_y: f32,+ last_pressure: f32,+ residual_dist: f32,+ stroke_is_eraser: bool,+}++impl StrokeDabGenerator {+ #[inline]+ pub fn is_active(&self) -> bool {+ self.active+ }++ #[inline]+ pub fn stroke_is_eraser(&self) -> bool {+ self.stroke_is_eraser+ }++ pub fn reset(&mut self) {+ self.active = false;+ self.residual_dist = 0.0;+ self.stroke_is_eraser = false;+ }++ #[inline]+ fn eval_radius(params: &BrushParams, pressure: f32) -> f32 {+ let base_size = params.size.clamp(0.5, 2000.0);+ let p = pressure.clamp(0.0, 1.0);+ let diam = if params.use_pressure_size {+ let min_r = params.min_size_ratio.clamp(0.0, 1.0);+ let scaled = base_size * (min_r + (1.0 - min_r) * p);+ if p > 0.005 {+ scaled.max(0.35_f32.min(base_size))+ } else {+ scaled.max(0.15)+ }+ } else {+ base_size+ };+ (diam * 0.5).max(0.25)+ }++ #[inline]+ fn eval_dab_alpha(params: &BrushParams, pressure: f32, spacing_ratio: f32) -> f32 {+ let base_opacity = params.opacity.clamp(0.01, 1.0);+ let p = pressure.clamp(0.0, 1.0);+ let target = if params.use_pressure_opacity {+ base_opacity * (0.1 + 0.9 * p)+ } else {+ base_opacity+ };+ // Flow compensation so tightly spaced dabs accumulate smoothly instead of harsh banding+ let flow_scale = if target >= 0.98 {+ 1.0+ } else {+ 1.0 - (1.0 - target).powf((spacing_ratio * 2.5).clamp(0.15, 1.0))+ };+ flow_scale.clamp(0.01, 1.0)+ }++ /// Starts a new stroke at `(doc_x, doc_y)` and pushes the initial contact dab.+ pub fn begin(+ &mut self,+ doc_x: f32,+ doc_y: f32,+ pressure: f32,+ inverted_eraser: bool,+ params: &BrushParams,+ out: &mut Vec<DabInstance>,+ ) {+ self.active = true;+ self.last_doc_x = doc_x;+ self.last_doc_y = doc_y;+ self.last_pressure = pressure.clamp(0.0, 1.0);+ self.residual_dist = 0.0;+ self.stroke_is_eraser = params.is_eraser || inverted_eraser;++ let spacing_ratio = params.spacing.clamp(0.03, 1.0);+ let radius = Self::eval_radius(params, self.last_pressure);+ let alpha = Self::eval_dab_alpha(params, self.last_pressure, spacing_ratio);+ out.push(DabInstance {+ center_doc: [doc_x, doc_y],+ radius_doc: radius,+ hardness: params.hardness.clamp(0.0, 1.0),+ color_rgba: [params.color[0], params.color[1], params.color[2], alpha],+ });+ }++ /// Advances the active stroke to `(doc_x, doc_y)` and appends spacing-interpolated dabs.+ pub fn push_move(+ &mut self,+ doc_x: f32,+ doc_y: f32,+ pressure: f32,+ params: &BrushParams,+ out: &mut Vec<DabInstance>,+ ) {+ if !self.active {+ return;+ }+ let p1 = pressure.clamp(0.0, 1.0);+ let dx = doc_x - self.last_doc_x;+ let dy = doc_y - self.last_doc_y;+ let seg_len = dx.hypot(dy);+ if seg_len < 1e-4 {+ self.last_pressure = p1;+ return;+ }++ let spacing_ratio = params.spacing.clamp(0.03, 1.0);+ let hardness = params.hardness.clamp(0.0, 1.0);+ let p0 = self.last_pressure;+ let x0 = self.last_doc_x;+ let y0 = self.last_doc_y;++ let mut dist = self.residual_dist;+ // Safety cap per single move packet to avoid giant stalls on huge teleports+ let mut emitted = 0u32;+ const MAX_DABS_PER_SEGMENT: u32 = 1024;++ while dist <= seg_len && emitted < MAX_DABS_PER_SEGMENT {+ let t = (dist / seg_len).clamp(0.0, 1.0);+ let p = p0 + (p1 - p0) * t;+ let radius = Self::eval_radius(params, p);+ let step = (radius * 2.0 * spacing_ratio).max(0.5);+ if dist > 0.0 || self.residual_dist == 0.0 {+ let cx = x0 + dx * t;+ let cy = y0 + dy * t;+ let alpha = Self::eval_dab_alpha(params, p, spacing_ratio);+ out.push(DabInstance {+ center_doc: [cx, cy],+ radius_doc: radius,+ hardness,+ color_rgba: [params.color[0], params.color[1], params.color[2], alpha],+ });+ emitted += 1;+ }+ dist += step;+ }++ self.residual_dist = (dist - seg_len).max(0.0);+ self.last_doc_x = doc_x;+ self.last_doc_y = doc_y;+ self.last_pressure = p1;+ }++ pub fn end(&mut self) {+ self.active = false;+ self.residual_dist = 0.0;+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_dab_generator_interpolates_smooth_pressure_segment() {+ let mut gen = StrokeDabGenerator::default();+ let params = BrushParams {+ size: 20.0,+ opacity: 1.0,+ hardness: 0.9,+ spacing: 0.1,+ min_size_ratio: 0.2,+ use_pressure_size: true,+ use_pressure_opacity: false,+ color: [0.0, 0.0, 0.0, 1.0],+ is_eraser: false,+ };+ let mut dabs = Vec::new();+ gen.begin(10.0, 10.0, 0.25, false, ¶ms, &mut dabs);+ assert_eq!(dabs.len(), 1);+ assert!(gen.is_active());++ gen.push_move(110.0, 10.0, 1.0, ¶ms, &mut dabs);+ assert!(dabs.len() > 20, "expected dense interpolated dabs, got {}", dabs.len());+ let first_r = dabs.first().unwrap().radius_doc;+ let last_r = dabs.last().unwrap().radius_doc;+ assert!(last_r > first_r, "radius should grow with pressure ({first_r} -> {last_r})");++ gen.end();+ assert!(!gen.is_active());+ }+}diff --git a/crates/ink-engine/src/tiles/format.rs b/crates/ink-engine/src/tiles/format.rsnew file mode 100644index 0000000..3aa771e--- /dev/null+++ b/crates/ink-engine/src/tiles/format.rs@@ -0,0 +1,483 @@+//! Fast pixel format conversions between `Monochrome1Bit`, `Grayscale8Bit`,+//! `Color32Bit` (RGBA8), `Mask8Bit`, and internal `Rgba16Float` (4×f16).+//!+//! Includes solid-color tile detection/expansion and 4×4 Bayer ordered dithering+//! when quantizing `Rgba16Float` down to 8-bit at I/O boundaries.++use super::{TileFormat, BYTES_16F, BYTES_1BIT, BYTES_32BIT, BYTES_8BIT, TILE_PIXELS, TILE_SIZE};+use half::f16;+use std::sync::LazyLock;++/// Precomputed LUT mapping every `u8` (0..=255) to its exact normalized IEEE-754 `f16` bits (`v / 255.0`).+static U8_TO_F16_BITS: LazyLock<[u16; 256]> = LazyLock::new(|| {+ let mut lut = [0u16; 256];+ for (i, slot) in lut.iter_mut().enumerate() {+ *slot = f16::from_f32(i as f32 / 255.0).to_bits();+ }+ lut+});++/// Normalized 4×4 Bayer ordered-dither threshold matrix centered in `[-0.46875, +0.46875]`.+const BAYER_4X4: [[f32; 4]; 4] = [+ [-0.46875, 0.03125, -0.34375, 0.15625],+ [0.28125, -0.21875, 0.40625, -0.09375],+ [-0.28125, 0.21875, -0.40625, 0.09375],+ [0.46875, -0.03125, 0.34375, -0.15625],+];++/// Converts a single RGBA8 pixel `[r, g, b, a]` to 4× IEEE-754 `f16` bits.+#[inline]+pub fn rgba8_pixel_to_f16(rgba8: [u8; 4]) -> [u16; 4] {+ let lut = &*U8_TO_F16_BITS;+ [+ lut[rgba8[0] as usize],+ lut[rgba8[1] as usize],+ lut[rgba8[2] as usize],+ lut[rgba8[3] as usize],+ ]+}++/// Converts a single 4× `f16` pixel back to RGBA8 with lossless rounding for 8-bit-origin values.+#[inline]+pub fn f16_pixel_to_rgba8(px: [u16; 4]) -> [u8; 4] {+ [+ (f16::from_bits(px[0]).to_f32().clamp(0.0, 1.0) * 255.0 + 0.5) as u8,+ (f16::from_bits(px[1]).to_f32().clamp(0.0, 1.0) * 255.0 + 0.5) as u8,+ (f16::from_bits(px[2]).to_f32().clamp(0.0, 1.0) * 255.0 + 0.5) as u8,+ (f16::from_bits(px[3]).to_f32().clamp(0.0, 1.0) * 255.0 + 0.5) as u8,+ ]+}++/// Parses `#rgb`, `#rrggbb`, `#rrggbbaa`, or `"transparent"` into `[r, g, b, a]`.+pub fn parse_hex_rgba8(hex: &str) -> Option<[u8; 4]> {+ let s = hex.trim();+ if s.eq_ignore_ascii_case("transparent") {+ return Some([0, 0, 0, 0]);+ }+ let h = s.strip_prefix('#').unwrap_or(s);+ match h.len() {+ 3 => {+ let r = u8::from_str_radix(&h[0..1], 16).ok()?;+ let g = u8::from_str_radix(&h[1..2], 16).ok()?;+ let b = u8::from_str_radix(&h[2..3], 16).ok()?;+ Some([r * 17, g * 17, b * 17, 255])+ }+ 6 => {+ let r = u8::from_str_radix(&h[0..2], 16).ok()?;+ let g = u8::from_str_radix(&h[2..4], 16).ok()?;+ let b = u8::from_str_radix(&h[4..6], 16).ok()?;+ Some([r, g, b, 255])+ }+ 8 => {+ let r = u8::from_str_radix(&h[0..2], 16).ok()?;+ let g = u8::from_str_radix(&h[2..4], 16).ok()?;+ let b = u8::from_str_radix(&h[4..6], 16).ok()?;+ let a = u8::from_str_radix(&h[6..8], 16).ok()?;+ Some([r, g, b, a])+ }+ _ => None,+ }+}++/// Sets a single pixel in an 8,192-byte MSB-first 1-bit monochrome tile.+#[inline]+pub fn set_pixel_1bit(data: &mut [u8], x: usize, y: usize, ink: bool) {+ debug_assert!(x < TILE_SIZE && y < TILE_SIZE && data.len() == BYTES_1BIT);+ let pixel_idx = y * TILE_SIZE + x;+ let byte_idx = pixel_idx >> 3;+ let bit_mask = 1u8 << (7 - (pixel_idx & 7));+ if ink {+ data[byte_idx] |= bit_mask;+ } else {+ data[byte_idx] &= !bit_mask;+ }+}++/// Reads a single pixel (`0` or `1`) from an 8,192-byte MSB-first 1-bit monochrome tile.+#[inline]+pub fn get_pixel_1bit(data: &[u8], x: usize, y: usize) -> u8 {+ debug_assert!(x < TILE_SIZE && y < TILE_SIZE && data.len() == BYTES_1BIT);+ let pixel_idx = y * TILE_SIZE + x;+ let byte_idx = pixel_idx >> 3;+ let bit_offset = 7 - (pixel_idx & 7);+ (data[byte_idx] >> bit_offset) & 1+}++/// Unpacks an 8,192-byte 1-bit tile into 262,144-byte RGBA8 using `ink_rgba` for set bits+/// and `paper_rgba` for cleared bits.+pub fn unpack_1bit_to_rgba8(+ src_1bit: &[u8],+ dst_rgba8: &mut [u8],+ ink_rgba: [u8; 4],+ paper_rgba: [u8; 4],+) {+ assert_eq!(src_1bit.len(), BYTES_1BIT);+ assert_eq!(dst_rgba8.len(), BYTES_32BIT);++ for (byte_i, &b) in src_1bit.iter().enumerate() {+ let base = byte_i * 32;+ if b == 0 {+ if paper_rgba == [0, 0, 0, 0] {+ dst_rgba8[base..base + 32].fill(0);+ } else {+ for p in 0..8 {+ let off = base + p * 4;+ dst_rgba8[off..off + 4].copy_from_slice(&paper_rgba);+ }+ }+ continue;+ }+ for bit in 0..8 {+ let off = base + bit * 4;+ let color = if (b & (0x80 >> bit)) != 0 {+ &ink_rgba+ } else {+ &paper_rgba+ };+ dst_rgba8[off..off + 4].copy_from_slice(color);+ }+ }+}++/// Packs 262,144-byte RGBA8 into an 8,192-byte 1-bit monochrome tile using ITU-R BT.601+/// perceptual luminance thresholding (`alpha >= 24 && lum < threshold`, matching `pixelCodec.ts`).+pub fn pack_rgba8_to_1bit(src_rgba8: &[u8], dst_1bit: &mut [u8], threshold: u8) {+ assert_eq!(src_rgba8.len(), BYTES_32BIT);+ assert_eq!(dst_1bit.len(), BYTES_1BIT);++ let thresh1000 = u32::from(threshold) * 1000;+ for (byte_i, dst_byte) in dst_1bit.iter_mut().enumerate() {+ let base = byte_i * 32;+ let mut out = 0u8;+ for bit in 0..8 {+ let off = base + bit * 4;+ let a = src_rgba8[off + 3];+ if a >= 24 {+ let lum1000 = u32::from(src_rgba8[off]) * 299+ + u32::from(src_rgba8[off + 1]) * 587+ + u32::from(src_rgba8[off + 2]) * 114;+ if lum1000 < thresh1000 {+ out |= 0x80 >> bit;+ }+ }+ }+ *dst_byte = out;+ }+}++/// Unpacks a 65,536-byte 8-bit grayscale tile into 262,144-byte RGBA8 (`0 -> transparent`,+/// non-zero `v -> [v, v, v, 255]`, matching `pixelCodec.ts`).+pub fn unpack_8bit_to_rgba8(src_8bit: &[u8], dst_rgba8: &mut [u8]) {+ assert_eq!(src_8bit.len(), BYTES_8BIT);+ assert_eq!(dst_rgba8.len(), BYTES_32BIT);++ for (i, &val) in src_8bit.iter().enumerate() {+ let off = i * 4;+ if val == 0 {+ dst_rgba8[off..off + 4].fill(0);+ } else {+ dst_rgba8[off] = val;+ dst_rgba8[off + 1] = val;+ dst_rgba8[off + 2] = val;+ dst_rgba8[off + 3] = 255;+ }+ }+}++/// Packs 262,144-byte RGBA8 into a 65,536-byte 8-bit grayscale tile (`a < 10 -> 0`,+/// else ITU-R BT.601 luminance).+pub fn pack_rgba8_to_8bit(src_rgba8: &[u8], dst_8bit: &mut [u8]) {+ assert_eq!(src_rgba8.len(), BYTES_32BIT);+ assert_eq!(dst_8bit.len(), BYTES_8BIT);++ for (i, dst) in dst_8bit.iter_mut().enumerate() {+ let off = i * 4;+ let a = src_rgba8[off + 3];+ if a < 10 {+ *dst = 0;+ } else {+ let lum = (u32::from(src_rgba8[off]) * 299+ + u32::from(src_rgba8[off + 1]) * 587+ + u32::from(src_rgba8[off + 2]) * 114+ + 500)+ / 1000;+ *dst = lum.min(255) as u8;+ }+ }+}++/// Unpacks an 8-bit layer mask (`0 = hidden`, `255 = fully visible`) into opaque grayscale RGBA8.+pub fn unpack_mask8_to_rgba8(src_mask: &[u8], dst_rgba8: &mut [u8]) {+ assert_eq!(src_mask.len(), BYTES_8BIT);+ assert_eq!(dst_rgba8.len(), BYTES_32BIT);++ for (i, &v) in src_mask.iter().enumerate() {+ let off = i * 4;+ dst_rgba8[off] = v;+ dst_rgba8[off + 1] = v;+ dst_rgba8[off + 2] = v;+ dst_rgba8[off + 3] = 255;+ }+}++/// Packs RGBA8 mask canvas pixels into 8-bit mask alpha (`lum * alpha / 255`).+pub fn pack_rgba8_to_mask8(src_rgba8: &[u8], dst_mask: &mut [u8]) {+ assert_eq!(src_rgba8.len(), dst_mask.len() * 4);+ for (i, dst) in dst_mask.iter_mut().enumerate() {+ let off = i * 4;+ let lum = (u32::from(src_rgba8[off]) * 299+ + u32::from(src_rgba8[off + 1]) * 587+ + u32::from(src_rgba8[off + 2]) * 114+ + 500)+ / 1000;+ let a = u32::from(src_rgba8[off + 3]);+ *dst = ((lum * a + 127) / 255).min(255) as u8;+ }+}++/// Converts 262,144-byte RGBA8 into 524,288-byte `Rgba16Float` (little-endian `u16` half-floats).+pub fn rgba8_to_rgba16f(src_rgba8: &[u8], dst_16f: &mut [u8]) {+ assert_eq!(src_rgba8.len(), BYTES_32BIT);+ assert_eq!(dst_16f.len(), BYTES_16F);+ let lut = &*U8_TO_F16_BITS;++ for (i, &channel) in src_rgba8.iter().enumerate() {+ let bits = lut[channel as usize].to_le_bytes();+ let off = i * 2;+ dst_16f[off] = bits[0];+ dst_16f[off + 1] = bits[1];+ }+}++/// Converts 524,288-byte `Rgba16Float` back to 262,144-byte RGBA8 using exact round-to-nearest.+/// Every 8-bit value promoted via `rgba8_to_rgba16f` round-trips bit-identically.+pub fn rgba16f_to_rgba8_lossless(src_16f: &[u8], dst_rgba8: &mut [u8]) {+ assert_eq!(src_16f.len(), BYTES_16F);+ assert_eq!(dst_rgba8.len(), BYTES_32BIT);++ for (dst, chunk) in dst_rgba8.iter_mut().zip(src_16f.chunks_exact(2)) {+ let bits = u16::from_le_bytes([chunk[0], chunk[1]]);+ let v = f16::from_bits(bits).to_f32().clamp(0.0, 1.0);+ *dst = (v * 255.0 + 0.5) as u8;+ }+}++/// Converts 524,288-byte `Rgba16Float` to 262,144-byte RGBA8 with 4×4 Bayer ordered dithering+/// to eliminate visible 8-bit quantization banding on smooth 16-bit gradients at I/O boundaries.+/// Preserves exact `0.0 -> 0` and `1.0 -> 255` endpoints with zero noise on solid black/white/transparent.+pub fn rgba16f_to_rgba8_dithered(src_16f: &[u8], dst_rgba8: &mut [u8]) {+ assert_eq!(src_16f.len(), BYTES_16F);+ assert_eq!(dst_rgba8.len(), BYTES_32BIT);++ for y in 0..TILE_SIZE {+ let bayer_row = &BAYER_4X4[y & 3];+ for x in 0..TILE_SIZE {+ let dither = bayer_row[x & 3];+ let px_idx = y * TILE_SIZE + x;+ let src_base = px_idx * 8;+ let dst_base = px_idx * 4;+ for c in 0..4 {+ let s_off = src_base + c * 2;+ let bits = u16::from_le_bytes([src_16f[s_off], src_16f[s_off + 1]]);+ let v = f16::from_bits(bits).to_f32().clamp(0.0, 1.0);+ if v <= 0.0 {+ dst_rgba8[dst_base + c] = 0;+ } else if v >= 1.0 {+ dst_rgba8[dst_base + c] = 255;+ } else {+ let scaled = (v * 255.0 + dither).clamp(0.0, 255.0);+ dst_rgba8[dst_base + c] = (scaled + 0.5) as u8;+ }+ }+ }+ }+}++/// Converts raw tile bytes from any `TileFormat` to any other `TileFormat`.+pub fn convert_tile_bytes(+ src: &[u8],+ src_fmt: TileFormat,+ dst_fmt: TileFormat,+ mono_threshold: u8,+ dither_16f_to_8: bool,+) -> Vec<u8> {+ if src_fmt == dst_fmt {+ return src.to_vec();+ }++ // Fast path RGBA8 <-> Rgba16Float+ if src_fmt == TileFormat::Color32Bit && dst_fmt == TileFormat::Rgba16Float {+ let mut out = vec![0u8; BYTES_16F];+ rgba8_to_rgba16f(src, &mut out);+ return out;+ }+ if src_fmt == TileFormat::Rgba16Float && dst_fmt == TileFormat::Color32Bit {+ let mut out = vec![0u8; BYTES_32BIT];+ if dither_16f_to_8 {+ rgba16f_to_rgba8_dithered(src, &mut out);+ } else {+ rgba16f_to_rgba8_lossless(src, &mut out);+ }+ return out;+ }++ // Intermediate RGBA8 canonical representation+ let rgba8: Vec<u8> = match src_fmt {+ TileFormat::Color32Bit => src.to_vec(),+ TileFormat::Monochrome1Bit => {+ let mut buf = vec![0u8; BYTES_32BIT];+ unpack_1bit_to_rgba8(src, &mut buf, [0, 0, 0, 255], [0, 0, 0, 0]);+ buf+ }+ TileFormat::Grayscale8Bit => {+ let mut buf = vec![0u8; BYTES_32BIT];+ unpack_8bit_to_rgba8(src, &mut buf);+ buf+ }+ TileFormat::Rgba16Float => {+ let mut buf = vec![0u8; BYTES_32BIT];+ if dither_16f_to_8 {+ rgba16f_to_rgba8_dithered(src, &mut buf);+ } else {+ rgba16f_to_rgba8_lossless(src, &mut buf);+ }+ buf+ }+ };++ match dst_fmt {+ TileFormat::Color32Bit => rgba8,+ TileFormat::Monochrome1Bit => {+ let mut out = vec![0u8; BYTES_1BIT];+ pack_rgba8_to_1bit(&rgba8, &mut out, mono_threshold);+ out+ }+ TileFormat::Grayscale8Bit => {+ let mut out = vec![0u8; BYTES_8BIT];+ pack_rgba8_to_8bit(&rgba8, &mut out);+ out+ }+ TileFormat::Rgba16Float => {+ let mut out = vec![0u8; BYTES_16F];+ rgba8_to_rgba16f(&rgba8, &mut out);+ out+ }+ }+}++/// Checks if a raw tile buffer is completely empty (all transparent / zero ink).+pub fn is_raw_empty(format: TileFormat, raw: &[u8]) -> bool {+ match format {+ TileFormat::Monochrome1Bit | TileFormat::Grayscale8Bit => raw.iter().all(|&b| b == 0),+ TileFormat::Color32Bit => raw.chunks_exact(4).all(|px| px[3] == 0),+ TileFormat::Rgba16Float => raw.chunks_exact(8).all(|px| {+ let a_bits = u16::from_le_bytes([px[6], px[7]]);+ // IEEE-754 +0.0 is 0x0000, -0.0 is 0x8000+ (a_bits & 0x7FFF) == 0+ }),+ }+}++/// Detects if an entire raw tile consists of one uniform pixel value.+/// Returns `Some((rgba8, rgba16f))` if uniform, exiting on the first differing pixel in nanoseconds.+pub fn detect_solid_color(format: TileFormat, raw: &[u8]) -> Option<([u8; 4], [u16; 4])> {+ if raw.len() != format.byte_size() {+ return None;+ }+ match format {+ TileFormat::Monochrome1Bit => {+ let first = raw[0];+ if first != 0x00 && first != 0xFF {+ return None;+ }+ if raw.iter().any(|&b| b != first) {+ return None;+ }+ let rgba8 = if first == 0xFF {+ [0, 0, 0, 255]+ } else {+ [0, 0, 0, 0]+ };+ Some((rgba8, rgba8_pixel_to_f16(rgba8)))+ }+ TileFormat::Grayscale8Bit => {+ let first = raw[0];+ if raw.iter().any(|&b| b != first) {+ return None;+ }+ let rgba8 = if first == 0 {+ [0, 0, 0, 0]+ } else {+ [first, first, first, 255]+ };+ Some((rgba8, rgba8_pixel_to_f16(rgba8)))+ }+ TileFormat::Color32Bit => {+ let first = [raw[0], raw[1], raw[2], raw[3]];+ if raw.chunks_exact(4).any(|px| px != first) {+ return None;+ }+ Some((first, rgba8_pixel_to_f16(first)))+ }+ TileFormat::Rgba16Float => {+ let first_bytes = &raw[0..8];+ if raw.chunks_exact(8).any(|px| px != first_bytes) {+ return None;+ }+ let f16_px = [+ u16::from_le_bytes([first_bytes[0], first_bytes[1]]),+ u16::from_le_bytes([first_bytes[2], first_bytes[3]]),+ u16::from_le_bytes([first_bytes[4], first_bytes[5]]),+ u16::from_le_bytes([first_bytes[6], first_bytes[7]]),+ ];+ Some((f16_pixel_to_rgba8(f16_px), f16_px))+ }+ }+}++/// Expands a uniform `SolidColor` into a full raw tile buffer in `format`.+pub fn expand_solid_to_raw(format: TileFormat, rgba8: [u8; 4], rgba16f: [u16; 4]) -> Vec<u8> {+ match format {+ TileFormat::Monochrome1Bit => {+ let fill = if rgba8[3] >= 24 { 0xFF } else { 0x00 };+ vec![fill; BYTES_1BIT]+ }+ TileFormat::Grayscale8Bit => {+ let fill = if rgba8[3] == 0 { 0 } else { rgba8[0] };+ vec![fill; BYTES_8BIT]+ }+ TileFormat::Color32Bit => {+ let mut out = vec![0u8; BYTES_32BIT];+ if rgba8 != [0, 0, 0, 0] {+ for px in out.chunks_exact_mut(4) {+ px.copy_from_slice(&rgba8);+ }+ }+ out+ }+ TileFormat::Rgba16Float => {+ let mut out = vec![0u8; BYTES_16F];+ if rgba16f != [0, 0, 0, 0] {+ let mut pattern = [0u8; 8];+ pattern[0..2].copy_from_slice(&rgba16f[0].to_le_bytes());+ pattern[2..4].copy_from_slice(&rgba16f[1].to_le_bytes());+ pattern[4..6].copy_from_slice(&rgba16f[2].to_le_bytes());+ pattern[6..8].copy_from_slice(&rgba16f[3].to_le_bytes());+ for px in out.chunks_exact_mut(8) {+ px.copy_from_slice(&pattern);+ }+ }+ out+ }+ }+}++/// Expands a uniform `SolidColor` directly into RGBA16F bytes (524,288 bytes) for GPU upload.+pub fn expand_solid_to_rgba16f(rgba16f: [u16; 4]) -> Vec<u8> {+ expand_solid_to_raw(TileFormat::Rgba16Float, [0, 0, 0, 0], rgba16f)+}++/// Expands a uniform mask value (`0..=255`) into 65,536-byte 8-bit mask buffer.+pub fn expand_solid_mask8(val: u8) -> Vec<u8> {+ vec![val; TILE_PIXELS]+}diff --git a/crates/ink-engine/src/tiles/grid.rs b/crates/ink-engine/src/tiles/grid.rsnew file mode 100644index 0000000..3698396--- /dev/null+++ b/crates/ink-engine/src/tiles/grid.rs@@ -0,0 +1,1230 @@+//! Per-layer sparse virtual tile grid storing BOTH raster tiles and non-destructive+//! 8-bit mask tiles with O(1) Copy-on-Write (`Arc<TileData>`) cloning and diffing.++use super::format::{+ convert_tile_bytes, get_pixel_1bit, is_raw_empty, pack_rgba8_to_1bit, pack_rgba8_to_8bit,+ rgba16f_to_rgba8_dithered, rgba8_to_rgba16f, set_pixel_1bit,+};+use super::tile_data::{TileData, TileStorage};+use super::{+ allocate_tile_version, pixel_to_tile_coord, TileCoord, TileFormat, TileKind, BYTES_16F,+ BYTES_1BIT, BYTES_32BIT, BYTES_8BIT, TILE_SIZE, TILE_SIZE_I32,+};+use crate::memory::ScratchBackend;+use serde::{Deserialize, Serialize};+use std::collections::{HashMap, HashSet};+use std::sync::Arc;++/// Integer axis-aligned rectangle in document pixel space.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RectI32 {+ pub x: i32,+ pub y: i32,+ pub width: u32,+ pub height: u32,+}++impl RectI32 {+ #[inline]+ pub const fn new(x: i32, y: i32, width: u32, height: u32) -> Self {+ Self {+ x,+ y,+ width,+ height,+ }+ }++ #[inline]+ pub const fn is_empty(&self) -> bool {+ self.width == 0 || self.height == 0+ }++ #[inline]+ pub const fn right(&self) -> i32 {+ self.x + self.width as i32+ }++ #[inline]+ pub const fn bottom(&self) -> i32 {+ self.y + self.height as i32+ }+}++/// Copy-on-Write tile delta stored in the Rust Undo/Redo history stack.+///+/// Both `before` and `after` hold shared `Arc<TileData>` references, so untouched tiles+/// cost zero extra memory and undo/redo swaps pointers in O(1).+#[derive(Debug, Clone)]+pub struct CowTileDelta {+ pub layer_id: String,+ pub kind: TileKind,+ pub coord: TileCoord,+ pub before: Option<Arc<TileData>>,+ pub after: Option<Arc<TileData>>,+ pub remote_epoch: u64,+}++/// Sparse virtual tile store for a single layer (raster tiles + non-destructive 8-bit mask tiles).+#[derive(Debug, Clone)]+pub struct SparseLayerGrid {+ pub format: TileFormat,+ /// LOD 0 raster tiles keyed by `(tx, ty)`. Empty/transparent tiles are omitted.+ pub tiles: HashMap<TileCoord, Arc<TileData>>,+ /// Whether this layer has a non-destructive 8-bit mask attached.+ pub has_mask: bool,+ /// Default mask alpha (`255` = reveal all, `0` = hide all) for unallocated mask tiles.+ pub mask_default_value: u8,+ /// LOD 0 sparse 8-bit mask tiles (`TileFormat::Grayscale8Bit`, `TileKind::Mask`).+ /// Tiles uniform at `mask_default_value` are omitted for 0-byte memory footprint.+ pub mask_tiles: HashMap<TileCoord, Arc<TileData>>,+ /// Dirty mipmap tiles awaiting GPU compute downsample regeneration for LOD 1, 2, 3.+ pub dirty_lods: [HashSet<TileCoord>; 3],+ /// Monotonic version counter bumped on any raster or mask mutation.+ pub layer_version: u64,+ /// Per-tile remote peer mutation epoch for collaborative conflict-aware selective undo.+ pub remote_epochs: HashMap<TileCoord, u64>,+}++impl Default for SparseLayerGrid {+ fn default() -> Self {+ Self::new(TileFormat::Color32Bit)+ }+}++impl SparseLayerGrid {+ pub fn new(format: TileFormat) -> Self {+ Self {+ format,+ tiles: HashMap::new(),+ has_mask: false,+ mask_default_value: 255,+ mask_tiles: HashMap::new(),+ dirty_lods: [HashSet::new(), HashSet::new(), HashSet::new()],+ layer_version: allocate_tile_version(),+ remote_epochs: HashMap::new(),+ }+ }++ /// O(1) Copy-on-Write clone: shares every `Arc<TileData>` without duplicating pixel buffers.+ pub fn clone_cow(&self) -> Self {+ Self {+ format: self.format,+ tiles: self.tiles.clone(),+ has_mask: self.has_mask,+ mask_default_value: self.mask_default_value,+ mask_tiles: self.mask_tiles.clone(),+ dirty_lods: self.dirty_lods.clone(),+ layer_version: allocate_tile_version(),+ remote_epochs: self.remote_epochs.clone(),+ }+ }++ #[inline]+ pub fn bump_version(&mut self) {+ self.layer_version = allocate_tile_version();+ }++ #[inline]+ pub fn mark_lod_ancestors_dirty(&mut self, coord: TileCoord) {+ let mut c = coord;+ for lod_idx in 0..3 {+ c = c.parent();+ self.dirty_lods[lod_idx].insert(c);+ }+ }++ /// Marks all populated tiles' LOD 1..3 ancestors dirty (e.g. after bulk hydration).+ pub fn mark_all_lods_dirty(&mut self) {+ let coords: Vec<TileCoord> = self.tiles.keys().copied().collect();+ for c in coords {+ self.mark_lod_ancestors_dirty(c);+ }+ }++ #[inline]+ pub fn tile_map(&self, kind: TileKind) -> &HashMap<TileCoord, Arc<TileData>> {+ match kind {+ TileKind::Raster => &self.tiles,+ TileKind::Mask => &self.mask_tiles,+ }+ }++ #[inline]+ pub fn tile_map_mut(&mut self, kind: TileKind) -> &mut HashMap<TileCoord, Arc<TileData>> {+ match kind {+ TileKind::Raster => &mut self.tiles,+ TileKind::Mask => &mut self.mask_tiles,+ }+ }++ #[inline]+ pub fn get_tile(&self, coord: TileCoord) -> Option<&Arc<TileData>> {+ self.tiles.get(&coord)+ }++ #[inline]+ pub fn get_mask_tile(&self, coord: TileCoord) -> Option<&Arc<TileData>> {+ self.mask_tiles.get(&coord)+ }++ pub fn set_tile(&mut self, coord: TileCoord, tile: Arc<TileData>) {+ self.tiles.insert(coord, tile);+ self.mark_lod_ancestors_dirty(coord);+ self.bump_version();+ }++ pub fn remove_tile(&mut self, coord: TileCoord) -> Option<Arc<TileData>> {+ let prev = self.tiles.remove(&coord);+ if prev.is_some() {+ self.mark_lod_ancestors_dirty(coord);+ self.bump_version();+ }+ prev+ }++ pub fn set_mask_tile(&mut self, coord: TileCoord, tile: Arc<TileData>) {+ self.has_mask = true;+ self.mask_tiles.insert(coord, tile);+ self.bump_version();+ }++ pub fn remove_mask_tile(&mut self, coord: TileCoord) -> Option<Arc<TileData>> {+ let prev = self.mask_tiles.remove(&coord);+ if prev.is_some() {+ self.bump_version();+ }+ prev+ }++ pub fn clear_raster(&mut self) {+ let coords: Vec<TileCoord> = self.tiles.keys().copied().collect();+ self.tiles.clear();+ for c in coords {+ self.mark_lod_ancestors_dirty(c);+ }+ self.bump_version();+ }++ /// Initializes a non-destructive 8-bit layer mask (`default_value = 255` for reveal-all+ /// allocates ZERO mask tiles!).+ pub fn init_mask(&mut self, default_value: u8) {+ self.has_mask = true;+ self.mask_default_value = default_value;+ self.mask_tiles.clear();+ self.bump_version();+ }++ pub fn remove_mask(&mut self) {+ self.has_mask = false;+ self.mask_tiles.clear();+ self.bump_version();+ }++ /// Fills `[0..width, 0..height]` with a uniform RGBA8 color using zero-allocation+ /// [`TileStorage::SolidColor`] tiles for full interior tiles and exact clipped tiles at edges.+ pub fn fill_solid_layer(&mut self, width: u32, height: u32, rgba8: [u8; 4]) {+ self.clear_raster();+ if width == 0 || height == 0 || rgba8[3] == 0 {+ return;+ }+ let max_tx = pixel_to_tile_coord(width as i32 - 1, 0);+ let max_ty = pixel_to_tile_coord(height as i32 - 1, 0);+ // Share a single Arc<TileData> across EVERY full interior solid tile (O(1) memory!)+ let shared_solid = Arc::new(TileData::new_solid(self.format, TileKind::Raster, rgba8));++ for ty in 0..=max_ty {+ let y0 = ty * TILE_SIZE_I32;+ let valid_h = ((height as i32) - y0).clamp(0, TILE_SIZE_I32) as usize;+ for tx in 0..=max_tx {+ let x0 = tx * TILE_SIZE_I32;+ let valid_w = ((width as i32) - x0).clamp(0, TILE_SIZE_I32) as usize;+ let coord = TileCoord::new(tx, ty);+ if valid_w == TILE_SIZE && valid_h == TILE_SIZE {+ self.tiles.insert(coord, Arc::clone(&shared_solid));+ } else {+ let mut tile_rgba = vec![0u8; BYTES_32BIT];+ for ly in 0..valid_h {+ let row_start = ly * TILE_SIZE * 4;+ for lx in 0..valid_w {+ let off = row_start + lx * 4;+ tile_rgba[off..off + 4].copy_from_slice(&rgba8);+ }+ }+ let raw = convert_tile_bytes(+ &tile_rgba,+ TileFormat::Color32Bit,+ self.format,+ 128,+ false,+ );+ self.tiles.insert(+ coord,+ Arc::new(TileData::from_raw_auto_compact(+ self.format,+ TileKind::Raster,+ raw,+ )),+ );+ }+ self.mark_lod_ancestors_dirty(coord);+ }+ }+ self.bump_version();+ }++ /// Reads a single RGBA8 pixel in O(1) without allocating a tile buffer.+ pub fn get_pixel_rgba8(&self, x: i32, y: i32, scratch: Option<&dyn ScratchBackend>) -> [u8; 4] {+ let tx = pixel_to_tile_coord(x, 0);+ let ty = pixel_to_tile_coord(y, 0);+ let Some(tile) = self.tiles.get(&TileCoord::new(tx, ty)) else {+ return [0, 0, 0, 0];+ };+ if let TileStorage::SolidColor { rgba8, .. } = tile.storage {+ return rgba8;+ }+ let lx = (x - tx * TILE_SIZE_I32) as usize;+ let ly = (y - ty * TILE_SIZE_I32) as usize;+ let Ok(raw) = tile.materialize_raw(scratch) else {+ return [0, 0, 0, 0];+ };+ match tile.format {+ TileFormat::Color32Bit => {+ let off = (ly * TILE_SIZE + lx) * 4;+ [raw[off], raw[off + 1], raw[off + 2], raw[off + 3]]+ }+ TileFormat::Monochrome1Bit => {+ if get_pixel_1bit(&raw, lx, ly) != 0 {+ [0, 0, 0, 255]+ } else {+ [0, 0, 0, 0]+ }+ }+ TileFormat::Grayscale8Bit => {+ let v = raw[ly * TILE_SIZE + lx];+ if v == 0 {+ [0, 0, 0, 0]+ } else {+ [v, v, v, 255]+ }+ }+ TileFormat::Rgba16Float => {+ let off = (ly * TILE_SIZE + lx) * 8;+ let px = [+ u16::from_le_bytes([raw[off], raw[off + 1]]),+ u16::from_le_bytes([raw[off + 2], raw[off + 3]]),+ u16::from_le_bytes([raw[off + 4], raw[off + 5]]),+ u16::from_le_bytes([raw[off + 6], raw[off + 7]]),+ ];+ super::format::f16_pixel_to_rgba8(px)+ }+ }+ }++ /// Reads a single 8-bit mask alpha value (`0..=255`) at `(x, y)`.+ pub fn get_mask_alpha(&self, x: i32, y: i32, scratch: Option<&dyn ScratchBackend>) -> u8 {+ if !self.has_mask {+ return 255;+ }+ let tx = pixel_to_tile_coord(x, 0);+ let ty = pixel_to_tile_coord(y, 0);+ let Some(tile) = self.mask_tiles.get(&TileCoord::new(tx, ty)) else {+ return self.mask_default_value;+ };+ if let TileStorage::SolidColor { rgba8, .. } = tile.storage {+ return rgba8[0];+ }+ let lx = (x - tx * TILE_SIZE_I32) as usize;+ let ly = (y - ty * TILE_SIZE_I32) as usize;+ match tile.materialize_raw(scratch) {+ Ok(raw) => raw[ly * TILE_SIZE + lx],+ Err(_) => self.mask_default_value,+ }+ }++ /// Writes an arbitrary RGBA8 rectangle into LOD 0 raster tiles (Copy-on-Write).+ /// Auto-converts into `self.format`, prunes completely transparent tiles, compacts uniform+ /// tiles to `SolidColor`, and returns the list of touched tile coordinates.+ pub fn write_rgba8_rect(+ &mut self,+ rgba8: &[u8],+ rect: RectI32,+ mono_threshold: u8,+ scratch: Option<&dyn ScratchBackend>,+ ) -> Result<Vec<TileCoord>, String> {+ if rect.is_empty() {+ return Ok(Vec::new());+ }+ let expected_len = (rect.width as usize)+ .checked_mul(rect.height as usize)+ .and_then(|n| n.checked_mul(4))+ .ok_or_else(|| "write_rgba8_rect dimensions overflow".to_string())?;+ if rgba8.len() != expected_len {+ return Err(format!(+ "write_rgba8_rect buffer length mismatch: expected {}, got {}",+ expected_len,+ rgba8.len()+ ));+ }++ let x0 = rect.x;+ let y0 = rect.y;+ let x1 = rect.right();+ let y1 = rect.bottom();+ let min_tx = pixel_to_tile_coord(x0, 0);+ let min_ty = pixel_to_tile_coord(y0, 0);+ let max_tx = pixel_to_tile_coord(x1 - 1, 0);+ let max_ty = pixel_to_tile_coord(y1 - 1, 0);++ let src_w = rect.width as usize;+ let mut touched = Vec::new();++ for ty in min_ty..=max_ty {+ let tile_y0 = ty * TILE_SIZE_I32;+ let iy0 = y0.max(tile_y0);+ let iy1 = y1.min(tile_y0 + TILE_SIZE_I32);+ if iy0 >= iy1 {+ continue;+ }+ for tx in min_tx..=max_tx {+ let tile_x0 = tx * TILE_SIZE_I32;+ let ix0 = x0.max(tile_x0);+ let ix1 = x1.min(tile_x0 + TILE_SIZE_I32);+ if ix0 >= ix1 {+ continue;+ }+ let coord = TileCoord::new(tx, ty);+ let copy_w = (ix1 - ix0) as usize;+ let full_tile = ix0 == tile_x0+ && iy0 == tile_y0+ && ix1 == tile_x0 + TILE_SIZE_I32+ && iy1 == tile_y0 + TILE_SIZE_I32;++ let mut work_rgba = if full_tile {+ vec![0u8; BYTES_32BIT]+ } else if let Some(existing) = self.tiles.get(&coord) {+ existing.to_rgba8(scratch, false)?+ } else {+ vec![0u8; BYTES_32BIT]+ };++ for y in iy0..iy1 {+ let sy = (y - y0) as usize;+ let sx = (ix0 - x0) as usize;+ let dy = (y - tile_y0) as usize;+ let dx = (ix0 - tile_x0) as usize;+ let src_off = (sy * src_w + sx) * 4;+ let dst_off = (dy * TILE_SIZE + dx) * 4;+ work_rgba[dst_off..dst_off + copy_w * 4]+ .copy_from_slice(&rgba8[src_off..src_off + copy_w * 4]);+ }++ if is_raw_empty(TileFormat::Color32Bit, &work_rgba) {+ self.tiles.remove(&coord);+ } else {+ let tile_bytes = match self.format {+ TileFormat::Color32Bit => work_rgba,+ TileFormat::Monochrome1Bit => {+ let mut out = vec![0u8; BYTES_1BIT];+ pack_rgba8_to_1bit(&work_rgba, &mut out, mono_threshold);+ if is_raw_empty(TileFormat::Monochrome1Bit, &out) {+ self.tiles.remove(&coord);+ self.mark_lod_ancestors_dirty(coord);+ touched.push(coord);+ continue;+ }+ out+ }+ TileFormat::Grayscale8Bit => {+ let mut out = vec![0u8; BYTES_8BIT];+ pack_rgba8_to_8bit(&work_rgba, &mut out);+ if is_raw_empty(TileFormat::Grayscale8Bit, &out) {+ self.tiles.remove(&coord);+ self.mark_lod_ancestors_dirty(coord);+ touched.push(coord);+ continue;+ }+ out+ }+ TileFormat::Rgba16Float => {+ let mut out = vec![0u8; BYTES_16F];+ rgba8_to_rgba16f(&work_rgba, &mut out);+ out+ }+ };+ self.tiles.insert(+ coord,+ Arc::new(TileData::from_raw_auto_compact(+ self.format,+ TileKind::Raster,+ tile_bytes,+ )),+ );+ }+ self.mark_lod_ancestors_dirty(coord);+ touched.push(coord);+ }+ }++ if !touched.is_empty() {+ self.bump_version();+ }+ Ok(touched)+ }++ /// Reads an arbitrary RGBA8 rectangle out of LOD 0 raster tiles.+ pub fn read_rgba8_rect(+ &self,+ rect: RectI32,+ dither: bool,+ scratch: Option<&dyn ScratchBackend>,+ ) -> Result<Vec<u8>, String> {+ let total = (rect.width as usize)+ .checked_mul(rect.height as usize)+ .and_then(|n| n.checked_mul(4))+ .ok_or_else(|| "read_rgba8_rect dimensions overflow".to_string())?;+ let mut out = vec![0u8; total];+ if rect.is_empty() || self.tiles.is_empty() {+ return Ok(out);+ }++ let x0 = rect.x;+ let y0 = rect.y;+ let x1 = rect.right();+ let y1 = rect.bottom();+ let min_tx = pixel_to_tile_coord(x0, 0);+ let min_ty = pixel_to_tile_coord(y0, 0);+ let max_tx = pixel_to_tile_coord(x1 - 1, 0);+ let max_ty = pixel_to_tile_coord(y1 - 1, 0);+ let dst_w = rect.width as usize;++ for ty in min_ty..=max_ty {+ let tile_y0 = ty * TILE_SIZE_I32;+ let iy0 = y0.max(tile_y0);+ let iy1 = y1.min(tile_y0 + TILE_SIZE_I32);+ if iy0 >= iy1 {+ continue;+ }+ for tx in min_tx..=max_tx {+ let Some(tile) = self.tiles.get(&TileCoord::new(tx, ty)) else {+ continue;+ };+ let tile_x0 = tx * TILE_SIZE_I32;+ let ix0 = x0.max(tile_x0);+ let ix1 = x1.min(tile_x0 + TILE_SIZE_I32);+ if ix0 >= ix1 {+ continue;+ }+ let copy_w = (ix1 - ix0) as usize;++ if let TileStorage::SolidColor { rgba8, .. } = tile.storage {+ if rgba8[3] == 0 {+ continue;+ }+ for y in iy0..iy1 {+ let dy = (y - y0) as usize;+ let dx = (ix0 - x0) as usize;+ let row_base = (dy * dst_w + dx) * 4;+ for px in 0..copy_w {+ out[row_base + px * 4..row_base + px * 4 + 4].copy_from_slice(&rgba8);+ }+ }+ continue;+ }++ let tile_rgba = tile.to_rgba8(scratch, dither)?;+ for y in iy0..iy1 {+ let sy = (y - tile_y0) as usize;+ let sx = (ix0 - tile_x0) as usize;+ let dy = (y - y0) as usize;+ let dx = (ix0 - x0) as usize;+ let src_off = (sy * TILE_SIZE + sx) * 4;+ let dst_off = (dy * dst_w + dx) * 4;+ out[dst_off..dst_off + copy_w * 4]+ .copy_from_slice(&tile_rgba[src_off..src_off + copy_w * 4]);+ }+ }+ }+ Ok(out)+ }++ /// Writes an 8-bit grayscale mask rectangle (`1 byte/pixel`) directly into sparse `mask_tiles`.+ /// Tiles that uniformly match `self.mask_default_value` are automatically deleted for zero memory.+ pub fn write_mask8_rect(+ &mut self,+ mask8: &[u8],+ rect: RectI32,+ scratch: Option<&dyn ScratchBackend>,+ ) -> Result<Vec<TileCoord>, String> {+ if rect.is_empty() {+ return Ok(Vec::new());+ }+ let expected_len = (rect.width as usize)+ .checked_mul(rect.height as usize)+ .ok_or_else(|| "write_mask8_rect dimensions overflow".to_string())?;+ if mask8.len() != expected_len {+ return Err(format!(+ "write_mask8_rect length mismatch: expected {}, got {}",+ expected_len,+ mask8.len()+ ));+ }++ self.has_mask = true;+ let x0 = rect.x;+ let y0 = rect.y;+ let x1 = rect.right();+ let y1 = rect.bottom();+ let min_tx = pixel_to_tile_coord(x0, 0);+ let min_ty = pixel_to_tile_coord(y0, 0);+ let max_tx = pixel_to_tile_coord(x1 - 1, 0);+ let max_ty = pixel_to_tile_coord(y1 - 1, 0);+ let src_w = rect.width as usize;+ let default_v = self.mask_default_value;+ let mut touched = Vec::new();++ for ty in min_ty..=max_ty {+ let tile_y0 = ty * TILE_SIZE_I32;+ let iy0 = y0.max(tile_y0);+ let iy1 = y1.min(tile_y0 + TILE_SIZE_I32);+ if iy0 >= iy1 {+ continue;+ }+ for tx in min_tx..=max_tx {+ let tile_x0 = tx * TILE_SIZE_I32;+ let ix0 = x0.max(tile_x0);+ let ix1 = x1.min(tile_x0 + TILE_SIZE_I32);+ if ix0 >= ix1 {+ continue;+ }+ let coord = TileCoord::new(tx, ty);+ let copy_w = (ix1 - ix0) as usize;+ let full_tile = ix0 == tile_x0+ && iy0 == tile_y0+ && ix1 == tile_x0 + TILE_SIZE_I32+ && iy1 == tile_y0 + TILE_SIZE_I32;++ let mut buf = if full_tile {+ vec![default_v; BYTES_8BIT]+ } else if let Some(existing) = self.mask_tiles.get(&coord) {+ existing.materialize_raw(scratch)?+ } else {+ vec![default_v; BYTES_8BIT]+ };++ for y in iy0..iy1 {+ let sy = (y - y0) as usize;+ let sx = (ix0 - x0) as usize;+ let dy = (y - tile_y0) as usize;+ let dx = (ix0 - tile_x0) as usize;+ let src_off = sy * src_w + sx;+ let dst_off = dy * TILE_SIZE + dx;+ buf[dst_off..dst_off + copy_w]+ .copy_from_slice(&mask8[src_off..src_off + copy_w]);+ }++ if buf.iter().all(|&b| b == default_v) {+ self.mask_tiles.remove(&coord);+ } else {+ self.mask_tiles.insert(+ coord,+ Arc::new(TileData::from_raw_auto_compact(+ TileFormat::Grayscale8Bit,+ TileKind::Mask,+ buf,+ )),+ );+ }+ touched.push(coord);+ }+ }++ if !touched.is_empty() {+ self.bump_version();+ }+ Ok(touched)+ }++ /// Reads an 8-bit grayscale mask rectangle out of sparse `mask_tiles`.+ pub fn read_mask8_rect(+ &self,+ rect: RectI32,+ scratch: Option<&dyn ScratchBackend>,+ ) -> Result<Vec<u8>, String> {+ let total = (rect.width as usize)+ .checked_mul(rect.height as usize)+ .ok_or_else(|| "read_mask8_rect dimensions overflow".to_string())?;+ let fill = if self.has_mask {+ self.mask_default_value+ } else {+ 255+ };+ let mut out = vec![fill; total];+ if !self.has_mask || rect.is_empty() || self.mask_tiles.is_empty() {+ return Ok(out);+ }++ let x0 = rect.x;+ let y0 = rect.y;+ let x1 = rect.right();+ let y1 = rect.bottom();+ let min_tx = pixel_to_tile_coord(x0, 0);+ let min_ty = pixel_to_tile_coord(y0, 0);+ let max_tx = pixel_to_tile_coord(x1 - 1, 0);+ let max_ty = pixel_to_tile_coord(y1 - 1, 0);+ let dst_w = rect.width as usize;++ for ty in min_ty..=max_ty {+ let tile_y0 = ty * TILE_SIZE_I32;+ let iy0 = y0.max(tile_y0);+ let iy1 = y1.min(tile_y0 + TILE_SIZE_I32);+ if iy0 >= iy1 {+ continue;+ }+ for tx in min_tx..=max_tx {+ let Some(tile) = self.mask_tiles.get(&TileCoord::new(tx, ty)) else {+ continue;+ };+ let tile_x0 = tx * TILE_SIZE_I32;+ let ix0 = x0.max(tile_x0);+ let ix1 = x1.min(tile_x0 + TILE_SIZE_I32);+ if ix0 >= ix1 {+ continue;+ }+ let copy_w = (ix1 - ix0) as usize;+ let raw = tile.materialize_raw(scratch)?;+ for y in iy0..iy1 {+ let sy = (y - tile_y0) as usize;+ let sx = (ix0 - tile_x0) as usize;+ let dy = (y - y0) as usize;+ let dx = (ix0 - x0) as usize;+ out[dy * dst_w + dx..dy * dst_w + dx + copy_w]+ .copy_from_slice(&raw[sy * TILE_SIZE + sx..sy * TILE_SIZE + sx + copy_w]);+ }+ }+ }+ Ok(out)+ }++ /// Captures an O(1) Copy-on-Write snapshot of all tiles in `kind` (just clones `Arc` pointers).+ pub fn snapshot_all_cow(&self, kind: TileKind) -> HashMap<TileCoord, Arc<TileData>> {+ self.tile_map(kind).clone()+ }++ /// Captures an O(1) Copy-on-Write snapshot of tiles intersecting `rect`.+ pub fn snapshot_rect_cow(+ &self,+ kind: TileKind,+ rect: RectI32,+ ) -> HashMap<TileCoord, Option<Arc<TileData>>> {+ let mut snap = HashMap::new();+ if rect.is_empty() {+ return snap;+ }+ let map = self.tile_map(kind);+ let min_tx = pixel_to_tile_coord(rect.x, 0);+ let min_ty = pixel_to_tile_coord(rect.y, 0);+ let max_tx = pixel_to_tile_coord(rect.right() - 1, 0);+ let max_ty = pixel_to_tile_coord(rect.bottom() - 1, 0);+ for ty in min_ty..=max_ty {+ for tx in min_tx..=max_tx {+ let c = TileCoord::new(tx, ty);+ snap.insert(c, map.get(&c).cloned());+ }+ }+ snap+ }++ /// Computes minimal Copy-on-Write deltas from a full `snapshot_all_cow`.+ /// Untouched tiles are skipped in O(1) via `Arc::ptr_eq`!+ pub fn diff_from_full_snapshot(+ &self,+ layer_id: &str,+ kind: TileKind,+ before_snap: &HashMap<TileCoord, Arc<TileData>>,+ ) -> Vec<CowTileDelta> {+ let current = self.tile_map(kind);+ let mut all_coords: HashSet<TileCoord> = before_snap.keys().copied().collect();+ all_coords.extend(current.keys().copied());++ let mut deltas = Vec::new();+ for coord in all_coords {+ let before = before_snap.get(&coord);+ let after = current.get(&coord);+ let unchanged = match (before, after) {+ (None, None) => true,+ (Some(a), Some(b)) => Arc::ptr_eq(a, b),+ _ => false,+ };+ if !unchanged {+ deltas.push(CowTileDelta {+ layer_id: layer_id.to_string(),+ kind,+ coord,+ before: before.cloned(),+ after: after.cloned(),+ remote_epoch: self.remote_epochs.get(&coord).copied().unwrap_or(0),+ });+ }+ }+ deltas+ }++ /// Applies a single CoW tile delta (`undo = true` restores `before`, `undo = false` restores `after`).+ pub fn apply_delta(&mut self, delta: &CowTileDelta, undo: bool) {+ let target = if undo { &delta.before } else { &delta.after };+ match delta.kind {+ TileKind::Raster => {+ if let Some(tile) = target {+ self.tiles.insert(delta.coord, Arc::clone(tile));+ } else {+ self.tiles.remove(&delta.coord);+ }+ self.mark_lod_ancestors_dirty(delta.coord);+ }+ TileKind::Mask => {+ if let Some(tile) = target {+ self.has_mask = true;+ self.mask_tiles.insert(delta.coord, Arc::clone(tile));+ } else {+ self.mask_tiles.remove(&delta.coord);+ }+ }+ }+ self.bump_version();+ }++ /// Converts all populated raster tiles in this layer to `target_format`.+ pub fn convert_format(+ &mut self,+ target_format: TileFormat,+ mono_threshold: u8,+ dither: bool,+ scratch: Option<&dyn ScratchBackend>,+ ) -> Result<(), String> {+ if self.format == target_format {+ return Ok(());+ }+ let coords: Vec<TileCoord> = self.tiles.keys().copied().collect();+ for coord in coords {+ let Some(tile) = self.tiles.get(&coord) else {+ continue;+ };+ let converted = tile.to_format_raw(target_format, mono_threshold, dither, scratch)?;+ if is_raw_empty(target_format, &converted) {+ self.tiles.remove(&coord);+ } else {+ self.tiles.insert(+ coord,+ Arc::new(TileData::from_raw_auto_compact(+ target_format,+ TileKind::Raster,+ converted,+ )),+ );+ }+ self.mark_lod_ancestors_dirty(coord);+ }+ self.format = target_format;+ self.bump_version();+ Ok(())+ }++ /// Resizes or crops this layer's raster (and optional mask) tiles directly without+ /// duplicating unaffected storage, supporting both anchor offset shift/crop and bilinear scaling.+ #[allow(clippy::too_many_arguments)]+ pub fn resize_and_crop(+ &mut self,+ old_w: u32,+ old_h: u32,+ new_w: u32,+ new_h: u32,+ offset_x: i32,+ offset_y: i32,+ scale_content: bool,+ bg_fill: Option<[u8; 4]>,+ scratch: Option<&dyn ScratchBackend>,+ ) -> Result<(), String> {+ let old_raster = self.read_rgba8_rect(RectI32::new(0, 0, old_w, old_h), false, scratch)?;+ let old_mask = if self.has_mask {+ Some(self.read_mask8_rect(RectI32::new(0, 0, old_w, old_h), scratch)?)+ } else {+ None+ };++ self.clear_raster();+ if let Some(bg) = bg_fill {+ if bg[3] > 0 {+ self.fill_solid_layer(new_w, new_h, bg);+ }+ }++ if new_w > 0 && new_h > 0 && old_w > 0 && old_h > 0 {+ let new_rgba = if scale_content {+ bilinear_scale_rgba8(&old_raster, old_w, old_h, new_w, new_h)+ } else {+ shift_and_crop_rgba8(&old_raster, old_w, old_h, new_w, new_h, offset_x, offset_y, bg_fill)+ };+ self.write_rgba8_rect(&new_rgba, RectI32::new(0, 0, new_w, new_h), 128, scratch)?;++ if let Some(mask_bytes) = old_mask {+ self.mask_tiles.clear();+ let new_mask = if scale_content {+ bilinear_scale_u8(&mask_bytes, old_w, old_h, new_w, new_h)+ } else {+ shift_and_crop_u8(+ &mask_bytes,+ old_w,+ old_h,+ new_w,+ new_h,+ offset_x,+ offset_y,+ self.mask_default_value,+ )+ };+ self.write_mask8_rect(&new_mask, RectI32::new(0, 0, new_w, new_h), scratch)?;+ }+ }+ self.bump_version();+ Ok(())+ }++ /// Computes a tight bounding box of non-transparent (or non-white for background) pixels.+ pub fn content_bounds(+ &self,+ doc_w: u32,+ doc_h: u32,+ is_background: bool,+ scratch: Option<&dyn ScratchBackend>,+ ) -> Option<RectI32> {+ if self.tiles.is_empty() || doc_w == 0 || doc_h == 0 {+ return None;+ }+ let mut min_x = doc_w as i32;+ let mut min_y = doc_h as i32;+ let mut max_x = -1i32;+ let mut max_y = -1i32;++ for (&coord, tile) in &self.tiles {+ if is_background && tile.solid_rgba8() == Some([255, 255, 255, 255]) {+ continue;+ }+ let tile_x0 = coord.tx * TILE_SIZE_I32;+ let tile_y0 = coord.ty * TILE_SIZE_I32;+ if tile_x0 >= doc_w as i32+ || tile_y0 >= doc_h as i32+ || tile_x0 + TILE_SIZE_I32 <= 0+ || tile_y0 + TILE_SIZE_I32 <= 0+ {+ continue;+ }+ let start_lx = (-tile_x0).max(0) as usize;+ let start_ly = (-tile_y0).max(0) as usize;+ let end_lx = (doc_w as i32 - tile_x0).min(TILE_SIZE_I32) as usize;+ let end_ly = (doc_h as i32 - tile_y0).min(TILE_SIZE_I32) as usize;++ if let TileStorage::SolidColor { rgba8, .. } = tile.storage {+ if rgba8[3] == 0 {+ continue;+ }+ min_x = min_x.min(tile_x0 + start_lx as i32);+ min_y = min_y.min(tile_y0 + start_ly as i32);+ max_x = max_x.max(tile_x0 + end_lx as i32 - 1);+ max_y = max_y.max(tile_y0 + end_ly as i32 - 1);+ continue;+ }++ let Ok(rgba) = tile.to_rgba8(scratch, false) else {+ continue;+ };+ for ly in start_ly..end_ly {+ let doc_y = tile_y0 + ly as i32;+ for lx in start_lx..end_lx {+ let off = (ly * TILE_SIZE + lx) * 4;+ let a = rgba[off + 3];+ if a == 0 {+ continue;+ }+ if is_background+ && rgba[off] == 255+ && rgba[off + 1] == 255+ && rgba[off + 2] == 255+ {+ continue;+ }+ let doc_x = tile_x0 + lx as i32;+ min_x = min_x.min(doc_x);+ min_y = min_y.min(doc_y);+ max_x = max_x.max(doc_x);+ max_y = max_y.max(doc_y);+ }+ }+ }++ if max_x < 0 || max_y < 0 {+ return None;+ }+ Some(RectI32::new(+ min_x,+ min_y,+ (max_x - min_x + 1) as u32,+ (max_y - min_y + 1) as u32,+ ))+ }++ /// Stamps a single pixel on a 1-bit tile (primarily for direct testing and binary ink ops).+ pub fn set_pixel_1bit_cow(+ &mut self,+ x: i32,+ y: i32,+ ink: bool,+ scratch: Option<&dyn ScratchBackend>,+ ) -> Result<(), String> {+ let tx = pixel_to_tile_coord(x, 0);+ let ty = pixel_to_tile_coord(y, 0);+ let coord = TileCoord::new(tx, ty);+ let lx = (x - tx * TILE_SIZE_I32) as usize;+ let ly = (y - ty * TILE_SIZE_I32) as usize;+ let entry = self+ .tiles+ .entry(coord)+ .or_insert_with(|| {+ Arc::new(TileData::from_raw(+ TileFormat::Monochrome1Bit,+ TileKind::Raster,+ vec![0u8; BYTES_1BIT],+ ))+ });+ let td = Arc::make_mut(entry);+ let raw = td.make_raw_mut(scratch)?;+ set_pixel_1bit(raw, lx, ly, ink);+ self.mark_lod_ancestors_dirty(coord);+ self.bump_version();+ Ok(())+ }++ /// Removes tiles that have become completely empty/transparent.+ pub fn prune_empty_tiles(&mut self, scratch: Option<&dyn ScratchBackend>) -> usize {+ let to_remove: Vec<TileCoord> = self+ .tiles+ .iter()+ .filter_map(|(&c, t)| if t.is_empty(scratch) { Some(c) } else { None })+ .collect();+ let count = to_remove.len();+ for c in to_remove {+ self.tiles.remove(&c);+ self.mark_lod_ancestors_dirty(c);+ }+ if count > 0 {+ self.bump_version();+ }+ count+ }++ /// Converts a single tile's RGBA16F GPU readback buffer into `self.format` and stores it+ /// (with dithering if `self.format == Color32Bit` and `dither == true`).+ pub fn commit_gpu_tile_rgba16f(+ &mut self,+ coord: TileCoord,+ rgba16f_bytes: &[u8],+ mono_threshold: u8,+ dither: bool,+ ) {+ debug_assert_eq!(rgba16f_bytes.len(), BYTES_16F);+ if is_raw_empty(TileFormat::Rgba16Float, rgba16f_bytes) {+ self.tiles.remove(&coord);+ } else {+ let stored = match self.format {+ TileFormat::Rgba16Float => rgba16f_bytes.to_vec(),+ TileFormat::Color32Bit => {+ let mut out = vec![0u8; BYTES_32BIT];+ if dither {+ rgba16f_to_rgba8_dithered(rgba16f_bytes, &mut out);+ } else {+ super::format::rgba16f_to_rgba8_lossless(rgba16f_bytes, &mut out);+ }+ out+ }+ other => convert_tile_bytes(+ rgba16f_bytes,+ TileFormat::Rgba16Float,+ other,+ mono_threshold,+ dither,+ ),+ };+ if is_raw_empty(self.format, &stored) {+ self.tiles.remove(&coord);+ } else {+ self.tiles.insert(+ coord,+ Arc::new(TileData::from_raw_auto_compact(+ self.format,+ TileKind::Raster,+ stored,+ )),+ );+ }+ }+ self.mark_lod_ancestors_dirty(coord);+ self.bump_version();+ }+}++#[allow(clippy::too_many_arguments)]+fn shift_and_crop_rgba8(+ src: &[u8],+ old_w: u32,+ old_h: u32,+ new_w: u32,+ new_h: u32,+ offset_x: i32,+ offset_y: i32,+ bg_fill: Option<[u8; 4]>,+) -> Vec<u8> {+ let mut dst = vec![0u8; (new_w as usize) * (new_h as usize) * 4];+ if let Some(bg) = bg_fill {+ if bg[3] > 0 {+ for px in dst.chunks_exact_mut(4) {+ px.copy_from_slice(&bg);+ }+ }+ }+ let sx0 = (-offset_x).max(0) as usize;+ let sy0 = (-offset_y).max(0) as usize;+ let sx1 = (new_w as i32 - offset_x).min(old_w as i32).max(0) as usize;+ let sy1 = (new_h as i32 - offset_y).min(old_h as i32).max(0) as usize;+ if sx0 >= sx1 || sy0 >= sy1 {+ return dst;+ }+ let copy_w = sx1 - sx0;+ for sy in sy0..sy1 {+ let dy = (sy as i32 + offset_y) as usize;+ let dx = (sx0 as i32 + offset_x) as usize;+ let src_off = (sy * old_w as usize + sx0) * 4;+ let dst_off = (dy * new_w as usize + dx) * 4;+ dst[dst_off..dst_off + copy_w * 4]+ .copy_from_slice(&src[src_off..src_off + copy_w * 4]);+ }+ dst+}++#[allow(clippy::too_many_arguments)]+fn shift_and_crop_u8(+ src: &[u8],+ old_w: u32,+ old_h: u32,+ new_w: u32,+ new_h: u32,+ offset_x: i32,+ offset_y: i32,+ default_v: u8,+) -> Vec<u8> {+ let mut dst = vec![default_v; (new_w as usize) * (new_h as usize)];+ let sx0 = (-offset_x).max(0) as usize;+ let sy0 = (-offset_y).max(0) as usize;+ let sx1 = (new_w as i32 - offset_x).min(old_w as i32).max(0) as usize;+ let sy1 = (new_h as i32 - offset_y).min(old_h as i32).max(0) as usize;+ if sx0 >= sx1 || sy0 >= sy1 {+ return dst;+ }+ let copy_w = sx1 - sx0;+ for sy in sy0..sy1 {+ let dy = (sy as i32 + offset_y) as usize;+ let dx = (sx0 as i32 + offset_x) as usize;+ let src_off = sy * old_w as usize + sx0;+ let dst_off = dy * new_w as usize + dx;+ dst[dst_off..dst_off + copy_w].copy_from_slice(&src[src_off..src_off + copy_w]);+ }+ dst+}++fn bilinear_scale_rgba8(src: &[u8], old_w: u32, old_h: u32, new_w: u32, new_h: u32) -> Vec<u8> {+ let mut dst = vec![0u8; (new_w as usize) * (new_h as usize) * 4];+ let ow = old_w as f32;+ let oh = old_h as f32;+ let nw = new_w as f32;+ let nh = new_h as f32;+ let max_x = (old_w - 1) as usize;+ let max_y = (old_h - 1) as usize;++ for dy in 0..new_h as usize {+ let sy = ((dy as f32 + 0.5) * (oh / nh) - 0.5).clamp(0.0, max_y as f32);+ let y0 = sy.floor() as usize;+ let y1 = (y0 + 1).min(max_y);+ let fy = sy - y0 as f32;+ for dx in 0..new_w as usize {+ let sx = ((dx as f32 + 0.5) * (ow / nw) - 0.5).clamp(0.0, max_x as f32);+ let x0 = sx.floor() as usize;+ let x1 = (x0 + 1).min(max_x);+ let fx = sx - x0 as f32;++ let i00 = (y0 * old_w as usize + x0) * 4;+ let i10 = (y0 * old_w as usize + x1) * 4;+ let i01 = (y1 * old_w as usize + x0) * 4;+ let i11 = (y1 * old_w as usize + x1) * 4;++ let w00 = (1.0 - fx) * (1.0 - fy);+ let w10 = fx * (1.0 - fy);+ let w01 = (1.0 - fx) * fy;+ let w11 = fx * fy;++ // Premultiplied alpha bilinear interpolation (prevents dark fringing)+ let a00 = src[i00 + 3] as f32 * w00;+ let a10 = src[i10 + 3] as f32 * w10;+ let a01 = src[i01 + 3] as f32 * w01;+ let a11 = src[i11 + 3] as f32 * w11;+ let sum_a = a00 + a10 + a01 + a11;++ let dst_off = (dy * new_w as usize + dx) * 4;+ if sum_a <= 0.5 {+ dst[dst_off..dst_off + 4].fill(0);+ } else {+ for c in 0..3 {+ let premul = src[i00 + c] as f32 * a00+ + src[i10 + c] as f32 * a10+ + src[i01 + c] as f32 * a01+ + src[i11 + c] as f32 * a11;+ dst[dst_off + c] = (premul / sum_a + 0.5).clamp(0.0, 255.0) as u8;+ }+ dst[dst_off + 3] = (sum_a + 0.5).clamp(0.0, 255.0) as u8;+ }+ }+ }+ dst+}++fn bilinear_scale_u8(src: &[u8], old_w: u32, old_h: u32, new_w: u32, new_h: u32) -> Vec<u8> {+ let mut dst = vec![0u8; (new_w as usize) * (new_h as usize)];+ let ow = old_w as f32;+ let oh = old_h as f32;+ let nw = new_w as f32;+ let nh = new_h as f32;+ let max_x = (old_w - 1) as usize;+ let max_y = (old_h - 1) as usize;++ for dy in 0..new_h as usize {+ let sy = ((dy as f32 + 0.5) * (oh / nh) - 0.5).clamp(0.0, max_y as f32);+ let y0 = sy.floor() as usize;+ let y1 = (y0 + 1).min(max_y);+ let fy = sy - y0 as f32;+ for dx in 0..new_w as usize {+ let sx = ((dx as f32 + 0.5) * (ow / nw) - 0.5).clamp(0.0, max_x as f32);+ let x0 = sx.floor() as usize;+ let x1 = (x0 + 1).min(max_x);+ let fx = sx - x0 as f32;++ let v00 = src[y0 * old_w as usize + x0] as f32;+ let v10 = src[y0 * old_w as usize + x1] as f32;+ let v01 = src[y1 * old_w as usize + x0] as f32;+ let v11 = src[y1 * old_w as usize + x1] as f32;++ let v = (v00 * (1.0 - fx) + v10 * fx) * (1.0 - fy)+ + (v01 * (1.0 - fx) + v11 * fx) * fy;+ dst[dy * new_w as usize + dx] = (v + 0.5).clamp(0.0, 255.0) as u8;+ }+ }+ dst+}diff --git a/crates/ink-engine/src/tiles/mod.rs b/crates/ink-engine/src/tiles/mod.rsnew file mode 100644index 0000000..96e0330--- /dev/null+++ b/crates/ink-engine/src/tiles/mod.rs@@ -0,0 +1,163 @@+//! Sparse virtual tile store (`256×256` tiles) with Copy-on-Write (`Arc<TileData>`),+//! solid-color zero-allocation fast tiles, 1-bit / 8-bit / 32-bit / 16-bit-float GPU working+//! formats, and unified per-layer raster + non-destructive 8-bit mask tiling.++pub mod format;+pub mod grid;+pub mod tile_data;++use serde::{Deserialize, Serialize};+use std::sync::atomic::{AtomicU64, Ordering};++pub const TILE_SIZE: usize = 256;+pub const TILE_SIZE_I32: i32 = 256;+pub const TILE_PIXELS: usize = TILE_SIZE * TILE_SIZE; // 65,536+pub const BYTES_1BIT: usize = TILE_PIXELS / 8; // 8,192 bytes (8 KB)+pub const BYTES_8BIT: usize = TILE_PIXELS; // 65,536 bytes (64 KB)+pub const BYTES_32BIT: usize = TILE_PIXELS * 4; // 262,144 bytes (256 KB)+pub const BYTES_16F: usize = TILE_PIXELS * 8; // 524,288 bytes (512 KB, 4×f16)++/// Supported sparse tile storage formats.+///+/// - `Monochrome1Bit`: 8 KB per tile (manga line art, 32× smaller than RGBA8)+/// - `Grayscale8Bit`: 64 KB per tile (grayscale ink / non-destructive 8-bit layer masks)+/// - `Color32Bit`: 256 KB per tile (standard sRGB RGBA8)+/// - `Rgba16Float`: 512 KB per tile (internal 16-bit half-float GPU working format, zero 8-bit banding)+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]+pub enum TileFormat {+ #[serde(rename = "monochrome-1bit")]+ Monochrome1Bit,+ #[serde(rename = "grayscale-8bit")]+ Grayscale8Bit,+ #[default]+ #[serde(rename = "color-32bit")]+ Color32Bit,+ #[serde(rename = "rgba-16f")]+ Rgba16Float,+}++impl TileFormat {+ #[inline]+ pub const fn byte_size(self) -> usize {+ match self {+ Self::Monochrome1Bit => BYTES_1BIT,+ Self::Grayscale8Bit => BYTES_8BIT,+ Self::Color32Bit => BYTES_32BIT,+ Self::Rgba16Float => BYTES_16F,+ }+ }++ /// Maps to the `.ink` v2 archive / `INKG` format tag byte (`0=1bit, 1=8bit, 2=32bit, 3=16f`).+ #[inline]+ pub const fn to_ink_byte(self) -> u8 {+ match self {+ Self::Monochrome1Bit => 0,+ Self::Grayscale8Bit => 1,+ Self::Color32Bit => 2,+ Self::Rgba16Float => 3,+ }+ }++ #[inline]+ pub const fn from_ink_byte(b: u8) -> Option<Self> {+ match b {+ 0 => Some(Self::Monochrome1Bit),+ 1 => Some(Self::Grayscale8Bit),+ 2 => Some(Self::Color32Bit),+ 3 => Some(Self::Rgba16Float),+ _ => None,+ }+ }++ /// Returns the persistent storage format used for `.ink` serialization boundaries+ /// (16-bit working tiles quantize with dithering to `Color32Bit` for v2 compatibility).+ #[inline]+ pub const fn io_storage_format(self) -> Self {+ match self {+ Self::Rgba16Float => Self::Color32Bit,+ other => other,+ }+ }+}++/// Distinguishes a layer's primary raster plane from its non-destructive 8-bit mask plane.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum TileKind {+ Raster,+ Mask,+}++/// Signed integer 2D tile coordinate in document tile space.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]+pub struct TileCoord {+ pub tx: i32,+ pub ty: i32,+}++impl TileCoord {+ #[inline]+ pub const fn new(tx: i32, ty: i32) -> Self {+ Self { tx, ty }+ }++ /// Top-left pixel coordinate of this tile at `lod` (`0` = 256 px, `1` = 512 px, ...).+ #[inline]+ pub const fn doc_origin(self, lod: u8) -> (i32, i32) {+ let span = TILE_SIZE_I32 << lod;+ (self.tx * span, self.ty * span)+ }++ /// Returns the parent tile coordinate at `lod + 1` (using arithmetic right-shift / Euclidean floor).+ #[inline]+ pub const fn parent(self) -> Self {+ Self {+ tx: self.tx.div_euclid(2),+ ty: self.ty.div_euclid(2),+ }+ }+}++/// Maps a document pixel coordinate to its enclosing tile index at `lod` (`0..=3`).+#[inline]+pub const fn pixel_to_tile_coord(pixel: i32, lod: u8) -> i32 {+ let span = TILE_SIZE_I32 << lod;+ pixel.div_euclid(span)+}++/// Uniquely identifies any tile across multi-tab documents, layers, raster/mask planes, and LODs.+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+pub struct TileKey {+ pub doc_id: String,+ pub layer_id: String,+ pub kind: TileKind,+ pub lod: u8,+ pub coord: TileCoord,+}++static NEXT_TILE_VERSION: AtomicU64 = AtomicU64::new(1);+static NEXT_ACCESS_SEQ: AtomicU64 = AtomicU64::new(1);++#[inline]+pub fn allocate_tile_version() -> u64 {+ NEXT_TILE_VERSION.fetch_add(1, Ordering::Relaxed) + 1+}++#[inline]+pub fn reserve_tile_version(version: u64) {+ let _ = NEXT_TILE_VERSION.fetch_max(version, Ordering::Relaxed);+}++#[inline]+pub fn next_access_seq() -> u64 {+ NEXT_ACCESS_SEQ.fetch_add(1, Ordering::Relaxed) + 1+}++pub use format::{+ convert_tile_bytes, detect_solid_color, expand_solid_to_raw, get_pixel_1bit, is_raw_empty,+ pack_rgba8_to_1bit, pack_rgba8_to_8bit, pack_rgba8_to_mask8, parse_hex_rgba8,+ rgba16f_to_rgba8_dithered, rgba16f_to_rgba8_lossless, rgba8_pixel_to_f16, rgba8_to_rgba16f,+ set_pixel_1bit, unpack_1bit_to_rgba8, unpack_8bit_to_rgba8, unpack_mask8_to_rgba8,+};+pub use grid::{CowTileDelta, RectI32, SparseLayerGrid};+pub use tile_data::{TileData, TileStorage};diff --git a/crates/ink-engine/src/tiles/tile_data.rs b/crates/ink-engine/src/tiles/tile_data.rsnew file mode 100644index 0000000..44423e7--- /dev/null+++ b/crates/ink-engine/src/tiles/tile_data.rs@@ -0,0 +1,414 @@+//! Copy-on-Write (`Arc<TileData>`) tile storage backing L1/L2/L3 tiered memory.+//!+//! - `SolidColor`: 0-byte pixel buffer for uniform tiles (e.g. paper background, flat fills).+//! - `Raw`: uncompressed CPU-resident pixels in the tile's native [`TileFormat`].+//! - `CompressedLz4`: L2 cold tile compressed in CPU RAM via `lz4_flex`.+//! - `PagedToDisk`: L3 tile offloaded to in-process scratch disk (0 bytes of pixel payload in RAM).++use super::format::{+ convert_tile_bytes, detect_solid_color, expand_solid_to_raw, is_raw_empty, rgba8_pixel_to_f16,+ unpack_mask8_to_rgba8,+};+use super::{allocate_tile_version, next_access_seq, TileCoord, TileFormat, TileKind, BYTES_16F, BYTES_32BIT};+use crate::memory::ScratchBackend;++/// Storage backing for a single `256×256` tile.+#[derive(Debug, Clone, PartialEq)]+pub enum TileStorage {+ /// Zero-allocation fast tile when all 65,536 pixels share one exact color/value.+ SolidColor {+ rgba8: [u8; 4],+ rgba16f: [u16; 4],+ },+ /// Uncompressed CPU-resident tile buffer in the owning [`TileData::format`].+ Raw(Vec<u8>),+ /// L2 cold tile compressed in CPU RAM via `lz4_flex::block::compress`.+ CompressedLz4 {+ compressed: Vec<u8>,+ uncompressed_len: u32,+ },+ /// L3 tile paged out to the in-process scratch disk backend (zero pixel RAM).+ PagedToDisk {+ session_id: String,+ layer_key: String,+ tx: i32,+ ty: i32,+ uncompressed_len: u32,+ },+}++/// Immutable-by-default tile unit wrapped in `Arc<TileData>` for O(1) Copy-on-Write+/// layer cloning and undo/redo snapshots.+#[derive(Debug, Clone, PartialEq)]+pub struct TileData {+ pub format: TileFormat,+ pub kind: TileKind,+ pub storage: TileStorage,+ pub version: u64,+ pub remote_epoch: u64,+ pub last_access_seq: u64,+}++impl TileData {+ /// Creates a zero-allocation uniform solid tile.+ pub fn new_solid(format: TileFormat, kind: TileKind, rgba8: [u8; 4]) -> Self {+ Self {+ format,+ kind,+ storage: TileStorage::SolidColor {+ rgba8,+ rgba16f: rgba8_pixel_to_f16(rgba8),+ },+ version: allocate_tile_version(),+ remote_epoch: 0,+ last_access_seq: next_access_seq(),+ }+ }++ /// Creates a solid 8-bit mask tile without allocating 64 KB.+ pub fn new_solid_mask(alpha: u8) -> Self {+ let rgba8 = [alpha, alpha, alpha, 255];+ Self {+ format: TileFormat::Grayscale8Bit,+ kind: TileKind::Mask,+ storage: TileStorage::SolidColor {+ rgba8,+ rgba16f: rgba8_pixel_to_f16(rgba8),+ },+ version: allocate_tile_version(),+ remote_epoch: 0,+ last_access_seq: next_access_seq(),+ }+ }++ /// Creates a tile from raw uncompressed bytes, automatically compacting uniform tiles into+ /// [`TileStorage::SolidColor`] so flat fills consume 0 bytes of pixel buffer.+ pub fn from_raw_auto_compact(format: TileFormat, kind: TileKind, raw: Vec<u8>) -> Self {+ debug_assert_eq!(raw.len(), format.byte_size());+ if kind == TileKind::Mask {+ if let Some(&first) = raw.first() {+ if raw.iter().all(|&b| b == first) {+ return Self::new_solid_mask(first);+ }+ }+ } else if let Some((rgba8, rgba16f)) = detect_solid_color(format, &raw) {+ return Self {+ format,+ kind,+ storage: TileStorage::SolidColor { rgba8, rgba16f },+ version: allocate_tile_version(),+ remote_epoch: 0,+ last_access_seq: next_access_seq(),+ };+ }+ Self {+ format,+ kind,+ storage: TileStorage::Raw(raw),+ version: allocate_tile_version(),+ remote_epoch: 0,+ last_access_seq: next_access_seq(),+ }+ }++ /// Creates a tile from raw uncompressed bytes without solid compaction.+ pub fn from_raw(format: TileFormat, kind: TileKind, raw: Vec<u8>) -> Self {+ debug_assert_eq!(raw.len(), format.byte_size());+ Self {+ format,+ kind,+ storage: TileStorage::Raw(raw),+ version: allocate_tile_version(),+ remote_epoch: 0,+ last_access_seq: next_access_seq(),+ }+ }++ /// Returns true if stored as a zero-allocation uniform `SolidColor` tile.+ #[inline]+ pub fn is_solid(&self) -> bool {+ matches!(self.storage, TileStorage::SolidColor { .. })+ }++ /// Returns the solid RGBA8 color if this tile is stored as `SolidColor`.+ #[inline]+ pub fn solid_rgba8(&self) -> Option<[u8; 4]> {+ match self.storage {+ TileStorage::SolidColor { rgba8, .. } => Some(rgba8),+ _ => None,+ }+ }++ /// Returns true if stored in L2 LZ4-compressed RAM.+ #[inline]+ pub fn is_compressed_lz4(&self) -> bool {+ matches!(self.storage, TileStorage::CompressedLz4 { .. })+ }++ /// Returns true if paged out to L3 scratch disk.+ #[inline]+ pub fn is_paged_to_disk(&self) -> bool {+ matches!(self.storage, TileStorage::PagedToDisk { .. })+ }++ /// Heap pixel bytes currently held in CPU RAM by this tile.+ #[inline]+ pub fn ram_bytes(&self) -> usize {+ match &self.storage {+ TileStorage::SolidColor { .. } => 0,+ TileStorage::Raw(v) => v.len(),+ TileStorage::CompressedLz4 { compressed, .. } => compressed.len(),+ TileStorage::PagedToDisk { .. } => 0,+ }+ }++ /// Logical uncompressed byte size if materialized.+ #[inline]+ pub fn logical_bytes(&self) -> usize {+ self.format.byte_size()+ }++ /// Returns true if this tile represents completely transparent / empty pixels.+ pub fn is_empty(&self, scratch: Option<&dyn ScratchBackend>) -> bool {+ match &self.storage {+ TileStorage::SolidColor { rgba8, .. } => match self.kind {+ TileKind::Mask => rgba8[0] == 0,+ TileKind::Raster => rgba8[3] == 0,+ },+ TileStorage::Raw(raw) => {+ if self.kind == TileKind::Mask {+ raw.iter().all(|&b| b == 0)+ } else {+ is_raw_empty(self.format, raw)+ }+ }+ TileStorage::CompressedLz4 { .. } | TileStorage::PagedToDisk { .. } => {+ match self.materialize_raw(scratch) {+ Ok(raw) => {+ if self.kind == TileKind::Mask {+ raw.iter().all(|&b| b == 0)+ } else {+ is_raw_empty(self.format, &raw)+ }+ }+ Err(_) => false,+ }+ }+ }+ }++ /// Materializes a standalone uncompressed `Vec<u8>` in this tile's native [`TileFormat`],+ /// promoting transparently from `SolidColor`, L2 `CompressedLz4`, or L3 `PagedToDisk`.+ pub fn materialize_raw(&self, scratch: Option<&dyn ScratchBackend>) -> Result<Vec<u8>, String> {+ match &self.storage {+ TileStorage::SolidColor { rgba8, rgba16f } => {+ if self.kind == TileKind::Mask {+ Ok(vec![rgba8[0]; self.format.byte_size()])+ } else {+ Ok(expand_solid_to_raw(self.format, *rgba8, *rgba16f))+ }+ }+ TileStorage::Raw(buf) => Ok(buf.clone()),+ TileStorage::CompressedLz4 {+ compressed,+ uncompressed_len,+ } => lz4_flex::block::decompress(compressed, *uncompressed_len as usize)+ .map_err(|e| format!("Failed to LZ4-decompress tile: {e}")),+ TileStorage::PagedToDisk {+ session_id,+ layer_key,+ tx,+ ty,+ uncompressed_len,+ } => {+ let backend = scratch.ok_or_else(|| {+ format!(+ "Tile ({layer_key} [{tx},{ty}]) is paged to scratch disk but no ScratchBackend was provided"+ )+ })?;+ let raw = backend.read_tile(session_id, layer_key, *tx, *ty)?;+ if raw.len() != *uncompressed_len as usize {+ return Err(format!(+ "Scratch disk tile length mismatch: expected {}, got {}",+ uncompressed_len,+ raw.len()+ ));+ }+ Ok(raw)+ }+ }+ }++ /// Promotes this tile in-place into [`TileStorage::Raw`] and returns a mutable slice.+ /// Intended to be called after `Arc::make_mut` during Copy-on-Write edits.+ pub fn make_raw_mut(&mut self, scratch: Option<&dyn ScratchBackend>) -> Result<&mut Vec<u8>, String> {+ if !matches!(self.storage, TileStorage::Raw(_)) {+ let raw = self.materialize_raw(scratch)?;+ self.storage = TileStorage::Raw(raw);+ }+ self.version = allocate_tile_version();+ self.last_access_seq = next_access_seq();+ match &mut self.storage {+ TileStorage::Raw(v) => Ok(v),+ _ => unreachable!(),+ }+ }++ /// Attempts to compact a `Raw` tile into `SolidColor` if all pixels are uniform.+ pub fn try_compact_solid(&mut self) -> bool {+ let TileStorage::Raw(raw) = &self.storage else {+ return self.is_solid();+ };+ if self.kind == TileKind::Mask {+ if let Some(&first) = raw.first() {+ if raw.iter().all(|&b| b == first) {+ let rgba8 = [first, first, first, 255];+ self.storage = TileStorage::SolidColor {+ rgba8,+ rgba16f: rgba8_pixel_to_f16(rgba8),+ };+ return true;+ }+ }+ return false;+ }+ if let Some((rgba8, rgba16f)) = detect_solid_color(self.format, raw) {+ self.storage = TileStorage::SolidColor { rgba8, rgba16f };+ return true;+ }+ false+ }++ /// Demotes a `Raw` tile in-place to L2 `CompressedLz4` RAM (or `SolidColor` if uniform).+ /// Returns bytes freed in CPU RAM.+ pub fn demote_to_lz4(&mut self) -> usize {+ if self.try_compact_solid() {+ return self.format.byte_size();+ }+ let TileStorage::Raw(raw) = &self.storage else {+ return 0;+ };+ let old_len = raw.len();+ let compressed = lz4_flex::block::compress(raw);+ if compressed.len() < old_len {+ let freed = old_len - compressed.len();+ self.storage = TileStorage::CompressedLz4 {+ compressed,+ uncompressed_len: old_len as u32,+ };+ freed+ } else {+ 0+ }+ }++ /// Demotes a `Raw` or `CompressedLz4` tile to L3 `PagedToDisk` via `scratch`.+ /// Returns bytes freed in CPU RAM.+ pub fn demote_to_disk(+ &mut self,+ session_id: &str,+ layer_key: &str,+ coord: TileCoord,+ scratch: &dyn ScratchBackend,+ ) -> Result<usize, String> {+ if self.is_solid() || self.is_paged_to_disk() {+ return Ok(0);+ }+ let old_ram = self.ram_bytes();+ let raw = self.materialize_raw(Some(scratch))?;+ let uncompressed_len = raw.len() as u32;+ scratch.write_tiles(+ session_id,+ vec![crate::memory::ScratchTileWrite {+ layer_key: layer_key.to_string(),+ tx: coord.tx,+ ty: coord.ty,+ data: raw,+ }],+ )?;+ self.storage = TileStorage::PagedToDisk {+ session_id: session_id.to_string(),+ layer_key: layer_key.to_string(),+ tx: coord.tx,+ ty: coord.ty,+ uncompressed_len,+ };+ Ok(old_ram)+ }++ /// Materializes this tile as 262,144-byte RGBA8 (dithered if converting from `Rgba16Float`+ /// when `dither = true`).+ pub fn to_rgba8(+ &self,+ scratch: Option<&dyn ScratchBackend>,+ dither: bool,+ ) -> Result<Vec<u8>, String> {+ if let TileStorage::SolidColor { rgba8, .. } = self.storage {+ return Ok(expand_solid_to_raw(+ TileFormat::Color32Bit,+ rgba8,+ [0, 0, 0, 0],+ ));+ }+ let raw = self.materialize_raw(scratch)?;+ if self.kind == TileKind::Mask {+ let mut out = vec![0u8; BYTES_32BIT];+ unpack_mask8_to_rgba8(&raw, &mut out);+ return Ok(out);+ }+ Ok(convert_tile_bytes(+ &raw,+ self.format,+ TileFormat::Color32Bit,+ 128,+ dither,+ ))+ }++ /// Materializes this tile as 524,288-byte `Rgba16Float` for lossless GPU atlas upload.+ pub fn to_rgba16f(&self, scratch: Option<&dyn ScratchBackend>) -> Result<Vec<u8>, String> {+ if let TileStorage::SolidColor { rgba16f, .. } = self.storage {+ return Ok(expand_solid_to_raw(+ TileFormat::Rgba16Float,+ [0, 0, 0, 0],+ rgba16f,+ ));+ }+ let raw = self.materialize_raw(scratch)?;+ if self.kind == TileKind::Mask {+ let mut rgba8 = vec![0u8; BYTES_32BIT];+ unpack_mask8_to_rgba8(&raw, &mut rgba8);+ let mut out = vec![0u8; BYTES_16F];+ super::format::rgba8_to_rgba16f(&rgba8, &mut out);+ return Ok(out);+ }+ Ok(convert_tile_bytes(+ &raw,+ self.format,+ TileFormat::Rgba16Float,+ 128,+ false,+ ))+ }++ /// Materializes this tile into the requested [`TileFormat`] (used at `.ink` save boundaries).+ pub fn to_format_raw(+ &self,+ target: TileFormat,+ mono_threshold: u8,+ dither: bool,+ scratch: Option<&dyn ScratchBackend>,+ ) -> Result<Vec<u8>, String> {+ let raw = self.materialize_raw(scratch)?;+ if self.format == target {+ return Ok(raw);+ }+ Ok(convert_tile_bytes(+ &raw,+ self.format,+ target,+ mono_threshold,+ dither,+ ))+ }+}diff --git a/crates/ink-engine/src/types.rs b/crates/ink-engine/src/types.rsnew file mode 100644index 0000000..b70e5e3--- /dev/null+++ b/crates/ink-engine/src/types.rs@@ -0,0 +1,513 @@+//! Strongly-typed engine commands, events, input samples, and rendering configs.+//! Completely decoupled from Tauri, wry, or WebView2.++use serde::{Deserialize, Serialize};+use std::ffi::c_void;+use std::sync::Arc;++/// Physical client-pixel bounds of the canvas viewport cutout inside the host window.+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ViewportRect {+ /// Left offset in physical pixels relative to the host window's client origin.+ pub x_px: i32,+ /// Top offset in physical pixels relative to the host window's client origin.+ pub y_px: i32,+ /// Physical pixel width of the swapchain surface.+ pub width_px: u32,+ /// Physical pixel height of the swapchain surface.+ pub height_px: u32,+ /// Effective device pixel ratio (`physical_px / viewport_css_px`), including WebView zoom.+ pub dpr: f32,+}++impl Default for ViewportRect {+ fn default() -> Self {+ Self {+ x_px: 0,+ y_px: 0,+ width_px: 0,+ height_px: 0,+ dpr: 1.0,+ }+ }+}++impl ViewportRect {+ #[inline]+ pub fn safe_dpr(&self) -> f32 {+ if self.dpr.is_finite() && self.dpr > 0.05 {+ self.dpr+ } else {+ 1.0+ }+ }++ #[inline]+ pub fn css_width(&self) -> f32 {+ self.width_px as f32 / self.safe_dpr()+ }++ #[inline]+ pub fn css_height(&self) -> f32 {+ self.height_px as f32 / self.safe_dpr()+ }++ #[inline]+ pub fn contains_phys(&self, phys_x: f32, phys_y: f32) -> bool {+ if self.width_px == 0 || self.height_px == 0 {+ return false;+ }+ let x0 = self.x_px as f32;+ let y0 = self.y_px as f32;+ let x1 = x0 + self.width_px as f32;+ let y1 = y0 + self.height_px as f32;+ phys_x >= x0 && phys_x < x1 && phys_y >= y0 && phys_y < y1+ }++ /// Converts window-client physical pixels to viewport-local CSS pixels.+ #[inline]+ pub fn phys_to_local_css(&self, phys_x: f32, phys_y: f32) -> (f32, f32) {+ let dpr = self.safe_dpr();+ (+ (phys_x - self.x_px as f32) / dpr,+ (phys_y - self.y_px as f32) / dpr,+ )+ }++ /// Converts window-client physical pixels to swapchain-local physical pixels.+ #[inline]+ pub fn phys_to_local_phys(&self, phys_x: f32, phys_y: f32) -> (f32, f32) {+ (phys_x - self.x_px as f32, phys_y - self.y_px as f32)+ }+}++/// An occluded UI rectangle in physical window client pixels (modals, popovers,+/// context menus, FloatingBrushPill, floating dock panels, etc.).+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct UiRect {+ pub x: f32,+ pub y: f32,+ pub width: f32,+ pub height: f32,+}++impl UiRect {+ #[inline]+ pub fn contains(&self, px: f32, py: f32) -> bool {+ self.width > 0.0+ && self.height > 0.0+ && px >= self.x+ && px <= self.x + self.width+ && py >= self.y+ && py <= self.y + self.height+ }+}++/// 2D affine canvas camera transform matching `CameraTransformState` and+/// `formatArtboardTransform` in `src/components/canvasArea/types.ts` pixel-for-pixel.+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct CameraState {+ pub pan_x: f32,+ pub pan_y: f32,+ pub zoom: f32,+ pub rotation: f32,+ pub flip_x: bool,+ pub flip_y: bool,+}++impl Default for CameraState {+ fn default() -> Self {+ Self {+ pan_x: 0.0,+ pan_y: 0.0,+ zoom: 1.0,+ rotation: 0.0,+ flip_x: false,+ flip_y: false,+ }+ }+}++/// Active tool classification used to determine whether native GPU brush capture fires.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum NativeToolKind {+ #[default]+ Brush,+ Eraser,+ Other,+}++impl NativeToolKind {+ #[inline]+ pub fn is_native_stroke_tool(self) -> bool {+ matches!(self, Self::Brush | Self::Eraser)+ }+}++/// GPU brush cursor visual configuration.+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct CursorConfig {+ /// Active brush diameter in document pixels.+ pub size: f32,+ /// Brush tip thickness ratio (0.05..=1.0).+ pub thickness_ratio: f32,+ /// Whether thickness compresses vertically instead of horizontally.+ pub thickness_vertical: bool,+ /// Brush tip angle in degrees (canvas-space).+ pub tip_angle_deg: f32,+ /// Square brush outline instead of circular/elliptical.+ pub is_square: bool,+ /// Whether the native GPU brush cursor ring should be shown when hovering canvas.+ pub visible: bool,+}++impl Default for CursorConfig {+ fn default() -> Self {+ Self {+ size: 16.0,+ thickness_ratio: 1.0,+ thickness_vertical: false,+ tip_angle_deg: 0.0,+ is_square: false,+ visible: true,+ }+ }+}++/// Minimal Phase 1 PoC GPU dab brush parameters.+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct BrushParams {+ /// Base brush diameter in document pixels.+ pub size: f32,+ /// Brush opacity (0.01..=1.0).+ pub opacity: f32,+ /// Edge hardness (0.0..=1.0, where 1.0 is crisp and 0.0 is soft airbrush falloff).+ pub hardness: f32,+ /// Dab spacing fraction of diameter (0.03..=1.0).+ pub spacing: f32,+ /// Minimum size ratio under zero pressure (0.0..=1.0).+ pub min_size_ratio: f32,+ /// Whether pressure modulates brush diameter.+ pub use_pressure_size: bool,+ /// Whether pressure modulates dab opacity.+ pub use_pressure_opacity: bool,+ /// Primary sRGB color `[r, g, b, a]` in `0.0..=1.0`.+ pub color: [f32; 4],+ /// True for destination-out erasing, false for normal premultiplied painting.+ pub is_eraser: bool,+}++impl Default for BrushParams {+ fn default() -> Self {+ Self {+ size: 16.0,+ opacity: 1.0,+ hardness: 0.9,+ spacing: 0.10,+ min_size_ratio: 0.15,+ use_pressure_size: true,+ use_pressure_opacity: false,+ color: [0.08, 0.08, 0.10, 1.0],+ is_eraser: false,+ }+ }+}++/// Mouse wheel action configured by user preferences.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum WheelNavMode {+ #[default]+ Zoom,+ Scroll,+ BrushSize,+}++/// Native modifier & tool gating flags mirrored from UI/OS state.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct InteractionPolicy {+ pub active_tool: NativeToolKind,+ pub native_stroke_enabled: bool,+ pub wheel_mode: WheelNavMode,+ pub is_webtoon_mode: bool,+ pub text_input_focused: bool,+ pub workspace_interacting: bool,+ pub modal_open: bool,+}++impl Default for InteractionPolicy {+ fn default() -> Self {+ Self {+ active_tool: NativeToolKind::Brush,+ native_stroke_enabled: true,+ wheel_mode: WheelNavMode::Zoom,+ is_webtoon_mode: false,+ text_input_focused: false,+ workspace_interacting: false,+ modal_open: false,+ }+ }+}++/// High-frequency tablet/pen sample pushed directly into the lock-free `rtrb` ring buffer+/// from `src-tauri/src/tablet_input.rs` (zero JSON, zero IPC).+#[derive(Debug, Clone, Copy)]+pub struct NativeInputSample {+ /// Sub-pixel physical X coordinate relative to the top-level window client origin.+ pub phys_x: f32,+ /// Sub-pixel physical Y coordinate relative to the top-level window client origin.+ pub phys_y: f32,+ /// Normalized pen pressure in `0.0..=1.0`.+ pub pressure: f32,+ /// Pen tilt X in degrees (`-90..=90`).+ pub tilt_x: f32,+ /// Pen tilt Y in degrees (`-90..=90`).+ pub tilt_y: f32,+ /// Barrel twist in degrees (`0..=360`).+ pub twist: f32,+ /// QPC monotonic timestamp in milliseconds (same domain as `clock::now_ms()`).+ pub timestamp_ms: f64,+ /// Button bitmask: bit 0=tip, 1=barrel1, 2=barrel2, 3=eraser/inverted.+ pub buttons: u16,+ /// Phase: 0=hover, 1=down, 2=move/drag, 3=up, 4=leave.+ pub phase: u8,+ /// Backend: 1=wintab, 2=windows-ink, 3=mouse.+ pub backend: u8,+}++/// Active native camera navigation gesture kind.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum NativeNavGesture {+ Pan,+ Rotate,+ ZoomDrag,+}++/// High-frequency native mouse/wheel navigation and hover events pushed into a lock-free+/// SPSC ring buffer directly from the Win32 subclass proc.+#[derive(Debug, Clone, Copy)]+pub enum NativeNavEvent {+ Hover {+ phys_x: f32,+ phys_y: f32,+ timestamp_ms: f64,+ },+ HoverLeave,+ GestureStart {+ gesture: NativeNavGesture,+ phys_x: f32,+ phys_y: f32,+ timestamp_ms: f64,+ },+ GestureMove {+ phys_x: f32,+ phys_y: f32,+ snap_15_deg: bool,+ timestamp_ms: f64,+ },+ GestureEnd {+ timestamp_ms: f64,+ },+ Wheel {+ phys_x: f32,+ phys_y: f32,+ delta_x: f32,+ delta_y: f32,+ ctrl_held: bool,+ shift_held: bool,+ timestamp_ms: f64,+ },+ MouseDraw {+ phys_x: f32,+ phys_y: f32,+ phase: u8, // 1=down, 2=move, 3=up+ timestamp_ms: f64,+ },+}++/// Typed control commands sent from the host UI/window layer into `ink-engine`.+#[derive(Debug, Clone)]+pub enum EngineCommand {+ /// Updates the physical pixel cutout rect and effective DPI of the canvas viewport.+ SetViewport(ViewportRect),+ /// Replaces the list of occluded UI rects in physical client pixels.+ SetOccludedRects(Vec<UiRect>),+ /// Updates document pixel dimensions and allocates/clears the GPU canvas surface if changed.+ SetDocumentSize {+ width: u32,+ height: u32,+ show_checkerboard: bool,+ },+ /// Sets whether the artboard checkerboard transparency grid is shown (vs solid white paper).+ SetShowCheckerboard(bool),+ /// Sets the canvas matte background sRGB color `[r, g, b, a]` synced from the active UI theme.+ SetMatteColor([f32; 4]),+ /// Updates the camera transform from programmatic UI actions (Navigator, buttons, resize, reset).+ SetCamera(CameraState),+ /// Updates the native GPU brush cursor configuration.+ SetCursorConfig(CursorConfig),+ /// Updates the Phase 1 PoC GPU dab brush parameters.+ SetBrushParams(BrushParams),+ /// Updates tool & interaction policy flags.+ SetInteractionPolicy(InteractionPolicy),+ /// Shows or hides rendering (e.g. hidden on Welcome Home screen or minimized window).+ SetVisible(bool),+ /// Clears the active layer or GPU canvas texture to transparent.+ ClearCanvas,+ /// Synchronizes the active Rust `Document` (dirty tiles, GPU mipmaps, and composited texture)+ /// into the DX12 `GpuRenderer`.+ SyncActiveDocument,+ /// Updates the L1 GPU VRAM tile atlas budget in bytes.+ SetVramBudget(u64),+ /// Flushes all resident tiles from the L1 GPU VRAM tile atlas pool.+ FlushGpuPool,+ /// Notifies the engine that the host window was resized, DPI changed, or restored.+ NotifySurfaceInvalidated,+ /// Requests a graceful shutdown of the engine thread.+ Shutdown,+}++/// Live GPU and latency telemetry emitted periodically to the host UI.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct EngineDiagnostics {+ pub ready: bool,+ pub adapter_name: String,+ pub backend: String,+ pub present_mode: String,+ pub fps: f32,+ pub frame_time_ms: f32,+ pub input_to_present_ms: f32,+ pub swapchain_width: u32,+ pub swapchain_height: u32,+ pub doc_width: u32,+ pub doc_height: u32,+ pub active_stroke_dabs: u64,+ pub total_frames_rendered: u64,+ pub device_lost_recoveries: u32,+ pub max_frame_latency: u32,+ pub composition_mode: String,+ #[serde(default)]+ pub gpu_vram_used_bytes: u64,+ #[serde(default)]+ pub gpu_vram_budget_bytes: u64,+ #[serde(default)]+ pub gpu_tiles_resident: u32,+ #[serde(default)]+ pub gpu_tiles_capacity: u32,+}++impl Default for EngineDiagnostics {+ fn default() -> Self {+ Self {+ ready: false,+ adapter_name: "Initializing...".to_string(),+ backend: "DX12".to_string(),+ present_mode: "Fifo".to_string(),+ fps: 0.0,+ frame_time_ms: 0.0,+ input_to_present_ms: 0.0,+ swapchain_width: 0,+ swapchain_height: 0,+ doc_width: 1920,+ doc_height: 1080,+ active_stroke_dabs: 0,+ total_frames_rendered: 0,+ device_lost_recoveries: 0,+ max_frame_latency: 1,+ composition_mode: "DirectComposition".to_string(),+ gpu_vram_used_bytes: 0,+ gpu_vram_budget_bytes: 0,+ gpu_tiles_resident: 0,+ gpu_tiles_capacity: 0,+ }+ }+}++/// Compact 64x64 PNG data URL update for a single layer and/or its non-destructive mask.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ThumbnailUpdate {+ pub layer_id: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub thumbnail_url: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub mask_thumbnail_url: Option<String>,+}++/// Lightweight events emitted from `ink-engine` back to the host (throttled outside hot strokes).+#[derive(Debug, Clone)]+pub enum EngineEvent {+ /// Emitted when native Rust pan/zoom/rotate updates the camera.+ /// `commit` is true when a drag/wheel gesture completes so React can commit UI state.+ CameraChanged {+ camera: CameraState,+ commit: bool,+ },+ /// Periodic (~4 Hz) GPU & latency diagnostics snapshot.+ Diagnostics(EngineDiagnostics),+ /// Throttled (~30 Hz) pointer coordinate & pressure telemetry for StatusBar.+ PointerStat {+ doc_x: Option<i32>,+ doc_y: Option<i32>,+ pressure: f32,+ },+ /// Emitted whenever Rust-side undo/redo history mutates (e.g. native stroke commit).+ HistoryChanged {+ doc_id: String,+ history: crate::history::HistoryStateSnapshot,+ },+ /// Emitted asynchronously when 64x64 layer/mask thumbnails finish rendering.+ ThumbnailsUpdated {+ doc_id: String,+ updates: Vec<ThumbnailUpdate>,+ },+ /// Emitted when a native DX12 brush stroke commits its CoW tile deltas to the active layer.+ StrokeCommitted {+ doc_id: String,+ layer_id: String,+ entry_id: String,+ },+}++/// Raw GPU surface target accepted by `ink-engine` without depending on Tauri/wry/WinUI.+pub enum SurfaceTarget {+ /// Windows DirectComposition `IDCompositionVisual` raw COM pointer (`*mut c_void`).+ ///+ /// # Safety Contract+ /// - `visual_ptr` must be a valid, AddRef'd or host-kept `IDCompositionVisual` pointer+ /// that outlives the engine thread (i.e. remains valid until `EngineHandle::shutdown()` joins).+ /// - `on_configured` is invoked immediately after `surface.configure(...)` so the host+ /// commits `IDCompositionDevice::Commit()` after `wgpu-hal` calls `visual.SetContent(swapchain)`.+ CompositionVisual {+ visual_ptr: usize,+ on_configured: Arc<dyn Fn() + Send + Sync>,+ },+ /// Headless offscreen target for automated GPU/unit tests without a window.+ Headless { width: u32, height: u32 },+}++impl SurfaceTarget {+ /// Helper to construct a `CompositionVisual` target from a raw `*mut c_void`.+ ///+ /// # Safety+ /// Caller must ensure `visual` is a valid non-null `IDCompositionVisual` COM pointer+ /// that outlives the engine handle.+ pub unsafe fn from_composition_visual(+ visual: *mut c_void,+ on_configured: Arc<dyn Fn() + Send + Sync>,+ ) -> Self {+ debug_assert!(!visual.is_null(), "IDCompositionVisual pointer cannot be null");+ Self::CompositionVisual {+ visual_ptr: visual as usize,+ on_configured,+ }+ }+}diff --git a/docs/rust-engine-migration.md b/docs/rust-engine-migration.mdnew file mode 100644index 0000000..3307a14--- /dev/null+++ b/docs/rust-engine-migration.md@@ -0,0 +1,165 @@+# InkStudio Hybrid Native Rust + `wgpu` (DX12) Engine Migration++> **Target Platform:** Windows 10/11 Desktop Only (`wgpu` DX12 + DirectComposition + transparent WebView2 UI)+> **Status:** Phase 2 of 6 (Document & Tile Memory Single Source of Truth in Rust) Complete++---++## 1. Architecture & Crate / Module Layout++InkStudio is structured as a Cargo workspace with a strictly decoupled GPU engine crate (`crates/ink-engine`) hosted beneath the transparent WebView2 UI in `src-tauri`:++```text+inkstudio/+├── Cargo.toml # Cargo workspace root (members: crates/ink-engine, src-tauri)+├── crates/+│ └── ink-engine/ # Pure Rust DX12 engine — ZERO tauri/wry/tao/WebView deps+│ ├── Cargo.toml # wgpu 30 (dx12/wgsl), rtrb, crossbeam-channel, pollster, bytemuck, windows-sys (QPC/thread)+│ └── src/+│ ├── lib.rs # Public engine API + headless DX12 vertical-slice integration test+│ ├── clock.rs # Shared Windows QPC monotonic millisecond clock (matches tablet_input.rs)+│ ├── types.rs # ViewportRect, UiRect, CameraState, CursorConfig, BrushParams, InteractionPolicy,+│ │ # NativeInputSample, NativeNavEvent, EngineCommand, EngineEvent, EngineDiagnostics, SurfaceTarget+│ ├── camera.rs # Exact 2D affine camera math matching formatArtboardTransform + NativeCameraNavigator+│ ├── hit_test.rs # Thread-safe physical-pixel viewport & UI occlusion mask (blocking + try_* non-blocking)+│ ├── ring.rs # Dedicated wait-free SPSC rtrb rings (wintab, winink, nav) + WakeSignal+│ ├── shaders.rs # WGSL shaders: artboard compositor, instanced GPU dab rasterizer, analytic SDF GPU cursor+│ ├── stroke.rs # Pressure-sensitive spacing-interpolated dab generator + eraser support+│ ├── gpu.rs # DX12 wgpu renderer (CreateSwapChainForComposition, waitable latency=1, device-lost recovery)+│ └── engine.rs # Dedicated above-normal priority render thread, chronological ring drain, EMA latency telemetry+├── src-tauri/+│ ├── tauri.conf.json # main window: decorations: false, transparent: true+│ └── src/+│ ├── dcomp_host.rs # Windows DirectComposition visual tree host + live DX12 composition swapchain test+│ ├── native_engine.rs # Tauri host lifecycle, WM_SIZE/DPI subclass, WH_MOUSE_LL zero-IPC nav/hover hook, event pump+│ ├── tablet_input.rs # Direct WinTab & Windows Ink SPSC ring push + zero-IPC Channel suppression on native strokes+│ └── lib.rs # WEBVIEW2_DEFAULT_BACKGROUND_COLOR=0, startup init, 11 native_engine_* commands, ordered exit+└── src/+ ├── index.css # :root[data-native-canvas="true"] RGBA(0,0,0,0) viewport cutout + opaque chrome seam sealing+ ├── utils/nativeEngineBridge.ts # Typed Tauri IPC + event client (no-op in non-Tauri / Vitest environments)+ ├── hooks/useNativeEngineViewport.ts # ResizeObserver/DPR/interfaceScale viewport sync, UI occlusion observer, bidirectional camera sync+ └── components/+ ├── CanvasArea.tsx # Mounts native engine hook, hides legacy WebGL2 canvas when native DX12 is active+ ├── FloatingBrushPill.tsx # Tagged with data-native-occluder="true"+ ├── AnimationTimeline.tsx # Tagged with data-native-occluder="true"+ └── canvasArea/+ ├── useCompositorViewport.ts # Keeps DOM artboard overlay transform synced; bypasses WebGL2 renders when DX12 is active+ ├── useCanvasEffects.ts # Suppresses DOM brush outline ring for native-handled tools so GPU SDF cursor is sole cursor+ ├── useCanvasPointerHandlers.ts # Skips JS brush/eraser stroke dispatch when native DX12 owns strokes+ └── CanvasViewportHud.tsx # Native DX12 Perf HUD pill (GPU adapter, FPS, frame time, input-to-present latency, Clear button)+```++### Hard Decoupling Invariant+`crates/ink-engine` has **zero dependencies** on `tauri`, `wry`, `tao`, or `webview2-com`. It accepts only:+- `SurfaceTarget::CompositionVisual { visual_ptr, on_configured }` (or `SurfaceTarget::Headless { width, height }` for automated GPU testing),+- Lock-free SPSC `rtrb` input ring producers (`InputProducers { wintab, winink, nav }`), and+- Typed `EngineCommand` control messages.++A future pure-Rust UI shell can host `crates/ink-engine` directly with no modifications to the engine crate.++---++## 2. Windows DirectComposition + WebView2 COM Integration & Lifecycle Invariants++### Visual Tree Layering (Single Top-Level HWND, Zero Canvas Child HWND)+On Windows, `wry` (`0.57.x`/`0.58.x`) hosts WebView2 via a child container HWND (`WRY_WEBVIEW`) inside the top-level `main_hwnd` using a windowed `ICoreWebView2Controller`. When `"transparent": true` is enabled on `main` in `src-tauri/tauri.conf.json`:+1. `tao` activates DWM transparency (`DwmEnableBlurBehindWindow` with an empty region) on `main_hwnd`.+2. `src-tauri/src/lib.rs` sets `WEBVIEW2_DEFAULT_BACKGROUND_COLOR=0` before WebView2 boots, and `DCompHost::configure_webview2_controller` calls `ICoreWebView2Controller2::SetDefaultBackgroundColor(COREWEBVIEW2_COLOR { A: 0, R: 0, G: 0, B: 0 })` so the transparent cutout never flashes white.+3. `DCompHost::new(main_hwnd)` creates an `IDCompositionDevice` via `DCompositionCreateDevice2(None)` and binds an `IDCompositionTarget` via **`device.CreateTargetForHwnd(main_hwnd, false)`** (`topmost = false`):+ - `topmost = false` places our DirectComposition visual tree (`root_visual -> canvas_visual`) strictly **beneath** `WRY_WEBVIEW` and Chromium's own compositor visual tree in DWM.+ - No opaque child HWND is created for the canvas. WebView2 dropdown menus, tooltips, floating dock panels, modals, `FloatingBrushPill`, and `QuickBrushPanel` composite seamlessly above the DX12 canvas with zero clipping.+ - Future-proofing: `configure_webview2_controller` also probes `controller.cast::<ICoreWebView2CompositionController>()` and, if a future `wry` switches to visual-hosting mode, attaches a top `webview_visual` above `canvas_visual` via `AddVisual(&webview_visual, true, Some(&canvas_visual))` + `SetRootVisualTarget(&webview_visual)`.++### `wgpu` DX12 Composition Swapchain Details+Inside `crates/ink-engine/src/gpu.rs`:+- **Backend:** Explicitly `wgpu::Backends::DX12`, `Dx12SwapchainKind::DxgiFromVisual`, `Dx12UseFrameLatencyWaitableObject::Wait`.+- **Surface Creation:** `instance.create_surface_unsafe(SurfaceTargetUnsafe::CompositionVisual { visual })`. `wgpu-hal` borrows and `AddRef`s the `IDCompositionVisual` pointer (`from_raw_borrowed` + `to_owned`) and releases it cleanly when `wgpu::Surface` drops.+- **Swapchain Configuration:**+ - Calls `IDXGIFactory2::CreateSwapChainForComposition` with `DXGI_SWAP_EFFECT_FLIP_DISCARD`, `DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT`, and `SetMaximumFrameLatency(1)` (`desired_maximum_frame_latency: 1`).+ - **Present Mode:** Prefers `PresentMode::Mailbox` when advertised by the adapter, falling back to `PresentMode::Fifo`.+ - **Alpha Mode:** Explicitly selects `CompositeAlphaMode::Opaque` (`DXGI_ALPHA_MODE_IGNORE`) or `CompositeAlphaMode::PreMultiplied` (`DXGI_ALPHA_MODE_PREMULTIPLIED`) — never `Auto`/`Inherit` (`DXGI_ALPHA_MODE_UNSPECIFIED`), which `CreateSwapChainForComposition` rejects with `DXGI_ERROR_INVALID_CALL`.+ - **Mandatory Commit Hook:** `wgpu-hal` calls `IDCompositionVisual::SetContent(&swap_chain1)` inside `surface.configure(...)` but does **not** call `IDCompositionDevice::Commit()`. `ink-engine` invokes the host's `on_configured` callback immediately after every `surface.configure(...)` so `DCompHost::commit()` commits the swapchain binding to DWM.+- **Viewport Positioning & Clipping:** `DCompHost::set_canvas_viewport(x_px, y_px, width_px, height_px, visible)` applies `SetOffsetX2`, `SetOffsetY2`, `SetClip2` (`0..width_px`, `0..height_px`, or `0..0` when hidden), and `Commit()`.++### Lifecycle, Recovery & Ordered Teardown Invariants+- **`WM_SIZE` (`SIZE_MINIMIZED` / restore):** `lifecycle_subclass_proc` on `main_hwnd` immediately pauses rendering (`SetVisible(false)` + empty DirectComposition clip) when minimized and restores viewport visibility + sends `NotifySurfaceInvalidated` on restore.+- **`WM_DPICHANGED` / `WM_DISPLAYCHANGE`:** Sends `NotifySurfaceInvalidated` to reconfigure the swapchain cleanly; React simultaneously observes `window.devicePixelRatio` via `matchMedia` and pushes updated physical bounds.+- **Device-Lost / Swapchain Outdated Recovery:** `GpuRenderer::render_frame` handles `SurfaceError::Outdated | Lost` by reconfiguring the swapchain, and `SurfaceError::Timeout | OutOfMemory | Other` by tracking device-lost recoveries and rebuilding the DX12 device + pipelines + canvas texture cleanly if needed.+- **Strict Shutdown Order (`native_engine::shutdown` in `RunEvent::Exit`):**+ 1. Mark engine inactive and detach `tablet_input` ring producers (`tablet_input::detach_engine_rings()`).+ 2. Stop `inkstudio-native-mouse` (`WH_MOUSE_LL`) hook thread (`PostThreadMessageW(WM_QUIT)` + `join`).+ 3. Remove `main_hwnd` lifecycle subclass (`RemoveWindowSubclass`).+ 4. Call **`EngineHandle::shutdown()`** and join `"inkstudio-gpu-engine"` — guarantees `wgpu::Surface` and the DXGI composition swapchain drop **strictly before** DirectComposition teardown.+ 5. Join the event bridge thread, call `DCompHost::clear_content()` (`SetContent(None)` + `Commit()`), and drop `DCompHost`.+- **Lock Hierarchy:** `RUNTIME` -> `DCompHost::inner`. `on_configured` only locks `DCompHost::inner`, and `shutdown()` releases `RUNTIME` before joining the GPU thread, eliminating AB-BA deadlocks.++---++## 3. Zero-IPC Hot Paths & Coordinate System Parity++### Lock-Free SPSC Input Routing (Zero JSON, Zero Tauri IPC During Strokes/Nav)+Three dedicated wait-free `rtrb` SPSC rings feed `ink-engine` and wake the render thread immediately via `WakeSignal`:+1. **`wintab` ring (`inkstudio-wintab` thread -> `ink-engine`):** `tablet_input.rs` maps WinTab packets to sub-pixel physical client coordinates `(phys_x, phys_y)` and pushes `NativeInputSample` batches directly into `rtrb`. When a pen-down lands inside the unoccluded canvas viewport for a native-handled tool (`Brush`/`Eraser`), `native_stroke_owned` suppresses Tauri Channel serialization completely for the entire stroke and unoccluded hover.+2. **`winink` ring (UI thread `ink_subclass_proc` -> `ink-engine`):** Same direct `rtrb` batch push + Channel suppression for Windows Ink `WM_POINTER*` history bursts.+3. **`nav` ring (`inkstudio-native-mouse` `WH_MOUSE_LL` thread -> `ink-engine`):** Non-blocking (`try_read` on `SharedHitTest` + wait-free `rtrb` push) delivery of mouse hover (120–240 Hz GPU cursor), mouse wheel zoom/scroll, middle-mouse pan/rotate/zoom, Space+Left-drag pan/rotate/zoom, and mouse PoC drawing (automatically suppressing pen/touch-synthesized mouse events via `MI_WP_SIGNATURE` and recent stylus timestamp). `WM_MOUSEMOVE` is never swallowed so the OS cursor never stalls.++### Physical Pixel Coordinate Invariance (DPI + `interfaceScale`)+- Native input coordinates (`WinTab`, `Windows Ink`, `WH_MOUSE_LL`) arrive as **physical client pixels** relative to `main_hwnd` (`ScreenToClient` without dividing by DPI).+- React sends viewport cutout bounds and UI occlusion rects as `DOMRect * window.devicePixelRatio`. Because WebView2 scales `window.devicePixelRatio = os_dpi_scale * native_webview_zoom`, physical pixel coordinates remain pixel-exact across all Windows DPI settings (100%–200%+) and InkStudio `interfaceScale` levels (60%–200%).+- `ink-engine` converts physical pixels to zoomed viewport-local CSS pixels via `(phys - viewport_origin) / dpr`, matching `formatArtboardTransform` (`src/components/canvasArea/types.ts`) and `CanvasArtboardOverlays` pixel-for-pixel.++---++## 4. React <-> Rust IPC Surface (Control & Telemetry Only)++All IPC calls are strictly **off the hot stroke/navigation path** (fired only on layout changes, tool/setting edits, document opens, or throttled background sync):++### Commands (`invoke` from React -> Rust)+| Command | Purpose |+| :--- | :--- |+| `native_engine_is_active()` | Returns `true` if Windows DirectComposition + DX12 engine initialized cleanly. |+| `native_engine_set_viewport(xPx, yPx, widthPx, heightPx, dpr, visible)` | Updates physical cutout bounds, DirectComposition offset/clip, and swapchain size. |+| `native_engine_set_occluded_rects(rects)` | Replaces physical-pixel UI occlusion rects (modals, popovers, menus, `FloatingBrushPill`, floating dock windows, `QuickBrushPanel`, `AnimationTimeline`, perf HUD). |+| `native_engine_set_document(width, height, showCheckerboard)` | Resizes/recreates the GPU document canvas surface. |+| `native_engine_set_appearance(matteRgba, showCheckerboard)` | Syncs `--ui-canvas-matte` theme color and checkerboard grid toggle. |+| `native_engine_set_camera(camera)` | Applies programmatic UI camera updates (Fit-to-Screen, Navigator, Flip H/V, Reset Rotation). |+| `native_engine_set_cursor(config)` | Updates GPU SDF brush outline cursor size, shape, aspect/thickness, tip angle, and visibility. |+| `native_engine_set_brush(params)` | Updates Phase 1 PoC GPU dab brush size, opacity, hardness, spacing, pressure toggles, color, and eraser mode. |+| `native_engine_set_policy(policy)` | Syncs active tool classification, wheel mode, Webtoon mode, text-input focus, workspace splitter drag lock, and modal guard. |+| `native_engine_clear_canvas()` | Clears the Phase 1 PoC GPU canvas texture to transparent. |+| `native_engine_get_diagnostics()` | Returns latest `EngineDiagnostics` snapshot on demand. |++### Throttled Events (Rust -> React)+| Event | Cadence | Purpose |+| :--- | :--- | :--- |+| `native-engine://camera` | ~60 Hz during native nav + final `commit: true` | Keeps `useCanvasNavigation.ts` & `CanvasArtboardOverlays` pixel-aligned with native Rust pan/zoom/rotate. |+| `native-engine://diagnostics` | ~4 Hz | Drives the minimal Native DX12 Perf HUD (`adapterName`, `fps`, `frameTimeMs`, `inputToPresentMs`, `presentMode`). |+| `native-engine://pointer-stat` | ~30 Hz | Dispatches `canvas-pointer-stat` so `StatusBar` coordinates & live pressure readout stay active during zero-IPC strokes. |++---++## 5. Phase 1 Completion Checklist++- [x] Cargo workspace root created with strictly decoupled `crates/ink-engine` (zero Tauri/wry/WebView deps).+- [x] Windows DirectComposition single-HWND visual tree (`CreateTargetForHwnd(main_hwnd, false)`) layering DX12 `CreateSwapChainForComposition` (`SetMaximumFrameLatency(1)`, `PresentMode::Mailbox` preferred else `Fifo`) beneath transparent WebView2 (`COREWEBVIEW2_COLOR = 0`).+- [x] Transparent WebView2 viewport cutout across `flat`, `hairline`, `islands`, and Focus Mode with zero seam leakage and full UI occlusion rect reporting.+- [x] Direct lock-free `rtrb` SPSC ring routing from `src-tauri/src/tablet_input.rs` (WinTab + Windows Ink) and `WH_MOUSE_LL` directly into `ink-engine` (zero IPC during active strokes and camera nav).+- [x] Native 120–240 Hz GPU camera navigation (pan/zoom `0.01..32.0`/rotate/flip) matching `formatArtboardTransform` pixel-for-pixel + throttled sync back to React.+- [x] Analytic SDF dual-tone GPU brush outline cursor ring + minimal GPU dab test brush + minimal DX12 Perf HUD with live GPU adapter, FPS, frame time, input-to-present latency, and Clear button.+- [x] Verified live DirectComposition + DX12 swapchain presentation test, workspace Rust tests, Clippy, TypeScript/Vite build, and Vitest suite.++---++## 6. Phase 2 Handoff Notes (Sparse Tile Engine & Multi-Layer GPU Compositor)++Phase 1 deliberately keeps a single RGBA8 test texture inside `crates/ink-engine/src/gpu.rs` so input-to-photon latency and DirectComposition visual layering could be validated end-to-end first. Phase 2 builds directly on this foundation:++1. **Sparse Tile Pyramid & VRAM Pool (`crates/ink-engine/src/tiles.rs`):**+ - Replace `GpuRenderer`'s single `canvas_tex` with a 256×256 sparse tile atlas (`wgpu::Texture` 2D array + LRU resident page table) matching InkStudio's existing `SparseTileGrid` semantics, with mipmapped/cached composite chunks for zoomed-out canvases.+2. **Multi-Layer Stack & Blend Mode Compositor (`crates/ink-engine/src/compositor.rs`):**+ - Add typed `EngineCommand`s for layer CRUD/reordering/visibility/opacity/blend-modes/clipping/masks/folders/screentone/monochrome expression color, porting the WGSL equivalents of `src/utils/compositor/shaders/coreShaders.ts` into `crates/ink-engine`.+ - Port document load/import (`.ink`, `.psd`, `.clip`) to upload initial raster tiles directly over binary IPC (`tauri::ipc::Request` raw bytes) into `ink-engine` without routing pixel arrays through JS canvas memory.+3. **Undo/Redo Tile Snapshots & Scratch Disk Integration:**+ - Capture dirty tile diffs on stroke end inside `ink-engine` and compress directly with `lz4_flex` into `src-tauri/src/scratch_disk.rs` and `recovery.rs` WAL entries in-process.+4. **Full Brush Engine Port (Phase 3):**+ - Expand `crates/ink-engine/src/stroke.rs` from the Phase 1 radial dab PoC to full custom tip textures, sub-tips, dual brush, tilt/twist dynamics, watercolor/natural paint mixing, ribbon tips, stabilizer/prediction, and ruler/symmetry snapping.diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 0dd84b0..bef1368 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -20,6 +20,10 @@ crate-type = ["staticlib", "cdylib", "rlib"]tauri-build = { version = "2", features = [] }[dependencies]+ink-engine = { path = "../crates/ink-engine" }+crossbeam-channel = "0.5"+parking_lot = "0.12"+rtrb = "0.4"tauri = { version = "2", features = [] }tauri-plugin-opener = "2"tauri-plugin-process = "2"@@ -41,6 +45,16 @@ rusqlite = { version = "0.32", features = ["bundled", "serialize"] }[target.'cfg(target_os = "windows")'.dependencies]webview2-com = "0.39"+windows = { version = "0.62", features = [+ "Win32_Foundation",+ "Win32_Graphics_Direct2D_Common",+ "Win32_Graphics_DirectComposition",+ "Win32_Graphics_Gdi",+ "Win32_UI_HiDpi",+ "Win32_UI_Input_KeyboardAndMouse",+ "Win32_UI_Shell",+ "Win32_UI_WindowsAndMessaging",+] }windows-core = "0.62"windows-sys = { version = "0.59", features = ["Win32_Foundation",@@ -61,13 +75,3 @@ windows-sys = { version = "0.59", features = [[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]tauri-plugin-single-instance = "2"tauri-plugin-updater = "2"----# Read the optimization guideline for more details: https://tauri.app/concept/size/#cargo-configuration-[profile.release]-codegen-units = 1-lto = true-opt-level = 3-panic = "abort"-strip = truediff --git a/src-tauri/src/clip_parser.rs b/src-tauri/src/clip_parser.rsindex 30b3eb8..4a42ca1 100644--- a/src-tauri/src/clip_parser.rs+++ b/src-tauri/src/clip_parser.rs@@ -1108,8 +1108,8 @@ fn extract_solid_fill_color(}/// Parses a `.clip` / `.csp` / `.lip` file buffer natively using bundled rusqlite + flate2 + rayon,-/// returning the compact `INKD` binary wire frame with LZ4-compressed 256x256 tiles.-pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {+/// returning raw assembled layers ready for direct zero-copy hydration into `ink-engine`.+pub fn parse_clip_assembled(bytes: &[u8]) -> Result<crate::doc_wire::ParsedDocumentAssembled, String> {let chunks = parse_csp_chunks(bytes);let sqlite_data = find_sqlite_data(&chunks, bytes).ok_or_else(|| {"Could not find SQLite database metadata within Clip Studio Paint file.".to_string()@@ -1965,7 +1965,28 @@ pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {}).collect();- pack_parsed_document(width, height, dpi, "color", preview, assembled)+ Ok(crate::doc_wire::ParsedDocumentAssembled {+ width,+ height,+ dpi,+ color_mode: "color".to_string(),+ preview,+ layers: assembled,+ })+}++/// Parses a `.clip` / `.csp` / `.lip` file buffer natively using bundled rusqlite + flate2 + rayon,+/// returning the compact `INKD` binary wire frame with LZ4-compressed 256x256 tiles.+pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {+ let parsed = parse_clip_assembled(bytes)?;+ pack_parsed_document(+ parsed.width,+ parsed.height,+ parsed.dpi,+ &parsed.color_mode,+ parsed.preview,+ parsed.layers,+ )}// ---------------------------------------------------------------------------@@ -5079,7 +5100,7 @@ pub fn format_sut_inspection_human(report: &SutInspectionReport) -> String {}#[cfg(test)]-mod tests {+pub(crate) mod tests {use super::*;fn zlib_compress(data: &[u8]) -> Vec<u8> {@@ -5124,9 +5145,7 @@ mod tests {payload}- #[test]- fn test_parse_synthetic_clip_end_to_end() {- // Build an in-memory SQLite DB and serialize it+ pub(crate) fn build_synthetic_clip_fixture() -> Vec<u8> {let conn = Connection::open_in_memory().unwrap();conn.execute_batch("@@ -5173,6 +5192,13 @@ mod tests {clip.extend_from_slice(&exta);clip.extend_from_slice(&sqli);clip.extend_from_slice(&foot);+ clip+ }++ #[test]+ fn test_parse_synthetic_clip_end_to_end() {+ let p = 5 * TILE_SIZE + 3;+ let clip = build_synthetic_clip_fixture();let wire = parse_clip_to_binary(&clip).expect("parse_clip_to_binary failed");assert_eq!(&wire[0..4], b"INKD");diff --git a/src-tauri/src/dcomp_host.rs b/src-tauri/src/dcomp_host.rsnew file mode 100644index 0000000..811c641--- /dev/null+++ b/src-tauri/src/dcomp_host.rs@@ -0,0 +1,446 @@+//! Windows DirectComposition visual host for InkStudio's hybrid DX12 + WebView2 layering.+//!+//! # Visual Tree Architecture (`wry 0.57.3` / `tauri 2.12.7` on Windows 10/11)+//!+//! `wry` creates a child container HWND (`WRY_WEBVIEW`) inside the top-level `main_hwnd`+//! and hosts WebView2 via `ICoreWebView2Controller`. When `"transparent": true` is enabled+//! on `main`, `tao` activates DWM alpha composition on `main_hwnd` and `wry` sets+//! `COREWEBVIEW2_COLOR { A: 0, R: 0, G: 0, B: 0 }` on the WebView2 controller.+//!+//! We bind an `IDCompositionTarget` directly to `main_hwnd` with `topmost = false`:+//! - **Bottom visual (`canvas_visual`):** Receives `wgpu` DX12 flip-model composition+//! swapchain (`CreateSwapChainForComposition`, `DXGI_SWAP_EFFECT_FLIP_DISCARD`,+//! `DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT`, `SetMaximumFrameLatency(1)`),+//! offset and clipped in physical client pixels to the transparent `<main>` viewport cutout.+//! - **Top layer (WebView2 UI):** Because `CreateTargetForHwnd(main_hwnd, false)` places+//! our visual tree strictly beneath child HWNDs (`WRY_WEBVIEW`) in DWM, the transparent+//! WebView2 UI renders cleanly on top with ZERO opaque canvas child HWND and ZERO clipping+//! of dropdowns, tooltips, floating dock panels, modals, or `FloatingBrushPill`.+//! - If a future `wry` switches to `ICoreWebView2CompositionController`, `configure_webview2_controller`+//! also opportunistically attaches a top `webview_visual` above `canvas_visual` via+//! `SetRootVisualTarget`.+//!+//! # Lifecycle & Drop Order Invariant+//! `EngineHandle::shutdown()` MUST join the render thread (dropping `wgpu::Surface` and the+//! DXGI swapchain) strictly BEFORE `DCompHost::clear_content()` and dropping `DCompHost`.++#[cfg(target_os = "windows")]+mod imp {+ use std::ffi::c_void;+ use std::sync::Mutex;+ use webview2_com::Microsoft::Web::WebView2::Win32::{+ ICoreWebView2CompositionController, ICoreWebView2Controller, ICoreWebView2Controller2,+ COREWEBVIEW2_COLOR,+ };+ use windows::Win32::Foundation::HWND;+ use windows::Win32::Graphics::Direct2D::Common::D2D_RECT_F;+ use windows::Win32::Graphics::DirectComposition::{+ DCompositionCreateDevice2, IDCompositionDevice, IDCompositionTarget, IDCompositionVisual,+ };+ use windows_core::{IUnknown, Interface};++ struct DCompInner {+ device: IDCompositionDevice,+ _target: IDCompositionTarget,+ root_visual: IDCompositionVisual,+ canvas_visual: IDCompositionVisual,+ webview_visual: Option<IDCompositionVisual>,+ last_rect: (i32, i32, u32, u32, bool),+ }++ pub struct DCompHost {+ inner: Mutex<DCompInner>,+ }++ // SAFETY: DirectComposition COM interfaces are agile/MTA-safe when access is serialized.+ // Every method acquires `self.inner: Mutex<DCompInner>` before touching any COM pointer.+ unsafe impl Send for DCompHost {}+ unsafe impl Sync for DCompHost {}++ impl DCompHost {+ /// Creates a DirectComposition device, non-topmost target bound to `main_hwnd`,+ /// and bottom `canvas_visual` ready to receive `wgpu`'s DX12 composition swapchain.+ pub fn new(main_hwnd_raw: isize) -> Result<Self, String> {+ if main_hwnd_raw == 0 {+ return Err("Cannot initialize DirectComposition with null HWND".to_string());+ }+ let hwnd = HWND(main_hwnd_raw as *mut c_void);++ unsafe {+ let device: IDCompositionDevice =+ DCompositionCreateDevice2(None::<&IUnknown>).map_err(|e| {+ format!("DCompositionCreateDevice2 failed: {e}")+ })?;++ // `topmost = false` layers the DirectComposition tree strictly BENEATH+ // child HWNDs (`WRY_WEBVIEW` / WebView2) so transparent UI chrome, modals,+ // tooltips, and floating panels composite cleanly on top without clipping.+ let target = device+ .CreateTargetForHwnd(hwnd, false)+ .map_err(|e| format!("IDCompositionDevice::CreateTargetForHwnd failed: {e}"))?;++ let root_visual = device+ .CreateVisual()+ .map_err(|e| format!("CreateVisual(root) failed: {e}"))?;+ let canvas_visual = device+ .CreateVisual()+ .map_err(|e| format!("CreateVisual(canvas) failed: {e}"))?;++ target+ .SetRoot(&root_visual)+ .map_err(|e| format!("IDCompositionTarget::SetRoot failed: {e}"))?;+ root_visual+ .AddVisual(&canvas_visual, false, None)+ .map_err(|e| format!("AddVisual(canvas) failed: {e}"))?;++ // Start hidden/clipped to 0x0 until React reports an active document viewport.+ let empty_clip = D2D_RECT_F {+ left: 0.0,+ top: 0.0,+ right: 0.0,+ bottom: 0.0,+ };+ let _ = canvas_visual.SetOffsetX2(0.0);+ let _ = canvas_visual.SetOffsetY2(0.0);+ let _ = canvas_visual.SetClip2(&empty_clip);+ device+ .Commit()+ .map_err(|e| format!("Initial IDCompositionDevice::Commit failed: {e}"))?;++ Ok(Self {+ inner: Mutex::new(DCompInner {+ device,+ _target: target,+ root_visual,+ canvas_visual,+ webview_visual: None,+ last_rect: (0, 0, 0, 0, false),+ }),+ })+ }+ }++ /// Enforces transparent WebView2 default background (`ARGB = 0,0,0,0`) and, if the+ /// WebView2 controller exposes `ICoreWebView2CompositionController`, attaches a top+ /// visual strictly above `canvas_visual`.+ pub fn configure_webview2_controller(+ &self,+ controller: &ICoreWebView2Controller,+ ) -> String {+ unsafe {+ if let Ok(controller2) = controller.cast::<ICoreWebView2Controller2>() {+ let _ = controller2.SetDefaultBackgroundColor(COREWEBVIEW2_COLOR {+ A: 0,+ R: 0,+ G: 0,+ B: 0,+ });+ }++ // Future-proof: if wry ever uses ICoreWebView2CompositionController, place+ // WebView2's visual directly above canvas_visual in our single visual tree.+ if let Ok(comp_controller) = controller.cast::<ICoreWebView2CompositionController>()+ {+ if let Ok(mut guard) = self.inner.lock() {+ if guard.webview_visual.is_none() {+ if let Ok(wv_visual) = guard.device.CreateVisual() {+ let canvas_ref = guard.canvas_visual.clone();+ if guard+ .root_visual+ .AddVisual(&wv_visual, true, Some(&canvas_ref))+ .is_ok()+ && comp_controller.SetRootVisualTarget(&wv_visual).is_ok()+ {+ let _ = guard.device.Commit();+ guard.webview_visual = Some(wv_visual);+ return "DirectComposition (Dual Visual)".to_string();+ }+ }+ }+ }+ }+ }++ "DirectComposition (Underlay)".to_string()+ }++ /// Returns the raw `IDCompositionVisual` COM pointer for `wgpu`'s+ /// `SurfaceTargetUnsafe::CompositionVisual`.+ ///+ /// `wgpu-hal` calls `IDCompositionVisual::from_raw_borrowed` + `.to_owned()` (AddRef)+ /// immediately during `create_surface_unsafe`.+ pub fn canvas_visual_raw(&self) -> Result<*mut c_void, String> {+ let guard = self+ .inner+ .lock()+ .map_err(|_| "DirectComposition host mutex poisoned".to_string())?;+ Ok(guard.canvas_visual.as_raw())+ }++ /// Positions and clips `canvas_visual` to the physical client-pixel viewport cutout+ /// and commits the DirectComposition batch immediately.+ pub fn set_canvas_viewport(+ &self,+ x_px: i32,+ y_px: i32,+ width_px: u32,+ height_px: u32,+ visible: bool,+ ) -> Result<(), String> {+ let mut guard = self+ .inner+ .lock()+ .map_err(|_| "DirectComposition host mutex poisoned".to_string())?;++ let next = (x_px, y_px, width_px, height_px, visible);+ if guard.last_rect == next {+ return Ok(());+ }++ let clip = if visible && width_px > 0 && height_px > 0 {+ D2D_RECT_F {+ left: 0.0,+ top: 0.0,+ right: width_px as f32,+ bottom: height_px as f32,+ }+ } else {+ D2D_RECT_F {+ left: 0.0,+ top: 0.0,+ right: 0.0,+ bottom: 0.0,+ }+ };++ unsafe {+ guard+ .canvas_visual+ .SetOffsetX2(x_px as f32)+ .map_err(|e| format!("SetOffsetX2 failed: {e}"))?;+ guard+ .canvas_visual+ .SetOffsetY2(y_px as f32)+ .map_err(|e| format!("SetOffsetY2 failed: {e}"))?;+ guard+ .canvas_visual+ .SetClip2(&clip)+ .map_err(|e| format!("SetClip2 failed: {e}"))?;+ guard+ .device+ .Commit()+ .map_err(|e| format!("IDCompositionDevice::Commit failed: {e}"))?;+ }++ guard.last_rect = next;+ Ok(())+ }++ /// Commits pending DirectComposition updates (REQUIRED immediately after+ /// `wgpu::Surface::configure`, because `wgpu-hal` calls `IDCompositionVisual::SetContent`+ /// without committing the caller's `IDCompositionDevice`).+ pub fn commit(&self) {+ if let Ok(guard) = self.inner.lock() {+ unsafe {+ let _ = guard.device.Commit();+ }+ }+ }++ /// Detaches swapchain content from `canvas_visual` and commits.+ /// Call strictly AFTER `EngineHandle::shutdown()` joins the GPU thread.+ pub fn clear_content(&self) {+ if let Ok(mut guard) = self.inner.lock() {+ unsafe {+ let _ = guard.canvas_visual.SetContent(None::<&IUnknown>);+ let empty_clip = D2D_RECT_F {+ left: 0.0,+ top: 0.0,+ right: 0.0,+ bottom: 0.0,+ };+ let _ = guard.canvas_visual.SetClip2(&empty_clip);+ let _ = guard.device.Commit();+ }+ guard.last_rect = (0, 0, 0, 0, false);+ }+ }+ }++ #[cfg(test)]+ mod tests {+ use super::*;+ use ink_engine::{+ CameraState, EngineCommand, EngineConfig, EngineHandle, NativeInputSample,+ SurfaceTarget, ViewportRect,+ };+ use std::sync::Arc;+ use std::time::{Duration, Instant};+ use windows_sys::Win32::UI::WindowsAndMessaging::{+ CreateWindowExW, DefWindowProcW, DestroyWindow, RegisterClassW, WNDCLASSW, WS_POPUP,+ };++ #[test]+ fn test_direct_composition_wgpu_dx12_swapchain_configure_and_present() {+ unsafe {+ let class_name: Vec<u16> =+ "InkStudioDCompTestWindow\0".encode_utf16().collect();+ let wc = WNDCLASSW {+ style: 0,+ lpfnWndProc: Some(DefWindowProcW),+ cbClsExtra: 0,+ cbWndExtra: 0,+ hInstance: std::ptr::null_mut(),+ hIcon: std::ptr::null_mut(),+ hCursor: std::ptr::null_mut(),+ hbrBackground: std::ptr::null_mut(),+ lpszMenuName: std::ptr::null(),+ lpszClassName: class_name.as_ptr(),+ };+ RegisterClassW(&wc);++ // Create a hidden top-level WS_POPUP window (never shown on screen) to exercise+ // real IDCompositionTarget + DXGI CreateSwapChainForComposition + latency=1.+ let hwnd = CreateWindowExW(+ 0,+ class_name.as_ptr(),+ class_name.as_ptr(),+ WS_POPUP,+ 0,+ 0,+ 320,+ 240,+ std::ptr::null_mut(),+ std::ptr::null_mut(),+ std::ptr::null_mut(),+ std::ptr::null(),+ );+ assert!(!hwnd.is_null(), "CreateWindowExW for test window failed");++ let dcomp = Arc::new(+ DCompHost::new(hwnd as isize).expect("DCompHost::new failed on test HWND"),+ );+ let visual_raw = dcomp.canvas_visual_raw().expect("canvas_visual_raw");+ let dcomp_commit = Arc::clone(&dcomp);+ let target = SurfaceTarget::from_composition_visual(+ visual_raw,+ Arc::new(move || {+ dcomp_commit.commit();+ }),+ );++ let spawned = EngineHandle::spawn(+ target,+ EngineConfig {+ doc_width: 512,+ doc_height: 512,+ show_checkerboard: true,+ matte_color: [0.086, 0.086, 0.086, 1.0],+ ..Default::default()+ },+ );++ let (handle, mut producers) = match spawned {+ Ok(pair) => pair,+ Err(err) => {+ eprintln!(+ "Skipping live DirectComposition DX12 test (no DX12 adapter): {err}"+ );+ dcomp.clear_content();+ drop(dcomp);+ DestroyWindow(hwnd);+ return;+ }+ };++ dcomp+ .set_canvas_viewport(16, 16, 288, 208, true)+ .expect("set_canvas_viewport");+ handle.send_command(EngineCommand::SetVisible(true));+ handle.send_command(EngineCommand::SetViewport(ViewportRect {+ x_px: 16,+ y_px: 16,+ width_px: 288,+ height_px: 208,+ dpr: 1.0,+ }));+ handle.send_command(EngineCommand::SetCamera(CameraState {+ pan_x: 144.0,+ pan_y: 104.0,+ zoom: 0.4,+ rotation: 0.0,+ flip_x: false,+ flip_y: false,+ }));++ let now = ink_engine::clock::now_ms();+ producers.wintab.push_batch(&[+ NativeInputSample {+ phys_x: 100.0,+ phys_y: 100.0,+ pressure: 0.5,+ tilt_x: 0.0,+ tilt_y: 0.0,+ twist: 0.0,+ timestamp_ms: now,+ buttons: 1,+ phase: 1,+ backend: 1,+ },+ NativeInputSample {+ phys_x: 200.0,+ phys_y: 140.0,+ pressure: 0.85,+ tilt_x: 0.0,+ tilt_y: 0.0,+ twist: 0.0,+ timestamp_ms: now + 4.0,+ buttons: 1,+ phase: 2,+ backend: 1,+ },+ NativeInputSample {+ phys_x: 200.0,+ phys_y: 140.0,+ pressure: 0.0,+ tilt_x: 0.0,+ tilt_y: 0.0,+ twist: 0.0,+ timestamp_ms: now + 8.0,+ buttons: 0,+ phase: 3,+ backend: 1,+ },+ ]);++ let deadline = Instant::now() + Duration::from_secs(4);+ while Instant::now() < deadline {+ if handle.diagnostics().total_frames_rendered >= 1 {+ break;+ }+ std::thread::sleep(Duration::from_millis(10));+ }++ let diag = handle.diagnostics();+ assert!(diag.ready, "DX12 DirectComposition engine should be ready");+ assert_eq!(diag.backend, "DX12");+ assert_eq!(diag.max_frame_latency, 1);+ assert!(+ diag.total_frames_rendered >= 1,+ "Expected at least 1 presented DirectComposition frame, got {}",+ diag.total_frames_rendered+ );++ // Verify strict ordered shutdown: engine stops & drops Surface BEFORE DCompHost drops.+ handle.shutdown();+ assert!(!handle.is_running());+ dcomp.clear_content();+ drop(dcomp);+ DestroyWindow(hwnd);+ }+ }+ }+}++#[cfg(target_os = "windows")]+pub use imp::DCompHost;diff --git a/src-tauri/src/doc_wire.rs b/src-tauri/src/doc_wire.rsindex fbb71ab..c5a087f 100644--- a/src-tauri/src/doc_wire.rs+++ b/src-tauri/src/doc_wire.rs@@ -128,6 +128,17 @@ pub struct AssembledLayer {pub mask: Option<RawMask>,}+/// Complete parsed document ready for direct zero-copy hydration into `ink-engine`+/// without serializing through `INKD` or sending pixel buffers across Tauri IPC.+pub struct ParsedDocumentAssembled {+ pub width: u32,+ pub height: u32,+ pub dpi: u32,+ pub color_mode: String,+ pub preview: Option<(Vec<u8>, String)>,+ pub layers: Vec<AssembledLayer>,+}+/// Slices a clipped RGBA sub-rectangle into sparse 256x256 RGBA tiles,/// skipping completely transparent tiles.pub fn slice_rgba_rect_to_tiles(@@ -309,10 +320,12 @@ pub fn pack_parsed_document(preview: Option<(Vec<u8>, String)>,assembled_layers: Vec<AssembledLayer>,) -> Result<Vec<u8>, String> {+ type CompressedMaskTuple = (bool, bool, u8, i32, i32, u32, u32, u8, Vec<u8>);+struct CompressedLayer {layer: AssembledLayer,compressed_tiles: Vec<(i32, i32, u8, Vec<u8>)>,- compressed_mask: Option<(bool, bool, u8, i32, i32, u32, u32, u8, Vec<u8>)>,+ compressed_mask: Option<CompressedMaskTuple>,}// Parallel compress across all layers & tilesdiff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex f214e60..6cd606a 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -1,6 +1,9 @@pub mod clip_parser;+mod dcomp_host;mod doc_wire;mod file_open;+mod native_docs;+mod native_engine;mod os_hotkeys;mod psd_parser;mod raster_ops;@@ -116,7 +119,6 @@ const DELETE_ALLOWED_EXTS: &[&str] = &[];const MAX_READ_FILE_BYTES: u64 = 512 * 1024 * 1024; // 512 MB ceiling-const MAX_UNDO_CACHE_BYTES: usize = 128 * 1024 * 1024; // 128 MB ceilingfn percent_decode(input: &str) -> Result<String, String> {let bytes = input.as_bytes();@@ -416,54 +418,6 @@ async fn validate_delete_path(Ok(Some(canonical))}-#[tauri::command]-async fn save_undo_tile_cache(request: tauri::ipc::Request<'_>) -> Result<(), String> {- let session_id = header_str(&request, "x-session-id")?;- let state_id = header_str(&request, "x-state-id")?;- let data = raw_body(&request)?;- if data.len() > MAX_UNDO_CACHE_BYTES {- return Err("Undo tile payload exceeds maximum allowed size".to_string());- }- let safe_session = sanitize_id(&session_id);- let safe_state = sanitize_id(&state_id);- let temp_dir = system_perf::get_undo_cache_base_dir().join(&safe_session);- tokio::fs::create_dir_all(&temp_dir)- .await- .map_err(|e| e.to_string())?;- let file_path = temp_dir.join(format!("{}.bin", safe_state));- tokio::fs::write(&file_path, data)- .await- .map_err(|e| e.to_string())?;- Ok(())-}--#[tauri::command]-async fn load_undo_tile_cache(- request: tauri::ipc::Request<'_>,-) -> Result<tauri::ipc::Response, String> {- let session_id = header_str(&request, "x-session-id")?;- let state_id = header_str(&request, "x-state-id")?;- let safe_session = sanitize_id(&session_id);- let safe_state = sanitize_id(&state_id);- let file_path = system_perf::get_undo_cache_base_dir()- .join(&safe_session)- .join(format!("{}.bin", safe_state));- let data = tokio::fs::read(&file_path)- .await- .map_err(|e| e.to_string())?;- Ok(tauri::ipc::Response::new(data))-}--#[tauri::command]-async fn clear_undo_tile_cache(session_id: String) -> Result<(), String> {- let safe_session = sanitize_id(&session_id);- let temp_dir = system_perf::get_undo_cache_base_dir().join(&safe_session);- if temp_dir.exists() {- let _ = tokio::fs::remove_dir_all(&temp_dir).await;- }- Ok(())-}-#[tauri::command]async fn delete_file_from_disk(app: tauri::AppHandle, path: String) -> Result<bool, String> {let allowed_dirs = get_allowed_base_dirs(&app);@@ -1133,6 +1087,542 @@ fn tablet_get_status() -> tablet_input::TabletStatus {tablet_input::get_tablet_status()}+#[tauri::command]+fn native_engine_is_active() -> bool {+ native_engine::is_active()+}++#[tauri::command]+fn native_engine_set_viewport(+ x_px: i32,+ y_px: i32,+ width_px: u32,+ height_px: u32,+ dpr: f32,+ visible: bool,+) -> Result<(), String> {+ native_engine::set_viewport(+ ink_engine::ViewportRect {+ x_px,+ y_px,+ width_px,+ height_px,+ dpr,+ },+ visible,+ )+}++#[tauri::command]+fn native_engine_set_occluded_rects(rects: Vec<ink_engine::UiRect>) {+ native_engine::set_occluded_rects(rects);+}++#[tauri::command]+fn native_engine_set_document(width: u32, height: u32, show_checkerboard: bool) {+ native_engine::set_document(width, height, show_checkerboard);+}++#[tauri::command]+fn native_engine_set_appearance(matte_rgba: [f32; 4], show_checkerboard: bool) {+ native_engine::set_appearance(matte_rgba, show_checkerboard);+}++#[tauri::command]+fn native_engine_set_camera(camera: ink_engine::CameraState) {+ native_engine::set_camera(camera);+}++#[tauri::command]+fn native_engine_set_cursor(config: ink_engine::CursorConfig) {+ native_engine::set_cursor(config);+}++#[tauri::command]+fn native_engine_set_brush(params: ink_engine::BrushParams) {+ native_engine::set_brush(params);+}++#[tauri::command]+fn native_engine_set_policy(policy: ink_engine::InteractionPolicy) {+ native_engine::set_policy(policy);+}++#[tauri::command]+fn native_engine_clear_canvas() {+ native_engine::clear_canvas();+}++#[tauri::command]+fn native_engine_get_diagnostics() -> ink_engine::EngineDiagnostics {+ native_engine::get_diagnostics()+}++// ---------------------------------------------------------------------------+// Phase 2: Native Rust Document Store, Layer Tree, CoW Undo/Redo & Zero-Copy I/O+// ---------------------------------------------------------------------------++#[tauri::command]+fn native_engine_create_document(+ doc_id: String,+ name: String,+ dimensions: ink_engine::CanvasDimensions,+ color_mode: Option<ink_engine::CanvasColorMode>,+ background_hex: Option<String>,+ default_tone_frequency: Option<f32>,+) -> ink_engine::DocumentMetaSnapshot {+ native_docs::create_document(+ doc_id,+ name,+ dimensions,+ color_mode.unwrap_or(ink_engine::CanvasColorMode::Color),+ background_hex.as_deref().unwrap_or("#ffffff"),+ default_tone_frequency.unwrap_or(60.0),+ )+}++#[tauri::command]+async fn native_engine_open_file(+ app: tauri::AppHandle,+ doc_id: String,+ path: String,+) -> Result<native_docs::OpenNativeDocumentResult, String> {+ let allowed_dirs = get_allowed_base_dirs(&app);+ let (canonical, _) = validate_read_path(&path, &allowed_dirs).await?;+ let file_name = canonical+ .file_name()+ .map(|n| n.to_string_lossy().into_owned())+ .unwrap_or_else(|| "Untitled.ink".to_string());+ let bytes = tokio::fs::read(&canonical)+ .await+ .map_err(|e| format!("Failed to read file {}: {}", canonical.display(), e))?;+ tokio::task::spawn_blocking(move || {+ native_docs::open_document_from_bytes(doc_id, file_name, &bytes)+ })+ .await+ .map_err(|e| format!("Native open worker failed: {e}"))?+}++#[tauri::command]+async fn native_engine_open_file_bytes(+ request: tauri::ipc::Request<'_>,+) -> Result<native_docs::OpenNativeDocumentResult, String> {+ let doc_id = header_str(&request, "x-doc-id")?;+ let file_name = header_str(&request, "x-file-name")?;+ let body = raw_body(&request)?;+ if body.len() as u64 > MAX_READ_FILE_BYTES {+ return Err("File exceeds 512 MB safety limit".to_string());+ }+ let owned = body.to_vec();+ tokio::task::spawn_blocking(move || {+ native_docs::open_document_from_bytes(doc_id, file_name, &owned)+ })+ .await+ .map_err(|e| format!("Native open bytes worker failed: {e}"))?+}++#[tauri::command]+async fn native_engine_save_ink(+ app: tauri::AppHandle,+ doc_id: String,+ path: String,+) -> Result<native_docs::SaveNativeInkResult, String> {+ let allowed_dirs = get_allowed_base_dirs(&app);+ let target = validate_write_path(&path, &allowed_dirs).await?;+ let doc_id_clone = doc_id.clone();+ let serialized = tokio::task::spawn_blocking(move || {+ native_docs::serialize_document_ink(&doc_id_clone)+ })+ .await+ .map_err(|e| format!("Native .ink serialize worker failed: {e}"))??;++ let bytes_written = serialized.bytes.len();+ let preview_data_url = serialized.preview_data_url;+ let tile_count = serialized.tile_count;+ let mask_count = serialized.mask_count;+ let zip_bytes = serialized.bytes;+ let target_for_write = target.clone();+ tokio::task::spawn_blocking(move || {+ save_dialog::write_file_atomic(&target_for_write, &zip_bytes)+ })+ .await+ .map_err(|e| format!("Atomic .ink save worker failed: {e}"))??;++ register_allowed_path(&target);+ Ok(native_docs::SaveNativeInkResult {+ path: Some(target.to_string_lossy().into_owned()),+ bytes_written,+ preview_data_url,+ tile_count,+ mask_count,+ })+}++#[tauri::command]+async fn native_engine_save_ink_with_dialog(+ app: tauri::AppHandle,+ doc_id: String,+ suggested_name: String,+ initial_dir: Option<String>,+) -> Result<native_docs::SaveNativeInkResult, String> {+ let pick = save_dialog::pick_save_path_with_dialog(+ &app,+ suggested_name,+ vec![save_dialog::SaveFilterSpec {+ name: "InkStudio Document".to_string(),+ extensions: vec!["ink".to_string()],+ }],+ 0,+ Some("Save InkStudio Document".to_string()),+ initial_dir,+ )+ .await?;+ if pick.canceled {+ return Ok(native_docs::SaveNativeInkResult {+ path: None,+ bytes_written: 0,+ preview_data_url: None,+ tile_count: 0,+ mask_count: 0,+ });+ }+ let chosen_path = pick+ .path+ .ok_or_else(|| "Save dialog returned no path".to_string())?;+ register_allowed_write_path(Path::new(&chosen_path));+ native_engine_save_ink(app, doc_id, chosen_path).await+}++#[tauri::command]+fn native_engine_switch_document(doc_id: String) -> Result<ink_engine::DocumentMetaSnapshot, String> {+ native_docs::switch_document(&doc_id)+}++#[tauri::command]+fn native_engine_close_document(doc_id: String) -> bool {+ native_docs::close_document(&doc_id)+}++#[tauri::command]+fn native_engine_get_document_state(+ doc_id: Option<String>,+) -> Option<ink_engine::DocumentMetaSnapshot> {+ native_docs::get_document_state(doc_id.as_deref())+}++#[tauri::command]+fn native_engine_add_layer(+ doc_id: String,+ layer: ink_engine::LayerNodeMeta,+ insert_index: Option<usize>,+ record_history: Option<bool>,+) -> Result<ink_engine::DocumentMetaSnapshot, String> {+ native_docs::add_layer(&doc_id, layer, insert_index, record_history.unwrap_or(true))+}++#[tauri::command]+fn native_engine_delete_layer(+ doc_id: String,+ layer_id: String,+ record_history: Option<bool>,+) -> Result<ink_engine::DocumentMetaSnapshot, String> {+ native_docs::delete_layer(&doc_id, &layer_id, record_history.unwrap_or(true))+}++#[tauri::command]+fn native_engine_duplicate_layer(+ doc_id: String,+ source_layer_id: String,+ new_layer_id: String,+ record_history: Option<bool>,+) -> Result<ink_engine::DocumentMetaSnapshot, String> {+ native_docs::duplicate_layer(+ &doc_id,+ &source_layer_id,+ new_layer_id,+ record_history.unwrap_or(true),+ )+}++#[tauri::command]+fn native_engine_reorder_layers(+ doc_id: String,+ ordered_ids: Vec<String>,+ parent_overrides: Option<std::collections::HashMap<String, Option<String>>>,+ record_history: Option<bool>,+) -> Result<ink_engine::DocumentMetaSnapshot, String> {+ native_docs::reorder_layers(+ &doc_id,+ &ordered_ids,+ parent_overrides.as_ref(),+ record_history.unwrap_or(true),+ )+}++#[tauri::command]+fn native_engine_update_layer(+ doc_id: String,+ layer_id: String,+ patch: ink_engine::LayerPropsPatch,+) -> Result<ink_engine::DocumentMetaSnapshot, String> {+ native_docs::update_layer(&doc_id, &layer_id, patch)+}++#[tauri::command]+fn native_engine_sync_layers(+ doc_id: String,+ layers: Vec<ink_engine::LayerNodeMeta>,+ active_layer_id: Option<String>,+) -> Result<ink_engine::DocumentMetaSnapshot, String> {+ native_docs::sync_layers(&doc_id, layers, active_layer_id)+}++#[tauri::command]+fn native_engine_clear_layer(+ doc_id: String,+ layer_id: String,+ record_history: Option<bool>,+) -> Result<ink_engine::DocumentMetaSnapshot, String> {+ native_docs::clear_layer(&doc_id, &layer_id, record_history.unwrap_or(true))+}++#[tauri::command]+fn native_engine_merge_down(+ doc_id: String,+ src_layer_id: String,+) -> Result<ink_engine::DocumentMetaSnapshot, String> {+ native_docs::merge_down(&doc_id, &src_layer_id)+}++#[tauri::command]+fn native_engine_merge_folder(+ doc_id: String,+ folder_id: String,+ new_layer_id: String,+) -> Result<ink_engine::DocumentMetaSnapshot, String> {+ native_docs::merge_folder(&doc_id, &folder_id, new_layer_id)+}++#[tauri::command]+fn native_engine_add_mask(+ doc_id: String,+ layer_id: String,+ default_value: Option<u8>,+ record_history: Option<bool>,+) -> Result<ink_engine::DocumentMetaSnapshot, String> {+ native_docs::add_mask(+ &doc_id,+ &layer_id,+ default_value.unwrap_or(255),+ record_history.unwrap_or(true),+ )+}++#[tauri::command]+fn native_engine_remove_mask(+ doc_id: String,+ layer_id: String,+ apply_to_raster: Option<bool>,+ record_history: Option<bool>,+) -> Result<ink_engine::DocumentMetaSnapshot, String> {+ native_docs::remove_mask(+ &doc_id,+ &layer_id,+ apply_to_raster.unwrap_or(false),+ record_history.unwrap_or(true),+ )+}++#[tauri::command]+fn native_engine_resize_canvas(+ doc_id: String,+ dimensions: ink_engine::CanvasDimensions,+ offset_x: Option<i32>,+ offset_y: Option<i32>,+ scale_content: Option<bool>,+ bg_hex: Option<String>,+ record_history: Option<bool>,+) -> Result<ink_engine::DocumentMetaSnapshot, String> {+ native_docs::resize_canvas(+ &doc_id,+ dimensions,+ offset_x.unwrap_or(0),+ offset_y.unwrap_or(0),+ scale_content.unwrap_or(false),+ bg_hex.as_deref().unwrap_or("#ffffff"),+ record_history.unwrap_or(true),+ )+}++#[tauri::command]+async fn native_engine_ingest_dirty_rect(+ request: tauri::ipc::Request<'_>,+) -> Result<ink_engine::DocumentMetaSnapshot, String> {+ let doc_id = header_str(&request, "x-doc-id")?;+ let layer_id = header_str(&request, "x-layer-id")?;+ let x: i32 = header_parse(&request, "x-x")?;+ let y: i32 = header_parse(&request, "x-y")?;+ let width: u32 = header_parse(&request, "x-width")?;+ let height: u32 = header_parse(&request, "x-height")?;+ let is_mask: bool = header_opt_parse::<u8>(&request, "x-is-mask").unwrap_or(0) != 0;+ let record_history: bool = header_opt_parse::<u8>(&request, "x-record-history").unwrap_or(1) != 0;+ let action_type =+ header_opt_str(&request, "x-action-type").unwrap_or_else(|| "raster".to_string());+ let label = header_opt_str(&request, "x-label").unwrap_or_else(|| "Edit Layer".to_string());+ let peer_id = header_opt_str(&request, "x-peer-id");+ let stroke_id = header_opt_str(&request, "x-stroke-id");+ let body = raw_body(&request)?.to_vec();++ tokio::task::spawn_blocking(move || {+ native_docs::ingest_dirty_rect(+ &doc_id,+ &layer_id,+ ink_engine::RectI32::new(x, y, width, height),+ &body,+ is_mask,+ record_history,+ &action_type,+ &label,+ peer_id,+ stroke_id,+ )+ })+ .await+ .map_err(|e| format!("Native dirty-rect ingest worker failed: {e}"))?+}++#[tauri::command]+fn native_engine_undo(doc_id: String) -> Result<native_docs::NativeHistoryMutationResult, String> {+ native_docs::undo(&doc_id)+}++#[tauri::command]+fn native_engine_redo(doc_id: String) -> Result<native_docs::NativeHistoryMutationResult, String> {+ native_docs::redo(&doc_id)+}++#[tauri::command]+fn native_engine_jump_history(+ doc_id: String,+ target_index: usize,+) -> Result<native_docs::NativeHistoryMutationResult, String> {+ native_docs::jump_history(&doc_id, target_index)+}++#[tauri::command]+fn native_engine_selective_undo(+ doc_id: String,+ peer_id: Option<String>,+ stroke_id: Option<String>,+) -> Result<native_docs::NativeHistoryMutationResult, String> {+ native_docs::selective_undo(&doc_id, peer_id.as_deref(), stroke_id.as_deref())+}++#[tauri::command]+fn native_engine_selective_redo(+ doc_id: String,+ peer_id: Option<String>,+) -> Result<native_docs::NativeHistoryMutationResult, String> {+ native_docs::selective_redo(&doc_id, peer_id.as_deref())+}++#[tauri::command]+fn native_engine_push_history_meta(+ doc_id: String,+ action_type: String,+ label: String,+ layer_id: Option<String>,+ document_state_delta: Option<serde_json::Value>,+ coalesce_key: Option<String>,+) -> Result<ink_engine::HistoryStateSnapshot, String> {+ native_docs::push_history_meta(+ &doc_id,+ action_type,+ label,+ layer_id,+ document_state_delta,+ coalesce_key,+ )+}++#[tauri::command]+fn native_engine_get_history(doc_id: String) -> Result<ink_engine::HistoryStateSnapshot, String> {+ native_docs::get_history(&doc_id)+}++#[tauri::command]+fn native_engine_reset_history(+ doc_id: String,+ label: Option<String>,+) -> Result<ink_engine::HistoryStateSnapshot, String> {+ native_docs::reset_history(&doc_id, label)+}++#[tauri::command]+fn native_engine_get_memory_stats() -> ink_engine::MemoryStats {+ native_docs::get_memory_stats()+}++#[tauri::command]+fn native_engine_set_memory_budget(+ input: native_docs::NativeMemoryBudgetInput,+) -> Result<ink_engine::MemoryStats, String> {+ native_docs::set_memory_budget(input)+}++#[tauri::command]+fn native_engine_purge_memory() -> Result<ink_engine::MemoryStats, String> {+ native_docs::purge_memory()+}++#[tauri::command]+fn native_engine_request_thumbnails(+ app: tauri::AppHandle,+ doc_id: String,+ layer_ids: Option<Vec<String>>,+) {+ native_docs::spawn_thumbnail_generation(app, doc_id, layer_ids.unwrap_or_default());+}++#[tauri::command]+async fn native_engine_capture_timelapse_frame(+ app: tauri::AppHandle,+ doc_id: String,+ session_id: String,+ frame_index: u32,+ max_dim: Option<u32>,+ capture_area: Option<String>,+) -> Result<native_docs::NativeTimelapseCaptureResult, String> {+ native_docs::capture_timelapse_frame(+ &app,+ doc_id,+ session_id,+ frame_index,+ max_dim.unwrap_or(1920),+ capture_area,+ )+ .await+}++#[tauri::command]+async fn native_engine_recovery_checkpoint(+ app: tauri::AppHandle,+ doc_id: String,+ session_id: String,+ manifest_json: Option<String>,+) -> Result<native_docs::NativeRecoveryCheckpointResult, String> {+ native_docs::recovery_checkpoint_document(&app, doc_id, session_id, manifest_json).await+}++#[tauri::command]+async fn native_engine_recovery_restore(+ app: tauri::AppHandle,+ session_id: String,+ doc_id: String,+) -> Result<ink_engine::DocumentMetaSnapshot, String> {+ native_docs::recovery_restore_document(&app, session_id, doc_id).await+}+#[tauri::command]fn os_hotkeys_sync(window: tauri::WebviewWindow,@@ -1279,6 +1769,9 @@ pub fn run() {}}std::env::set_var("WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS", merged);+ // Ensure WebView2 initializes with a transparent default background (ARGB 0x00000000)+ // so the DirectComposition DX12 canvas visual underneath is visible without white flashes.+ std::env::set_var("WEBVIEW2_DEFAULT_BACKGROUND_COLOR", "0");}let builder = tauri::Builder::default();@@ -1326,23 +1819,31 @@ pub fn run() {if let Some(main_window) = app.get_webview_window("main") {let _ = main_window.maximize();#[cfg(target_os = "windows")]- let _ = main_window.with_webview(|webview| {- use webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Settings3;- use windows_core::Interface;- unsafe {- if let Ok(core) = webview.controller().CoreWebView2() {- if let Ok(settings) = core.Settings() {- // Disable built-in browser accelerator keys (Ctrl+R, F5, Ctrl+Shift+R,- // Alt+Left/Right, Ctrl+P, Ctrl+F, etc.) at the WebView2 layer so accidental- // refreshes can never wipe unsaved artwork. Standard editing keys and DOM- // keydown events (including Ink Studio shortcuts) continue to work normally.- if let Ok(settings3) = settings.cast::<ICoreWebView2Settings3>() {- let _ = settings3.SetAreBrowserAcceleratorKeysEnabled(false);+ {+ if let Err(err) = native_engine::init_for_main_window(+ app.handle().clone(),+ &main_window,+ ) {+ eprintln!("[native_engine] initialization failed (falling back): {err}");+ // Still disable built-in browser accelerator keys if native engine failed+ let _ = main_window.with_webview(|webview| {+ use webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Settings3;+ use windows_core::Interface;+ unsafe {+ if let Ok(core) = webview.controller().CoreWebView2() {+ if let Ok(settings) = core.Settings() {+ if let Ok(settings3) =+ settings.cast::<ICoreWebView2Settings3>()+ {+ let _ = settings3+ .SetAreBrowserAcceleratorKeysEnabled(false);+ }+ }}}- }+ });}- });+ }}}Ok(())@@ -1362,9 +1863,6 @@ pub fn run() {is_cloudflared_installed,get_os_username,get_local_lan_ip,- save_undo_tile_cache,- load_undo_tile_cache,- clear_undo_tile_cache,delete_file_from_disk,read_file_from_disk,read_file_binary,@@ -1406,6 +1904,53 @@ pub fn run() {tablet_start_input,tablet_stop_input,tablet_get_status,+ native_engine_is_active,+ native_engine_set_viewport,+ native_engine_set_occluded_rects,+ native_engine_set_document,+ native_engine_set_appearance,+ native_engine_set_camera,+ native_engine_set_cursor,+ native_engine_set_brush,+ native_engine_set_policy,+ native_engine_clear_canvas,+ native_engine_get_diagnostics,+ native_engine_create_document,+ native_engine_open_file,+ native_engine_open_file_bytes,+ native_engine_save_ink,+ native_engine_save_ink_with_dialog,+ native_engine_switch_document,+ native_engine_close_document,+ native_engine_get_document_state,+ native_engine_add_layer,+ native_engine_delete_layer,+ native_engine_duplicate_layer,+ native_engine_reorder_layers,+ native_engine_update_layer,+ native_engine_sync_layers,+ native_engine_clear_layer,+ native_engine_merge_down,+ native_engine_merge_folder,+ native_engine_add_mask,+ native_engine_remove_mask,+ native_engine_resize_canvas,+ native_engine_ingest_dirty_rect,+ native_engine_undo,+ native_engine_redo,+ native_engine_jump_history,+ native_engine_selective_undo,+ native_engine_selective_redo,+ native_engine_push_history_meta,+ native_engine_get_history,+ native_engine_reset_history,+ native_engine_get_memory_stats,+ native_engine_set_memory_budget,+ native_engine_purge_memory,+ native_engine_request_thumbnails,+ native_engine_capture_timelapse_frame,+ native_engine_recovery_checkpoint,+ native_engine_recovery_restore,os_hotkeys_sync,os_hotkeys_stop,get_system_hardware_info,@@ -1432,6 +1977,7 @@ pub fn run() {if let tauri::RunEvent::Exit = event {os_hotkeys::stop_os_hotkeys();tablet_input::stop_tablet_input();+ native_engine::shutdown();server::shutdown_sync();}});diff --git a/src-tauri/src/native_docs.rs b/src-tauri/src/native_docs.rsnew file mode 100644index 0000000..eee76e9--- /dev/null+++ b/src-tauri/src/native_docs.rs@@ -0,0 +1,1349 @@+//! Phase 2 In-Process Rust Document Store, Zero-Copy `.clip`/`.psd`/`.ink` Hydration,+//! In-Process Scratch Disk Backend, Async Thumbnails, Timelapse & Crash Recovery Bridge.+//!+//! Eliminates all full-res pixel IPC between React and Rust: React receives ONLY compact+//! metadata (`DocumentMetaSnapshot`, `HistoryStateSnapshot`, `MemoryStats`) and tiny 64x64+//! layer/mask thumbnails.++use crate::clip_parser;+use crate::doc_wire::ParsedDocumentAssembled;+use crate::native_engine;+use crate::psd_parser;+use crate::recovery;+use crate::scratch_disk;+use crate::timelapse;+use ink_engine::document::{+ BlendMode, CanvasColorMode, CanvasDimensions, Document, DocumentManager, DocumentMetaSnapshot,+ ExpressionColor, LayerNode, LayerNodeMeta, LayerPropsPatch, LayerType,+};+use ink_engine::history::{HistoryItemMeta, HistoryStateSnapshot, SelectiveUndoOutcome};+use ink_engine::io::{+ compositor_cpu, encode_document_checkpoint, encode_rgba8_to_png, parse_ink_document,+ png_bytes_to_data_url, replay_recovery_into_document, serialize_ink_document,+ SerializedInkResult, WalRawEntry,+};+use ink_engine::memory::{MemoryBudgetConfig, MemoryStats, ScratchBackend, ScratchTileWrite};+use ink_engine::tiles::{+ parse_hex_rgba8, RectI32, SparseLayerGrid, TileCoord, TileData, TileFormat, TileKind,+};+use ink_engine::ThumbnailUpdate;+use parking_lot::RwLock;+use rayon::prelude::*;+use serde::{Deserialize, Serialize};+use std::collections::HashMap;+use std::sync::{Arc, LazyLock, Mutex};+use tauri::Emitter;++/// In-process [`ScratchBackend`] wired directly into `src-tauri/src/scratch_disk.rs`+/// with zero Tauri IPC overhead.+pub struct TauriScratchDiskBackend;++impl ScratchBackend for TauriScratchDiskBackend {+ fn init_session(&self, session_id: &str) -> Result<(), String> {+ scratch_disk::init_scratch_disk_sync(session_id).map(|_| ())+ }++ fn write_tiles(&self, session_id: &str, tiles: Vec<ScratchTileWrite>) -> Result<usize, String> {+ let payloads = tiles+ .into_iter()+ .map(|t| scratch_disk::TileWritePayload {+ layer_id: t.layer_key,+ tile_x: t.tx,+ tile_y: t.ty,+ data: t.data,+ })+ .collect();+ scratch_disk::write_tiles_sync(session_id, payloads)+ }++ fn read_tile(+ &self,+ session_id: &str,+ layer_key: &str,+ tx: i32,+ ty: i32,+ ) -> Result<Vec<u8>, String> {+ scratch_disk::read_tile_sync(session_id, layer_key, tx, ty)+ }++ fn clear_session(&self, session_id: &str) -> Result<(), String> {+ scratch_disk::clear_scratch_disk_sync(session_id)+ }+}++static ATTACHED_DOCS: LazyLock<Mutex<Option<Arc<RwLock<DocumentManager>>>>> =+ LazyLock::new(|| Mutex::new(None));++static FALLBACK_DOCS: LazyLock<Arc<RwLock<DocumentManager>>> = LazyLock::new(|| {+ Arc::new(RwLock::new(DocumentManager::new(+ MemoryBudgetConfig::default(),+ Arc::new(TauriScratchDiskBackend),+ )))+});++/// Attaches the active `EngineHandle`'s shared `DocumentManager` so all Tauri commands operate+/// on the exact same in-memory document store that the DX12 render thread reads.+pub fn attach_engine_documents(docs: Arc<RwLock<DocumentManager>>) {+ if let Ok(mut guard) = ATTACHED_DOCS.lock() {+ *guard = Some(docs);+ }+}++/// Detaches the DX12 `EngineHandle`'s `DocumentManager` on shutdown.+pub fn detach_engine_documents() {+ if let Ok(mut guard) = ATTACHED_DOCS.lock() {+ *guard = None;+ }+}++/// Returns the active [`DocumentManager`] handle (either the running DX12 engine's store or+/// the in-process fallback store for headless/test execution).+pub fn documents_handle() -> Arc<RwLock<DocumentManager>> {+ if let Ok(guard) = ATTACHED_DOCS.lock() {+ if let Some(ref docs) = *guard {+ return Arc::clone(docs);+ }+ }+ Arc::clone(&FALLBACK_DOCS)+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct OpenNativeDocumentResult {+ pub doc: DocumentMetaSnapshot,+ pub preview_data_url: Option<String>,+ pub source_format: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SaveNativeInkResult {+ pub path: Option<String>,+ pub bytes_written: usize,+ pub preview_data_url: Option<String>,+ pub tile_count: usize,+ pub mask_count: usize,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeHistoryMutationResult {+ pub doc: DocumentMetaSnapshot,+ pub dimensions_changed: bool,+ pub layers_changed: bool,+ pub changed_layer_ids: Vec<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub document_state_delta: Option<serde_json::Value>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub selective_outcome: Option<SelectiveUndoOutcome>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeMemoryBudgetInput {+ #[serde(default)]+ pub ram_budget_mb: Option<u64>,+ #[serde(default)]+ pub vram_budget_mb: Option<u64>,+ #[serde(default)]+ pub max_history_steps: Option<usize>,+ #[serde(default)]+ pub offload_inactive_tabs: Option<bool>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeTimelapseCaptureResult {+ pub width: u32,+ pub height: u32,+ pub bytes: usize,+ pub frame_index: u32,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeRecoveryCheckpointResult {+ pub snapshot_bytes: usize,+ pub thumbnail_bytes: usize,+}++fn parse_blend_mode_str(s: &str) -> BlendMode {+ serde_json::from_value(serde_json::Value::String(s.to_string())).unwrap_or(BlendMode::Normal)+}++fn parse_expression_color_str(s: Option<&str>) -> Option<ExpressionColor> {+ match s {+ Some("monochrome") => Some(ExpressionColor::Monochrome),+ Some("gray") => Some(ExpressionColor::Gray),+ Some("color") => Some(ExpressionColor::Color),+ _ => None,+ }+}++fn render_layer_thumb_url(+ node: &LayerNode,+ doc_w: u32,+ doc_h: u32,+ scratch: Option<&dyn ScratchBackend>,+) -> Option<String> {+ let (tw, th, rgba) =+ compositor_cpu::render_layer_thumbnail_rgba(node, doc_w, doc_h, 64, 64, scratch).ok()?;+ let png = encode_rgba8_to_png(tw, th, &rgba).ok()?;+ Some(png_bytes_to_data_url(&png))+}++fn render_mask_thumb_url(+ node: &LayerNode,+ doc_w: u32,+ doc_h: u32,+ scratch: Option<&dyn ScratchBackend>,+) -> Option<String> {+ let (tw, th, rgba) =+ compositor_cpu::render_mask_thumbnail_rgba(node, doc_w, doc_h, 64, 64, scratch).ok()?;+ let png = encode_rgba8_to_png(tw, th, &rgba).ok()?;+ Some(png_bytes_to_data_url(&png))+}++/// Hydrates a [`ParsedDocumentAssembled`] (from `.clip` or `.psd`/`.psb`) directly into an+/// `ink-engine` [`Document`] in parallel using Rayon — zero `INKD` serialization and zero+/// JS pixel copies!+pub fn hydrate_assembled_document(+ parsed: ParsedDocumentAssembled,+ doc_id: impl Into<String>,+ name: impl Into<String>,+ max_history_steps: usize,+) -> (Document, Option<String>) {+ let color_mode = match parsed.color_mode.as_str() {+ "grayscale" => CanvasColorMode::Grayscale,+ _ => CanvasColorMode::Color,+ };+ let dims = CanvasDimensions {+ width: parsed.width.max(1),+ height: parsed.height.max(1),+ dpi: parsed.dpi.max(1),+ };++ let preview_data_url = parsed+ .preview+ .as_ref()+ .map(|(bytes, mime)| format!("data:{};base64,{}", mime, ink_engine::io::to_base64(bytes)));++ // Parallel hydrate each layer's sparse tiles, masks, and 64x64 thumbnails+ let mut layer_nodes: Vec<LayerNode> = parsed+ .layers+ .into_par_iter()+ .map(|al| {+ let is_folder = al.layer_type == "folder";+ let expr = parse_expression_color_str(al.expression_color.as_deref());+ let tile_fmt = expr+ .map(|e| e.to_tile_format())+ .unwrap_or(TileFormat::Color32Bit);++ let mut meta = if is_folder {+ LayerNodeMeta::new_folder(al.id.clone(), al.name.clone())+ } else {+ LayerNodeMeta::new_raster(al.id.clone(), al.name.clone())+ };+ meta.visible = al.visible;+ meta.opacity = al.opacity.clamp(0.0, 1.0);+ meta.blend_mode = parse_blend_mode_str(&al.blend_mode);+ meta.locked = al.locked;+ meta.alpha_locked = Some(al.alpha_locked);+ meta.clipped = Some(al.clipped);+ meta.collapsed = Some(al.collapsed);+ meta.parent_id = al.parent_id.clone();+ meta.expression_color = expr;+ meta.mono_express_black = al.mono_express_black;+ meta.mono_express_white = al.mono_express_white;+ meta.layer_color_enabled = al.layer_color_enabled;+ meta.layer_color = al.layer_color.clone();+ meta.layer_sub_color = al.layer_sub_color.clone();++ let mut grid = SparseLayerGrid::new(tile_fmt);++ if !is_folder {+ if let Some(ref hex) = al.solid_fill_hex {+ if let Some(rgba) = parse_hex_rgba8(hex) {+ grid.fill_solid_layer(dims.width, dims.height, rgba);+ }+ }+ for raw_tile in al.tiles {+ let coord = TileCoord::new(raw_tile.tx, raw_tile.ty);+ // Convert RGBA8 tile into target expression format + auto-compact uniform solid tiles+ let td = match tile_fmt {+ TileFormat::Color32Bit => TileData::from_raw_auto_compact(+ TileFormat::Color32Bit,+ TileKind::Raster,+ raw_tile.rgba,+ ),+ TileFormat::Grayscale8Bit => {+ let mut gray = vec![0u8; ink_engine::tiles::BYTES_8BIT];+ ink_engine::tiles::pack_rgba8_to_8bit(&raw_tile.rgba, &mut gray);+ TileData::from_raw_auto_compact(+ TileFormat::Grayscale8Bit,+ TileKind::Raster,+ gray,+ )+ }+ TileFormat::Monochrome1Bit => {+ let mut mono = vec![0u8; ink_engine::tiles::BYTES_1BIT];+ ink_engine::tiles::pack_rgba8_to_1bit(&raw_tile.rgba, &mut mono, 128);+ TileData::from_raw_auto_compact(+ TileFormat::Monochrome1Bit,+ TileKind::Raster,+ mono,+ )+ }+ TileFormat::Rgba16Float => {+ let mut f16b = vec![0u8; ink_engine::tiles::BYTES_16F];+ ink_engine::tiles::rgba8_to_rgba16f(&raw_tile.rgba, &mut f16b);+ TileData::from_raw_auto_compact(+ TileFormat::Rgba16Float,+ TileKind::Raster,+ f16b,+ )+ }+ };+ grid.tiles.insert(coord, Arc::new(td));+ }+ if !grid.tiles.is_empty() {+ grid.mark_all_lods_dirty();+ }+ }++ if let Some(raw_mask) = al.mask {+ grid.init_mask(raw_mask.default_color);+ if raw_mask.width > 0 && raw_mask.height > 0 && !raw_mask.gray.is_empty() {+ let rect = RectI32::new(+ raw_mask.left,+ raw_mask.top,+ raw_mask.width,+ raw_mask.height,+ );+ let _ = grid.write_mask8_rect(&raw_mask.gray, rect, None);+ }+ meta.has_mask = true;+ meta.mask_enabled = Some(raw_mask.enabled);+ meta.mask_linked = Some(raw_mask.linked);+ }++ let mut node = LayerNode { meta, grid };+ if !is_folder && !node.grid.tiles.is_empty() {+ node.meta.thumbnail_url = render_layer_thumb_url(&node, dims.width, dims.height, None);+ }+ if node.grid.has_mask {+ node.meta.mask_thumbnail_url =+ render_mask_thumb_url(&node, dims.width, dims.height, None);+ }+ node+ })+ .collect();++ if layer_nodes.is_empty() {+ let mut bg = LayerNode {+ meta: LayerNodeMeta::new_raster("layer-bg", "Background"),+ grid: SparseLayerGrid::new(TileFormat::Color32Bit),+ };+ bg.grid+ .fill_solid_layer(dims.width, dims.height, [255, 255, 255, 255]);+ layer_nodes.push(bg);+ }++ let active_layer_id = layer_nodes+ .iter()+ .find(|l| l.meta.layer_type == LayerType::Raster && l.meta.visible)+ .or_else(|| layer_nodes.first())+ .map(|l| l.meta.id.clone());++ let mut doc = Document::from_layers(+ doc_id,+ name,+ dims,+ color_mode,+ layer_nodes,+ active_layer_id,+ max_history_steps,+ );+ doc.preview_data_url = preview_data_url.clone();+ (doc, preview_data_url)+}++/// Creates a blank multi-layer document directly in Rust and activates it.+pub fn create_document(+ doc_id: String,+ name: String,+ dimensions: CanvasDimensions,+ color_mode: CanvasColorMode,+ background_hex: &str,+ default_tone_frequency: f32,+) -> DocumentMetaSnapshot {+ let docs = documents_handle();+ let snap = {+ let mut mgr = docs.write();+ let snap = mgr.create_document(+ doc_id,+ name,+ dimensions,+ color_mode,+ background_hex,+ default_tone_frequency,+ );+ let _ = mgr.enforce_memory_budget();+ snap+ };+ native_engine::sync_active_document();+ snap+}++/// Opens a `.ink`, `.clip`/`.csp`/`.lip`, or `.psd`/`.psb` file directly from raw bytes into+/// Rust `DocumentManager` without sending any full-res pixel arrays across IPC.+pub fn open_document_from_bytes(+ doc_id: String,+ file_name: String,+ bytes: &[u8],+) -> Result<OpenNativeDocumentResult, String> {+ let lower = file_name.to_ascii_lowercase();+ let max_history = documents_handle().read().budget_config().max_history_steps;++ let (doc, preview_data_url, source_format) = if lower.ends_with(".clip")+ || lower.ends_with(".csp")+ || lower.ends_with(".lip")+ {+ let assembled = clip_parser::parse_clip_assembled(bytes)?;+ let (doc, preview) = hydrate_assembled_document(assembled, doc_id, file_name, max_history);+ (doc, preview, "clip".to_string())+ } else if lower.ends_with(".psd") || lower.ends_with(".psb") {+ let assembled = psd_parser::parse_psd_assembled(bytes)?;+ let (doc, preview) = hydrate_assembled_document(assembled, doc_id, file_name, max_history);+ (doc, preview, "psd".to_string())+ } else {+ // Default: InkStudio `.ink` v2 ZIP archive (parallel decode directly into SparseLayerGrid)+ let doc = parse_ink_document(bytes, doc_id, &file_name, max_history)?;+ let preview = doc.preview_data_url.clone();+ (doc, preview, "ink".to_string())+ };++ let docs = documents_handle();+ let meta = {+ let mut mgr = docs.write();+ let meta = mgr.insert_and_activate(doc);+ let _ = mgr.enforce_memory_budget();+ meta+ };+ native_engine::sync_active_document();++ Ok(OpenNativeDocumentResult {+ doc: meta,+ preview_data_url,+ source_format,+ })+}++/// Serializes an open Rust document directly into `.ink` v2 ZIP bytes (parallelized with Rayon).+pub fn serialize_document_ink(doc_id: &str) -> Result<SerializedInkResult, String> {+ let docs = documents_handle();+ let mgr = docs.read();+ let scratch = mgr.scratch_backend();+ let doc = mgr+ .get_document(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ serialize_ink_document(doc, 1, Some(scratch.as_ref()))+}++pub fn switch_document(doc_id: &str) -> Result<DocumentMetaSnapshot, String> {+ let docs = documents_handle();+ let snap = {+ let mut mgr = docs.write();+ mgr.switch_document(doc_id)?+ };+ native_engine::sync_active_document();+ Ok(snap)+}++pub fn close_document(doc_id: &str) -> bool {+ let docs = documents_handle();+ let removed = {+ let mut mgr = docs.write();+ mgr.close_document(doc_id)+ };+ native_engine::sync_active_document();+ removed+}++pub fn get_document_state(doc_id: Option<&str>) -> Option<DocumentMetaSnapshot> {+ let docs = documents_handle();+ let mgr = docs.read();+ let doc = match doc_id {+ Some(id) => mgr.get_document(id),+ None => mgr.active_document(),+ }?;+ Some(doc.snapshot_meta())+}++pub fn add_layer(+ doc_id: &str,+ meta: LayerNodeMeta,+ insert_index: Option<usize>,+ record_history: bool,+) -> Result<DocumentMetaSnapshot, String> {+ let docs = documents_handle();+ let snap = {+ let mut mgr = docs.write();+ let doc = mgr+ .get_document_mut(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ doc.add_layer(meta, insert_index, true, record_history);+ doc.snapshot_meta()+ };+ native_engine::sync_active_document();+ Ok(snap)+}++pub fn delete_layer(+ doc_id: &str,+ layer_id: &str,+ record_history: bool,+) -> Result<DocumentMetaSnapshot, String> {+ let docs = documents_handle();+ let snap = {+ let mut mgr = docs.write();+ let doc = mgr+ .get_document_mut(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ doc.delete_layer(layer_id, record_history)?;+ doc.snapshot_meta()+ };+ native_engine::sync_active_document();+ Ok(snap)+}++pub fn duplicate_layer(+ doc_id: &str,+ source_layer_id: &str,+ new_layer_id: String,+ record_history: bool,+) -> Result<DocumentMetaSnapshot, String> {+ let docs = documents_handle();+ let snap = {+ let mut mgr = docs.write();+ let doc = mgr+ .get_document_mut(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ doc.duplicate_layer(source_layer_id, new_layer_id, record_history)?;+ doc.snapshot_meta()+ };+ native_engine::sync_active_document();+ Ok(snap)+}++pub fn reorder_layers(+ doc_id: &str,+ ordered_ids: &[String],+ parent_overrides: Option<&HashMap<String, Option<String>>>,+ record_history: bool,+) -> Result<DocumentMetaSnapshot, String> {+ let docs = documents_handle();+ let snap = {+ let mut mgr = docs.write();+ let doc = mgr+ .get_document_mut(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ doc.reorder_layers(ordered_ids, parent_overrides, record_history)?;+ doc.snapshot_meta()+ };+ native_engine::sync_active_document();+ Ok(snap)+}++pub fn update_layer(+ doc_id: &str,+ layer_id: &str,+ patch: LayerPropsPatch,+) -> Result<DocumentMetaSnapshot, String> {+ let docs = documents_handle();+ let snap = {+ let mut mgr = docs.write();+ let scratch = Arc::clone(mgr.scratch_backend());+ let doc = mgr+ .get_document_mut(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ doc.update_layer_props(layer_id, patch, Some(scratch.as_ref()))?;+ doc.snapshot_meta()+ };+ native_engine::sync_active_document();+ Ok(snap)+}++pub fn sync_layers(+ doc_id: &str,+ layers: Vec<LayerNodeMeta>,+ active_layer_id: Option<String>,+) -> Result<DocumentMetaSnapshot, String> {+ let docs = documents_handle();+ let snap = {+ let mut mgr = docs.write();+ let doc = mgr+ .get_document_mut(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ doc.sync_layers_metadata(layers, active_layer_id);+ doc.snapshot_meta()+ };+ native_engine::sync_active_document();+ Ok(snap)+}++pub fn clear_layer(+ doc_id: &str,+ layer_id: &str,+ record_history: bool,+) -> Result<DocumentMetaSnapshot, String> {+ let docs = documents_handle();+ let snap = {+ let mut mgr = docs.write();+ let doc = mgr+ .get_document_mut(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ doc.clear_layer(layer_id, record_history)?;+ doc.snapshot_meta()+ };+ native_engine::sync_active_document();+ Ok(snap)+}++pub fn merge_down(doc_id: &str, src_layer_id: &str) -> Result<DocumentMetaSnapshot, String> {+ let docs = documents_handle();+ let snap = {+ let mut mgr = docs.write();+ let scratch = Arc::clone(mgr.scratch_backend());+ let doc = mgr+ .get_document_mut(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ doc.merge_down(src_layer_id, Some(scratch.as_ref()))?;+ doc.snapshot_meta()+ };+ native_engine::sync_active_document();+ Ok(snap)+}++pub fn merge_folder(+ doc_id: &str,+ folder_id: &str,+ new_layer_id: String,+) -> Result<DocumentMetaSnapshot, String> {+ let docs = documents_handle();+ let snap = {+ let mut mgr = docs.write();+ let scratch = Arc::clone(mgr.scratch_backend());+ let doc = mgr+ .get_document_mut(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ doc.merge_folder(folder_id, new_layer_id, Some(scratch.as_ref()))?;+ doc.snapshot_meta()+ };+ native_engine::sync_active_document();+ Ok(snap)+}++pub fn add_mask(+ doc_id: &str,+ layer_id: &str,+ default_value: u8,+ record_history: bool,+) -> Result<DocumentMetaSnapshot, String> {+ let docs = documents_handle();+ let snap = {+ let mut mgr = docs.write();+ let doc = mgr+ .get_document_mut(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ doc.add_layer_mask(layer_id, default_value, record_history)?;+ doc.snapshot_meta()+ };+ native_engine::sync_active_document();+ Ok(snap)+}++pub fn remove_mask(+ doc_id: &str,+ layer_id: &str,+ apply_to_raster: bool,+ record_history: bool,+) -> Result<DocumentMetaSnapshot, String> {+ let docs = documents_handle();+ let snap = {+ let mut mgr = docs.write();+ let scratch = Arc::clone(mgr.scratch_backend());+ let doc = mgr+ .get_document_mut(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ doc.remove_layer_mask(layer_id, apply_to_raster, record_history, Some(scratch.as_ref()))?;+ doc.snapshot_meta()+ };+ native_engine::sync_active_document();+ Ok(snap)+}++pub fn resize_canvas(+ doc_id: &str,+ new_dims: CanvasDimensions,+ offset_x: i32,+ offset_y: i32,+ scale_content: bool,+ bg_hex: &str,+ record_history: bool,+) -> Result<DocumentMetaSnapshot, String> {+ let docs = documents_handle();+ let snap = {+ let mut mgr = docs.write();+ let scratch = Arc::clone(mgr.scratch_backend());+ let doc = mgr+ .get_document_mut(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ doc.resize_canvas(+ new_dims,+ offset_x,+ offset_y,+ scale_content,+ bg_hex,+ record_history,+ Some(scratch.as_ref()),+ )?;+ let _ = mgr.enforce_memory_budget();+ mgr.get_document(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?+ .snapshot_meta()+ };+ native_engine::sync_active_document();+ Ok(snap)+}++#[allow(clippy::too_many_arguments)]+pub fn ingest_dirty_rect(+ doc_id: &str,+ layer_id: &str,+ rect: RectI32,+ bytes: &[u8],+ is_mask: bool,+ record_history: bool,+ action_type: &str,+ label: &str,+ peer_id: Option<String>,+ stroke_id: Option<String>,+) -> Result<DocumentMetaSnapshot, String> {+ let docs = documents_handle();+ let snap = {+ let mut mgr = docs.write();+ let scratch = Arc::clone(mgr.scratch_backend());+ let doc = mgr+ .get_document_mut(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ doc.ingest_dirty_rect(+ layer_id,+ rect,+ bytes,+ is_mask,+ record_history,+ action_type,+ label,+ peer_id,+ stroke_id,+ Some(scratch.as_ref()),+ )?;+ let _ = mgr.enforce_memory_budget();+ mgr.get_document(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?+ .snapshot_meta()+ };+ native_engine::sync_active_document();+ Ok(snap)+}++pub fn undo(doc_id: &str) -> Result<NativeHistoryMutationResult, String> {+ let docs = documents_handle();+ let res = {+ let mut mgr = docs.write();+ let doc = mgr+ .get_document_mut(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ let change = doc.undo();+ NativeHistoryMutationResult {+ doc: doc.snapshot_meta(),+ dimensions_changed: change.dimensions_changed,+ layers_changed: change.layers_changed,+ changed_layer_ids: change.changed_layer_ids.into_iter().collect(),+ document_state_delta: change.document_state_delta,+ selective_outcome: None,+ }+ };+ native_engine::sync_active_document();+ Ok(res)+}++pub fn redo(doc_id: &str) -> Result<NativeHistoryMutationResult, String> {+ let docs = documents_handle();+ let res = {+ let mut mgr = docs.write();+ let doc = mgr+ .get_document_mut(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ let change = doc.redo();+ NativeHistoryMutationResult {+ doc: doc.snapshot_meta(),+ dimensions_changed: change.dimensions_changed,+ layers_changed: change.layers_changed,+ changed_layer_ids: change.changed_layer_ids.into_iter().collect(),+ document_state_delta: change.document_state_delta,+ selective_outcome: None,+ }+ };+ native_engine::sync_active_document();+ Ok(res)+}++pub fn jump_history(doc_id: &str, target_index: usize) -> Result<NativeHistoryMutationResult, String> {+ let docs = documents_handle();+ let res = {+ let mut mgr = docs.write();+ let doc = mgr+ .get_document_mut(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ let change = doc.jump_to_history(target_index);+ NativeHistoryMutationResult {+ doc: doc.snapshot_meta(),+ dimensions_changed: change.dimensions_changed,+ layers_changed: change.layers_changed,+ changed_layer_ids: change.changed_layer_ids.into_iter().collect(),+ document_state_delta: change.document_state_delta,+ selective_outcome: None,+ }+ };+ native_engine::sync_active_document();+ Ok(res)+}++pub fn selective_undo(+ doc_id: &str,+ peer_id: Option<&str>,+ stroke_id: Option<&str>,+) -> Result<NativeHistoryMutationResult, String> {+ let docs = documents_handle();+ let res = {+ let mut mgr = docs.write();+ let doc = mgr+ .get_document_mut(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ let outcome = doc.selective_undo(peer_id, stroke_id);+ let changed = outcome.layer_id.clone().into_iter().collect();+ NativeHistoryMutationResult {+ doc: doc.snapshot_meta(),+ dimensions_changed: false,+ layers_changed: false,+ changed_layer_ids: changed,+ document_state_delta: None,+ selective_outcome: Some(outcome),+ }+ };+ native_engine::sync_active_document();+ Ok(res)+}++pub fn selective_redo(+ doc_id: &str,+ peer_id: Option<&str>,+) -> Result<NativeHistoryMutationResult, String> {+ let docs = documents_handle();+ let res = {+ let mut mgr = docs.write();+ let doc = mgr+ .get_document_mut(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ let outcome = doc.selective_redo(peer_id);+ let changed = outcome.layer_id.clone().into_iter().collect();+ NativeHistoryMutationResult {+ doc: doc.snapshot_meta(),+ dimensions_changed: false,+ layers_changed: false,+ changed_layer_ids: changed,+ document_state_delta: None,+ selective_outcome: Some(outcome),+ }+ };+ native_engine::sync_active_document();+ Ok(res)+}++pub fn push_history_meta(+ doc_id: &str,+ action_type: String,+ label: String,+ layer_id: Option<String>,+ document_state_delta: Option<serde_json::Value>,+ _coalesce_key: Option<String>,+) -> Result<HistoryStateSnapshot, String> {+ let docs = documents_handle();+ let mut mgr = docs.write();+ let doc = mgr+ .get_document_mut(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_millis() as u64)+ .unwrap_or(0);+ let entry = ink_engine::history::HistoryEntry {+ meta: HistoryItemMeta {+ id: format!("hist-{now}"),+ action_type,+ label,+ timestamp: now,+ time_formatted: String::new(),+ thumbnail_url: String::new(),+ layer_id,+ undone: false,+ },+ tile_deltas: Vec::new(),+ layer_tree_delta: None,+ canvas_resize_delta: None,+ document_state_delta,+ peer_id: None,+ stroke_id: None,+ is_mask_edit: false,+ };+ doc.history.push(entry);+ Ok(doc.history.snapshot())+}++pub fn get_history(doc_id: &str) -> Result<HistoryStateSnapshot, String> {+ let docs = documents_handle();+ let mgr = docs.read();+ let doc = mgr+ .get_document(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ Ok(doc.history.snapshot())+}++pub fn reset_history(doc_id: &str, label: Option<String>) -> Result<HistoryStateSnapshot, String> {+ let docs = documents_handle();+ let mut mgr = docs.write();+ let doc = mgr+ .get_document_mut(doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ let initial_label = label.unwrap_or_else(|| "Initial State".to_string());+ let active_id = doc.active_layer_id.clone();+ doc.history+ .reset_with_initial(initial_label, active_id, String::new());+ Ok(doc.history.snapshot())+}++fn attach_gpu_pool_stats(mut stats: MemoryStats) -> MemoryStats {+ let pool = native_engine::gpu_pool_stats();+ if pool.slots_capacity > 0 {+ stats.vram_used_bytes = pool.used_bytes;+ stats.vram_budget_bytes = pool.capacity_bytes;+ stats.vram_slots_used = pool.slots_used;+ stats.vram_slots_capacity = pool.slots_capacity;+ }+ stats+}++pub fn get_memory_stats() -> MemoryStats {+ let docs = documents_handle();+ let mgr = docs.read();+ attach_gpu_pool_stats(mgr.memory_stats())+}++pub fn set_memory_budget(input: NativeMemoryBudgetInput) -> Result<MemoryStats, String> {+ let docs = documents_handle();+ let mut vram_to_apply: Option<u64> = None;+ let stats = {+ let mut mgr = docs.write();+ let mut cfg = mgr.budget_config();+ if let Some(ram_mb) = input.ram_budget_mb {+ cfg.ram_budget_bytes = ram_mb.clamp(64, 32768) * 1024 * 1024;+ }+ if let Some(vram_mb) = input.vram_budget_mb {+ let vbytes = vram_mb.clamp(64, 8192) * 1024 * 1024;+ cfg.vram_budget_bytes = vbytes;+ vram_to_apply = Some(vbytes);+ }+ if let Some(steps) = input.max_history_steps {+ cfg.max_history_steps = steps.clamp(10, 1000);+ }+ if let Some(offload) = input.offload_inactive_tabs {+ cfg.offload_inactive_tabs = offload;+ }+ mgr.set_memory_budget(cfg)?+ };+ if let Some(vbytes) = vram_to_apply {+ native_engine::set_vram_budget(vbytes);+ }+ Ok(attach_gpu_pool_stats(stats))+}++pub fn purge_memory() -> Result<MemoryStats, String> {+ native_engine::flush_gpu_pool();+ let docs = documents_handle();+ let mut mgr = docs.write();+ let outcome = mgr.purge_memory(false)?;+ Ok(attach_gpu_pool_stats(outcome.stats))+}++/// Generates 64x64 layer & mask thumbnails asynchronously in a Rayon worker and emits+/// `native-engine://thumbnails` back to React (never blocking the main UI or GPU thread).+pub fn spawn_thumbnail_generation(+ app: tauri::AppHandle,+ doc_id: String,+ layer_ids: Vec<String>,+) {+ tokio::task::spawn_blocking(move || {+ let docs = documents_handle();+ let updates: Vec<ThumbnailUpdate> = {+ let mgr = docs.read();+ let scratch = mgr.scratch_backend();+ let Some(doc) = mgr.get_document(&doc_id) else {+ return;+ };+ let target_ids: Vec<String> = if layer_ids.is_empty() {+ doc.layers+ .iter()+ .filter(|l| l.meta.layer_type.has_tiles() || l.grid.has_mask)+ .map(|l| l.meta.id.clone())+ .collect()+ } else {+ layer_ids+ };+ let dims = doc.dimensions;+ target_ids+ .into_par_iter()+ .filter_map(|lid| {+ let node = doc.layer(&lid)?;+ let thumb = if node.meta.layer_type.has_tiles() {+ render_layer_thumb_url(node, dims.width, dims.height, Some(scratch.as_ref()))+ } else {+ None+ };+ let mask_thumb = if node.grid.has_mask {+ render_mask_thumb_url(node, dims.width, dims.height, Some(scratch.as_ref()))+ } else {+ None+ };+ if thumb.is_none() && mask_thumb.is_none() {+ return None;+ }+ Some(ThumbnailUpdate {+ layer_id: lid,+ thumbnail_url: thumb,+ mask_thumbnail_url: mask_thumb,+ })+ })+ .collect()+ };++ if updates.is_empty() {+ return;+ }+ // Cache thumbnails on Document metadata as well+ {+ let mut mgr = docs.write();+ if let Some(doc) = mgr.get_document_mut(&doc_id) {+ for u in &updates {+ if let Some(node) = doc.layer_mut(&u.layer_id) {+ if let Some(ref url) = u.thumbnail_url {+ node.meta.thumbnail_url = Some(url.clone());+ }+ if let Some(ref murl) = u.mask_thumbnail_url {+ node.meta.mask_thumbnail_url = Some(murl.clone());+ }+ }+ }+ }+ }+ let _ = app.emit(+ native_engine::EVENT_THUMBNAILS,+ native_engine::NativeThumbnailsEventPayload { doc_id, updates },+ );+ });+}++/// Renders a downscaled flattened PNG directly from the Rust `Document` and persists it+/// directly into `src-tauri/src/timelapse.rs` (zero JS pixel transfer!).+pub async fn capture_timelapse_frame(+ app: &tauri::AppHandle,+ doc_id: String,+ session_id: String,+ frame_index: u32,+ max_dim: u32,+ capture_area: Option<String>,+) -> Result<NativeTimelapseCaptureResult, String> {+ let clamped_dim = max_dim.clamp(256, 3840);+ let (w, h, png_bytes) =+ tokio::task::spawn_blocking(move || -> Result<(u32, u32, Vec<u8>), String> {+ let docs = documents_handle();+ let mgr = docs.read();+ let scratch = mgr.scratch_backend();+ let doc = mgr+ .get_document(&doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ doc.render_flattened_png(clamped_dim, true, Some(scratch.as_ref()))+ })+ .await+ .map_err(|e| format!("Timelapse capture worker failed: {e}"))??;++ let bytes_len = png_bytes.len();+ let now_ms = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_millis() as u64)+ .unwrap_or(0);++ timelapse::write_frame(+ app,+ &session_id,+ frame_index,+ "png",+ &png_bytes,+ Some(timelapse::FrameWriteMeta {+ timestamp: now_ms,+ width: w,+ height: h,+ capture_area,+ }),+ )+ .await?;++ Ok(NativeTimelapseCaptureResult {+ width: w,+ height: h,+ bytes: bytes_len,+ frame_index,+ })+}++/// Writes an atomic crash-recovery checkpoint (`INKG v1` base snapshot + manifest + PNG thumbnail)+/// directly from the Rust `Document` into `src-tauri/src/recovery.rs` (zero JS pixel IPC!).+pub async fn recovery_checkpoint_document(+ app: &tauri::AppHandle,+ doc_id: String,+ session_id: String,+ manifest_override: Option<String>,+) -> Result<NativeRecoveryCheckpointResult, String> {+ let (generated_manifest, snapshot_bytes, thumb_png) =+ tokio::task::spawn_blocking(move || -> Result<(String, Vec<u8>, Vec<u8>), String> {+ let docs = documents_handle();+ let mgr = docs.read();+ let scratch = mgr.scratch_backend();+ let doc = mgr+ .get_document(&doc_id)+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;+ encode_document_checkpoint(doc, Some(scratch.as_ref()))+ })+ .await+ .map_err(|e| format!("Recovery checkpoint worker failed: {e}"))??;++ let manifest_json = manifest_override+ .filter(|s| !s.trim().is_empty())+ .unwrap_or(generated_manifest);+ let snap_len = snapshot_bytes.len();+ let thumb_len = thumb_png.len();++ recovery::checkpoint(+ app,+ &session_id,+ &snapshot_bytes,+ &manifest_json,+ &thumb_png,+ )+ .await?;++ Ok(NativeRecoveryCheckpointResult {+ snapshot_bytes: snap_len,+ thumbnail_bytes: thumb_len,+ })+}++/// Restores a crashed recovery session directly in Rust (replaying `INKG v1` base snapshot ++/// `TD v1` WAL frames straight into `DocumentManager`) and returns compact metadata to React!+pub async fn recovery_restore_document(+ app: &tauri::AppHandle,+ session_id: String,+ doc_id: String,+) -> Result<DocumentMetaSnapshot, String> {+ let replay = recovery::load_session_data(app, &session_id).await?;+ let max_history = documents_handle().read().budget_config().max_history_steps;++ let doc = tokio::task::spawn_blocking(move || -> Result<Document, String> {+ let wal_entries: Vec<WalRawEntry> = replay+ .wal_entries+ .into_iter()+ .map(|w| WalRawEntry {+ entry_type: w.entry_type,+ payload: w.payload,+ })+ .collect();+ let (mut doc, _strokes, _mutations) = replay_recovery_into_document(+ doc_id,+ &replay.manifest_json,+ replay.base_snapshot.as_deref(),+ &wal_entries,+ max_history,+ )?;++ // Refresh 64x64 thumbnails in parallel+ let dims = doc.dimensions;+ doc.layers.par_iter_mut().for_each(|node| {+ if node.meta.layer_type.has_tiles() && !node.grid.tiles.is_empty() {+ node.meta.thumbnail_url =+ render_layer_thumb_url(node, dims.width, dims.height, None);+ }+ if node.grid.has_mask {+ node.meta.mask_thumbnail_url =+ render_mask_thumb_url(node, dims.width, dims.height, None);+ }+ });+ Ok(doc)+ })+ .await+ .map_err(|e| format!("Recovery restore worker failed: {e}"))??;++ let docs = documents_handle();+ let snap = {+ let mut mgr = docs.write();+ mgr.insert_and_activate(doc)+ };+ native_engine::sync_active_document();+ Ok(snap)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_tauri_scratch_disk_backend_in_process_roundtrip() {+ let backend = TauriScratchDiskBackend;+ let session = format!(+ "ink_engine_inproc_{}",+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ );+ backend.init_session(&session).expect("init_session failed");++ let tile_payload: Vec<u8> = (0..65536).map(|i| ((i * 7) & 0xff) as u8).collect();+ let written = backend+ .write_tiles(+ &session,+ vec![ScratchTileWrite {+ layer_key: "layer-alpha".to_string(),+ tx: 3,+ ty: -2,+ data: tile_payload.clone(),+ }],+ )+ .expect("write_tiles failed");+ assert_eq!(written, 1);++ let loaded = backend+ .read_tile(&session, "layer-alpha", 3, -2)+ .expect("read_tile failed");+ assert_eq!(loaded, tile_payload);++ backend+ .clear_session(&session)+ .expect("clear_session failed");+ }++ #[test]+ fn test_zero_copy_psd_to_ink_engine_hydration_and_ink_roundtrip() {+ // Minimal 8x2 1-bit Bitmap PSD (bit 1 = black, bit 0 = white)+ let mut psd = Vec::new();+ psd.extend_from_slice(b"8BPS");+ psd.extend_from_slice(&1u16.to_be_bytes());+ psd.extend_from_slice(&[0u8; 6]);+ psd.extend_from_slice(&1u16.to_be_bytes());+ psd.extend_from_slice(&2u32.to_be_bytes()); // height+ psd.extend_from_slice(&8u32.to_be_bytes()); // width+ psd.extend_from_slice(&1u16.to_be_bytes()); // 1-bit+ psd.extend_from_slice(&0u16.to_be_bytes()); // Bitmap+ psd.extend_from_slice(&0u32.to_be_bytes());+ psd.extend_from_slice(&0u32.to_be_bytes());+ psd.extend_from_slice(&0u32.to_be_bytes());+ psd.extend_from_slice(&0u16.to_be_bytes()); // raw+ psd.push(0b1000_0000);+ psd.push(0b0100_0000);++ let assembled = psd_parser::parse_psd_assembled(&psd).expect("parse_psd_assembled failed");+ let (doc, _preview) = hydrate_assembled_document(assembled, "doc-psd-test", "Manga.psd", 50);++ assert_eq!(doc.dimensions.width, 8);+ assert_eq!(doc.dimensions.height, 2);+ assert_eq!(doc.color_mode, CanvasColorMode::Grayscale);+ assert_eq!(doc.layers.len(), 1);+ assert!(doc.layers[0].meta.thumbnail_url.is_some());++ // Verify exact pixels directly in Rust SparseLayerGrid+ let rgba = doc.layers[0]+ .grid+ .read_rgba8_rect(RectI32::new(0, 0, 8, 2), false, None)+ .expect("read_rgba8_rect failed");+ assert_eq!(&rgba[0..4], &[0, 0, 0, 255]); // (0, 0) black+ assert_eq!(&rgba[4..8], &[255, 255, 255, 255]); // (1, 0) white+ assert_eq!(&rgba[(8 + 1) * 4..(8 + 1) * 4 + 4], &[0, 0, 0, 255]); // (1, 1) black++ // Round-trip save directly from Rust into `.ink` v2 ZIP and reload+ let saved = serialize_ink_document(&doc, 1, None).expect("serialize_ink_document failed");+ assert!(saved.preview_png.is_some());+ let reloaded = parse_ink_document(&saved.bytes, "doc-psd-reloaded", "Manga.ink", 50)+ .expect("parse_ink_document failed");+ assert!(reloaded.preview_data_url.is_some());+ let reloaded_rgba = reloaded.layers[0]+ .grid+ .read_rgba8_rect(RectI32::new(0, 0, 8, 2), false, None)+ .expect("reloaded read failed");+ assert_eq!(reloaded_rgba, rgba);+ }++ #[test]+ fn test_zero_copy_clip_to_ink_engine_hydration_and_ink_roundtrip() {+ let clip_bytes = crate::clip_parser::tests::build_synthetic_clip_fixture();+ let assembled =+ clip_parser::parse_clip_assembled(&clip_bytes).expect("parse_clip_assembled failed");+ let (doc, _preview) =+ hydrate_assembled_document(assembled, "doc-clip-test", "Synthetic.clip", 50);++ assert_eq!(doc.dimensions.width, 512);+ assert_eq!(doc.dimensions.height, 256);+ assert_eq!(doc.dimensions.dpi, 600);+ assert_eq!(doc.layers.len(), 2);+ assert_eq!(doc.layers[0].meta.name, "Ink");+ assert_eq!(doc.layers[0].meta.blend_mode, BlendMode::Multiply);+ assert_eq!(doc.layers[0].meta.alpha_locked, Some(true));+ assert_eq!(doc.layers[0].meta.clipped, Some(true));+ assert!(doc.layers[0].meta.thumbnail_url.is_some());+ assert_eq!(doc.layers[1].meta.name, "Paper");++ // Exact pixel at (3, 5) hydrated directly into Rust SparseLayerGrid without INKD IPC!+ let px = doc.layers[0]+ .grid+ .read_rgba8_rect(RectI32::new(3, 5, 1, 1), false, None)+ .expect("read_rgba8_rect failed");+ assert_eq!(px, [240, 20, 10, 200]);++ // Paper layer uses zero-allocation SolidColor tiles+ let paper_px = doc.layers[1]+ .grid+ .read_rgba8_rect(RectI32::new(100, 100, 1, 1), false, None)+ .expect("paper read failed");+ assert_eq!(paper_px, [255, 255, 255, 255]);++ // Round-trip save directly from Rust into `.ink` v2 ZIP and reload+ let saved = serialize_ink_document(&doc, 1, None).expect("serialize_ink_document failed");+ let reloaded = parse_ink_document(&saved.bytes, "doc-clip-reloaded", "Synthetic.ink", 50)+ .expect("parse_ink_document failed");+ assert_eq!(reloaded.layers.len(), 2);+ let reloaded_px = reloaded.layers[0]+ .grid+ .read_rgba8_rect(RectI32::new(3, 5, 1, 1), false, None)+ .expect("reloaded read failed");+ assert_eq!(reloaded_px, [240, 20, 10, 200]);+ }+}diff --git a/src-tauri/src/native_engine.rs b/src-tauri/src/native_engine.rsnew file mode 100644index 0000000..e85085f--- /dev/null+++ b/src-tauri/src/native_engine.rs@@ -0,0 +1,978 @@+//! Tauri desktop host integration for `ink-engine` on Windows 10/11.+//!+//! Responsibilities:+//! - Initializes [`DCompHost`] on the top-level `main` HWND (`topmost = false`) and configures+//! WebView2's transparent background (`COREWEBVIEW2_COLOR { A: 0, R: 0, G: 0, B: 0 }`).+//! - Spawns `ink-engine`'s dedicated DX12 render thread targeting `canvas_visual`.+//! - Attaches the lock-free `rtrb` SPSC tablet rings directly to `tablet_input.rs`.+//! - Installs a `main_hwnd` Win32 lifecycle subclass (`WM_SIZE`, `WM_DPICHANGED`,+//! `WM_DISPLAYCHANGE`, `WM_DESTROY`) for minimize/restore and DPI invalidation.+//! - Runs a lightweight, high-priority `WH_MOUSE_LL` hook thread (`inkstudio-native-mouse`)+//! that pushes mouse hover, wheel zoom/scroll, middle-click pan, Space+drag pan/rotate/zoom,+//! and mouse PoC draw events directly into `ink-engine`'s lock-free `nav` SPSC ring+//! (zero JS/IPC round-trips during camera navigation and hover cursor tracking).+//! - Bridges throttled `EngineEvent`s (`CameraChanged`, `Diagnostics`, `PointerStat`) back+//! to React via Tauri app events.+//! - Guarantees strict ordered shutdown: detach input hooks -> join `ink-engine` (drops+//! `wgpu::Surface` & DXGI swapchain) -> clear & drop `DCompHost`.++use ink_engine::{+ BrushParams, CameraState, CursorConfig, EngineCommand, EngineDiagnostics, GpuPoolStats,+ HistoryStateSnapshot, InteractionPolicy, ThumbnailUpdate, UiRect, ViewportRect,+};+use serde::Serialize;++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeCameraEventPayload {+ pub pan_x: f32,+ pub pan_y: f32,+ pub zoom: f32,+ pub rotation: f32,+ pub flip_x: bool,+ pub flip_y: bool,+ pub commit: bool,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct NativePointerStatPayload {+ pub doc_x: Option<i32>,+ pub doc_y: Option<i32>,+ pub pressure: f32,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeHistoryEventPayload {+ pub doc_id: String,+ pub history: HistoryStateSnapshot,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeThumbnailsEventPayload {+ pub doc_id: String,+ pub updates: Vec<ThumbnailUpdate>,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeStrokeCommittedEventPayload {+ pub doc_id: String,+ pub layer_id: String,+ pub entry_id: String,+}++pub const EVENT_CAMERA: &str = "native-engine://camera";+pub const EVENT_DIAGNOSTICS: &str = "native-engine://diagnostics";+pub const EVENT_POINTER_STAT: &str = "native-engine://pointer-stat";+pub const EVENT_HISTORY: &str = "native-engine://history";+pub const EVENT_THUMBNAILS: &str = "native-engine://thumbnails";+pub const EVENT_STROKE_COMMITTED: &str = "native-engine://stroke-committed";++#[cfg(target_os = "windows")]+mod win_host {+ use super::*;+ use crate::dcomp_host::DCompHost;+ use crate::tablet_input;+ use ink_engine::{+ EngineConfig, EngineEvent, EngineHandle, NativeNavEvent, NativeNavGesture, NavRingProducer,+ SharedHitTest, SurfaceTarget, WheelNavMode,+ };+ use std::cell::RefCell;+ use std::sync::atomic::{AtomicBool, AtomicIsize, AtomicU32, Ordering};+ use std::sync::{mpsc, Arc, LazyLock, Mutex};+ use std::thread::JoinHandle;+ use tauri::Emitter;+ use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, POINT, WPARAM};+ use windows_sys::Win32::Graphics::Gdi::ScreenToClient;+ use windows_sys::Win32::System::Threading::{+ GetCurrentThread, GetCurrentThreadId, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL,+ };+ use windows_sys::Win32::UI::Input::KeyboardAndMouse::{+ GetAsyncKeyState, VK_CONTROL, VK_SHIFT, VK_SPACE,+ };+ use windows_sys::Win32::UI::Shell::{+ DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass,+ };+ use windows_sys::Win32::UI::WindowsAndMessaging::{+ CallNextHookEx, DispatchMessageW, GetAncestor, GetForegroundWindow, GetMessageW,+ PostThreadMessageW, SetWindowsHookExW, TranslateMessage, UnhookWindowsHookEx,+ WindowFromPoint, GA_ROOT, HHOOK, MSG, MSLLHOOKSTRUCT, SIZE_MINIMIZED, WH_MOUSE_LL,+ WM_DESTROY, WM_DISPLAYCHANGE, WM_DPICHANGED, WM_LBUTTONDOWN, WM_LBUTTONUP,+ WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MOUSEHWHEEL, WM_MOUSEMOVE, WM_MOUSEWHEEL, WM_QUIT,+ WM_SIZE,+ };++ const LIFECYCLE_SUBCLASS_ID: usize = 0x494E_4B45; // "INKE"+ const MI_WP_SIGNATURE: usize = 0xFF51_5700;+ const MI_WP_MASK: usize = 0xFFFF_FF00;+ const WHEEL_DELTA_NORM: f32 = 100.0 / 120.0;++ struct NativeEngineRuntime {+ dcomp: Arc<DCompHost>,+ engine: EngineHandle,+ hit_test: SharedHitTest,+ main_hwnd: isize,+ composition_mode: String,+ event_thread: Option<JoinHandle<()>>,+ mouse_hook_thread: Option<JoinHandle<()>>,+ last_viewport: ViewportRect,+ ui_visible: bool,+ }++ static RUNTIME: LazyLock<Mutex<Option<NativeEngineRuntime>>> =+ LazyLock::new(|| Mutex::new(None));+ static ENGINE_ACTIVE: AtomicBool = AtomicBool::new(false);+ static MAIN_HWND_RAW: AtomicIsize = AtomicIsize::new(0);+ static WINDOW_MINIMIZED: AtomicBool = AtomicBool::new(false);+ static MOUSE_HOOK_THREAD_ID: AtomicU32 = AtomicU32::new(0);+ static MOUSE_HOOK_RUNNING: AtomicBool = AtomicBool::new(false);++ // Non-blocking handles mirrored for the dedicated WH_MOUSE_LL hook thread+ static HOOK_HIT_TEST: LazyLock<Mutex<Option<SharedHitTest>>> =+ LazyLock::new(|| Mutex::new(None));++ #[derive(Clone, Copy, PartialEq, Eq)]+ enum ActiveNavButton {+ None,+ Middle,+ LeftSpaceNav,+ }++ struct MouseHookLocal {+ nav_tx: Option<NavRingProducer>,+ hit_test: Option<SharedHitTest>,+ nav_button: ActiveNavButton,+ mouse_drawing: bool,+ was_hovering_canvas: bool,+ }++ thread_local! {+ static MOUSE_HOOK_LOCAL: RefCell<MouseHookLocal> = const {+ RefCell::new(MouseHookLocal {+ nav_tx: None,+ hit_test: None,+ nav_button: ActiveNavButton::None,+ mouse_drawing: false,+ was_hovering_canvas: false,+ })+ };+ }++ #[inline]+ fn is_vk_pressed(vk: u16) -> bool {+ unsafe { (GetAsyncKeyState(vk as i32) as u16 & 0x8000) != 0 }+ }++ #[inline]+ fn is_main_window_foreground(main_hwnd: HWND) -> bool {+ unsafe {+ let fg = GetForegroundWindow();+ if fg.is_null() {+ return false;+ }+ fg == main_hwnd || GetAncestor(fg, GA_ROOT) == main_hwnd+ }+ }++ #[inline]+ fn is_point_over_main_window(main_hwnd: HWND, screen_pt: POINT) -> bool {+ unsafe {+ let w = WindowFromPoint(screen_pt);+ if w.is_null() {+ return false;+ }+ w == main_hwnd || GetAncestor(w, GA_ROOT) == main_hwnd+ }+ }++ #[inline]+ fn screen_to_client_phys(main_hwnd: HWND, screen_pt: POINT) -> (f32, f32) {+ unsafe {+ let mut pt = screen_pt;+ ScreenToClient(main_hwnd, &mut pt);+ (pt.x as f32, pt.y as f32)+ }+ }++ #[inline]+ fn is_pen_or_touch_synthesized(extra_info: usize, now_ms: f64) -> bool {+ if (extra_info & MI_WP_MASK) == MI_WP_SIGNATURE {+ return true;+ }+ let last_stylus = tablet_input::last_stylus_activity_ms();+ last_stylus > 0.0 && (now_ms - last_stylus) < 120.0+ }++ /// Low-level mouse hook callback running on dedicated high-priority `inkstudio-native-mouse`+ /// thread. Strictly non-blocking (`try_read` + wait-free SPSC `rtrb` push) and returns in+ /// nanoseconds. NEVER swallows `WM_MOUSEMOVE` so the OS cursor stays smooth.+ unsafe extern "system" fn ll_mouse_proc(+ n_code: i32,+ w_param: WPARAM,+ l_param: LPARAM,+ ) -> LRESULT {+ if n_code < 0 || !ENGINE_ACTIVE.load(Ordering::Relaxed) {+ return CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param);+ }++ let main_raw = MAIN_HWND_RAW.load(Ordering::Relaxed);+ if main_raw == 0 || WINDOW_MINIMIZED.load(Ordering::Relaxed) {+ return CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param);+ }+ let main_hwnd = main_raw as HWND;+ let ms = &*(l_param as *const MSLLHOOKSTRUCT);+ let msg = w_param as u32;++ let consume = std::panic::catch_unwind(|| -> bool {+ MOUSE_HOOK_LOCAL.with(|cell| {+ let mut st_ref = cell.borrow_mut();+ let MouseHookLocal {+ nav_tx,+ hit_test,+ nav_button,+ mouse_drawing,+ was_hovering_canvas,+ } = &mut *st_ref;+ let (Some(nav_tx), Some(hit_test)) = (nav_tx.as_mut(), hit_test.as_ref()) else {+ return false;+ };++ let now_ms = ink_engine::clock::now_ms();+ let (px, py) = screen_to_client_phys(main_hwnd, ms.pt);++ match msg {+ WM_MOUSEMOVE => {+ if *nav_button != ActiveNavButton::None {+ nav_tx.push(NativeNavEvent::GestureMove {+ phys_x: px,+ phys_y: py,+ snap_15_deg: is_vk_pressed(VK_SHIFT),+ timestamp_ms: now_ms,+ });+ return false;+ }+ if *mouse_drawing {+ nav_tx.push(NativeNavEvent::MouseDraw {+ phys_x: px,+ phys_y: py,+ phase: 2,+ timestamp_ms: now_ms,+ });+ return false;+ }++ // Hover tracking for 120–240 Hz GPU brush cursor (skip pen-synthesized+ // mouse moves while WinTab / Windows Ink is already feeding sub-pixel pen hover).+ if is_pen_or_touch_synthesized(ms.dwExtraInfo, now_ms) {+ return false;+ }+ let over_unoccluded = is_main_window_foreground(main_hwnd)+ && is_point_over_main_window(main_hwnd, ms.pt)+ && hit_test.try_is_unoccluded_canvas_point(px, py);+ if over_unoccluded {+ *was_hovering_canvas = true;+ nav_tx.push(NativeNavEvent::Hover {+ phys_x: px,+ phys_y: py,+ timestamp_ms: now_ms,+ });+ } else if *was_hovering_canvas {+ *was_hovering_canvas = false;+ nav_tx.push(NativeNavEvent::HoverLeave);+ }+ false+ }+ WM_MOUSEWHEEL | WM_MOUSEHWHEEL => {+ if !is_main_window_foreground(main_hwnd)+ || !is_point_over_main_window(main_hwnd, ms.pt)+ {+ return false;+ }+ if hit_test.try_wheel_mode() == WheelNavMode::BrushSize {+ // Let React handle brush-size wheel stepping+ return false;+ }+ if !hit_test.try_should_capture_native_nav(px, py) {+ return false;+ }+ let raw_delta = ((ms.mouseData >> 16) as u16) as i16 as f32;+ if raw_delta == 0.0 {+ return false;+ }+ let (delta_x, delta_y) = if msg == WM_MOUSEWHEEL {+ (0.0, -raw_delta * WHEEL_DELTA_NORM)+ } else {+ (raw_delta * WHEEL_DELTA_NORM, 0.0)+ };+ nav_tx.push(NativeNavEvent::Wheel {+ phys_x: px,+ phys_y: py,+ delta_x,+ delta_y,+ ctrl_held: is_vk_pressed(VK_CONTROL),+ shift_held: is_vk_pressed(VK_SHIFT),+ timestamp_ms: now_ms,+ });+ true+ }+ WM_MBUTTONDOWN => {+ if !is_main_window_foreground(main_hwnd)+ || !is_point_over_main_window(main_hwnd, ms.pt)+ {+ return false;+ }+ if !hit_test.try_should_capture_native_nav(px, py) {+ return false;+ }+ let gesture = if is_vk_pressed(VK_SHIFT) {+ NativeNavGesture::Rotate+ } else if is_vk_pressed(VK_CONTROL) {+ NativeNavGesture::ZoomDrag+ } else {+ NativeNavGesture::Pan+ };+ *nav_button = ActiveNavButton::Middle;+ nav_tx.push(NativeNavEvent::GestureStart {+ gesture,+ phys_x: px,+ phys_y: py,+ timestamp_ms: now_ms,+ });+ true+ }+ WM_MBUTTONUP => {+ if *nav_button == ActiveNavButton::Middle {+ *nav_button = ActiveNavButton::None;+ nav_tx.push(NativeNavEvent::GestureEnd {+ timestamp_ms: now_ms,+ });+ return true;+ }+ false+ }+ WM_LBUTTONDOWN => {+ if !is_main_window_foreground(main_hwnd)+ || !is_point_over_main_window(main_hwnd, ms.pt)+ {+ return false;+ }+ // Space + Left Drag -> native Pan / Shift+Rotate / Ctrl+ZoomDrag+ if is_vk_pressed(VK_SPACE)+ && !hit_test.try_text_input_focused()+ && hit_test.try_should_capture_native_nav(px, py)+ {+ let gesture = if is_vk_pressed(VK_CONTROL) {+ NativeNavGesture::ZoomDrag+ } else if is_vk_pressed(VK_SHIFT) {+ NativeNavGesture::Rotate+ } else {+ NativeNavGesture::Pan+ };+ *nav_button = ActiveNavButton::LeftSpaceNav;+ nav_tx.push(NativeNavEvent::GestureStart {+ gesture,+ phys_x: px,+ phys_y: py,+ timestamp_ms: now_ms,+ });+ return true;+ }++ // Mouse PoC stroke on unoccluded canvas (skip pen-synthesized clicks so+ // WinTab/Windows Ink remains sole owner of stylus strokes).+ if !is_pen_or_touch_synthesized(ms.dwExtraInfo, now_ms)+ && hit_test.try_should_capture_native_stroke(px, py)+ {+ *mouse_drawing = true;+ nav_tx.push(NativeNavEvent::MouseDraw {+ phys_x: px,+ phys_y: py,+ phase: 1,+ timestamp_ms: now_ms,+ });+ // Do NOT swallow WM_LBUTTONDOWN here so DOM focus/blur & non-modal+ // menu dismissal keep working normally; React skips JS brush stroke+ // dispatch when native canvas owns Brush/Eraser.+ }+ false+ }+ WM_LBUTTONUP => {+ if *nav_button == ActiveNavButton::LeftSpaceNav {+ *nav_button = ActiveNavButton::None;+ nav_tx.push(NativeNavEvent::GestureEnd {+ timestamp_ms: now_ms,+ });+ return true;+ } else if *mouse_drawing {+ *mouse_drawing = false;+ nav_tx.push(NativeNavEvent::MouseDraw {+ phys_x: px,+ phys_y: py,+ phase: 3,+ timestamp_ms: now_ms,+ });+ }+ false+ }+ _ => false,+ }+ })+ })+ .unwrap_or(false);++ if consume {+ 1+ } else {+ CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param)+ }+ }++ fn spawn_mouse_hook_thread(+ nav_tx: NavRingProducer,+ hit_test: SharedHitTest,+ ) -> Result<JoinHandle<()>, String> {+ if let Ok(mut guard) = HOOK_HIT_TEST.lock() {+ *guard = Some(hit_test.clone());+ }+ let (ready_tx, ready_rx) = mpsc::channel::<Result<(), String>>();+ let handle = std::thread::Builder::new()+ .name("inkstudio-native-mouse".to_string())+ .spawn(move || unsafe {+ SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);+ let tid = GetCurrentThreadId();+ MOUSE_HOOK_THREAD_ID.store(tid, Ordering::SeqCst);++ MOUSE_HOOK_LOCAL.with(|cell| {+ let mut st = cell.borrow_mut();+ st.nav_tx = Some(nav_tx);+ st.hit_test = Some(hit_test);+ st.nav_button = ActiveNavButton::None;+ st.mouse_drawing = false;+ st.was_hovering_canvas = false;+ });++ let hook: HHOOK =+ SetWindowsHookExW(WH_MOUSE_LL, Some(ll_mouse_proc), std::ptr::null_mut(), 0);+ if hook.is_null() {+ MOUSE_HOOK_THREAD_ID.store(0, Ordering::SeqCst);+ let _ = ready_tx.send(Err("Failed to install WH_MOUSE_LL hook".to_string()));+ return;+ }++ MOUSE_HOOK_RUNNING.store(true, Ordering::SeqCst);+ let _ = ready_tx.send(Ok(()));++ let mut msg: MSG = std::mem::zeroed();+ while GetMessageW(&mut msg, std::ptr::null_mut(), 0, 0) > 0 {+ TranslateMessage(&msg);+ DispatchMessageW(&msg);+ }++ UnhookWindowsHookEx(hook);+ MOUSE_HOOK_RUNNING.store(false, Ordering::SeqCst);+ MOUSE_HOOK_THREAD_ID.store(0, Ordering::SeqCst);+ MOUSE_HOOK_LOCAL.with(|cell| {+ let mut st = cell.borrow_mut();+ st.nav_tx = None;+ st.hit_test = None;+ st.nav_button = ActiveNavButton::None;+ st.mouse_drawing = false;+ st.was_hovering_canvas = false;+ });+ })+ .map_err(|e| format!("Failed to spawn native mouse hook thread: {e}"))?;++ match ready_rx.recv_timeout(std::time::Duration::from_secs(2)) {+ Ok(Ok(())) => Ok(handle),+ Ok(Err(err)) => {+ let _ = handle.join();+ Err(err)+ }+ Err(_) => {+ let _ = handle.join();+ Err("Native mouse hook thread initialization timed out".to_string())+ }+ }+ }++ fn stop_mouse_hook_thread(handle: Option<JoinHandle<()>>) {+ let tid = MOUSE_HOOK_THREAD_ID.load(Ordering::SeqCst);+ if tid != 0 {+ unsafe {+ let _ = PostThreadMessageW(tid, WM_QUIT, 0, 0);+ }+ }+ if let Some(h) = handle {+ let _ = h.join();+ }+ if let Ok(mut guard) = HOOK_HIT_TEST.lock() {+ *guard = None;+ }+ }++ /// Top-level `main_hwnd` Win32 lifecycle subclass: handles minimize/restore (`WM_SIZE`),+ /// monitor DPI change (`WM_DPICHANGED`), display mode change (`WM_DISPLAYCHANGE`),+ /// and window teardown (`WM_DESTROY`).+ unsafe extern "system" fn lifecycle_subclass_proc(+ hwnd: HWND,+ msg: u32,+ wparam: WPARAM,+ lparam: LPARAM,+ uid_subclass: usize,+ _dw_ref_data: usize,+ ) -> LRESULT {+ let _ = std::panic::catch_unwind(|| match msg {+ WM_SIZE => {+ let minimized = wparam == SIZE_MINIMIZED as usize;+ let prev = WINDOW_MINIMIZED.swap(minimized, Ordering::SeqCst);+ if let Ok(guard) = RUNTIME.try_lock() {+ if let Some(rt) = guard.as_ref() {+ if minimized && !prev {+ rt.engine.send_command(EngineCommand::SetVisible(false));+ let _ = rt.dcomp.set_canvas_viewport(0, 0, 0, 0, false);+ } else if !minimized && prev {+ let vp = rt.last_viewport;+ let vis = rt.ui_visible && vp.width_px > 0 && vp.height_px > 0;+ let _ = rt.dcomp.set_canvas_viewport(+ vp.x_px,+ vp.y_px,+ vp.width_px,+ vp.height_px,+ vis,+ );+ rt.engine.send_command(EngineCommand::SetVisible(vis));+ rt.engine+ .send_command(EngineCommand::NotifySurfaceInvalidated);+ } else if !minimized {+ rt.engine+ .send_command(EngineCommand::NotifySurfaceInvalidated);+ }+ }+ }+ }+ WM_DPICHANGED | WM_DISPLAYCHANGE => {+ if let Ok(guard) = RUNTIME.try_lock() {+ if let Some(rt) = guard.as_ref() {+ rt.engine+ .send_command(EngineCommand::NotifySurfaceInvalidated);+ }+ }+ }+ WM_DESTROY => {+ RemoveWindowSubclass(hwnd, Some(lifecycle_subclass_proc), uid_subclass);+ }+ _ => {}+ });++ DefSubclassProc(hwnd, msg, wparam, lparam)+ }++ pub fn init_for_main_window(+ app_handle: tauri::AppHandle,+ main_window: &tauri::WebviewWindow,+ ) -> Result<(), String> {+ let hwnd = main_window+ .hwnd()+ .map_err(|e| format!("Failed to acquire main window HWND: {e}"))?;+ let main_hwnd_raw = hwnd.0 as isize;+ MAIN_HWND_RAW.store(main_hwnd_raw, Ordering::SeqCst);++ let dcomp = Arc::new(DCompHost::new(main_hwnd_raw)?);+ let dcomp_for_webview = Arc::clone(&dcomp);+ let composition_mode_cell = Arc::new(Mutex::new("DirectComposition (Underlay)".to_string()));+ let mode_clone = Arc::clone(&composition_mode_cell);++ // Configure WebView2 transparent background + disable browser accelerator keys on UI thread+ main_window+ .with_webview(move |webview| {+ use webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Settings3;+ use windows_core::Interface;++ let controller = webview.controller();+ let mode = dcomp_for_webview.configure_webview2_controller(&controller);+ if let Ok(mut g) = mode_clone.lock() {+ *g = mode;+ }++ unsafe {+ if let Ok(core) = controller.CoreWebView2() {+ if let Ok(settings) = core.Settings() {+ if let Ok(settings3) = settings.cast::<ICoreWebView2Settings3>() {+ let _ = settings3.SetAreBrowserAcceleratorKeysEnabled(false);+ }+ }+ }+ }+ })+ .map_err(|e| format!("with_webview setup failed: {e}"))?;++ let composition_mode = composition_mode_cell+ .lock()+ .map(|g| g.clone())+ .unwrap_or_else(|_| "DirectComposition (Underlay)".to_string());++ let visual_raw = dcomp.canvas_visual_raw()?;+ let dcomp_commit = Arc::clone(&dcomp);+ let target = unsafe {+ SurfaceTarget::from_composition_visual(+ visual_raw,+ Arc::new(move || {+ dcomp_commit.commit();+ }),+ )+ };++ let engine_cfg = EngineConfig {+ scratch_backend: Some(Arc::new(crate::native_docs::TauriScratchDiskBackend)),+ ..EngineConfig::default()+ };+ let (engine, producers) = EngineHandle::spawn(target, engine_cfg)?;+ crate::native_docs::attach_engine_documents(engine.documents());+ let hit_test = engine.hit_test();++ // Wire lock-free SPSC WinTab & Windows Ink rings directly into `tablet_input.rs`+ tablet_input::attach_engine_rings(producers.wintab, producers.winink, hit_test.clone());+ tablet_input::start_native_only_if_idle(main_hwnd_raw);++ // Spawn dedicated high-priority WH_MOUSE_LL zero-IPC nav & hover hook thread+ let mouse_hook_thread = match spawn_mouse_hook_thread(producers.nav, hit_test.clone()) {+ Ok(h) => Some(h),+ Err(err) => {+ eprintln!("[native_engine] WH_MOUSE_LL hook unavailable: {err}");+ None+ }+ };++ // Install main_hwnd Win32 lifecycle subclass on main UI thread+ let subclass_hwnd = main_hwnd_raw;+ let _ = main_window.run_on_main_thread(move || unsafe {+ let _ = SetWindowSubclass(+ subclass_hwnd as HWND,+ Some(lifecycle_subclass_proc),+ LIFECYCLE_SUBCLASS_ID,+ 0,+ );+ });++ // Bridge throttled EngineEvents back to React+ let event_rx = engine.events().clone();+ let mode_for_events = composition_mode.clone();+ let event_thread = std::thread::Builder::new()+ .name("inkstudio-engine-events".to_string())+ .spawn(move || {+ while let Ok(evt) = event_rx.recv() {+ match evt {+ EngineEvent::CameraChanged { camera, commit } => {+ let _ = app_handle.emit(+ EVENT_CAMERA,+ NativeCameraEventPayload {+ pan_x: camera.pan_x,+ pan_y: camera.pan_y,+ zoom: camera.zoom,+ rotation: camera.rotation,+ flip_x: camera.flip_x,+ flip_y: camera.flip_y,+ commit,+ },+ );+ }+ EngineEvent::Diagnostics(mut diag) => {+ diag.composition_mode = mode_for_events.clone();+ let _ = app_handle.emit(EVENT_DIAGNOSTICS, diag);+ }+ EngineEvent::PointerStat {+ doc_x,+ doc_y,+ pressure,+ } => {+ let _ = app_handle.emit(+ EVENT_POINTER_STAT,+ NativePointerStatPayload {+ doc_x,+ doc_y,+ pressure,+ },+ );+ }+ EngineEvent::HistoryChanged { doc_id, history } => {+ let _ = app_handle.emit(+ EVENT_HISTORY,+ NativeHistoryEventPayload { doc_id, history },+ );+ }+ EngineEvent::ThumbnailsUpdated { doc_id, updates } => {+ let _ = app_handle.emit(+ EVENT_THUMBNAILS,+ NativeThumbnailsEventPayload { doc_id, updates },+ );+ }+ EngineEvent::StrokeCommitted {+ doc_id,+ layer_id,+ entry_id,+ } => {+ let _ = app_handle.emit(+ EVENT_STROKE_COMMITTED,+ NativeStrokeCommittedEventPayload {+ doc_id,+ layer_id,+ entry_id,+ },+ );+ }+ }+ }+ })+ .ok();++ if let Ok(mut guard) = RUNTIME.lock() {+ *guard = Some(NativeEngineRuntime {+ dcomp,+ engine,+ hit_test,+ main_hwnd: main_hwnd_raw,+ composition_mode,+ event_thread,+ mouse_hook_thread,+ last_viewport: ViewportRect::default(),+ ui_visible: false,+ });+ }+ ENGINE_ACTIVE.store(true, Ordering::SeqCst);+ Ok(())+ }++ pub fn shutdown() {+ ENGINE_ACTIVE.store(false, Ordering::SeqCst);+ crate::native_docs::detach_engine_documents();+ tablet_input::detach_engine_rings();++ let runtime = RUNTIME.lock().ok().and_then(|mut g| g.take());+ let Some(mut rt) = runtime else {+ return;+ };++ // 1. Stop WH_MOUSE_LL hook thread first so no more nav events are produced+ stop_mouse_hook_thread(rt.mouse_hook_thread.take());++ // 2. Remove main_hwnd lifecycle subclass+ if rt.main_hwnd != 0 {+ unsafe {+ let _ = RemoveWindowSubclass(+ rt.main_hwnd as HWND,+ Some(lifecycle_subclass_proc),+ LIFECYCLE_SUBCLASS_ID,+ );+ }+ }++ // 3. STRICT ORDER: Shut down and join ink-engine thread FIRST (drops wgpu::Surface &+ // DXGI swapchain) BEFORE detaching and dropping DirectComposition visuals/device.+ rt.engine.shutdown();++ if let Some(ev_thread) = rt.event_thread.take() {+ let _ = ev_thread.join();+ }++ // 4. Detach visual content and drop DCompHost+ rt.dcomp.clear_content();+ drop(rt.dcomp);+ MAIN_HWND_RAW.store(0, Ordering::SeqCst);+ }++ pub fn is_active() -> bool {+ ENGINE_ACTIVE.load(Ordering::Acquire)+ }++ pub fn set_viewport(viewport: ViewportRect, visible: bool) -> Result<(), String> {+ let mut guard = RUNTIME+ .lock()+ .map_err(|_| "Native engine runtime lock poisoned".to_string())?;+ let Some(rt) = guard.as_mut() else {+ return Ok(());+ };+ rt.last_viewport = viewport;+ rt.ui_visible = visible;+ let effective_visible =+ visible && !WINDOW_MINIMIZED.load(Ordering::Acquire) && viewport.width_px > 0 && viewport.height_px > 0;+ rt.dcomp.set_canvas_viewport(+ viewport.x_px,+ viewport.y_px,+ viewport.width_px,+ viewport.height_px,+ effective_visible,+ )?;+ rt.hit_test.set_viewport(viewport);+ rt.hit_test.set_visible(effective_visible);+ rt.engine.send_command(EngineCommand::SetViewport(viewport));+ rt.engine+ .send_command(EngineCommand::SetVisible(effective_visible));+ Ok(())+ }++ pub fn set_occluded_rects(rects: Vec<UiRect>) {+ if let Ok(guard) = RUNTIME.lock() {+ if let Some(rt) = guard.as_ref() {+ rt.hit_test.set_occluded_rects(rects.clone());+ rt.engine+ .send_command(EngineCommand::SetOccludedRects(rects));+ }+ }+ }++ pub fn set_document(width: u32, height: u32, show_checkerboard: bool) {+ if let Ok(guard) = RUNTIME.lock() {+ if let Some(rt) = guard.as_ref() {+ rt.engine.send_command(EngineCommand::SetDocumentSize {+ width,+ height,+ show_checkerboard,+ });+ }+ }+ }++ pub fn set_appearance(matte_rgba: [f32; 4], show_checkerboard: bool) {+ if let Ok(guard) = RUNTIME.lock() {+ if let Some(rt) = guard.as_ref() {+ rt.engine+ .send_command(EngineCommand::SetMatteColor(matte_rgba));+ rt.engine+ .send_command(EngineCommand::SetShowCheckerboard(show_checkerboard));+ }+ }+ }++ pub fn set_camera(camera: CameraState) {+ if let Ok(guard) = RUNTIME.lock() {+ if let Some(rt) = guard.as_ref() {+ rt.engine.send_command(EngineCommand::SetCamera(camera));+ }+ }+ }++ pub fn set_cursor(config: CursorConfig) {+ if let Ok(guard) = RUNTIME.lock() {+ if let Some(rt) = guard.as_ref() {+ rt.engine+ .send_command(EngineCommand::SetCursorConfig(config));+ }+ }+ }++ pub fn set_brush(params: BrushParams) {+ if let Ok(guard) = RUNTIME.lock() {+ if let Some(rt) = guard.as_ref() {+ rt.engine+ .send_command(EngineCommand::SetBrushParams(params));+ }+ }+ }++ pub fn set_policy(policy: InteractionPolicy) {+ if let Ok(guard) = RUNTIME.lock() {+ if let Some(rt) = guard.as_ref() {+ rt.hit_test.set_policy(policy);+ rt.engine+ .send_command(EngineCommand::SetInteractionPolicy(policy));+ }+ }+ }++ pub fn clear_canvas() {+ if let Ok(guard) = RUNTIME.lock() {+ if let Some(rt) = guard.as_ref() {+ rt.engine.send_command(EngineCommand::ClearCanvas);+ }+ }+ }++ pub fn sync_active_document() {+ if let Ok(guard) = RUNTIME.lock() {+ if let Some(rt) = guard.as_ref() {+ rt.engine.send_command(EngineCommand::SyncActiveDocument);+ }+ }+ }++ pub fn set_vram_budget(budget_bytes: u64) {+ if let Ok(guard) = RUNTIME.lock() {+ if let Some(rt) = guard.as_ref() {+ rt.engine+ .send_command(EngineCommand::SetVramBudget(budget_bytes));+ }+ }+ }++ pub fn flush_gpu_pool() {+ if let Ok(guard) = RUNTIME.lock() {+ if let Some(rt) = guard.as_ref() {+ rt.engine.send_command(EngineCommand::FlushGpuPool);+ }+ }+ }++ pub fn gpu_pool_stats() -> GpuPoolStats {+ if let Ok(guard) = RUNTIME.lock() {+ if let Some(rt) = guard.as_ref() {+ return rt.engine.gpu_pool_stats();+ }+ }+ GpuPoolStats::default()+ }++ pub fn get_diagnostics() -> EngineDiagnostics {+ if let Ok(guard) = RUNTIME.lock() {+ if let Some(rt) = guard.as_ref() {+ let mut diag = rt.engine.diagnostics();+ diag.composition_mode = rt.composition_mode.clone();+ return diag;+ }+ }+ EngineDiagnostics::default()+ }+}++#[cfg(not(target_os = "windows"))]+mod win_host {+ use super::*;+ pub fn init_for_main_window(+ _app_handle: tauri::AppHandle,+ _main_window: &tauri::WebviewWindow,+ ) -> Result<(), String> {+ Ok(())+ }+ pub fn shutdown() {}+ pub fn is_active() -> bool {+ false+ }+ pub fn set_viewport(_viewport: ViewportRect, _visible: bool) -> Result<(), String> {+ Ok(())+ }+ pub fn set_occluded_rects(_rects: Vec<UiRect>) {}+ pub fn set_document(_width: u32, _height: u32, _show_checkerboard: bool) {}+ pub fn set_appearance(_matte_rgba: [f32; 4], _show_checkerboard: bool) {}+ pub fn set_camera(_camera: CameraState) {}+ pub fn set_cursor(_config: CursorConfig) {}+ pub fn set_brush(_params: BrushParams) {}+ pub fn set_policy(_policy: InteractionPolicy) {}+ pub fn clear_canvas() {}+ pub fn sync_active_document() {}+ pub fn set_vram_budget(_budget_bytes: u64) {}+ pub fn flush_gpu_pool() {}+ pub fn gpu_pool_stats() -> GpuPoolStats {+ GpuPoolStats::default()+ }+ pub fn get_diagnostics() -> EngineDiagnostics {+ EngineDiagnostics::default()+ }+}++pub use win_host::{+ clear_canvas, flush_gpu_pool, get_diagnostics, gpu_pool_stats, init_for_main_window,+ is_active, set_appearance, set_brush, set_camera, set_cursor, set_document,+ set_occluded_rects, set_policy, set_viewport, set_vram_budget, shutdown, sync_active_document,+};diff --git a/src-tauri/src/psd_parser.rs b/src-tauri/src/psd_parser.rsindex 60e7e6a..f1d4f08 100644--- a/src-tauri/src/psd_parser.rs+++ b/src-tauri/src/psd_parser.rs@@ -850,8 +850,8 @@ fn decode_merged_composite(}/// Parses a Photoshop `.psd` or `.psb` file buffer natively in Rust with Rayon parallelism,-/// returning the compact `INKD` binary wire frame with LZ4-compressed sparse 256x256 tiles.-pub fn parse_psd_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {+/// returning raw assembled layers ready for direct zero-copy hydration into `ink-engine`.+pub fn parse_psd_assembled(bytes: &[u8]) -> Result<crate::doc_wire::ParsedDocumentAssembled, String> {let mut cur = Cursor::new(bytes);// 1. File Header (26 bytes)@@ -1135,7 +1135,28 @@ pub fn parse_psd_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {}}- pack_parsed_document(width, height, dpi, ink_color_mode, None, assembled)+ Ok(crate::doc_wire::ParsedDocumentAssembled {+ width,+ height,+ dpi,+ color_mode: ink_color_mode.to_string(),+ preview: None,+ layers: assembled,+ })+}++/// Parses a Photoshop `.psd` or `.psb` file buffer natively in Rust with Rayon parallelism,+/// returning the compact `INKD` binary wire frame with LZ4-compressed sparse 256x256 tiles.+pub fn parse_psd_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {+ let parsed = parse_psd_assembled(bytes)?;+ pack_parsed_document(+ parsed.width,+ parsed.height,+ parsed.dpi,+ &parsed.color_mode,+ parsed.preview,+ parsed.layers,+ )}#[cfg(test)]diff --git a/src-tauri/src/scratch_disk.rs b/src-tauri/src/scratch_disk.rsindex 2b65c80..64771f9 100644--- a/src-tauri/src/scratch_disk.rs+++ b/src-tauri/src/scratch_disk.rs@@ -1,9 +1,9 @@use serde::{Deserialize, Serialize};use std::collections::HashMap;+use std::io::{Read, Seek, Write};use std::path::PathBuf;use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Mutex, RwLock};-use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt, SeekFrom};#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]@@ -32,8 +32,8 @@ type ScratchRegistry = Mutex<HashMap<String, HashMap<String, HashMap<(i32, i32),static SCRATCH_REGISTRY: std::sync::LazyLock<ScratchRegistry> =std::sync::LazyLock::new(|| Mutex::new(HashMap::new()));-static SCRATCH_IO_LOCK: std::sync::LazyLock<tokio::sync::Mutex<()>> =- std::sync::LazyLock::new(|| tokio::sync::Mutex::new(()));+static SCRATCH_IO_LOCK: std::sync::LazyLock<Mutex<()>> =+ std::sync::LazyLock::new(|| Mutex::new(()));static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);@@ -196,10 +196,11 @@ fn sanitize_layer_id(layer_id: &str) -> String {}}-pub async fn init_scratch_disk(session_id: &str) -> Result<PathBuf, String> {+/// Synchronous in-process scratch disk initialization used directly by `ink-engine`+/// (zero Tauri IPC).+pub fn init_scratch_disk_sync(session_id: &str) -> Result<PathBuf, String> {let dir = get_scratch_root(session_id);- tokio::fs::create_dir_all(&dir)- .await+ std::fs::create_dir_all(&dir).map_err(|e| format!("Failed to create scratch directory: {}", e))?;{@@ -212,6 +213,13 @@ pub async fn init_scratch_disk(session_id: &str) -> Result<PathBuf, String> {Ok(dir)}+pub async fn init_scratch_disk(session_id: &str) -> Result<PathBuf, String> {+ let sid = session_id.to_string();+ tokio::task::spawn_blocking(move || init_scratch_disk_sync(&sid))+ .await+ .map_err(|e| format!("Scratch disk init worker failed: {}", e))?+}+struct CompressedTileWrite {tile_x: i32,tile_y: i32,@@ -219,7 +227,9 @@ struct CompressedTileWrite {compressed: Vec<u8>,}-pub async fn write_tiles(+/// Synchronous in-process scratch disk tile writer used directly by `ink-engine`'s L3 tier+/// (zero Tauri IPC) and delegated to by the async Tauri command wrapper.+pub fn write_tiles_sync(session_id: &str,tiles: Vec<TileWritePayload>,) -> Result<usize, String> {@@ -228,44 +238,36 @@ pub async fn write_tiles(}let use_lz4 = is_scratch_compression_enabled();-- // Validate & optionally LZ4-compress tiles off Tokio async worker threads and BEFORE acquiring SCRATCH_IO_LOCK- let compressed_by_layer = tokio::task::spawn_blocking(move || -> Result<(usize, HashMap<String, Vec<CompressedTileWrite>>), String> {- let mut grouped: HashMap<String, Vec<CompressedTileWrite>> = HashMap::new();- let count = tiles.len();- for tile in tiles {- if tile.data.len() > MAX_UNCOMPRESSED_TILE_BYTES {- return Err("Tile uncompressed payload exceeds 4 MB safety ceiling".to_string());- }- let raw_len = tile.data.len() as u32;- let (uncompressed_len, payload) = if use_lz4 {- (raw_len, lz4_flex::compress_prepend_size(&tile.data))- } else {- (raw_len | RAW_TILE_FLAG, tile.data)- };- grouped- .entry(tile.layer_id)- .or_default()- .push(CompressedTileWrite {- tile_x: tile.tile_x,- tile_y: tile.tile_y,- uncompressed_len,- compressed: payload,- });+ let count_written = tiles.len();+ let mut tiles_by_layer: HashMap<String, Vec<CompressedTileWrite>> = HashMap::new();+ for tile in tiles {+ if tile.data.len() > MAX_UNCOMPRESSED_TILE_BYTES {+ return Err("Tile uncompressed payload exceeds 4 MB safety ceiling".to_string());}- Ok((count, grouped))- })- .await- .map_err(|e| format!("Scratch disk LZ4 compression worker failed: {}", e))??;-- let (count_written, tiles_by_layer) = compressed_by_layer;+ let raw_len = tile.data.len() as u32;+ let (uncompressed_len, payload) = if use_lz4 {+ (raw_len, lz4_flex::compress_prepend_size(&tile.data))+ } else {+ (raw_len | RAW_TILE_FLAG, tile.data)+ };+ tiles_by_layer+ .entry(tile.layer_id)+ .or_default()+ .push(CompressedTileWrite {+ tile_x: tile.tile_x,+ tile_y: tile.tile_y,+ uncompressed_len,+ compressed: payload,+ });+ }- let _io_guard = SCRATCH_IO_LOCK.lock().await;+ let _io_guard = SCRATCH_IO_LOCK+ .lock()+ .map_err(|_| "Failed to acquire scratch disk I/O lock".to_string())?;let scratch_dir = get_scratch_root(session_id);if !scratch_dir.exists() {- tokio::fs::create_dir_all(&scratch_dir)- .await+ std::fs::create_dir_all(&scratch_dir).map_err(|e| format!("Failed to create scratch dir: {}", e))?;}@@ -276,7 +278,6 @@ pub async fn write_tiles(let seq = TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);let index_tmp_path = scratch_dir.join(format!("index_{}_{}.tmp", safe_name, seq));- // Snapshot existing entries for this layer so we can reuse in-place slots when compressed data fitslet existing_layer_entries = {let reg = SCRATCH_REGISTRY.lock()@@ -287,18 +288,16 @@ pub async fn write_tiles(.unwrap_or_default()};- // Open bucket file in read+write mode- let mut bucket_file = tokio::fs::OpenOptions::new()+ let mut bucket_file = std::fs::OpenOptions::new().create(true)+ .truncate(false).read(true).write(true).open(&bucket_path)- .await.map_err(|e| format!("Failed to open bucket file {}: {}", bucket_path.display(), e))?;let mut end_offset = bucket_file- .seek(SeekFrom::End(0))- .await+ .seek(std::io::SeekFrom::End(0)).map_err(|e| format!("Failed to seek bucket file: {}", e))?;let mut new_entries: Vec<TileIndexEntry> = Vec::with_capacity(layer_tiles.len());@@ -306,35 +305,32 @@ pub async fn write_tiles(for tile in layer_tiles {let compressed_len = tile.compressed.len() as u32;- let write_offset = if let Some(prev) = existing_layer_entries.get(&(tile.tile_x, tile.tile_y)) {- if compressed_len <= prev.compressed_len {- bucket_file- .seek(SeekFrom::Start(prev.offset))- .await- .map_err(|e| format!("Failed to seek bucket file: {}", e))?;- prev.offset+ let write_offset =+ if let Some(prev) = existing_layer_entries.get(&(tile.tile_x, tile.tile_y)) {+ if compressed_len <= prev.compressed_len {+ bucket_file+ .seek(std::io::SeekFrom::Start(prev.offset))+ .map_err(|e| format!("Failed to seek bucket file: {}", e))?;+ prev.offset+ } else {+ bucket_file+ .seek(std::io::SeekFrom::Start(end_offset))+ .map_err(|e| format!("Failed to seek bucket file: {}", e))?;+ let off = end_offset;+ end_offset += compressed_len as u64;+ off+ }} else {bucket_file- .seek(SeekFrom::Start(end_offset))- .await+ .seek(std::io::SeekFrom::Start(end_offset)).map_err(|e| format!("Failed to seek bucket file: {}", e))?;let off = end_offset;end_offset += compressed_len as u64;off- }- } else {- bucket_file- .seek(SeekFrom::Start(end_offset))- .await- .map_err(|e| format!("Failed to seek bucket file: {}", e))?;- let off = end_offset;- end_offset += compressed_len as u64;- off- };+ };bucket_file.write_all(&tile.compressed)- .await.map_err(|e| format!("Failed to write to bucket file: {}", e))?;new_entries.push(TileIndexEntry {@@ -348,10 +344,8 @@ pub async fn write_tiles(bucket_file.flush()- .await.map_err(|e| format!("Failed to flush bucket file: {}", e))?;- // Update in-memory registry and prepare binary index bytes without holding lock across awaitlet index_bytes = {let mut reg = SCRATCH_REGISTRY.lock()@@ -379,15 +373,12 @@ pub async fn write_tiles(bytes};- // Atomically write index table to .tmp then rename (with fallback remove on Windows)- tokio::fs::write(&index_tmp_path, &index_bytes)- .await+ std::fs::write(&index_tmp_path, &index_bytes).map_err(|e| format!("Failed to write index temp file: {}", e))?;- if tokio::fs::rename(&index_tmp_path, &index_path).await.is_err() {- let _ = tokio::fs::remove_file(&index_path).await;- tokio::fs::rename(&index_tmp_path, &index_path)- .await+ if std::fs::rename(&index_tmp_path, &index_path).is_err() {+ let _ = std::fs::remove_file(&index_path);+ std::fs::rename(&index_tmp_path, &index_path).map_err(|e| format!("Failed to atomically update index file: {}", e))?;}}@@ -395,126 +386,147 @@ pub async fn write_tiles(Ok(count_written)}-pub async fn read_tile(+pub async fn write_tiles(+ session_id: &str,+ tiles: Vec<TileWritePayload>,+) -> Result<usize, String> {+ if tiles.is_empty() {+ return Ok(0);+ }+ let sid = session_id.to_string();+ tokio::task::spawn_blocking(move || write_tiles_sync(&sid, tiles))+ .await+ .map_err(|e| format!("Scratch disk write worker failed: {}", e))?+}++/// Synchronous in-process scratch disk tile reader used directly by `ink-engine`'s L3 tier+/// (zero Tauri IPC).+pub fn read_tile_sync(session_id: &str,layer_id: &str,tile_x: i32,tile_y: i32,) -> Result<Vec<u8>, String> {- let _io_guard = SCRATCH_IO_LOCK.lock().await;-- // 1. Look up in in-memory registry first- let entry = {- let reg = SCRATCH_REGISTRY+ let (entry, compressed_buf) = {+ let _io_guard = SCRATCH_IO_LOCK.lock()- .map_err(|_| "Failed to lock scratch registry".to_string())?;+ .map_err(|_| "Failed to acquire scratch disk I/O lock".to_string())?;- reg.get(session_id)- .and_then(|sm| sm.get(layer_id))- .and_then(|lm| lm.get(&(tile_x, tile_y)).copied())- };+ // 1. Look up in in-memory registry first+ let entry = {+ let reg = SCRATCH_REGISTRY+ .lock()+ .map_err(|_| "Failed to lock scratch registry".to_string())?;- let entry = match entry {- Some(e) => e,- None => {- // Not in memory; attempt to load index table from disk- let safe_name = sanitize_layer_id(layer_id);- let index_path = get_scratch_root(session_id).join(format!("index_{}.bin", safe_name));- if !index_path.exists() {- return Err(format!(- "Tile index not found for layer {} (tile=[{}, {}])",- layer_id, tile_x, tile_y- ));- }+ reg.get(session_id)+ .and_then(|sm| sm.get(layer_id))+ .and_then(|lm| lm.get(&(tile_x, tile_y)).copied())+ };- let data = tokio::fs::read(&index_path)- .await- .map_err(|e| format!("Failed to read index file: {}", e))?;+ let entry = match entry {+ Some(e) => e,+ None => {+ // Not in memory; attempt to load index table from disk+ let safe_name = sanitize_layer_id(layer_id);+ let index_path =+ get_scratch_root(session_id).join(format!("index_{}.bin", safe_name));+ if !index_path.exists() {+ return Err(format!(+ "Tile index not found for layer {} (tile=[{}, {}])",+ layer_id, tile_x, tile_y+ ));+ }- if data.len() < 4 {- return Err("Corrupt index table: header too short".to_string());- }+ let data = std::fs::read(&index_path)+ .map_err(|e| format!("Failed to read index file: {}", e))?;- let count = u32::from_le_bytes(data[0..4].try_into().unwrap()) as usize;- let mut offset = 4;- let mut found_entry: Option<TileIndexEntry> = None;-- {- let mut reg = SCRATCH_REGISTRY- .lock()- .map_err(|_| "Failed to lock scratch registry".to_string())?;-- let session_map = reg.entry(session_id.to_string()).or_default();- let layer_map = session_map.entry(layer_id.to_string()).or_default();-- for _ in 0..count {- if offset + 24 <= data.len() {- let tx = i32::from_le_bytes(data[offset..offset + 4].try_into().unwrap());- let ty = i32::from_le_bytes(data[offset + 4..offset + 8].try_into().unwrap());- let off = u64::from_le_bytes(data[offset + 8..offset + 16].try_into().unwrap());- let clen = u32::from_le_bytes(data[offset + 16..offset + 20].try_into().unwrap());- let ulen = u32::from_le_bytes(data[offset + 20..offset + 24].try_into().unwrap());- offset += 24;-- let ent = TileIndexEntry {- tile_x: tx,- tile_y: ty,- offset: off,- compressed_len: clen,- uncompressed_len: ulen,- };-- if tx == tile_x && ty == tile_y {- found_entry = Some(ent);- }+ if data.len() < 4 {+ return Err("Corrupt index table: header too short".to_string());+ }- layer_map.insert((tx, ty), ent);+ let count = u32::from_le_bytes(data[0..4].try_into().unwrap()) as usize;+ let mut offset = 4;+ let mut found_entry: Option<TileIndexEntry> = None;++ {+ let mut reg = SCRATCH_REGISTRY+ .lock()+ .map_err(|_| "Failed to lock scratch registry".to_string())?;++ let session_map = reg.entry(session_id.to_string()).or_default();+ let layer_map = session_map.entry(layer_id.to_string()).or_default();++ for _ in 0..count {+ if offset + 24 <= data.len() {+ let tx =+ i32::from_le_bytes(data[offset..offset + 4].try_into().unwrap());+ let ty = i32::from_le_bytes(+ data[offset + 4..offset + 8].try_into().unwrap(),+ );+ let off = u64::from_le_bytes(+ data[offset + 8..offset + 16].try_into().unwrap(),+ );+ let clen = u32::from_le_bytes(+ data[offset + 16..offset + 20].try_into().unwrap(),+ );+ let ulen = u32::from_le_bytes(+ data[offset + 20..offset + 24].try_into().unwrap(),+ );+ offset += 24;++ let ent = TileIndexEntry {+ tile_x: tx,+ tile_y: ty,+ offset: off,+ compressed_len: clen,+ uncompressed_len: ulen,+ };++ if tx == tile_x && ty == tile_y {+ found_entry = Some(ent);+ }++ layer_map.insert((tx, ty), ent);+ }}}++ found_entry.ok_or_else(|| {+ format!(+ "Tile not found in index (session={}, layer={}, tile=[{}, {}])",+ session_id, layer_id, tile_x, tile_y+ )+ })?}+ };- found_entry.ok_or_else(|| {- format!(- "Tile not found in index (session={}, layer={}, tile=[{}, {}])",- session_id, layer_id, tile_x, tile_y- )- })?+ let logical_uncompressed_len = (entry.uncompressed_len & RAW_TILE_LEN_MASK) as usize;+ if entry.compressed_len == 0+ || entry.compressed_len > MAX_COMPRESSED_TILE_BYTES+ || logical_uncompressed_len > MAX_UNCOMPRESSED_TILE_BYTES+ {+ return Err("Corrupt or oversized tile index entry".to_string());}- };-- let is_raw_tile = (entry.uncompressed_len & RAW_TILE_FLAG) != 0;- let logical_uncompressed_len = (entry.uncompressed_len & RAW_TILE_LEN_MASK) as usize;-- if entry.compressed_len == 0- || entry.compressed_len > MAX_COMPRESSED_TILE_BYTES- || logical_uncompressed_len > MAX_UNCOMPRESSED_TILE_BYTES- {- return Err("Corrupt or oversized tile index entry".to_string());- }- // 2. Read payload from bucket file- let safe_name = sanitize_layer_id(layer_id);- let bucket_path = get_scratch_root(session_id).join(format!("bucket_{}.bin", safe_name));+ let safe_name = sanitize_layer_id(layer_id);+ let bucket_path = get_scratch_root(session_id).join(format!("bucket_{}.bin", safe_name));- let mut bucket_file = tokio::fs::File::open(&bucket_path)- .await- .map_err(|e| format!("Failed to open bucket file {}: {}", bucket_path.display(), e))?;+ let mut bucket_file = std::fs::File::open(&bucket_path)+ .map_err(|e| format!("Failed to open bucket file {}: {}", bucket_path.display(), e))?;- bucket_file- .seek(SeekFrom::Start(entry.offset))- .await- .map_err(|e| format!("Failed to seek to tile offset {}: {}", entry.offset, e))?;+ bucket_file+ .seek(std::io::SeekFrom::Start(entry.offset))+ .map_err(|e| format!("Failed to seek to tile offset {}: {}", entry.offset, e))?;- let mut compressed_buf = vec![0u8; entry.compressed_len as usize];- bucket_file- .read_exact(&mut compressed_buf)- .await- .map_err(|e| format!("Failed to read compressed tile bytes: {}", e))?;+ let mut buf = vec![0u8; entry.compressed_len as usize];+ bucket_file+ .read_exact(&mut buf)+ .map_err(|e| format!("Failed to read compressed tile bytes: {}", e))?;- // Release file/IO mutex before CPU decompression- drop(bucket_file);- drop(_io_guard);+ (entry, buf)+ };+ let is_raw_tile = (entry.uncompressed_len & RAW_TILE_FLAG) != 0;if is_raw_tile {return Ok(compressed_buf);}@@ -522,46 +534,56 @@ pub async fn read_tile(if compressed_buf.len() < 4 {return Err("Corrupt LZ4 tile header".to_string());}- let declared_uncompressed = u32::from_le_bytes(compressed_buf[0..4].try_into().unwrap()) as usize;+ let declared_uncompressed =+ u32::from_le_bytes(compressed_buf[0..4].try_into().unwrap()) as usize;if declared_uncompressed > MAX_UNCOMPRESSED_TILE_BYTES {return Err("LZ4 declared uncompressed size exceeds 4 MB safety ceiling".to_string());}- // 3. Decompress using LZ4 (offload large tiles to blocking pool)- let decompressed = if declared_uncompressed >= 131_072 {- tokio::task::spawn_blocking(move || {- lz4_flex::decompress_size_prepended(&compressed_buf)- .map_err(|e| format!("LZ4 decompression failed: {}", e))- })- .await- .map_err(|e| format!("LZ4 decompression worker failed: {}", e))??- } else {- lz4_flex::decompress_size_prepended(&compressed_buf)- .map_err(|e| format!("LZ4 decompression failed: {}", e))?- };+ lz4_flex::decompress_size_prepended(&compressed_buf)+ .map_err(|e| format!("LZ4 decompression failed: {}", e))+}- Ok(decompressed)+pub async fn read_tile(+ session_id: &str,+ layer_id: &str,+ tile_x: i32,+ tile_y: i32,+) -> Result<Vec<u8>, String> {+ let sid = session_id.to_string();+ let lid = layer_id.to_string();+ tokio::task::spawn_blocking(move || read_tile_sync(&sid, &lid, tile_x, tile_y))+ .await+ .map_err(|e| format!("Scratch disk read worker failed: {}", e))?}-pub async fn clear_scratch_disk(session_id: &str) -> Result<(), String> {- let _io_guard = SCRATCH_IO_LOCK.lock().await;+/// Synchronous in-process scratch disk cleanup used directly by `ink-engine`.+pub fn clear_scratch_disk_sync(session_id: &str) -> Result<(), String> {+ let _io_guard = SCRATCH_IO_LOCK+ .lock()+ .map_err(|_| "Failed to acquire scratch disk I/O lock".to_string())?;- // 1. Remove from in-memory registryif let Ok(mut reg) = SCRATCH_REGISTRY.lock() {reg.remove(session_id);}- // 2. Recursively delete disk fileslet dir = get_scratch_root(session_id);if dir.exists() {- tokio::fs::remove_dir_all(&dir)- .await- .map_err(|e| format!("Failed to remove scratch directory {}: {}", dir.display(), e))?;+ std::fs::remove_dir_all(&dir).map_err(|e| {+ format!("Failed to remove scratch directory {}: {}", dir.display(), e)+ })?;}Ok(())}+pub async fn clear_scratch_disk(session_id: &str) -> Result<(), String> {+ let sid = session_id.to_string();+ tokio::task::spawn_blocking(move || clear_scratch_disk_sync(&sid))+ .await+ .map_err(|e| format!("Scratch disk clear worker failed: {}", e))?+}+#[cfg(test)]mod tests {use super::*;diff --git a/src-tauri/src/tablet_input.rs b/src-tauri/src/tablet_input.rsindex c873d6c..b8d1d81 100644--- a/src-tauri/src/tablet_input.rs+++ b/src-tauri/src/tablet_input.rs@@ -661,7 +661,11 @@ mod win_impl {}}- fn screen_to_css_client_f64(main_hwnd: HWND, sx: f64, sy: f64) -> (f32, f32) {+ fn screen_to_physical_and_css_client_f64(+ main_hwnd: HWND,+ sx: f64,+ sy: f64,+ ) -> ((f32, f32), (f32, f32)) {unsafe {let ix = sx.floor() as i32;let iy = sy.floor() as i32;@@ -669,11 +673,13 @@ mod win_impl {let fy = sy - (iy as f64);let mut pt = POINT { x: ix, y: iy };ScreenToClient(main_hwnd, &mut pt);+ let phys_x = (pt.x as f64 + fx) as f32;+ let phys_y = (pt.y as f64 + fy) as f32;let dpi = GetDpiForWindow(main_hwnd);let scale = if dpi > 0 { (dpi as f64) / 96.0 } else { 1.0 };(- ((pt.x as f64 + fx) / scale) as f32,- ((pt.y as f64 + fy) / scale) as f32,+ (phys_x, phys_y),+ ((phys_x as f64 / scale) as f32, (phys_y as f64 / scale) as f32),)}}@@ -765,8 +771,148 @@ mod win_impl {static WINTAB_MSG_HWND: AtomicIsize = AtomicIsize::new(0);static WINTAB_FOCUS_SUBCLASS_HWND: AtomicIsize = AtomicIsize::new(0);static LAST_WINTAB_PACKET_MS_BITS: AtomicU64 = AtomicU64::new(0);+ static LAST_STYLUS_ACTIVITY_MS_BITS: AtomicU64 = AtomicU64::new(0);static WINTAB_THREAD: LazyLock<Mutex<Option<JoinHandle<()>>>> =LazyLock::new(|| Mutex::new(None));++ // Lock-free SPSC ring handoff slots into `ink-engine` (claimed once per producer thread).+ static ENGINE_ATTACHED: AtomicBool = AtomicBool::new(false);+ static WINTAB_RING_PENDING: AtomicBool = AtomicBool::new(false);+ static WININK_RING_PENDING: AtomicBool = AtomicBool::new(false);+ static WINTAB_RING_SLOT: LazyLock<Mutex<Option<ink_engine::TabletRingProducer>>> =+ LazyLock::new(|| Mutex::new(None));+ static WININK_RING_SLOT: LazyLock<Mutex<Option<ink_engine::TabletRingProducer>>> =+ LazyLock::new(|| Mutex::new(None));+ static ENGINE_HIT_TEST: LazyLock<Mutex<Option<ink_engine::SharedHitTest>>> =+ LazyLock::new(|| Mutex::new(None));++ struct WinInkEngineLocal {+ tx: Option<ink_engine::TabletRingProducer>,+ hit_test: Option<ink_engine::SharedHitTest>,+ native_stroke_owned: bool,+ }++ thread_local! {+ static WININK_ENGINE: std::cell::RefCell<WinInkEngineLocal> =+ const { std::cell::RefCell::new(WinInkEngineLocal { tx: None, hit_test: None, native_stroke_owned: false }) };+ }++ pub fn attach_engine_rings(+ wintab_tx: ink_engine::TabletRingProducer,+ winink_tx: ink_engine::TabletRingProducer,+ hit_test: ink_engine::SharedHitTest,+ ) {+ if let Ok(mut guard) = ENGINE_HIT_TEST.lock() {+ *guard = Some(hit_test);+ }+ if let Ok(mut guard) = WINTAB_RING_SLOT.lock() {+ *guard = Some(wintab_tx);+ }+ if let Ok(mut guard) = WININK_RING_SLOT.lock() {+ *guard = Some(winink_tx);+ }+ WINTAB_RING_PENDING.store(true, Ordering::Release);+ WININK_RING_PENDING.store(true, Ordering::Release);+ ENGINE_ATTACHED.store(true, Ordering::Release);+ }++ pub fn detach_engine_rings() {+ ENGINE_ATTACHED.store(false, Ordering::SeqCst);+ WINTAB_RING_PENDING.store(false, Ordering::SeqCst);+ WININK_RING_PENDING.store(false, Ordering::SeqCst);+ if let Ok(mut guard) = WINTAB_RING_SLOT.lock() {+ *guard = None;+ }+ if let Ok(mut guard) = WININK_RING_SLOT.lock() {+ *guard = None;+ }+ if let Ok(mut guard) = ENGINE_HIT_TEST.lock() {+ *guard = None;+ }+ // Clear UI-thread TLS if called on the main thread+ WININK_ENGINE.with(|cell| {+ let mut st = cell.borrow_mut();+ st.tx = None;+ st.hit_test = None;+ st.native_stroke_owned = false;+ });+ }++ #[inline]+ pub fn last_stylus_activity_ms() -> f64 {+ let bits = LAST_STYLUS_ACTIVITY_MS_BITS.load(Ordering::Relaxed);+ if bits == 0 {+ 0.0+ } else {+ f64::from_bits(bits)+ }+ }++ fn take_wintab_engine_binding() -> (+ Option<ink_engine::TabletRingProducer>,+ Option<ink_engine::SharedHitTest>,+ ) {+ if !ENGINE_ATTACHED.load(Ordering::Acquire) {+ return (None, None);+ }+ let tx = WINTAB_RING_SLOT.lock().ok().and_then(|mut g| g.take());+ let ht = ENGINE_HIT_TEST.lock().ok().and_then(|g| g.clone());+ if tx.is_some() {+ WINTAB_RING_PENDING.store(false, Ordering::Release);+ }+ (tx, ht)+ }++ fn sync_winink_engine_local(local: &mut WinInkEngineLocal) {+ if !ENGINE_ATTACHED.load(Ordering::Acquire) {+ local.tx = None;+ local.hit_test = None;+ local.native_stroke_owned = false;+ return;+ }+ if local.tx.is_none() && WININK_RING_PENDING.load(Ordering::Acquire) {+ local.tx = WININK_RING_SLOT.lock().ok().and_then(|mut g| g.take());+ local.hit_test = ENGINE_HIT_TEST.lock().ok().and_then(|g| g.clone());+ if local.tx.is_some() {+ WININK_RING_PENDING.store(false, Ordering::Release);+ }+ }+ }++ #[inline]+ fn route_sample_ownership(+ native_owned: &mut bool,+ hit_test: Option<&ink_engine::SharedHitTest>,+ phys_x: f32,+ phys_y: f32,+ phase: u8,+ ) -> bool {+ let Some(ht) = hit_test else {+ *native_owned = false;+ return false;+ };+ match phase {+ 1 => {+ // Pen down: capture natively iff landing inside unoccluded canvas viewport+ // for a native-handled tool (Brush/Eraser).+ let owned = ht.should_capture_native_stroke(phys_x, phys_y);+ *native_owned = owned;+ owned+ }+ 2 => *native_owned,+ 3 | 4 => {+ let was_owned = *native_owned;+ *native_owned = false;+ was_owned+ }+ 0 => {+ // Hover: suppress JS Channel flood while hovering unoccluded native canvas+ // so the native GPU brush cursor handles 240Hz hover with zero IPC.+ ht.should_capture_native_stroke(phys_x, phys_y)+ }+ _ => false,+ }+ }static CURRENT_STATUS: LazyLock<Mutex<TabletStatus>> = LazyLock::new(|| {Mutex::new(TabletStatus {active: false,@@ -815,18 +961,42 @@ mod win_impl {.map(|mut dedup| dedup.force_end_all_active()).unwrap_or(false);if had_active {- send_samples(&[TabletSample {- client_x: 0.0,- client_y: 0.0,- pressure: 0.0,- tilt_x: 0.0,- tilt_y: 0.0,- twist: 0.0,- timestamp_ms: qpc_now_ms(),- buttons: 0,- phase: 3,- backend: 2,- }]);+ let ts = qpc_now_ms();+ let was_native = WININK_ENGINE.with(|cell| {+ let mut local = cell.borrow_mut();+ sync_winink_engine_local(&mut local);+ if let Some(tx) = local.tx.as_mut() {+ tx.push(ink_engine::NativeInputSample {+ phys_x: 0.0,+ phys_y: 0.0,+ pressure: 0.0,+ tilt_x: 0.0,+ tilt_y: 0.0,+ twist: 0.0,+ timestamp_ms: ts,+ buttons: 0,+ phase: 3,+ backend: 2,+ });+ }+ let owned = local.native_stroke_owned;+ local.native_stroke_owned = false;+ owned+ });+ if !was_native {+ send_samples(&[TabletSample {+ client_x: 0.0,+ client_y: 0.0,+ pressure: 0.0,+ tilt_x: 0.0,+ tilt_y: 0.0,+ twist: 0.0,+ timestamp_ms: ts,+ buttons: 0,+ phase: 3,+ backend: 2,+ }]);+ }}return;}@@ -889,9 +1059,11 @@ mod win_impl {let prev_perf_cutoff = decision.prev_perf_cutoff;let prev_ts_ms = decision.prev_ts_ms;- let mut samples = Vec::with_capacity(n);+ let mut js_samples = Vec::with_capacity(n);+ let mut native_samples = Vec::with_capacity(n);let mut max_perf_emitted = prev_perf_cutoff;let mut running_ts = prev_ts_ms;+ LAST_STYLUS_ACTIVITY_MS_BITS.store(ts_now.to_bits(), Ordering::Relaxed);// Fallback span when hardware PerformanceCount is unavailablelet fallback_span = if prev_ts_ms > 0.0 && ts_now > prev_ts_ms + 0.5 {@@ -925,7 +1097,8 @@ mod win_impl {pinfo.ptPixelLocationRaw.x,pinfo.ptPixelLocationRaw.y,);- let (cx, cy) = screen_to_css_client_f64(main_hwnd, sx, sy);+ let ((phys_x, phys_y), (cx, cy)) =+ screen_to_physical_and_css_client_f64(main_hwnd, sx, sy);let in_contact = (pinfo.pointerFlags & POINTER_FLAG_INCONTACT) != 0;let pressure = if (info.penMask & PEN_MASK_PRESSURE) != 0 {@@ -990,7 +1163,20 @@ mod win_impl {};running_ts = sample_ts;- samples.push(TabletSample {+ native_samples.push(ink_engine::NativeInputSample {+ phys_x,+ phys_y,+ pressure,+ tilt_x,+ tilt_y,+ twist,+ timestamp_ms: sample_ts,+ buttons,+ phase: sample_phase,+ backend: 2,+ });++ js_samples.push(TabletSample {client_x: cx,client_y: cy,pressure,@@ -1004,7 +1190,7 @@ mod win_impl {});}- if !samples.is_empty() {+ if !native_samples.is_empty() {if let Ok(mut dedup) = INK_DEDUP.lock() {dedup.record_emitted(pointer_id,@@ -1013,7 +1199,40 @@ mod win_impl {running_ts,);}- send_samples(&samples);++ // Push directly into lock-free SPSC ring for `ink-engine` (zero IPC),+ // and suppress Tauri Channel forwarding when natively owned.+ let mut forward_js: Vec<TabletSample> = Vec::new();+ WININK_ENGINE.with(|cell| {+ let mut local = cell.borrow_mut();+ sync_winink_engine_local(&mut local);+ let WinInkEngineLocal {+ tx,+ hit_test,+ native_stroke_owned,+ } = &mut *local;+ if let Some(tx) = tx.as_mut() {+ tx.push_batch(&native_samples);+ for (ns, js) in native_samples.iter().zip(js_samples) {+ let owned_by_engine = route_sample_ownership(+ native_stroke_owned,+ hit_test.as_ref(),+ ns.phys_x,+ ns.phys_y,+ ns.phase,+ );+ if !owned_by_engine {+ forward_js.push(js);+ }+ }+ } else {+ forward_js = js_samples;+ }+ });++ if !forward_js.is_empty() {+ send_samples(&forward_js);+ }}}}@@ -1091,6 +1310,9 @@ mod win_impl {contact: WintabContactState,was_foreground: bool,last_ts_ms: f64,+ engine_tx: Option<ink_engine::TabletRingProducer>,+ hit_test: Option<ink_engine::SharedHitTest>,+ native_stroke_owned: bool,}thread_local! {@@ -1185,18 +1407,37 @@ mod win_impl {rt.was_foreground = false;if rt.contact.was_down {rt.contact.reset();- send_samples(&[TabletSample {- client_x: 0.0,- client_y: 0.0,- pressure: 0.0,- tilt_x: 0.0,- tilt_y: 0.0,- twist: 0.0,- timestamp_ms: qpc_now_ms(),- buttons: 0,- phase: 3,- backend: 1,- }]);+ let ts = qpc_now_ms();+ if let Some(tx) = rt.engine_tx.as_mut() {+ tx.push(ink_engine::NativeInputSample {+ phys_x: 0.0,+ phys_y: 0.0,+ pressure: 0.0,+ tilt_x: 0.0,+ tilt_y: 0.0,+ twist: 0.0,+ timestamp_ms: ts,+ buttons: 0,+ phase: 3,+ backend: 1,+ });+ }+ let was_native = rt.native_stroke_owned;+ rt.native_stroke_owned = false;+ if !was_native {+ send_samples(&[TabletSample {+ client_x: 0.0,+ client_y: 0.0,+ pressure: 0.0,+ tilt_x: 0.0,+ tilt_y: 0.0,+ twist: 0.0,+ timestamp_ms: ts,+ buttons: 0,+ phase: 3,+ backend: 1,+ }]);+ }}});} else if msg == WT_PACKET {@@ -1204,6 +1445,19 @@ mod win_impl {let mut borrow = cell.borrow_mut();let Some(rt) = borrow.as_mut() else { return };+ // Lazily claim/drop engine SPSC ring producer if engine attached/detached+ if !ENGINE_ATTACHED.load(Ordering::Acquire) {+ rt.engine_tx = None;+ rt.hit_test = None;+ rt.native_stroke_owned = false;+ } else if rt.engine_tx.is_none()+ && WINTAB_RING_PENDING.load(Ordering::Acquire)+ {+ let (tx, ht) = take_wintab_engine_binding();+ rt.engine_tx = tx;+ rt.hit_test = ht;+ }+// Only assert WinTab Z-order overlap when foreground transitions to our window// (avoid calling WTOverlap at 250Hz inside every WT_PACKET, which stalls some drivers)let is_fg = GetForegroundWindow() == rt.main_hwnd;@@ -1223,7 +1477,9 @@ mod win_impl {let count = n as usize;let ts_now = qpc_now_ms();LAST_WINTAB_PACKET_MS_BITS.store(ts_now.to_bits(), Ordering::Relaxed);- let mut samples = Vec::with_capacity(count);+ LAST_STYLUS_ACTIVITY_MS_BITS.store(ts_now.to_bits(), Ordering::Relaxed);+ let mut native_samples = Vec::with_capacity(count);+ let mut forward_js = Vec::new();let denom_p = (rt.max_pressure.max(1)) as f32;let mut cur_pt = POINT { x: 0, y: 0 };@@ -1265,7 +1521,7 @@ mod win_impl {let fallback_start = ts_now - fallback_span;for (idx, pkt) in buf[..count].iter().enumerate() {- // Map WinTab high-res output space -> sub-pixel virtual screen -> CSS client pixels.+ // Map WinTab high-res output space -> sub-pixel virtual screen -> physical + CSS client pixels.// Pass cursor_pos only for the newest packet in the burst so older history points// preserve exact sub-pixel positions while still guarding against driver quirks.let pkt_cursor = if idx + 1 == count { cursor_pos } else { None };@@ -1282,7 +1538,8 @@ mod win_impl {rt.sys_ext_y,pkt_cursor,);- let (cx, cy) = screen_to_css_client_f64(rt.main_hwnd, sx, sy);+ let ((phys_x, phys_y), (cx, cy)) =+ screen_to_physical_and_css_client_f64(rt.main_hwnd, sx, sy);let raw_pressure = (pkt.pk_normal_pressure as f32 / denom_p).clamp(0.0, 1.0);let (tilt_x, tilt_y, twist) = wintab_orientation_to_tilt(@@ -1331,9 +1588,9 @@ mod win_impl {buttons |= 8;}- samples.push(TabletSample {- client_x: cx,- client_y: cy,+ native_samples.push(ink_engine::NativeInputSample {+ phys_x,+ phys_y,pressure,tilt_x,tilt_y,@@ -1343,30 +1600,85 @@ mod win_impl {phase,backend: 1,});++ let owned_by_engine = if rt.engine_tx.is_some() {+ route_sample_ownership(+ &mut rt.native_stroke_owned,+ rt.hit_test.as_ref(),+ phys_x,+ phys_y,+ phase,+ )+ } else {+ false+ };++ if !owned_by_engine {+ forward_js.push(TabletSample {+ client_x: cx,+ client_y: cy,+ pressure,+ tilt_x,+ tilt_y,+ twist,+ timestamp_ms: sample_ts,+ buttons,+ phase,+ backend: 1,+ });+ }}- send_samples(&samples);+ // Lock-free SPSC push directly into `ink-engine` (zero IPC, immediate wake)+ if let Some(tx) = rt.engine_tx.as_mut() {+ tx.push_batch(&native_samples);+ }+ if !forward_js.is_empty() {+ send_samples(&forward_js);+ }});} else if msg == WT_PROXIMITY {let entering = (lparam & 0xFFFF) != 0;if !entering {- WT_RT.with(|cell| {+ let ts = qpc_now_ms();+ let was_native = WT_RT.with(|cell| {if let Some(rt) = cell.borrow_mut().as_mut() {rt.contact.reset();+ if let Some(tx) = rt.engine_tx.as_mut() {+ tx.push(ink_engine::NativeInputSample {+ phys_x: 0.0,+ phys_y: 0.0,+ pressure: 0.0,+ tilt_x: 0.0,+ tilt_y: 0.0,+ twist: 0.0,+ timestamp_ms: ts,+ buttons: 0,+ phase: 4,+ backend: 1,+ });+ }+ let owned = rt.native_stroke_owned;+ rt.native_stroke_owned = false;+ owned+ } else {+ false}});- send_samples(&[TabletSample {- client_x: 0.0,- client_y: 0.0,- pressure: 0.0,- tilt_x: 0.0,- tilt_y: 0.0,- twist: 0.0,- timestamp_ms: qpc_now_ms(),- buttons: 0,- phase: 4,- backend: 1,- }]);+ if !was_native {+ send_samples(&[TabletSample {+ client_x: 0.0,+ client_y: 0.0,+ pressure: 0.0,+ tilt_x: 0.0,+ tilt_y: 0.0,+ twist: 0.0,+ timestamp_ms: ts,+ buttons: 0,+ phase: 4,+ backend: 1,+ }]);+ }}}});@@ -1561,6 +1873,8 @@ mod win_impl {}WINTAB_MSG_HWND.store(msg_hwnd as isize, Ordering::Release);+ let (engine_tx, hit_test) = take_wintab_engine_binding();+WT_RT.with(|cell| {*cell.borrow_mut() = Some(WintabRuntime {lib,@@ -1582,6 +1896,9 @@ mod win_impl {contact: WintabContactState::default(),was_foreground: GetForegroundWindow() == main_hwnd as HWND,last_ts_ms: 0.0,+ engine_tx,+ hit_test,+ native_stroke_owned: false,});});@@ -1597,7 +1914,16 @@ mod win_impl {WINTAB_MSG_HWND.store(0, Ordering::Release);WT_RT.with(|cell| {- if let Some(rt) = cell.borrow_mut().take() {+ if let Some(mut rt) = cell.borrow_mut().take() {+ // Preserve SPSC producer across WinTab restarts while engine is attached+ if ENGINE_ATTACHED.load(Ordering::Acquire) {+ if let Some(producer) = rt.engine_tx.take() {+ if let Ok(mut slot) = WINTAB_RING_SLOT.lock() {+ *slot = Some(producer);+ WINTAB_RING_PENDING.store(true, Ordering::Release);+ }+ }+ }(rt.lib.wt_close)(rt.hctx);}});@@ -1738,6 +2064,53 @@ mod win_impl {}}+ pub fn start_native_only_if_idle(main_hwnd_raw: isize) {+ if main_hwnd_raw == 0 {+ return;+ }+ let already_active = CURRENT_STATUS+ .lock()+ .map(|st| st.active)+ .unwrap_or(false);+ if already_active {+ return;+ }+ let (wt_avail, _, _) = probe_wintab();+ let (chosen_backend, device_name, max_pressure) = if wt_avail {+ match start_wintab_thread(main_hwnd_raw) {+ Ok((dev, mp)) => {+ let _ = install_windows_ink_hooks(main_hwnd_raw as HWND);+ ("wintab".to_string(), dev, mp)+ }+ Err(_) => {+ let _ = install_windows_ink_hooks(main_hwnd_raw as HWND);+ (+ "windows-ink".to_string(),+ Some("Windows Ink Digitizer".to_string()),+ 1024,+ )+ }+ }+ } else {+ let _ = install_windows_ink_hooks(main_hwnd_raw as HWND);+ (+ "windows-ink".to_string(),+ Some("Windows Ink Digitizer".to_string()),+ 1024,+ )+ };+ if let Ok(mut st) = CURRENT_STATUS.lock() {+ *st = TabletStatus {+ active: true,+ backend: chosen_backend,+ wintab_available: wt_avail,+ windows_ink_available: true,+ device_name,+ max_pressure,+ };+ }+ }+pub fn get_status() -> TabletStatus {if let Ok(st) = CURRENT_STATUS.lock() {if st.active {@@ -1815,6 +2188,30 @@ pub fn get_tablet_status() -> TabletStatus {}}+#[cfg(target_os = "windows")]+pub fn attach_engine_rings(+ wintab_tx: ink_engine::TabletRingProducer,+ winink_tx: ink_engine::TabletRingProducer,+ hit_test: ink_engine::SharedHitTest,+) {+ win_impl::attach_engine_rings(wintab_tx, winink_tx, hit_test);+}++#[cfg(target_os = "windows")]+pub fn detach_engine_rings() {+ win_impl::detach_engine_rings();+}++#[cfg(target_os = "windows")]+pub fn start_native_only_if_idle(main_hwnd_raw: isize) {+ win_impl::start_native_only_if_idle(main_hwnd_raw);+}++#[cfg(target_os = "windows")]+pub fn last_stylus_activity_ms() -> f64 {+ win_impl::last_stylus_activity_ms()+}+#[cfg(test)]mod tests {use super::*;diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex f8b457f..e22e3c7 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -20,6 +20,7 @@"minHeight": 600,"maximized": true,"decorations": false,+ "transparent": true,"additionalBrowserArgs": "--disable-features=StylusHandwritingWin,StylusHandwriting,msAbydos,msAbydosHandwritingAttr,msAbydosGestureSupport"}],diff --git a/src/components/AnimationTimeline.tsx b/src/components/AnimationTimeline.tsxindex 144da42..cb8772a 100644--- a/src/components/AnimationTimeline.tsx+++ b/src/components/AnimationTimeline.tsx@@ -232,6 +232,7 @@ export const AnimationTimeline: React.FC<AnimationTimelineProps> = ({return (<divref={timelineRootRef}+ data-native-occluder="true"tabIndex={-1}className="absolute inset-x-0 bottom-0 z-40 bg-ui-panel border-t border-ui-default shadow-ui-floating flex flex-col select-none text-xs text-ui-primary outline-none">diff --git a/src/components/CanvasArea.tsx b/src/components/CanvasArea.tsxindex 3cb2c56..6febf0c 100644--- a/src/components/CanvasArea.tsx+++ b/src/components/CanvasArea.tsx@@ -13,6 +13,7 @@ import { useCompositorViewport } from './canvasArea/useCompositorViewport';import { useCanvasPointerHandlers } from './canvasArea/useCanvasPointerHandlers';import { CanvasArtboardOverlays } from './canvasArea/CanvasArtboardOverlays';import { CanvasViewportHud } from './canvasArea/CanvasViewportHud';+import { useNativeEngineViewport } from '../hooks/useNativeEngineViewport';export { extractCoalescedEvents };@@ -97,6 +98,37 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {const artboardRef = useRef<HTMLDivElement | null>(null);+ const isNativeBrushOrEraser = tool === 'brush' || tool === 'eraser';+ const {+ nativeActive,+ diagnostics: nativeDiagnostics,+ onClearNativeCanvas,+ } = useNativeEngineViewport({+ viewportRef,+ navigation,+ dimensions,+ showCheckerboard,+ hasOpenDocument,+ tool,+ brushSettings,+ primaryColor,+ isSquare: isNativeBrushOrEraser && brushSettings.preset === 'square-digital',+ thicknessRatio: isNativeBrushOrEraser ? (brushSettings.thickness ?? 1.0) : 1.0,+ thicknessVertical: Boolean(brushSettings.thicknessVertical && isNativeBrushOrEraser),+ tipAngleDeg: isNativeBrushOrEraser ? (brushSettings.customTipAngle ?? 0) : 0,+ isResizingBrush,+ isSpaceDown,+ isPanning,+ isRotating,+ isZoomDragging,+ isRotateModifier,+ pan: livePan,+ zoom: liveZoom,+ rotation: liveRotation,+ flipX: liveFlipX,+ flipY: liveFlipY,+ });+const {tipOutline,isCustomTip,@@ -141,6 +173,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {setQuickPalettePos,resizeOriginRef,resizeStartSettingsRef,+ nativeCanvasActive: nativeActive,});const { viewportCanvasRef, compositorKey } = useCompositorViewport({@@ -174,6 +207,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {brushOpacity: brushSettings.opacity,colorMode,tileGrid,+ nativeCanvasActive: nativeActive,});const {@@ -212,6 +246,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {onPointerDown,onPointerMove,onPointerUp,+ nativeCanvasActive: nativeActive,});const cursorStyleBase = {@@ -291,7 +326,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {zoom={zoom}/>)}- {/* Unified GPU Viewport Canvas (WebGL2 with Frustum Culling & Shaders, or Canvas 2D Software) */}+ {/* Unified GPU Viewport Canvas (hidden when Native Windows DX12 DirectComposition visual is active underneath) */}<canvaskey={compositorKey}ref={viewportCanvasRef}@@ -299,7 +334,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {style={{width: '100%',height: '100%',- display: 'block',+ display: nativeActive ? 'none' : 'block',}}/>@@ -424,6 +459,9 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {resizePreviewY={resizePreviewY}quickPalettePos={quickPalettePos}setQuickPalettePos={setQuickPalettePos}+ nativeCanvasActive={nativeActive}+ nativeDiagnostics={nativeDiagnostics}+ onClearNativeCanvas={onClearNativeCanvas}/></main>);diff --git a/src/components/DocumentLifecycleManager.tsx b/src/components/DocumentLifecycleManager.tsxindex 18aa280..fef5530 100644--- a/src/components/DocumentLifecycleManager.tsx+++ b/src/components/DocumentLifecycleManager.tsx@@ -69,6 +69,20 @@ import {readTauriPathAsFile,takePendingOpenFiles,} from '../utils/osFileOpen';+import {+ closeNativeDocument,+ fromNativeLayerNodeMeta,+ isNativeCanvasActive,+ nativeRecoveryRestore,+ openNativeDocumentBytes,+ openNativeDocumentFromPath,+ purgeNativeMemory,+ resizeNativeCanvas,+ saveNativeInkDocument,+ saveNativeInkDocumentWithDialog,+ setNativeMemoryBudget,+ vramBudgetMbFromPreset,+} from '../utils/nativeEngineBridge';import { t } from '../i18n';function hasMeaningfulLayerEdit(prev: LayerItem[], next: LayerItem[]): boolean {@@ -524,16 +538,44 @@ export function useDocumentLifecycle({: null;const beforeSelection = cloneSelectionForHistory(getSelection?.() ?? null);- const resizeRes = resizeCanvas(newDims, options) as CanvasResizeResult | void;+ const useNativeResize = isNativeCanvasActive() && Boolean(activeId);+ const resizeRes = useNativeResize+ ? undefined+ : (resizeCanvas(newDims, options) as CanvasResizeResult | void);++ const scaleContent = resizeRes ? resizeRes.scaleContent : Boolean(options.scaleContent);+ let offsetX = resizeRes ? resizeRes.offsetX : 0;+ let offsetY = resizeRes ? resizeRes.offsetY : 0;+ if (useNativeResize && !scaleContent) {+ const anchor = options.anchor || 'center';+ const dw = newDims.width - curDims.width;+ const dh = newDims.height - curDims.height;+ if (anchor.includes('left')) offsetX = 0;+ else if (anchor.includes('right')) offsetX = dw;+ else offsetX = Math.round(dw / 2);+ if (anchor.includes('top')) offsetY = 0;+ else if (anchor.includes('bottom')) offsetY = dh;+ else offsetY = Math.round(dh / 2);+ }++ if (useNativeResize && activeId) {+ void resizeNativeCanvas({+ docId: activeId,+ dimensions: newDims,+ offsetX,+ offsetY,+ scaleContent,+ bgHex: options.backgroundColor || '#ffffff',+ recordHistory: true,+ });+ }+if (clearSelectionWithoutHistory) {clearSelectionWithoutHistory();} else {onDeselectAfterPaste?.();}- const scaleContent = resizeRes ? resizeRes.scaleContent : Boolean(options.scaleContent);- const offsetX = resizeRes ? resizeRes.offsetX : 0;- const offsetY = resizeRes ? resizeRes.offsetY : 0;const scaleX = resizeRes ? resizeRes.scaleX : newDims.width / Math.max(1, curDims.width);const scaleY = resizeRes ? resizeRes.scaleY : newDims.height / Math.max(1, curDims.height);const afterPersp = transformPerspectiveRulerForResize(@@ -749,7 +791,6 @@ export function useDocumentLifecycle({try {uiStoreActions.setLoading(true, t('Loading {name}...', { name: file.name }));- const doc = await openFile(file);const alreadyOpenId = options?.docId? useDocumentStore.getState().documents.some((d) => d.id === options.docId): false;@@ -766,6 +807,44 @@ export function useDocumentLifecycle({const realDiskPath = isRealNativeDiskPath(candidateSourcePath)? candidateSourcePath: null;++ const isNativeZeroCopyFormat =+ openedExt === '.ink' ||+ openedExt === '.clip' ||+ openedExt === '.csp' ||+ openedExt === '.lip' ||+ openedExt === '.psd' ||+ openedExt === '.psb';++ let doc: LoadedDocument;+ let openedDirectlyInRust = false;++ if (isNativeCanvasActive() && isNativeZeroCopyFormat) {+ // Phase 2 Zero-Copy Rust Hydration: parses .ink / .clip / .psd directly into+ // crates/ink-engine SparseLayerGrid and returns ONLY compact metadata + 64x64 thumbnails!+ const nativeRes = realDiskPath+ ? await openNativeDocumentFromPath(newDocId, realDiskPath)+ : await openNativeDocumentBytes(+ newDocId,+ file.name,+ new Uint8Array(await file.arrayBuffer())+ );+ openedDirectlyInRust = true;+ doc = {+ name: nativeRes.doc.name || file.name,+ dimensions: nativeRes.doc.dimensions,+ colorMode: nativeRes.doc.colorMode,+ layers: nativeRes.doc.layers.map(fromNativeLayerNodeMeta),+ previewDataUrl: nativeRes.previewDataUrl ?? nativeRes.doc.previewDataUrl ?? undefined,+ perspectiveRuler: (nativeRes.doc.perspectiveRuler as any) ?? null,+ animationTimeline: nativeRes.doc.animationTimeline as any,+ timelapse: (nativeRes.doc.timelapse as any) ?? null,+ workTimeMs: nativeRes.doc.workTimeMs,+ };+ } else {+ doc = await openFile(file);+ }+const initialSavedInfo =(fileHandle || realDiskPath) && DIRECT_SAVE_EXTENSIONS.has(openedExt)? {@@ -782,7 +861,7 @@ export function useDocumentLifecycle({documentStoreActions.setDocumentName(doc.name);documentStoreActions.setSavedFileInfo(initialSavedInfo);- loadDocument(doc, newDocId);+ loadDocument(doc, newDocId, openedDirectlyInRust);needsAdaptiveFitRef.current = true;pendingFitDimsRef.current = doc.dimensions;resetZoomAndCenter(doc.dimensions);@@ -867,6 +946,9 @@ export function useDocumentLifecycle({globalTimelapseManager.detachSession(replacedAutoDocId).catch(console.warn);documentStore.closeSession(replacedAutoDocId).catch(console.warn);recoveryService.closeSession(replacedAutoDocId).catch(console.warn);+ if (isNativeCanvasActive()) {+ void closeNativeDocument(replacedAutoDocId);+ }}documentStoreActions.setActiveDocumentId(newDocId);uiStoreActions.setAppView('workspace');@@ -1022,6 +1104,9 @@ export function useDocumentLifecycle({globalTimelapseManager.detachSession(id).catch(console.warn);documentStore.closeSession(id).catch(console.warn);recoveryService.closeSession(id).catch(console.warn);+ if (isNativeCanvasActive()) {+ void closeNativeDocument(id);+ }}},[activeDocumentId, clearDocument, resetZoomAndCenter, switchDocumentSession]@@ -1030,6 +1115,59 @@ export function useDocumentLifecycle({const handleRestoreCrashedSession = useCallback(async (session: CrashedSessionInfo) => {try {+ if (isNativeCanvasActive()) {+ // Phase 2 Zero-Copy Rust Recovery: replays INKG v1 snapshot + TD v1 WAL directly in Rust!+ const restoredMeta = await nativeRecoveryRestore(+ session.session_id,+ session.session_id+ );+ const restoredLayers = restoredMeta.layers.map(fromNativeLayerNodeMeta);+ const restoredDims: CanvasDimensions = restoredMeta.dimensions;+ loadDocument(+ {+ name: restoredMeta.name,+ dimensions: restoredDims,+ colorMode: restoredMeta.colorMode,+ layers: restoredLayers,+ },+ session.session_id,+ true+ );+ if (restoredMeta.activeLayerId) {+ setActiveLayerId(restoredMeta.activeLayerId);+ }+ documentStoreActions.setDimensions(restoredDims);+ documentStoreActions.setColorMode(restoredMeta.colorMode);+ documentStoreActions.setDocumentName(restoredMeta.name);+ const restoredWorkTimeMs = sanitizeWorkTimeMs(restoredMeta.workTimeMs);+ artworkTimeTracker.initDocument(session.session_id, restoredWorkTimeMs);+ const restoredDoc: DocumentTab = {+ id: session.session_id,+ name: restoredMeta.name,+ isDirty: true,+ dimensions: restoredDims,+ colorMode: restoredMeta.colorMode,+ layers: restoredLayers,+ activeLayerId: restoredMeta.activeLayerId || restoredLayers[0]?.id || '',+ workTimeMs: restoredWorkTimeMs,+ };+ documentStoreActions.setDocuments((prev) => {+ const filtered = prev.filter((d) => d.id !== session.session_id);+ return [restoredDoc, ...filtered];+ });+ documentStoreActions.setActiveDocumentId(session.session_id);+ uiStoreActions.setAppView('workspace');+ needsAdaptiveFitRef.current = true;+ pendingFitDimsRef.current = restoredDims;+ resetZoomAndCenter(restoredDims);+ uiStoreActions.setRecoveryModal(false);+ uiStoreActions.setCrashedSessions((prev) =>+ prev.filter((s) => s.session_id !== session.session_id)+ );+ showToast(t('Restored "{name}"', { name: restoredMeta.name }));+ return;+ }+const replayData = await recoveryService.loadSessionData(session.session_id);const restoredSession = documentStore.getOrCreateSession(session.session_id);const { manifest, replayedStrokesCount, replayedMutationsCount } =@@ -1398,6 +1536,49 @@ export function useDocumentLifecycle({const hasDirectTarget = Boolean(docSavedInfo?.handle || isRealNativeDiskPath(docSavedInfo?.path));++ // Phase 2 Native Rust Direct `.ink` Save: reads sparse tiles straight from crates/ink-engine+ // with Rayon parallel compression and atomic disk write — ZERO JS pixel transfer!+ if (isNativeCanvasActive() && preferredExt.toLowerCase() === '.ink') {+ try {+ uiStoreActions.setLoading(true, t('Saving .ink project...'));+ const nativeSave =+ hasDirectTarget && isRealNativeDiskPath(docSavedInfo?.path)+ ? await saveNativeInkDocument(docId, docSavedInfo!.path!)+ : await saveNativeInkDocumentWithDialog(+ docId,+ `${cleanNameForSave}.ink`,+ initialDir+ );+ if (!nativeSave.path) {+ return 'canceled';+ }+ const fileName = nativeSave.path.split(/[\\/]/).pop() || `${cleanNameForSave}.ink`;+ applySavedMetadata(+ {+ name: fileName,+ path: nativeSave.path,+ extension: '.ink',+ size: nativeSave.bytesWritten,+ previewDataUrl: nativeSave.previewDataUrl ?? undefined,+ },+ true+ );+ void recoveryService.markCleanSaved(docId);+ return 'saved';+ } catch (err: unknown) {+ const msg = err instanceof Error ? err.message : String(err);+ void uiStoreActions.alertDialog({+ title: t('Save Failed'),+ message: t('Failed to save file.'),+ detail: msg,+ });+ return 'error';+ } finally {+ uiStoreActions.setLoading(false, '');+ }+ }+if (!hasDirectTarget || docSavedInfo?.extension?.toLowerCase() === '.sora') {try {const info = await promptSaveAs(docData, preferredExt, true, { initialDir });@@ -1788,8 +1969,18 @@ export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> =documentStore.setTileBudgetMb(appSettings.tileMemoryBudgetMb || 1024);documentStore.setSharedUndoRamStepsBudget(appSettings.undoRamSteps || 15);documentStore.setOffloadInactiveUndoOnSwitch(appSettings.offloadInactiveTabs);+ if (isNativeCanvasActive()) {+ void setNativeMemoryBudget({+ ramBudgetMb: appSettings.tileMemoryBudgetMb || 1024,+ vramBudgetMb: vramBudgetMbFromPreset(appSettings.gpuTexturePoolPreset),+ maxHistorySteps: appSettings.maxHistorySteps || 50,+ offloadInactiveTabs: appSettings.offloadInactiveTabs !== false,+ });+ }}, [appSettings.tileMemoryBudgetMb,+ appSettings.gpuTexturePoolPreset,+ appSettings.maxHistorySteps,appSettings.undoRamSteps,appSettings.offloadInactiveTabs,]);@@ -1800,7 +1991,12 @@ export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> =getTileBudgetBytes: () => documentStore.getTileBudgetBytes(),getUndoStats: () => documentStore.getUndoMemoryStats(),getActiveSessionIds: () => documentStore.getActiveSessionIds(),- purgeTiles: () => documentStore.purgeTileMemory(),+ purgeTiles: async () => {+ if (isNativeCanvasActive()) {+ await purgeNativeMemory();+ }+ return documentStore.purgeTileMemory();+ },purgeUndo: () => documentStore.purgeUndoMemory(),flushBrushGpuCaches: () => WebGlBrushEngine.getInstance().releaseCaches(),});diff --git a/src/components/FloatingBrushPill.tsx b/src/components/FloatingBrushPill.tsxindex 844bbb6..485b76c 100644--- a/src/components/FloatingBrushPill.tsx+++ b/src/components/FloatingBrushPill.tsx@@ -307,6 +307,7 @@ export const FloatingBrushPill: React.FC<FloatingBrushPillProps> = React.memo(({return (<divdata-testid="floating-brush-pill"+ data-native-occluder="true"data-anchor-side={leftHandedMode ? 'right' : 'left'}onPointerDown={(e) => e.stopPropagation()}onWheel={(e) => e.stopPropagation()}diff --git a/src/components/canvasArea/CanvasViewportHud.tsx b/src/components/canvasArea/CanvasViewportHud.tsxindex d394c06..540b3e2 100644--- a/src/components/canvasArea/CanvasViewportHud.tsx+++ b/src/components/canvasArea/CanvasViewportHud.tsx@@ -8,6 +8,7 @@ import { SmartphoneViewportSimulator } from '../SmartphoneViewportSimulator';import { AnimationTimeline } from '../AnimationTimeline';import { CanvasAreaProps } from './types';import { useI18n } from '../../i18n';+import type { NativeEngineDiagnostics } from '../../utils/nativeEngineBridge';export interface CanvasViewportHudProps {canvasProps: CanvasAreaProps;@@ -32,6 +33,9 @@ export interface CanvasViewportHudProps {resizePreviewY: number;quickPalettePos: { x: number; y: number } | null;setQuickPalettePos: React.Dispatch<React.SetStateAction<{ x: number; y: number } | null>>;+ nativeCanvasActive?: boolean;+ nativeDiagnostics?: NativeEngineDiagnostics | null;+ onClearNativeCanvas?: () => void;}export const CanvasViewportHud: React.FC<CanvasViewportHudProps> = ({@@ -57,6 +61,9 @@ export const CanvasViewportHud: React.FC<CanvasViewportHudProps> = ({resizePreviewY,quickPalettePos,setQuickPalettePos,+ nativeCanvasActive = false,+ nativeDiagnostics = null,+ onClearNativeCanvas,}) => {const { t } = useI18n();const {@@ -358,6 +365,7 @@ export const CanvasViewportHud: React.FC<CanvasViewportHudProps> = ({{/* Floating Quick Palette Popover (triggered by modifier mapped to 'quick-palette') */}{quickPalettePos && (<div+ data-native-occluder="true"onPointerDown={(e) => e.stopPropagation()}onContextMenu={(e) => e.preventDefault()}className="absolute z-50 bg-ui-floating border border-ui-default rounded-ui-md shadow-ui-popover p-2.5 w-48 space-y-2 text-[11px] text-ui-primary select-none"@@ -439,7 +447,10 @@ export const CanvasViewportHud: React.FC<CanvasViewportHudProps> = ({{/* Floating Webtoon Mode Controls (only shown when Webtoon Mode is active) */}{isWebtoonMode && (- <div className="absolute top-3 right-3 z-40 flex items-center gap-1.5 select-none">+ <div+ data-native-occluder="true"+ className="absolute top-3 right-3 z-40 flex items-center gap-1.5 select-none"+ ><buttononClick={onToggleWebtoonMode}className="px-2.5 py-1 rounded-full text-[11px] font-medium flex items-center gap-1.5 bg-ui-floating hover:bg-ui-control-hover border border-ui-default text-ui-primary shadow-ui-floating transition-colors cursor-pointer"@@ -478,6 +489,56 @@ export const CanvasViewportHud: React.FC<CanvasViewportHudProps> = ({/>)}+ {/* Native Rust + wgpu (DX12) Perf HUD Readout (Phase 1 Vertical Slice) */}+ {nativeCanvasActive && (+ <div+ data-testid="native-gpu-perf-hud"+ data-native-occluder="true"+ onPointerDown={(e) => e.stopPropagation()}+ onWheel={(e) => e.stopPropagation()}+ className="absolute bottom-2.5 right-3 z-40 flex items-center gap-2 px-2.5 py-1 rounded-ui-md bg-ui-floating border border-ui-default shadow-ui-floating text-[10px] font-ui-mono tabular-nums text-ui-secondary select-none"+ title={+ nativeDiagnostics+ ? `${nativeDiagnostics.adapterName} · ${nativeDiagnostics.compositionMode} · ${nativeDiagnostics.presentMode} (latency=${nativeDiagnostics.maxFrameLatency})`+ : 'Native DX12 Engine'+ }+ >+ <span className="inline-flex items-center gap-1 text-ui-primary font-medium">+ <span className="w-1.5 h-1.5 rounded-full bg-ui-success" />+ {nativeDiagnostics?.backend || 'DX12'}+ </span>+ <span className="max-w-[160px] truncate text-ui-muted">+ {nativeDiagnostics?.adapterName || 'Initializing GPU...'}+ </span>+ <span className="text-ui-subtle">|</span>+ <span className="text-ui-primary">+ {nativeDiagnostics ? `${Math.round(nativeDiagnostics.fps)} FPS` : '-- FPS'}+ </span>+ <span className="text-ui-muted">+ {nativeDiagnostics ? `${nativeDiagnostics.frameTimeMs.toFixed(1)}ms` : '--'}+ </span>+ <span className="text-ui-subtle">|</span>+ <span className="text-ui-primary" title="Input-to-present latency">+ {nativeDiagnostics+ ? `I2P ${nativeDiagnostics.inputToPresentMs.toFixed(2)}ms`+ : 'I2P --'}+ </span>+ {onClearNativeCanvas && (+ <>+ <span className="text-ui-subtle">|</span>+ <button+ type="button"+ onClick={onClearNativeCanvas}+ className="px-1.5 py-0.5 rounded-ui-xs bg-ui-control hover:bg-ui-control-hover text-ui-primary border border-ui-subtle transition-colors cursor-pointer"+ title={t('Clear test GPU stroke canvas')}+ >+ {t('Clear')}+ </button>+ </>+ )}+ </div>+ )}+{/* 2D Frame-by-Frame Animation Timeline Scrubber Dock */}{animationTimeline && onUpdateAnimationTimeline && (<AnimationTimelinediff --git a/src/components/canvasArea/useCanvasEffects.ts b/src/components/canvasArea/useCanvasEffects.tsindex 29b3062..a086d9f 100644--- a/src/components/canvasArea/useCanvasEffects.ts+++ b/src/components/canvasArea/useCanvasEffects.ts@@ -5,6 +5,7 @@ import { getBrushTipOutline, resolveBrushTipImage, TipOutline } from '../../utilimport { computeTipStampDimensions } from '../../engine/BrushEngine';import { preloadTipImage } from '../../utils/brushStorage';import { shouldSuppressDomPointerEvent, subscribeNativeTablet } from '../../utils/nativeTabletInput';+import { isNativeStrokeTool } from '../../utils/nativeEngineBridge';import { isNaturalPaintBrush } from '../../engine/NaturalPaintRenderer';import { useUiStore } from '../../stores';import {@@ -46,6 +47,7 @@ export interface UseCanvasEffectsParams {setQuickPalettePos: React.Dispatch<React.SetStateAction<{ x: number; y: number } | null>>;resizeOriginRef: React.MutableRefObject<{ clientX: number; clientY: number }>;resizeStartSettingsRef: React.MutableRefObject<{ size: number; hardness: number }>;+ nativeCanvasActive?: boolean;}export function useCanvasEffects({@@ -78,6 +80,7 @@ export function useCanvasEffects({setQuickPalettePos,resizeOriginRef,resizeStartSettingsRef,+ nativeCanvasActive = false,}: UseCanvasEffectsParams) {// Resolve tip image and extract vector outline silhouetteconst activeTipImage = resolveBrushTipImage(brushSettings);@@ -270,6 +273,7 @@ export function useCanvasEffects({const isResizeCanvasModalOpen = useUiStore((s) => s.isResizeCanvasModalOpen);const shouldHideCursorRing =+ Boolean(nativeCanvasActive && isNativeStrokeTool(tool)) ||isResizeCanvasModalOpen ||isSpaceDown ||isPanning ||@@ -659,6 +663,8 @@ export function useCanvasEffects({isCursorRotating: cursorRotationSpec.enabled,cursorOrientationOffsetDeg: cursorRotationSpec.orientationOffsetDeg,thicknessRatio,+ thicknessVertical,+ tipAngleDeg,cursorWidth,cursorHeight,totalAngleDeg,diff --git a/src/components/canvasArea/useCanvasPointerHandlers.ts b/src/components/canvasArea/useCanvasPointerHandlers.tsindex fe7ffd1..6c7fd73 100644--- a/src/components/canvasArea/useCanvasPointerHandlers.ts+++ b/src/components/canvasArea/useCanvasPointerHandlers.ts@@ -12,6 +12,7 @@ import { CanvasNavigationHandle } from '../../hooks/useCanvasNavigation';import { screenToCanvas } from '../../utils/canvasUtils';import { resolvePointerModifierAction } from '../../utils/shortcutManager';import { shouldSuppressDomPointerEvent } from '../../utils/nativeTabletInput';+import { isNativeStrokeTool } from '../../utils/nativeEngineBridge';import { isWorkspaceInteractionActive } from '../../utils/workspacePointerGuard';import { artworkTimeTracker } from '../../utils/artworkTimeTracker';import { toolStoreActions, uiStoreActions, useToolStore, useUiStore } from '../../stores';@@ -46,6 +47,7 @@ export interface UseCanvasPointerHandlersParams {onPointerDown: (e: React.PointerEvent<HTMLElement>, coalesced?: PointerEvent[]) => void;onPointerMove: (e: React.PointerEvent<HTMLElement>, coalesced?: PointerEvent[], predicted?: PointerEvent[]) => void;onPointerUp: (e: React.PointerEvent<HTMLElement>) => void;+ nativeCanvasActive?: boolean;}export function useCanvasPointerHandlers({@@ -77,6 +79,7 @@ export function useCanvasPointerHandlers({onPointerDown,onPointerMove,onPointerUp,+ nativeCanvasActive = false,}: UseCanvasPointerHandlersParams) {const tempEraserPrevToolRef = useRef<ToolType | null>(null);const activeDomPointerIdRef = useRef<number | null>(null);@@ -338,6 +341,12 @@ export function useCanvasPointerHandlers({return;}+ // When native DX12 `ink-engine` owns Brush/Eraser strokes directly via lock-free SPSC+ // rings (WinTab/Windows Ink/native mouse), skip JS stroke dispatch completely (zero IPC).+ if (nativeCanvasActive && isNativeStrokeTool(tool)) {+ return;+ }+// Native WinTab / Windows Ink channel owns pen brush/eraser strokes; skip duplicate DOM// pen events AND WinTab CXO_SYSTEM-synthesized mouse events (which carry constant pressure=0.5).if (@@ -368,6 +377,9 @@ export function useCanvasPointerHandlers({const handleCanvasPointerMove = (e: React.PointerEvent<HTMLElement>) => {if (isWorkspaceInteractionActive() || useUiStore.getState().isResizeCanvasModalOpen) return;+ if (nativeCanvasActive && isNativeStrokeTool(tool) && activeDomPointerIdRef.current !== e.pointerId) {+ return;+ }const isTrackedDomStroke = activeDomPointerIdRef.current === e.pointerId;if (!isTrackedDomStroke &&@@ -392,6 +404,14 @@ export function useCanvasPointerHandlers({if (isTrackedDomStroke) {activeDomPointerIdRef.current = null;}+ if (nativeCanvasActive && isNativeStrokeTool(tool) && !isTrackedDomStroke) {+ if (tempEraserPrevToolRef.current !== null) {+ const prev = tempEraserPrevToolRef.current;+ tempEraserPrevToolRef.current = null;+ toolStoreActions.selectTool(prev);+ }+ return;+ }if (isTrackedDomStroke ||!(diff --git a/src/components/canvasArea/useCompositorViewport.ts b/src/components/canvasArea/useCompositorViewport.tsindex 82713bf..53ec552 100644--- a/src/components/canvasArea/useCompositorViewport.ts+++ b/src/components/canvasArea/useCompositorViewport.ts@@ -56,6 +56,7 @@ export interface UseCompositorViewportParams {brushOpacity?: number;colorMode: CanvasColorMode;tileGrid: SparseTileGrid;+ nativeCanvasActive?: boolean;}export function useCompositorViewport({@@ -89,9 +90,12 @@ export function useCompositorViewport({brushOpacity,colorMode,tileGrid,+ nativeCanvasActive = false,}: UseCompositorViewportParams) {const tileGridRef = useRef<SparseTileGrid>(tileGrid);tileGridRef.current = tileGrid;+ const nativeCanvasActiveRef = useRef<boolean>(nativeCanvasActive);+ nativeCanvasActiveRef.current = nativeCanvasActive;// Compute colored onion skin frames and active cel isolation for animationconst onionSkinFrames = useMemo(() => {@@ -378,6 +382,9 @@ export function useCompositorViewport({}}+ if (nativeCanvasActiveRef.current) {+ return;+ }if (viewportCanvasRef.current && !compositorRef.current) {compositorRef.current = new ViewportCompositor(viewportCanvasRef.current);}@@ -437,7 +444,7 @@ export function useCompositorViewport({}const vCanvas = viewportCanvasRef.current;- if (vCanvas) {+ if (vCanvas && !nativeCanvasActiveRef.current) {if (compositorRef.current && compositorRef.current.getCanvas() !== vCanvas) {compositorRef.current.dispose();compositorRef.current = null;@@ -524,6 +531,7 @@ export function useCompositorViewport({// Render scene using Unified GPU Viewport CompositoruseEffect(() => {+ if (nativeCanvasActive) return;const vCanvas = viewportCanvasRef.current;if (!vCanvas) return;if (compositorRef.current && compositorRef.current.getCanvas() !== vCanvas) {@@ -579,10 +587,12 @@ export function useCompositorViewport({perfConfig.canvasFilteringQuality,perfConfig.viewportResolutionScale,interfaceScale,+ nativeCanvasActive,]);// Event-Driven Compositor Invalidation via active document's SparseTileGrid subscriptionuseEffect(() => {+ if (nativeCanvasActive) return;let rafId: number | null = null;const activeGrid = tileGrid;const renderCompositor = () => {@@ -627,7 +637,7 @@ export function useCompositorViewport({unsubscribe();if (rafId !== null) cancelAnimationFrame(rafId);};- }, [tileGrid]);+ }, [tileGrid, nativeCanvasActive]);useEffect(() => {return () => {diff --git a/src/hooks/drawing/useDrawingHistory.ts b/src/hooks/drawing/useDrawingHistory.tsindex 510eb07..bf39a7c 100644--- a/src/hooks/drawing/useDrawingHistory.ts+++ b/src/hooks/drawing/useDrawingHistory.ts@@ -23,6 +23,24 @@ import { documentStore } from '../../utils/documentStore';import { performanceManager } from '../../utils/performanceManager';import { multiplayerService } from '../../services/multiplayerService';import { recoveryService } from '../../services/recoveryService';+import {+ clearNativeLayer,+ fromNativeLayerNodeMeta,+ isNativeCanvasActive,+ nativeGetHistory,+ nativeJumpHistory,+ nativePushHistoryMeta,+ nativeRedo,+ nativeResetHistory,+ nativeSelectiveRedo,+ nativeSelectiveUndo,+ nativeUndo,+ NativeHistoryMutationResult,+ NativeHistoryStateSnapshot,+ requestNativeThumbnails,+ subscribeNativeHistory,+} from '../../utils/nativeEngineBridge';+import { documentStoreActions } from '../../stores';import { renderVectorLayer } from '../../utils/vectorEngine';import { createCanvasThumbnail, formatTime, get2DContext } from '../../utils/canvasUtils';import { canEditLayer } from '../../utils/collabPermissions';@@ -269,7 +287,59 @@ export function useDrawingHistory({);}, []);+ const applyNativeHistorySnapshot = useCallback((snap: NativeHistoryStateSnapshot) => {+ historyIndexRef.current = snap.index;+ setHistoryIndex(snap.index);+ setCanUndo(snap.canUndo);+ setCanRedo(snap.canRedo);+ setHistoryList(snap.items);+ }, []);++ const applyNativeMutationResult = useCallback(+ (res: NativeHistoryMutationResult | null) => {+ if (!res) return;+ applyNativeHistorySnapshot(res.doc.history);+ if (res.dimensionsChanged) {+ dimensionsRef.current = res.doc.dimensions;+ documentStoreActions.setDimensions(res.doc.dimensions, res.doc.id);+ }+ if (res.layersChanged) {+ const hydrated = res.doc.layers.map(fromNativeLayerNodeMeta);+ const prevLayers = layersRef.current ?? [];+ const prevActive = activeLayerIdRef.current;+ const nextActive = res.doc.activeLayerId ?? hydrated[0]?.id ?? '';+ layersRef.current = hydrated;+ if (nextActive) {+ activeLayerIdRef.current = nextActive;+ }+ onApplyLayerTreeDeltaRef?.current?.(+ {+ beforeLayers: prevLayers,+ afterLayers: hydrated,+ beforeActiveLayerId: prevActive,+ afterActiveLayerId: nextActive,+ },+ 'redo'+ );+ }+ if (res.changedLayerIds.length > 0) {+ void requestNativeThumbnails(res.doc.id, res.changedLayerIds);+ }+ },+ [activeLayerIdRef, applyNativeHistorySnapshot, dimensionsRef, layersRef, onApplyLayerTreeDeltaRef]+ );++ // Phase 2: Subscribe to live Rust CoW history updates (e.g. native DX12 brush stroke commits)+ useEffect(() => {+ return subscribeNativeHistory((ev) => {+ if (!isNativeCanvasActive()) return;+ if (activeSessionIdRef.current && ev.docId !== activeSessionIdRef.current) return;+ applyNativeHistorySnapshot(ev.history);+ });+ }, [applyNativeHistorySnapshot]);+const ensureInitialHistory = useCallback(() => {+ if (isNativeCanvasActive()) return;if (historyRef.current.length === 0) {const now = Date.now();const targetLayerId = activeLayerIdRef.current;@@ -318,11 +388,29 @@ export function useDrawingHistory({layerTreeDelta?: LayerTreeDelta,documentStateDelta?: DocumentStateDelta) => {+ const docId = activeSessionIdRef.current;+ // Phase 2 Native Rust path: Rust owns all tile & layer CoW history — never duplicate pixel+ // buffers or TileDeltas in JS RAM/UndoCacheManager. Only push compact document-state metadata.+ if (isNativeCanvasActive() && docId) {+ if (documentStateDelta && !explicitTileDeltas?.length && !layerTreeDelta) {+ void nativePushHistoryMeta({+ docId,+ actionType,+ label,+ layerId: targetLayerId || null,+ documentStateDelta,+ coalesceKey: documentStateDelta.coalesceKey,+ }).then((snap) => {+ if (snap) applyNativeHistorySnapshot(snap);+ });+ }+ return;+ }+ensureInitialHistory();const now = Date.now();const dims = dimensionsRef.current;const grid = activeTileGridRef.current;- const docId = activeSessionIdRef.current;const undoCache = activeUndoCacheRef.current;let tileDeltas = explicitTileDeltas;@@ -831,6 +919,15 @@ export function useDrawingHistory({}lastStrokeEndRef.current = null;+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ return nativeJumpHistory(nativeDocId, targetIndex)+ .then((res) => applyNativeMutationResult(res))+ .catch((err) => {+ console.warn('[History] Native jumpToHistoryIndex failed:', err);+ });+ }+// Fast synchronous path when no async history job is in flight and every touched step is// already resident in RAM (eliminates Ctrl+Z -> quick-draw race conditions).if (inFlightHistoryOpsRef.current === 0) {@@ -953,13 +1050,20 @@ export function useDrawingHistory({if (isDrawingRef.current) {abortActiveStrokeRef.current();}+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ void nativeUndo(nativeDocId)+ .then((res) => applyNativeMutationResult(res))+ .catch((err) => console.warn('[History] Native undo failed:', err));+ return;+ }const baseIndex =pendingTargetIndexRef.current !== null? pendingTargetIndexRef.current: historyIndexRef.current;if (baseIndex <= 0) return;jumpToHistoryIndex(baseIndex - 1);- }, [abortActiveStrokeRef, flushPendingHistoryTasks, isDrawingRef, jumpToHistoryIndex]);+ }, [abortActiveStrokeRef, applyNativeMutationResult, flushPendingHistoryTasks, isDrawingRef, jumpToHistoryIndex]);const selectiveUndo = useCallback((@@ -972,6 +1076,27 @@ export function useDrawingHistory({}lastStrokeEndRef.current = null;+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ return nativeSelectiveUndo(nativeDocId, peerIdToUndo, strokeIdToUndo)+ .then((res) => {+ if (!res) return null;+ applyNativeMutationResult(res);+ const outcome = res.selectiveOutcome;+ if (!outcome?.applied) return null;+ return {+ strokeId: outcome.strokeId ?? undefined,+ layerId: outcome.layerId ?? activeLayerId,+ hadContestedTiles: outcome.contestedTileCount > 0,+ preservedPeerEdits: outcome.preservedPeerEdits,+ };+ })+ .catch((err) => {+ console.warn('[History] Native selectiveUndo failed:', err);+ return null;+ });+ }+let result: SelectiveUndoResult | null = null;const nextOp = historyQueueRef.current.then(async () => {const isLocalUndo = !peerIdToUndo || peerIdToUndo === 'local';@@ -1276,6 +1401,27 @@ export function useDrawingHistory({}lastStrokeEndRef.current = null;+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ return nativeSelectiveRedo(nativeDocId, peerIdToRedo)+ .then((res) => {+ if (!res) return null;+ applyNativeMutationResult(res);+ const outcome = res.selectiveOutcome;+ if (!outcome?.applied) return null;+ return {+ strokeId: outcome.strokeId ?? undefined,+ layerId: outcome.layerId ?? activeLayerId,+ hadContestedTiles: outcome.contestedTileCount > 0,+ preservedPeerEdits: outcome.preservedPeerEdits,+ };+ })+ .catch((err) => {+ console.warn('[History] Native selectiveRedo failed:', err);+ return null;+ });+ }+let result: SelectiveUndoResult | null = null;const nextOp = historyQueueRef.current.then(async () => {const isLocalRedo = !peerIdToRedo || peerIdToRedo === 'local';@@ -1553,6 +1699,13 @@ export function useDrawingHistory({if (isDrawingRef.current) {abortActiveStrokeRef.current();}+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ void nativeRedo(nativeDocId)+ .then((res) => applyNativeMutationResult(res))+ .catch((err) => console.warn('[History] Native redo failed:', err));+ return;+ }if (localRedoStackRef.current.length > 0) {void selectiveRedo('local');return;@@ -1571,13 +1724,24 @@ export function useDrawingHistory({return;}jumpToHistoryIndex(baseIndex + 1);- }, [abortActiveStrokeRef, flushPendingHistoryTasks, isDrawingRef, jumpToHistoryIndex, selectiveRedo]);+ }, [abortActiveStrokeRef, applyNativeMutationResult, flushPendingHistoryTasks, isDrawingRef, jumpToHistoryIndex, selectiveRedo]);const clearCanvas = useCallback(() => {if (!activeLayerId || activeLayerLocked) return;const dims = dimensionsRef.current;if (dims.width <= 0 || dims.height <= 0) return;+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ void clearNativeLayer(nativeDocId, activeLayerId, true).then((snap) => {+ if (snap) {+ applyNativeHistorySnapshot(snap.history);+ void requestNativeThumbnails(nativeDocId, [activeLayerId]);+ }+ });+ return;+ }+const grid = activeTileGridRef.current;const activeLayer = layersRef.current?.find((l) => l.id === activeLayerId);const isBg = isBackgroundLayerId(activeLayerId);@@ -1635,6 +1799,14 @@ export function useDrawingHistory({(targetDocumentId?: string) => {flushPendingHistoryTasks();const docId = targetDocumentId ?? activeSessionIdRef.current;+ if (isNativeCanvasActive() && docId) {+ void nativeResetHistory(docId, t('New Document')).then((snap) => {+ if (snap && (!targetDocumentId || targetDocumentId === activeSessionIdRef.current)) {+ applyNativeHistorySnapshot(snap);+ }+ });+ return;+ }const sess = docId ? documentStore.getSession(docId) : null;const targetCache = sess ? sess.undoCache : activeUndoCacheRef.current;const targetGrid = sess ? sess.tileGrid : activeTileGridRef.current;@@ -1722,6 +1894,14 @@ export function useDrawingHistory({const sess = documentStore.getOrCreateSession(nextDocId);activeTileGridRef.current = tileGrid ?? sess.tileGrid;activeUndoCacheRef.current = sess.undoCache;+ if (isNativeCanvasActive()) {+ void nativeGetHistory(nextDocId).then((snap) => {+ if (snap && activeSessionIdRef.current === nextDocId) {+ applyNativeHistorySnapshot(snap);+ }+ });+ return;+ }historyRef.current = sess.history;historyIndexRef.current = sess.historyIndex;localRedoStackRef.current = sess.localRedoStack;@@ -1737,6 +1917,7 @@ export function useDrawingHistory({}, [abortActiveStrokeRef,activeSessionId,+ applyNativeHistorySnapshot,flushPendingHistoryTasks,isDrawingRef,lastStrokeEndRef,diff --git a/src/hooks/layerManager/useLayerCrud.ts b/src/hooks/layerManager/useLayerCrud.tsindex 655906b..625a845 100644--- a/src/hooks/layerManager/useLayerCrud.ts+++ b/src/hooks/layerManager/useLayerCrud.ts@@ -7,6 +7,15 @@ import {hasTileBackedLayer,} from '../../types/editor';import { get2DContext } from '../../utils/canvasUtils';+import {+ addNativeLayer,+ deleteNativeLayer,+ duplicateNativeLayer,+ isNativeCanvasActive,+ reorderNativeLayers,+ syncNativeLayers,+ updateNativeLayer,+} from '../../utils/nativeEngineBridge';import {computeBatchDeleteLayers,computeBatchReorderLayers,@@ -19,6 +28,7 @@ import { t } from '../../i18n';export function useLayerCrud(ctx: LayerManagerContext) {const {activeTileGridRef,+ activeSessionIdRef,thumbDebounceTimersRef,layers,setLayers,@@ -106,15 +116,20 @@ export function useLayerCrud(ctx: LayerManagerContext) {};let nextLayers = beforeLayers;+ const insertIndex = currentActiveIdx >= 0 ? currentActiveIdx : 0;if (!beforeLayers.some((l) => l.id === id)) {- const insertIndex = currentActiveIdx >= 0 ? currentActiveIdx : 0;nextLayers = [...beforeLayers];nextLayers.splice(insertIndex, 0, createdLayer);layersRef.current = nextLayers;setLayers(nextLayers);}- if (hasTileBackedLayer({ type })) {+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ if (nextLayers !== beforeLayers) {+ void addNativeLayer(nativeDocId, createdLayer, insertIndex, true);+ }+ } else if (hasTileBackedLayer({ type })) {const grid = activeTileGridRef.current;const isMono = createdLayer.expressionColor === 'monochrome';grid.setLayerFormat(id, isMono ? 'monochrome-1bit' : 'color-32bit');@@ -126,7 +141,7 @@ export function useLayerCrud(ctx: LayerManagerContext) {setActiveLayerId(id);}- if (nextLayers !== beforeLayers) {+ if (!nativeDocId && nextLayers !== beforeLayers) {const label =type === 'folder' ? t('Add Folder') :type === 'vector' ? t('Add Vector Layer') :@@ -143,7 +158,7 @@ export function useLayerCrud(ctx: LayerManagerContext) {return createdLayer;},- [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setActiveLayerId, setLayers]+ [activeLayerIdRef, activeSessionIdRef, activeTileGridRef, layersRef, recordLayerHistory, setActiveLayerId, setLayers]);// Duplicate an existing layer or folder hierarchy with a single click@@ -152,6 +167,26 @@ export function useLayerCrud(ctx: LayerManagerContext) {const beforeActiveLayerId = activeLayerIdRef.current;const sourceIdx = prev.findIndex((l) => l.id === id);if (sourceIdx < 0) return;++ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId && !isFolderLikeLayer(prev[sourceIdx])) {+ const source = prev[sourceIdx];+ const newId = `${source.type}-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;+ const cloned: LayerItem = {+ ...source,+ id: newId,+ name: t('{name} Copy', { name: source.name }),+ };+ const nextLayers = [...prev];+ nextLayers.splice(sourceIdx, 0, cloned);+ layersRef.current = nextLayers;+ setLayers(nextLayers);+ setActiveLayerId(newId);+ // O(1) Rust Copy-on-Write Arc<TileData> duplication — zero JS tile clones!+ void duplicateNativeLayer(nativeDocId, source.id, newId, true);+ return;+ }+const grid = activeTileGridRef.current;const allTileDeltas: TileDelta[] = [];@@ -255,6 +290,21 @@ export function useLayerCrud(ctx: LayerManagerContext) {const res = computeBatchDeleteLayers(prev, [id], beforeActiveLayerId);if (res.deletedIds.length === 0) return;+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ layersRef.current = res.nextLayers;+ setLayers(res.nextLayers);+ if (res.deletedIds.includes(beforeActiveLayerId)) {+ setActiveLayerId(res.nextActiveId);+ } else {+ setSelectedLayerIds((prevSelected) =>+ prevSelected.filter((sid) => !res.deletedIds.includes(sid))+ );+ }+ void deleteNativeLayer(nativeDocId, id, true);+ return;+ }+const grid = activeTileGridRef.current;const deletedTileDeltas: TileDelta[] = [];@@ -300,7 +350,7 @@ export function useLayerCrud(ctx: LayerManagerContext) {deletedTileDeltas,'layer');- }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setActiveLayerId, setLayers, setSelectedLayerIds, thumbDebounceTimersRef]);+ }, [activeLayerIdRef, activeSessionIdRef, activeTileGridRef, layersRef, recordLayerHistory, setActiveLayerId, setLayers, setSelectedLayerIds, thumbDebounceTimersRef]);// Delete all selected layers or foldersconst deleteSelectedLayers = useCallback(() => {@@ -309,6 +359,15 @@ export function useLayerCrud(ctx: LayerManagerContext) {const res = computeBatchDeleteLayers(prev, selectedLayerIdsRef.current, beforeActiveLayerId);if (res.deletedIds.length === 0) return;+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ layersRef.current = res.nextLayers;+ setLayers(res.nextLayers);+ setActiveLayerId(res.nextActiveId);+ void syncNativeLayers(nativeDocId, res.nextLayers, res.nextActiveId);+ return;+ }+const grid = activeTileGridRef.current;const deletedTileDeltas: TileDelta[] = [];@@ -347,7 +406,7 @@ export function useLayerCrud(ctx: LayerManagerContext) {deletedTileDeltas,'layer');- }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, selectedLayerIdsRef, setActiveLayerId, setLayers, thumbDebounceTimersRef]);+ }, [activeLayerIdRef, activeSessionIdRef, activeTileGridRef, layersRef, recordLayerHistory, selectedLayerIdsRef, setActiveLayerId, setLayers, thumbDebounceTimersRef]);// Group all currently selected layers into a new folderconst groupSelectedLayers = useCallback(() => {@@ -360,6 +419,12 @@ export function useLayerCrud(ctx: LayerManagerContext) {setLayers(res.nextLayers);setActiveLayerId(res.newFolder.id);+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ void syncNativeLayers(nativeDocId, res.nextLayers, res.newFolder.id);+ return;+ }+recordLayerHistory(t('Group Layers'),res.newFolder.id,@@ -367,7 +432,7 @@ export function useLayerCrud(ctx: LayerManagerContext) {undefined,'layer');- }, [activeLayerIdRef, layersRef, recordLayerHistory, selectedLayerIdsRef, setActiveLayerId, setLayers]);+ }, [activeLayerIdRef, activeSessionIdRef, layersRef, recordLayerHistory, selectedLayerIdsRef, setActiveLayerId, setLayers]);// Rename a layerconst renameLayer = useCallback((id: string, newName: string) => {@@ -380,6 +445,15 @@ export function useLayerCrud(ctx: LayerManagerContext) {const next = prev.map((l) => (l.id === id ? { ...l, name: trimmed } : l));layersRef.current = next;setLayers(next);+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ void updateNativeLayer(nativeDocId, id, {+ name: trimmed,+ recordHistory: true,+ historyLabel: t('Rename Layer'),+ });+ return;+ }recordLayerHistory(t('Rename Layer'),id,@@ -387,7 +461,7 @@ export function useLayerCrud(ctx: LayerManagerContext) {undefined,'layer');- }, [activeLayerIdRef, layersRef, recordLayerHistory, setLayers]);+ }, [activeLayerIdRef, activeSessionIdRef, layersRef, recordLayerHistory, setLayers]);// Move layer up or down in visual stackconst moveLayer = useCallback((id: string, direction: 'up' | 'down') => {@@ -403,6 +477,11 @@ export function useLayerCrud(ctx: LayerManagerContext) {next.splice(targetIdx, 0, item);layersRef.current = next;setLayers(next);+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ void reorderNativeLayers(nativeDocId, next.map((l) => l.id), undefined, true);+ return;+ }activeTileGridRef.current.notifyChange(true);recordLayerHistory(t('Reorder Layer'),@@ -411,7 +490,7 @@ export function useLayerCrud(ctx: LayerManagerContext) {undefined,'layer');- }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);+ }, [activeLayerIdRef, activeSessionIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Move layer into a specific folder or to rootconst moveLayerToFolder = useCallback((id: string, targetFolderId: string | null) => {@@ -431,6 +510,15 @@ export function useLayerCrud(ctx: LayerManagerContext) {const next = prev.map((l) => (l.id === id ? { ...l, parentId: targetFolderId } : l));layersRef.current = next;setLayers(next);+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ void updateNativeLayer(nativeDocId, id, {+ parentId: targetFolderId,+ recordHistory: true,+ historyLabel: t('Move Layer to Folder'),+ });+ return;+ }activeTileGridRef.current.notifyChange(true);recordLayerHistory(t('Move Layer to Folder'),@@ -439,7 +527,7 @@ export function useLayerCrud(ctx: LayerManagerContext) {undefined,'layer');- }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);+ }, [activeLayerIdRef, activeSessionIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Reorder layer via drag-and-drop (supports multi-layer selection)const reorderLayers = useCallback((draggedId: string, targetId: string, position: 'above' | 'below' | 'inside') => {@@ -448,6 +536,15 @@ export function useLayerCrud(ctx: LayerManagerContext) {if (next === prev) return;layersRef.current = next;setLayers(next);+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ const parentOverrides: Record<string, string | null> = {};+ for (const l of next) {+ parentOverrides[l.id] = l.parentId ?? null;+ }+ void reorderNativeLayers(nativeDocId, next.map((l) => l.id), parentOverrides, true);+ return;+ }activeTileGridRef.current.notifyChange(true);recordLayerHistory(t('Reorder Layers'),@@ -456,7 +553,7 @@ export function useLayerCrud(ctx: LayerManagerContext) {undefined,'layer');- }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, selectedLayerIdsRef, setLayers]);+ }, [activeLayerIdRef, activeSessionIdRef, activeTileGridRef, layersRef, recordLayerHistory, selectedLayerIdsRef, setLayers]);// Move selected layers into a target parent folder or indexconst moveSelectedLayers = useCallback((targetParentId: string | null, targetIndex?: number) => {@@ -510,6 +607,15 @@ export function useLayerCrud(ctx: LayerManagerContext) {remaining.splice(insertIdx, 0, ...movingItems);layersRef.current = remaining;setLayers(remaining);+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ const parentOverrides: Record<string, string | null> = {};+ for (const l of remaining) {+ parentOverrides[l.id] = l.parentId ?? null;+ }+ void reorderNativeLayers(nativeDocId, remaining.map((l) => l.id), parentOverrides, true);+ return;+ }activeTileGridRef.current.notifyChange(true);recordLayerHistory(t('Move Layers'),@@ -518,7 +624,7 @@ export function useLayerCrud(ctx: LayerManagerContext) {undefined,'layer');- }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, selectedLayerIdsRef, setLayers]);+ }, [activeLayerIdRef, activeSessionIdRef, activeTileGridRef, layersRef, recordLayerHistory, selectedLayerIdsRef, setLayers]);// Calculate effective opacity accounting for parent foldersconst getEffectiveOpacity = useCallback((layer: LayerItem): number => {diff --git a/src/hooks/layerManager/useLayerDocumentOps.ts b/src/hooks/layerManager/useLayerDocumentOps.tsindex aa04179..4865340 100644--- a/src/hooks/layerManager/useLayerDocumentOps.ts+++ b/src/hooks/layerManager/useLayerDocumentOps.ts@@ -13,6 +13,16 @@ import { documentStore } from '../../utils/documentStore';import { multiplayerService } from '../../services/multiplayerService';import { compositeCanvas } from '../../utils/saveManager/gpuComposite';import { releaseTemporaryCanvas } from '../../utils/tileEngine';+import {+ clearNativeLayer,+ createNativeDocument,+ ingestNativeDirtyRect,+ isNativeCanvasActive,+ mergeNativeDown,+ mergeNativeFolder,+ requestNativeThumbnails,+ switchNativeDocument,+} from '../../utils/nativeEngineBridge';import {computeMergeFolderLayers,createLayerTreeSnapshotDelta,@@ -40,10 +50,17 @@ export function useLayerDocumentOps(} = ctx;const { updateLayerThumbnail } = canvasRegistry;- // Clear active layer content directly in SparseTileGrid (zero forced full canvas allocation)+ // Clear active layer content directly in Rust (or JS SparseTileGrid in non-native tests)const clearActiveLayer = useCallback(() => {const targetId = activeLayerIdRef.current || activeLayerId;if (!targetId) return;+ if (isNativeCanvasActive() && activeSessionIdRef.current) {+ const docId = activeSessionIdRef.current;+ void clearNativeLayer(docId, targetId, true).then(() => {+ void requestNativeThumbnails(docId, [targetId]);+ });+ return;+ }const grid = activeTileGridRef.current;const dims = dimensionsRef.current;const isBg = isBackgroundLayerId(targetId);@@ -94,6 +111,19 @@ export function useLayerDocumentOps(const dstLayer = currentLayers[dstIdx];if (dstLayer.locked) return null;+ if (isNativeCanvasActive() && activeSessionIdRef.current) {+ const docId = activeSessionIdRef.current;+ const nextLayers = currentLayers.filter((l) => l.id !== srcLayer.id);+ layersRef.current = nextLayers;+ setLayers(nextLayers);+ setActiveLayerId(dstLayer.id);+ setSelectedLayerIds([dstLayer.id]);+ void mergeNativeDown(docId, srcLayer.id).then(() => {+ void requestNativeThumbnails(docId, [dstLayer.id]);+ });+ return { targetId: dstLayer.id, removedId: srcLayer.id };+ }+const grid = activeTileGridRef.current;const dims = dimensionsRef.current;const dstFormat =@@ -194,6 +224,23 @@ export function useLayerDocumentOps(if (!mergePlan) return null;const { folder, descendantLayers, descendantIds, mergedLayer, nextLayers } = mergePlan;++ if (isNativeCanvasActive() && activeSessionIdRef.current) {+ const docId = activeSessionIdRef.current;+ layersRef.current = nextLayers;+ setLayers(nextLayers);+ setActiveLayerId(mergedLayer.id);+ setSelectedLayerIds([mergedLayer.id]);+ void mergeNativeFolder(docId, folder.id, mergedLayer.id).then(() => {+ void requestNativeThumbnails(docId, [mergedLayer.id]);+ });+ return {+ mergedLayerId: mergedLayer.id,+ removedFolderId: folder.id,+ removedDescendantIds: descendantIds,+ };+ }+const grid = activeTileGridRef.current;const dims = dimensionsRef.current;@@ -396,7 +443,11 @@ export function useLayerDocumentOps(? nextActiveLayerId: (nextLayers.find((l) => l.type === 'raster')?.id || nextLayers[0]?.id || '');setActiveLayerId(resolvedActiveId);- session.tileGrid.notifyChange(true);+ if (isNativeCanvasActive()) {+ void switchNativeDocument(documentId);+ } else {+ session.tileGrid.notifyChange(true);+ }},[activeSessionIdRef, activeTileGridRef, dimensionsRef, layersRef, setActiveLayerId, setLayers, thumbDebounceTimersRef]);@@ -426,26 +477,49 @@ export function useLayerDocumentOps(grid = session.tileGrid;}- grid.clearAll();-+ const useNative = isNativeCanvasActive() && Boolean(targetDocumentId);const now = Date.now();- const bgId = `layer-bg-${now}`;- const topId = `layer-1-${now}`;-- // Initialize background directly in SparseTileGrid without creating full-size HTMLCanvasElement- if (backgroundColor !== 'transparent') {- grid.fillLayerSolidColor(bgId, _dims.width, _dims.height, backgroundColor, 'color-32bit');+ const bgId = useNative ? `layer-bg-${targetDocumentId}` : `layer-bg-${now}`;+ const topId = useNative ? `layer-1-${targetDocumentId}` : `layer-1-${now}`;++ let bgThumb = '';+ if (useNative && targetDocumentId) {+ // Phase 2 Native Rust path: allocate SolidColor background directly in Rust (0 JS tile buffers!)+ grid.clearAll();+ void createNativeDocument({+ docId: targetDocumentId,+ name: 'Untitled*',+ dimensions: _dims,+ colorMode: _mode,+ backgroundHex: backgroundColor,+ defaultToneFrequency: defaultToneFrequencyRef.current,+ }).then((snap) => {+ if (!snap || activeSessionIdRef.current !== targetDocumentId) return;+ const bgMeta = snap.layers.find((l) => l.id === bgId);+ if (bgMeta?.thumbnailUrl) {+ setLayers((prev) =>+ prev.map((l) => (l.id === bgId ? { ...l, thumbnailUrl: bgMeta.thumbnailUrl! } : l))+ );+ }+ });} else {- grid.setLayerFormat(bgId, 'color-32bit');- grid.markLayerIngested(bgId);- }+ grid.clearAll();- // Empty top layer: 0 tiles, 0 HTMLCanvasElement allocated- const topFormat = _mode === 'monochrome' ? 'monochrome-1bit' : 'color-32bit';- grid.setLayerFormat(topId, topFormat);- grid.markLayerIngested(topId);+ // Initialize background directly in SparseTileGrid without creating full-size HTMLCanvasElement+ if (backgroundColor !== 'transparent') {+ grid.fillLayerSolidColor(bgId, _dims.width, _dims.height, backgroundColor, 'color-32bit');+ } else {+ grid.setLayerFormat(bgId, 'color-32bit');+ grid.markLayerIngested(bgId);+ }- const bgThumb = createCanvasThumbnail({ grid, layerId: bgId, dimensions: _dims }, false);+ // Empty top layer: 0 tiles, 0 HTMLCanvasElement allocated+ const topFormat = _mode === 'monochrome' ? 'monochrome-1bit' : 'color-32bit';+ grid.setLayerFormat(topId, topFormat);+ grid.markLayerIngested(topId);++ bgThumb = createCanvasThumbnail({ grid, layerId: bgId, dimensions: _dims }, false);+ }const initialLayers: LayerItem[] = [{@@ -541,12 +615,39 @@ export function useLayerDocumentOps(}if (!skipIngest && doc.layerCanvases) {- doc.layerCanvases.forEach((c, id) => {- const layerMeta = doc.layers.find((l) => l.id === id);- const isMono = layerMeta?.expressionColor === 'monochrome';- grid.ingestCanvas(id, c, isMono ? 'monochrome-1bit' : 'color-32bit');- releaseTemporaryCanvas(c);- });+ if (isNativeCanvasActive() && targetDocumentId) {+ doc.layerCanvases.forEach((c, id) => {+ const c2d = c.getContext('2d');+ if (c2d && c.width > 0 && c.height > 0) {+ const imgData = c2d.getImageData(0, 0, c.width, c.height);+ const bytes = new Uint8Array(+ imgData.data.buffer,+ imgData.data.byteOffset,+ imgData.data.byteLength+ );+ void ingestNativeDirtyRect({+ docId: targetDocumentId,+ layerId: id,+ x: 0,+ y: 0,+ width: c.width,+ height: c.height,+ bytes,+ recordHistory: false,+ actionType: 'import',+ label: 'Import Layer',+ });+ }+ releaseTemporaryCanvas(c);+ });+ } else {+ doc.layerCanvases.forEach((c, id) => {+ const layerMeta = doc.layers.find((l) => l.id === id);+ const isMono = layerMeta?.expressionColor === 'monochrome';+ grid.ingestCanvas(id, c, isMono ? 'monochrome-1bit' : 'color-32bit');+ releaseTemporaryCanvas(c);+ });+ }}setLayers(doc.layers);diff --git a/src/hooks/layerManager/useLayerPropertiesAndMasks.ts b/src/hooks/layerManager/useLayerPropertiesAndMasks.tsindex 10ba5d2..4925178 100644--- a/src/hooks/layerManager/useLayerPropertiesAndMasks.ts+++ b/src/hooks/layerManager/useLayerPropertiesAndMasks.ts@@ -11,6 +11,14 @@ import {import { createCanvasThumbnail, get2DContext } from '../../utils/canvasUtils';import { computeBatchColorLabel } from '../../utils/layerOrganization';import { multiplayerService } from '../../services/multiplayerService';+import {+ addNativeLayer,+ addNativeLayerMask,+ isNativeCanvasActive,+ removeNativeLayerMask,+ syncNativeLayers,+ updateNativeLayer,+} from '../../utils/nativeEngineBridge';import {computeBatchLock,computeBatchVisibility,@@ -27,6 +35,7 @@ export function useLayerPropertiesAndMasks(const {dimensions,activeTileGridRef,+ activeSessionIdRef,setLayers,layersRef,activeLayerIdRef,@@ -43,6 +52,20 @@ export function useLayerPropertiesAndMasks(if (next === prev) return;layersRef.current = next;setLayers(next);+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ const changed = next.filter((l, i) => prev[i]?.visible !== l.visible);+ if (changed.length === 1) {+ void updateNativeLayer(nativeDocId, changed[0].id, {+ visible: changed[0].visible,+ recordHistory: true,+ historyLabel: t('Toggle Visibility'),+ });+ } else {+ void syncNativeLayers(nativeDocId, next, activeLayerIdRef.current);+ }+ return;+ }activeTileGridRef.current.notifyChange(true);recordLayerHistory(t('Toggle Visibility'),@@ -51,7 +74,7 @@ export function useLayerPropertiesAndMasks(undefined,'layer');- }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, selectedLayerIdsRef, setLayers]);+ }, [activeLayerIdRef, activeSessionIdRef, activeTileGridRef, layersRef, recordLayerHistory, selectedLayerIdsRef, setLayers]);// Set layer opacity (0.0 to 1.0)const setOpacity = useCallback((id: string, opacity: number) => {@@ -62,6 +85,16 @@ export function useLayerPropertiesAndMasks(const next = prev.map((l) => (l.id === id ? { ...l, opacity: clamped } : l));layersRef.current = next;setLayers(next);+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ void updateNativeLayer(nativeDocId, id, {+ opacity: clamped,+ recordHistory: true,+ historyLabel: t('Layer Opacity'),+ coalesceKey: `opacity:${id}`,+ });+ return;+ }activeTileGridRef.current.notifyChange(true);recordLayerHistory(t('Layer Opacity'),@@ -72,7 +105,7 @@ export function useLayerPropertiesAndMasks(undefined,'layer');- }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);+ }, [activeLayerIdRef, activeSessionIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Set layer blend modeconst setBlendMode = useCallback((id: string, blendMode: BlendMode) => {@@ -82,6 +115,15 @@ export function useLayerPropertiesAndMasks(const next = prev.map((l) => (l.id === id ? { ...l, blendMode } : l));layersRef.current = next;setLayers(next);+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ void updateNativeLayer(nativeDocId, id, {+ blendMode,+ recordHistory: true,+ historyLabel: t('Blend Mode ({mode})', { mode: tc('blendModeId', blendMode) }),+ });+ return;+ }activeTileGridRef.current.notifyChange(true);recordLayerHistory(t('Blend Mode ({mode})', { mode: tc('blendModeId', blendMode) }),@@ -90,7 +132,7 @@ export function useLayerPropertiesAndMasks(undefined,'layer');- }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);+ }, [activeLayerIdRef, activeSessionIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Toggle locked state (batch toggle if part of multi-selection)const toggleLock = useCallback((id: string) => {@@ -99,6 +141,20 @@ export function useLayerPropertiesAndMasks(if (next === prev) return;layersRef.current = next;setLayers(next);+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ const changed = next.filter((l, i) => prev[i]?.locked !== l.locked);+ if (changed.length === 1) {+ void updateNativeLayer(nativeDocId, changed[0].id, {+ locked: changed[0].locked,+ recordHistory: true,+ historyLabel: t('Toggle Layer Lock'),+ });+ } else {+ void syncNativeLayers(nativeDocId, next, activeLayerIdRef.current);+ }+ return;+ }recordLayerHistory(t('Toggle Layer Lock'),id,@@ -106,16 +162,24 @@ export function useLayerPropertiesAndMasks(undefined,'layer');- }, [activeLayerIdRef, layersRef, recordLayerHistory, selectedLayerIdsRef, setLayers]);+ }, [activeLayerIdRef, activeSessionIdRef, layersRef, recordLayerHistory, selectedLayerIdsRef, setLayers]);// Toggle folder collapse stateconst toggleCollapse = useCallback((id: string) => {setLayers((prev) => {const next = prev.map((l) => (l.id === id ? { ...l, collapsed: !l.collapsed } : l));layersRef.current = next;+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ const updated = next.find((l) => l.id === id);+ if (nativeDocId && updated) {+ void updateNativeLayer(nativeDocId, id, {+ collapsed: Boolean(updated.collapsed),+ recordHistory: false,+ });+ }return next;});- }, [layersRef, setLayers]);+ }, [activeSessionIdRef, layersRef, setLayers]);// Toggle clipping mask state (Clip to Layer Below)const toggleClipping = useCallback((id: string) => {@@ -127,6 +191,15 @@ export function useLayerPropertiesAndMasks(const next = prev.map((l) => (l.id === id ? { ...l, clipped: !l.clipped } : l));layersRef.current = next;setLayers(next);+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ void updateNativeLayer(nativeDocId, id, {+ clipped: !prev[idx].clipped,+ recordHistory: true,+ historyLabel: t('Toggle Clipping Mask'),+ });+ return;+ }activeTileGridRef.current.notifyChange(true);recordLayerHistory(t('Toggle Clipping Mask'),@@ -135,7 +208,7 @@ export function useLayerPropertiesAndMasks(undefined,'layer');- }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);+ }, [activeLayerIdRef, activeSessionIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Toggle alpha locked state (Lock Transparent Pixels)const toggleAlphaLock = useCallback((id: string) => {@@ -145,6 +218,15 @@ export function useLayerPropertiesAndMasks(const next = prev.map((l) => (l.id === id ? { ...l, alphaLocked: !l.alphaLocked } : l));layersRef.current = next;setLayers(next);+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ void updateNativeLayer(nativeDocId, id, {+ alphaLocked: !target.alphaLocked,+ recordHistory: true,+ historyLabel: t('Toggle Alpha Lock'),+ });+ return;+ }recordLayerHistory(t('Toggle Alpha Lock'),id,@@ -152,7 +234,7 @@ export function useLayerPropertiesAndMasks(undefined,'layer');- }, [activeLayerIdRef, layersRef, recordLayerHistory, setLayers]);+ }, [activeLayerIdRef, activeSessionIdRef, layersRef, recordLayerHistory, setLayers]);// Assign organizational color label tag (batch applies if part of multi-selection)const setLayerColorLabel = useCallback((id: string, colorLabel: LayerColorLabel) => {@@ -161,6 +243,11 @@ export function useLayerPropertiesAndMasks(if (next === prev) return;layersRef.current = next;setLayers(next);+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ void syncNativeLayers(nativeDocId, next, activeLayerIdRef.current);+ return;+ }recordLayerHistory(t('Set Layer Color Label'),id,@@ -168,7 +255,7 @@ export function useLayerPropertiesAndMasks(undefined,'layer');- }, [activeLayerIdRef, layersRef, recordLayerHistory, selectedLayerIdsRef, setLayers]);+ }, [activeLayerIdRef, activeSessionIdRef, layersRef, recordLayerHistory, selectedLayerIdsRef, setLayers]);// Add a non-destructive grayscale Layer Maskconst addLayerMask = useCallback((layerId: string) => {@@ -176,6 +263,25 @@ export function useLayerPropertiesAndMasks(const target = prev.find((l) => l.id === layerId);if (!target || target.maskCanvas) return;+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ // Phase 2 Native Rust path: 0 tiles allocated for default reveal-all 8-bit mask in Rust!+ const next = prev.map((l) =>+ l.id === layerId+ ? {+ ...l,+ maskEnabled: true,+ maskLinked: true,+ maskVersion: 1,+ }+ : l+ );+ layersRef.current = next;+ setLayers(next);+ void addNativeLayerMask(nativeDocId, layerId, 255, true);+ return;+ }+const mask = document.createElement('canvas');mask.width = dimensions.width;mask.height = dimensions.height;@@ -209,19 +315,39 @@ export function useLayerPropertiesAndMasks(undefined,'layer');- }, [activeLayerIdRef, activeTileGridRef, dimensions, layersRef, recordLayerHistory, setLayers]);+ }, [activeLayerIdRef, activeSessionIdRef, activeTileGridRef, dimensions, layersRef, recordLayerHistory, setLayers]);- // Remove or apply layer mask (directly onto SparseTileGrid tiles, zero full-doc layer canvas)+ // Remove or apply layer mask (directly in Rust, or JS SparseTileGrid in non-native tests)const removeLayerMask = useCallback((layerId: string, apply: boolean = false) => {const prev = layersRef.current;const target = prev.find((l) => l.id === layerId);- if (!target || !target.maskCanvas) return;+ if (!target || (!target.maskCanvas && !isNativeCanvasActive())) return;++ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ const next = prev.map((l) =>+ l.id === layerId+ ? {+ ...l,+ maskCanvas: undefined,+ maskEnabled: undefined,+ maskLinked: undefined,+ maskThumbnailUrl: undefined,+ maskVersion: undefined,+ }+ : l+ );+ layersRef.current = next;+ setLayers(next);+ void removeNativeLayerMask(nativeDocId, layerId, apply, true);+ return;+ }const grid = activeTileGridRef.current;let tileDeltas: TileDelta[] = [];- if (apply) {+ if (apply && target.maskCanvas) {const beforeSnap = grid.snapshotLayerTiles(layerId);grid.applyMaskCanvasToLayer(layerId, target.maskCanvas, dimensions);tileDeltas = grid.computeDeltasFromSnapshot(beforeSnap, layerId);@@ -261,17 +387,26 @@ export function useLayerPropertiesAndMasks('layer');},- [activeLayerIdRef, activeTileGridRef, dimensions, layersRef, recordLayerHistory, setLayers, updateLayerThumbnail]+ [activeLayerIdRef, activeSessionIdRef, activeTileGridRef, dimensions, layersRef, recordLayerHistory, setLayers, updateLayerThumbnail]);// Toggle layer mask enabled stateconst toggleLayerMask = useCallback((layerId: string) => {const prev = layersRef.current;const target = prev.find((l) => l.id === layerId);- if (!target || !target.maskCanvas) return;+ if (!target || (!target.maskCanvas && !isNativeCanvasActive())) return;const next = prev.map((l) => (l.id === layerId ? { ...l, maskEnabled: !l.maskEnabled } : l));layersRef.current = next;setLayers(next);+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ void updateNativeLayer(nativeDocId, layerId, {+ maskEnabled: !target.maskEnabled,+ recordHistory: true,+ historyLabel: t('Toggle Layer Mask'),+ });+ return;+ }activeTileGridRef.current.notifyChange(true);recordLayerHistory(t('Toggle Layer Mask'),@@ -280,16 +415,25 @@ export function useLayerPropertiesAndMasks(undefined,'layer');- }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);+ }, [activeLayerIdRef, activeSessionIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Toggle mask linked stateconst toggleMaskLinked = useCallback((layerId: string) => {const prev = layersRef.current;const target = prev.find((l) => l.id === layerId);- if (!target || !target.maskCanvas) return;+ if (!target || (!target.maskCanvas && !isNativeCanvasActive())) return;const next = prev.map((l) => (l.id === layerId ? { ...l, maskLinked: !l.maskLinked } : l));layersRef.current = next;setLayers(next);+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ void updateNativeLayer(nativeDocId, layerId, {+ maskLinked: !target.maskLinked,+ recordHistory: true,+ historyLabel: t('Toggle Mask Link'),+ });+ return;+ }recordLayerHistory(t('Toggle Mask Link'),layerId,@@ -297,7 +441,7 @@ export function useLayerPropertiesAndMasks(undefined,'layer');- }, [activeLayerIdRef, layersRef, recordLayerHistory, setLayers]);+ }, [activeLayerIdRef, activeSessionIdRef, layersRef, recordLayerHistory, setLayers]);// Update mask thumbnailconst updateMaskThumbnail = useCallback(@@ -432,6 +576,11 @@ export function useLayerPropertiesAndMasks(layersRef.current = next;setLayers(next);setActiveLayerId(id);+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ void addNativeLayer(nativeDocId, newLayer, insertIndex, true);+ return newLayer;+ }activeTileGridRef.current.notifyChange(true);recordLayerHistory(t('Add {name}', { name }),@@ -442,7 +591,7 @@ export function useLayerPropertiesAndMasks();return newLayer;},- [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setActiveLayerId, setLayers]+ [activeLayerIdRef, activeSessionIdRef, activeTileGridRef, layersRef, recordLayerHistory, setActiveLayerId, setLayers]);// Update adjustment layer data@@ -452,6 +601,16 @@ export function useLayerPropertiesAndMasks(const next = prev.map((l) => (l.id === layerId ? { ...l, adjustmentData: data } : l));layersRef.current = next;setLayers(next);+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ void updateNativeLayer(nativeDocId, layerId, {+ adjustmentData: data,+ recordHistory: true,+ historyLabel: t('Update Adjustment'),+ coalesceKey: `adjustment:${layerId}`,+ });+ return;+ }activeTileGridRef.current.notifyChange(true);recordLayerHistory(t('Update Adjustment'),@@ -460,7 +619,7 @@ export function useLayerPropertiesAndMasks(undefined,'layer');- }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);+ }, [activeLayerIdRef, activeSessionIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Update Layer Styles (Stroke, Drop Shadow, Outer Glow)const updateLayerStyles = useCallback((id: string, styles: LayerStyles) => {@@ -470,6 +629,16 @@ export function useLayerPropertiesAndMasks(const next = prev.map((l) => (l.id === id ? { ...l, styles } : l));layersRef.current = next;setLayers(next);+ const nativeDocId = isNativeCanvasActive() ? activeSessionIdRef.current : null;+ if (nativeDocId) {+ void updateNativeLayer(nativeDocId, id, {+ styles,+ recordHistory: true,+ historyLabel: t('Layer Styles'),+ coalesceKey: `styles:${id}`,+ });+ return;+ }activeTileGridRef.current.notifyChange(true);recordLayerHistory(t('Layer Styles'),@@ -478,7 +647,7 @@ export function useLayerPropertiesAndMasks(undefined,'layer');- }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);+ }, [activeLayerIdRef, activeSessionIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);return {toggleVisibility,diff --git a/src/hooks/useLayerManager.ts b/src/hooks/useLayerManager.tsindex 07be8f6..7bad38f 100644--- a/src/hooks/useLayerManager.ts+++ b/src/hooks/useLayerManager.ts@@ -4,6 +4,11 @@ import { SparseTileGrid, globalTileGrid } from '../utils/tileEngine';import { documentStore } from '../utils/documentStore';import { recoveryService } from '../services/recoveryService';import { documentStoreActions } from '../stores';+import {+ isNativeCanvasActive,+ subscribeNativeThumbnails,+ syncNativeLayers,+} from '../utils/nativeEngineBridge';import {SoloLayerState,computeRestoreSolo,@@ -86,6 +91,38 @@ export function useLayerManager({const layersRef = useRef(layers);layersRef.current = layers;+ // Phase 2: Subscribe to async 64x64 layer & mask PNG thumbnails rendered on Rust Rayon workers+ useEffect(() => {+ return subscribeNativeThumbnails((ev) => {+ if (!isNativeCanvasActive()) return;+ if (activeSessionIdRef.current && ev.docId !== activeSessionIdRef.current) return;+ if (!ev.updates || ev.updates.length === 0) return;+ const updateMap = new Map(ev.updates.map((u) => [u.layerId, u]));+ setLayers((prev) => {+ let changed = false;+ const next = prev.map((l) => {+ const u = updateMap.get(l.id);+ if (!u) return l;+ const nextThumb = u.thumbnailUrl !== undefined ? u.thumbnailUrl : l.thumbnailUrl;+ const nextMaskThumb =+ u.maskThumbnailUrl !== undefined ? u.maskThumbnailUrl : l.maskThumbnailUrl;+ if (nextThumb === l.thumbnailUrl && nextMaskThumb === l.maskThumbnailUrl) return l;+ changed = true;+ return {+ ...l,+ thumbnailUrl: nextThumb,+ maskThumbnailUrl: nextMaskThumb,+ };+ });+ if (changed) {+ layersRef.current = next;+ return next;+ }+ return prev;+ });+ });+ }, []);+// Track structural layer mutations and log to recovery service WAL (ignore pure thumbnailUrl refreshes)const isInitialLayerMount = useRef(true);const lastLoggedLayersSigRef = useRef<string>('');@@ -260,7 +297,15 @@ export function useLayerManager({setSoloLayerId(result.nextSolo?.layerId ?? null);layersRef.current = result.nextLayers;setLayers(result.nextLayers);- activeTileGridRef.current.notifyChange(true);+ if (isNativeCanvasActive() && activeSessionIdRef.current) {+ void syncNativeLayers(+ activeSessionIdRef.current,+ result.nextLayers,+ activeLayerIdRef.current+ );+ } else {+ activeTileGridRef.current.notifyChange(true);+ }recordLayerHistory(result.nextSolo ? 'Solo Layer' : 'Exit Solo Layer',id,@@ -288,7 +333,15 @@ export function useLayerManager({if (result.nextLayers !== prevLayers) {layersRef.current = result.nextLayers;setLayers(result.nextLayers);- activeTileGridRef.current.notifyChange(true);+ if (isNativeCanvasActive() && activeSessionIdRef.current) {+ void syncNativeLayers(+ activeSessionIdRef.current,+ result.nextLayers,+ activeLayerIdRef.current+ );+ } else {+ activeTileGridRef.current.notifyChange(true);+ }recordLayerHistory('Exit Solo Layer',currentSolo.layerId,diff --git a/src/hooks/useNativeEngineViewport.ts b/src/hooks/useNativeEngineViewport.tsnew file mode 100644index 0000000..6b22665--- /dev/null+++ b/src/hooks/useNativeEngineViewport.ts@@ -0,0 +1,594 @@+import React, { useCallback, useEffect, useRef, useState } from 'react';+import { BrushSettings, CanvasDimensions, ToolType } from '../types/editor';+import { CanvasNavigationHandle } from './useCanvasNavigation';+import { selectIsAnyModalOpen, useUiStore, useWorkspaceStore } from '../stores';+import { DEFAULT_INTERFACE_SCALE } from '../utils/interfaceScale';+import {+ classifyNativeTool,+ clearNativeCanvas,+ getNativeDiagnostics,+ initNativeEngineBridge,+ isNativeCanvasActive,+ isNativeStrokeTool,+ NativeEngineDiagnostics,+ NativeUiRect,+ NativeWheelNavMode,+ parseCssColorToRgba,+ setNativeAppearance,+ setNativeBrush,+ setNativeCamera,+ setNativeCursor,+ setNativeDocument,+ setNativeOccludedRects,+ setNativePolicy,+ setNativeViewport,+ subscribeNativeCamera,+ subscribeNativeCanvasActive,+ subscribeNativeDiagnostics,+ subscribeNativePointerStat,+} from '../utils/nativeEngineBridge';++export interface UseNativeEngineViewportParams {+ viewportRef: React.RefObject<HTMLDivElement | null>;+ navigation?: CanvasNavigationHandle;+ dimensions: CanvasDimensions;+ showCheckerboard: boolean;+ hasOpenDocument: boolean;+ tool: ToolType;+ brushSettings: BrushSettings;+ primaryColor: string;+ isSquare: boolean;+ thicknessRatio: number;+ thicknessVertical: boolean;+ tipAngleDeg: number;+ isResizingBrush: boolean;+ isSpaceDown: boolean;+ isPanning: boolean;+ isRotating: boolean;+ isZoomDragging: boolean;+ isRotateModifier: boolean;+ pan: { x: number; y: number };+ zoom: number;+ rotation: number;+ flipX: boolean;+ flipY: boolean;+}++const OCCLUDER_SELECTOR = [+ '[data-native-occluder="true"]',+ '[role="dialog"]',+ '[aria-modal="true"]',+ '[role="menu"]',+ '[data-chrome-floating="true"]',+ '[data-testid="floating-brush-pill"]',+ '[data-testid="quick-brush-panel"]',+ '[data-testid="collab-room-overlay"]',+ '[data-testid="collab-follow-banner"]',+ '[data-testid^="focus-hud"]',+ '[data-testid*="popover"]',+ '[data-testid*="modal"]',+].join(',');++function isEditableElement(el: Element | null): boolean {+ if (!el) return false;+ const tag = el.tagName;+ if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true;+ return Boolean((el as HTMLElement).isContentEditable);+}++export function useNativeEngineViewport({+ viewportRef,+ navigation,+ dimensions,+ showCheckerboard,+ hasOpenDocument,+ tool,+ brushSettings,+ primaryColor,+ isSquare,+ thicknessRatio,+ thicknessVertical,+ tipAngleDeg,+ isResizingBrush,+ isSpaceDown,+ isPanning,+ isRotating,+ isZoomDragging,+ isRotateModifier,+ pan,+ zoom,+ rotation,+ flipX,+ flipY,+}: UseNativeEngineViewportParams) {+ const [nativeActive, setNativeActive] = useState<boolean>(() => isNativeCanvasActive());+ const [diagnostics, setDiagnostics] = useState<NativeEngineDiagnostics | null>(null);+ const [textInputFocused, setTextInputFocused] = useState<boolean>(false);+ const [workspaceInteracting, setWorkspaceInteracting] = useState<boolean>(false);++ const interfaceScale = useUiStore(+ (s) => s.appSettings.interfaceScale ?? DEFAULT_INTERFACE_SCALE+ );+ const themePreset = useUiStore((s) => s.appSettings.themePreset);+ const appearance = useUiStore((s) => s.appSettings.appearance);+ const wheelModeRaw = useUiStore((s) => s.appSettings.modifierKeys?.mouseWheel ?? 'zoom');+ const isWebtoonMode = useUiStore((s) => s.isWebtoonMode);+ const isModalOpen = useUiStore(+ (s) => selectIsAnyModalOpen(s) || s.isAppearanceStudioOpen || s.is3DLayerOpen+ );+ const openPopover = useWorkspaceStore((s) => s.openPopover);+ const floatingPanelsCount = useWorkspaceStore((s) => s.layout.floatingPanels?.length ?? 0);+ const palettesHidden = useWorkspaceStore((s) => s.palettesHidden);++ const applyingNativeCameraRef = useRef(false);+ const lastViewportSigRef = useRef<string>('');+ const lastOccludedSigRef = useRef<string>('');++ // Detect native Windows DX12 DirectComposition engine once on desktop+ useEffect(() => {+ let mounted = true;+ const unsub = subscribeNativeCanvasActive((active) => {+ if (mounted) setNativeActive(active);+ });+ void initNativeEngineBridge().then((active) => {+ if (mounted) {+ setNativeActive(active);+ if (active) {+ void getNativeDiagnostics().then((diag) => {+ if (mounted && diag) setDiagnostics(diag);+ });+ }+ }+ });+ return () => {+ mounted = false;+ unsub();+ };+ }, []);++ // Toggle transparent WebView2 cutout attribute on :root while document is open+ useEffect(() => {+ if (typeof document === 'undefined' || !document.documentElement) return;+ const root = document.documentElement;+ if (nativeActive && hasOpenDocument) {+ if (typeof root.setAttribute === 'function') {+ root.setAttribute('data-native-canvas', 'true');+ } else if (root.dataset) {+ root.dataset.nativeCanvas = 'true';+ }+ } else if (typeof root.removeAttribute === 'function') {+ root.removeAttribute('data-native-canvas');+ } else if (root.dataset) {+ delete root.dataset.nativeCanvas;+ }+ return () => {+ if (typeof document !== 'undefined' && document.documentElement) {+ const el = document.documentElement;+ if (typeof el.removeAttribute === 'function') {+ el.removeAttribute('data-native-canvas');+ } else if (el.dataset) {+ delete el.dataset.nativeCanvas;+ }+ }+ };+ }, [nativeActive, hasOpenDocument]);++ // Hide DirectComposition visual whenever CanvasArea unmounts or document closes+ useEffect(() => {+ if (!nativeActive) return;+ if (!hasOpenDocument) {+ lastViewportSigRef.current = '';+ void setNativeViewport({+ xPx: 0,+ yPx: 0,+ widthPx: 0,+ heightPx: 0,+ dpr: typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1,+ visible: false,+ });+ }+ return () => {+ lastViewportSigRef.current = '';+ void setNativeViewport({+ xPx: 0,+ yPx: 0,+ widthPx: 0,+ heightPx: 0,+ dpr: typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1,+ visible: false,+ });+ };+ }, [nativeActive, hasOpenDocument]);++ // Track text-input focus and workspace splitter/drag guard on document+ useEffect(() => {+ if (!nativeActive || typeof document === 'undefined') return;+ const syncFocus = () => setTextInputFocused(isEditableElement(document.activeElement));+ syncFocus();+ document.addEventListener('focusin', syncFocus, true);+ document.addEventListener('focusout', syncFocus, true);++ const root = document.documentElement;+ const syncWorkspace = () => {+ setWorkspaceInteracting(root.getAttribute('data-workspace-interacting') === 'true');+ };+ syncWorkspace();+ const attrObserver = new MutationObserver(syncWorkspace);+ attrObserver.observe(root, {+ attributes: true,+ attributeFilter: ['data-workspace-interacting'],+ });++ return () => {+ document.removeEventListener('focusin', syncFocus, true);+ document.removeEventListener('focusout', syncFocus, true);+ attrObserver.disconnect();+ };+ }, [nativeActive]);++ // Observe canvas viewport physical bounds (ResizeObserver + DPR + interfaceScale + layout)+ // AND occluded UI rects (modals, popovers, context menus, FloatingBrushPill, floating docks)+ useEffect(() => {+ if (!nativeActive || !hasOpenDocument) return;+ const viewport = viewportRef.current;+ if (!viewport || typeof window === 'undefined') return;++ let rafId: number | null = null;+ let dprMql: MediaQueryList | null = null;+ let scaleTimer: ReturnType<typeof setTimeout> | null = null;++ const pushViewportAndOccluders = () => {+ rafId = null;+ const vp = viewportRef.current;+ if (!vp) return;++ const dpr = window.devicePixelRatio || 1;+ const rect = vp.getBoundingClientRect();+ const leftPx = Math.round(rect.left * dpr);+ const topPx = Math.round(rect.top * dpr);+ const rightPx = Math.round(rect.right * dpr);+ const bottomPx = Math.round(rect.bottom * dpr);+ const widthPx = Math.max(0, rightPx - leftPx);+ const heightPx = Math.max(0, bottomPx - topPx);+ const visible = widthPx > 0 && heightPx > 0;++ const vpSig = `${leftPx},${topPx},${widthPx},${heightPx},${dpr.toFixed(4)},${visible ? 1 : 0}`;+ if (vpSig !== lastViewportSigRef.current) {+ lastViewportSigRef.current = vpSig;+ void setNativeViewport({+ xPx: leftPx,+ yPx: topPx,+ widthPx,+ heightPx,+ dpr,+ visible,+ });+ }++ // Compute physical-pixel UI occlusion rects overlapping the canvas viewport+ const occluded: NativeUiRect[] = [];+ let occSig = '';+ if (visible) {+ const nodes = document.querySelectorAll(OCCLUDER_SELECTOR);+ for (let i = 0; i < nodes.length; i++) {+ const el = nodes[i] as HTMLElement;+ if (!el || el === vp) continue;+ const style = window.getComputedStyle(el);+ if (+ style.display === 'none' ||+ style.visibility === 'hidden' ||+ style.pointerEvents === 'none' ||+ parseFloat(style.opacity || '1') <= 0.01+ ) {+ continue;+ }+ const r = el.getBoundingClientRect();+ if (r.width <= 0 || r.height <= 0) continue;+ // Only include elements that overlap the viewport bounds+ if (+ r.right <= rect.left ||+ r.left >= rect.right ||+ r.bottom <= rect.top ||+ r.top >= rect.bottom+ ) {+ continue;+ }+ const x = Math.round(r.left * dpr);+ const y = Math.round(r.top * dpr);+ const w = Math.max(0, Math.round(r.right * dpr) - x);+ const h = Math.max(0, Math.round(r.bottom * dpr) - y);+ if (w > 0 && h > 0) {+ occluded.push({ x, y, width: w, height: h });+ occSig += `${x},${y},${w},${h};`;+ }+ }+ }++ if (occSig !== lastOccludedSigRef.current) {+ lastOccludedSigRef.current = occSig;+ void setNativeOccludedRects(occluded);+ }+ };++ const scheduleSync = () => {+ if (rafId !== null) return;+ rafId = requestAnimationFrame(pushViewportAndOccluders);+ };++ const handleDprChange = () => {+ scheduleSync();+ attachDprListener();+ };++ const attachDprListener = () => {+ if (dprMql) {+ dprMql.removeEventListener?.('change', handleDprChange);+ dprMql = null;+ }+ if (typeof window.matchMedia === 'function') {+ const cur = window.devicePixelRatio || 1;+ dprMql = window.matchMedia(`(resolution: ${cur}dppx)`);+ dprMql.addEventListener?.('change', handleDprChange);+ }+ };++ pushViewportAndOccluders();+ attachDprListener();+ // Re-sync after async Tauri setZoom() settles when interfaceScale changes+ scaleTimer = setTimeout(scheduleSync, 80);++ const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(scheduleSync) : null;+ ro?.observe(viewport);+ if (document.body) {+ ro?.observe(document.body);+ }++ const mo = new MutationObserver(scheduleSync);+ mo.observe(document.body, {+ childList: true,+ subtree: true,+ attributes: true,+ attributeFilter: ['style', 'class', 'data-native-occluder', 'data-chrome-floating'],+ });++ window.addEventListener('resize', scheduleSync);++ return () => {+ if (rafId !== null) cancelAnimationFrame(rafId);+ if (scaleTimer !== null) clearTimeout(scaleTimer);+ dprMql?.removeEventListener?.('change', handleDprChange);+ ro?.disconnect();+ mo.disconnect();+ window.removeEventListener('resize', scheduleSync);+ };+ }, [+ nativeActive,+ hasOpenDocument,+ viewportRef,+ interfaceScale,+ palettesHidden,+ floatingPanelsCount,+ openPopover,+ isModalOpen,+ ]);++ // Sync document size+ useEffect(() => {+ if (!nativeActive || !hasOpenDocument) return;+ void setNativeDocument(dimensions.width, dimensions.height, showCheckerboard);+ }, [nativeActive, hasOpenDocument, dimensions.width, dimensions.height, showCheckerboard]);++ // Sync canvas matte color & checkerboard setting from CSS theme tokens+ useEffect(() => {+ if (!nativeActive || !hasOpenDocument || typeof window === 'undefined') return;+ const syncAppearance = () => {+ const matteCss = getComputedStyle(document.documentElement).getPropertyValue(+ '--ui-canvas-matte'+ );+ const rgba = parseCssColorToRgba(matteCss, [0.086, 0.086, 0.086, 1.0]);+ void setNativeAppearance(rgba, showCheckerboard);+ };+ const raf = requestAnimationFrame(syncAppearance);+ return () => cancelAnimationFrame(raf);+ }, [nativeActive, hasOpenDocument, themePreset, appearance, showCheckerboard]);++ // Sync Phase 1 PoC GPU brush params+ useEffect(() => {+ if (!nativeActive || !hasOpenDocument) return;+ const isEraser = tool === 'eraser';+ const color = parseCssColorToRgba(primaryColor, [0.08, 0.08, 0.1, 1.0]);+ const usePressureSize = Boolean(+ brushSettings.sizeSensor?.usePressure ?? brushSettings.usePressure ?? true+ );+ const usePressureOpacity = Boolean(brushSettings.opacitySensor?.usePressure);+ const spacing = Math.max(0.03, Math.min(1.0, brushSettings.spacing || 0.1));+ const minSizeRatio = Math.max(0.0, Math.min(1.0, brushSettings.minSizeFactor ?? 0.15));++ void setNativeBrush({+ size: Math.max(0.5, brushSettings.size || 12),+ opacity: Math.max(0.01, Math.min(1.0, brushSettings.opacity ?? 1.0)),+ hardness: Math.max(0.0, Math.min(1.0, brushSettings.hardness ?? 0.9)),+ spacing,+ minSizeRatio,+ usePressureSize,+ usePressureOpacity,+ color,+ isEraser,+ });+ }, [+ nativeActive,+ hasOpenDocument,+ tool,+ primaryColor,+ brushSettings.size,+ brushSettings.opacity,+ brushSettings.hardness,+ brushSettings.spacing,+ brushSettings.minSizeFactor,+ brushSettings.usePressure,+ brushSettings.sizeSensor?.usePressure,+ brushSettings.opacitySensor?.usePressure,+ ]);++ // Sync GPU brush cursor config+ useEffect(() => {+ if (!nativeActive || !hasOpenDocument) return;+ const hideCursor =+ isModalOpen ||+ isSpaceDown ||+ isPanning ||+ isRotating ||+ isZoomDragging ||+ isRotateModifier ||+ isResizingBrush ||+ !isNativeStrokeTool(tool);++ void setNativeCursor({+ size: Math.max(0.5, brushSettings.size || 12),+ thicknessRatio: Math.max(0.05, Math.min(1.0, thicknessRatio || 1.0)),+ thicknessVertical,+ tipAngleDeg,+ isSquare,+ visible: !hideCursor,+ });+ }, [+ nativeActive,+ hasOpenDocument,+ tool,+ brushSettings.size,+ thicknessRatio,+ thicknessVertical,+ tipAngleDeg,+ isSquare,+ isModalOpen,+ isSpaceDown,+ isPanning,+ isRotating,+ isZoomDragging,+ isRotateModifier,+ isResizingBrush,+ ]);++ // Sync interaction policy (tool classification, wheel mode, focus & modal guards)+ useEffect(() => {+ if (!nativeActive || !hasOpenDocument) return;+ const wheelMode: NativeWheelNavMode =+ wheelModeRaw === 'scroll'+ ? 'scroll'+ : wheelModeRaw === 'brush-size'+ ? 'brush-size'+ : 'zoom';++ void setNativePolicy({+ activeTool: classifyNativeTool(tool),+ nativeStrokeEnabled: true,+ wheelMode,+ isWebtoonMode,+ textInputFocused,+ workspaceInteracting,+ modalOpen: isModalOpen || Boolean(openPopover),+ });+ }, [+ nativeActive,+ hasOpenDocument,+ tool,+ wheelModeRaw,+ isWebtoonMode,+ textInputFocused,+ workspaceInteracting,+ isModalOpen,+ openPopover,+ ]);++ // Bidirectional camera sync between Rust 120–240Hz navigator and React useCanvasNavigation+ useEffect(() => {+ if (!nativeActive || !hasOpenDocument) return;++ // Push initial camera snapshot into Rust+ const initial = navigation+ ? navigation.getCameraState()+ : { pan, zoom, rotation, flipX, flipY };+ void setNativeCamera({+ panX: initial.pan.x,+ panY: initial.pan.y,+ zoom: initial.zoom,+ rotation: initial.rotation,+ flipX: initial.flipX,+ flipY: initial.flipY,+ });++ const unsubReactCam = navigation+ ? navigation.subscribeCamera((cam) => {+ if (applyingNativeCameraRef.current) return;+ void setNativeCamera({+ panX: cam.pan.x,+ panY: cam.pan.y,+ zoom: cam.zoom,+ rotation: cam.rotation,+ flipX: cam.flipX,+ flipY: cam.flipY,+ });+ })+ : () => {};++ const unsubNativeCam = subscribeNativeCamera((ev) => {+ if (!navigation?.setCameraLive) return;+ applyingNativeCameraRef.current = true;+ try {+ navigation.setCameraLive(+ {+ pan: { x: ev.panX, y: ev.panY },+ zoom: ev.zoom,+ rotation: ev.rotation,+ flipX: ev.flipX,+ flipY: ev.flipY,+ },+ ev.commit,+ 'programmatic'+ );+ } finally {+ applyingNativeCameraRef.current = false;+ }+ });++ return () => {+ unsubReactCam();+ unsubNativeCam();+ };+ }, [nativeActive, hasOpenDocument, navigation]);++ // Subscribe to throttled GPU diagnostics (~4Hz) and pointer stats (~30Hz) from Rust+ useEffect(() => {+ if (!nativeActive || !hasOpenDocument) return;+ const unsubDiag = subscribeNativeDiagnostics((diag) => {+ setDiagnostics(diag);+ });+ const unsubStat = subscribeNativePointerStat((stat) => {+ if (typeof window !== 'undefined') {+ window.dispatchEvent(+ new CustomEvent('canvas-pointer-stat', {+ detail: {+ x: stat.docX,+ y: stat.docY,+ pressure: stat.pressure,+ },+ })+ );+ }+ });+ return () => {+ unsubDiag();+ unsubStat();+ };+ }, [nativeActive, hasOpenDocument]);++ const handleClearNativeCanvas = useCallback(() => {+ void clearNativeCanvas();+ }, []);++ return {+ nativeActive: nativeActive && hasOpenDocument,+ diagnostics,+ onClearNativeCanvas: handleClearNativeCanvas,+ };+}diff --git a/src/index.css b/src/index.cssindex e509864..87d5587 100644--- a/src/index.css+++ b/src/index.css@@ -668,3 +668,58 @@ input[type="checkbox"] {:root[data-chrome-style="islands"] [data-testid="dock-workspace"][data-palettes-hidden="true"] [data-chrome-canvas-stage="true"] {border-radius: 0;}++/* ========================================================================== */+/* Hybrid Native DX12 + Transparent WebView2 Viewport Cutout */+/* ========================================================================== */+/* When the native Windows DirectComposition DX12 canvas is active beneath */+/* WebView2, punch a clean RGBA(0,0,0,0) cutout strictly through the canvas */+/* ancestor chain while keeping every UI panel, dock, seam, and rounded */+/* island corner completely opaque so desktop wallpaper never leaks through. */+:root[data-native-canvas="true"],+:root[data-native-canvas="true"] body,+:root[data-native-canvas="true"] #root,+:root[data-native-canvas="true"] .app-root-container,+:root[data-native-canvas="true"] [data-chrome-workspace-frame="true"],+:root[data-native-canvas="true"] [data-testid="dock-workspace"],+:root[data-native-canvas="true"] [data-testid="canvas-center-column"],+:root[data-native-canvas="true"] [data-testid="canvas-stage-region"],+:root[data-native-canvas="true"] [data-chrome-canvas-stage="true"],+:root[data-native-canvas="true"] main.canvas-viewport {+ background-color: transparent !important;+}++/* Keep left/right dock zones and surrounding seams opaque outside the cutout */+:root[data-native-canvas="true"] [data-testid="left-dock-zone"],+:root[data-native-canvas="true"] [data-testid="right-dock-zone"] {+ background-color: var(--ui-bg-void);+}++:root[data-native-canvas="true"] [data-chrome-bar="header"] {+ box-shadow: 0 2px 0 0 var(--ui-bg-void);+}++:root[data-native-canvas="true"] [data-testid="dock-workspace"] {+ box-shadow: 0 0 0 16px var(--ui-bg-void);+}++:root[data-native-canvas="true"] [data-testid="canvas-center-column"] {+ box-shadow: 0 0 0 16px var(--ui-bg-void);+}++:root[data-native-canvas="true"] [data-chrome-canvas-stage="true"] {+ box-shadow: 0 0 0 16px var(--ui-bg-void);+}++/* Islands chrome: seal 6px inter-island gaps and rounded stage corners with matte */+:root[data-native-canvas="true"][data-chrome-style="islands"] [data-testid="left-dock-zone"],+:root[data-native-canvas="true"][data-chrome-style="islands"] [data-testid="right-dock-zone"] {+ background-color: var(--ui-canvas-matte);+ box-shadow: 0 0 0 16px var(--ui-canvas-matte);+}++:root[data-native-canvas="true"][data-chrome-style="islands"] [data-testid="dock-workspace"],+:root[data-native-canvas="true"][data-chrome-style="islands"] [data-testid="canvas-center-column"],+:root[data-native-canvas="true"][data-chrome-style="islands"] [data-chrome-canvas-stage="true"] {+ box-shadow: 0 0 0 20px var(--ui-canvas-matte);+}diff --git a/src/services/recoveryService.ts b/src/services/recoveryService.tsindex 7d0d928..c88f896 100644--- a/src/services/recoveryService.ts+++ b/src/services/recoveryService.ts@@ -24,6 +24,7 @@ import {import { deflateAsync } from '../utils/asyncCompression';import { documentStore } from '../utils/documentStore';import { artworkTimeTracker } from '../utils/artworkTimeTracker';+import { isNativeCanvasActive, nativeRecoveryCheckpoint } from '../utils/nativeEngineBridge';export const WAL_MAGIC_BYTES = new Uint8Array([0x49, 0x4e, 0x4b, 0x57]); // 'INKW'export const WAL_ENTRY_STROKE_TILE_DELTA = 1;@@ -656,6 +657,21 @@ class RecoveryService {let abortedByActivity = false;try {+ // Phase 2 Native Rust path: serialize INKG v1 snapshot + PNG thumbnail entirely in Rust (zero JS pixel IPC)+ if (isNativeCanvasActive()) {+ const rawManifest = this.manifestProvider?.() || null;+ const safeManifest = rawManifest+ ? {+ ...rawManifest,+ layers: this.stripLayerTransientFields(rawManifest.layers),+ }+ : null;+ const manifestJson = safeManifest ? JSON.stringify(safeManifest) : undefined;+ await nativeRecoveryCheckpoint(activeId, activeId, manifestJson);+ this.dirtySinceCheckpoint = false;+ return;+ }+// Wait for any in-flight WAL appends before capturing baseline + truncating WALawait this.walQueue;if (shouldAbort()) {diff --git a/src/types/editor.ts b/src/types/editor.tsindex 08f3876..6ece426 100644--- a/src/types/editor.ts+++ b/src/types/editor.ts@@ -1516,7 +1516,7 @@ export interface InkTimelapseFrameMetadata {timestamp: number;width: number;height: number;- mimeType: 'image/webp' | 'image/jpeg';+ mimeType: 'image/webp' | 'image/jpeg' | 'image/png';bytes: number;captureArea?: TimelapseCaptureArea;}@@ -1526,7 +1526,7 @@ export interface InkTimelapseFrameData {timestamp: number;width: number;height: number;- mimeType: 'image/webp' | 'image/jpeg';+ mimeType: 'image/webp' | 'image/jpeg' | 'image/png';bytes: Uint8Array;captureArea?: TimelapseCaptureArea;}diff --git a/src/utils/__tests__/nativeEngineBridge.test.ts b/src/utils/__tests__/nativeEngineBridge.test.tsnew file mode 100644index 0000000..b47ea3b--- /dev/null+++ b/src/utils/__tests__/nativeEngineBridge.test.ts@@ -0,0 +1,93 @@+import { describe, expect, it } from 'vitest';+import {+ classifyNativeTool,+ fromNativeLayerNodeMeta,+ isNativeCanvasActive,+ isNativeStrokeTool,+ nativeGetHistory,+ nativeGetMemoryStats,+ parseCssColorToRgba,+ toNativeLayerNodeMeta,+ vramBudgetMbFromPreset,+} from '../nativeEngineBridge';+import type { LayerItem } from '../../types/editor';++describe('nativeEngineBridge', () => {+ it('stays inactive in non-Tauri browser/jsdom environments', () => {+ expect(isNativeCanvasActive()).toBe(false);+ });++ it('classifies brush and eraser as native stroke tools', () => {+ expect(isNativeStrokeTool('brush')).toBe(true);+ expect(isNativeStrokeTool('eraser')).toBe(true);+ expect(isNativeStrokeTool('fill')).toBe(false);+ expect(isNativeStrokeTool('pen')).toBe(false);++ expect(classifyNativeTool('brush')).toBe('brush');+ expect(classifyNativeTool('eraser')).toBe('eraser');+ expect(classifyNativeTool('liquify')).toBe('other');+ });++ it('parses hex and rgb/rgba CSS color strings to normalized RGBA floats', () => {+ const hex6 = parseCssColorToRgba('#161616');+ expect(hex6[0]).toBeCloseTo(22 / 255, 4);+ expect(hex6[1]).toBeCloseTo(22 / 255, 4);+ expect(hex6[2]).toBeCloseTo(22 / 255, 4);+ expect(hex6[3]).toBe(1);++ const hex3 = parseCssColorToRgba('#f0a');+ expect(hex3[0]).toBeCloseTo(1, 4);+ expect(hex3[1]).toBeCloseTo(0, 4);+ expect(hex3[2]).toBeCloseTo(170 / 255, 4);+ expect(hex3[3]).toBe(1);++ const rgba = parseCssColorToRgba('rgba(51, 102, 204, 0.5)');+ expect(rgba[0]).toBeCloseTo(0.2, 4);+ expect(rgba[1]).toBeCloseTo(0.4, 4);+ expect(rgba[2]).toBeCloseTo(0.8, 4);+ expect(rgba[3]).toBeCloseTo(0.5, 4);++ const fallback = parseCssColorToRgba('not-a-color', [0.1, 0.2, 0.3, 1.0]);+ expect(fallback).toEqual([0.1, 0.2, 0.3, 1.0]);+ });++ it('converts compact Phase 2 layer metadata cleanly without DOM canvases and no-ops safely off-desktop', async () => {+ const fakeCanvas = {} as HTMLCanvasElement;+ const layer: LayerItem = {+ id: 'layer-1-doc1',+ name: 'Ink',+ type: 'raster',+ visible: true,+ opacity: 85,+ blendMode: 'multiply',+ locked: false,+ alphaLocked: true,+ clipped: false,+ parentId: null,+ maskCanvas: fakeCanvas,+ maskEnabled: true,+ maskLinked: true,+ expressionColor: 'monochrome',+ monoThreshold: 140,+ thumbnailUrl: 'data:image/png;base64,AA==',+ };++ const nativeMeta = toNativeLayerNodeMeta(layer);+ expect('maskCanvas' in nativeMeta).toBe(false);+ expect(nativeMeta.hasMask).toBe(true);+ expect(nativeMeta.blendMode).toBe('multiply');+ expect(nativeMeta.monoThreshold).toBe(140);++ const hydrated = fromNativeLayerNodeMeta(nativeMeta);+ expect(hydrated.id).toBe('layer-1-doc1');+ expect(hydrated.thumbnailUrl).toBe('data:image/png;base64,AA==');++ expect(vramBudgetMbFromPreset('low')).toBe(128);+ expect(vramBudgetMbFromPreset('medium')).toBe(256);+ expect(vramBudgetMbFromPreset('high')).toBe(512);+ expect(vramBudgetMbFromPreset('ultra')).toBe(1024);++ expect(await nativeGetHistory('doc1')).toBeNull();+ expect(await nativeGetMemoryStats()).toBeNull();+ });+});diff --git a/src/utils/nativeEngineBridge.ts b/src/utils/nativeEngineBridge.tsnew file mode 100644index 0000000..e9c2818--- /dev/null+++ b/src/utils/nativeEngineBridge.ts@@ -0,0 +1,1129 @@+import type {+ BlendMode,+ CanvasColorMode,+ CanvasDimensions,+ ExpressionColor,+ HistoryItemMeta,+ LayerColorLabel,+ LayerItem,+ LayerType,+ ToolType,+} from '../types/editor';++type ToneDotShape = NonNullable<LayerItem['toneDotShape']>;+type ToneDensityType = NonNullable<LayerItem['toneDensityType']>;++export interface NativeViewportRect {+ xPx: number;+ yPx: number;+ widthPx: number;+ heightPx: number;+ dpr: number;+ visible: boolean;+}++export interface NativeUiRect {+ x: number;+ y: number;+ width: number;+ height: number;+}++export interface NativeCameraState {+ panX: number;+ panY: number;+ zoom: number;+ rotation: number;+ flipX: boolean;+ flipY: boolean;+}++export interface NativeCameraEvent extends NativeCameraState {+ commit: boolean;+}++export interface NativeCursorConfig {+ size: number;+ thicknessRatio: number;+ thicknessVertical: boolean;+ tipAngleDeg: number;+ isSquare: boolean;+ visible: boolean;+}++export interface NativeBrushParams {+ size: number;+ opacity: number;+ hardness: number;+ spacing: number;+ minSizeRatio: number;+ usePressureSize: boolean;+ usePressureOpacity: boolean;+ color: [number, number, number, number];+ isEraser: boolean;+}++export type NativeToolKind = 'brush' | 'eraser' | 'other';+export type NativeWheelNavMode = 'zoom' | 'scroll' | 'brush-size';++export interface NativeInteractionPolicy {+ activeTool: NativeToolKind;+ nativeStrokeEnabled: boolean;+ wheelMode: NativeWheelNavMode;+ isWebtoonMode: boolean;+ textInputFocused: boolean;+ workspaceInteracting: boolean;+ modalOpen: boolean;+}++export interface NativeEngineDiagnostics {+ ready: boolean;+ adapterName: string;+ backend: string;+ presentMode: string;+ fps: number;+ frameTimeMs: number;+ inputToPresentMs: number;+ swapchainWidth: number;+ swapchainHeight: number;+ docWidth: number;+ docHeight: number;+ activeStrokeDabs: number;+ totalFramesRendered: number;+ deviceLostRecoveries: number;+ maxFrameLatency: number;+ compositionMode: string;+ gpuVramUsedBytes?: number;+ gpuVramBudgetBytes?: number;+ gpuTilesResident?: number;+ gpuTilesCapacity?: number;+}++export interface NativePointerStatEvent {+ docX: number | null;+ docY: number | null;+ pressure: number;+}++// ---------------------------------------------------------------------------+// Phase 2: Rust Document Store, Layer Tree, CoW History & Tiered Memory Types+// ---------------------------------------------------------------------------++export interface NativeLayerNodeMeta {+ id: string;+ name: string;+ type: LayerType;+ visible: boolean;+ opacity: number;+ blendMode: BlendMode;+ locked: boolean;+ alphaLocked?: boolean;+ clipped?: boolean;+ collapsed?: boolean;+ parentId: string | null;+ isReference?: boolean;+ colorLabel?: LayerColorLabel;+ thumbnailUrl?: string;+ isToneLayer?: boolean;+ toneEnabled?: boolean;+ toneFrequency?: number;+ toneAngle?: number;+ toneDotShape?: ToneDotShape;+ toneDensity?: number;+ toneDensityType?: ToneDensityType;+ layerColorEnabled?: boolean;+ layerColor?: string;+ layerSubColor?: string;+ expressionColor?: ExpressionColor;+ monoThreshold?: number;+ monoExpressBlack?: boolean;+ monoExpressWhite?: boolean;+ hasMask?: boolean;+ maskEnabled?: boolean;+ maskLinked?: boolean;+ maskThumbnailUrl?: string;+ maskVersion?: number;+ adjustmentData?: unknown;+ styles?: unknown;+ comicFrames?: unknown;+ textData?: unknown;+ balloonData?: unknown;+ vectorStrokes?: unknown;+}++export interface NativeLayerPropsPatch {+ name?: string;+ visible?: boolean;+ opacity?: number;+ blendMode?: BlendMode;+ locked?: boolean;+ alphaLocked?: boolean;+ clipped?: boolean;+ collapsed?: boolean;+ parentId?: string | null;+ isReference?: boolean;+ colorLabel?: LayerColorLabel;+ isToneLayer?: boolean;+ toneEnabled?: boolean;+ toneFrequency?: number;+ toneAngle?: number;+ toneDotShape?: ToneDotShape;+ toneDensity?: number;+ toneDensityType?: ToneDensityType;+ layerColorEnabled?: boolean;+ layerColor?: string;+ layerSubColor?: string;+ expressionColor?: ExpressionColor;+ monoThreshold?: number;+ monoExpressBlack?: boolean;+ monoExpressWhite?: boolean;+ maskEnabled?: boolean;+ maskLinked?: boolean;+ adjustmentData?: unknown;+ styles?: unknown;+ comicFrames?: unknown;+ textData?: unknown;+ balloonData?: unknown;+ vectorStrokes?: unknown;+ recordHistory?: boolean;+ historyLabel?: string;+ coalesceKey?: string;+}++export interface NativeHistoryStateSnapshot {+ items: HistoryItemMeta[];+ index: number;+ canUndo: boolean;+ canRedo: boolean;+}++export interface NativeDocumentMetaSnapshot {+ id: string;+ name: string;+ dimensions: CanvasDimensions;+ colorMode: CanvasColorMode;+ defaultToneFrequency: number;+ layers: NativeLayerNodeMeta[];+ activeLayerId: string | null;+ history: NativeHistoryStateSnapshot;+ workTimeMs: number;+ previewDataUrl?: string | null;+ perspectiveRuler?: unknown;+ straightRuler?: unknown;+ animationTimeline?: unknown;+ timelapse?: unknown;+}++export interface NativeOpenDocumentResult {+ doc: NativeDocumentMetaSnapshot;+ previewDataUrl: string | null;+ sourceFormat: string;+}++export interface NativeSaveInkResult {+ path: string | null;+ bytesWritten: number;+ previewDataUrl: string | null;+ tileCount: number;+ maskCount: number;+}++export interface NativeSelectiveUndoOutcome {+ applied: boolean;+ strokeId?: string | null;+ layerId?: string | null;+ contestedTileCount: number;+ preservedPeerEdits: boolean;+ history: NativeHistoryStateSnapshot;+}++export interface NativeHistoryMutationResult {+ doc: NativeDocumentMetaSnapshot;+ dimensionsChanged: boolean;+ layersChanged: boolean;+ changedLayerIds: string[];+ documentStateDelta?: unknown;+ selectiveOutcome?: NativeSelectiveUndoOutcome;+}++export interface NativeMemoryStats {+ ramRawBytes: number;+ ramLz4Bytes: number;+ ramTotalBytes: number;+ ramBudgetBytes: number;+ diskPagedTiles: number;+ diskPagedLogicalBytes: number;+ vramUsedBytes: number;+ vramBudgetBytes: number;+ vramSlotsUsed: number;+ vramSlotsCapacity: number;+ solidTileCount: number;+ rawTileCount: number;+ lz4TileCount: number;+ totalTileCount: number;+ historyEntryCount: number;+ openDocumentCount: number;+}++export interface NativeMemoryBudgetInput {+ ramBudgetMb?: number;+ vramBudgetMb?: number;+ maxHistorySteps?: number;+ offloadInactiveTabs?: boolean;+}++export interface NativeThumbnailUpdate {+ layerId: string;+ thumbnailUrl?: string;+ maskThumbnailUrl?: string;+}++export interface NativeHistoryEvent {+ docId: string;+ history: NativeHistoryStateSnapshot;+}++export interface NativeThumbnailsEvent {+ docId: string;+ updates: NativeThumbnailUpdate[];+}++export interface NativeStrokeCommittedEvent {+ docId: string;+ layerId: string;+ entryId: string;+}++export interface NativeTimelapseCaptureResult {+ width: number;+ height: number;+ bytes: number;+ frameIndex: number;+}++export interface NativeRecoveryCheckpointResult {+ snapshotBytes: number;+ thumbnailBytes: number;+}++const EVENT_CAMERA = 'native-engine://camera';+const EVENT_DIAGNOSTICS = 'native-engine://diagnostics';+const EVENT_POINTER_STAT = 'native-engine://pointer-stat';+const EVENT_HISTORY = 'native-engine://history';+const EVENT_THUMBNAILS = 'native-engine://thumbnails';+const EVENT_STROKE_COMMITTED = 'native-engine://stroke-committed';++let cachedNativeActive = false;+let initPromise: Promise<boolean> | null = null;+const activeListeners = new Set<(active: boolean) => void>();++export function isTauriDesktopRuntime(): boolean {+ if (typeof window === 'undefined') return false;+ const w = window as unknown as Record<string, unknown>;+ return Boolean(w.__TAURI_INTERNALS__ || w.__TAURI__);+}++/**+ * Synchronous check used on hot input paths (pointer handlers, cursor ring, document ops)+ * to determine whether the native Windows DX12 DirectComposition engine is currently active.+ * Always returns `false` in web/Vitest environments.+ */+export function isNativeCanvasActive(): boolean {+ return cachedNativeActive;+}++/**+ * Returns true if the given tool is natively handled on the zero-IPC Rust stroke path.+ */+export function isNativeStrokeTool(tool: ToolType | string): boolean {+ return tool === 'brush' || tool === 'eraser';+}++export function classifyNativeTool(tool: ToolType | string): NativeToolKind {+ if (tool === 'brush') return 'brush';+ if (tool === 'eraser') return 'eraser';+ return 'other';+}++/**+ * Maps `performanceManager`'s `gpuTexturePoolPreset` string to an L1 DX12 VRAM tile budget (MB).+ */+export function vramBudgetMbFromPreset(preset?: string): number {+ switch (preset) {+ case 'low':+ return 128;+ case 'medium':+ return 256;+ case 'high':+ return 512;+ case 'ultra':+ return 1024;+ default:+ return 256;+ }+}++/**+ * Converts a React `LayerItem` into a compact JSON-serializable `NativeLayerNodeMeta`+ * (stripping DOM canvas references while preserving all layer properties and mask flags).+ */+export function toNativeLayerNodeMeta(layer: LayerItem): NativeLayerNodeMeta {+ const { maskCanvas, ...rest } = layer;+ const anyLayer = layer as LayerItem & { hasMask?: boolean };+ return {+ ...rest,+ hasMask: Boolean(maskCanvas || anyLayer.hasMask),+ } as NativeLayerNodeMeta;+}++/**+ * Hydrates a compact Rust `NativeLayerNodeMeta` into a React `LayerItem` without allocating+ * any full-resolution JS pixel buffers or DOM canvases.+ */+export function fromNativeLayerNodeMeta(meta: NativeLayerNodeMeta): LayerItem {+ return {+ ...(meta as unknown as LayerItem),+ thumbnailUrl: meta.thumbnailUrl ?? '',+ };+}++export function subscribeNativeCanvasActive(listener: (active: boolean) => void): () => void {+ activeListeners.add(listener);+ return () => {+ activeListeners.delete(listener);+ };+}++function setCachedNativeActive(active: boolean) {+ if (cachedNativeActive === active) return;+ cachedNativeActive = active;+ for (const cb of activeListeners) {+ try {+ cb(active);+ } catch {+ // Ignore subscriber errors+ }+ }+}++/**+ * Queries the Tauri host once to verify whether `ink-engine` initialized its Windows DX12+ * DirectComposition swapchain cleanly. Safe to call repeatedly.+ */+export async function initNativeEngineBridge(): Promise<boolean> {+ if (!isTauriDesktopRuntime()) {+ setCachedNativeActive(false);+ return false;+ }+ if (initPromise) return initPromise;++ initPromise = (async () => {+ try {+ const { invoke } = await import('@tauri-apps/api/core');+ const active = await invoke<boolean>('native_engine_is_active');+ const resolved = Boolean(active);+ setCachedNativeActive(resolved);+ return resolved;+ } catch {+ setCachedNativeActive(false);+ return false;+ }+ })();++ return initPromise;+}++/**+ * Parses a CSS hex (`#rgb`, `#rrggbb`, `#rrggbbaa`) or `rgb()/rgba()` color string into+ * normalized `[r, g, b, a]` in `0.0..=1.0`.+ */+export function parseCssColorToRgba(+ cssColor: string | null | undefined,+ fallback: [number, number, number, number] = [0.086, 0.086, 0.086, 1.0]+): [number, number, number, number] {+ if (!cssColor) return fallback;+ const raw = cssColor.trim();+ if (raw.startsWith('#')) {+ const hex = raw.slice(1);+ if (hex.length === 3) {+ const r = parseInt(hex[0] + hex[0], 16);+ const g = parseInt(hex[1] + hex[1], 16);+ const b = parseInt(hex[2] + hex[2], 16);+ if (!Number.isNaN(r) && !Number.isNaN(g) && !Number.isNaN(b)) {+ return [r / 255, g / 255, b / 255, 1.0];+ }+ } else if (hex.length === 6 || hex.length === 8) {+ const r = parseInt(hex.slice(0, 2), 16);+ const g = parseInt(hex.slice(2, 4), 16);+ const b = parseInt(hex.slice(4, 6), 16);+ const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) : 255;+ if (!Number.isNaN(r) && !Number.isNaN(g) && !Number.isNaN(b) && !Number.isNaN(a)) {+ return [r / 255, g / 255, b / 255, a / 255];+ }+ }+ return fallback;+ }++ const match = raw.match(+ /rgba?\(\s*([\d.]+)\s*[,\s]\s*([\d.]+)\s*[,\s]\s*([\d.]+)(?:\s*[,/]\s*([\d.]+))?\s*\)/i+ );+ if (match) {+ const r = Math.max(0, Math.min(255, Number(match[1]))) / 255;+ const g = Math.max(0, Math.min(255, Number(match[2]))) / 255;+ const b = Math.max(0, Math.min(255, Number(match[3]))) / 255;+ const a = match[4] !== undefined ? Math.max(0, Math.min(1, Number(match[4]))) : 1.0;+ if (Number.isFinite(r) && Number.isFinite(g) && Number.isFinite(b) && Number.isFinite(a)) {+ return [r, g, b, a];+ }+ }+ return fallback;+}++async function invokeFireAndForget(cmd: string, args?: Record<string, unknown>): Promise<void> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return;+ try {+ const { invoke } = await import('@tauri-apps/api/core');+ await invoke(cmd, args);+ } catch {+ // Ignore transient IPC errors during window teardown+ }+}++async function invokeNative<T>(cmd: string, args?: Record<string, unknown>): Promise<T> {+ const { invoke } = await import('@tauri-apps/api/core');+ return invoke<T>(cmd, args);+}++// ---------------------------------------------------------------------------+// Phase 1: Viewport, Camera, Brush, Cursor & Policy Commands+// ---------------------------------------------------------------------------++export function setNativeViewport(rect: NativeViewportRect): Promise<void> {+ return invokeFireAndForget('native_engine_set_viewport', {+ xPx: Math.round(rect.xPx),+ yPx: Math.round(rect.yPx),+ widthPx: Math.max(0, Math.round(rect.widthPx)),+ heightPx: Math.max(0, Math.round(rect.heightPx)),+ dpr: rect.dpr,+ visible: rect.visible,+ });+}++export function setNativeOccludedRects(rects: NativeUiRect[]): Promise<void> {+ return invokeFireAndForget('native_engine_set_occluded_rects', { rects });+}++export function setNativeDocument(+ width: number,+ height: number,+ showCheckerboard: boolean+): Promise<void> {+ return invokeFireAndForget('native_engine_set_document', {+ width: Math.max(1, Math.round(width)),+ height: Math.max(1, Math.round(height)),+ showCheckerboard,+ });+}++export function setNativeAppearance(+ matteRgba: [number, number, number, number],+ showCheckerboard: boolean+): Promise<void> {+ return invokeFireAndForget('native_engine_set_appearance', {+ matteRgba,+ showCheckerboard,+ });+}++export function setNativeCamera(camera: NativeCameraState): Promise<void> {+ return invokeFireAndForget('native_engine_set_camera', { camera });+}++export function setNativeCursor(config: NativeCursorConfig): Promise<void> {+ return invokeFireAndForget('native_engine_set_cursor', { config });+}++export function setNativeBrush(params: NativeBrushParams): Promise<void> {+ return invokeFireAndForget('native_engine_set_brush', { params });+}++export function setNativePolicy(policy: NativeInteractionPolicy): Promise<void> {+ return invokeFireAndForget('native_engine_set_policy', { policy });+}++export function clearNativeCanvas(): Promise<void> {+ return invokeFireAndForget('native_engine_clear_canvas');+}++export async function getNativeDiagnostics(): Promise<NativeEngineDiagnostics | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ try {+ return await invokeNative<NativeEngineDiagnostics>('native_engine_get_diagnostics');+ } catch {+ return null;+ }+}++// ---------------------------------------------------------------------------+// Phase 2: Document Lifecycle & Zero-Copy File I/O Commands+// ---------------------------------------------------------------------------++export async function createNativeDocument(params: {+ docId: string;+ name: string;+ dimensions: CanvasDimensions;+ colorMode?: CanvasColorMode;+ backgroundHex?: string;+ defaultToneFrequency?: number;+}): Promise<NativeDocumentMetaSnapshot | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ return invokeNative<NativeDocumentMetaSnapshot>('native_engine_create_document', {+ docId: params.docId,+ name: params.name,+ dimensions: params.dimensions,+ colorMode: params.colorMode ?? 'color',+ backgroundHex: params.backgroundHex ?? '#ffffff',+ defaultToneFrequency: params.defaultToneFrequency ?? 60,+ });+}++export async function openNativeDocumentFromPath(+ docId: string,+ path: string+): Promise<NativeOpenDocumentResult> {+ return invokeNative<NativeOpenDocumentResult>('native_engine_open_file', {+ docId,+ path,+ });+}++export async function openNativeDocumentBytes(+ docId: string,+ fileName: string,+ bytes: Uint8Array+): Promise<NativeOpenDocumentResult> {+ const { invoke } = await import('@tauri-apps/api/core');+ const payload =+ bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength+ ? bytes+ : bytes.slice();+ return invoke<NativeOpenDocumentResult>('native_engine_open_file_bytes', payload, {+ headers: {+ 'x-doc-id': encodeURIComponent(docId),+ 'x-file-name': encodeURIComponent(fileName),+ },+ });+}++export async function saveNativeInkDocument(+ docId: string,+ path: string+): Promise<NativeSaveInkResult> {+ return invokeNative<NativeSaveInkResult>('native_engine_save_ink', {+ docId,+ path,+ });+}++export async function saveNativeInkDocumentWithDialog(+ docId: string,+ suggestedName: string,+ initialDir?: string+): Promise<NativeSaveInkResult> {+ return invokeNative<NativeSaveInkResult>('native_engine_save_ink_with_dialog', {+ docId,+ suggestedName,+ initialDir: initialDir ?? null,+ });+}++export async function switchNativeDocument(+ docId: string+): Promise<NativeDocumentMetaSnapshot | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ try {+ return await invokeNative<NativeDocumentMetaSnapshot>('native_engine_switch_document', {+ docId,+ });+ } catch {+ return null;+ }+}++export async function closeNativeDocument(docId: string): Promise<boolean> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return false;+ try {+ return await invokeNative<boolean>('native_engine_close_document', { docId });+ } catch {+ return false;+ }+}++export async function getNativeDocumentState(+ docId?: string+): Promise<NativeDocumentMetaSnapshot | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ try {+ return await invokeNative<NativeDocumentMetaSnapshot | null>(+ 'native_engine_get_document_state',+ { docId: docId ?? null }+ );+ } catch {+ return null;+ }+}++// ---------------------------------------------------------------------------+// Phase 2: Layer Tree CRUD, Properties, Masks & Dirty-Rect Raster Ingestion+// ---------------------------------------------------------------------------++export async function addNativeLayer(+ docId: string,+ layer: LayerItem,+ insertIndex?: number,+ recordHistory: boolean = true+): Promise<NativeDocumentMetaSnapshot | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ return invokeNative<NativeDocumentMetaSnapshot>('native_engine_add_layer', {+ docId,+ layer: toNativeLayerNodeMeta(layer),+ insertIndex: insertIndex ?? null,+ recordHistory,+ });+}++export async function deleteNativeLayer(+ docId: string,+ layerId: string,+ recordHistory: boolean = true+): Promise<NativeDocumentMetaSnapshot | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ return invokeNative<NativeDocumentMetaSnapshot>('native_engine_delete_layer', {+ docId,+ layerId,+ recordHistory,+ });+}++export async function duplicateNativeLayer(+ docId: string,+ sourceLayerId: string,+ newLayerId: string,+ recordHistory: boolean = true+): Promise<NativeDocumentMetaSnapshot | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ return invokeNative<NativeDocumentMetaSnapshot>('native_engine_duplicate_layer', {+ docId,+ sourceLayerId,+ newLayerId,+ recordHistory,+ });+}++export async function reorderNativeLayers(+ docId: string,+ orderedIds: string[],+ parentOverrides?: Record<string, string | null>,+ recordHistory: boolean = true+): Promise<NativeDocumentMetaSnapshot | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ return invokeNative<NativeDocumentMetaSnapshot>('native_engine_reorder_layers', {+ docId,+ orderedIds,+ parentOverrides: parentOverrides ?? null,+ recordHistory,+ });+}++export async function updateNativeLayer(+ docId: string,+ layerId: string,+ patch: NativeLayerPropsPatch+): Promise<NativeDocumentMetaSnapshot | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ return invokeNative<NativeDocumentMetaSnapshot>('native_engine_update_layer', {+ docId,+ layerId,+ patch,+ });+}++export async function syncNativeLayers(+ docId: string,+ layers: LayerItem[],+ activeLayerId?: string | null+): Promise<NativeDocumentMetaSnapshot | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ return invokeNative<NativeDocumentMetaSnapshot>('native_engine_sync_layers', {+ docId,+ layers: layers.map(toNativeLayerNodeMeta),+ activeLayerId: activeLayerId ?? null,+ });+}++export async function clearNativeLayer(+ docId: string,+ layerId: string,+ recordHistory: boolean = true+): Promise<NativeDocumentMetaSnapshot | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ return invokeNative<NativeDocumentMetaSnapshot>('native_engine_clear_layer', {+ docId,+ layerId,+ recordHistory,+ });+}++export async function mergeNativeDown(+ docId: string,+ srcLayerId: string+): Promise<NativeDocumentMetaSnapshot | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ return invokeNative<NativeDocumentMetaSnapshot>('native_engine_merge_down', {+ docId,+ srcLayerId,+ });+}++export async function mergeNativeFolder(+ docId: string,+ folderId: string,+ newLayerId: string+): Promise<NativeDocumentMetaSnapshot | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ return invokeNative<NativeDocumentMetaSnapshot>('native_engine_merge_folder', {+ docId,+ folderId,+ newLayerId,+ });+}++export async function addNativeLayerMask(+ docId: string,+ layerId: string,+ defaultValue: number = 255,+ recordHistory: boolean = true+): Promise<NativeDocumentMetaSnapshot | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ return invokeNative<NativeDocumentMetaSnapshot>('native_engine_add_mask', {+ docId,+ layerId,+ defaultValue,+ recordHistory,+ });+}++export async function removeNativeLayerMask(+ docId: string,+ layerId: string,+ applyToRaster: boolean = false,+ recordHistory: boolean = true+): Promise<NativeDocumentMetaSnapshot | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ return invokeNative<NativeDocumentMetaSnapshot>('native_engine_remove_mask', {+ docId,+ layerId,+ applyToRaster,+ recordHistory,+ });+}++export async function resizeNativeCanvas(params: {+ docId: string;+ dimensions: CanvasDimensions;+ offsetX?: number;+ offsetY?: number;+ scaleContent?: boolean;+ bgHex?: string;+ recordHistory?: boolean;+}): Promise<NativeDocumentMetaSnapshot | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ return invokeNative<NativeDocumentMetaSnapshot>('native_engine_resize_canvas', {+ docId: params.docId,+ dimensions: params.dimensions,+ offsetX: Math.round(params.offsetX ?? 0),+ offsetY: Math.round(params.offsetY ?? 0),+ scaleContent: Boolean(params.scaleContent),+ bgHex: params.bgHex ?? '#ffffff',+ recordHistory: params.recordHistory ?? true,+ });+}++/**+ * Raw binary IPC ingestion of a dirty rectangle (RGBA8 or 8-bit mask) into Rust's sparse+ * tile grid — used when UI-edited layers (text, speech balloons, 3D bakes, image paste) commit.+ */+export async function ingestNativeDirtyRect(params: {+ docId: string;+ layerId: string;+ x: number;+ y: number;+ width: number;+ height: number;+ bytes: Uint8Array;+ isMask?: boolean;+ recordHistory?: boolean;+ actionType?: string;+ label?: string;+ peerId?: string;+ strokeId?: string;+}): Promise<NativeDocumentMetaSnapshot | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ const { invoke } = await import('@tauri-apps/api/core');+ const payload =+ params.bytes.byteOffset === 0 && params.bytes.byteLength === params.bytes.buffer.byteLength+ ? params.bytes+ : params.bytes.slice();+ const headers: Record<string, string> = {+ 'x-doc-id': encodeURIComponent(params.docId),+ 'x-layer-id': encodeURIComponent(params.layerId),+ 'x-x': String(Math.round(params.x)),+ 'x-y': String(Math.round(params.y)),+ 'x-width': String(Math.max(1, Math.round(params.width))),+ 'x-height': String(Math.max(1, Math.round(params.height))),+ 'x-is-mask': params.isMask ? '1' : '0',+ 'x-record-history': params.recordHistory === false ? '0' : '1',+ 'x-action-type': encodeURIComponent(params.actionType ?? 'raster'),+ 'x-label': encodeURIComponent(params.label ?? 'Edit Layer'),+ };+ if (params.peerId) headers['x-peer-id'] = encodeURIComponent(params.peerId);+ if (params.strokeId) headers['x-stroke-id'] = encodeURIComponent(params.strokeId);+ return invoke<NativeDocumentMetaSnapshot>('native_engine_ingest_dirty_rect', payload, {+ headers,+ });+}++// ---------------------------------------------------------------------------+// Phase 2: Rust CoW Undo / Redo & Collaborative Selective Undo Commands+// ---------------------------------------------------------------------------++export async function nativeUndo(docId: string): Promise<NativeHistoryMutationResult | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ return invokeNative<NativeHistoryMutationResult>('native_engine_undo', { docId });+}++export async function nativeRedo(docId: string): Promise<NativeHistoryMutationResult | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ return invokeNative<NativeHistoryMutationResult>('native_engine_redo', { docId });+}++export async function nativeJumpHistory(+ docId: string,+ targetIndex: number+): Promise<NativeHistoryMutationResult | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ return invokeNative<NativeHistoryMutationResult>('native_engine_jump_history', {+ docId,+ targetIndex,+ });+}++export async function nativeSelectiveUndo(+ docId: string,+ peerId?: string | number | null,+ strokeId?: string | null+): Promise<NativeHistoryMutationResult | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ return invokeNative<NativeHistoryMutationResult>('native_engine_selective_undo', {+ docId,+ peerId: peerId !== undefined && peerId !== null ? String(peerId) : null,+ strokeId: strokeId ?? null,+ });+}++export async function nativeSelectiveRedo(+ docId: string,+ peerId?: string | number | null+): Promise<NativeHistoryMutationResult | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ return invokeNative<NativeHistoryMutationResult>('native_engine_selective_redo', {+ docId,+ peerId: peerId !== undefined && peerId !== null ? String(peerId) : null,+ });+}++export async function nativePushHistoryMeta(params: {+ docId: string;+ actionType: string;+ label: string;+ layerId?: string | null;+ documentStateDelta?: unknown;+ coalesceKey?: string;+}): Promise<NativeHistoryStateSnapshot | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ return invokeNative<NativeHistoryStateSnapshot>('native_engine_push_history_meta', {+ docId: params.docId,+ actionType: params.actionType,+ label: params.label,+ layerId: params.layerId ?? null,+ documentStateDelta: params.documentStateDelta ?? null,+ coalesceKey: params.coalesceKey ?? null,+ });+}++export async function nativeGetHistory(docId: string): Promise<NativeHistoryStateSnapshot | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ try {+ return await invokeNative<NativeHistoryStateSnapshot>('native_engine_get_history', { docId });+ } catch {+ return null;+ }+}++export async function nativeResetHistory(+ docId: string,+ label?: string+): Promise<NativeHistoryStateSnapshot | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ try {+ return await invokeNative<NativeHistoryStateSnapshot>('native_engine_reset_history', {+ docId,+ label: label ?? null,+ });+ } catch {+ return null;+ }+}++// ---------------------------------------------------------------------------+// Phase 2: Tiered Memory, Async Thumbnails, Timelapse & Crash Recovery+// ---------------------------------------------------------------------------++export async function getNativeMemoryStats(): Promise<NativeMemoryStats | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ try {+ return await invokeNative<NativeMemoryStats>('native_engine_get_memory_stats');+ } catch {+ return null;+ }+}++export async function setNativeMemoryBudget(+ input: NativeMemoryBudgetInput+): Promise<NativeMemoryStats | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ try {+ return await invokeNative<NativeMemoryStats>('native_engine_set_memory_budget', { input });+ } catch {+ return null;+ }+}++export async function purgeNativeMemory(): Promise<NativeMemoryStats | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ try {+ return await invokeNative<NativeMemoryStats>('native_engine_purge_memory');+ } catch {+ return null;+ }+}++export function requestNativeThumbnails(docId: string, layerIds?: string[]): Promise<void> {+ return invokeFireAndForget('native_engine_request_thumbnails', {+ docId,+ layerIds: layerIds ?? null,+ });+}++export async function captureNativeTimelapseFrame(params: {+ docId: string;+ sessionId: string;+ frameIndex: number;+ maxDim?: number;+ captureArea?: string;+}): Promise<NativeTimelapseCaptureResult | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ return invokeNative<NativeTimelapseCaptureResult>('native_engine_capture_timelapse_frame', {+ docId: params.docId,+ sessionId: params.sessionId,+ frameIndex: params.frameIndex,+ maxDim: params.maxDim ?? 1920,+ captureArea: params.captureArea ?? null,+ });+}++export async function nativeRecoveryCheckpoint(+ docId: string,+ sessionId: string,+ manifestJson?: string+): Promise<NativeRecoveryCheckpointResult | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ return invokeNative<NativeRecoveryCheckpointResult>('native_engine_recovery_checkpoint', {+ docId,+ sessionId,+ manifestJson: manifestJson ?? null,+ });+}++export async function nativeRecoveryRestore(+ sessionId: string,+ docId: string+): Promise<NativeDocumentMetaSnapshot> {+ return invokeNative<NativeDocumentMetaSnapshot>('native_engine_recovery_restore', {+ sessionId,+ docId,+ });+}++// ---------------------------------------------------------------------------+// Event Subscriptions (Rust -> React)+// ---------------------------------------------------------------------------++function subscribeTauriEvent<T>(eventName: string, handler: (payload: T) => void): () => void {+ if (!isTauriDesktopRuntime()) return () => {};+ let unlistenFn: (() => void) | null = null;+ let disposed = false;++ void import('@tauri-apps/api/event')+ .then(({ listen }) =>+ listen<T>(eventName, (event) => {+ if (!disposed) {+ handler(event.payload);+ }+ })+ )+ .then((unlisten) => {+ if (disposed) {+ unlisten();+ } else {+ unlistenFn = unlisten;+ }+ })+ .catch(() => {+ // Ignore outside Tauri+ });++ return () => {+ disposed = true;+ unlistenFn?.();+ unlistenFn = null;+ };+}++export function subscribeNativeCamera(cb: (ev: NativeCameraEvent) => void): () => void {+ return subscribeTauriEvent<NativeCameraEvent>(EVENT_CAMERA, cb);+}++export function subscribeNativeDiagnostics(cb: (diag: NativeEngineDiagnostics) => void): () => void {+ return subscribeTauriEvent<NativeEngineDiagnostics>(EVENT_DIAGNOSTICS, cb);+}++export function subscribeNativePointerStat(+ cb: (stat: NativePointerStatEvent) => void+): () => void {+ return subscribeTauriEvent<NativePointerStatEvent>(EVENT_POINTER_STAT, cb);+}++export function subscribeNativeHistory(cb: (ev: NativeHistoryEvent) => void): () => void {+ return subscribeTauriEvent<NativeHistoryEvent>(EVENT_HISTORY, cb);+}++export function subscribeNativeThumbnails(cb: (ev: NativeThumbnailsEvent) => void): () => void {+ return subscribeTauriEvent<NativeThumbnailsEvent>(EVENT_THUMBNAILS, cb);+}++export function subscribeNativeStrokeCommitted(+ cb: (ev: NativeStrokeCommittedEvent) => void+): () => void {+ return subscribeTauriEvent<NativeStrokeCommittedEvent>(EVENT_STROKE_COMMITTED, cb);+}diff --git a/src/utils/saveManager/inkSerialize.ts b/src/utils/saveManager/inkSerialize.tsindex d789b01..03a0f00 100644--- a/src/utils/saveManager/inkSerialize.ts+++ b/src/utils/saveManager/inkSerialize.ts@@ -271,7 +271,7 @@ export async function serializeInkProject(// Stream time-lapse keyframes directly into ZIP with ZipPassThrough (already WebP/JPEG compressed)const savedTimelapseFrames: InkTimelapseFrameMetadata[] = [];const usedTimelapsePaths = new Set<string>();- const allocateTimelapsePath = (frameIndex: number, ext: 'webp' | 'jpg'): string => {+ const allocateTimelapsePath = (frameIndex: number, ext: 'webp' | 'jpg' | 'png'): string => {const baseIndex = Number.isSafeInteger(frameIndex) && frameIndex >= 0 ? frameIndex : 0;let candidate = `timelapse/frame_${String(baseIndex).padStart(6, '0')}.${ext}`;let suffix = 1;@@ -289,7 +289,7 @@ export async function serializeInkProject(timestamp: number;width: number;height: number;- mimeType: 'image/webp' | 'image/jpeg';+ mimeType: 'image/webp' | 'image/jpeg' | 'image/png';};let frameBytes: Uint8Array | null = null;@@ -310,9 +310,14 @@ export async function serializeInkProject(frameBytes.byteLength > 0 &&frameBytes.byteLength <= MAX_TIMELAPSE_FRAME_BYTES) {- const mimeType: 'image/webp' | 'image/jpeg' =- frameMeta.mimeType === 'image/jpeg' ? 'image/jpeg' : 'image/webp';- const ext: 'webp' | 'jpg' = mimeType === 'image/jpeg' ? 'jpg' : 'webp';+ const mimeType: 'image/webp' | 'image/jpeg' | 'image/png' =+ frameMeta.mimeType === 'image/jpeg'+ ? 'image/jpeg'+ : frameMeta.mimeType === 'image/png'+ ? 'image/png'+ : 'image/webp';+ const ext: 'webp' | 'jpg' | 'png' =+ mimeType === 'image/jpeg' ? 'jpg' : mimeType === 'image/png' ? 'png' : 'webp';const safeIndex =Number.isSafeInteger(frameMeta.index) && frameMeta.index >= 0 ? frameMeta.index : i;const framePath = allocateTimelapsePath(safeIndex, ext);diff --git a/src/utils/saveManager/types.ts b/src/utils/saveManager/types.tsindex de5d159..4e5599a 100644--- a/src/utils/saveManager/types.ts+++ b/src/utils/saveManager/types.ts@@ -17,7 +17,7 @@ export interface TimelapsePersistenceFrameMeta {timestamp: number;width: number;height: number;- mimeType: 'image/webp' | 'image/jpeg';+ mimeType: 'image/webp' | 'image/jpeg' | 'image/png';bytes: number;}diff --git a/src/utils/timelapseEngine.ts b/src/utils/timelapseEngine.tsindex dd3536a..b87f9ad 100644--- a/src/utils/timelapseEngine.ts+++ b/src/utils/timelapseEngine.ts@@ -25,6 +25,10 @@ import {import { ViewportCompositor } from './compositor';import { SparseTileGrid } from './tileEngine';import { canvasToBlob, TimelapsePersistenceProvider } from './saveManager';+import {+ captureNativeTimelapseFrame,+ isNativeCanvasActive,+} from './nativeEngineBridge';import {captureNativeAppWindowToCanvas,computeCanvasViewDimensions,@@ -79,7 +83,7 @@ export interface TimelapseFrameEntry {timestamp: number;width: number;height: number;- mimeType: 'image/webp' | 'image/jpeg';+ mimeType: 'image/webp' | 'image/jpeg' | 'image/png';bytes: number;offloadedToDisk: boolean;captureArea?: TimelapseCaptureArea;@@ -1337,6 +1341,46 @@ export class TimelapseRecorderManager {const maxCaptureDim = captureResolutionToMaxDim(sess.captureResolution);const area = sess.captureArea;++ // Phase 2 Native Rust Artwork Timelapse Capture: renders downscaled PNG straight from+ // crates/ink-engine tiles directly into src-tauri/src/timelapse.rs (ZERO JS pixel IPC!)+ if (isNativeCanvasActive() && area === 'artwork') {+ const idx = sess.nextIndex;+ const nativeRes = await captureNativeTimelapseFrame({+ docId: documentId,+ sessionId: sess.recordingId,+ frameIndex: idx,+ maxDim: maxCaptureDim,+ captureArea: 'artwork',+ });+ if (this.sessions.get(documentId) !== sess || sess.generation !== gen) {+ return false;+ }+ if (nativeRes) {+ sess.nextIndex = idx + 1;+ sess.lastCaptureSig = visualSig;+ sess.updatedAt = now;+ const entry: TimelapseFrameEntry = {+ id: `tl-${sess.recordingId}-${idx}`,+ index: idx,+ timestamp: now,+ width: nativeRes.width,+ height: nativeRes.height,+ mimeType: 'image/png',+ bytes: nativeRes.bytes,+ offloadedToDisk: true,+ captureArea: 'artwork',+ };+ sess.storageBytes += entry.bytes;+ sess.frames.push(entry);+ if (sess.frames.length === 1 || sess.frames.length % 10 === 0) {+ this.enqueueMetaPersist(sess);+ }+ this.notify();+ return true;+ }+ }+let outW = 0;let outH = 0;let capturedAreaUsed: TimelapseCaptureArea = area;diff --git a/src/utils/timelapseStorage.ts b/src/utils/timelapseStorage.tsindex 0489253..77dd214 100644--- a/src/utils/timelapseStorage.ts+++ b/src/utils/timelapseStorage.ts@@ -32,7 +32,7 @@ export interface PersistentFrameRecord {timestamp: number;width: number;height: number;- mimeType: 'image/webp' | 'image/jpeg';+ mimeType: 'image/webp' | 'image/jpeg' | 'image/png';bytes: number;captureArea?: TimelapseCaptureArea;}@@ -237,7 +237,7 @@ interface IdbStoredFrameRow {key: string;recordingId: string;index: number;- mimeType: 'image/webp' | 'image/jpeg';+ mimeType: 'image/webp' | 'image/jpeg' | 'image/png';bytes: Uint8Array;}@@ -510,7 +510,12 @@ export async function persistSingleFrame(): Promise<boolean> {if (isTauriRuntime()) {try {- const ext = record.mimeType === 'image/jpeg' ? 'jpg' : 'webp';+ const ext =+ record.mimeType === 'image/jpeg'+ ? 'jpg'+ : record.mimeType === 'image/png'+ ? 'png'+ : 'webp';const headers: Record<string, string> = {'x-session-id': encodeURIComponent(recordingId),'x-frame-index': String(record.index),@@ -560,7 +565,12 @@ export async function loadPersistedSession(timestamp: Number(f.timestamp) || 0,width: Math.max(0, Number(f.width) || 0),height: Math.max(0, Number(f.height) || 0),- mimeType: f.mimeType === 'image/jpeg' ? 'image/jpeg' : 'image/webp',+ mimeType:+ f.mimeType === 'image/jpeg'+ ? 'image/jpeg'+ : f.mimeType === 'image/png'+ ? 'image/png'+ : 'image/webp',bytes: Math.max(0, Number(f.bytes) || 0),...(f.captureArea ? { captureArea: sanitizeCaptureArea(f.captureArea) } : {}),}))@@ -581,7 +591,12 @@ export async function loadPersistedSession(timestamp: 0,width: 0,height: 0,- mimeType: ext === 'jpg' || ext === 'jpeg' ? 'image/jpeg' : 'image/webp',+ mimeType:+ ext === 'jpg' || ext === 'jpeg'+ ? 'image/jpeg'+ : ext === 'png'+ ? 'image/png'+ : 'image/webp',bytes: 0,}));return { meta: null, frames, totalBytes: 0 };@@ -596,7 +611,7 @@ export async function loadPersistedSession(export async function readPersistedFrame(recordingId: string,index: number,- mimeType: 'image/webp' | 'image/jpeg'+ mimeType: 'image/webp' | 'image/jpeg' | 'image/png'): Promise<Uint8Array | null> {if (isTauriRuntime()) {try {@@ -606,7 +621,12 @@ export async function readPersistedFrame({'x-session-id': encodeURIComponent(recordingId),'x-frame-index': String(index),- 'x-ext': mimeType === 'image/jpeg' ? 'jpg' : 'webp',+ 'x-ext':+ mimeType === 'image/jpeg'+ ? 'jpg'+ : mimeType === 'image/png'+ ? 'png'+ : 'webp',});return new Uint8Array(toArrayBuffer(raw));diff --git a/src/utils/undoCache.ts b/src/utils/undoCache.tsindex a43f281..2a79fdd 100644--- a/src/utils/undoCache.ts+++ b/src/utils/undoCache.ts@@ -1,9 +1,9 @@/**- * LRU Tile-Delta Undo/Redo Disk Caching Engine+ * In-memory compressed tile-delta cache used in Vitest/headless JS tests.*- * Designed for 600 DPI professional manga documents (4961 x 7016 px, 70MP double spreads).- * Keeps only the most recent steps in RAM, seamlessly offloading older tile-delta states- * to temporary disk storage via Tauri v2 Rust IPC or zlib-compressed RAM buffers.+ * On Windows desktop (`isNativeCanvasActive() === true`), all Copy-on-Write undo/redo+ * tile deltas, L2 LZ4 compression, and L3 scratch disk paging live exclusively in Rust+ * (`crates/ink-engine`) with zero JS undo-cache IPC round-trips.*/import { zlibSync, unzlibSync } from 'fflate';@@ -81,14 +81,6 @@ export class UndoCacheManager {private compressedRamCache: Map<string, Uint8Array> = new Map();private inFlightOffloads: Map<string, Promise<void>> = new Map();private keepInRamIds: Set<string> = new Set();- private invokePromise: Promise<typeof import('@tauri-apps/api/core').invoke> | null = null;-- private getInvoke(): Promise<typeof import('@tauri-apps/api/core').invoke> {- if (!this.invokePromise) {- this.invokePromise = import('@tauri-apps/api/core').then((m) => m.invoke);- }- return this.invokePromise;- }constructor(sessionId?: string) {this.sessionId = sessionId || `session-${Date.now()}-${Math.random().toString(36).substring(2, 8)}`;@@ -195,8 +187,9 @@ export class UndoCacheManager {}/**- * Offload a single history item's tile deltas to disk via Tauri IPC (with off-main-thread Worker zlib),- * or to a compact zlib-compressed RAM buffer when running in a browser environment.+ * Compresses a single history item's tile deltas into a compact zlib-compressed RAM buffer.+ * (Obsolete Tauri `save_undo_tile_cache` IPC removed in Phase 2 — Rust CoW history owns+ * all desktop undo/redo memory & scratch paging directly in-process.)*/public async offloadToDisk(item: HistoryItem): Promise<void> {if (!item.tileDeltas || item.tileDeltas.length === 0) return;@@ -211,31 +204,6 @@ export class UndoCacheManager {const job = (async () => {const compressed = await compressTileDeltasPayloadAsync(deltasToOffload);-- if (isTauriEnvironment()) {- try {- const invoke = await this.getInvoke();- const payload =- compressed.byteOffset === 0 && compressed.byteLength === compressed.buffer.byteLength- ? compressed- : compressed.slice();- await invoke('save_undo_tile_cache', payload, {- headers: {- 'x-session-id': encodeURIComponent(this.sessionId),- 'x-state-id': encodeURIComponent(item.id),- },- });- this.diskCachedIds.add(item.id);- if (!this.keepInRamIds.delete(item.id)) {- this.ramItems.delete(item.id);- item.tileDeltas = undefined;- }- return;- } catch (err) {- console.warn('[UndoCache] Failed to offload tile deltas to disk, using compressed RAM fallback:', err);- }- }-this.compressedRamCache.set(item.id, compressed);if (!this.keepInRamIds.delete(item.id)) {this.ramItems.delete(item.id);@@ -306,39 +274,11 @@ export class UndoCacheManager {return deltas;}- if (this.diskCachedIds.has(item.id) && isTauriEnvironment()) {- try {- const invoke = await this.getInvoke();- const rawData = await invoke<ArrayBuffer | Uint8Array | number[]>('load_undo_tile_cache', undefined, {- headers: {- 'x-session-id': encodeURIComponent(this.sessionId),- 'x-state-id': encodeURIComponent(item.id),- },- });- if (rawData) {- const u8 =- rawData instanceof Uint8Array- ? rawData- : rawData instanceof ArrayBuffer- ? new Uint8Array(rawData)- : new Uint8Array(rawData);- if (u8.length > 0) {- const deltas = await decompressTileDeltasPayloadAsync(u8);- item.tileDeltas = deltas;- this.ramItems.add(item.id);- return deltas;- }- }- } catch (err) {- console.warn('[UndoCache] Failed to restore tile deltas from disk:', err);- }- }-return null;}/**- * Clear all disk and compressed cached states for this session.+ * Clear all compressed cached states for this session.*/public async clearCache(): Promise<void> {this.ramItems.clear();@@ -346,14 +286,6 @@ export class UndoCacheManager {this.compressedRamCache.clear();this.inFlightOffloads.clear();this.keepInRamIds.clear();- if (isTauriEnvironment()) {- try {- const invoke = await this.getInvoke();- await invoke('clear_undo_tile_cache', { sessionId: this.sessionId });- } catch (err) {- console.warn('[UndoCache] Failed to clear disk cache:', err);- }- }}}diff --git a/src/utils/vectorLayerRenderer.ts b/src/utils/vectorLayerRenderer.tsindex 20f95f2..3487c0e 100644--- a/src/utils/vectorLayerRenderer.ts+++ b/src/utils/vectorLayerRenderer.ts@@ -7,6 +7,13 @@ import {import { computeMangaTextLayout, renderMangaTextToCanvas } from './mangaTextEngine';import { hitTestBalloon, renderSpeechBalloon } from './balloonEngine';import { SparseTileGrid, releaseTemporaryCanvas } from './tileEngine';+import {+ clearNativeLayer,+ ingestNativeDirtyRect,+ isNativeCanvasActive,+ requestNativeThumbnails,+} from './nativeEngineBridge';+import { useDocumentStore } from '../stores';/*** Renders non-destructive TextLayerData onto a 2D canvas context.@@ -170,12 +177,22 @@ export function syncVectorObjectLayerToGrid(const rw = maxX - minX;const rh = maxY - minY;const format = layer.expressionColor === 'monochrome' ? 'monochrome-1bit' : 'color-32bit';- tileGrid.clearLayer(layer.id);- tileGrid.setLayerFormat(layer.id, format);- tileGrid.markLayerIngested(layer.id);+ const nativeDocId = isNativeCanvasActive()+ ? useDocumentStore.getState().activeDocumentId+ : null;++ if (!nativeDocId) {+ tileGrid.clearLayer(layer.id);+ tileGrid.setLayerFormat(layer.id, format);+ tileGrid.markLayerIngested(layer.id);+ }if (rw <= 0 || rh <= 0) {- tileGrid.notifyChange(true);+ if (nativeDocId) {+ void clearNativeLayer(nativeDocId, layer.id, false);+ } else {+ tileGrid.notifyChange(true);+ }return;}@@ -198,7 +215,32 @@ export function syncVectorObjectLayerToGrid(ctx.restore();const imgData = ctx.getImageData(0, 0, rw, rh);- tileGrid.writeImageData(layer.id, imgData, minX, minY, format, true);- tileGrid.notifyChange(true);+ if (nativeDocId) {+ // Phase 2 Native Rust path: stream tight dirty-rect raw RGBA8 straight to Rust SparseLayerGrid+ const bytes = new Uint8Array(+ imgData.data.buffer,+ imgData.data.byteOffset,+ imgData.data.byteLength+ );+ void clearNativeLayer(nativeDocId, layer.id, false)+ .then(() =>+ ingestNativeDirtyRect({+ docId: nativeDocId,+ layerId: layer.id,+ x: minX,+ y: minY,+ width: rw,+ height: rh,+ bytes,+ recordHistory: true,+ actionType: layer.type,+ label: layer.type === 'balloon' ? 'Edit Speech Balloon' : 'Edit Text Layer',+ })+ )+ .then(() => requestNativeThumbnails(nativeDocId, [layer.id]));+ } else {+ tileGrid.writeImageData(layer.id, imgData, minX, minY, format, true);+ tileGrid.notifyChange(true);+ }releaseTemporaryCanvas(targetCanvas);}