LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
M0.37: port LightCraft UI, input and capture lifecycle to egui 0.37
skylartaylor50df6461835c
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex d2fef73a6..a309a9fb3 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -22,7 +22,7 @@ jobs:uses: storytold/craft-common-actions/.github/workflows/gate.yml@mainwith:# Same craft-fonts commit as release.yml.- craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc+ craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83timeout-minutes: 90# xtask ci runs cargo test: the demo scene cache is per process, so nextest is slower here.tools: ""diff --git a/.github/workflows/freebsd.yml b/.github/workflows/freebsd.ymlindex 19470cf69..9077bac2c 100644--- a/.github/workflows/freebsd.yml+++ b/.github/workflows/freebsd.yml@@ -28,4 +28,4 @@ jobs:uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@mainwith:require-craft-fonts: true- craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc+ craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 7356f66fe..d1841ebe7 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -66,7 +66,7 @@ jobs:with:app-name: lightcraftapp-title: LightCraft- craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc+ craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83web-craft-fonts: trueversion: ${{ inputs.version }}secrets:diff --git a/Cargo.lock b/Cargo.lockindex 8b3985fc0..8eab2b93f 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -20,21 +20,21 @@ checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618"[[package]]name = "accesskit"-version = "0.24.1"+version = "0.25.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d3b7f7f85a7e5f68090000ed7622545829afd484d210358702ae4cb97dd0c320"+checksum = "ad442f58ee04714aaa0ba0a2768c1ea1935b29507bb22ddece8cbbc76db02932"dependencies = ["uuid",][[package]]name = "accesskit_atspi_common"-version = "0.18.1"+version = "0.21.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1e8c61bee90b42a772d39d06a740207dc71a4e780004ace1db8d99fb1baaa954"+checksum = "52c182f9c282ac9c5638d876d551d15e5f7d397ec263349a0c6a2b61595dd5e4"dependencies = ["accesskit",- "accesskit_consumer 0.36.0",+ "accesskit_consumer","atspi-common","phf","serde",@@ -43,43 +43,37 @@ dependencies = [[[package]]name = "accesskit_consumer"-version = "0.35.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "53cf47daed85312e763fbf85ceca136e0d7abc68e0a7e12abe11f48172bc3b10"-dependencies = [- "accesskit",- "hashbrown 0.16.1",-]--[[package]]-name = "accesskit_consumer"-version = "0.36.0"+version = "0.39.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "25e0d7e25d06f4dc21d1774d67146e9e80d6789216cbd4d1e88185b0095dba60"+checksum = "8a45e2bb300bea6d5f33a82c3e051c3ddc6f41c209750f68a0acbe991a284344"dependencies = ["accesskit",- "hashbrown 0.16.1",+ "hashbrown 0.17.1",][[package]]-name = "accesskit_consumer"-version = "0.38.0"+name = "accesskit_ios"+version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5d10a236f96f87d70732e44520046785431ef01d5bcd6b041317bfadd2f88245"+checksum = "28e539d64b27fd4c14de8f78ada8f7c944c092f52f7e49fb63316507a57f6937"dependencies = ["accesskit",- "hashbrown 0.16.1",+ "accesskit_consumer",+ "hashbrown 0.17.1",+ "objc2 0.5.2",+ "objc2-foundation 0.2.2",+ "objc2-ui-kit 0.2.2",][[package]]name = "accesskit_macos"-version = "0.26.3"+version = "0.27.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ce02dc63b43f0c9296af9ac946312a2dc8814427d7a64d2d600971dac55b6076"+checksum = "5701624bf6a11efb6d4c8e922bf44126ed96250e5faa9a7a0468c979635839a4"dependencies = ["accesskit",- "accesskit_consumer 0.38.0",- "hashbrown 0.16.1",+ "accesskit_consumer",+ "hashbrown 0.17.1","objc2 0.5.2","objc2-app-kit 0.2.2","objc2-foundation 0.2.2",@@ -87,9 +81,9 @@ dependencies = [[[package]]name = "accesskit_unix"-version = "0.21.1"+version = "0.24.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b016ca8db0ea0ea2ceff29a9d6240391492d960716aa471967c00e8cc8cb197c"+checksum = "202f24df034a7476d07b7f74284de84f6d62aabd858dbe7ee9cad3b7ad6f8f9d"dependencies = ["accesskit","accesskit_atspi_common",@@ -105,13 +99,13 @@ dependencies = [[[package]]name = "accesskit_windows"-version = "0.32.1"+version = "0.35.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "eff7009f1a532e917d66970a1e80c965140c6cfbbabbdde3d64e5431e6c78e21"+checksum = "ce63f35d6bdcf59f26b76b3379063f738e6412cef46999cc772d46aa3de35adb"dependencies = ["accesskit",- "accesskit_consumer 0.35.0",- "hashbrown 0.16.1",+ "accesskit_consumer",+ "hashbrown 0.17.1","static_assertions","windows","windows-core",@@ -119,11 +113,12 @@ dependencies = [[[package]]name = "accesskit_winit"-version = "0.32.2"+version = "0.34.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1fe9a94394896352cc4660ca2288bd4ef883d83238853c038b44070c8f134313"+checksum = "ee96dd150375c05912d8a473f98c2fb155fb3234fac88292d396548a2460fa77"dependencies = ["accesskit",+ "accesskit_ios","accesskit_macos","accesskit_unix","accesskit_windows",@@ -296,6 +291,7 @@ dependencies = ["parking_lot","percent-encoding","windows-sys 0.60.2",+ "wl-clipboard-rs","x11rb",]@@ -1089,7 +1085,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=82a24b006eefa036b43c09[[package]]name = "craft-ui"version = "0.1.0"-source = "git+https://github.com/storytold/craft-libs?rev=5c874d51eeb3de70e735c8ce87a59a7dedd47675#5c874d51eeb3de70e735c8ce87a59a7dedd47675"+source = "git+https://github.com/storytold/craft-libs?rev=c488caa9fbc2fb1a86e4674887e9b80b598ebbfa#c488caa9fbc2fb1a86e4674887e9b80b598ebbfa"dependencies = ["egui","serde",@@ -1350,9 +1346,8 @@ dependencies = [[[package]]name = "ecolor"-version = "0.36.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0656a7530b9e2841ee7a5f983965bdd9840c32f4012f759cfd44b912cced6b34"+version = "0.37.0"+source = "git+https://github.com/storytold/egui.git?rev=173cc7375d35dc5fbc5b5d0994fdf787f547c5d1#173cc7375d35dc5fbc5b5d0994fdf787f547c5d1"dependencies = ["bytemuck","emath",@@ -1384,9 +1379,8 @@ dependencies = [[[package]]name = "eframe"-version = "0.36.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "55ad41fac6e3149abb4866e93df37dbd33baa95db525c3368c944584e95a5dc2"+version = "0.37.0"+source = "git+https://github.com/storytold/egui.git?rev=173cc7375d35dc5fbc5b5d0994fdf787f547c5d1#173cc7375d35dc5fbc5b5d0994fdf787f547c5d1"dependencies = ["ahash","bytemuck",@@ -1409,6 +1403,7 @@ dependencies = ["pollster 1.0.1","profiling","raw-window-handle",+ "send_wrapper","static_assertions","wasm-bindgen","web-sys",@@ -1420,9 +1415,8 @@ dependencies = [[[package]]name = "egui"-version = "0.36.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dc938cc27cd911415e1e4d151bc56ff9df063d8db081374e87aeb805ea74b2ba"+version = "0.37.0"+source = "git+https://github.com/storytold/egui.git?rev=173cc7375d35dc5fbc5b5d0994fdf787f547c5d1#173cc7375d35dc5fbc5b5d0994fdf787f547c5d1"dependencies = ["accesskit","ahash",@@ -1440,9 +1434,8 @@ dependencies = [[[package]]name = "egui-wgpu"-version = "0.36.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5cef1f6d1bba40b09a4d0d62cb822b81030922cfbf65c5373398c3a3caafc5bd"+version = "0.37.0"+source = "git+https://github.com/storytold/egui.git?rev=173cc7375d35dc5fbc5b5d0994fdf787f547c5d1#173cc7375d35dc5fbc5b5d0994fdf787f547c5d1"dependencies = ["ahash","bytemuck",@@ -1460,30 +1453,33 @@ dependencies = [[[package]]name = "egui-winit"-version = "0.36.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "98466000559d66ba4db786a30448b01483946add4188e7f10f522a27b4fb89cc"+version = "0.37.0"+source = "git+https://github.com/storytold/egui.git?rev=173cc7375d35dc5fbc5b5d0994fdf787f547c5d1#173cc7375d35dc5fbc5b5d0994fdf787f547c5d1"dependencies = ["accesskit_winit","arboard",+ "block2 0.6.2","bytemuck","egui",+ "image","log","objc2 0.6.4",+ "objc2-app-kit 0.3.2","objc2-foundation 0.3.2","objc2-ui-kit 0.3.2",+ "parking_lot","profiling","raw-window-handle","smithay-clipboard","web-time",+ "windows-sys 0.61.2","winit",][[package]]name = "egui_glow"-version = "0.36.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "606ed4167daf341e5753d703285c4c1d562324b2c07aa8f405cd7d066fe58f3b"+version = "0.37.0"+source = "git+https://github.com/storytold/egui.git?rev=173cc7375d35dc5fbc5b5d0994fdf787f547c5d1#173cc7375d35dc5fbc5b5d0994fdf787f547c5d1"dependencies = ["bytemuck","egui",@@ -1495,9 +1491,8 @@ dependencies = [[[package]]name = "egui_kittest"-version = "0.36.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5eb3f3effb2726fee23449293e67acbf6cc6ce35525b1722bd5743bb348114d5"+version = "0.37.0"+source = "git+https://github.com/storytold/egui.git?rev=173cc7375d35dc5fbc5b5d0994fdf787f547c5d1#173cc7375d35dc5fbc5b5d0994fdf787f547c5d1"dependencies = ["dify","eframe",@@ -1543,9 +1538,8 @@ dependencies = [[[package]]name = "emath"-version = "0.36.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "52c8d4141cf0f60fb2f7aefaf352d3ffa5171ef0ab09731c64391801e95e48f1"+version = "0.37.0"+source = "git+https://github.com/storytold/egui.git?rev=173cc7375d35dc5fbc5b5d0994fdf787f547c5d1#173cc7375d35dc5fbc5b5d0994fdf787f547c5d1"dependencies = ["bytemuck",]@@ -1591,9 +1585,8 @@ dependencies = [[[package]]name = "epaint"-version = "0.36.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a0ec0308dc23130fc1a7d4623a8534c2ed069c6dc84e258ee4f3de99615aa1a3"+version = "0.37.0"+source = "git+https://github.com/storytold/egui.git?rev=173cc7375d35dc5fbc5b5d0994fdf787f547c5d1#173cc7375d35dc5fbc5b5d0994fdf787f547c5d1"dependencies = ["ahash","bytemuck",@@ -1609,16 +1602,17 @@ dependencies = ["self_cell","skrifa","smallvec",+ "unicode-bidi","unicode-general-category",+ "unicode-properties","unicode-segmentation","vello_cpu",][[package]]name = "epaint_default_fonts"-version = "0.36.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "773fa9c96dd0dbef887e39d0ed6177f141cce4d68e6041df77570aa3702dfa13"+version = "0.37.0"+source = "git+https://github.com/storytold/egui.git?rev=173cc7375d35dc5fbc5b5d0994fdf787f547c5d1#173cc7375d35dc5fbc5b5d0994fdf787f547c5d1"[[package]]name = "equator"@@ -1796,6 +1790,12 @@ version = "0.1.14"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"+[[package]]+name = "fixedbitset"+version = "0.5.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99"+[[package]]name = "flate2"version = "1.1.10"@@ -1825,6 +1825,12 @@ version = "1.0.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"+[[package]]+name = "foldhash"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"+[[package]]name = "foldhash"version = "0.2.0"@@ -2379,12 +2385,12 @@ dependencies = [[[package]]name = "glifo"-version = "0.2.0"+version = "0.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ed4a1bb24121291d27230c1b1b44e07d6a9b28cefdb32fe1581dfb84e14f940a"+checksum = "282a26c1e23de04bdab3e34a21b6f877a479b96737792516b9b8b8f69b6661be"dependencies = ["bytemuck",- "foldhash",+ "foldhash 0.2.0","hashbrown 0.17.1","log","peniko",@@ -2532,6 +2538,15 @@ dependencies = ["smallvec",]+[[package]]+name = "hashbrown"+version = "0.15.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"+dependencies = [+ "foldhash 0.1.5",+]+[[package]]name = "hashbrown"version = "0.16.1"@@ -2540,7 +2555,7 @@ checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"dependencies = ["allocator-api2","equivalent",- "foldhash",+ "foldhash 0.2.0","serde","serde_core",]@@ -2551,7 +2566,7 @@ version = "0.17.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"dependencies = [- "foldhash",+ "foldhash 0.2.0",][[package]]@@ -3012,12 +3027,12 @@ checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc"[[package]]name = "kittest"-version = "0.4.0"+version = "0.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "90ceaa75eb0036a32b6b9833962eb18137449e9817e2e586006471925b727fd5"+checksum = "0bb81a721ba76aa095b7f45deb180504f786904e56ca4b8e141f66eb89a78b75"dependencies = ["accesskit",- "accesskit_consumer 0.35.0",+ "accesskit_consumer",][[package]]@@ -4389,6 +4404,16 @@ dependencies = ["pin-project-lite",]+[[package]]+name = "os_pipe"+version = "1.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]+[[package]]name = "owned_ttf_parser"version = "0.25.1"@@ -4491,11 +4516,22 @@ version = "2.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"+[[package]]+name = "petgraph"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455"+dependencies = [+ "fixedbitset",+ "hashbrown 0.15.5",+ "indexmap",+]+[[package]]name = "phf"-version = "0.13.1"+version = "0.14.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"+checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6"dependencies = ["phf_macros","phf_shared",@@ -4504,9 +4540,9 @@ dependencies = [[[package]]name = "phf_generator"-version = "0.13.1"+version = "0.14.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"+checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100"dependencies = ["fastrand","phf_shared",@@ -4514,9 +4550,9 @@ dependencies = [[[package]]name = "phf_macros"-version = "0.13.1"+version = "0.14.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"+checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085"dependencies = ["phf_generator","phf_shared",@@ -4527,9 +4563,9 @@ dependencies = [[[package]]name = "phf_shared"-version = "0.13.1"+version = "0.14.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"+checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89"dependencies = ["siphasher",]@@ -5429,6 +5465,12 @@ version = "1.0.28"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"+[[package]]+name = "send_wrapper"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73"+[[package]]name = "seq-macro"version = "0.3.6"@@ -5964,6 +6006,17 @@ dependencies = ["once_cell",]+[[package]]+name = "tree_magic_mini"+version = "3.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6"+dependencies = [+ "memchr",+ "nom",+ "petgraph",+]+[[package]]name = "ttf-parser"version = "0.25.1"@@ -6043,6 +6096,12 @@ version = "0.1.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"+[[package]]+name = "unicode-bidi"+version = "0.3.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"+[[package]]name = "unicode-general-category"version = "1.1.0"@@ -6055,6 +6114,12 @@ version = "1.0.26"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"+[[package]]+name = "unicode-properties"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d"+[[package]]name = "unicode-segmentation"version = "1.13.3"@@ -6107,9 +6172,9 @@ dependencies = [[[package]]name = "vello_common"-version = "0.1.0"+version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b2e9aed918117e8152c9eddfd8362d73c465c23f26c44786aa331707b8a64fa2"+checksum = "bbb2141a2bca6e6d598e471fd4d1d7eed8e020aad6a28187edda07f091a325dd"dependencies = ["bytemuck","fearless_simd",@@ -6122,9 +6187,9 @@ dependencies = [[[package]]name = "vello_cpu"-version = "0.1.0"+version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ac7349e1f55f6b801c7c277958df4ea53e7f20f21e8014910ad888b2ecda93ea"+checksum = "ace506ca414548966fcf3c283be94eb1cad8254de488791ee698bf438b0890a9"dependencies = ["bytemuck","glifo",@@ -6868,8 +6933,7 @@ checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"[[package]]name = "winit"version = "0.30.13"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d"+source = "git+https://github.com/storytold/winit.git?rev=ae48c756a3b81125eb796c0cc6dccf60990d1181#ae48c756a3b81125eb796c0cc6dccf60990d1181"dependencies = ["ahash","android-activity",@@ -6941,6 +7005,24 @@ version = "0.57.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"+[[package]]+name = "wl-clipboard-rs"+version = "0.9.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4d7888ccd4896447b2d14d3a9350a85df2aeb6f181e2e7a31349d104ac46cac1"+dependencies = [+ "libc",+ "log",+ "os_pipe",+ "rustix 1.1.5",+ "thiserror 2.0.21",+ "tree_magic_mini",+ "wayland-backend",+ "wayland-client",+ "wayland-protocols",+ "wayland-protocols-wlr",+]+[[package]]name = "x11-dl"version = "2.21.0"@@ -7333,3 +7415,23 @@ dependencies = ["syn 3.0.6","winnow",]++[[patch.unused]]+name = "egui_demo_lib"+version = "0.37.0"+source = "git+https://github.com/storytold/egui.git?rev=173cc7375d35dc5fbc5b5d0994fdf787f547c5d1#173cc7375d35dc5fbc5b5d0994fdf787f547c5d1"++[[patch.unused]]+name = "egui_extras"+version = "0.37.0"+source = "git+https://github.com/storytold/egui.git?rev=173cc7375d35dc5fbc5b5d0994fdf787f547c5d1#173cc7375d35dc5fbc5b5d0994fdf787f547c5d1"++[[patch.unused]]+name = "egui_inspection"+version = "0.37.0"+source = "git+https://github.com/storytold/egui.git?rev=173cc7375d35dc5fbc5b5d0994fdf787f547c5d1#173cc7375d35dc5fbc5b5d0994fdf787f547c5d1"++[[patch.unused]]+name = "egui_system_font_provider"+version = "0.37.0"+source = "git+https://github.com/storytold/egui.git?rev=173cc7375d35dc5fbc5b5d0994fdf787f547c5d1#173cc7375d35dc5fbc5b5d0994fdf787f547c5d1"diff --git a/Cargo.toml b/Cargo.tomlindex 22956f31b..aca12d197 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -10,7 +10,7 @@ rust-version = "1.90"repository = "https://github.com/storytold/lightcraft"[workspace.dependencies]-craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "5c874d51eeb3de70e735c8ce87a59a7dedd47675", features = ["serde"] }+craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c488caa9fbc2fb1a86e4674887e9b80b598ebbfa", features = ["serde"] }craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "82a24b006eefa036b43c09a67fb9a3fbd17ffe63" }# internallightcraft-denoise-core = { path = "crates/denoise-core" }@@ -91,10 +91,13 @@ wgpu = { version = "30", default-features = false, features = ["std", "parking_lpollster = "1"# ui-egui = "0.36"-egui_extras = { version = "0.36", default-features = false }-eframe = { version = "0.36", default-features = false }-egui_kittest = "0.36"+# 0.37: `default_fonts` is no longer an egui default and the monochrome emoji faces moved behind+# `monochrome_emoji_fonts`. Every resolution root (native, CLI/headless, kittest, wasm) needs both:+# kittest's own dev-dependencies do not propagate to its consumers.+egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] }+egui_extras = { version = "0.37", default-features = false }+eframe = { version = "0.37", default-features = false }+egui_kittest = "0.37"rfd = "0.17"muda = { version = "0.21", default-features = false } # native menu bar (macOS: objc2/AppKit, pure Rust; no GTK)# macOS: the profile of the screen showing the window (safe AppKit bindings; muda and wgpu use the same)@@ -169,3 +172,21 @@ jpeg-decoder = { opt-level = 3 }jpeg-encoder = { opt-level = 3 }png = { opt-level = 3 }miniz_oxide = { opt-level = 3 }++# Keep the complete egui family and native event bridge on reviewed fork commits.+[patch.crates-io]+ecolor = { git = "https://github.com/storytold/egui.git", rev = "173cc7375d35dc5fbc5b5d0994fdf787f547c5d1" }+emath = { git = "https://github.com/storytold/egui.git", rev = "173cc7375d35dc5fbc5b5d0994fdf787f547c5d1" }+epaint = { git = "https://github.com/storytold/egui.git", rev = "173cc7375d35dc5fbc5b5d0994fdf787f547c5d1" }+epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "173cc7375d35dc5fbc5b5d0994fdf787f547c5d1" }+egui = { git = "https://github.com/storytold/egui.git", rev = "173cc7375d35dc5fbc5b5d0994fdf787f547c5d1" }+egui-winit = { git = "https://github.com/storytold/egui.git", rev = "173cc7375d35dc5fbc5b5d0994fdf787f547c5d1" }+egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "173cc7375d35dc5fbc5b5d0994fdf787f547c5d1" }+egui_glow = { git = "https://github.com/storytold/egui.git", rev = "173cc7375d35dc5fbc5b5d0994fdf787f547c5d1" }+egui_extras = { git = "https://github.com/storytold/egui.git", rev = "173cc7375d35dc5fbc5b5d0994fdf787f547c5d1" }+egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "173cc7375d35dc5fbc5b5d0994fdf787f547c5d1" }+egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "173cc7375d35dc5fbc5b5d0994fdf787f547c5d1" }+eframe = { git = "https://github.com/storytold/egui.git", rev = "173cc7375d35dc5fbc5b5d0994fdf787f547c5d1" }+egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "173cc7375d35dc5fbc5b5d0994fdf787f547c5d1" }+egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "173cc7375d35dc5fbc5b5d0994fdf787f547c5d1" }+winit = { git = "https://github.com/storytold/winit.git", rev = "ae48c756a3b81125eb796c0cc6dccf60990d1181" }diff --git a/apps/lightcraft-cli/src/main.rs b/apps/lightcraft-cli/src/main.rsindex a27e97beb..c1f9d258c 100644--- a/apps/lightcraft-cli/src/main.rs+++ b/apps/lightcraft-cli/src/main.rs@@ -819,6 +819,7 @@ fn snapshot(args: &[String]) -> Result<(), String> {let services = lightcraft_ui_egui::Services {write_shared: Some(std::sync::Arc::new(lightcraft_engine::export::write_file)),write: Some(Box::new(lightcraft_engine::export::write_file)),+ write_new: Some(Box::new(lightcraft_engine::export::write_file_new)),png: Some(Box::new(|img: &lightcraft_raster::Rgba8| {lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(img), &lightcraft_codecs::EncodeMeta::default()).unwrap_or_default()})),diff --git a/apps/lightcraft-web/src/bench.rs b/apps/lightcraft-web/src/bench.rsindex b1b976bfa..6b58c5106 100644--- a/apps/lightcraft-web/src/bench.rs+++ b/apps/lightcraft-web/src/bench.rs@@ -39,7 +39,7 @@ pub struct Bench {}impl Bench {- /// `start_ms`: the page's time origin in the same clock as [`lightcraft_ui_egui::now_ms`].+ /// `start_ms`: an origin on the same monotonic clock as [`lightcraft_ui_egui::monotonic_ms`].pub fn new(start_ms: f64) -> Self {Bench {phase: Phase::Idle,@@ -58,9 +58,10 @@ impl Bench {app.renderer.textures.get(&Slot::Main).map(|t| t.key)}- /// Call once per frame after `LightcraftApp::logic`. Returns the report when finished.+ /// Call once per root UI pass after `LightcraftApp::ui` (a UI-phase step, never a hidden tick).+ /// Returns the report when finished.pub fn step(&mut self, app: &mut LightcraftApp) -> Option<Value> {- let now = lightcraft_ui_egui::now_ms();+ let now = lightcraft_ui_egui::monotonic_ms();self.frames += 1;if self.first_frame_ms.is_none() && self.frames > 1 {self.first_frame_ms = Some(now - self.start_ms);diff --git a/apps/lightcraft-web/src/web.rs b/apps/lightcraft-web/src/web.rsindex 14a5d050b..4f8059c53 100644--- a/apps/lightcraft-web/src/web.rs+++ b/apps/lightcraft-web/src/web.rs@@ -225,6 +225,9 @@ fn services(originals: Originals, backend: Option<Backend>, files: Files, frozenpick_slideshow_templates: None,save_slideshow_template: None,write: Some(Box::new(download)),+ // the browser download path has no meaningful create-new file write; the control channel+ // (and therefore screenshot paths) is not available on the web+ write_new: None,// downloads happen on the main thread: exports run in the foreground on the webwrite_shared: None,png: Some(Box::new(|img: &lightcraft_raster::Rgba8| {@@ -267,7 +270,7 @@ async fn flush(files: Files, backend: Backend, dir: String, flushing: Rc<Cell<bolog::error!("saving {} failed: {e}", op.name());files.failed(&ops[i..]);files.set_error(Some(e));- failed_at.set(perf_now());+ failed_at.set(lightcraft_ui_egui::monotonic_ms());break 'outer;}}@@ -488,7 +491,7 @@ impl WebApp {}log::info!("lightcraft: {n} render workers");CTX.with(|c| *c.borrow_mut() = Some(cc.egui_ctx.clone()));- let origin = lightcraft_ui_egui::now_ms() - perf_now();+ let origin = lightcraft_ui_egui::monotonic_ms();WebApp {app,originals,@@ -506,13 +509,15 @@ impl WebApp {}}+ /// Consume the drops the raw-input hook queued once (never re-read `raw.dropped_files` in a+ /// hidden logic tick), and add originals whose bytes have arrived.fn import_dropped(&mut self, ctx: &egui::Context) {- let dropped = ctx.input(|i| i.raw.dropped_files.clone());+ let dropped = self.app.take_dropped_files();for f in dropped {let (originals, backend, ctx) = (self.originals.clone(), self.backend.clone(), ctx.clone());wasm_bindgen_futures::spawn_local(async move {- let name = f.path().to_string_lossy().to_string();- match f.bytes_async().await {+ let name = egui::DroppedFile::path(f.as_ref()).to_string_lossy().to_string();+ match egui::DroppedFile::bytes_async(f.as_ref()).await {Ok(bytes) => store_file(originals, backend, name, bytes, ctx).await,Err(e) => log::warn!("reading dropped {name}: {e}"),}@@ -563,7 +568,7 @@ impl WebApp {if self.frozen.get() {return;}- let now = perf_now();+ let now = lightcraft_ui_egui::monotonic_ms();if now - self.last_save >= SAVE_EVERY_MS {self.last_save = now;self.app.session.save_view();@@ -652,11 +657,10 @@ impl WebApp {impl eframe::App for WebApp {fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {for text in safety::take_notices() {- let now = ctx.input(|i| i.time);+ let now = self.app.tick_now();self.app.ui.toast = Some((text, now + NOTICE_SECS, None));}self.run_inbox();- self.import_dropped(ctx);self.load_originals(ctx);if let Some(w) = &self.workers {// `library.preferences ▸ cacheMb` is read by the session; the worker index prunes on@@ -665,19 +669,6 @@ impl eframe::App for WebApp {}self.app.logic(ctx);self.save();- if let Some(b) = self.bench.as_mut()- && let Some(report) = b.step(&mut self.app)- {- log::info!("lightcraft-bench {report}");- if let Some((alive, ready, remote, inline)) = self.workers.as_ref().map(Workers::stats) {- log::info!("lightcraft-workers {{\"alive\":{alive},\"ready\":{ready},\"remote_jobs\":{remote},\"inline_jobs\":{inline}}}");- }- set_status(&format!("bench: {report}"));- self.bench = None;- }- if self.bench.is_some() {- ctx.request_repaint();- }}fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) {@@ -685,7 +676,26 @@ impl eframe::App for WebApp {}fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {+ // Drops are the UI phase's: a hidden `logic`/`run_logic` tick must not import them twice.+ let ctx = ui.ctx().clone();+ self.import_dropped(&ctx);self.app.ui(ui);+ // The benchmark is a UI-phase step: a second layout pass or a hidden tick must not count a frame.+ if ui.ctx().current_pass_index() == 0 {+ if let Some(b) = self.bench.as_mut()+ && let Some(report) = b.step(&mut self.app)+ {+ log::info!("lightcraft-bench {report}");+ if let Some((alive, ready, remote, inline)) = self.workers.as_ref().map(Workers::stats) {+ log::info!("lightcraft-workers {{\"alive\":{alive},\"ready\":{ready},\"remote_jobs\":{remote},\"inline_jobs\":{inline}}}");+ }+ set_status(&format!("bench: {report}"));+ self.bench = None;+ }+ if self.bench.is_some() {+ ctx.request_repaint();+ }+ }if !self.first_frame_logged && !self.app.widgets.is_empty() {self.first_frame_logged = true;log::info!("lightcraft first UI frame at {:.0} ms after navigation start", perf_now());diff --git a/apps/lightcraft/Cargo.toml b/apps/lightcraft/Cargo.tomlindex 95e080974..f93bd2ccd 100644--- a/apps/lightcraft/Cargo.toml+++ b/apps/lightcraft/Cargo.toml@@ -23,7 +23,9 @@ lightcraft-sysmem = { workspace = true }lightcraft-ui-egui = { workspace = true }lightcraft-codecs = { workspace = true }lightcraft-raster = { workspace = true }-eframe = { workspace = true, features = ["default_fonts", "wgpu", "glow", "accesskit", "wayland", "x11"] }+# `clipboard` is a separate eframe feature in 0.37: without it egui-winit simulates an in-process+# clipboard and cut/copy/paste, RequestPaste and the Wayland PRIMARY path are unavailable.+eframe = { workspace = true, features = ["default_fonts", "clipboard", "wgpu", "glow", "accesskit", "wayland", "x11"] }egui = { workspace = true }serde_json = { workspace = true }chrono = { workspace = true }diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rsindex 95739b3e9..1fe570599 100644--- a/apps/lightcraft/src/main.rs+++ b/apps/lightcraft/src/main.rs@@ -405,12 +405,20 @@ impl PrefsWriter {fn tick(&mut self, app: &mut LightcraftApp, ctx: &egui::Context) {// (asked for before the input is read: the context is not asked from inside its own lock)let zoom = ctx.zoom_factor();- let (now, seen) = ctx.input(|i| (i.time, lightcraft_ui_egui::window_place::Seen::of(i.viewport(), i.content_rect(), zoom)));+ // The monotonic app clock: `i.time` stands still while the window is hidden.+ let now = app.tick_now();+ let (hidden, seen) = ctx.input(|i| {+ let hidden = i.viewport().visible() == Some(false);+ (hidden, lightcraft_ui_egui::window_place::Seen::of(i.viewport(), i.content_rect(), zoom))+ });// how the window is, to open like that next time (written with the settings below). What- // the settings hold is checked first: a script may have set it (`ui.set`)+ // the settings hold is checked first: a script may have set it (`ui.set`). A hidden+ // `run_logic` pass has no fresh content rect: keep the last known placement.let remembered = app.ui.window.and_then(lightcraft_ui_egui::window_place::WindowPlace::checked);let at = self.window_since.get_or_insert_with(std::time::Instant::now).elapsed().as_secs_f64();- app.ui.window = self.window.note(remembered, &seen, at);+ if !hidden {+ app.ui.window = self.window.note(remembered, &seen, at);+ }if let Some(wait) = self.window.waits(at) {// (a size is only remembered once the window has rested at it: look again then, though// nothing else asks for a frame)@@ -707,6 +715,7 @@ fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::path::Path>// atomic (temp file + sync + rename): a failed write never leaves a truncated filewrite_shared: Some(std::sync::Arc::new(lightcraft_engine::export::write_file)),write: Some(Box::new(lightcraft_engine::export::write_file)),+ write_new: Some(Box::new(lightcraft_engine::export::write_file_new)),png: Some(Box::new(|img: &lightcraft_raster::Rgba8| {lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(img), &lightcraft_codecs::EncodeMeta::default()).unwrap_or_default()})),diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rsindex 0e2254afd..2580aefd8 100644--- a/crates/engine/src/export.rs+++ b/crates/engine/src/export.rs@@ -2019,6 +2019,18 @@ pub fn write_file_durable(path: &str, bytes: &[u8]) -> Result<(), String> {write_with(path, bytes, true)}+/// Write `path` only when nothing exists there: the destination is prepared as a complete temp+/// file and published with create-new semantics, so a file that appears after a caller's check is+/// never replaced. Screenshots of an initially absent path use this instead of the overwriting+/// writer.+pub fn write_file_new(path: &str, bytes: &[u8]) -> Result<(), String> {+ let p = std::path::Path::new(path);+ if let Some(dir) = p.parent().filter(|d| !d.as_os_str().is_empty()) {+ std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;+ }+ lightcraft_catalog::safe_file::write_new(p, bytes).map_err(|e| format!("{path}: {e}"))+}+fn write_with(path: &str, bytes: &[u8], durable: bool) -> Result<(), String> {use lightcraft_catalog::safe_file::{write_atomic, write_atomic_nosync};let p = std::path::Path::new(path);diff --git a/crates/engine/src/originals.rs b/crates/engine/src/originals.rsindex b3a140a2b..890e98f81 100644--- a/crates/engine/src/originals.rs+++ b/crates/engine/src/originals.rs@@ -6,17 +6,102 @@use std::collections::HashMap;use std::path::{Path, PathBuf};+#[cfg(not(any(unix, windows)))]+use std::time::SystemTime;use lightcraft_catalog::safe_file::same_file;use lightcraft_catalog::{Catalog, Source};+/// The directory entry a screenshot is about to write, pinned at request admission.+///+/// A later write must not replace a path that was absent when the request was admitted (for+/// example a photo imported while the capture was waiting), nor a destination that was replaced by+/// another file in the meantime. [`Session::revalidate_write_target`] checks this immediately+/// before the write, and an absent destination is then published with create-new semantics.+#[derive(Clone, Debug)]+pub struct WriteTarget {+ path: String,+ state: WriteTargetState,+ /// The canonical parent folder at admission, when it existed: a retargeted parent symlink is a+ /// different destination even when the file name is unchanged.+ parent: Option<PathBuf>,+}++#[derive(Clone, Debug)]+enum WriteTargetState {+ /// The directory entry did not exist at admission.+ Absent,+ /// The directory entry existed; this is its identity (not its contents).+ Existing(FileIdentity),+}++/// Stable identity of a directory entry, from `symlink_metadata` (so replacing a symlink or a+/// hard link is a different entry). Unix uses device + inode; Windows uses the canonical path,+/// length and creation time; other platforms use a canonical/len/mtime fallback.+#[derive(Clone, Debug, PartialEq, Eq)]+struct FileIdentity {+ #[cfg(unix)]+ dev: u64,+ #[cfg(unix)]+ ino: u64,+ #[cfg(windows)]+ canonical: PathBuf,+ #[cfg(windows)]+ len: u64,+ #[cfg(windows)]+ created: u64,+ #[cfg(not(any(unix, windows)))]+ canonical: PathBuf,+ #[cfg(not(any(unix, windows)))]+ len: u64,+ #[cfg(not(any(unix, windows)))]+ modified: Option<SystemTime>,+}++impl FileIdentity {+ fn of(path: &Path, meta: &std::fs::Metadata) -> Self {+ #[cfg(unix)]+ {+ use std::os::unix::fs::MetadataExt;+ let _ = path;+ Self { dev: meta.dev(), ino: meta.ino() }+ }+ #[cfg(windows)]+ {+ // The volume serial/file index metadata is still unstable; use stable metadata that+ // changes when a different file replaces the entry, and keep the same in-place+ // content edits (which do not change the creation time or length) overwritable.+ use std::os::windows::fs::MetadataExt;+ Self { canonical: std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()), len: meta.len(), created: meta.creation_time() }+ }+ #[cfg(not(any(unix, windows)))]+ {+ Self { canonical: std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()), len: meta.len(), modified: meta.modified().ok() }+ }+ }+}++impl WriteTarget {+ /// The destination path as the request named it.+ pub fn path(&self) -> &str {+ &self.path+ }++ /// Was the directory entry absent at admission? Such a destination is published with+ /// create-new semantics, never with the overwriting writer.+ pub fn was_absent(&self) -> bool {+ matches!(&self.state, WriteTargetState::Absent)+ }+}+/// The library's originals and their sidecars, looked up by file name.#[derive(Debug, Default)]pub struct OriginalGuard {/// lower-case file name → (path on disk, what it is: "the original of IMG_1.CR3", …)by_name: HashMap<String, Vec<(PathBuf, String)>>,- /// The entries of `by_name` that are symlinks, found on the first check that needs them.- links: std::sync::OnceLock<Vec<(PathBuf, String)>>,+ /// Every indexed entry, built on the first check whose target name did not match: a hard+ /// link or symlink may name an original differently from the catalogued path.+ others: std::sync::OnceLock<Vec<(PathBuf, String)>>,}impl OriginalGuard {@@ -34,7 +119,7 @@ impl OriginalGuard {/// Protect `path` (an original named `label`) and its sidecars (`IMG_1.xmp`, `IMG_1.CR3.xmp`).pub fn add(&mut self, path: &Path, label: &str) {let Some(name) = path.file_name().map(|n| n.to_string_lossy().to_string()) else { return };- self.links = std::sync::OnceLock::new();+ self.others = std::sync::OnceLock::new();let mut put = |file: String, p: PathBuf, what: String| self.by_name.entry(file.to_lowercase()).or_default().push((p, what));put(name.clone(), path.to_path_buf(), format!("the original of {label}"));let stem = path.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();@@ -44,6 +129,17 @@ impl OriginalGuard {/// `Err` (a message for the user) when writing `target` would replace a protected file.pub fn check(&self, target: &Path) -> Result<(), String> {+ self.check_target(target, false)+ }++ /// [`Self::check`] plus hard links: a screenshot target must not replace an original reached+ /// through a link with a different name. The per-entry identity scan is limited to this+ /// long-lived, user-visible destination check, not every ordinary export overwrite.+ pub fn check_identity(&self, target: &Path) -> Result<(), String> {+ self.check_target(target, true)+ }++ fn check_target(&self, target: &Path, hard_links: bool) -> Result<(), String> {if std::fs::symlink_metadata(target).is_err() {return Ok(()); // nothing there to replace}@@ -61,12 +157,15 @@ impl OriginalGuard {}}}- // An imported symlink can have a different name from its original. A write to- // that original would change what the library reads through the link. Only do- // this fallback for existing targets that the name index did not protect; the links are- // looked up once per guard, not once per target.- let links = self.links.get_or_init(|| self.by_name.values().flatten().filter(|(p, _)| std::fs::read_link(p).is_ok()).cloned().collect());- for (p, what) in links {+ // An imported hard link or symlink can have a different name from its original. A write+ // to that entry would change what the library reads. Only do this fallback for existing+ // targets that the name index did not protect; the list is built once per guard, not once+ // per target. Ordinary exports keep the cheaper symlink-only scan.+ let others = self.others.get_or_init(|| self.by_name.values().flatten().cloned().collect());+ for (p, what) in others {+ if !hard_links && std::fs::read_link(p).is_err() {+ continue;+ }if same_file(p, target) {return Err(format!("{} is {what} in the library: LightCraft never writes over an original (choose another folder or file name)",@@ -93,6 +192,69 @@ impl crate::Session {}self.original_guard().check(path)}++ /// Pin the destination of a long-running write (a screenshot) now.+ ///+ /// The returned [`WriteTarget`] records whether the directory entry existed and, if so, its+ /// identity, plus the canonical parent folder. Pass it to [`Self::revalidate_write_target`]+ /// immediately before writing.+ pub fn pin_write_target(&self, path: &str) -> Result<WriteTarget, String> {+ let p = Path::new(path);+ let parent = p.parent().filter(|d| !d.as_os_str().is_empty()).and_then(|d| std::fs::canonicalize(d).ok());+ match std::fs::symlink_metadata(p) {+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ Ok(WriteTarget { path: path.to_string(), state: WriteTargetState::Absent, parent })+ }+ Err(error) => Err(format!("{path}: {error}")),+ Ok(meta) => {+ // Refuse a catalogued original or sidecar (including a differently named hard+ // link) before the request is queued.+ self.original_guard().check_identity(p)?;+ Ok(WriteTarget { path: path.to_string(), state: WriteTargetState::Existing(FileIdentity::of(p, &meta)), parent })+ }+ }+ }++ /// Re-check a pinned target immediately before writing.+ ///+ /// An absent target must still be absent; an existing target must still name the same+ /// directory entry and must still pass the current catalog's original guard. A parent folder+ /// whose canonical path changed (a retargeted symlink) is refused too.+ pub fn revalidate_write_target(&self, target: &WriteTarget) -> Result<(), String> {+ if let Some(parent) = &target.parent {+ // Resolve the request's parent again: canonicalizing the saved resolved folder+ // would miss a directory symlink in the original path being retargeted.+ let now = Path::new(&target.path).parent().and_then(|path| std::fs::canonicalize(path).ok());+ match now {+ Some(now) if now == *parent => {}+ _ => {+ return Err(format!(+ "{}: the destination folder changed while the screenshot was being captured; refusing to write",+ target.path+ ));+ }+ }+ }+ match std::fs::symlink_metadata(&target.path) {+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => match &target.state {+ WriteTargetState::Absent => Ok(()),+ WriteTargetState::Existing(_) => {+ Err(format!("{}: the file was removed while the screenshot was being captured; refusing to create it again", target.path))+ }+ },+ Err(error) => Err(format!("{}: {error}", target.path)),+ Ok(meta) => match &target.state {+ WriteTargetState::Absent => Err(format!("{} appeared while the screenshot was being captured; refusing to replace it", target.path)),+ WriteTargetState::Existing(identity) => {+ if FileIdentity::of(Path::new(&target.path), &meta) != *identity {+ return Err(format!("{} changed while the screenshot was being captured; refusing to replace the new file", target.path));+ }+ // The catalog may have gained this file as an original since admission.+ self.original_guard().check_identity(Path::new(&target.path))+ }+ },+ }+ }}#[cfg(test)]@@ -120,4 +282,61 @@ mod tests {assert!(g.check(&d.join("new.jpg")).is_ok(), "a free name");let _ = std::fs::remove_dir_all(&d);}++ #[test]+ fn write_targets_pin_absent_paths_and_recheck_the_current_library() {+ let d = std::env::temp_dir().join(format!("lc-write-targets-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&d);+ std::fs::create_dir_all(&d).unwrap();+ let mut s = crate::Session::new();+ let original = d.join("IMG_1.jpg");+ std::fs::write(&original, b"original").unwrap();+ let photo = Photo::new(PhotoId(1), Source::File { path: original.to_string_lossy().to_string() }, "IMG_1.jpg", "JPEG", 10, 10, "2026-01-01");+ s.catalog.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap();++ // A path that was absent at admission is refused when anything appears there.+ let free = d.join("new-shot.png");+ let absent = s.pin_write_target(&free.to_string_lossy()).expect("free path");+ assert!(absent.was_absent());+ std::fs::write(&free, b"appeared").unwrap();+ assert!(s.revalidate_write_target(&absent).unwrap_err().contains("appeared"));+ std::fs::remove_file(&free).unwrap();++ // An ordinary existing path can still be overwritten in place (same entry).+ let allowed = d.join("old-shot.png");+ std::fs::write(&allowed, b"old").unwrap();+ let existing = s.pin_write_target(&allowed.to_string_lossy()).expect("ordinary file");+ assert!(!existing.was_absent());+ std::fs::write(&allowed, b"new").unwrap();+ assert!(s.revalidate_write_target(&existing).is_ok(), "an allowed screenshot refresh keeps working");++ // A hard link to an original is refused at admission, and an absent path that becomes+ // such a link is refused at write time.+ let linked = d.join("linked.png");+ std::fs::hard_link(&original, &linked).unwrap();+ assert!(s.pin_write_target(&linked.to_string_lossy()).unwrap_err().contains("original"));+ std::fs::remove_file(&linked).unwrap();+ let appears_as_link = d.join("late-link.png");+ let late = s.pin_write_target(&appears_as_link.to_string_lossy()).expect("free path");+ std::fs::hard_link(&original, &appears_as_link).unwrap();+ assert!(s.revalidate_write_target(&late).unwrap_err().contains("appeared"));++ // A path pinned as an ordinary file becomes an original through a catalog import while+ // the capture is queued: the current guard refuses the write.+ let imported = d.join("imported.png");+ std::fs::write(&imported, b"not yet imported").unwrap();+ let queued = s.pin_write_target(&imported.to_string_lossy()).expect("ordinary file");+ let p = Photo::new(PhotoId(2), Source::File { path: imported.to_string_lossy().to_string() }, "imported.png", "PNG", 10, 10, "2026-01-01");+ s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();+ assert!(s.revalidate_write_target(&queued).unwrap_err().contains("original"));++ #[cfg(unix)]+ {+ use std::os::unix::fs::symlink;+ let link = d.join("link-shot.png");+ symlink(&original, &link).unwrap();+ assert!(s.pin_write_target(&link.to_string_lossy()).unwrap_err().contains("original"));+ }+ let _ = std::fs::remove_dir_all(&d);+ }}diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rsindex 76d48872d..be2ba8d44 100644--- a/crates/raster/src/lib.rs+++ b/crates/raster/src/lib.rs@@ -268,6 +268,27 @@ impl Rgba8 {}Some(Self { width, height, data: bytes.as_chunks::<4>().0.iter().map(|c| [c[0], c[1], c[2], c[3]]).collect() })}++ /// Build an image from exactly `width * height` RGBA pixels.+ ///+ /// This copies each pixel once, straight into the image's own buffer, so a caller that already+ /// holds a pixel array (an egui `ColorImage`, say) does not need a second full byte vector.+ /// `None` for a zero or overflowing size, or a pixel count that is not exactly `width * height`.+ pub fn from_pixels(width: usize, height: usize, pixels: impl IntoIterator<Item = [u8; 4]>) -> Option<Self> {+ if width == 0 || height == 0 {+ return None;+ }+ let expected = width.checked_mul(height)?;+ let mut data = Vec::new();+ data.try_reserve_exact(expected).ok()?;+ for (i, pixel) in pixels.into_iter().enumerate() {+ if i == expected {+ return None;+ }+ data.push(pixel);+ }+ (data.len() == expected).then_some(Self { width, height, data })+ }/// Linear Rec.709/sRGB primaries float image from 8-bit sRGB.pub fn to_linear(&self) -> Rgb32f {use lightcraft_color::transfer::decode_srgb8;@@ -356,4 +377,15 @@ mod tests {assert_eq!(img.to_linear().to_srgb8(), img);assert_eq!(Rgba8::from_bytes(16, 16, &img.as_bytes()).unwrap(), img);}++ #[test]+ fn from_pixels_requires_exactly_the_stated_pixels() {+ let img = Rgba8::from_fn(4, 3, |x, y| [x as u8, y as u8, 9, 255]);+ let rebuilt = Rgba8::from_pixels(4, 3, img.as_bytes().as_chunks::<4>().0.iter().map(|p| [p[0], p[1], p[2], p[3]])).unwrap();+ assert_eq!(rebuilt, img);+ assert!(Rgba8::from_pixels(4, 3, vec![[0, 0, 0, 0]; 11]).is_none(), "too few pixels");+ assert!(Rgba8::from_pixels(4, 3, vec![[0, 0, 0, 0]; 13]).is_none(), "too many pixels");+ assert!(Rgba8::from_pixels(0, 3, std::iter::empty()).is_none());+ assert!(Rgba8::from_pixels(usize::MAX, 2, std::iter::empty()).is_none());+ }}diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.tomlindex 1ae33a03d..d9b417a36 100644--- a/crates/ui-egui/Cargo.toml+++ b/crates/ui-egui/Cargo.toml@@ -30,6 +30,11 @@ log = { workspace = true }[dev-dependencies]# tests record why they skip (`cargo xtask ci` lists the skips)lightcraft-testkit = { workspace = true }+# The model-setup tests install and resume a real denoise model. Without this the engine's+# `default_loader` is the "this build cannot run denoise models" stub when the package is tested+# on its own (`cargo test -p lightcraft-ui-egui`); a workspace test only passed by feature+# unification with the desktop app's default `denoise` feature.+lightcraft-engine = { workspace = true, features = ["denoise"] }egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] }lightcraft-denoise = { workspace = true, features = ["runtime"] }lightcraft-codecs = { workspace = true }diff --git a/crates/ui-egui/examples/thumb_request_bench.rs b/crates/ui-egui/examples/thumb_request_bench.rsindex 675c920d5..166c0e9b6 100644--- a/crates/ui-egui/examples/thumb_request_bench.rs+++ b/crates/ui-egui/examples/thumb_request_bench.rs@@ -283,6 +283,7 @@ fn real() {unit: egui::MouseWheelUnit::Point,delta: egui::vec2(0.0, if (i / 45) % 2 == 0 { -12.0 } else { 12.0 }),phase: egui::TouchPhase::Move,+ source: egui::MouseWheelSource::Unknown,modifiers: Default::default(),});let t = Instant::now();diff --git a/crates/ui-egui/src/album_picker.rs b/crates/ui-egui/src/album_picker.rsindex 835dbcce8..44c534743 100644--- a/crates/ui-egui/src/album_picker.rs+++ b/crates/ui-egui/src/album_picker.rs@@ -212,7 +212,7 @@ impl<'a> AlbumPicker<'a> {let arrow_color = crate::theme::Tokens::get(ui.ctx()).icon;disclosure(ui.painter(), egui::pos2(button.rect.right() - 10.0, button.rect.center().y), true, arrow_color);register(ui.ctx(), format!("albumPicker:{id}"), button.rect);- let key = egui::Id::new(("albumPicker", id.as_str()));+ let key = egui::Id::unique(("albumPicker", id.as_str()));if button.clicked() {// open on the chosen album's folders, with the search empty and ready for typinglet open = chosen.map(|c| ancestors(entries, c)).unwrap_or_default();@@ -292,7 +292,7 @@ impl<'a> AlbumPicker<'a> {register(ui.ctx(), format!("albumPickerFolder:{}:{id}", e.id), r.rect);// what assistive tools announce: the folder, and whether it is openlet name = e.name.clone();- r.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::CollapsingHeader, true, open, &name));+ crate::widgets::announce_disclosure(&r, true, open, &name);if r.clicked() {// the click took the keyboard from the search box: give it backstate.focus = true;diff --git a/crates/ui-egui/src/button.rs b/crates/ui-egui/src/button.rsindex f46156ed9..5ada0b038 100644--- a/crates/ui-egui/src/button.rs+++ b/crates/ui-egui/src/button.rs@@ -322,7 +322,7 @@ impl<'a> Button<'a> {// stable across frames and moves: its widget id (with its salt) when it has one, else its// place in the ui (moved on, so the next button in the same ui gets another)let id = match &self.widget {- Some(w) => ui.id().with(("lc-button", w.as_str(), self.id_salt)),+ Some(w) => ui.scope_id().with(("lc-button", w.as_str(), self.id_salt)),None => {let id = ui.auto_id_with(("lc-button", self.text.or(self.name), self.id_salt));ui.skip_ahead_auto_ids(1);@@ -333,7 +333,7 @@ impl<'a> Button<'a> {let enabled = self.enabled && ui.is_enabled();let resp = ui.interact(rect, id, if enabled { Sense::click() } else { Sense::hover() });let words = crate::i18n::tr(self.name.or(self.text).unwrap_or_default()).to_string();- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, enabled, words.clone()));+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, words.clone()));if let Some(w) = &self.widget {crate::widgets::register(ui.ctx(), w.clone(), rect);}diff --git a/crates/ui-egui/src/canvas_keys.rs b/crates/ui-egui/src/canvas_keys.rsindex dadbb1577..1a4857372 100644--- a/crates/ui-egui/src/canvas_keys.rs+++ b/crates/ui-egui/src/canvas_keys.rs@@ -12,12 +12,12 @@ pub const STEP: f64 = 0.005;pub const BIG_STEP: f64 = 0.05;fn focused_key() -> Id {- Id::new("lc-canvas-handle-focused")+ Id::unique("lc-canvas-handle-focused")}/// The egui id of the stand-in registered as `key` (to focus it, or find it in tests).pub fn id(key: &str) -> Id {- Id::new("lc-canvas-handle").with(key)+ Id::unique("lc-canvas-handle").with(key)}/// Whether a canvas handle holds the keyboard focus: it keeps the arrow keys and Return from the@@ -49,7 +49,7 @@ pub fn handle(ui: &mut Ui, key: &str, name: &str, value: String, at: Pos2) -> Halet rect = Rect::from_center_size(at, vec2(14.0, 14.0));let resp = ui.interact(rect, id, egui::Sense::focusable_noninteractive());let label = name.to_string();- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label.clone()));+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label.clone()));ui.ctx().accesskit_node_builder(id, |node| {node.set_value(value);});diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rsindex efb3ea3ac..f52589a7d 100644--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@ -10,7 +10,7 @@//! - `ui.move/click/drag {x, y, …}`: raw pointer input in screen points//! - `ui.pointer {events: [{kind: down|drag|up, x, y}], space: "image"}`: gestures in normalized//! image coordinates (brush strokes, crop handles…) — mapped to screen and injected as real input-//! - `ui.key {key, shift?, alt?, cmd?}` / `ui.text {text}` / `ui.scroll {dx, dy}`+//! - `ui.key {key, shift?, alt?, cmd?}` / `ui.text {text}` / `ui.scroll {dx, dy, source?, unit?, phase?}`//! - `ui.set {view?, panel?, filmstrip?, leftPanel?, zoom?, …}` / `ui.dialog.confirm|cancel`//! - `ui.screenshot {path?, headless?}` (headless: CPU-rendered, no compositor needed), `ui.resize {width, height}`, `ui.render {id?, size?, path?}`, `app.quit`@@ -59,7 +59,17 @@ impl ControlRequest {pub enum Outcome {Done(Value),- Screenshot { path: Option<String>, headless: bool },+ /// A capture was admitted: `target` pins the destination identity until the write.+ Screenshot {+ target: Option<lightcraft_engine::originals::WriteTarget>,+ headless: bool,+ },+ /// A synthetic-input request that must wait for a fresh layout and for its last event to be+ /// consumed before it is answered (see `LightcraftApp::admit_gesture`).+ Gesture {+ method: String,+ params: Value,+ },}fn ok(v: Value) -> Outcome {@@ -217,128 +227,13 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequestapp.widgets.iter().filter(|(id, _)| id.contains(filter)).map(|(id, r)| json!({"id": id, "rect": rect_json(*r)})).collect(),))}- "ui.clickWidget" | "ui.dragWidget" | "ui.hoverWidget" => {- let Some(id) = s("id") else { return err("missing `id`") };- let Some(r) = widget_rect(app, id) else { return err(format!("no widget `{id}` on screen (see ui.widgets)")) };- let m = modifiers(p);- // optional relative position inside the widget (0..1)- let at = egui::pos2(r.left() + r.width() * f("fx").unwrap_or(0.5) as f32, r.top() + r.height() * f("fy").unwrap_or(0.5) as f32);- if req.method == "ui.hoverWidget" {- app.synthetic.push(egui::Event::PointerMoved(at));- } else if req.method == "ui.clickWidget" {- let n = p.get("count").and_then(Value::as_u64).unwrap_or(1);- let button = if s("button") == Some("right") { egui::PointerButton::Secondary } else { egui::PointerButton::Primary };- app.synthetic.push(egui::Event::PointerMoved(at));- for _ in 0..n {- app.synthetic.push(egui::Event::PointerButton { pos: at, button, pressed: true, modifiers: m });- app.synthetic.push(egui::Event::PointerButton { pos: at, button, pressed: false, modifiers: m });- }- } else {- let to = egui::pos2(- f("toX").map(|v| v as f32).unwrap_or(at.x + f("dx").unwrap_or(0.0) as f32),- f("toY").map(|v| v as f32).unwrap_or(at.y + f("dy").unwrap_or(0.0) as f32),- );- push_drag(app, at, to, p.get("steps").and_then(Value::as_u64).unwrap_or(10), m);- }- ctx.request_repaint();- ok(json!({"rect": rect_json(r)}))- }- "ui.move" => {- app.synthetic.push(egui::Event::PointerMoved(egui::pos2(f("x").unwrap_or(0.0) as f32, f("y").unwrap_or(0.0) as f32)));- ctx.request_repaint();- ok(Value::Null)- }- "ui.click" | "ui.drag" => {- let a = egui::pos2(f("x").unwrap_or(0.0) as f32, f("y").unwrap_or(0.0) as f32);- let m = modifiers(p);- let button = if s("button") == Some("right") { egui::PointerButton::Secondary } else { egui::PointerButton::Primary };- if req.method == "ui.drag" {- let b = egui::pos2(f("toX").unwrap_or(0.0) as f32, f("toY").unwrap_or(0.0) as f32);- push_drag(app, a, b, p.get("steps").and_then(Value::as_u64).unwrap_or(10), m);- } else {- app.synthetic.push(egui::Event::PointerMoved(a));- for _ in 0..p.get("count").and_then(Value::as_u64).unwrap_or(1) {- app.synthetic.push(egui::Event::PointerButton { pos: a, button, pressed: true, modifiers: m });- app.synthetic.push(egui::Event::PointerButton { pos: a, button, pressed: false, modifiers: m });- }- }- ctx.request_repaint();- ok(Value::Null)- }- "ui.pointer" => {- // events in normalized image coordinates of the displayed photo frame- let Some(img) = app.image_rect else { return err("no image on screen (switch to Detail view)") };- let Some(events) = p.get("events").and_then(Value::as_array) else { return err("missing `events`") };- let m = modifiers(p);- for e in events {- let x = e.get("x").and_then(Value::as_f64).unwrap_or(0.5) as f32;- let y = e.get("y").and_then(Value::as_f64).unwrap_or(0.5) as f32;- let pos = egui::pos2(img.left() + x * img.width(), img.top() + y * img.height());- match e.get("kind").and_then(Value::as_str).unwrap_or("move") {- "down" => {- app.synthetic.push(egui::Event::PointerMoved(pos));- app.synthetic.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: m });- }- "up" => {- app.synthetic.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: m })- }- _ => app.synthetic.push(egui::Event::PointerMoved(pos)),- }- }- ctx.request_repaint();- ok(json!({"events": events.len()}))- }- "ui.key" => {- let Some(k) = s("key").and_then(key_from) else { return err("unknown or missing `key`") };- let m = modifiers(p);- app.synthetic.push(egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: m });- app.synthetic.push(egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers: m });- ctx.request_repaint();- ok(Value::Null)- }- "ui.text" => {- app.synthetic.push(egui::Event::Text(s("text").unwrap_or("").to_string()));- ctx.request_repaint();- ok(Value::Null)- }- // what the system does for ⌘X / ⌘C / ⌘V in a text field: paste `text`, or (without it)- // what the system clipboard holds- "ui.clipboard" => {- // outside a text field ⌘C / ⌘V are the app's shortcuts (and the macOS menu bar's):- // agents run those as commands (`develop.copy`, `develop.paste`)- if !ctx.text_edit_focused() {- return err("ui.clipboard: no text field has the focus (click one first)");- }- match s("action") {- Some("cut") => app.synthetic.push(egui::Event::Cut),- Some("copy") => app.synthetic.push(egui::Event::Copy),- Some("paste") => match s("text") {- Some(text) => app.synthetic.push(egui::Event::Paste(text.to_string())),- None => ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaste),- },- _ => return err("ui.clipboard: `action` is cut, copy or paste"),- }- ctx.request_repaint();- ok(Value::Null)- }- "ui.scroll" => {- app.synthetic.push(egui::Event::MouseWheel {- unit: egui::MouseWheelUnit::Point,- delta: egui::vec2(f("dx").unwrap_or(0.0) as f32, f("dy").unwrap_or(0.0) as f32),- phase: egui::TouchPhase::Move,- modifiers: modifiers(p),- });- ctx.request_repaint();- ok(Value::Null)- }- "ui.zoom" => {- let Some(factor) = f("factor").map(|v| v as f32).filter(|v| v.is_finite() && *v > 0.0) else {- return err("ui.zoom: factor must be a finite positive number (1 = unchanged)");- };- app.synthetic.push(egui::Event::Zoom(factor));- ctx.request_repaint();- ok(Value::Null)+ "ui.clickWidget" | "ui.dragWidget" | "ui.hoverWidget" | "ui.move" | "ui.click" | "ui.drag" | "ui.pointer" | "ui.key" | "ui.text"+ | "ui.clipboard" | "ui.scroll" => {+ // Geometry and input events are resolved only after a fresh completed layout; the+ // reply waits until the UI has consumed the last event (plan §4.5).+ Outcome::Gesture { method: req.method.clone(), params: req.params.clone() }}+ "ui.zoom" => Outcome::Gesture { method: req.method.clone(), params: req.params.clone() },"ui.set" => {// an arrangement of the sidebar is checked, not made whole as a settings file's islet sidebar = match p.get("sidebar").map(crate::sidebar::SidebarLayout::parse).transpose() {@@ -430,12 +325,18 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest_ => err("ui.zoomFactor: factor must be a number from 0.5 to 3"),},"ui.screenshot" => {- // never over a photo's original- if let Some(Err(e)) = s("path").map(|path| app.session.check_write_target(path)) {- return err(e);- }+ // Never over a photo's original, and pin the destination identity now: the write+ // revalidates it after the (possibly lengthy) capture and never replaces a path that+ // was absent at admission but appeared meanwhile.+ let target = match s("path") {+ Some(path) => match app.session.pin_write_target(path) {+ Ok(t) => Some(t),+ Err(e) => return err(e),+ },+ None => None,+ };ctx.request_repaint();- Outcome::Screenshot { path: s("path").map(str::to_string), headless: p.get("headless").and_then(Value::as_bool).unwrap_or(false) }+ Outcome::Screenshot { target, headless: p.get("headless").and_then(Value::as_bool).unwrap_or(false) }}"ui.render" => {let id = match p.get("id").filter(|v| !v.is_null()) {@@ -562,22 +463,195 @@ pub fn export_active(app: &mut LightcraftApp, p: &Value) -> Result<Value, StringOk(out)}-pub fn save_screenshot(app: &mut LightcraftApp, image: &egui::ColorImage, path: Option<&str>) -> Value {+/// Resolve one queued synthetic-input control request against the **current** layout.+///+/// Called by the app only after a completed UI pass newer than admission (plan §4.5). Widget rects+/// and the image rect therefore come from that pass; nothing is retargeted. A successful return+/// has pushed the events onto `app.synthetic`; the app answers the request once the UI consumed+/// them.+pub(crate) fn gesture_events(app: &mut LightcraftApp, ctx: &egui::Context, method: &str, p: &Value) -> Result<Value, String> {+ let s = |k: &str| p.get(k).and_then(Value::as_str);+ let f = |k: &str| p.get(k).and_then(Value::as_f64);+ match method {+ "ui.clickWidget" | "ui.dragWidget" | "ui.hoverWidget" => {+ let Some(id) = s("id") else { return Err("missing `id`".into()) };+ let Some(r) = widget_rect(app, id) else { return Err(format!("no widget `{id}` on screen (see ui.widgets)")) };+ let m = modifiers(p);+ let at = egui::pos2(r.left() + r.width() * f("fx").unwrap_or(0.5) as f32, r.top() + r.height() * f("fy").unwrap_or(0.5) as f32);+ if method == "ui.hoverWidget" {+ app.synthetic.push(egui::Event::PointerMoved(at));+ } else if method == "ui.clickWidget" {+ let n = p.get("count").and_then(Value::as_u64).unwrap_or(1);+ let button = if s("button") == Some("right") { egui::PointerButton::Secondary } else { egui::PointerButton::Primary };+ app.synthetic.push(egui::Event::PointerMoved(at));+ for _ in 0..n {+ app.synthetic.push(egui::Event::PointerButton { pos: at, button, pressed: true, modifiers: m });+ app.synthetic.push(egui::Event::PointerButton { pos: at, button, pressed: false, modifiers: m });+ }+ } else {+ let to = egui::pos2(+ f("toX").map(|v| v as f32).unwrap_or(at.x + f("dx").unwrap_or(0.0) as f32),+ f("toY").map(|v| v as f32).unwrap_or(at.y + f("dy").unwrap_or(0.0) as f32),+ );+ push_drag(app, at, to, p.get("steps").and_then(Value::as_u64).unwrap_or(10), m);+ }+ ctx.request_repaint();+ Ok(json!({"rect": rect_json(r)}))+ }+ "ui.move" => {+ app.synthetic.push(egui::Event::PointerMoved(egui::pos2(f("x").unwrap_or(0.0) as f32, f("y").unwrap_or(0.0) as f32)));+ ctx.request_repaint();+ Ok(Value::Null)+ }+ "ui.click" | "ui.drag" => {+ let a = egui::pos2(f("x").unwrap_or(0.0) as f32, f("y").unwrap_or(0.0) as f32);+ let m = modifiers(p);+ let button = if s("button") == Some("right") { egui::PointerButton::Secondary } else { egui::PointerButton::Primary };+ if method == "ui.drag" {+ let b = egui::pos2(f("toX").unwrap_or(0.0) as f32, f("toY").unwrap_or(0.0) as f32);+ push_drag(app, a, b, p.get("steps").and_then(Value::as_u64).unwrap_or(10), m);+ } else {+ app.synthetic.push(egui::Event::PointerMoved(a));+ for _ in 0..p.get("count").and_then(Value::as_u64).unwrap_or(1) {+ app.synthetic.push(egui::Event::PointerButton { pos: a, button, pressed: true, modifiers: m });+ app.synthetic.push(egui::Event::PointerButton { pos: a, button, pressed: false, modifiers: m });+ }+ }+ ctx.request_repaint();+ Ok(Value::Null)+ }+ "ui.pointer" => {+ let Some(img) = app.image_rect else { return Err("no image on screen (switch to Detail view)".into()) };+ let Some(events) = p.get("events").and_then(Value::as_array) else { return Err("missing `events`".into()) };+ let m = modifiers(p);+ for e in events {+ let x = e.get("x").and_then(Value::as_f64).unwrap_or(0.5) as f32;+ let y = e.get("y").and_then(Value::as_f64).unwrap_or(0.5) as f32;+ let pos = egui::pos2(img.left() + x * img.width(), img.top() + y * img.height());+ match e.get("kind").and_then(Value::as_str).unwrap_or("move") {+ "down" => {+ app.synthetic.push(egui::Event::PointerMoved(pos));+ app.synthetic.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: m });+ }+ "up" => {+ app.synthetic.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: m })+ }+ _ => app.synthetic.push(egui::Event::PointerMoved(pos)),+ }+ }+ ctx.request_repaint();+ Ok(json!({"events": events.len()}))+ }+ "ui.key" => {+ let Some(k) = s("key").and_then(key_from) else { return Err("unknown or missing `key`".into()) };+ let m = modifiers(p);+ app.synthetic.push(egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: m });+ app.synthetic.push(egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers: m });+ ctx.request_repaint();+ Ok(Value::Null)+ }+ "ui.text" => {+ app.synthetic.push(egui::Event::Text(s("text").unwrap_or("").to_string()));+ ctx.request_repaint();+ Ok(Value::Null)+ }+ "ui.clipboard" => {+ if !ctx.text_edit_focused() {+ return Err("ui.clipboard: no text field has the focus (click one first)".into());+ }+ match s("action") {+ Some("cut") => app.synthetic.push(egui::Event::Cut),+ Some("copy") => app.synthetic.push(egui::Event::Copy),+ Some("paste") => match s("text") {+ Some(text) => app.synthetic.push(egui::Event::Paste(text.to_string())),+ None => ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaste),+ },+ _ => return Err("ui.clipboard: `action` is cut, copy or paste".into()),+ }+ ctx.request_repaint();+ Ok(Value::Null)+ }+ "ui.scroll" => {+ // Omitted keys keep the pre-0.37 request meaning; all other values are validated+ // before anything is queued.+ let source = match s("source") {+ None | Some("unknown") => egui::MouseWheelSource::Unknown,+ Some("wheel") => egui::MouseWheelSource::Wheel,+ Some("trackpad") => egui::MouseWheelSource::Trackpad,+ Some("momentum") => egui::MouseWheelSource::Momentum,+ Some(other) => return Err(format!("ui.scroll: `source` is wheel, trackpad, momentum or unknown, not {other:?}")),+ };+ let unit = match s("unit") {+ None | Some("point") => egui::MouseWheelUnit::Point,+ Some("line") => egui::MouseWheelUnit::Line,+ Some("page") => egui::MouseWheelUnit::Page,+ Some(other) => return Err(format!("ui.scroll: `unit` is point, line or page, not {other:?}")),+ };+ let phase = match s("phase") {+ None | Some("move") => egui::TouchPhase::Move,+ Some("start") => egui::TouchPhase::Start,+ Some("end") => egui::TouchPhase::End,+ Some("cancel") => egui::TouchPhase::Cancel,+ Some(other) => return Err(format!("ui.scroll: `phase` is start, move, end or cancel, not {other:?}")),+ };+ app.synthetic.push(egui::Event::MouseWheel {+ unit,+ delta: egui::vec2(f("dx").unwrap_or(0.0) as f32, f("dy").unwrap_or(0.0) as f32),+ phase,+ source,+ modifiers: modifiers(p),+ });+ ctx.request_repaint();+ Ok(Value::Null)+ }+ "ui.zoom" => {+ let Some(factor) = f("factor").map(|v| v as f32).filter(|v| v.is_finite() && *v > 0.0) else {+ return Err("ui.zoom: factor must be a finite positive number (1 = unchanged)".into());+ };+ app.synthetic.push(egui::Event::Zoom(factor));+ ctx.request_repaint();+ Ok(Value::Null)+ }+ other => Err(format!("not a synthetic-input gesture: `{other}`")),+ }+}++pub fn save_screenshot(app: &mut LightcraftApp, image: &egui::ColorImage, target: Option<&lightcraft_engine::originals::WriteTarget>) -> Value {let [w, h] = image.size;- let Some(path) = path else {+ let Some(target) = target else {return json!({"ok": true, "result": {"width": w, "height": h}});};- let rgba: Vec<u8> = image.pixels.iter().flat_map(|c| c.to_array()).collect();- let Some(img) = lightcraft_raster::Rgba8::from_bytes(w, h, &rgba) else {+ // Re-check the pinned destination immediately before encoding/writing. This is the point the+ // asynchronous renderer callback and the CPU fallback share.+ if let Err(error) = app.session.revalidate_write_target(target) {+ return json!({"ok": false, "error": error});+ }+ // Rgba8's buffer is the only extra full-image allocation while encoding (the PNG bytes are+ // the second transient; see MAX_SHOT_WORKING_SET_BYTES in `lib.rs`). Building it straight from+ // the `Color32` pixels avoids the former flat `Vec<u8>` copy of the same image.+ let Some(img) = lightcraft_raster::Rgba8::from_pixels(w, h, image.pixels.iter().map(|c| c.to_array())) else {return json!({"ok": false, "error": "bad screenshot buffer"});};let Some(png) = app.services.png.as_ref() else { return json!({"ok": false, "error": "no encoder"}) };let bytes = png(&img);- match app.services.write.as_mut() {- Some(wr) => match wr(path, &bytes) {+ let path = target.path();+ if target.was_absent() {+ // Publish a complete temp file with create-new semantics: a file that appeared after the+ // revalidation above is never replaced. Without this writer the capture fails closed.+ let Some(writer) = app.services.write_new.as_mut() else {+ return json!({"ok": false, "error": format!("{path}: no create-new writer configured for a new screenshot path")});+ };+ match writer(path, &bytes) {Ok(()) => json!({"ok": true, "result": {"path": path, "width": w, "height": h}}),Err(e) => json!({"ok": false, "error": e}),- },- None => json!({"ok": false, "error": "no writer configured"}),+ }+ } else {+ match app.services.write.as_mut() {+ Some(wr) => match wr(path, &bytes) {+ Ok(()) => json!({"ok": true, "result": {"path": path, "width": w, "height": h}}),+ Err(e) => json!({"ok": false, "error": e}),+ },+ None => json!({"ok": false, "error": "no writer configured"}),+ }}}diff --git a/crates/ui-egui/src/credits.rs b/crates/ui-egui/src/credits.rsindex d451aa79d..ac893ebf0 100644--- a/crates/ui-egui/src/credits.rs+++ b/crates/ui-egui/src/credits.rs@@ -229,7 +229,7 @@ fn name_link(app: &mut LightcraftApp, ui: &mut egui::Ui, c: &Contributor, names:/// About ▸ Contributors: a name toggle, a sort, and the list as a grab bag or a table.pub fn contributors_ui(app: &mut LightcraftApp, ui: &mut egui::Ui) {let t = Tokens::get(ui.ctx());- let id = egui::Id::new("credits_view");+ let id = egui::Id::unique("credits_view");let mut v = ui.data_mut(|d| d.get_temp::<View>(id)).unwrap_or_default();ui.horizontal_wrapped(|ui| {ui.label(crate::i18n::tr("Show"));@@ -240,7 +240,7 @@ pub fn contributors_ui(app: &mut LightcraftApp, ui: &mut egui::Ui) {}ui.separator();ui.label(crate::i18n::tr("Sort"));- crate::widgets::combo_box("credits_sort").selected_text(crate::i18n::tr(v.key.label().0)).show_ui(ui, |ui| {+ let sort = crate::widgets::combo_box("credits_sort").selected_text(crate::i18n::tr(v.key.label().0)).show_ui(ui, |ui| {for k in SortKey::ALL {if ui.selectable_label(v.key == k, crate::i18n::tr(k.label().0)).clicked() {v.key = k;@@ -248,9 +248,10 @@ pub fn contributors_ui(app: &mut LightcraftApp, ui: &mut egui::Ui) {}}});+ crate::widgets::name_combo(&sort.response, crate::i18n::tr("Sort"));let reverse =crate::widgets::arrow_button(ui, "", if v.ascending { crate::icons::Icon::ChevronUp } else { crate::icons::Icon::ChevronDown }, false);- reverse.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), crate::i18n::tr("Reverse the order")));+ reverse.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), crate::i18n::tr("Reverse the order")));if reverse.on_hover_text(crate::i18n::tr("Reverse the order")).clicked() {v.ascending = !v.ascending;}diff --git a/crates/ui-egui/src/date_picker.rs b/crates/ui-egui/src/date_picker.rsindex c84df98c4..710cd8956 100644--- a/crates/ui-egui/src/date_picker.rs+++ b/crates/ui-egui/src/date_picker.rs@@ -239,7 +239,7 @@ impl<'a> DatePicker<'a> {let DatePicker { id, value, precisions, min, max, today } = self;let mut button = crate::widgets::icon_button(ui, &format!("datePicker:{id}"), Icon::Calendar, vec2(24.0, 22.0), false, true, "Pick a date");register(ui.ctx(), format!("datePicker:{id}"), button.rect);- let state = egui::Id::new(("datePicker", id.as_str()));+ let state = egui::Id::unique(("datePicker", id.as_str()));if button.clicked() {// open on the value (or today), at its precision when it is one of those offeredlet at = value.or(today).unwrap_or(PickedDate::year(2026));@@ -267,7 +267,7 @@ impl<'a> DatePicker<'a> {}ui.horizontal(|ui| {let prev = crate::widgets::arrow_button(ui, "", Icon::ChevronLeft, true);- prev.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), crate::i18n::tr("Previous page")));+ prev.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), crate::i18n::tr("Previous page")));register(ui.ctx(), format!("datePickerPrev:{id}"), prev.rect);let title = match view.precision {Precision::Day => crate::i18n::date_group_label(&format!("{:04}-{:02}", view.year, view.month), false),@@ -280,7 +280,7 @@ impl<'a> DatePicker<'a> {ui.label(RichText::new(title).strong());ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {let next = crate::widgets::arrow_button(ui, "", Icon::ChevronRight, false);- next.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), crate::i18n::tr("Next page")));+ next.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), crate::i18n::tr("Next page")));register(ui.ctx(), format!("datePickerNext:{id}"), next.rect);if next.clicked() {view = step(view, true);diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rsindex e9f51a56f..9044d2579 100644--- a/crates/ui-egui/src/docking.rs+++ b/crates/ui-egui/src/docking.rs@@ -370,7 +370,7 @@ pub(crate) fn cancel_replaced_gesture(app: &crate::LightcraftApp, workspace: Opt_ => true,};if replaced && let Some(ctx) = &app.tasks.repaint {- craft_ui::docking::cancel_drag::<Panel>(ctx, egui::Id::new("lightcraft-docking"));+ craft_ui::docking::cancel_drag::<Panel>(ctx, egui::Id::unique("lightcraft-docking"));}}@@ -401,7 +401,7 @@ pub fn show(app: &mut crate::LightcraftApp, ui: &mut egui::Ui) {let t = crate::theme::Tokens::get(ui.ctx());let mut workspace = app.ui.docking.clone().unwrap_or_else(|| from_ui(app));if let Err(error) = workspace.validate().and_then(|()| sync(&mut workspace, app)) {- app.ui.toast = Some((format!("Panel layout could not be restored: {error}"), ui.input(|input| input.time) + 8.0, None));+ app.ui.toast = Some((format!("Panel layout could not be restored: {error}"), app.tick_now() + 8.0, None));workspace = from_ui(app);let _ = sync(&mut workspace, app);}@@ -427,7 +427,7 @@ pub fn show(app: &mut crate::LightcraftApp, ui: &mut egui::Ui) {style.font = t.font(12.0);// Tool and preset panels publish hover previews before the photo consumes them.let mut canvas = None;- let output = DockArea::new(egui::Id::new("lightcraft-docking")).show_with_limits(+ let output = DockArea::new(egui::Id::unique("lightcraft-docking")).show_with_limits(ui,&workspace.layout,&style,@@ -476,7 +476,7 @@ pub fn show(app: &mut crate::LightcraftApp, ui: &mut egui::Ui) {let _ = sync(&mut workspace, app);let stale = workspace.layout != rendered.layout || workspace.hidden != rendered.hidden;if stale {- craft_ui::docking::cancel_drag::<Panel>(ui.ctx(), egui::Id::new("lightcraft-docking"));+ craft_ui::docking::cancel_drag::<Panel>(ui.ctx(), egui::Id::unique("lightcraft-docking"));}publish_visibility(app, &workspace);app.ui.docking = Some(workspace);@@ -488,7 +488,7 @@ pub fn show(app: &mut crate::LightcraftApp, ui: &mut egui::Ui) {.map_err(|error| error.to_string()).and_then(|action| command_impl(app, false, &json!({"action": action}), true)){- app.ui.toast = Some((format!("Panel move was not applied: {error}"), ui.input(|input| input.time) + 8.0, None));+ app.ui.toast = Some((format!("Panel move was not applied: {error}"), app.tick_now() + 8.0, None));}}}diff --git a/crates/ui-egui/src/focus_scan.rs b/crates/ui-egui/src/focus_scan.rsindex de6e292dc..66e8174e3 100644--- a/crates/ui-egui/src/focus_scan.rs+++ b/crates/ui-egui/src/focus_scan.rs@@ -10,8 +10,7 @@ use crate::LightcraftApp;const BUSY_SECS: f64 = 0.25;/// Called every frame. Idle, it costs a comparison and wakes nothing; reading, it asks again every [`BUSY_SECS`].-pub fn pump(app: &mut LightcraftApp, ctx: &egui::Context) {- let now = ctx.input(|i| i.time);+pub fn pump(app: &mut LightcraftApp, ctx: &egui::Context, now: f64) {if now < app.caches.focus_next_pump {return;}diff --git a/crates/ui-egui/src/headless.rs b/crates/ui-egui/src/headless.rsindex c33ba0998..947c01455 100644--- a/crates/ui-egui/src/headless.rs+++ b/crates/ui-egui/src/headless.rs@@ -13,7 +13,6 @@//! is occluded.use std::collections::HashMap;-use std::sync::Arc;use std::sync::mpsc::Sender;use std::time::{Duration, Instant};@@ -156,7 +155,20 @@ impl HeadlessView {self.clipboard.clone_from(text);}}- let commands = out.viewport_output.remove(&ViewportId::ROOT).map(|v| v.commands).unwrap_or_default();+ let mut commands = out.viewport_output.remove(&ViewportId::ROOT).map(|v| v.commands).unwrap_or_default();+ // 0.37: `ViewportCommand::Screenshot` carries a one-shot callback. A headless host answers+ // it here, after the pass it was issued in, exactly once.+ let mut shots = Vec::new();+ commands.retain(|command| match command {+ ViewportCommand::Screenshot(callback) => {+ shots.push(callback.clone());+ false+ }+ _ => true,+ });+ for callback in shots {+ callback.complete(std::sync::Arc::new(self.paint(&std::collections::HashMap::new())));+ }// what a desktop host does with a cut, copy or paste request (egui-winit): the event, next framefor c in &commands {match c {@@ -314,6 +326,8 @@ impl Headless {raw.viewports.entry(ViewportId::ROOT).or_default().maximized = Some(self.window_maximized);raw.max_texture_side = (self.reported_texture_side != Some(self.max_texture_side)).then_some(self.max_texture_side);self.reported_texture_side = Some(self.max_texture_side);+ // A headless run's timers follow its simulated clock, not the host's wall clock.+ self.app.set_simulated_clock(Some(self.time));self.app.raw_input_hook(&mut raw);let app = &mut self.app;let mut cursor = egui::CursorIcon::Default;@@ -326,11 +340,10 @@ impl Headless {self.time += FRAME_DT;self.frames += 1;for c in commands {+ // `ViewportCommand::Screenshot` never reaches here: `HeadlessView::run` answers the+ // one-shot callback after the pass it was issued in, so there is exactly one reply.match c {- ViewportCommand::Screenshot(user_data) => {- let image = Arc::new(self.paint());- self.events.push(egui::Event::Screenshot { viewport_id: ViewportId::ROOT, user_data, image });- }+ ViewportCommand::Screenshot(_) => {}ViewportCommand::InnerSize(size) => {// Viewport commands use current egui points, which include UI zoom.if let Ok(native_size) = resized_viewport([size.x, size.y], self.pixels_per_point, self.view.ctx.zoom_factor()) {@@ -362,6 +375,7 @@ impl Headless {|| self.app.session.denoise_busy()|| !self.app.tasks.is_empty()|| !self.app.synthetic.is_empty()+ || !self.app.pending_gestures.is_empty()|| !self.events.is_empty()}@@ -597,6 +611,7 @@ mod tests {}use super::*;+ use std::sync::Arc;/// The pretend host has a clipboard, as a desktop does: text the UI copies lands in it, and a/// cut, copy or paste request (from a context menu) comes back as that event on the next frame.@@ -849,7 +864,7 @@ mod tests {let (Some(a), Some(b)) = (thumbs.first().cloned(), thumbs.get(1).cloned()) else { panic!("two grid photos: {thumbs:?}") };let popup = |w: &str| {let id: u64 = w.trim_start_matches("thumb:").parse().expect("a photo id");- egui::Id::new(("cell", id)).with("popup")+ egui::Id::unique(("cell", id)).with("popup")};assert!(!egui::Popup::is_any_open(&h.view.ctx));let r = h.request("ui.clickWidget", json!({"id": a, "button": "right"}), t);@@ -1522,7 +1537,7 @@ mod tests {assert_eq!(names(&h), vec![Some("Jane Doe".into()), None, None, None, None, None, Some("John Roe".into())]);// With no target A cannot name a face, even on this page.h.request("ui.move", json!({"x": 1, "y": 1}), t);- h.view.ctx.memory_mut(|m| m.surrender_focus(egui::Id::new(("more-face-above", ids[2].0, 0_usize))));+ h.view.ctx.memory_mut(|m| m.surrender_focus(egui::Id::unique(("more-face-above", ids[2].0, 0_usize))));set_page(&mut h);h.request("ui.key", json!({"key": "a"}), t);h.step();@@ -1550,7 +1565,7 @@ mod tests {h.request("ui.move", json!({"x": 1, "y": 1}), t);set_page(&mut h);// Keyboard focus on the candidate makes the same batch action available without hovering it.- h.view.ctx.memory_mut(|m| m.request_focus(egui::Id::new(("more-face", ids[2].0, 0_usize))));+ h.view.ctx.memory_mut(|m| m.request_focus(egui::Id::unique(("more-face", ids[2].0, 0_usize))));h.request("ui.key", json!({"key": "a"}), t);h.step();assert_eq!(@@ -2830,6 +2845,25 @@ mod tests {assert!(!h.app.ui.visualize_spots);}+ /// Bring a right-panel field into the visible panel before clicking it. The Info panel is a+ /// scroll area: 0.37's roomier text rows push the place fields below a 1000-point window, and a+ /// click at an off-screen rect would leave the previous field focused.+ fn click_field_in_view(h: &mut Headless, key: &str, timeout: Duration) {+ let id = format!("field:{key}");+ let panel = h.app.widgets.iter().find(|(w, _)| w == "panel:right_panel").map(|(_, r)| *r).expect("the right panel is laid out");+ let rect = h.app.widgets.iter().find(|(w, _)| *w == id).map(|(_, r)| *r).expect("the field is laid out");+ if !panel.contains(rect.center()) {+ let dy = (panel.center().y - rect.center().y).clamp(-4000.0, 4000.0);+ assert_eq!(h.request("ui.move", json!({"x": panel.center().x, "y": panel.center().y}), timeout)["ok"], true);+ assert_eq!(h.request("ui.scroll", json!({"dy": dy}), timeout)["ok"], true);+ h.settle(timeout);+ }+ let rect = h.app.widgets.iter().find(|(w, _)| *w == id).map(|(_, r)| *r).expect("the field is laid out");+ assert!(panel.contains(rect.center()), "the field must be scrolled into view before clicking: {rect:?} in {panel:?}");+ let r = h.request("ui.clickWidget", json!({"id": id}), timeout);+ assert_eq!(r["ok"], true, "{r}");+ }+/// Info panel: typing into a field survives frames and is saved when it loses focus; the new/// accessibility and place fields reach the photo.#[test]@@ -2839,8 +2873,7 @@ mod tests {h.request("ui.set", json!({"view": "detail", "right": "info"}), t);h.settle(SETTLE);for (key, text) in [("altText", "A lake at dawn"), ("usageTerms", "Editorial use only"), ("city", "Zermatt")] {- let r = h.request("ui.clickWidget", json!({"id": format!("field:{key}")}), t);- assert_eq!(r["ok"], true, "{r}");+ click_field_in_view(&mut h, key, t);h.request("ui.key", json!({"key": "A", "cmd": true}), t);h.request("ui.text", json!({"text": text}), t);h.step();@@ -4247,7 +4280,7 @@ mod tests {// Paint the edited template before locating the Tags button in the resized dialog.assert!(h.settle(SETTLE), "Copy dialog layout should settle before locating Tags");// the cursor sits after "Trip-"- let id = egui::Id::new("import-rename");+ let id = egui::Id::unique("import-rename");let mut st = egui::text_edit::TextEditState::default();st.cursor.set_char_range(Some(egui::text::CCursorRange::one(egui::text::CCursor::new(5))));st.store(&h.view.ctx, id);@@ -4284,7 +4317,7 @@ mod tests {let r = h.request("ui.clickWidget", json!({"id": format!("button:aboutTab-{tab}")}), t);assert_eq!(r["ok"], true, "{tab}: {r}");h.step();- let shown = h.view.ctx.data_mut(|d| d.get_temp::<u8>(egui::Id::new("about_tab")));+ let shown = h.view.ctx.data_mut(|d| d.get_temp::<u8>(egui::Id::unique("about_tab")));assert_eq!(shown.map(usize::from), Some(i), "{tab}");}h.request("ui.clickWidget", json!({"id": "button:aboutTab-contributors"}), t);@@ -4713,6 +4746,7 @@ mod tests {unit: egui::MouseWheelUnit::Point,delta: egui::vec2(10.0, -10.0),phase: egui::TouchPhase::Move,+ source: egui::MouseWheelSource::Unknown,modifiers: egui::Modifiers::NONE,}),None,@@ -4791,7 +4825,13 @@ mod tests {] {h.request("ui.set", json!({"zoom": "fit", "pan": [0.5, 0.5]}), t);h.request("ui.hoverWidget", json!({"id": "canvas:image"}), t);- h.app.synthetic.push(egui::Event::MouseWheel { unit, delta: egui::vec2(0.0, y), phase: egui::TouchPhase::Move, modifiers });+ h.app.synthetic.push(egui::Event::MouseWheel {+ unit,+ delta: egui::vec2(0.0, y),+ phase: egui::TouchPhase::Move,+ source: egui::MouseWheelSource::Unknown,+ modifiers,+ });for _ in 0..10 {h.step();}diff --git a/crates/ui-egui/src/import.rs b/crates/ui-egui/src/import.rsindex 323d8d902..ffbfbf28a 100644--- a/crates/ui-egui/src/import.rs+++ b/crates/ui-egui/src/import.rs@@ -47,7 +47,7 @@ pub(crate) fn grid_height(available: f32, below: f32, row: f32) -> f32 {pub(crate) fn note_dialog_bottom(ui: &egui::Ui) {if !ui.is_sizing_pass() {let y = ui.min_rect().bottom();- ui.ctx().data_mut(|m| m.insert_temp(egui::Id::new(CONTENT_BOTTOM), y));+ ui.ctx().data_mut(|m| m.insert_temp(egui::Id::unique(CONTENT_BOTTOM), y));}}@@ -1040,7 +1040,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) {// as tall as the window leaves after the options and buttons below it (measured last frame),// so resizing the dialog resizes the gridlet below = ui.ctx().data(|m| {- let y = |key: &str| m.get_temp::<f32>(egui::Id::new(key));+ let y = |key: &str| m.get_temp::<f32>(egui::Id::unique(key));y(CONTENT_BOTTOM).zip(y(GRID_BOTTOM)).map(|(content, grid)| content - grid)});let grid_h = grid_height(ui.available_height(), below.unwrap_or(DEFAULT_BELOW_GRID), cell + 26.0);@@ -1058,7 +1058,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) {}});if !ui.is_sizing_pass() {- ui.ctx().data_mut(|m| m.insert_temp(egui::Id::new(GRID_BOTTOM), grid.inner_rect.bottom()));+ ui.ctx().data_mut(|m| m.insert_temp(egui::Id::unique(GRID_BOTTOM), grid.inner_rect.bottom()));}ui.add_space(4.0);// options@@ -1155,10 +1155,11 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) {}}});+ crate::widgets::name_combo(&combo.response, crate::i18n::tr("Organize into"));register(ui.ctx(), "combo:importOrganize", combo.response.rect);});if d.organize == "custom" {- let folders_id = egui::Id::new("import-folder-template");+ let folders_id = egui::Id::unique("import-folder-template");let tags_open = field(ui, "Template", |ui| {ui.spacing_mut().item_spacing.x = 4.0;let w = tag_field_width(ui);@@ -1190,7 +1191,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) {register(ui.ctx(), "check:importDng", r.rect);});}- let rename_id = egui::Id::new("import-rename");+ let rename_id = egui::Id::unique("import-rename");let tags_open = field(ui, "Rename", |ui| {ui.spacing_mut().item_spacing.x = 4.0;let w = tag_field_width(ui);@@ -1226,13 +1227,14 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) {_ => "Leave them",};let mut pick = None;- crate::widgets::combo_box("import-on-deleted").selected_text(crate::i18n::tr(cur)).show_ui(ui, |ui| {+ let combo = crate::widgets::combo_box("import-on-deleted").selected_text(crate::i18n::tr(cur)).show_ui(ui, |ui| {for (v, label) in [("restore", "Restore them"), ("fresh", "Import as new"), ("", "Leave them")] {if ui.selectable_label(d.on_deleted == v, crate::i18n::tr(label)).clicked() {pick = Some(v);}}});+ crate::widgets::name_combo(&combo.response, crate::i18n::tr("Recently deleted files"));if let Some(v) = pick {d.set_on_deleted(v);}@@ -1296,7 +1298,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) {.find(|p| p.id == d.preset).map(|p| crate::i18n::builtin_label(&p.name, p.builtin).to_string()).unwrap_or_else(|| crate::i18n::tr("None").into());- crate::widgets::combo_box("import-preset").selected_text(cur).height(300.0).show_ui(ui, |ui| {+ let combo = crate::widgets::combo_box("import-preset").selected_text(cur).height(300.0).show_ui(ui, |ui| {if ui.selectable_label(d.preset.is_empty(), crate::i18n::tr("None")).clicked() {d.preset.clear();}@@ -1305,11 +1307,12 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) {d.preset = pid;}});+ crate::widgets::name_combo(&combo.response, crate::i18n::tr("Preset"));});if !app.session.metadata_presets.is_empty() {field(ui, "Metadata", |ui| {let cur = if d.metadata_preset.is_empty() { crate::i18n::tr("None").to_string() } else { d.metadata_preset.clone() };- crate::widgets::combo_box("import-metadata").selected_text(cur).show_ui(ui, |ui| {+ let combo = crate::widgets::combo_box("import-metadata").selected_text(cur).show_ui(ui, |ui| {if ui.selectable_label(d.metadata_preset.is_empty(), crate::i18n::tr("None")).clicked() {d.metadata_preset.clear();}@@ -1319,6 +1322,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) {}}});+ crate::widgets::name_combo(&combo.response, crate::i18n::tr("Metadata preset"));});}field(ui, "Keywords", |ui| {@@ -1332,7 +1336,7 @@ fn candidate_cell(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDiallet c = d.candidates[i].clone();let ok = d.importable(i);let img = Rect::from_min_size(rect.min, vec2(rect.width(), rect.width()));- let resp = ui.interact(img, egui::Id::new(("import-cell", i)), Sense::click());+ let resp = ui.interact(img, egui::Id::unique(("import-cell", i)), Sense::click());crate::widgets::announce(&resp, c.name.clone());register(ui.ctx(), format!("import:{i}"), img);let p = ui.painter();@@ -1415,7 +1419,7 @@ pub(crate) fn tag_field_width(ui: &egui::Ui) -> f32 {/// The "Tags" toggle beside a template field (`button:<key>Tags`); returns whether the tag help/// ([`tag_help`]) is open.pub(crate) fn tag_toggle(ui: &mut egui::Ui, key: &str) -> bool {- let id = egui::Id::new((key, "tags-open"));+ let id = egui::Id::unique((key, "tags-open"));let mut open = ui.ctx().data(|d| d.get_temp::<bool>(id)).unwrap_or(false);let r = crate::widgets::text_button(ui, &format!("{key}Tags"), crate::i18n::tr("Tags"), open).on_hover_text(crate::i18n::tr("Show the template tags; click one to insert it"));diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 6f23c9bd7..daeb3de74 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -123,6 +123,8 @@ mod tests_layout_image;#[cfg(test)]mod tests_library_problem;#[cfg(test)]+mod tests_lifecycle_037;+#[cfg(test)]mod tests_lights_out;#[cfg(test)]mod tests_mask_effects;@@ -274,6 +276,10 @@ pub struct Services {/// Save dialog for an exported slideshow template (`.json`).pub save_slideshow_template: Option<SaveFile>,pub write: Option<WriteFn>,+ /// Create-new writer (never replaces an existing path), for screenshots of destinations that+ /// did not exist when the request was admitted. Required for such captures: falling back to+ /// [`Self::write`] would reopen the admission-to-write race.+ pub write_new: Option<WriteFn>,/// Thread-safe writer: with it, UI-started exports run in the background (desktop only).pub write_shared: Option<SharedWrite>,/// PNG encoder (the host links an image encoder; the UI crate stays codec-free).@@ -378,7 +384,38 @@ pub struct LightcraftApp {pub quit_confirmed: bool,control_rx: Option<Receiver<ControlRequest>>,pending_screenshots: Vec<PendingShot>,+ /// Synthetic-input control requests waiting for a fresh layout and delivery (plan §4.5).+ pending_gestures: Vec<PendingGesture>,+ /// Completed, nondiscarded UI layouts. A gesture admitted before this advanced may resolve.+ layout_epoch: u64,screenshot_token: u64,+ /// Bytes reserved by admitted, not-yet-drained screenshots (in-flight and completed alike).+ shot_bytes: usize,+ /// A geometry change since the last logic call: a completed image from an older epoch is+ /// stale even when the window has meanwhile been resized back to the issued size.+ shot_geometry_epoch: u64,+ last_shot_geometry: Option<ShotGeometry>,+ /// The texture limit the host last reported (`RawInput::max_texture_side`), retained across+ /// passes where the host reports it only once.+ max_texture_side: usize,+ /// Monotonic app clock (`web_time::Instant`), not the wall clock and not egui's per-pass time:+ /// timers must keep advancing while the window is hidden.+ clock: AppClock,+ /// The language already sent to `Context::set_language`, so a logic pass does not allocate a+ /// `String` just to compare it.+ accesskit_language: Option<String>,+ /// When playback was auto-paused because the window became hidden (`None`: it is running, or+ /// the user paused it). On unhide the pause is lifted and the slide keeps its remaining time.+ slideshow_hidden_at: Option<f64>,+ /// The app (not the user) paused the slideshow because the window was hidden.+ slideshow_auto_paused: bool,+ /// Files dropped since the last UI pass, consumed exactly once by the UI phase.+ dropped_files: Vec<egui::DroppedFileHandle>,+ /// A synthetic batch was injected into a pass and has not been consumed by a completed+ /// (nondiscarded) UI pass yet: a hidden logic tick must not inject another one.+ synthetic_in_flight: bool,+ /// Completed, nondiscarded root UI passes; host frames, not layout passes.+ ui_passes: u64,/// Offscreen context for headless screenshots of the windowed app.shadow: Option<headless::HeadlessView>,/// Synthetic input events (from the control channel) injected one step per frame.@@ -511,7 +548,20 @@ impl LightcraftApp {quit_confirmed: false,control_rx: None,pending_screenshots: vec![],+ pending_gestures: vec![],+ layout_epoch: 0,screenshot_token: 0,+ shot_bytes: 0,+ shot_geometry_epoch: 0,+ last_shot_geometry: None,+ max_texture_side: MAX_TEXTURE_SIDE,+ clock: AppClock::new(),+ accesskit_language: None,+ slideshow_hidden_at: None,+ slideshow_auto_paused: false,+ dropped_files: vec![],+ synthetic_in_flight: false,+ ui_passes: 0,shadow: None,synthetic: vec![],copied: None,@@ -584,6 +634,109 @@ impl LightcraftApp {self}+ /// Seconds on the app's monotonic clock. Every timer that must advance while the window is+ /// hidden (imports, autosave, playback, toasts, captures) uses this, never `i.time`.+ pub fn tick_now(&self) -> f64 {+ self.clock.now()+ }++ fn tick_now_ms(&self) -> f64 {+ self.clock.now() * 1000.0+ }++ /// The immutable identity a capture is bound to: the library generation. It changes when a+ /// different library is opened, not on every edit, import batch or keyword op (`catalog.revision`+ /// bumps on all of those), so a screenshot during interactive editing still belongs to the+ /// document the user asked for.+ fn shot_document_generation(&self) -> u64 {+ self.session.library_generation()+ }++ /// Give a headless driver its simulated time (`None` returns to the monotonic host clock).+ pub fn set_simulated_clock(&mut self, seconds: Option<f64>) {+ self.clock.simulated = seconds.filter(|s| s.is_finite() && *s >= 0.0);+ }++ /// The window's current surface geometry as native points plus native pixels per point.+ /// `run_logic` refreshes `input.viewports`, so this is fresh even while the UI is not laid out;+ /// without one, the last laid-out content rect is used.+ fn shot_geometry(&self, ctx: &egui::Context) -> ShotGeometry {+ // Both `viewport.inner_rect` and the content rect are in egui points, and `pixels_per_point`+ // already includes the UI zoom (egui-winit divides by the zoomed ppp). Multiplying by the+ // zoom again would reserve a surface that is too small, so the zoom is only tracked as a+ // change signal.+ let zoom = ctx.zoom_factor();+ let zoom = if zoom.is_finite() && zoom > 0.0 { zoom } else { 1.0 };+ let pixels_per_point = ctx.input(|i| i.pixels_per_point());+ let viewport = ctx.input(|i| {+ i.viewport().inner_rect.filter(|r| r.width() > 0.0 && r.height() > 0.0).map_or_else(|| i.content_rect().size(), |inner| inner.size())+ });+ ShotGeometry { viewport, pixels_per_point, zoom, epoch: self.shot_geometry_epoch }+ }++ /// Track geometry changes as a generation. Called once per logic tick from the refreshed+ /// viewport information, so a hidden window still notices a resize.+ fn note_shot_geometry(&mut self, ctx: &egui::Context) {+ let mut now = self.shot_geometry(ctx);+ if let Some(last) = self.last_shot_geometry+ && (last.viewport != now.viewport || last.pixels_per_point != now.pixels_per_point || last.zoom != now.zoom)+ {+ self.shot_geometry_epoch = self.shot_geometry_epoch.wrapping_add(1);+ now.epoch = self.shot_geometry_epoch;+ }+ self.last_shot_geometry = Some(now);+ }++ /// The texture limit the host reported (16 384 unless it said otherwise).+ fn max_texture_side(&self) -> usize {+ self.max_texture_side+ }++ /// Retain the host's `RawInput::max_texture_side`. Hosts (egui-winit, `Headless`) report it+ /// only when it changes, so keep the last value instead of assuming 16 384.+ fn note_max_texture_side(&mut self, ctx: &egui::Context) {+ if let Some(limit) = ctx.input(|i| i.raw.max_texture_side)+ && limit > 0+ {+ self.max_texture_side = limit;+ }+ }++ /// Reserve a new image's `bytes` against the aggregate screenshot budget, or report why not.+ fn reserve_shot_bytes(&mut self, bytes: usize) -> Result<(), String> {+ if bytes > MAX_SHOT_BYTES {+ return Err(format!("ui.screenshot: {bytes} bytes is over the {MAX_SHOT_BYTES}-byte per-image limit"));+ }+ let total = self.shot_bytes.checked_add(bytes).ok_or("ui.screenshot: byte reservation overflow")?;+ if total > MAX_SHOT_TOTAL_BYTES {+ return Err(format!("ui.screenshot: {total} bytes reserved is over the {MAX_SHOT_TOTAL_BYTES}-byte limit"));+ }+ self.shot_bytes = total;+ Ok(())+ }++ /// A surface that grew after admission (a stale `content_rect` on Wayland, a resize between+ /// issue and completion): bound the *new image* against the per-image limit, then reserve only+ /// the growth against the aggregate. The old per-image check would compare the delta to the+ /// per-image cap and name the delta as if it were the image.+ fn grow_shot_reservation(&mut self, current_reserved: usize, image_bytes: usize) -> Result<(), String> {+ if image_bytes > MAX_SHOT_BYTES {+ return Err(format!("ui.screenshot: {image_bytes} bytes is over the {MAX_SHOT_BYTES}-byte per-image limit"));+ }+ let extra = image_bytes.saturating_sub(current_reserved);+ let total = self.shot_bytes.checked_add(extra).ok_or("ui.screenshot: byte reservation overflow")?;+ if total > MAX_SHOT_TOTAL_BYTES {+ return Err(format!("ui.screenshot: {total} bytes reserved is over the {MAX_SHOT_TOTAL_BYTES}-byte limit"));+ }+ self.shot_bytes = total;+ Ok(())+ }++ /// Release a reservation; never let an accounting bug underflow `usize`.+ fn release_shot_bytes(&mut self, bytes: usize) {+ self.shot_bytes = self.shot_bytes.saturating_sub(bytes);+ }+/// The open person page, the way back to it, and the photo it was opened from follow a rename.fn follow_renamed_person(&mut self, from: &str, to: &str) {let same = |n: &str| n.trim().to_lowercase() == from.trim().to_lowercase();@@ -666,8 +819,7 @@ impl LightcraftApp {_ => None,};if let Some(message) = completed {- // Menu clicks can arrive before the next frame updates last_time.- let now = self.tasks.repaint.as_ref().map(|ctx| ctx.input(|i| i.time)).unwrap_or(self.last_time);+ let now = self.tick_now();self.ui.toast = Some((message, now + TOAST_SECONDS, None));}}@@ -681,8 +833,7 @@ impl LightcraftApp {}None => i18n::tr("Color label cleared").into(),};- // Native menu clicks can arrive before logic() updates last_time after an idle gap.- let now = self.tasks.repaint.as_ref().map(|ctx| ctx.input(|i| i.time)).unwrap_or(self.last_time);+ let now = self.tick_now();self.ui.toast = Some((text, now + TOAST_SECONDS, label));}match &r {@@ -752,10 +903,34 @@ impl LightcraftApp {Ok(())}- /// Show a transient toast at the bottom of the canvas (like the reference app's HUD).- /// Advance a running slideshow.- fn slideshow_tick(&mut self, ctx: &egui::Context) {- panels::slideshow::tick(self, ctx);+ /// Advance a running slideshow, but not while the window is hidden: in 0.36 `i.time` froze+ /// there, and a minimized show must not keep waking the event loop or requesting full-size+ /// slide renders overnight. Playback is auto-paused on hide and resumed on unhide with the+ /// slide's remaining time preserved.+ fn slideshow_tick(&mut self, ctx: &egui::Context, now: f64) {+ let hidden = ctx.input(|i| i.viewport().visible() == Some(false));+ let Some(run) = self.ui.slideshow.as_mut() else {+ self.slideshow_hidden_at = None;+ self.slideshow_auto_paused = false;+ return;+ };+ if hidden {+ if self.slideshow_hidden_at.is_none() {+ self.slideshow_hidden_at = Some(now);+ if !run.play.is_paused() {+ run.play.toggle_pause(now);+ self.slideshow_auto_paused = true;+ }+ }+ return;+ }+ if self.slideshow_hidden_at.take().is_some() && self.slideshow_auto_paused {+ self.slideshow_auto_paused = false;+ if run.play.is_paused() {+ run.play.toggle_pause(now);+ }+ }+ panels::slideshow::tick(self, ctx, now);}/// Announce the end of a Build Previews run.@@ -793,7 +968,7 @@ impl LightcraftApp {match (unsaved, self.ui.unsaved_seen) {(Some((n, e)), false) => {self.ui.unsaved_seen = true;- let t = ctx.input(|i| i.time);+ let t = self.tick_now();self.ui.toast = Some((crate::i18n::tr_format!("{n} change{} saved in memory but not written to disk: {e} — LightCraft will retry",@@ -831,8 +1006,8 @@ impl LightcraftApp {}/// A toast that stays `secs` seconds (messages that say where to look or what to do next).- pub fn toast_for(&mut self, ctx: &egui::Context, text: impl Into<String>, secs: f64) {- let t = ctx.input(|i| i.time);+ pub fn toast_for(&mut self, _ctx: &egui::Context, text: impl Into<String>, secs: f64) {+ let t = self.tick_now();self.ui.toast = Some((text.into(), t + secs, None));}@@ -851,9 +1026,8 @@ impl LightcraftApp {/// AI masks: apply finished background requests (clicks, descriptions, detail passes) and/// show their errors; start a zoomed-in detail pass once the clicking stops/// (`ui.detail_due`); watch the model download. Never waits for the model.- fn ai_mask_detail(&mut self, ctx: &egui::Context) {+ fn ai_mask_detail(&mut self, ctx: &egui::Context, now: f64) {let polled = self.session.segment_poll();- let now = ctx.input(|i| i.time);if polled.changed {ctx.request_repaint();}@@ -919,8 +1093,8 @@ impl LightcraftApp {}/// A toast for an error the user has to read and act on (stays 6 s).- pub fn toast_error(&mut self, ctx: &egui::Context, text: impl Into<String>) {- let t = ctx.input(|i| i.time);+ pub fn toast_error(&mut self, _ctx: &egui::Context, text: impl Into<String>) {+ let t = self.tick_now();self.ui.toast = Some((text.into(), t + 6.0, None));}@@ -937,68 +1111,378 @@ impl LightcraftApp {control::Outcome::Done(v) => {let _ = reply.send(v);}- control::Outcome::Screenshot { path, headless } => {- self.screenshot_token += 1;- let now = now_ms();- self.pending_screenshots.push(PendingShot {- token: self.screenshot_token,- path,- reply,- headless: headless && !self.headless_host,- not_before: now + 120.0,- deadline: now + SCREENSHOT_SETTLE_MS,- frames: 0,- sent_at: None,- });+ control::Outcome::Screenshot { target, headless } => {+ if let Err(error) = self.admit_shot(ctx, target, headless, reply.clone()) {+ let _ = reply.send(serde_json::json!({"ok": false, "error": error}));+ }+ }+ control::Outcome::Gesture { method, params } => {+ if let Err(error) = self.admit_gesture(ctx, method, params, reply.clone()) {+ let _ = reply.send(serde_json::json!({"ok": false, "error": error}));+ }}}}self.control_rx = Some(rx);}- /// Advance pending screenshots: wait (≥ 3 frames, ≥ 120 ms) until no renders are in flight- /// (or a timeout), then capture — via the host's compositor, or headlessly- /// ([`Self::headless_screenshot`]) when asked or when the compositor delivers nothing.+ /// The navigation/document/modal/panel state that decides what an automation id means.+ fn gesture_frame(&self) -> GestureFrame {+ GestureFrame {+ view: self.ui.view,+ active: self.session.active(),+ library: self.session.library_generation(),+ dialog: self.ui.dialog.as_ref().map(std::mem::discriminant),+ left_panel: self.ui.left_panel,+ right: self.ui.right,+ presets: self.ui.presets,+ filmstrip: self.ui.filmstrip,+ }+ }++ /// Queue a synthetic-input request. Nothing is answered and no event is queued until a+ /// completed layout newer than this admission exists (see [`Self::resolve_pending_gestures`]).+ fn admit_gesture(&mut self, ctx: &egui::Context, method: String, params: Value, reply: Sender<ControlResponse>) -> Result<(), String> {+ if self.pending_gestures.len() >= MAX_PENDING_GESTURES {+ return Err(format!("{}: {MAX_PENDING_GESTURES} control gestures are already pending", method));+ }+ let now = self.tick_now_ms();+ self.pending_gestures.push(PendingGesture {+ method,+ params,+ reply,+ admitted_epoch: self.layout_epoch,+ frame: self.gesture_frame(),+ deadline_ms: now + GESTURE_TIMEOUT_MS,+ resolved_pass: None,+ remaining_events: 0,+ started: false,+ result: Value::Null,+ });+ ctx.request_repaint();+ Ok(())+ }++ /// Resolve one queued gesture against the fresh widgets/image rect of the pass that just+ /// completed. A changed view/document/dialog/panel state cancels instead of retargeting.+ fn resolve_pending_gestures(&mut self, ctx: &egui::Context) {+ if self.pending_gestures.is_empty() {+ return;+ }+ let now = self.tick_now_ms();+ let frame = self.gesture_frame();+ let epoch = self.layout_epoch;+ let mut gestures = std::mem::take(&mut self.pending_gestures);+ let mut keep = Vec::with_capacity(gestures.len());+ let mut timed_out = false;+ for mut gesture in gestures.drain(..) {+ if now > gesture.deadline_ms {+ let _ =+ gesture.reply.send(serde_json::json!({"ok": false, "error": format!("{} timed out before the UI consumed it", gesture.method)}));+ timed_out = true;+ continue;+ }+ if timed_out {+ let _ = gesture.reply.send(serde_json::json!({+ "ok": false,+ "error": "control gesture canceled: another request timed out before the UI consumed it",+ }));+ continue;+ }+ if gesture.resolved_pass.is_some() {+ keep.push(gesture);+ continue;+ }+ if epoch <= gesture.admitted_epoch {+ keep.push(gesture);+ continue;+ }+ if gesture.frame != frame {+ let _ = gesture.reply.send(serde_json::json!({+ "ok": false,+ "error": format!("{} canceled: the view, document, dialog or panel layout changed before a fresh layout", gesture.method),+ }));+ continue;+ }+ let before = self.synthetic.len();+ match control::gesture_events(self, ctx, &gesture.method, &gesture.params) {+ Ok(result) => {+ gesture.result = result;+ gesture.resolved_pass = Some(self.ui_passes);+ gesture.remaining_events = self.synthetic.len().saturating_sub(before);+ gesture.started = gesture.remaining_events == 0;+ keep.push(gesture);+ }+ Err(error) => {+ let _ = gesture.reply.send(serde_json::json!({"ok": false, "error": error}));+ }+ }+ }+ self.pending_gestures = keep;+ if timed_out {+ // Fail closed: an error must not be followed by a late synthetic click.+ self.synthetic.clear();+ let remaining = std::mem::take(&mut self.pending_gestures);+ for gesture in remaining {+ let _ = gesture.reply.send(serde_json::json!({+ "ok": false,+ "error": "control gesture canceled: another request timed out before the UI consumed it",+ }));+ }+ }+ }++ /// Answer gestures whose last synthetic event a completed, nondiscarded UI pass consumed.+ /// A zero-event action waits for one completed pass after resolution.+ ///+ /// Delivery does not compare the frame again: the gesture's own event may legitimately change+ /// the view, document, dialog or panel (a click that opens a dialog, a key that starts Compare),+ /// so a second snapshot would cancel exactly the input that did its job. Freshness is checked+ /// before resolution ([`Self::resolve_pending_gestures`]) and again immediately before the+ /// batch is injected ([`Self::drop_gestures_stale_before_injection`]).+ fn reply_delivered_gestures(&mut self) {+ if self.pending_gestures.is_empty() {+ return;+ }+ let now = self.tick_now_ms();+ if self.pending_gestures.iter().any(|g| g.resolved_pass.is_some() && now > g.deadline_ms) {+ self.synthetic.clear();+ let gestures = std::mem::take(&mut self.pending_gestures);+ for gesture in gestures {+ let _ = gesture.reply.send(serde_json::json!({+ "ok": false,+ "error": format!("{} timed out before the UI consumed its last event", gesture.method),+ }));+ }+ return;+ }+ if !self.synthetic.is_empty() || self.synthetic_in_flight {+ return;+ }+ let mut gestures = std::mem::take(&mut self.pending_gestures);+ let mut keep = Vec::with_capacity(gestures.len());+ for mut gesture in gestures.drain(..) {+ let Some(resolved) = gesture.resolved_pass else {+ keep.push(gesture);+ continue;+ };+ if self.ui_passes <= resolved {+ keep.push(gesture);+ continue;+ }+ let result = std::mem::take(&mut gesture.result);+ let _ = gesture.reply.send(serde_json::json!({"ok": true, "result": result}));+ }+ self.pending_gestures = keep;+ }++ /// The gesture whose events sit at the head of the synthetic queue.+ fn head_gesture(&self) -> Option<usize> {+ self.pending_gestures.iter().position(|gesture| gesture.resolved_pass.is_some() && gesture.remaining_events > 0)+ }++ /// Fail resolved gestures whose view/document/dialog/panel snapshot changed before their+ /// first synthetic batch reached the next completed pass. A hidden logic tick runs between+ /// passes and may change what an automation id or a photo click means; fail closed instead of+ /// delivering it against the new state.+ ///+ /// Only the gesture at the head of the queue, and only before its first batch, is checked:+ /// later batches of the same gesture may see its own partial effect (the first click of a+ /// double click selects the photo the second one opens), and a second, concurrently queued+ /// gesture is checked when its events reach the head.+ fn drop_gestures_stale_before_injection(&mut self) -> bool {+ let Some(head) = self.head_gesture() else { return false };+ let gesture = &self.pending_gestures[head];+ if gesture.started || gesture.frame == self.gesture_frame() {+ return false;+ }+ let gestures = std::mem::take(&mut self.pending_gestures);+ for gesture in gestures {+ if gesture.resolved_pass.is_none() {+ self.pending_gestures.push(gesture);+ } else {+ let _ = gesture.reply.send(serde_json::json!({+ "ok": false,+ "error": format!("{} canceled: the view, document, dialog or panel layout changed before delivery", gesture.method),+ }));+ }+ }+ self.synthetic.clear();+ true+ }++ /// Fail pending gestures at the monotonic deadline even when no UI pass runs (a hidden window+ /// whose paint request the host ignored). `logic` calls this every tick.+ fn expire_gestures(&mut self) {+ if self.pending_gestures.is_empty() {+ return;+ }+ let now = self.tick_now_ms();+ if self.pending_gestures.iter().any(|gesture| now > gesture.deadline_ms) {+ self.synthetic.clear();+ let gestures = std::mem::take(&mut self.pending_gestures);+ for gesture in gestures {+ let _ =+ gesture.reply.send(serde_json::json!({"ok": false, "error": format!("{} timed out before the UI consumed it", gesture.method)}));+ }+ }+ }++ /// Admit a `ui.screenshot` request against the bounded capture budget. Nothing is written and+ /// no capture is issued here: [`Self::issue_screenshots`] waits for a settled, nondiscarded UI+ /// pass and a fresh geometry generation.+ fn admit_shot(+ &mut self,+ ctx: &egui::Context,+ target: Option<lightcraft_engine::originals::WriteTarget>,+ headless: bool,+ reply: Sender<ControlResponse>,+ ) -> Result<(), String> {+ if self.pending_screenshots.len() >= MAX_PENDING_SHOTS {+ return Err(format!("ui.screenshot: {MAX_PENDING_SHOTS} requests are already pending; wait for a reply first"));+ }+ let geometry = self.last_shot_geometry.unwrap_or_else(|| self.shot_geometry(ctx));+ let bytes = geometry.bytes(self.max_texture_side()).ok_or_else(|| geometry.rejection(self.max_texture_side()))?;+ self.reserve_shot_bytes(bytes)?;+ self.screenshot_token = self.screenshot_token.wrapping_add(1);+ let now = self.tick_now_ms();+ self.pending_screenshots.push(PendingShot {+ token: self.screenshot_token,+ target,+ reply,+ headless: headless && !self.headless_host,+ admitted_passes: self.ui_passes,+ not_before_ms: now + SHOT_SETTLE_MS,+ // Capture the current settled frame at this instant even if renders are still in flight+ // (0.36 did this at its three-second deadline, so automation never got an error instead+ // of an image while a slider/import kept the renderer busy).+ force_ms: now + SHOT_FORCE_BUSY_MS,+ // Settle + forced capture + compositor fallback + the headless settle, all from admission.+ deadline_ms: now + SHOT_SETTLE_MS + SCREENSHOT_SETTLE_MS + SCREENSHOT_FALLBACK_MS + SCREENSHOT_SETTLE_MS,+ sent_at_ms: None,+ reserved: bytes,+ slot: None,+ issued: None,+ issued_library: self.shot_document_generation(),+ });+ ctx.request_repaint();+ Ok(())+ }++ /// Advance pending screenshots: wait (≥ 3 completed UI frames, ≥ 120 ms) until no renders are+ /// in flight — or until the forced-capture instant, so sustained rendering cannot turn a+ /// request into a timeout — then capture through the compositor's one-shot callback, or+ /// headlessly ([`Self::headless_screenshot`]) when asked or when the compositor delivers nothing.fn issue_screenshots(&mut self, ctx: &egui::Context) {if self.pending_screenshots.is_empty() {return;}- let now = now_ms();+ let now = self.tick_now_ms();let busy = self.renderer.in_flight() > 0 || self.merge.busy();+ let max_side = self.max_texture_side();+ let library = self.shot_document_generation();+ let geometry = self.last_shot_geometry.unwrap_or_else(|| self.shot_geometry(ctx));let mut shots = std::mem::take(&mut self.pending_screenshots);let mut shadow_ticked = false;- shots.retain_mut(|s| {- if let Some(sent) = s.sent_at {+ let mut keep = Vec::with_capacity(shots.len());+ for mut shot in shots.drain(..) {+ // Hard deadline from admission: a compositor fallback does not extend it.+ if now > shot.deadline_ms {+ let _ = shot.reply.send(serde_json::json!({"ok": false, "error": format!("screenshot {} timed out", shot.token)}));+ if let Some(slot) = shot.slot.take() {+ slot.cancel();+ }+ self.release_shot_bytes(shot.reserved);+ continue;+ }+ if let Some(sent) = shot.sent_at_ms {if now - sent < SCREENSHOT_FALLBACK_MS || self.headless_host {- return true;+ keep.push(shot);+ continue;}// The compositor delivered nothing (display asleep, window occluded): go headless.log::warn!("ui.screenshot: no frame from the compositor after {SCREENSHOT_FALLBACK_MS} ms; rendering headlessly");- s.sent_at = None;- s.headless = true;- s.deadline = now + SCREENSHOT_SETTLE_MS;+ if let Some(slot) = shot.slot.take() {+ slot.cancel();+ }+ shot.sent_at_ms = None;+ shot.issued = None;+ shot.headless = true;}- s.frames += 1;- let ready = now >= s.not_before && s.frames >= 3 && (!busy || now > s.deadline);- if s.headless {+ // A busy renderer only defers the capture until the forced instant; after that the+ // settled frame that exists now is captured (0.36's deadline behavior), never an error.+ let ready = shot_ready(now, &shot, busy, self.ui_passes);+ if !ready {+ keep.push(shot);+ continue;+ }+ if shot.headless {// The shadow frame requests the renders the UI needs, even while the window shows nothing.- let img = if ready || !shadow_ticked { self.headless_screenshot(ctx, ready) } else { None };+ let img = if shadow_ticked { None } else { self.headless_screenshot(ctx, true) };shadow_ticked = true;if let Some(img) = img {- let _ = s.reply.send(control::save_screenshot(self, &img, s.path.as_deref()));- return false;+ let bytes = img.size[0].checked_mul(img.size[1]).and_then(|p| p.checked_mul(std::mem::size_of::<egui::Color32>()));+ match bytes {+ Some(bytes) if bytes > shot.reserved => {+ // A stale/undersized reservation is not a user error: grow it to the+ // actual image and encode it when the per-image and aggregate caps allow.+ if let Err(error) = self.grow_shot_reservation(shot.reserved, bytes) {+ let _ = shot.reply.send(serde_json::json!({"ok": false, "error": error}));+ self.release_shot_bytes(shot.reserved);+ continue;+ }+ shot.reserved = bytes;+ }+ Some(_) => {}+ None => {+ let reply = serde_json::json!({+ "ok": false,+ "error": "ui.screenshot: the rendered image has invalid dimensions",+ });+ let _ = shot.reply.send(reply);+ self.release_shot_bytes(shot.reserved);+ continue;+ }+ }+ let _ = shot.reply.send(control::save_screenshot(self, &img, shot.target.as_ref()));+ self.release_shot_bytes(shot.reserved);+ continue;}- true- } else {- if ready {- ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(egui::UserData::new(s.token)));- s.sent_at = Some(now);+ keep.push(shot);+ continue;+ }+ // The compositor path needs a real, laid-out UI and fresh fonts; a queued request on a+ // hidden window is kept alive by RequestPaintWhileHidden from `logic`.+ if !self.fonts_ready || self.ui_passes == 0 {+ keep.push(shot);+ continue;+ }+ // Revalidate the reservation against the geometry the command is actually bound to.+ let Some(bytes) = geometry.bytes(max_side) else {+ let _ = shot.reply.send(serde_json::json!({"ok": false, "error": geometry.rejection(max_side)}));+ self.release_shot_bytes(shot.reserved);+ continue;+ };+ if bytes > shot.reserved {+ if let Err(error) = self.grow_shot_reservation(shot.reserved, bytes) {+ let _ = shot.reply.send(serde_json::json!({"ok": false, "error": error}));+ self.release_shot_bytes(shot.reserved);+ continue;}- true+ shot.reserved = bytes;}- });- shots.append(&mut self.pending_screenshots);- self.pending_screenshots = shots;+ // One slot and one callback per issue; the callback only holds a weak slot and wakes+ // the viewport. File writes and replies happen in `collect_screenshots`.+ let (slot, callback) = craft_ui::capture::CaptureSlot::new(ctx, egui::ViewportId::ROOT, MAX_SHOT_BYTES);+ ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(callback));+ log::debug!("ui.screenshot {}: issued at {:?}, {} bytes reserved", shot.token, geometry.viewport, shot.reserved);+ shot.slot = Some(slot);+ shot.sent_at_ms = Some(now);+ shot.issued = Some(geometry);+ shot.issued_library = library;+ keep.push(shot);+ }+ self.pending_screenshots = keep;if !self.pending_screenshots.is_empty() {ctx.request_repaint_after(std::time::Duration::from_millis(16));}@@ -1037,7 +1521,7 @@ impl LightcraftApp {// same scroll offsets, open sections, style… as the windowlet memory = main.memory(|m| m.clone());view.ctx.memory_mut(|m| *m = memory);- view.run(headless::HeadlessView::raw_input(size, ppp, time, vec![]), |ui| self.ui(ui));+ view.run(headless::HeadlessView::raw_input(size, ppp, time, vec![]), |ui| self.draw_window(ui));let img = capture.then(|| {let mut tex = self.renderer.cpu_textures();if let (Some((t, ..)), Some(px)) = (&self.merge.preview, &self.merge.preview_pixels) {@@ -1049,29 +1533,76 @@ impl LightcraftApp {img}- fn collect_screenshots(&mut self, ctx: &egui::Context) {+ /// Take each completed capture once, reject stale generations before writing anything, and+ /// reply exactly once. A late callback after cancel/drop finds no slot and is inert.+ fn collect_screenshots(&mut self, _ctx: &egui::Context) {if self.pending_screenshots.is_empty() {return;}- let events: Vec<_> = ctx.input(|i| {- i.raw- .events- .iter()- .filter_map(|e| match e {- egui::Event::Screenshot { user_data, image, .. } => {- let token = user_data.data.as_ref().and_then(|d| d.downcast_ref::<u64>()).copied()?;- Some((token, image.clone()))+ let now = self.tick_now_ms();+ let current = self.last_shot_geometry;+ let library = self.shot_document_generation();+ let mut shots = std::mem::take(&mut self.pending_screenshots);+ let mut keep = Vec::with_capacity(shots.len());+ for mut shot in shots.drain(..) {+ let completed = shot.slot.as_ref().and_then(craft_ui::capture::CaptureSlot::take);+ match completed {+ Some(Ok(image)) => {+ let stale =+ shot.issued.is_none_or(|issued| current.is_none_or(|now| now.epoch != issued.epoch)) || shot.issued_library != library;+ if stale {+ // A resize/DPI/zoom or library change between issue and completion: never+ // combine old pixels with new geometry. Retry with a fresh slot.+ shot.slot = None;+ shot.sent_at_ms = None;+ shot.issued = None;+ shot.not_before_ms = now + SHOT_SETTLE_MS;+ keep.push(shot);+ continue;}- _ => None,- })- .collect()- });- for (token, image) in events {- if let Some(i) = self.pending_screenshots.iter().position(|s| s.token == token) {- let s = self.pending_screenshots.remove(i);- let _ = s.reply.send(control::save_screenshot(self, &image, s.path.as_deref()));+ let pixels = image.size[0].checked_mul(image.size[1]).and_then(|p| p.checked_mul(std::mem::size_of::<egui::Color32>()));+ let Some(bytes) = pixels else {+ let reply = serde_json::json!({+ "ok": false,+ "error": "ui.screenshot: the rendered image has invalid dimensions",+ });+ let _ = shot.reply.send(reply);+ self.release_shot_bytes(shot.reserved);+ continue;+ };+ if bytes > shot.reserved {+ // Wayland reports no `inner_rect`, so the reservation can be based on a stale+ // content rect while the compositor returns the new, larger surface. Treat a+ // larger-but-legal image as a stale reservation and grow it; never mix it+ // with geometry of another epoch (checked above).+ if let Err(error) = self.grow_shot_reservation(shot.reserved, bytes) {+ let _ = shot.reply.send(serde_json::json!({"ok": false, "error": error}));+ self.release_shot_bytes(shot.reserved);+ continue;+ }+ shot.reserved = bytes;+ }+ self.release_shot_bytes(shot.reserved);+ let _ = shot.reply.send(control::save_screenshot(self, &image, shot.target.as_ref()));+ }+ Some(Err(error)) => {+ let _ = shot.reply.send(serde_json::json!({"ok": false, "error": error.to_string()}));+ self.release_shot_bytes(shot.reserved);+ }+ None => {+ if now > shot.deadline_ms {+ let _ = shot.reply.send(serde_json::json!({"ok": false, "error": format!("screenshot {} timed out", shot.token)}));+ if let Some(slot) = shot.slot.take() {+ slot.cancel();+ }+ self.release_shot_bytes(shot.reserved);+ } else {+ keep.push(shot);+ }+ }}}+ self.pending_screenshots = keep;}/// The process is about to end (settings and library are saved by then): make sure nothing is@@ -1091,19 +1622,39 @@ impl LightcraftApp {stopped && idle}- /// Per-frame logic before layout (control channel, renders, shortcuts, drops).+ /// Background and queue work. Called before layout on every host pass and, while the window is+ /// hidden, from `Context::run_logic`. It may read the refreshed viewport fields only: never+ /// `i.time`, events, keys or dropped files.pub fn logic(&mut self, ctx: &egui::Context) {i18n::set_language(self.ui.language);- let t0 = now_ms();+ // The fork's AccessKit root language and bidi runs follow the locale; presentation only.+ // Compare against the cached string: `Context::language()` allocates on every call, and+ // this runs on every UI pass and every hidden logic tick.+ let language = self.ui.language.code();+ if self.accesskit_language.as_deref() != Some(language) {+ ctx.set_language(Some(language.to_owned()));+ self.accesskit_language = Some(language.to_owned());+ }+ let t0 = monotonic_ms();+ self.note_max_texture_side(ctx);+ self.note_shot_geometry(ctx);+ self.ensure_fonts(ctx);+ // Applying the theme belongs to logic: a host that only calls `logic` (and every hidden+ // tick) must see an Appearance Mode / system-theme change, and the UI pass that follows+ // then draws with the new visuals. `ui` keeps its own call for a settings change made by+ // a command during the same pass; it is a no-op when the theme already matches.+ self.sync_theme(ctx);panels::library_problem::logic(self);- self.logic_inner(ctx);- self.perf.logic_ms = now_ms() - t0;+ self.logic_background(ctx);+ self.perf.logic_ms = monotonic_ms() - t0;}- fn logic_inner(&mut self, ctx: &egui::Context) {+ /// Install/refresh fonts once and watch the device and availability caches. Setup, not input.+ fn ensure_fonts(&mut self, ctx: &egui::Context) {if !self.styled {theme::install_fonts_with_chinese(ctx, self.chinese_font.as_ref());theme::apply(ctx);+ Self::drop_legacy_panel_state(ctx);// File → Add from Device lists cards scanned in the background: show hot-plugslet repaint = ctx.clone();lightcraft_engine::devices::on_change(move || repaint.request_repaint());@@ -1121,23 +1672,30 @@ impl LightcraftApp {} else {self.fonts_ready = true;}- self.sync_theme(ctx);+ }++ /// 0.36 stored each `PanelState` under the panel's exact `Id`; 0.37 stores it under+ /// `parent_ui.scope_id().with_salt(id_salt)`, so the old entries are unreachable and the+ /// panels reset once by simply not finding them. Remove the old keys anyway so egui memory+ /// does not retain dead entries (no document, workspace JSON, catalog or XMP data is+ /// migrated; nothing above a user's photo edits depends on them).+ fn drop_legacy_panel_state(ctx: &egui::Context) {+ for salt in ["top_bar", "bottom_bar", "tool_strip", "library-problem-banner"] {+ ctx.data_mut(|d| d.remove::<egui::containers::panel::PanelState>(egui::Id::unique(salt)));+ }+ }++ /// Queues and timers. Each consumed queue is drained once per call; time-gated work uses the+ /// monotonic app clock, so a hidden `run_logic` keeps it advancing and a second layout pass is+ /// a no-op rather than a duplicate.+ fn logic_background(&mut self, ctx: &egui::Context) {panels::notices::logic(self);// closing the window (or Quit) with changes only in memory: retry, else ask firstif ctx.input(|i| i.viewport().close_requested()) && !panels::notices::may_close(self) {ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);}- // (once a frame: a pass drawn again after a discard has no input of its own, and still the- // widgets of the pass thrown away, where a request would find them out of place)- if ctx.current_pass_index() == 0 {- let now = ctx.input(|i| i.time);- let dt = now - self.last_time;- if dt > 0.0 {- self.perf.fps = self.perf.fps * 0.9 + (1.0 / dt).min(240.0) * 0.1;- }- self.last_time = now;- self.drain_control(ctx);- }+ let now = self.tick_now();+ self.drain_control(ctx);self.apply_settings(ctx);if !self.synthetic.is_empty() {ctx.request_repaint();@@ -1147,31 +1705,29 @@ impl LightcraftApp {import::poll_scan(self, ctx);sync::poll(self, ctx);sync::poll_run(self, ctx);- import::tick(self, ctx);+ // Import commits batches and must not run twice in one host frame. The first layout pass+ // and a hidden logic tick both report pass index 0; a second pass reports 1. A wall-clock+ // gate cannot express that (a slow discarded first pass would re-run it).+ if import_tick_allowed(ctx) {+ import::tick(self, ctx);+ }lightroom_import::tick(self, ctx);recheck::tick(self);tasks::poll(self, ctx);self.preview_build_status(ctx);self.save_status(ctx);- self.slideshow_tick(ctx);- panels::faces::pump(self, ctx);- // back from an external editor: pick up the files it saved- let focused = ctx.input(|i| i.focused);- if focused && !self.ui.was_focused && !self.ui.external_edits.is_empty() {- let ids = self.ui.external_edits.clone();- if let Ok(r) = self.session.execute("photo.reload", &serde_json::json!({"ids": ids}))- && r["reloaded"].as_array().is_some_and(|a| !a.is_empty())- {- self.toast(ctx, crate::i18n::tr("Updated the edits saved in the external editor"));- }- }- self.ui.was_focused = focused;+ self.ai_mask_detail(ctx, now);+ self.place_names_outcome(ctx);+ self.slideshow_tick(ctx, now);+ panels::denoise::pump_background(self, ctx, now);+ panels::faces::pump_background(self, ctx, now);+ model_setup::pump(self, ctx, now);+ focus_scan::pump(self, ctx, now);// auto import: list the watched folder every few seconds (on a worker thread: it may be on// a network share), then import what's new like any import (also on a worker thread)#[cfg(not(target_arch = "wasm32"))]if let Some(folder) = self.session.import_defaults.auto_folder.clone() {const LABEL: &str = "Auto Import";- let now = ctx.input(|i| i.time);if now - self.ui.auto_import_at >= 3.0&& self.import.is_none()&& self.sync_run.is_none()@@ -1208,7 +1764,6 @@ impl LightcraftApp {#[cfg(not(target_arch = "wasm32"))]{if self.session.unsaved_sidecars() > 0 {- let now = ctx.input(|i| i.time);if now - self.ui.sidecar_retry_at >= 10.0 {self.ui.sidecar_retry_at = now;self.session.retry_unsaved_sidecars();@@ -1241,19 +1796,79 @@ impl LightcraftApp {self.ui.known_cards = None;}self.session.persist_if_dirty();- panels::denoise::pump(self, ctx);- model_setup::pump(self, ctx);- panels::faces::pump(self, ctx);- focus_scan::pump(self, ctx);+ self.expire_gestures();self.collect_screenshots(ctx);self.issue_screenshots(ctx);+ self.request_paint_while_hidden(ctx);+ }++ /// While hidden, queued captures and an injected gesture step need a real UI pass; a pending+ /// screenshot command paints by itself once issued.+ fn request_paint_while_hidden(&self, ctx: &egui::Context) {+ // `logic` runs per layout pass; one command per host frame is enough.+ if ctx.current_pass_index() != 0 {+ return;+ }+ // `ViewportInfo::visible()`: minimized or fully occluded is `Some(false)`; `None`+ // (headless, `RawInput::default()`) is normal and must not be treated as hidden.+ let hidden = ctx.input(|i| i.viewport().visible() == Some(false));+ if hidden && self.needs_ui_pass_while_hidden() {+ ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaintWhileHidden);+ }+ }++ /// A hidden window needs a real UI pass for queued/settling captures, for control gestures+ /// that still have to resolve or deliver, and for an injected synthetic step. An already+ /// issued screenshot has its own compositor-driven paint and must not request another+ /// `RequestPaintWhileHidden`; its fallback and timeout keep running from `logic`.+ fn needs_ui_pass_while_hidden(&self) -> bool {+ !self.pending_gestures.is_empty()+ || self.pending_screenshots.iter().any(|shot| shot.sent_at_ms.is_none())+ || !self.synthetic.is_empty()+ || self.synthetic_in_flight+ }++ /// Input, layout and setup for a known UI phase: at most once per host frame, and never from a+ /// hidden logic tick. `current_pass_index() == 0` is the first pass of this `run_ui`; a second+ /// pass has empty events.+ fn ui_pass(&mut self, ctx: &egui::Context) {+ if ctx.current_pass_index() != 0 {+ return;+ }+ let now = self.tick_now();+ // the last pass's time is fine here: this is a UI phase, not a hidden tick+ let t = ctx.input(|i| i.time);+ let dt = t - self.last_time;+ if dt > 0.0 {+ self.perf.fps = self.perf.fps * 0.9 + (1.0 / dt).min(240.0) * 0.1;+ }+ self.last_time = t;+ panels::denoise::pump_ui_input(self, ctx, now);+ panels::faces::pump_ui_input(self, ctx, now);+ self.import_dropped_files(ctx);+ self.check_external_editor(ctx);if self.fonts_ready {shortcuts::handle(self, ctx);}+ }++ /// Take the host's dropped files, exactly once. The queue is filled by `raw_input_hook`, so a+ /// hidden logic tick can never replay the last pass's drop. Web hosts call this in their UI+ /// phase (they need `bytes_async`, which is not available on a native file path).+ pub fn take_dropped_files(&mut self) -> Vec<egui::DroppedFileHandle> {+ std::mem::take(&mut self.dropped_files)+ }++ /// Import native drops as presets, face models or photos.+ fn import_dropped_files(&mut self, ctx: &egui::Context) {+ let dropped = self.take_dropped_files();+ if dropped.is_empty() {+ return;+ }#[cfg(not(target_arch = "wasm32"))]{let dropped: Vec<String> =- ctx.input(|i| i.raw.dropped_files.iter().map(|f| f.path().to_string_lossy().to_string()).filter(|p| !p.is_empty()).collect());+ dropped.iter().map(|f| egui::DroppedFile::path(f.as_ref()).to_string_lossy().to_string()).filter(|p| !p.is_empty()).collect();// preset files import as presets, everything else as photos// a dropped face model opens its licence dialog; presets and photos as beforelet (models, dropped): (Vec<String>, Vec<String>) = dropped.into_iter().partition(|p| is_model_file(p));@@ -1275,6 +1890,33 @@ impl LightcraftApp {}}}+ // The browser host (`lightcraft-web`'s `WebApp::ui`) consumes the same app queue first+ // because it needs `bytes_async`; a future wasm host must do the same, not call this and+ // silently discard the drops.+ #[cfg(target_arch = "wasm32")]+ let _ = (dropped, ctx);+ }++ /// A file dropped by the host, kept for the next UI pass (web hosts consume their own queue).+ fn queue_dropped_files(&mut self, raw: &mut egui::RawInput) {+ if !raw.dropped_files.is_empty() {+ self.dropped_files.append(&mut raw.dropped_files);+ }+ }++ /// Back from an external editor: pick up the files it saved. Reads `i.focused`, which+ /// `run_logic` does not refresh, so it belongs to the UI phase.+ fn check_external_editor(&mut self, ctx: &egui::Context) {+ let focused = ctx.input(|i| i.focused);+ if focused && !self.ui.was_focused && !self.ui.external_edits.is_empty() {+ let ids = self.ui.external_edits.clone();+ if let Ok(r) = self.session.execute("photo.reload", &serde_json::json!({"ids": ids}))+ && r["reloaded"].as_array().is_some_and(|a| !a.is_empty())+ {+ self.toast(ctx, crate::i18n::tr("Updated the edits saved in the external editor"));+ }+ }+ self.ui.was_focused = focused;}/// Apply settings that act outside the UI state: GPU rendering and window full screen.@@ -1331,8 +1973,8 @@ impl LightcraftApp {/// While no display profile is chosen, show previews through the profile of the screen the/// window is on (`services.screen_profile`), read about once a second so moving the window to/// another screen is followed. Without the service (or a profile) the display is sRGB.- fn follow_screen_profile(&mut self, ctx: &egui::Context) {- let now = ctx.input(|i| i.time);+ fn follow_screen_profile(&mut self, _ctx: &egui::Context) {+ let now = self.tick_now();if self.services.screen_profile.is_none() || self.screen_profile_read.is_some_and(|t| (0.0..1.0).contains(&(now - t))) {return;}@@ -1359,8 +2001,20 @@ impl LightcraftApp {self.screen_profile = icc;}- /// Inject synthetic events (pointer events one per frame; key sequences up to the release).+ /// Take the host's dropped files once and inject synthetic events (pointer events one per+ /// frame; key sequences up to the release).+ ///+ /// The hook also runs before a hidden logic-only tick, so it injects at most one batch and+ /// keeps that batch in flight until a completed UI pass consumed it. It never injects while+ /// the fonts are not installed (the pass would draw nothing and the events would be lost).pub fn raw_input_hook(&mut self, raw: &mut egui::RawInput) {+ self.queue_dropped_files(raw);+ if !self.fonts_ready || self.synthetic_in_flight {+ return;+ }+ if self.drop_gestures_stale_before_injection() {+ return;+ }// the frame after a synthetic release / key: modifiers back upif std::mem::take(&mut self.synthetic_mods_release) && self.synthetic_mods != egui::Modifiers::NONE {self.synthetic_mods = egui::Modifiers::NONE;@@ -1373,7 +2027,9 @@ impl LightcraftApp {egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } | egui::Event::MouseWheel { .. } => 1,_ => self.synthetic.iter().position(|e| matches!(e, egui::Event::Key { pressed: false, .. })).map_or(self.synthetic.len(), |i| i + 1),};- if let Some(egui::Event::PointerMoved(p) | egui::Event::PointerButton { pos: p, .. }) = self.synthetic.first() {+ // A press needs the pointer at its position before the button event; the move that is+ // itself the first event is delivered by the drain below, so it must not be sent twice.+ if let Some(egui::Event::PointerButton { pos: p, .. }) = self.synthetic.first() {raw.events.push(egui::Event::PointerMoved(*p));}// egui's `input.modifiers` follow `ModifiersChanged` events, not the modifiers carried by@@ -1392,6 +2048,12 @@ impl LightcraftApp {self.synthetic_mods_release = ends;}raw.events.extend(self.synthetic.drain(..n));+ if let Some(head) = self.head_gesture() {+ let gesture = &mut self.pending_gestures[head];+ gesture.started = true;+ gesture.remaining_events = gesture.remaining_events.saturating_sub(n);+ }+ self.synthetic_in_flight = true;}/// Lights Out: veil everything but the photo (the loupe's image, or the grid / Compare /@@ -1404,7 +2066,7 @@ impl LightcraftApp {let screen = ctx.content_rect();let keep = if self.ui.view == state::ViewMode::Detail { self.image_rect.or(self.canvas_rect) } else { self.canvas_rect };let veil = egui::Color32::from_black_alpha((a.clamp(0.0, 1.0) * 255.0).round() as u8);- let p = ctx.layer_painter(egui::LayerId::new(egui::Order::Middle, egui::Id::new("lights-out")));+ let p = ctx.layer_painter(egui::LayerId::new(egui::Order::Middle, egui::Id::unique("lights-out")));let k = keep.unwrap_or(egui::Rect::NOTHING).intersect(screen);if !k.is_positive() {p.rect_filled(screen, 0.0, veil);@@ -1427,7 +2089,7 @@ impl LightcraftApp {}}});- self.perf.frame_ms = now_ms() - t0;+ self.perf.frame_ms = monotonic_ms() - t0;self.perf.update_ms = self.perf.logic_ms + self.perf.frame_ms;self.perf.max_update_ms = self.perf.max_update_ms.max(self.perf.update_ms);}@@ -1455,7 +2117,8 @@ impl LightcraftApp {}}- /// Lay out the whole window.+ /// Lay out the whole window: input/setup for the known UI phase, then presentation, then the+ /// frame bookkeeping. A hidden `run_logic` never reaches this.pub fn ui(&mut self, ui: &mut egui::Ui) {i18n::set_language(self.ui.language);let ctx = ui.ctx().clone();@@ -1463,16 +2126,39 @@ impl LightcraftApp {ctx.request_repaint();return;}+ self.sync_theme(&ctx);+ self.ui_pass(&ctx);+ self.draw_window(ui);+ self.finish_ui_pass(&ctx);+ }++ /// A completed, nondiscarded pass is a settled frame; a discarded pass threw its widgets away+ /// and must not advance the geometry generation a capture binds to.+ fn finish_ui_pass(&mut self, ctx: &egui::Context) {+ // Any pass consumed the injected batch; a discarded pass still read its events and the+ // next pass has none. Only a nondiscarded pass, however, is a settled frame a capture may+ // bind to and a control gesture may resolve against.+ self.synthetic_in_flight = false;+ if ctx.will_discard() {+ return;+ }+ self.ui_passes = self.ui_passes.wrapping_add(1);+ self.layout_epoch = self.layout_epoch.wrapping_add(1);+ self.resolve_pending_gestures(ctx);+ self.reply_delivered_gestures();+ }++ /// Presentation only: the window's panels, dialogs and overlays.+ fn draw_window(&mut self, ui: &mut egui::Ui) {+ let ctx = ui.ctx().clone();panels::dialogs::prepare(self, ui);- let t0 = now_ms();+ let t0 = monotonic_ms();if std::mem::take(&mut self.ui.quit) {ctx.send_viewport_cmd(egui::ViewportCommand::Close);}self.library_changed(&ctx);// panels set it again this frame while the pointer rests on a preset or profileself.hover_preview = None;- self.ai_mask_detail(&ctx);- self.place_names_outcome(&ctx);if self.ui.fullscreen {// full-screen preview: the photo alone on blackegui::CentralPanel::default()@@ -1516,25 +2202,197 @@ impl LightcraftApp {}}-/// How long a screenshot waits for in-flight renders.+/// How long a screenshot waits for in-flight renders before it is captured anyway (and the+/// headless fallback's settle budget).const SCREENSHOT_SETTLE_MS: f64 = 3000.0;/// How long a windowed screenshot waits for the compositor before falling back to headless.const SCREENSHOT_FALLBACK_MS: f64 = 2000.0;+/// Screenshots admitted at once (queued, issued and completed-but-undrained).+const MAX_PENDING_SHOTS: usize = 4;+/// Bytes one screenshot image may use.+const MAX_SHOT_BYTES: usize = 128 * 1024 * 1024;+/// Bytes all pending/completed screenshots may reserve together.+const MAX_SHOT_TOTAL_BYTES: usize = 256 * 1024 * 1024;+/// Slack for PNG framing and deflate overhead while encoding one screenshot. zlib can exceed the+/// raw bytes slightly for incompressible input; this bounds that transient honestly.+const SHOT_ENCODE_SLACK_BYTES: usize = 64 * 1024;+/// Peak working set of capture encoding: every reserved image (≤ [`MAX_SHOT_TOTAL_BYTES`]) plus,+/// for the image being written, its `Rgba8` copy and encoded PNG (each ≤ [`MAX_SHOT_BYTES`] plus+/// [`SHOT_ENCODE_SLACK_BYTES`]). Encoding runs on the UI thread, one image at a time.+const MAX_SHOT_WORKING_SET_BYTES: usize = MAX_SHOT_TOTAL_BYTES + 2 * MAX_SHOT_BYTES + SHOT_ENCODE_SLACK_BYTES;+const _: () = {+ assert!(MAX_SHOT_WORKING_SET_BYTES > MAX_SHOT_TOTAL_BYTES);+ assert!(SHOT_ENCODE_SLACK_BYTES > 0);+};+/// Synthetic-input control requests waiting for a fresh layout/delivery at once.+const MAX_PENDING_GESTURES: usize = 32;+/// A control gesture is answered with an error after this long without a completed UI pass and+/// delivery (milliseconds).+const GESTURE_TIMEOUT_MS: f64 = 5000.0;+/// Completed UI frames a request waits for before it is issued (a settled, laid-out frame).+const SHOT_SETTLE_FRAMES: u64 = 3;+/// Time a request waits before it is issued, so a control command that triggered a layout change+/// is not captured mid-change.+const SHOT_SETTLE_MS: f64 = 120.0;+/// A settled capture is issued at this instant even while renders are still in flight. The hard+/// admission deadline below still leaves the compositor fallback and the headless settle after it.+const SHOT_FORCE_BUSY_MS: f64 = SCREENSHOT_SETTLE_MS;+/// The texture limit when the host has not reported one.+const MAX_TEXTURE_SIDE: usize = 16_384;++/// The viewport geometry a screenshot was issued for. A completion from an older generation is+/// rejected even if the window has since returned to the same size.+#[derive(Clone, Copy, Debug, PartialEq)]+struct ShotGeometry {+ /// Viewport size in egui points (the same units as `content_rect`).+ viewport: egui::Vec2,+ /// Egui pixels per point, including UI zoom.+ pixels_per_point: f32,+ /// The UI zoom factor.+ zoom: f32,+ /// [`LightcraftApp::shot_geometry_epoch`] at issue.+ epoch: u64,+}++impl ShotGeometry {+ /// The surface pixels this geometry would produce, before the host's texture limit.+ fn surface_pixels(self) -> Option<(usize, usize)> {+ let w = (self.viewport.x * self.pixels_per_point).round();+ let h = (self.viewport.y * self.pixels_per_point).round();+ if !w.is_finite() || !h.is_finite() || w < 1.0 || h < 1.0 {+ return None;+ }+ Some((w as usize, h as usize))+ }++ /// The surface pixels this geometry can produce, or `None` when it is not a usable surface or+ /// exceeds one side of the host's texture limit.+ fn pixels(self, max_texture_side: usize) -> Option<(usize, usize)> {+ let (w, h) = self.surface_pixels()?;+ (w <= max_texture_side && h <= max_texture_side).then_some((w, h))+ }++ /// Checked `width * height * 4` bytes for this geometry.+ fn bytes(self, max_texture_side: usize) -> Option<usize> {+ let (w, h) = self.pixels(max_texture_side)?;+ w.checked_mul(h)?.checked_mul(std::mem::size_of::<egui::Color32>())+ }++ /// Why [`Self::bytes`] returned `None`: no laid-out surface, or one side over the host's limit.+ /// The two are not the same user action (a driver/GL limit is not "the window has not drawn").+ fn rejection(self, max_texture_side: usize) -> String {+ match self.surface_pixels() {+ None => "ui.screenshot: the window has no usable surface size yet (no frame has been laid out)".to_string(),+ Some((w, h)) => format!("ui.screenshot: the {w}×{h} pixel surface is over the host's {max_texture_side}-pixel per-side texture limit"),+ }+ }+}++/// Import commits batches at most once per host frame. The first layout pass and a hidden+/// `run_logic` tick both report pass index 0; a discarded frame's later passes report 1+. A+/// wall-clock gate cannot express that (a slow first pass could re-run it within one frame).+fn import_tick_allowed(ctx: &egui::Context) -> bool {+ ctx.current_pass_index() == 0+}++/// Whether a pending request may be issued now: it has waited for the settle time and completed+/// UI frames, and either no render is in flight or the forced-capture instant has passed.+fn shot_ready(now_ms: f64, shot: &PendingShot, busy: bool, ui_passes: u64) -> bool {+ let settled = ui_passes.saturating_sub(shot.admitted_passes) >= SHOT_SETTLE_FRAMES && now_ms >= shot.not_before_ms;+ settled && (!busy || now_ms >= shot.force_ms)+}++/// The navigation/document/modal/panel state a gesture was admitted under. The same automation+/// id can mean a different control after any of these changes; the request is canceled rather+/// than retargeted.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+struct GestureFrame {+ view: crate::state::ViewMode,+ active: Option<lightcraft_catalog::PhotoId>,+ library: u64,+ dialog: Option<std::mem::Discriminant<crate::state::Dialog>>,+ left_panel: bool,+ right: crate::state::RightPanel,+ presets: bool,+ filmstrip: bool,+}++/// A synthetic-input control request waiting for a fresh layout and for its last event to be+/// consumed by a completed UI pass.+struct PendingGesture {+ method: String,+ params: Value,+ reply: Sender<ControlResponse>,+ /// [`LightcraftApp::layout_epoch`] at admission; resolution needs a later one.+ admitted_epoch: u64,+ frame: GestureFrame,+ /// Monotonic deadline (milliseconds).+ deadline_ms: f64,+ /// [`LightcraftApp::ui_passes`] when the events were queued (`None`: not resolved yet).+ resolved_pass: Option<u64>,+ /// Synthetic events queued for this gesture that the host has not injected yet.+ remaining_events: usize,+ /// At least one batch of this gesture's events has reached a pass. Later batches may see the+ /// gesture's own effect (a first click selects, the second opens), so freshness is only+ /// checked before the first one.+ started: bool,+ result: Value,+}/// A `ui.screenshot` request in progress.struct PendingShot {token: u64,- path: Option<String>,+ /// Destination identity pinned at admission (revalidated immediately before the write).+ target: Option<lightcraft_engine::originals::WriteTarget>,reply: Sender<ControlResponse>,headless: bool,- not_before: f64,- deadline: f64,- frames: u32,+ /// Admitted UI pass count and monotonic deadlines (milliseconds).+ admitted_passes: u64,+ not_before_ms: f64,+ /// At this instant a busy renderer no longer holds the capture back.+ force_ms: f64,+ deadline_ms: f64,/// When the viewport screenshot command went out.- sent_at: Option<f64>,+ sent_at_ms: Option<f64>,+ /// Bytes this request reserves until it is drained or cancelled.+ reserved: usize,+ /// The one-shot completion slot; only the app owns the strong reference.+ slot: Option<craft_ui::capture::CaptureSlot>,+ /// The geometry and document generation the issued command was bound to.+ issued: Option<ShotGeometry>,+ /// Library generation at issue (a different library changed mid-capture).+ issued_library: u64,+}++/// A monotonic clock for the app's own timers.+///+/// `web_time::Instant` is backed by the browser's `performance.now()` on WASM and by+/// `std::time::Instant` natively: it never jumps with the wall clock and has no `Date.now()`+/// zero-origin problem. A headless host may supply its simulated time instead.+#[derive(Clone, Copy, Debug)]+struct AppClock {+ start: web_time::Instant,+ simulated: Option<f64>,+}++impl AppClock {+ fn new() -> Self {+ Self { start: web_time::Instant::now(), simulated: None }+ }++ fn now(&self) -> f64 {+ self.simulated.unwrap_or_else(|| self.start.elapsed().as_secs_f64())+ }+}++/// Monotonic milliseconds since the first call, for durations and deadlines.+pub fn monotonic_ms() -> f64 {+ static START: std::sync::OnceLock<web_time::Instant> = std::sync::OnceLock::new();+ START.get_or_init(web_time::Instant::now).elapsed().as_secs_f64() * 1000.0}-/// Wall-clock milliseconds since the Unix epoch (`web-time` maps to `Date.now()` on the web).+/// Wall-clock milliseconds since the Unix epoch, only for names that must be unique in the world+/// (`library-restored-<ms>`), never for timing or deadlines.pub fn now_ms() -> f64 {use web_time::{SystemTime, UNIX_EPOCH};SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs_f64() * 1000.0).unwrap_or(0.0)diff --git a/crates/ui-egui/src/menu_level.rs b/crates/ui-egui/src/menu_level.rsindex 96ff422f4..70a5f9fd5 100644--- a/crates/ui-egui/src/menu_level.rs+++ b/crates/ui-egui/src/menu_level.rs@@ -16,7 +16,7 @@ const EDGE: f32 = 6.0;const SPEED: f32 = 600.0;fn anchor_id(depth: usize) -> Id {- Id::new(("lc-menu-anchor", depth))+ Id::unique(("lc-menu-anchor", depth))}/// Remember the row the submenu at `depth` (2 = a top-level menu's submenu) hangs from. It is@@ -76,7 +76,7 @@ pub fn level(ui: &mut Ui, depth: usize, bar_bottom: Option<f32>, rows: impl FnOnlet screen = ctx.content_rect();// The menu frame's margin and stroke around the rows.let frame = ui.spacing().menu_margin.sum().y + 2.0;- let key = ui.id().with(("lc-menu-level", depth));+ let key = ui.scope_id().with(("lc-menu-level", depth));// Rows' height from the last frame: does this level overflow?let content: Option<f32> = ctx.data(|d| d.get_temp(key));let room = level_room(screen, bar_bottom, depth, anchor(&ctx, depth), content, frame);@@ -89,13 +89,19 @@ pub fn level(ui: &mut Ui, depth: usize, bar_bottom: Option<f32>, rows: impl FnOn// No scrollbar: the ▲ / ▼ strips, the wheel and dragging scroll a menu, like native menus.// egui's floating bar is drawn over the rows' right edge, where the shortcut text ends, and in// its wide (hovered) state its background hides the last character (issue #691).- let out = egui::ScrollArea::vertical()+ // 0.37's `ScrollAreaState.offset` is private: a scroll requested after layout is applied as+ // the next frame's start offset instead of writing the state directly.+ let scroll_to = ctx.data_mut(|d| d.remove_temp::<f32>(key.with("scroll-to")));+ let mut area = egui::ScrollArea::vertical().id_salt(("menu-level", depth)).max_height(height).min_scrolled_height(height).scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden)- .scroll_source(egui::containers::scroll_area::ScrollSource::ALL)- .show(ui, rows);+ .scroll_source(egui::containers::scroll_area::ScrollSource::ALL);+ if let Some(y) = scroll_to {+ area = area.vertical_scroll_offset(y);+ }+ let out = area.show(ui, rows);let down = over.then(|| ui.allocate_exact_size(vec2(0.0, ARROW), Sense::hover()).0);ctx.data_mut(|d| d.insert_temp(key, out.content_size.y));crate::widgets::register(&ctx, format!("menu-level:{depth}"), ui.min_rect());@@ -103,7 +109,7 @@ pub fn level(ui: &mut Ui, depth: usize, bar_bottom: Option<f32>, rows: impl FnOnlet t = crate::theme::Tokens::get(&ctx);let x = ui.min_rect().x_range();let max = (out.content_size.y - out.inner_rect.height()).max(0.0);- let offset = out.state.offset.y;+ let offset = out.state.clamped_offset().y;let dt = ctx.input(|i| i.stable_dt).clamp(0.0, 0.1);let mut target = offset;for (strip, dir, live) in [(up, -1.0, offset > 0.5), (down, 1.0, offset < max - 0.5)] {@@ -118,7 +124,7 @@ pub fn level(ui: &mut Ui, depth: usize, bar_bottom: Option<f32>, rows: impl FnOnlet id = key.with(dir < 0.0);let r = ui.interact(strip, id, Sense::hover());r.widget_info(|| {- egui::WidgetInfo::labeled(egui::WidgetType::Button, live, crate::i18n::tr(if dir < 0.0 { "Scroll menu up" } else { "Scroll menu down" }))+ egui::WidgetInfo::labeled(egui::Role::Button, live, crate::i18n::tr(if dir < 0.0 { "Scroll menu up" } else { "Scroll menu down" }))});if live && pointer_on(ui, strip) {target = (offset + dir * SPEED * dt.max(1.0 / 120.0)).clamp(0.0, max);@@ -132,10 +138,9 @@ pub fn level(ui: &mut Ui, depth: usize, bar_bottom: Option<f32>, rows: impl FnOn}}}- if target != offset {- let mut st = out.state;- st.offset.y = target;- st.store(&ctx, out.id);+ if (target - offset).abs() > 0.01 {+ ctx.data_mut(|d| d.insert_temp(key.with("scroll-to"), target));+ ctx.request_repaint();}}diff --git a/crates/ui-egui/src/menubar.rs b/crates/ui-egui/src/menubar.rsindex f315b105a..18b68b9d3 100644--- a/crates/ui-egui/src/menubar.rs+++ b/crates/ui-egui/src/menubar.rs@@ -985,7 +985,7 @@ pub fn show_in_window(app: &mut LightcraftApp, ui: &mut egui::Ui, max_width: f32/// Returns the menu whose title was just clicked right after a hover opened it.fn switch_open_title(ctx: &egui::Context, titles: &[egui::Response]) -> Option<egui::Id> {let popup = egui::Popup::default_response_id;- let key = egui::Id::new("lc-menubar-hover-opened");+ let key = egui::Id::unique("lc-menubar-hover-opened");let open = titles.iter().position(|r| egui::Popup::is_id_open(ctx, popup(r)));// the menu a hover opened, until it closes or is clickedlet mut confirmed = None;diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 747cfbccb..5fde24d94 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -656,8 +656,9 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option<Re} else if app.ui.keyword_painter.is_some() {app.ui.keyword_painter = None;} else if app.ui.fullscreen {- app.ui.fullscreen = false;- app.ui.slideshow = None;+ // Through `slideshow::end`: it also releases the held slide textures. Clearing the+ // two fields directly left every rendered slide in the renderer.+ crate::panels::slideshow::end(app);} else if !app.ui.tool.is_empty() {app.ui.tool.clear();} else if app.ui.right == RightPanel::Crop && app.ui.view == ViewMode::Detail {@@ -681,7 +682,7 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option<Re}"view.slideshow" => {// the photos in view, full screen, with the playback settings (see panels::slideshow)- let now = ctx.input(|i| i.time);+ let now = app.tick_now();let r = crate::panels::slideshow::start(app, p, now);if r.is_ok() {app.toast(&ctx, crate::i18n::tr("Slideshow · Space pauses · Esc ends"));@@ -689,7 +690,7 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option<Rer}"slideshow.togglePause" | "slideshow.next" | "slideshow.previous" | "slideshow.end" => {- let now = ctx.input(|i| i.time);+ let now = app.tick_now();crate::panels::slideshow::command(app, id, now)}"view.slideshowOptions" => {diff --git a/crates/ui-egui/src/model_setup.rs b/crates/ui-egui/src/model_setup.rsindex bb088eaa9..47cdfe1eb 100644--- a/crates/ui-egui/src/model_setup.rs+++ b/crates/ui-egui/src/model_setup.rs@@ -118,7 +118,7 @@ fn abandoned(app: &mut LightcraftApp) -> bool {!v["downloads"].as_array().into_iter().flatten().any(|d| matches!(d["state"].as_str(), Some("running" | "done" | "installing" | "installed")))}-pub(crate) fn pump(app: &mut LightcraftApp, ctx: &egui::Context) {+pub(crate) fn pump(app: &mut LightcraftApp, ctx: &egui::Context, now: f64) {if app.model_setup.denoise.is_none() {return;}@@ -132,7 +132,6 @@ pub(crate) fn pump(app: &mut LightcraftApp, ctx: &egui::Context) {ctx.request_repaint_after(std::time::Duration::from_millis(250));return;}- let now = ctx.input(|i| i.time);if now < app.model_setup.next_check {return;}diff --git a/crates/ui-egui/src/panels/activity.rs b/crates/ui-egui/src/panels/activity.rsindex 2e4137fda..32e079555 100644--- a/crates/ui-egui/src/panels/activity.rs+++ b/crates/ui-egui/src/panels/activity.rs@@ -73,7 +73,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {let mut cancel = None;let mut toggle = false;let frame = egui::Frame::NONE.fill(t.chrome).stroke(Stroke::new(1.0, t.field_border)).corner_radius(6).inner_margin(Margin::same(MARGIN));- egui::Area::new(egui::Id::new("activity-stack")).order(egui::Order::Middle).fixed_pos(pos2(8.0, t.top_bar_h + 8.0)).show(ctx, |ui| {+ egui::Area::new(egui::Id::unique("activity-stack")).order(egui::Order::Middle).fixed_pos(pos2(8.0, t.top_bar_h + 8.0)).show(ctx, |ui| {// An area lays out in the size it had last frame, and the scroll area would take that as all the room there// is: the stack would never grow when rows are added. Give it the whole height below the top bar instead// (the scroll area keeps to `max_height`).diff --git a/crates/ui-egui/src/panels/bottombar.rs b/crates/ui-egui/src/panels/bottombar.rsindex 69b76bcb8..226ac9aa8 100644--- a/crates/ui-egui/src/panels/bottombar.rs+++ b/crates/ui-egui/src/panels/bottombar.rs@@ -146,7 +146,7 @@ fn centre(app: &mut LightcraftApp, ui: &mut egui::Ui, full: Rect, from: f32, to:return;}let copy_r = Rect::from_min_size(pos2(pill.right() + 10.0, pill.top()), vec2(copy_width, 30.0));- let cresp = ui.interact(copy_r, egui::Id::new("copy-settings"), Sense::click());+ let cresp = ui.interact(copy_r, egui::Id::unique("copy-settings"), Sense::click());crate::widgets::announce(&cresp, label.to_string());register(ui.ctx(), "button:copySettings", copy_r);ui.painter().rect_filled(copy_r, 15.0, if cresp.hovered() { t.hover } else { t.canvas });@@ -157,7 +157,7 @@ fn centre(app: &mut LightcraftApp, ui: &mut egui::Ui, full: Rect, from: f32, to:app.toast(ui.ctx(), crate::i18n::tr(msg));}let gear_r = Rect::from_min_size(pos2(copy_r.right() + 4.0, pill.top()), vec2(30.0, 30.0));- let gresp = ui.interact(gear_r, egui::Id::new("copy-gear"), Sense::click());+ let gresp = ui.interact(gear_r, egui::Id::unique("copy-gear"), Sense::click());crate::widgets::announce(&gresp, crate::i18n::tr("Copy Settings…"));register(ui.ctx(), "icon:copyGear", gear_r);ui.painter().rect_filled(gear_r, 15.0, if gresp.hovered() { t.hover } else { t.canvas });@@ -368,7 +368,8 @@ mod visual_regressions {harness.run_steps(4);let stem = format!("lightcraft-bottom-{view:?}-{width}-{scale}x");harness.render().unwrap().save(directory.join(format!("{stem}.png"))).unwrap();- let panel = egui::containers::panel::PanelState::load(&harness.ctx, egui::Id::new("bottom_bar")).unwrap().outer_rect;+ let panel_id = harness.ctx.viewport_id().root_ui_id().with("bottom_bar");+ let panel = egui::containers::panel::PanelState::load(&harness.ctx, panel_id).unwrap().outer_rect;let controls: serde_json::Map<String, serde_json::Value> = crate::widgets::take_registry(&harness.ctx).into_iter().map(|(id, r)| (id, json!([r.left(), r.top(), r.width(), r.height()])))diff --git a/crates/ui-egui/src/panels/chips.rs b/crates/ui-egui/src/panels/chips.rsindex 3a8f0ce8e..e66244447 100644--- a/crates/ui-egui/src/panels/chips.rs+++ b/crates/ui-egui/src/panels/chips.rs@@ -101,7 +101,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, chips: &[FilterChip]) {let text_r = Rect::from_min_max(r.min, pos2(r.right() - 22.0, r.max.y));ui.painter().with_clip_rect(text_r).text(pos2(r.left() + 10.0, r.center().y), egui::Align2::LEFT_CENTER, &label, font.clone(), t.text);let xr = Rect::from_center_size(pos2(r.right() - 12.0, r.center().y), vec2(18.0, 18.0));- let resp = ui.interact(xr, egui::Id::new(("filter-chip-x", i)), Sense::click()).on_hover_text(crate::i18n::tr("Remove this filter"));+ let resp = ui.interact(xr, egui::Id::unique(("filter-chip-x", i)), Sense::click()).on_hover_text(crate::i18n::tr("Remove this filter"));crate::widgets::announce(&resp, format!("{}: {label}", crate::i18n::tr("Remove this filter")));register(ui.ctx(), format!("chip:{i}"), xr);let col = if resp.hovered() { t.text } else { t.text_dim };diff --git a/crates/ui-egui/src/panels/compare.rs b/crates/ui-egui/src/panels/compare.rsindex bb7937640..2280c2241 100644--- a/crates/ui-egui/src/panels/compare.rs+++ b/crates/ui-egui/src/panels/compare.rs@@ -200,7 +200,7 @@ fn area_and_filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui) -> Rect {fn photo_tile(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, slot: Slot, area: Rect, label: &str, zoom: Zoom) -> (Rect, egui::Response) {let t = Tokens::get(ui.ctx());let ppp = ui.ctx().pixels_per_point();- let resp = ui.interact(area, egui::Id::new(("cull-tile", slot_index(slot), id.0)), Sense::click_and_drag());+ let resp = ui.interact(area, egui::Id::unique(("cull-tile", slot_index(slot), id.0)), Sense::click_and_drag());crate::widgets::announce(&resp, app.session.catalog.photo(id).map(|p| p.file_name.clone()).unwrap_or_default());let Some(photo) = app.session.catalog.photo(id).cloned() else { return (area, resp) };let caption_h = 26.0;@@ -306,7 +306,7 @@ fn photo_tile(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, slot: Slolet now = ui.input(|i| i.time);// (the wait belongs to the photo in the pane: one moved in starts its own)let rendering = ui.ctx().data_mut(|d| {- let (photo, wait) = d.get_temp_mut_or(egui::Id::new(("compare-rendering", i)), (id, None));+ let (photo, wait) = d.get_temp_mut_or(egui::Id::unique(("compare-rendering", i)), (id, None));if *photo != id {(*photo, *wait) = (id, None);}@@ -572,7 +572,7 @@ pub fn show_survey(app: &mut LightcraftApp, ui: &mut egui::Ui) {// remove from the survey (deselect) on hoverif resp.hovered() && photos.len() > 1 {let xr = Rect::from_min_size(pos2(img.right() - 26.0, img.top() + 6.0), vec2(20.0, 20.0));- let xresp = ui.interact(xr, egui::Id::new(("survey-x", id.0)), Sense::click()).on_hover_text(crate::i18n::tr("Remove from survey"));+ let xresp = ui.interact(xr, egui::Id::unique(("survey-x", id.0)), Sense::click()).on_hover_text(crate::i18n::tr("Remove from survey"));crate::widgets::announce(&xresp, crate::i18n::tr("Remove from survey"));ui.painter().circle_filled(xr.center(), 10.0, Color32::from_black_alpha(if xresp.hovered() { 230 } else { 160 }));paint(ui.painter(), xr.shrink(4.0), Icon::Close, t.text);diff --git a/crates/ui-egui/src/panels/denoise.rs b/crates/ui-egui/src/panels/denoise.rsindex 437a378a7..9a0385639 100644--- a/crates/ui-egui/src/panels/denoise.rs+++ b/crates/ui-egui/src/panels/denoise.rs@@ -41,9 +41,16 @@ pub struct Ui {/// Called every frame: keeps the engine's denoise work going and asks for a redraw when a photo's picture appears (the/// loupe and the thumbnails then render from it) or while one is being made (the progress).+/// `pump_background` plus the UI-input half, for hosts/tests that have no phase split (the app's+/// own `logic` and `ui_pass` keep them apart so a hidden tick never paces work from stale input).pub fn pump(app: &mut LightcraftApp, ctx: &egui::Context) {- watch_downloads(app, ctx);- let now = ctx.input(|i| i.time);+ let now = app.tick_now();+ pump_ui_input(app, ctx, now);+ pump_background(app, ctx, now);+}++/// The input-reading half: fresh pointer/key activity and its timestamp. UI phase only.+pub fn pump_ui_input(app: &mut LightcraftApp, ctx: &egui::Context, now: f64) {let (working, moving) = ctx.input(|i| {let keys = i.events.iter().any(|e| matches!(e, egui::Event::Key { .. } | egui::Event::Text(_) | egui::Event::MouseWheel { .. }));(i.pointer.any_down() || keys, i.pointer.is_moving())@@ -54,6 +61,11 @@ pub fn pump(app: &mut LightcraftApp, ctx: &egui::Context) {if moving || working {app.caches.last_move = now;}+}++/// Worker results and pacing on monotonic deadlines; safe in `logic`, including while hidden.+pub fn pump_background(app: &mut LightcraftApp, ctx: &egui::Context, now: f64) {+ watch_downloads(app, ctx);if now < app.caches.denoise.next_pump {return;}@@ -85,8 +97,8 @@ pub fn pump(app: &mut LightcraftApp, ctx: &egui::Context) {}/// The engine's model list, re-read at most every [`REFRESH_SECS`], or at once after an action changed it.-fn models(app: &mut LightcraftApp, ctx: &egui::Context) -> Value {- let now = ctx.input(|i| i.time);+fn models(app: &mut LightcraftApp, _ctx: &egui::Context) -> Value {+ let now = app.tick_now();let epoch = app.caches.denoise.epoch;if let Some((e, at, v)) = &app.caches.denoise.list&& *e == epoch@@ -165,7 +177,7 @@ pub fn detail_status(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, amPhotoState::Idle => {if amount > 0.0 && app.session.denoise_auto() {// the pump has not met this photo yet: let it come round soon instead of waiting out its pause- let now = ui.ctx().input(|i| i.time);+ let now = app.tick_now();app.caches.denoise.next_pump = app.caches.denoise.next_pump.min(now + 0.05);ui.ctx().request_repaint_after(std::time::Duration::from_millis(60));egui::Frame::NONE.inner_margin(pad).show(ui, |ui| note(ui, "Waiting to start…", t.text_dim));@@ -371,11 +383,12 @@ fn work_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, list: &Vui.label(RichText::new(crate::i18n::tr("Limit")).color(t.text_label));let current = list["cacheGb"].as_u64().unwrap_or(20) as u32;let mut choice = current;- crate::widgets::combo_box("denoise-cache-limit").selected_text(tr_format!("{size} GB", size = current)).show_ui(ui, |ui| {+ let combo = crate::widgets::combo_box("denoise-cache-limit").selected_text(tr_format!("{size} GB", size = current)).show_ui(ui, |ui| {for gb in CACHE_LIMITS {ui.selectable_value(&mut choice, gb, tr_format!("{size} GB", size = gb));}});+ crate::widgets::name_combo(&combo.response, tr("Cache limit"));if choice != current {let _ = app.run("denoise.settings", json!({"cacheGb": choice}));app.caches.denoise.epoch += 1;@@ -574,7 +587,7 @@ fn count(n: u64, one: &str, many: &str) -> String {}pub(super) fn window_pace(app: &LightcraftApp, ctx: &egui::Context, now: f64, watching: bool) -> &'static str {- let (focused, minimized) = ctx.input(|i| (i.focused, i.raw.viewports.get(&i.raw.viewport_id).and_then(|v| v.minimized).unwrap_or(false)));+ let (focused, minimized) = ctx.input(|i| (i.raw.focused, i.viewport().minimized.unwrap_or(false)));pace_for(focused, minimized, now - app.caches.last_input, now - app.caches.last_move, watching)}diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rsindex 082508d08..4d050235e 100644--- a/crates/ui-egui/src/panels/detail.rs+++ b/crates/ui-egui/src/panels/detail.rs@@ -211,7 +211,7 @@ pub(crate) fn navigate_gesture(app: &mut LightcraftApp, ui: &mut egui::Ui, resp:ui.input(|i| (i.zoom_delta(), i.translation_delta(), i.multi_touch().map(|t| t.center_pos).or(i.pointer.hover_pos())));// A notched mouse wheel (line/page units, no modifier) zooms around the pointer, through egui's smoothed wheel// delta like Ctrl+wheel (so it glides instead of jumping); trackpads report points and still pan.- let wheel_id = egui::Id::new("loupe-wheel-zoom");+ let wheel_id = egui::Id::unique("loupe-wheel-zoom");if ui.input(|i| wheel_notches(&i.events)) != 0.0 {ui.data_mut(|d| d.insert_temp(wheel_id, true));}@@ -330,7 +330,7 @@ pub(crate) fn draw_focus_point(p: &egui::Painter, img: Rect, photo: &lightcraft_/// Ease the loupe rect toward `target` while a click-zoom animation runs; otherwise follow it exactly.fn animated_rect(ctx: &egui::Context, anim: &mut bool, target: Rect) -> Rect {let t = if *anim { 0.22 } else { 0.0 };- let id = egui::Id::new("loupe_anim");+ let id = egui::Id::unique("loupe_anim");let v = |k: &str, x: f32| ctx.animate_value_with_time(id.with(k), x, t);let (c, s) = (target.center(), target.size());let r = Rect::from_center_size(pos2(v("cx", c.x), v("cy", c.y)), vec2(v("w", s.x), v("h", s.y)));@@ -524,7 +524,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {// another crop): a texture's whole-pixel size is a little off the exact aspect, and the crop// tool's overlays need the frame's own geometry.let display_aspect = visible_texture_aspect.filter(|a| !crop_tool && (a / aspect - 1.0).abs() > 0.02).unwrap_or(aspect);- let resp = ui.interact(canvas, egui::Id::new("loupe"), Sense::click_and_drag());+ let resp = ui.interact(canvas, egui::Id::unique("loupe"), Sense::click_and_drag());crate::widgets::announce(&resp, crate::i18n::tr("Photo"));let mut target_rect = fit_rect(main_area, display_aspect, app.ui.zoom, native, ppp, app.ui.pan);let mut img_rect = animated_rect(ui.ctx(), &mut app.ui.zoom_anim, target_rect);@@ -935,7 +935,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {&& whole.iter().chain(windows.iter().map(|(v, _)| &v.slot)).any(|s| app.renderer.is_pending(*s) && !app.renderer.retrying(*s));let keys =[Slot::Main, Slot::Before, Slot::Region, Slot::RegionBefore].map(|s| app.renderer.textures.get(&s).filter(|t| t.photo == id).map(|t| t.key));- let rendering = ui.ctx().data_mut(|d| rendering_overdue(d.get_temp_mut_or(egui::Id::new("loupe-rendering"), None), keys, coming, now));+ let rendering = ui.ctx().data_mut(|d| rendering_overdue(d.get_temp_mut_or(egui::Id::unique("loupe-rendering"), None), keys, coming, now));// the render failed while a stand-in is up: what is on screen is all there will be (also while// a library change retries it)let failed = (!rendering@@ -1080,7 +1080,7 @@ fn region_overlay(let clip = p.clip_rect();let pointer = ui.input(|i| i.pointer.hover_pos());// the box being dragged: (region index, its box so far)- let drag_key = egui::Id::new("region-drag");+ let drag_key = egui::Id::unique("region-drag");let live: Option<(usize, lightcraft_geom::Rect)> = ui.data(|d| d.get_temp(drag_key));let mut edit = None;for (index, r) in photo.meta.regions.iter().enumerate() {@@ -1093,7 +1093,7 @@ fn region_overlay(if dragging.is_some() || (live.is_none() && pointer.is_some_and(|h| rect.expand(8.0).contains(h))) {for (h, (fx, fy, cursor)) in REGION_HANDLES.iter().enumerate() {let c = pos2(rect.left() + fx * rect.width(), rect.top() + fy * rect.height());- let resp = ui.interact(Rect::from_center_size(c, vec2(14.0, 14.0)), egui::Id::new(("region-handle", index, h)), Sense::drag());+ let resp = ui.interact(Rect::from_center_size(c, vec2(14.0, 14.0)), egui::Id::unique(("region-handle", index, h)), Sense::drag());crate::widgets::announce(&resp, crate::i18n::tr("Resize region"));if resp.hovered() || resp.dragged() {ui.ctx().set_cursor_icon(*cursor);@@ -1138,7 +1138,7 @@ fn region_overlay(}if dragging.is_none() && live.is_none() && pointer.is_some_and(|h| rect.expand(3.0).contains(h)) {let xr = Rect::from_center_size(pos2(rect.right() - 13.0, rect.top() + 13.0), vec2(16.0, 16.0));- let resp = ui.interact(xr, egui::Id::new(("region-x", index)), Sense::click());+ let resp = ui.interact(xr, egui::Id::unique(("region-x", index)), Sense::click());crate::widgets::announce(&resp, crate::i18n::tr("Remove region"));register(ui.ctx(), format!("regionRemove:{index}"), xr);let fill = Color32::from_black_alpha(if resp.hovered() { 235 } else { 190 });@@ -1188,7 +1188,7 @@ fn region_overlay(p.galley(label.min + pad, g, text_color);if is_face && live.is_none() {// a click on the label opens the name box, filled with the name or the guess- let resp = ui.interact(label, egui::Id::new(("region-label", index)), Sense::click());+ let resp = ui.interact(label, egui::Id::unique(("region-label", index)), Sense::click());crate::widgets::announce(&resp, crate::i18n::tr("Click to name this face"));register(ui.ctx(), format!("regionLabel:{index}"), label);if resp.on_hover_text(crate::i18n::tr("Click to name this face")).clicked() {@@ -1235,7 +1235,7 @@ fn filter_pill(app: &mut LightcraftApp, ui: &mut egui::Ui, canvas: Rect) {let inset = FILTER_PILL_INSET;let w = (g.size().x + 40.0).min((canvas.width() - 2.0 * inset).max(60.0));let r = Rect::from_min_size(canvas.min + vec2(inset, inset), vec2(w, FILTER_PILL_HEIGHT));- let resp = ui.interact(r, egui::Id::new("loupe-filter-pill"), Sense::click());+ let resp = ui.interact(r, egui::Id::unique("loupe-filter-pill"), Sense::click());crate::widgets::announce(&resp, crate::i18n::tr("Filters"));register(ui.ctx(), "loupe:filters", r);p.rect_filled(r, 10.0, Color32::from_black_alpha(if resp.hovered() { 225 } else { 185 }));@@ -1263,7 +1263,7 @@ fn preview_only_pill(ui: &mut egui::Ui, canvas: Rect, reason: &str) {crate::icons::paint(&p, Rect::from_center_size(pos2(r.left() + 16.0, r.center().y), vec2(15.0, 15.0)), crate::icons::Icon::Info, t.caution);p.galley(pos2(r.left() + 29.0, r.center().y - g.size().y / 2.0), g, Color32::WHITE);register(ui.ctx(), "notice:previewOnly:loupe", r);- ui.interact(r, egui::Id::new("preview-only-pill"), Sense::hover()).on_hover_text(crate::widgets::preview_only_explanation(reason));+ ui.interact(r, egui::Id::unique("preview-only-pill"), Sense::hover()).on_hover_text(crate::widgets::preview_only_explanation(reason));}/// One line of the info overlay for `photo`; `None` when the field is None or the photo has@@ -1334,7 +1334,7 @@ fn navigator(app: &mut LightcraftApp, ui: &mut egui::Ui, canvas: Rect, img: Rectp.rect_stroke(view, 0.0, Stroke::new(1.5, Color32::WHITE), StrokeKind::Inside);p.rect_stroke(view.expand(1.5), 0.0, Stroke::new(1.0, Color32::from_black_alpha(160)), StrokeKind::Outside);register(ui.ctx(), "canvas:navigator", frame);- let resp = ui.interact(frame.expand(5.0), egui::Id::new("navigator"), Sense::click_and_drag());+ let resp = ui.interact(frame.expand(5.0), egui::Id::unique("navigator"), Sense::click_and_drag());crate::widgets::announce(&resp, crate::i18n::tr("Navigator"));if (resp.clicked() || resp.dragged())&& let Some(q) = resp.interact_pointer_pos()@@ -1416,8 +1416,8 @@ pub(crate) fn failed_pill(let offline = matches!(&photo.source, lightcraft_catalog::Source::File { path } if app.session.media.availability.is_offline(path));let text = crate::i18n::tr(if offline { "Original offline · no smart preview" } else { "This photo can't be opened" });let r = loupe_pill(ui, canvas, over, navigator, id, text, true);- let resp = ui.interact(r, egui::Id::new(("render-failed", id)), Sense::hover()).on_hover_text(error);- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, format!("{text}: {error}")));+ let resp = ui.interact(r, egui::Id::unique(("render-failed", id)), Sense::hover()).on_hover_text(error);+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{text}: {error}")));}fn quick_name(q: lightcraft_engine::media::QuickSource) -> &'static str {@@ -1847,7 +1847,7 @@ pub(crate) fn readout_rect(at: Pos2, size: egui::Vec2, bounds: Rect) -> Rect {/// On top of everything (the tooltip layer), so neither the photo nor a panel covers it.fn top_painter(ui: &egui::Ui, name: &'static str) -> egui::Painter {- ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new(name)))+ ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique(name)))}/// The rotation pointer: a curved double arrow on a dark disc, so it reads over any photo,@@ -2359,7 +2359,7 @@ fn mask_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Responsmatch app.run_typed("mask.objectPoint", json!({"x": n.x, "y": n.y, "exclude": exclude})) {Ok(_) => {if let Some(mid) = app.session.active_mask {- app.ui.detail_due = Some((ui.input(|i| i.time) + 1.0, mid));+ app.ui.detail_due = Some((app.tick_now() + 1.0, mid));}}Err(e) => app.ai_error(ui.ctx(), e, Some(("object", "new"))),@@ -2709,7 +2709,7 @@ fn spot_keys(app: &mut LightcraftApp, ui: &mut egui::Ui, map: &CanvasMap, d: &De}}// where a new spot goes: the photo's centre at first, then wherever the arrows took it- let key = egui::Id::new("lc-spot-placement");+ let key = egui::Id::unique("lc-spot-placement");let place: (f64, f64) = ui.data(|m| m.get_temp(key)).unwrap_or((0.5, 0.5));let q = map.screen(Point::new(place.0, place.1));let keys = crate::canvas_keys::handle(@@ -2826,10 +2826,10 @@ pub(crate) fn filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect) {// a vertical mouse wheel scrolls the strip sideways (horizontal trackpad scrolls still work)child.style_mut().always_scroll_the_only_direction = true;// only a new active photo (or the strip appearing) scrolls it; see `grid::follow_active`- let follow = super::grid::follow_active(child.ctx(), egui::Id::new("film-follow-active"), active, app.session.source);+ let follow = super::grid::follow_active(child.ctx(), egui::Id::unique("film-follow-active"), active, app.session.source);// a wheel notch scrolls a third of its width; see `grid::wheel_step`register(ui.ctx(), "filmstrip", child.max_rect());- let wheel = super::grid::wheel_step(&child, egui::Id::new("film-wheel"), child.max_rect(), child.max_rect().width(), true);+ let wheel = super::grid::wheel_step(&child, egui::Id::unique("film-wheel"), child.max_rect(), child.max_rect().width(), true);egui::ScrollArea::horizontal().id_salt("filmstrip").auto_shrink([false, false]).show_viewport(&mut child, |ui, vp| {if wheel != egui::Vec2::ZERO {ui.scroll_with_delta_animation(wheel, egui::style::ScrollAnimation::none());@@ -2846,7 +2846,7 @@ pub(crate) fn filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect) {if !local.intersects(vp.expand2(vec2(cell_w * 4.0, 0.0))) {continue;}- let resp = ui.interact(cr, egui::Id::new(("film", id.0)), Sense::click());+ let resp = ui.interact(cr, egui::Id::unique(("film", id.0)), Sense::click());crate::widgets::announce(&resp, app.session.catalog.photo(*id).map(|p| p.file_name.clone()).unwrap_or_default());register(ui.ctx(), format!("film:{}", id.0), cr);let state = app.session.selection.state_of(*id);@@ -2892,7 +2892,7 @@ pub(crate) fn filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect) {let g = p.layout_no_wrap(text, t.semibold(9.5), Color32::WHITE);let br = Rect::from_min_size(fr.min + vec2(3.0, 3.0), vec2(g.size().x + 22.0, 15.0));// like the grid's badge: a click expands / collapses the stack- let badge = ui.interact(br, egui::Id::new(("film-stack-badge", id.0)), Sense::click()).on_hover_text(if collapsed {+ let badge = ui.interact(br, egui::Id::unique(("film-stack-badge", id.0)), Sense::click()).on_hover_text(if collapsed {"Stack — click to expand"} else {"Stack — click to collapse"@@ -3289,7 +3289,7 @@ mod wheel_zoom_tests {use super::*;fn wheel(unit: egui::MouseWheelUnit, y: f32, modifiers: egui::Modifiers) -> egui::Event {- egui::Event::MouseWheel { unit, delta: egui::vec2(0.0, y), phase: egui::TouchPhase::Move, modifiers }+ egui::Event::MouseWheel { unit, delta: egui::vec2(0.0, y), phase: egui::TouchPhase::Move, source: egui::MouseWheelSource::Unknown, modifiers }}#[test]diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rsindex c24f6da7c..9527ab8c2 100644--- a/crates/ui-egui/src/panels/dialogs.rs+++ b/crates/ui-egui/src/panels/dialogs.rs@@ -28,7 +28,7 @@ pub(crate) fn rename_preview(let mut h = std::collections::hash_map::DefaultHasher::new();(template, start, app.session.catalog.revision, &ids).hash(&mut h);let key = h.finish();- let id = egui::Id::new("rename-preview-rows");+ let id = egui::Id::unique("rename-preview-rows");let read = |rows: &Rows| rows.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();if let Some((k, rows)) = ctx.data(|d| d.get_temp::<(u64, Rows)>(id))&& k == key@@ -82,7 +82,7 @@ fn watermark_preview((id, app.session.catalog.revision, px).hash(&mut h);let key = h.finish();let ctx = ui.ctx().clone();- let (base_id, shown_id) = (egui::Id::new("export-wm-preview-base"), egui::Id::new("export-wm-preview-shown"));+ let (base_id, shown_id) = (egui::Id::unique("export-wm-preview-base"), egui::Id::unique("export-wm-preview-shown"));let base = match ctx.data(|d| d.get_temp::<(u64, Base)>(base_id)) {Some((k, base)) if k == key => base,_ => {@@ -174,7 +174,7 @@ pub const WHATS_NEW: &str = include_str!("../../../../docs/whats-new.md");/// The import review and Settings keep window ids of their own, so the size each is given/// doesn't carry over to the other dialogs.fn window_id(dialog: &Dialog) -> egui::Id {- egui::Id::new(match dialog {+ egui::Id::unique(match dialog {Dialog::Import { .. } => "lightcraft-import-dialog",Dialog::Print => "lightcraft-print-dialog",Dialog::Settings { .. } => "lightcraft-settings-dialog",@@ -205,7 +205,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {let screen = ctx.content_rect();// The backdrop is an area below the dialog window (a bare `Middle` layer painter would be// painted after every area — i.e. over the dialog too).- egui::Area::new(egui::Id::new("dialog-dim")).order(egui::Order::Middle).fixed_pos(screen.min).interactable(false).show(ctx, |ui| {+ egui::Area::new(egui::Id::unique("dialog-dim")).order(egui::Order::Middle).fixed_pos(screen.min).interactable(false).show(ctx, |ui| {ui.painter().rect_filled(screen, 0.0, egui::Color32::from_black_alpha(140));});let mut close = false;@@ -570,7 +570,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {Dialog::Rename { template, start } => {let n = app.session.selected().len();ui.label(egui::RichText::new(crate::i18n::tr_format!("{n} photo{}", if n == 1 { "" } else { "s" }, n = n)).color(t.text_dim));- let template_id = egui::Id::new("rename-template");+ let template_id = egui::Id::unique("rename-template");let tags_open = field(ui, "Template", |ui| {ui.spacing_mut().item_spacing.x = 4.0;let w = crate::import::tag_field_width(ui);@@ -725,10 +725,11 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {let n = app.session.selected().len();ui.label(crate::i18n::tr_format!("{n} selected photos · {pages} pages", n = n, pages = n.div_ceil(options.columns * options.rows)));field(ui, "Paper", |ui| {- crate::widgets::combo_box("contactSheetPaper").selected_text(&options.paper).show_ui(ui, |ui| {+ let c = crate::widgets::combo_box("contactSheetPaper").selected_text(&options.paper).show_ui(ui, |ui| {ui.selectable_value(&mut options.paper, "a4".into(), "A4");ui.selectable_value(&mut options.paper, "letter".into(), crate::i18n::tr("Letter"));});+ crate::widgets::name_combo(&c.response, crate::i18n::tr("Paper"));});ui.checkbox(&mut options.landscape, crate::i18n::tr("Landscape"));field(ui, "Columns", |ui| { ui.add(egui::DragValue::new(&mut options.columns).range(1..=8)); });@@ -756,6 +757,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {}}});+ crate::widgets::name_combo(&c.response, crate::i18n::tr("Preset"));crate::widgets::register(ui.ctx(), "combo:exportPreset", c.response.rect);if let Some(name) = chosen&& let Ok(params) = app.session.export_params(&json!({"preset": name}))@@ -913,11 +915,11 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {}if let Some(wm) = &mut opts.watermark {// text, or a graphic (a logo with transparency)- let mut graphic = !wm.image.is_empty() || ui.data(|d| d.get_temp::<bool>(egui::Id::new("wm-graphic"))).unwrap_or(false);+ let mut graphic = !wm.image.is_empty() || ui.data(|d| d.get_temp::<bool>(egui::Id::unique("wm-graphic"))).unwrap_or(false);let before = graphic;choices(ui, "Style", "exportWmStyle", &[(false, "Text"), (true, "Graphic")], &mut graphic);if graphic != before {- ui.data_mut(|d| d.insert_temp(egui::Id::new("wm-graphic"), graphic));+ ui.data_mut(|d| d.insert_temp(egui::Id::unique("wm-graphic"), graphic));if !graphic {wm.image.clear();}@@ -989,7 +991,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {use lightcraft_engine::export::DngCompression as Z;choices(ui, "Compression", "exportDngCompression", &[(Z::Lossless, "Lossless"), (Z::Deflate, "ZIP"), (Z::Uncompressed, "None"), (Z::Lossy, "Lossy")], &mut opts.dng_compression);}- let naming_id = egui::Id::new("export-naming");+ let naming_id = egui::Id::unique("export-naming");let tags_open = field(ui, "File name", |ui| {ui.spacing_mut().item_spacing.x = 4.0;let w = crate::import::tag_field_width(ui);@@ -1268,7 +1270,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {}Dialog::About => {ui.set_min_width(680.0);- let tab_id = egui::Id::new("about_tab");+ let tab_id = egui::Id::unique("about_tab");let mut tab = ui.data_mut(|d| d.get_temp::<u8>(tab_id)).unwrap_or(0);ui.horizontal(|ui| {ui.spacing_mut().item_spacing.x = 4.0;@@ -1526,11 +1528,11 @@ const DIALOG_MIN_BODY: f32 = 80.0;const DIALOG_MIN_LIST: f32 = 120.0;fn list_shrink_id() -> egui::Id {- egui::Id::new("dialog-list-shrink")+ egui::Id::unique("dialog-list-shrink")}fn list_applied_id() -> egui::Id {- egui::Id::new("dialog-list-applied")+ egui::Id::unique("dialog-list-applied")}/// The height for a list in a dialog that scrolls on its own (What's New, All Metadata, the@@ -2039,6 +2041,7 @@ fn export_size(ui: &mut egui::Ui, full: &mut bool, r: &mut lightcraft_engine::exui.selectable_value(&mut r.mode, m, crate::i18n::tr(l));}});+ crate::widgets::name_combo(&c.response, crate::i18n::tr("Resize"));crate::widgets::register(ui.ctx(), "combo:exportResizeMode", c.response.rect);if r.mode != before {// a sensible value for the new unit@@ -2261,7 +2264,7 @@ fn dialog_field(ui: &mut egui::Ui, widget: &str, text: &mut String, hint: &str)/// The dialog part `key` is drawn this frame but wasn't the frame before: the dialog has just/// opened (to give its first field the focus once).fn just_opened(ui: &egui::Ui, key: &str) -> bool {- let id = egui::Id::new(("dialog-shown", key));+ let id = egui::Id::unique(("dialog-shown", key));let pass = ui.ctx().cumulative_pass_nr();let last: Option<u64> = ui.data_mut(|d| d.get_temp(id));ui.data_mut(|d| d.insert_temp(id, pass));diff --git a/crates/ui-egui/src/panels/edit.rs b/crates/ui-egui/src/panels/edit.rsindex 08f70bd02..03062d0c4 100644--- a/crates/ui-egui/src/panels/edit.rs+++ b/crates/ui-egui/src/panels/edit.rs@@ -595,7 +595,7 @@ fn preview_histogram(app: &LightcraftApp, id: PhotoId) -> Option<lightcraft_rast/// the SDR layout and back while a slider moves. Every render with HDR bins replaces the one kept for the photo, so/// the histogram still follows the edit live; an SDR edit shows what it gets.fn steady_hdr_histogram(ctx: &egui::Context, id: PhotoId, hdr_edit: bool, hist: Option<Histogram>) -> Option<Histogram> {- let key = egui::Id::new(("hdrHistogram", id));+ let key = egui::Id::unique(("hdrHistogram", id));match hist {Some(h) if h.hdr.is_some() => {ctx.data_mut(|d| d.insert_temp(key, h.clone()));@@ -656,7 +656,7 @@ fn histogram(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {p.text(pos2((x0 + plot.right()) / 2.0, y), Align2::CENTER_CENTER, crate::i18n::tr("HDR"), t.font(12.5), t.text_label);let info = Rect::from_center_size(pos2(plot.right() - 16.0, y), vec2(14.0, 14.0));paint(p, info, Icon::Info, t.text_label);- ui.interact(info, egui::Id::new("hdrHistogramInfo"), Sense::hover()).on_hover_text(crate::i18n::tr(+ ui.interact(info, egui::Id::unique("hdrHistogramInfo"), Sense::hover()).on_hover_text(crate::i18n::tr("Left: the standard (SDR) range up to SDR white. Right: the HDR range, one band per stop above SDR white (the orange line: the HDR headroom). With Visualize HDR range on, the bands take its colours.",));}@@ -730,9 +730,9 @@ fn histogram(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {("highlights", plot.right() - inset, "Highlight clipping", clipping.map(|(_, hi)| hi > 0.003)),] {let rect = Rect::from_center_size(pos2(x, plot.top() + 14.0), vec2(24.0, 22.0));- let response = ui.interact(rect, ui.id().with(("histogram-clipping", name)), Sense::click());+ let response = ui.interact(rect, ui.scope_id().with(("histogram-clipping", name)), Sense::click());register(ui.ctx(), format!("histogram:{name}"), rect);- response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, ui.is_enabled(), app.ui.show_clipping, crate::i18n::tr(label)));+ response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), app.ui.show_clipping, crate::i18n::tr(label)));clicked |= response.clicked();let active = app.ui.show_clipping;// Keep the hit target comfortable, with a smaller box and clear space to the plot edges.@@ -829,7 +829,7 @@ fn soft_proofing(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {let device = app.ui.proof_profile.as_ref().map(|(_, n)| n.clone());let shown = device.clone().unwrap_or_else(|| cur.label().to_string());let mut pick = false;- crate::widgets::combo_box("proof-space").width(170.0).selected_text(shown).show_ui(ui, |ui| {+ let combo = crate::widgets::combo_box("proof-space").width(170.0).selected_text(shown).show_ui(ui, |ui| {for s in OutputSpace::ALL {if ui.selectable_label(device.is_none() && cur == s, s.label()).clicked() {let _ = app.run("view.softProof", json!({"space": s}));@@ -842,6 +842,7 @@ fn soft_proofing(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {pick = true;}});+ crate::widgets::name_combo(&combo.response, crate::i18n::tr("Profile"));if pick&& let Some(path) = app.services.pick_display_profile.as_mut().and_then(|pick| pick().into_iter().next())&& let Err(e) = app.run("view.softProof", json!({"profile": path}))@@ -981,7 +982,7 @@ fn curve_editor(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, d: &Devlet side = (w - 48.0).max(80.0);let (outer, _) = ui.allocate_exact_size(vec2(w, side + 12.0), Sense::hover());let r = Rect::from_min_size(pos2(outer.left() + 24.0, outer.top() + 6.0), vec2(side, side));- let resp = ui.interact(r, egui::Id::new(("curve", &ch)), Sense::click_and_drag());+ let resp = ui.interact(r, egui::Id::unique(("curve", &ch)), Sense::click_and_drag());crate::widgets::announce(&resp, crate::i18n::tr("Tone Curve"));register(ui.ctx(), "curve", r);crate::widgets::context_menu(&resp, |ui| curve_reset_menu(app, ui, &ch));@@ -1058,7 +1059,7 @@ fn curve_editor(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, d: &Devp.add(egui::Shape::line(line, Stroke::new(2.0, color)));// interaction: drag a point (both axes, between its neighbours; ⌥ = fine), drag empty space to add and// drag a new point, click empty space to add, double-click a point to delete it- let drag_id = egui::Id::new(("curve-drag", &ch));+ let drag_id = egui::Id::unique(("curve-drag", &ch));// the point being dragged (stored as `Option<usize>` so a stale value can be cleared)let mut dragging: Option<usize> = ui.data(|dd| dd.get_temp::<Option<usize>>(drag_id)).flatten();let nearest = |q: Pos2| pts.iter().enumerate().map(|(i, p)| (i, to_screen(p.x, p.y).distance(q))).min_by(|a, b| a.1.total_cmp(&b.1));@@ -1526,7 +1527,7 @@ fn grading_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings// the corners (eye, readout) count as the wheel for hoveringlet zone = r.expand(10.0);let hovering = ui.rect_contains_pointer(zone);- let resp = ui.interact(r, egui::Id::new(("wheel", key)), Sense::click_and_drag());+ let resp = ui.interact(r, egui::Id::unique(("wheel", key)), Sense::click_and_drag());crate::widgets::announce(&resp, format!("{} {key}", crate::i18n::tr("Color wheel")));let resp = resp.on_hover_text(crate::i18n::tr("Drag to set hue and saturation. Hold Shift to keep the hue, Cmd/Ctrl to keep the saturation, Alt/Option to fine-adjust. Double-click to reset.",@@ -1550,7 +1551,7 @@ fn grading_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings// Modifiers (as in Lightroom): Shift keeps the hue, Cmd/Ctrl keeps the saturation, Alt moves// the puck a tenth as far as the pointer. Pressing or releasing one mid-drag re-grabs the// puck as it is at that moment.- let grab_id = egui::Id::new(("wheelGrab", key));+ let grab_id = egui::Id::unique(("wheelGrab", key));let mods = ui.input(|i| WheelMods::from_modifiers(i.modifiers));let grab = match resp.interact_pointer_pos() {Some(q) if resp.dragged() || resp.clicked() => {@@ -1616,7 +1617,7 @@ fn grading_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings// the eye: on top of the wheel, shown while hovering or while the wheel is hiddenif hovering || hidden {let eye = Rect::from_center_size(r.left_bottom() + vec2(2.0, -2.0), vec2(16.0, 16.0));- let er = ui.interact(eye, egui::Id::new(("wheelEye", key)), Sense::click());+ let er = ui.interact(eye, egui::Id::unique(("wheelEye", key)), Sense::click());crate::widgets::announce(&er, crate::i18n::tr("Show / hide"));register(ui.ctx(), format!("wheelEye:{key}"), eye);paint(ui.painter(), eye, if hidden { Icon::EyeOff } else { Icon::Eye }, if hidden { t.text_disabled } else { t.icon });@@ -1797,7 +1798,7 @@ fn quick_develop(app: &mut LightcraftApp, ui: &mut egui::Ui, n: usize) {let r = crate::widgets::arrow_button(ui, "", icon, false);r.widget_info(|| {egui::WidgetInfo::labeled(- egui::WidgetType::Button,+ egui::Role::Button,ui.is_enabled(),crate::i18n::tr_format!("{label} {d:+} on every selected photo", d = d, label = crate::i18n::tr(label)),)diff --git a/crates/ui-egui/src/panels/faces.rs b/crates/ui-egui/src/panels/faces.rsindex f1eb97caf..6b0bd4f3b 100644--- a/crates/ui-egui/src/panels/faces.rs+++ b/crates/ui-egui/src/panels/faces.rs@@ -21,7 +21,7 @@ use crate::widgets::register;/// machine once they have been idle for a few seconds, or while another app has the keyboard but this window is still/// on screen; most of it while they are looking at the scan's progress.fn scan_pace(app: &LightcraftApp, ctx: &egui::Context, now: f64) -> (&'static str, bool) {- let (focused, minimized) = ctx.input(|i| (i.focused, i.raw.viewports.get(&i.raw.viewport_id).and_then(|v| v.minimized).unwrap_or(false)));+ let (focused, minimized) = ctx.input(|i| (i.raw.focused, i.viewport().minimized.unwrap_or(false)));let watching =matches!(&app.ui.dialog, Some(crate::state::Dialog::Settings { tab }) if tab == "faces") || app.ui.view == crate::state::ViewMode::People;(pace_for(focused, minimized, now - app.caches.last_input, now - app.caches.last_move, watching), focused && !minimized)@@ -30,7 +30,7 @@ fn scan_pace(app: &LightcraftApp, ctx: &egui::Context, now: f64) -> (&'static st/// The pace for other background work that reads the library's files (the focus-point reader): the face scan's, without/// the "watching" speed-up.pub(crate) fn background_pace(app: &LightcraftApp, ctx: &egui::Context, now: f64) -> &'static str {- let (focused, minimized) = ctx.input(|i| (i.focused, i.raw.viewports.get(&i.raw.viewport_id).and_then(|v| v.minimized).unwrap_or(false)));+ let (focused, minimized) = ctx.input(|i| (i.raw.focused, i.viewport().minimized.unwrap_or(false)));pace_for(focused, minimized, now - app.caches.last_input, now - app.caches.last_move, false)}@@ -58,12 +58,12 @@ fn pace_for(focused: bool, minimized: bool, worked: f64, moved: f64, watching: bconst REFRESH_SECS: f64 = 1.5;fn list_id() -> egui::Id {- egui::Id::new("faces-model-list")+ egui::Id::unique("faces-model-list")}/// The engine's model list, re-read at most every [`REFRESH_SECS`], or at once after an action changed it.fn models(app: &mut LightcraftApp, ctx: &egui::Context) -> Value {- let now = ctx.input(|i| i.time);+ let now = app.tick_now();let epoch = app.caches.faces_epoch;if let Some((e, at, v)) = ctx.data(|d| d.get_temp::<(u64, f64, Value)>(list_id()))&& e == epoch@@ -642,7 +642,7 @@ pub fn name_editor(let t = Tokens::get(ctx);let mut outcome = Editor::Open;let opening = edit.fresh;- let shown = egui::Area::new(egui::Id::new("face-name-editor")).order(egui::Order::Foreground).fixed_pos(at).constrain(true).show(ctx, |ui| {+ let shown = egui::Area::new(egui::Id::unique("face-name-editor")).order(egui::Order::Foreground).fixed_pos(at).constrain(true).show(ctx, |ui| {egui::Frame::popup(ui.style()).show(ui, |ui| {ui.set_min_width(230.0);let r = ui.add(egui::TextEdit::singleline(&mut edit.text).hint_text("Name").desired_width(220.0));@@ -700,9 +700,15 @@ pub fn name_editor(/// Called every frame: keeps the background face indexer going while recognition is on, and notes whether it is/// running, how many faces it has done and how many photos are left (the loupe's suggestions depend on it).+/// `pump_background` plus the UI-input half; the app's own phases keep them apart.pub fn pump(app: &mut LightcraftApp, ctx: &egui::Context) {- watch_downloads(app, ctx);- let now = ctx.input(|i| i.time);+ let now = app.tick_now();+ pump_ui_input(app, ctx, now);+ pump_background(app, ctx, now);+}++/// Fresh pointer/key activity (UI phase only).+pub fn pump_ui_input(app: &mut LightcraftApp, ctx: &egui::Context, now: f64) {let (working, moving) = ctx.input(|i| {let key_or_scroll = i.events.iter().any(|e| matches!(e, egui::Event::Key { .. } | egui::Event::Text(_) | egui::Event::MouseWheel { .. }));(i.pointer.any_down() || key_or_scroll, i.pointer.is_moving())@@ -713,6 +719,11 @@ pub fn pump(app: &mut LightcraftApp, ctx: &egui::Context) {if moving || working {app.caches.last_move = now;}+}++/// Worker results and pacing on monotonic deadlines; safe while hidden.+pub fn pump_background(app: &mut LightcraftApp, ctx: &egui::Context, now: f64) {+ watch_downloads(app, ctx);if now < app.caches.faces_next_pump {return;}diff --git a/crates/ui-egui/src/panels/grid.rs b/crates/ui-egui/src/panels/grid.rsindex fbe52cf12..b7f8d1ab2 100644--- a/crates/ui-egui/src/panels/grid.rs+++ b/crates/ui-egui/src/panels/grid.rs@@ -312,7 +312,7 @@ fn show_inner(app: &mut LightcraftApp, ui: &mut egui::Ui) {crate::widgets::register(ui.ctx(), "grid:title", title_rect);crate::widgets::register(ui.ctx(), "grid:count", count_rect);if title != full {- ui.interact(title_rect, ui.id().with("grid-title"), Sense::hover()).on_hover_text(full);+ ui.interact(title_rect, ui.scope_id().with("grid-title"), Sense::hover()).on_hover_text(full);}}}@@ -384,7 +384,7 @@ fn show_inner(app: &mut LightcraftApp, ui: &mut egui::Ui) {let active = app.session.selection.active;// bring the active photo into view when it changes (keyboard, click, command) or the grid// comes back on screen; otherwise the scroll position is the user's- let scroll_to: Option<Rect> = if follow_active(ui.ctx(), egui::Id::new("grid-follow-active"), active, app.session.source) {+ let scroll_to: Option<Rect> = if follow_active(ui.ctx(), egui::Id::unique("grid-follow-active"), active, app.session.source) {active.and_then(|a| ids.iter().position(|x| *x == a)).and_then(|i| lay.cells.get(i).copied())} else {None@@ -394,7 +394,7 @@ fn show_inner(app: &mut LightcraftApp, ui: &mut egui::Ui) {// a wheel notch scrolls a third of the grid's heightlet scroll_rect = ui.available_rect_before_wrap();crate::widgets::register(ui.ctx(), "grid:scroll", scroll_rect);- let wheel = wheel_step(ui, egui::Id::new("grid-wheel"), scroll_rect, scroll_rect.height(), false);+ let wheel = wheel_step(ui, egui::Id::unique("grid-wheel"), scroll_rect, scroll_rect.height(), false);egui::ScrollArea::vertical().id_salt("grid-scroll").auto_shrink([false, false]).show_viewport(ui, |ui, viewport| {if wheel != egui::Vec2::ZERO {ui.scroll_with_delta_animation(wheel, egui::style::ScrollAnimation::none());@@ -656,7 +656,7 @@ pub fn layout(aspects: &[f32], groups: &[(usize, usize)], avail_w: f32, target:/// (Cmd/Shift: adds to the selection).fn group_header(app: &mut LightcraftApp, ui: &mut egui::Ui, run: &DateRun, ids: &[PhotoId], r: Rect, pinned: bool) {let t = Tokens::get(ui.ctx());- let resp = ui.interact(r, egui::Id::new(("group-header", run.start, pinned)), Sense::click());+ let resp = ui.interact(r, egui::Id::unique(("group-header", run.start, pinned)), Sense::click());crate::widgets::announce(&resp, if run.key.is_empty() { crate::i18n::tr("Unknown date").to_string() } else { run.key.clone() });if !pinned {register(ui.ctx(), format!("group:{}", if run.key.is_empty() { "unknown" } else { &run.key }), r);@@ -758,7 +758,7 @@ pub const BACKGROUND_THUMB_PRIORITY: u32 = 3;fn cell(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, r: Rect, square: bool, onscreen: bool, ppp: f32) {let t = Tokens::get(ui.ctx());let Some(photo) = app.session.catalog.photo(id).cloned() else { return };- let resp = ui.interact(r, egui::Id::new(("cell", id.0)), Sense::click_and_drag());+ let resp = ui.interact(r, egui::Id::unique(("cell", id.0)), Sense::click_and_drag());register(ui.ctx(), format!("thumb:{}", id.0), r);let state = app.session.selection.state_of(id);let selected = state != lightcraft_engine::SelectionState::NotSelected;@@ -775,7 +775,7 @@ fn cell(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, r: Rect, squareif let Some(l) = photo.label {spoken.push_str(&crate::i18n::tr_format!(", {} label", crate::i18n::color_label(&app.session.catalog, l)));}- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, selected, &spoken));+ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, &spoken));let active = state == lightcraft_engine::SelectionState::Active;let p = ui.painter();let img_rect = if square {@@ -902,7 +902,7 @@ fn cell(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, r: Rect, squarepaint(p, Rect::from_center_size(pos2(br.left() + 9.0, br.center().y), vec2(12.0, 12.0)), Icon::Info, t.caution);p.galley(pos2(br.left() + 17.0, br.center().y - g.size().y / 2.0), g, Color32::WHITE);register(ui.ctx(), format!("badge:previewOnly:{}", id.0), br);- ui.interact(br, egui::Id::new(("preview-only-badge", id.0)), Sense::hover())+ ui.interact(br, egui::Id::unique(("preview-only-badge", id.0)), Sense::hover()).on_hover_text(crate::i18n::tr_format!("Preview only — {}", crate::widgets::preview_only_explanation(why)));}if photo.flag == Flag::Reject {@@ -1065,7 +1065,7 @@ fn folder_breadcrumbs(app: &mut LightcraftApp, ui: &mut egui::Ui, path: &str) {/// drop would put them (set by the drop target under the pointer, read by [`drag_feedback`]).pub fn drag_hint(ctx: &egui::Context, text: String) {let frame = ctx.cumulative_frame_nr();- ctx.data_mut(|d| d.insert_temp(egui::Id::new("drag-photos-hint"), (frame, text)));+ ctx.data_mut(|d| d.insert_temp(egui::Id::unique("drag-photos-hint"), (frame, text)));}pub fn drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) {@@ -1081,14 +1081,17 @@ pub fn drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) {ctx.set_cursor_icon(egui::CursorIcon::Grabbing);// a drop target under the pointer says where they would go (only this frame's)let frame = ctx.cumulative_frame_nr();- let hint = ctx.data(|d| d.get_temp::<(u64, String)>(egui::Id::new("drag-photos-hint"))).filter(|(f, _)| *f == frame).map(|(_, text)| text);+ let hint = ctx.data(|d| d.get_temp::<(u64, String)>(egui::Id::unique("drag-photos-hint"))).filter(|(f, _)| *f == frame).map(|(_, text)| text);let text = hint.unwrap_or_else(|| crate::i18n::tr_format!("{n} photo{}", if n == 1 { "" } else { "s" }, n = n));- egui::Area::new(egui::Id::new("drag-photos")).order(egui::Order::Tooltip).interactable(false).fixed_pos(pos + vec2(14.0, 10.0)).show(ctx, |ui| {- egui::Frame::NONE.fill(t.accent).corner_radius(10.0).inner_margin(egui::Margin::symmetric(9, 3)).show(ui, |ui| {- let label = ui.add(egui::Label::new(egui::RichText::new(text).color(Color32::WHITE).font(t.semibold(12.0))).extend());- crate::widgets::register(ui.ctx(), "dragPhotos", label.rect);- });- });+ egui::Area::new(egui::Id::unique("drag-photos")).order(egui::Order::Tooltip).interactable(false).fixed_pos(pos + vec2(14.0, 10.0)).show(+ ctx,+ |ui| {+ egui::Frame::NONE.fill(t.accent).corner_radius(10.0).inner_margin(egui::Margin::symmetric(9, 3)).show(ui, |ui| {+ let label = ui.add(egui::Label::new(egui::RichText::new(text).color(Color32::WHITE).font(t.semibold(12.0))).extend());+ crate::widgets::register(ui.ctx(), "dragPhotos", label.rect);+ });+ },+ );}pub use super::filterbar::label_color;@@ -1176,7 +1179,7 @@ pub fn stack_badge(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, sid:let g = p.layout_no_wrap(text, t.semibold(11.0), Color32::WHITE);let origin = if square { r.min + vec2(10.0, 26.0) } else { r.min + vec2(5.0, 5.0) };let br = Rect::from_min_size(origin, vec2(g.size().x + 30.0, 20.0));- let resp = ui.interact(br, egui::Id::new(("stack-badge", id.0)), Sense::click()).on_hover_text(if collapsed {+ let resp = ui.interact(br, egui::Id::unique(("stack-badge", id.0)), Sense::click()).on_hover_text(if collapsed {"Stack — click to expand (S)"} else {"Stack — click to collapse (S)"diff --git a/crates/ui-egui/src/panels/keymap.rs b/crates/ui-egui/src/panels/keymap.rsindex 1bda17758..642aa2c5e 100644--- a/crates/ui-egui/src/panels/keymap.rs+++ b/crates/ui-egui/src/panels/keymap.rs@@ -19,7 +19,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {let mac = ui.ctx().os() == egui::os::OperatingSystem::Mac;capture(app, ui.ctx());ui.set_min_width(560.0);- let (search_id, all_id) = (egui::Id::new(SEARCH), egui::Id::new(SHOW_ALL));+ let (search_id, all_id) = (egui::Id::unique(SEARCH), egui::Id::unique(SHOW_ALL));let mut search: String = ui.data(|d| d.get_temp(search_id)).unwrap_or_default();let mut show_all: bool = ui.data(|d| d.get_temp(all_id)).unwrap_or(false);ui.horizontal(|ui| {diff --git a/crates/ui-egui/src/panels/keyword_list.rs b/crates/ui-egui/src/panels/keyword_list.rsindex 4f2cba91c..262a22530 100644--- a/crates/ui-egui/src/panels/keyword_list.rs+++ b/crates/ui-egui/src/panels/keyword_list.rs@@ -42,7 +42,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {if !open {return;}- let fid = egui::Id::new("keyword-list-filter");+ let fid = egui::Id::unique("keyword-list-filter");let mut filter: String = ui.data(|d| d.get_temp(fid)).unwrap_or_default();ui.horizontal(|ui| {ui.add_space(24.0);@@ -130,11 +130,14 @@ pub fn drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) {let t = Tokens::get(ctx);ctx.set_cursor_icon(egui::CursorIcon::Grabbing);let name = keyword.rsplit('|').next().unwrap_or(&keyword).to_string();- egui::Area::new(egui::Id::new("drag-keyword")).order(egui::Order::Tooltip).interactable(false).fixed_pos(at + vec2(14.0, 10.0)).show(ctx, |ui| {- egui::Frame::NONE.fill(t.accent).corner_radius(10.0).inner_margin(egui::Margin::symmetric(9, 3)).show(ui, |ui| {- ui.label(egui::RichText::new(name).color(Color32::WHITE).font(t.semibold(12.0)));- });- });+ egui::Area::new(egui::Id::unique("drag-keyword")).order(egui::Order::Tooltip).interactable(false).fixed_pos(at + vec2(14.0, 10.0)).show(+ ctx,+ |ui| {+ egui::Frame::NONE.fill(t.accent).corner_radius(10.0).inner_margin(egui::Margin::symmetric(9, 3)).show(ui, |ui| {+ ui.label(egui::RichText::new(name).color(Color32::WHITE).font(t.semibold(12.0)));+ });+ },+ );}/// Drop the dragged `keyword` inside `parent` (`None`: the top level). Where one of its name is@@ -185,7 +188,7 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, r: &Row, selection: &[PhotoIdif r.has_children {let c = pos2(x + 6.0, cy);let tri = Rect::from_center_size(c, vec2(16.0, 16.0));- let tr = ui.interact(tri, egui::Id::new(("keyword-list-tri", r.path.to_lowercase())), Sense::click());+ let tr = ui.interact(tri, egui::Id::unique(("keyword-list-tri", r.path.to_lowercase())), Sense::click());crate::widgets::announce(&tr, crate::i18n::tr(if r.open { "Collapse" } else { "Expand" }));register(ui.ctx(), format!("keywordRowToggle:{}", r.path), tri);// while a filter opens the levels the triangle does nothing: it doesn't light up either@@ -206,7 +209,7 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, r: &Row, selection: &[PhotoIdlet on = !selection.is_empty();// (it senses drags too, so a press there that moves doesn't pick the keyword up)let sense = if on { Sense::click_and_drag() } else { Sense::hover() };- let tb = ui.interact(boxr.expand(3.0), egui::Id::new(("keyword-list-tick", r.path.to_lowercase())), sense);+ let tb = ui.interact(boxr.expand(3.0), egui::Id::unique(("keyword-list-tick", r.path.to_lowercase())), sense);crate::widgets::announce(&tb, format!("{} {}", crate::i18n::tr("Keyword"), r.path));register(ui.ctx(), format!("keywordCheck:{}", r.path), boxr);let edge = if on { t.text_label } else { t.text_dim.gamma_multiply(0.5) };@@ -243,7 +246,7 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, r: &Row, selection: &[PhotoIdregister(ui.ctx(), format!("keywordCount:{}", r.path), count_rect);ui.painter().galley(count_rect.min, count, t.text_dim);let arrow = Rect::from_center_size(pos2(count_rect.left() - 12.0, cy), vec2(16.0, 16.0));- let ar = ui.interact(arrow, egui::Id::new(("keyword-list-show", r.path.to_lowercase())), Sense::click());+ let ar = ui.interact(arrow, egui::Id::unique(("keyword-list-show", r.path.to_lowercase())), Sense::click());crate::widgets::announce(&ar, crate::i18n::tr("Show photos"));register(ui.ctx(), format!("keywordShow:{}", r.path), arrow);if resp.hovered() || ar.hovered() {diff --git a/crates/ui-egui/src/panels/keywording.rs b/crates/ui-egui/src/panels/keywording.rsindex a6f53562d..8a9516fe2 100644--- a/crates/ui-egui/src/panels/keywording.rs+++ b/crates/ui-egui/src/panels/keywording.rs@@ -87,17 +87,17 @@ fn chip(ui: &mut egui::Ui, path: &str, name: &str, partial: bool, cross: bool, r// the row places it; its name and × answer under ids of their own keyword, so an open menu// stays with its keyword when the chips changelet (rect, _) = ui.allocate_exact_size(vec2(w, 22.0), Sense::hover());- let id = egui::Id::new(("keyword-chip", path.to_lowercase(), cross));+ let id = egui::Id::unique(("keyword-chip", path.to_lowercase(), cross));let body = Rect::from_min_max(rect.min, pos2(rect.right() - cross_w, rect.bottom()));let full = path.replace('|', " › ");let resp = ui.interact(body, id, Sense::click());- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &full));+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &full));// the ×: the whole end of the chip, so that it is hard to miss and easy to tell from the namelet x = cross.then(|| {let xr = Rect::from_min_max(pos2(rect.right() - cross_w, rect.top()), rect.max);let xresp = ui.interact(xr, id.with("remove"), Sense::click());let said = crate::i18n::tr_format!("Remove “{name}”", name = full);- xresp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &said));+ xresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &said));xresp});let p = ui.painter();@@ -273,7 +273,7 @@ fn chip_groups(app: &mut LightcraftApp, ui: &mut egui::Ui, groups: &[Group], sellet measure = |s: &str| ui.painter().layout_no_wrap(s.to_string(), small.clone(), t.text_label).size().x;let shown = chip_label(&group.parent, false, avail, measure);let full = group.parent.replace('|', " › ");- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, &full));+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, &full));ui.painter().text(r.left_center(), Align2::LEFT_CENTER, &shown, small.clone(), t.text_label);// (cut short, it says its whole name on hover, as a chip does)if shown != full {@@ -434,7 +434,7 @@ pub(crate) fn offers_below(ui: &egui::Ui, below: egui::Rect, offers: &Offers, atlet lit = at.and_then(|k| offers.keywords.iter().position(|x| x == k));let first = lit.map_or(0, |a| a.saturating_add(1).saturating_sub(count)).min(offers.keywords.len().saturating_sub(count));let listed = offers.keywords.iter().skip(first).take(count);- let area = egui::Area::new(egui::Id::new("keyword-offers")).order(egui::Order::Foreground).constrain(true);+ let area = egui::Area::new(egui::Id::unique("keyword-offers")).order(egui::Order::Foreground).constrain(true);let area = if over {area.pivot(Align2::LEFT_BOTTOM).fixed_pos(below.left_top() - vec2(0.0, 2.0))} else {@@ -448,7 +448,7 @@ pub(crate) fn offers_below(ui: &egui::Ui, below: egui::Rect, offers: &Offers, atlet line = |ui: &mut egui::Ui, id: egui::Id, name: &str, place: &str, said: &str, lit: bool| {let (r, resp) = ui.allocate_exact_size(vec2(width, 24.0), Sense::hover());let resp = ui.interact(r, id, Sense::click()).union(resp);- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, true, lit, said));+ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, lit, said));if lit || resp.hovered() {ui.painter().rect_filled(r, 4.0, if lit { t.pressed } else { t.hover });}@@ -469,7 +469,7 @@ pub(crate) fn offers_below(ui: &egui::Ui, below: egui::Rect, offers: &Offers, atlet (place, name) = k.rsplit_once(SEP).unwrap_or(("", k));let whole = k.replace(SEP, " › ");let lit = at == Some(k.as_str());- let r = line(ui, egui::Id::new(("keyword-offer", k.to_lowercase())), name, place, &whole, lit);+ let r = line(ui, egui::Id::unique(("keyword-offer", k.to_lowercase())), name, place, &whole, lit);register(ui.ctx(), format!("kwComplete:{k}"), r.rect);if lit {register(ui.ctx(), format!("kwCompleteAt:{k}"), r.rect);@@ -497,7 +497,7 @@ pub(crate) fn offers_below(ui: &egui::Ui, below: egui::Rect, offers: &Offers, at)};// (its place is said in words: not a path to cut from the front)- let r = line(ui, egui::Id::new("keyword-offer-create"), name, "", &said, false);+ let r = line(ui, egui::Id::unique("keyword-offer-create"), name, "", &said, false);let small = t.font(11.5);ui.painter().text(pos2(r.rect.right() - 8.0, r.rect.center().y), Align2::RIGHT_CENTER, place, small, t.text_label);register(ui.ctx(), "kwCompleteCreate", r.rect);diff --git a/crates/ui-egui/src/panels/layout_overlay.rs b/crates/ui-egui/src/panels/layout_overlay.rsindex 9b4800d0f..323c035a6 100644--- a/crates/ui-egui/src/panels/layout_overlay.rs+++ b/crates/ui-egui/src/panels/layout_overlay.rs@@ -112,7 +112,7 @@ pub fn draw(app: &LightcraftApp, p: &egui::Painter, photo: Rect) {return;}let ctx = p.ctx().clone();- let id = egui::Id::new("loupe-layout-image");+ let id = egui::Id::unique("loupe-layout-image");let file = (path.to_string(), li.revision);let mut cache = match ctx.data(|d| d.get_temp::<Cache>(id)) {Some(c) if c.file == file => c,diff --git a/crates/ui-egui/src/panels/left.rs b/crates/ui-egui/src/panels/left.rsindex 2c7d2642c..c1c709fd7 100644--- a/crates/ui-egui/src/panels/left.rs+++ b/crates/ui-egui/src/panels/left.rs@@ -15,7 +15,7 @@ use crate::widgets::{icon_button, register};/// drawn at this width (or the panel's, if wider), and the sidebar scrolls sideways when it/// exceeds the panel. One frame behind, which needs no second layout pass.pub(crate) fn content_width(ctx: &egui::Context) -> f32 {- ctx.data(|d| d.get_temp::<f32>(egui::Id::new("left-content-width"))).unwrap_or(0.0)+ ctx.data(|d| d.get_temp::<f32>(egui::Id::unique("left-content-width"))).unwrap_or(0.0)}/// The most a row asks for its name: longer ones are cut when there is no more room.@@ -35,7 +35,7 @@ const LIBFOLDER_REVEALED: &str = "libfolder-revealed";/// A row says how wide it needs to be.fn note_width(ui: &egui::Ui, w: f32) {ui.data_mut(|d| {- let m = d.get_temp_mut_or_insert_with::<f32>(egui::Id::new("left-content-width-next"), || 0.0);+ let m = d.get_temp_mut_or_insert_with::<f32>(egui::Id::unique("left-content-width-next"), || 0.0);*m = m.max(w);});}@@ -56,7 +56,7 @@ const COUNT_ROOM: f32 = 40.0;/// The step a level is drawn with this frame: [`INDENT_STEP`] while the deepest open row fits the/// panel, narrower when it would not, never below [`MIN_INDENT_STEP`]. From the last frame.pub(crate) fn indent_step(ctx: &egui::Context) -> f32 {- ctx.data(|d| d.get_temp::<f32>(egui::Id::new("left-indent-step"))).unwrap_or(INDENT_STEP)+ ctx.data(|d| d.get_temp::<f32>(egui::Id::unique("left-indent-step"))).unwrap_or(INDENT_STEP)}/// How far right a row at `indent` (in [`INDENT_STEP`]s) is drawn this frame.@@ -68,7 +68,7 @@ fn indent_x(ctx: &egui::Context, indent: f32) -> f32 {/// frame's step.fn drawn_indent(ui: &egui::Ui, indent: f32) -> f32 {ui.data_mut(|d| {- let m = d.get_temp_mut_or_insert_with::<f32>(egui::Id::new("left-deepest-indent-next"), || 0.0);+ let m = d.get_temp_mut_or_insert_with::<f32>(egui::Id::unique("left-deepest-indent-next"), || 0.0);*m = m.max(indent);});indent_x(ui.ctx(), indent)@@ -145,10 +145,10 @@ fn row_sensed(Some(n) => crate::i18n::tr_format!("{label}, {n} photos", label = said, n = n),None => said.to_string(),};- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, selected, &name));+ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, &name));// what is visible of the row: when the sidebar is scrolled sideways its bars and counts end at// the panel's edge, not at the end of the (wider) content- let visible_right: f32 = ui.data(|d| d.get_temp(egui::Id::new("left-visible-right"))).unwrap_or(f32::MAX);+ let visible_right: f32 = ui.data(|d| d.get_temp(egui::Id::unique("left-visible-right"))).unwrap_or(f32::MAX);let edge = r.right().min(visible_right);let inner = Rect::from_min_max(r.min + vec2(8.0, 0.0), pos2((r.right() - 8.0).min(edge - 8.0).max(r.left() + 8.0), r.bottom()));if selected {@@ -216,7 +216,7 @@ fn out_of_sight(app: &LightcraftApp, ui: &mut egui::Ui, id: &str, label: &str, c/// Whether the sidebar is asked to scroll to the row `id` this frame ([`SCROLL_TO_ROW`]).fn scroll_asked(ui: &egui::Ui, id: &str) -> bool {- ui.data(|d| d.get_temp::<String>(egui::Id::new(SCROLL_TO_ROW))).is_some_and(|want| want == id.to_lowercase())+ ui.data(|d| d.get_temp::<String>(egui::Id::unique(SCROLL_TO_ROW))).is_some_and(|want| want == id.to_lowercase())}/// How wide a row needs to be, from its indent, name, colour dot and count widths. It asks for@@ -260,7 +260,7 @@ fn tree_toggle(ui: &mut egui::Ui, row: &egui::Response, indent: f32, key: egui::set_tree_open(ui, key, *open);}let label = if *open { crate::i18n::tr("Collapse") } else { crate::i18n::tr("Expand") };- tri.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label));+ tri.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label));tri}@@ -286,7 +286,7 @@ fn section(let edge = visible_right(ui).min(header.right());let y = header.top() - SECTION_GAP / 2.0;ui.painter().hline(header.left() + 18.0..=(edge - 18.0).max(header.left() + 18.0), y, egui::Stroke::new(1.0, t.divider));- let show = egui::Id::new("left-show-section");+ let show = egui::Id::unique("left-show-section");if let Some((asked, frame)) = ui.data(|d| d.get_temp::<(SidebarSection, u64)>(show))&& asked == section{@@ -294,7 +294,7 @@ fn section(// asked for by the frame before (a request the section was not drawn for is forgotten),// and up or down only: the sidebar stays where it was scrolled sidewaysif ui.ctx().cumulative_frame_nr().saturating_sub(frame) <= 2 {- let view_top: f32 = ui.data(|d| d.get_temp(egui::Id::new("left-view-top"))).unwrap_or(header.top());+ let view_top: f32 = ui.data(|d| d.get_temp(egui::Id::unique("left-view-top"))).unwrap_or(header.top());let delta = vec2(0.0, view_top - header.top());ui.scroll_with_delta_animation(delta, egui::style::ScrollAnimation::none());}@@ -313,7 +313,7 @@ fn section(/// Where what the panel shows of the sidebar's content ends (screen x): the content is wider/// than the panel while the sidebar scrolls sideways.fn visible_right(ui: &egui::Ui) -> f32 {- ui.data(|d| d.get_temp(egui::Id::new("left-visible-right"))).unwrap_or(f32::MAX)+ ui.data(|d| d.get_temp(egui::Id::unique("left-visible-right"))).unwrap_or(f32::MAX)}/// The header of the open section whose own header has scrolled out of sight stays at the top of@@ -327,7 +327,7 @@ fn pinned_header(app: &mut LightcraftApp, ui: &mut egui::Ui, placed: &[PlacedSecRect::from_x_y_ranges(ui.max_rect().x_range(), top..=top + SECTION_HEADER)});// rows ask where it is (next frame: they are laid out before it)- ui.data_mut(|d| d.insert_temp(egui::Id::new("left-pinned-rect"), rect));+ ui.data_mut(|d| d.insert_temp(egui::Id::unique("left-pinned-rect"), rect));let (Some(p), Some(r)) = (pinned, rect) else { return };let t = Tokens::get(ui.ctx());let view = ui.clip_rect();@@ -338,7 +338,7 @@ fn pinned_header(app: &mut LightcraftApp, ui: &mut egui::Ui, placed: &[PlacedSec// folded from here: its own header comes into view, not whatever was below the section// (next frame, when the section is laid out folded: see `section`)let frame = ui.ctx().cumulative_frame_nr();- ui.data_mut(|d| d.insert_temp(egui::Id::new("left-show-section"), (p.section, frame)));+ ui.data_mut(|d| d.insert_temp(egui::Id::unique("left-show-section"), (p.section, frame)));ui.ctx().request_repaint();}}@@ -432,7 +432,7 @@ pub fn section_drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) {let Some(pos) = pos else { return };let t = Tokens::get(ctx);ctx.set_cursor_icon(egui::CursorIcon::Grabbing);- egui::Area::new(egui::Id::new("drag-section")).order(egui::Order::Tooltip).interactable(false).fixed_pos(pos + vec2(14.0, 10.0)).show(+ egui::Area::new(egui::Id::unique("drag-section")).order(egui::Order::Tooltip).interactable(false).fixed_pos(pos + vec2(14.0, 10.0)).show(ctx,|ui| {egui::Frame::NONE.fill(t.accent).corner_radius(10.0).inner_margin(egui::Margin::symmetric(9, 3)).show(ui, |ui| {@@ -452,7 +452,7 @@ fn section_header(app: &mut LightcraftApp, ui: &mut egui::Ui, section: SidebarSelet id = section.id();let title = crate::i18n::tr(section.title());let (interact, widget) = if pinned { ("sidebar-section-pinned", "sidebarSectionPinned") } else { ("sidebar-section", "sidebarSection") };- let resp = ui.interact(r, ui.id().with((interact, id)), Sense::click_and_drag());+ let resp = ui.interact(r, ui.scope_id().with((interact, id)), Sense::click_and_drag());register(ui.ctx(), format!("{widget}:{id}"), r);let toggled = resp.clicked();if toggled {@@ -463,12 +463,12 @@ fn section_header(app: &mut LightcraftApp, ui: &mut egui::Ui, section: SidebarSelet on_button = header_button(section).is_some() && ui.input(|i| i.pointer.press_origin()).is_some_and(|p| header_button_rect(ui, r).contains(p));if resp.drag_started_by(egui::PointerButton::Primary) && !on_button {// picked up by the pinned header, the drag starts inside the top edge (see `drag_auto_scroll`)- ui.data_mut(|d| d.insert_temp(egui::Id::new("left-section-drag-from-pinned"), pinned));+ ui.data_mut(|d| d.insert_temp(egui::Id::unique("left-section-drag-from-pinned"), pinned));app.ui.dragging_section = Some(section);}crate::widgets::context_menu(&resp, |ui| sections_menu(app, ui, Some(section)));let open = !app.ui.sidebar.is_collapsed(section);- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::CollapsingHeader, true, open, title));+ crate::widgets::announce_disclosure(&resp, true, open, title);// what is visible of the header: its bar and count end at the panel's edge, like a row'slet edge = r.right().min(visible_right(ui));let hovered = resp.hovered() && app.ui.dragging_section.is_none();@@ -672,16 +672,16 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {drag_auto_scroll(app, ui);// where the visible part of the content starts (screen y), for the pinned headerlet view_top = ui.cursor().top() + viewport.min.y;- ui.data_mut(|d| d.insert_temp(egui::Id::new("left-view-top"), view_top));+ ui.data_mut(|d| d.insert_temp(egui::Id::unique("left-view-top"), view_top));// rows are as wide as the widest one needs (last frame), at least the panellet wide = viewport.width().max(content_width(ui.ctx()));ui.set_min_width(wide);ui.set_max_width(wide);ui.data_mut(|d| {- d.insert_temp(egui::Id::new("left-content-width-next"), 0.0f32);- d.insert_temp(egui::Id::new("left-deepest-indent-next"), 0.0f32);+ d.insert_temp(egui::Id::unique("left-content-width-next"), 0.0f32);+ d.insert_temp(egui::Id::unique("left-deepest-indent-next"), 0.0f32);// where the visible part of the content ends (screen x), for what stays at the edge- d.insert_temp(egui::Id::new("left-visible-right"), ui.cursor().left() + viewport.max.x);+ d.insert_temp(egui::Id::unique("left-visible-right"), ui.cursor().left() + viewport.max.x);});let src = app.session.source;for (id, icon, label, count, s) in [@@ -719,18 +719,18 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {above.push('|');}above.push_str(name);- set_tree_open(ui, egui::Id::new(("kw-open", above.to_lowercase())), true);+ set_tree_open(ui, egui::Id::unique(("kw-open", above.to_lowercase())), true);}// …and the sidebar scrolls to it- ui.data_mut(|d| d.insert_temp(egui::Id::new(SCROLL_TO_ROW), format!("keyword:{path}").to_lowercase()));+ ui.data_mut(|d| d.insert_temp(egui::Id::unique(SCROLL_TO_ROW), format!("keyword:{path}").to_lowercase()));}// the folder Show in Folders went to: Folders is shown and opened, and so are the// folders above it, also when it was already the one shown and one was folded by hand…if let Some(path) = app.ui.reveal_folder.take() {app.ui.sidebar.reveal(SidebarSection::Folders);- ui.data_mut(|d| d.remove::<Option<String>>(egui::Id::new(LIBFOLDER_REVEALED)));+ ui.data_mut(|d| d.remove::<Option<String>>(egui::Id::unique(LIBFOLDER_REVEALED)));// …and the sidebar scrolls to it- ui.data_mut(|d| d.insert_temp(egui::Id::new(SCROLL_TO_ROW), format!("libfolder:{path}").to_lowercase()));+ ui.data_mut(|d| d.insert_temp(egui::Id::unique(SCROLL_TO_ROW), format!("libfolder:{path}").to_lowercase()));}// Local keeps track of the folder being browsed whether or not it is drawnlet local = local_now(app, ui);@@ -764,22 +764,22 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {};placed.push(at);}- ui.data_mut(|d| d.remove::<String>(egui::Id::new(SCROLL_TO_ROW)));+ ui.data_mut(|d| d.remove::<String>(egui::Id::unique(SCROLL_TO_ROW)));// room below the last section (a section dragged to the end is dropped here)ui.add_space(SECTION_GAP * 2.0);pinned_header(app, ui, &placed, view_top);section_drag(app, ui, &placed);// what the rows asked for becomes next frame's width- let next = ui.data(|d| d.get_temp::<f32>(egui::Id::new("left-content-width-next"))).unwrap_or(0.0);+ let next = ui.data(|d| d.get_temp::<f32>(egui::Id::unique("left-content-width-next"))).unwrap_or(0.0);if (next - content_width(ui.ctx())).abs() > 0.5 {- ui.data_mut(|d| d.insert_temp(egui::Id::new("left-content-width"), next));+ ui.data_mut(|d| d.insert_temp(egui::Id::unique("left-content-width"), next));ui.ctx().request_repaint();}// …and the deepest row drawn (or passed over out of sight) sets next frame's step- let deepest = ui.data(|d| d.get_temp::<f32>(egui::Id::new("left-deepest-indent-next"))).unwrap_or(0.0);+ let deepest = ui.data(|d| d.get_temp::<f32>(egui::Id::unique("left-deepest-indent-next"))).unwrap_or(0.0);let step = step_for(viewport.width(), deepest);if step != indent_step(ui.ctx()) {- ui.data_mut(|d| d.insert_temp(egui::Id::new("left-indent-step"), step));+ ui.data_mut(|d| d.insert_temp(egui::Id::unique("left-indent-step"), step));ui.ctx().request_repaint();}});@@ -831,7 +831,7 @@ fn missing_count(app: &mut LightcraftApp, ui: &mut egui::Ui) -> usize {at: f64,rev: u64,}- let id = egui::Id::new("missing-count");+ let id = egui::Id::unique("missing-count");let now = ui.input(|i| i.time);let rev = app.session.catalog.revision;let mut job: Job = ui.data(|d| d.get_temp(id)).unwrap_or(Job { rev: u64::MAX, at: f64::MIN, ..Default::default() });@@ -1058,7 +1058,7 @@ pub(crate) fn fs_cached_running(ctx: &egui::Context) -> usize {}fn fs_running_counter(ctx: &egui::Context) -> std::sync::Arc<std::sync::atomic::AtomicUsize> {- ctx.data_mut(|d| d.get_temp_mut_or_default::<std::sync::Arc<std::sync::atomic::AtomicUsize>>(egui::Id::new("fs-cached-running")).clone())+ ctx.data_mut(|d| d.get_temp_mut_or_default::<std::sync::Arc<std::sync::atomic::AtomicUsize>>(egui::Id::unique("fs-cached-running")).clone())}/// A file-system answer for `path` (`f(path)`), kept per `kind` and path and refreshed on a worker@@ -1071,7 +1071,7 @@ pub(crate) fn fs_cached<T: Clone + Send + 'static>(ui: &egui::Ui, kind: &'staticrunning: bool,}type Cell<T> = std::sync::Arc<std::sync::Mutex<Entry<T>>>;- let id = egui::Id::new(("fs-cached", kind, path.to_string()));+ let id = egui::Id::unique(("fs-cached", kind, path.to_string()));let now = ui.input(|i| i.time);let cell: Cell<T> = match ui.data(|d| d.get_temp::<Cell<T>>(id)) {Some(c) => c,@@ -1136,13 +1136,13 @@ fn folder_tree(reveal: bool,transient: bool,) {- let open_id = egui::Id::new(("folder-open", place.to_string(), path.to_string()));+ let open_id = egui::Id::unique(("folder-open", place.to_string(), path.to_string()));let sel = current.is_some_and(|c| same_folder(c, path));let on_the_way = !sel && current.is_some_and(|c| lightcraft_catalog::query::folder_within(c, path));let mut open = tree_open(ui, open_id, false);if reveal && on_the_way {// opened once per browsed folder: collapsing it again afterwards sticks- let revealed_id = egui::Id::new(("folder-revealed", place.to_string(), path.to_string()));+ let revealed_id = egui::Id::unique(("folder-revealed", place.to_string(), path.to_string()));let target = current.map(str::to_string);if ui.data(|d| d.get_temp::<Option<String>>(revealed_id)) != Some(target.clone()) {open = true;@@ -1220,7 +1220,7 @@ fn folder_tree(/// One By Date row (`key`: `YYYY`, `YYYY-MM` or `YYYY-MM-DD`); returns whether it is open.fn date_row(app: &mut LightcraftApp, ui: &mut egui::Ui, key: &str, label: &str, count: usize, indent: f32) -> bool {- let open_id = egui::Id::new(("date-open", key.to_string()));+ let open_id = egui::Id::unique(("date-open", key.to_string()));let mut open = tree_open(ui, open_id, false);let sel = app.session.filter.date.as_deref() == Some(key);let resp = row(app, ui, &format!("date:{key}"), Icon::Clock, label, Some(count), sel, indent);@@ -1256,7 +1256,7 @@ fn albums_tree(app: &mut LightcraftApp, ui: &mut egui::Ui, all: &AlbumKids, parelet Some(kids) = all.get(&parent) else { return };for a in kids {if a.folder {- let open_id = egui::Id::new(("folder-open", a.id.0));+ let open_id = egui::Id::unique(("folder-open", a.id.0));let mut open = tree_open(ui, open_id, true);if open_to.contains(&a.id) && !open {open = true;@@ -1348,7 +1348,7 @@ fn pointer_over_row(ui: &egui::Ui, rect: Rect) -> bool {/// Where the pinned header was drawn last frame, if one was (rows are laid out before it).fn pinned_rect(ui: &egui::Ui) -> Option<Rect> {- ui.data(|d| d.get_temp::<Option<Rect>>(egui::Id::new("left-pinned-rect"))).flatten()+ ui.data(|d| d.get_temp::<Option<Rect>>(egui::Id::unique("left-pinned-rect"))).flatten()}fn pointer_on_pinned_header(ui: &egui::Ui) -> bool {@@ -1380,7 +1380,7 @@ fn drag_auto_scroll(app: &LightcraftApp, ui: &egui::Ui) {let Some(p) = ui.input(|i| i.pointer.latest_pos()).filter(|p| p.x >= view.left() && p.x <= view.right()) else { return };// a section picked up by its pinned header starts inside the top edge: it scrolls once it has// left the header. Any other drag scrolls there as at any edge, to reach what is above- let from_pinned = egui::Id::new("left-section-drag-from-pinned");+ let from_pinned = egui::Id::unique("left-section-drag-from-pinned");if app.ui.dragging_section.is_some() && ui.data(|d| d.get_temp::<bool>(from_pinned)) == Some(true) {if pointer_on_pinned_header(ui) {return;@@ -1429,7 +1429,7 @@ fn forget_hover(app: &LightcraftApp, ctx: &egui::Context) {let ids: Vec<u64> = app.session.catalog.albums().filter(|a| a.folder).map(|a| a.id.0).collect();ctx.data_mut(|d| {for id in ids {- d.remove_temp::<f64>(egui::Id::new(("album-hover", id)));+ d.remove_temp::<f64>(egui::Id::unique(("album-hover", id)));}});}@@ -1497,7 +1497,7 @@ fn album_drop_at(app: &LightcraftApp, dragged: AlbumId, target: &Album, frac: f3/// done on release. A closed folder with something inside (`open`) opens once the pointer rests on/// it; returns whether it did.fn album_drag_over(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, row: &Album, open: Option<&mut bool>, indent: f32) -> bool {- let hover_id = egui::Id::new(("album-hover", row.id.0));+ let hover_id = egui::Id::unique(("album-hover", row.id.0));let Some(dragged) = app.ui.dragging_album.map(AlbumId) else { return false };let pos = ui.input(|i| i.pointer.latest_pos()).filter(|_| pointer_over_row(ui, resp.rect));let Some(pos) = pos else {@@ -1586,11 +1586,14 @@ pub fn album_drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) {let (Some(pos), Some(name)) = (pos, app.session.catalog.album(AlbumId(id)).map(|a| a.name.clone())) else { return };let t = Tokens::get(ctx);ctx.set_cursor_icon(egui::CursorIcon::Grabbing);- egui::Area::new(egui::Id::new("drag-album")).order(egui::Order::Tooltip).interactable(false).fixed_pos(pos + vec2(14.0, 10.0)).show(ctx, |ui| {- egui::Frame::NONE.fill(t.accent).corner_radius(10.0).inner_margin(egui::Margin::symmetric(9, 3)).show(ui, |ui| {- ui.label(egui::RichText::new(name).color(egui::Color32::WHITE).font(t.semibold(12.0)));- });- });+ egui::Area::new(egui::Id::unique("drag-album")).order(egui::Order::Tooltip).interactable(false).fixed_pos(pos + vec2(14.0, 10.0)).show(+ ctx,+ |ui| {+ egui::Frame::NONE.fill(t.accent).corner_radius(10.0).inner_margin(egui::Margin::symmetric(9, 3)).show(ui, |ui| {+ ui.label(egui::RichText::new(name).color(egui::Color32::WHITE).font(t.semibold(12.0)));+ });+ },+ );}/// An album row while photos are dragged from the grid: highlighted under the pointer; a@@ -1812,7 +1815,7 @@ fn is_within(app: &LightcraftApp, id: lightcraft_catalog::AlbumId, ancestor: ligfn reveal_chosen(app: &LightcraftApp, ui: &egui::Ui, tree: &[FolderNode]) {let shown = app.session.library_folder.clone().filter(|_| app.session.source == LibrarySource::LibraryFolder);let chosen = shown.filter(|c| !lightcraft_catalog::query::folder_key(c).is_empty());- let seen = egui::Id::new(LIBFOLDER_REVEALED);+ let seen = egui::Id::unique(LIBFOLDER_REVEALED);let now = chosen.as_deref().map(lightcraft_catalog::query::folder_key);if ui.data(|d| d.get_temp::<Option<String>>(seen)) == Some(now.clone()) {return;@@ -1823,7 +1826,7 @@ fn reveal_chosen(app: &LightcraftApp, ui: &egui::Ui, tree: &[FolderNode]) {for n in nodes {if lightcraft_catalog::query::folder_within(chosen, &n.path) && !same_folder(chosen, &n.path) {let key = lightcraft_catalog::query::folder_key(&n.path);- ui.data_mut(|d| d.insert_temp(egui::Id::new(("libfolder-open", key)), true));+ ui.data_mut(|d| d.insert_temp(egui::Id::unique(("libfolder-open", key)), true));open_above(ui, &n.children, chosen);}}@@ -1844,7 +1847,7 @@ pub(crate) fn folder_row_of<'a>(tree: &'a [FolderNode], dir: &str) -> Option<&'afn folder_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, nodes: &[FolderNode], indent: f32) {for n in nodes {let key = lightcraft_catalog::query::folder_key(&n.path);- let open_id = egui::Id::new(("libfolder-open", key.clone()));+ let open_id = egui::Id::unique(("libfolder-open", key.clone()));// a disk starts open, and so does a folder that holds nothing itself and leads to one// folder (`Users` → `me`): the first row where the library branches is what you look forlet leads_on = n.own == 0 && n.children.len() == 1;@@ -1970,7 +1973,7 @@ fn spring_open(ui: &egui::Ui, n: &FolderNode, open_id: egui::Id, open: &mut boolif *open || n.children.is_empty() {return;}- let key = egui::Id::new("folder-spring-open");+ let key = egui::Id::unique("folder-spring-open");let (now, frame) = (ui.input(|i| i.time), ui.ctx().cumulative_frame_nr());// held without a break: over this row last frame toolet since = match ui.data(|d| d.get_temp::<(String, f64, u64)>(key)) {@@ -2200,7 +2203,7 @@ fn folder_menu_for_library(app: &mut LightcraftApp, resp: &egui::Response, n: &Ffn keyword_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, nodes: &[KeywordNode], indent: f32) {for n in nodes {// leaves (most keywords) have no open state to look up- let open_id = (!n.children.is_empty()).then(|| egui::Id::new(("kw-open", n.path.to_lowercase())));+ let open_id = (!n.children.is_empty()).then(|| egui::Id::unique(("kw-open", n.path.to_lowercase())));let mut open = open_id.is_some_and(|k| tree_open(ui, k, false));let id = format!("keyword:{}", n.path);if !out_of_sight(app, ui, &id, &n.name, Some(n.count), indent, false) {diff --git a/crates/ui-egui/src/panels/library_problem.rs b/crates/ui-egui/src/panels/library_problem.rsindex 212e57d90..ac0dff431 100644--- a/crates/ui-egui/src/panels/library_problem.rs+++ b/crates/ui-egui/src/panels/library_problem.rs@@ -90,7 +90,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {}let t = Tokens::get(ctx);let screen = ctx.content_rect();- egui::Area::new(egui::Id::new("library-problem-dim")).order(egui::Order::Middle).fixed_pos(screen.min).interactable(true).show(ctx, |ui| {+ egui::Area::new(egui::Id::unique("library-problem-dim")).order(egui::Order::Middle).fixed_pos(screen.min).interactable(true).show(ctx, |ui| {// swallows clicks: nothing behind the window can be used meanwhileui.allocate_rect(screen, egui::Sense::click_and_drag());ui.painter().rect_filled(screen, 0.0, egui::Color32::from_black_alpha(160));@@ -98,7 +98,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {let mut choice = None;let frame = egui::Frame::window(&ctx.global_style()).inner_margin(egui::Margin::symmetric(18, 14));egui::Window::new(crate::i18n::tr("Your library couldn't be opened"))- .id(egui::Id::new("library-problem"))+ .id(egui::Id::unique("library-problem")).order(egui::Order::Foreground).collapsible(false).resizable(false)diff --git a/crates/ui-egui/src/panels/mask_effects.rs b/crates/ui-egui/src/panels/mask_effects.rsindex 6062d241c..355308b61 100644--- a/crates/ui-egui/src/panels/mask_effects.rs+++ b/crates/ui-egui/src/panels/mask_effects.rs@@ -123,7 +123,7 @@ struct MenuState {}fn state_id() -> egui::Id {- egui::Id::new("maskEffectMenuState")+ egui::Id::unique("maskEffectMenuState")}/// The effects the menu lists for `query`: (section heading, effect name, its row widget id).diff --git a/crates/ui-egui/src/panels/masking.rs b/crates/ui-egui/src/panels/masking.rsindex 4fb31be80..91a4e856b 100644--- a/crates/ui-egui/src/panels/masking.rs+++ b/crates/ui-egui/src/panels/masking.rs@@ -264,7 +264,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {if ui.rect_contains_pointer(r) || !m.visible {let er = Rect::from_center_size(pos2(r.right() - 16.0, r.center().y), vec2(22.0, 22.0));register(ui.ctx(), format!("maskVisible:{}", m.id), er);- let eye = ui.interact(er, egui::Id::new(("maskVisible", m.id)), Sense::click());+ let eye = ui.interact(er, egui::Id::unique(("maskVisible", m.id)), Sense::click());crate::widgets::announce_selected(&eye, crate::i18n::tr("Show mask"), m.visible);paint(ui.painter(),diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rsindex 2fcb36663..b603e3eb3 100644--- a/crates/ui-egui/src/panels/mod.rs+++ b/crates/ui-egui/src/panels/mod.rs@@ -59,11 +59,14 @@ pub fn resizable_side(reserve: f32,add: impl FnOnce(&mut egui::Ui),) -> Option<f32> {- let pid = egui::Id::new(id);+ // `Panel::new` stores `IdSalt::new(id)`; the panel's persisted key is+ // `parent_ui.scope_id().with_salt(that_salt)`, which is exactly `scope_id().with(id)`.+ // (Passing an already-built `Id` through `Panel::left` would salt it a second time.)+ let pid = ui.scope_id().with(id);ui.ctx().data_mut(|d| d.remove::<egui::containers::panel::PanelState>(pid));let avail = ui.available_rect_before_wrap();let max = (avail.width() - reserve - crate::state::MIN_PHOTO_WIDTH).clamp(limits.min, limits.max);- let panel = if left { egui::Panel::left(pid) } else { egui::Panel::right(pid) };+ let panel = if left { egui::Panel::left(id) } else { egui::Panel::right(id) };let r = panel.frame(frame).resizable(true).size_range(limits.min..=max).default_size(limits.clamp(width).min(max)).show(ui, add);crate::widgets::register(ui.ctx(), format!("panel:{id}"), r.response.rect);// egui names the edge's drag widget `<panel id>.with("__resize")`; the width is measured from@@ -78,7 +81,7 @@ pub fn resizable_side(/// The HUD toast at the bottom centre of the canvas.pub fn toast(app: &mut LightcraftApp, ctx: &egui::Context) {- let now = ctx.input(|i| i.time);+ let now = app.tick_now();let Some((text, until, label)) = app.ui.toast.clone() else { return };if now > until {app.ui.toast = None;@@ -87,7 +90,7 @@ pub fn toast(app: &mut LightcraftApp, ctx: &egui::Context) {let Some(canvas) = app.canvas_rect else { return };let t = Tokens::get(ctx);let fade = ((until - now) / 0.25).clamp(0.0, 1.0) as f32;- let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("toast")));+ let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("toast")));// long messages (a save warning, the web build's notices) wrap within the canvaslet wrap = (canvas.width() - 80.0).clamp(200.0, 720.0);let (background, foreground) = label.map(crate::theme::label_toast_colors).unwrap_or((egui::Color32::from_black_alpha(200), t.text));diff --git a/crates/ui-egui/src/panels/notices.rs b/crates/ui-egui/src/panels/notices.rsindex 016323e95..beeff2e03 100644--- a/crates/ui-egui/src/panels/notices.rs+++ b/crates/ui-egui/src/panels/notices.rs@@ -92,14 +92,14 @@ enum Choice {fn window(ctx: &egui::Context, id: &str, title: &str, text: &str, buttons: &[(&str, &str, Choice)]) -> Option<usize> {let t = Tokens::get(ctx);let screen = ctx.content_rect();- egui::Area::new(egui::Id::new((id, "dim"))).order(egui::Order::Middle).fixed_pos(screen.min).show(ctx, |ui| {+ egui::Area::new(egui::Id::unique((id, "dim"))).order(egui::Order::Middle).fixed_pos(screen.min).show(ctx, |ui| {ui.allocate_rect(screen, egui::Sense::click_and_drag());ui.painter().rect_filled(screen, 0.0, egui::Color32::from_black_alpha(140));});let mut chosen = None;let frame = egui::Frame::window(&ctx.global_style()).inner_margin(egui::Margin::symmetric(18, 14));egui::Window::new(crate::i18n::tr(title))- .id(egui::Id::new(id))+ .id(egui::Id::unique(id)).order(egui::Order::Foreground).collapsible(false).resizable(false)diff --git a/crates/ui-egui/src/panels/people.rs b/crates/ui-egui/src/panels/people.rsindex c5cd27b40..380bd829f 100644--- a/crates/ui-egui/src/panels/people.rs+++ b/crates/ui-egui/src/panels/people.rs@@ -156,7 +156,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {fn card(app: &mut LightcraftApp, ui: &mut egui::Ui, person: &Person, r: Rect, edge: f32, ppp: f32, selected: bool) {let t = Tokens::get(ui.ctx());let face = Rect::from_min_size(r.min, vec2(edge, edge));- let resp = ui.interact(r, egui::Id::new(("person-card", &person.name)), Sense::click());+ let resp = ui.interact(r, egui::Id::unique(("person-card", &person.name)), Sense::click());crate::widgets::announce(&resp, person.name.clone());register(ui.ctx(), format!("person:{}", person.name), r);let view = app.session.face_view(person.photo, person.face);diff --git a/crates/ui-egui/src/panels/person.rs b/crates/ui-egui/src/panels/person.rsindex f2c719d43..eab26a271 100644--- a/crates/ui-egui/src/panels/person.rs+++ b/crates/ui-egui/src/panels/person.rs@@ -129,7 +129,8 @@ pub(crate) fn handle_bulk_key(app: &mut LightcraftApp, ctx: &egui::Context) -> b.or_else(|| {page.more.iter().filter(|f| !app.ui.dismissed_faces.contains(&(f.photo, f.index))).find(|f| {ctx.memory(|m| {- m.has_focus(egui::Id::new(("more-face", f.photo, f.index))) || m.has_focus(egui::Id::new(("more-face-above", f.photo, f.index)))+ m.has_focus(egui::Id::unique(("more-face", f.photo, f.index)))+ || m.has_focus(egui::Id::unique(("more-face-above", f.photo, f.index)))})})});@@ -291,14 +292,14 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, name: &str) {fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect, f: &Face, ppp: f32, more: bool, name: &str, above_count: usize) -> Hit {let t = Tokens::get(ui.ctx());let salt = if more { "more-face" } else { "person-face" };- let resp = ui.interact(r, egui::Id::new((salt, f.photo, f.index)), Sense::click());+ let resp = ui.interact(r, egui::Id::unique((salt, f.photo, f.index)), Sense::click());crate::widgets::announce(&resp, name.to_string());register(ui.ctx(), format!("{salt}:{}:{}", f.photo, f.index), r);// the × is added after the tile, so it wins where they overlaplet x_rect = Rect::from_min_size(pos2(r.right() - 24.0, r.top() + 4.0), vec2(20.0, 20.0));- let x_resp = more.then(|| ui.interact(x_rect, egui::Id::new(("more-face-x", f.photo, f.index)), Sense::click()));+ let x_resp = more.then(|| ui.interact(x_rect, egui::Id::unique(("more-face-x", f.photo, f.index)), Sense::click()));let above_rect = Rect::from_min_size(pos2(r.left() + 4.0, r.top() + 4.0), vec2(24.0, 20.0));- let above_resp = more.then(|| ui.interact(above_rect, egui::Id::new(("more-face-above", f.photo, f.index)), Sense::click()));+ let above_resp = more.then(|| ui.interact(above_rect, egui::Id::unique(("more-face-above", f.photo, f.index)), Sense::click()));if more {register(ui.ctx(), format!("more-face-above:{}:{}", f.photo, f.index), above_rect);}diff --git a/crates/ui-egui/src/panels/presets.rs b/crates/ui-egui/src/panels/presets.rsindex a8cf21424..fc8eee09c 100644--- a/crates/ui-egui/src/panels/presets.rs+++ b/crates/ui-egui/src/panels/presets.rs@@ -62,7 +62,7 @@ impl AppliedByPhoto {/// Remember `preset` on the photos `preset.apply` just changed (the selection, else the active/// photo; an active photo outside the selection wasn't changed and isn't marked).fn remember(ctx: &egui::Context, session: &lightcraft_engine::Session, preset: &str) {- let id = egui::Id::new(Self::ID);+ let id = egui::Id::unique(Self::ID);let mut map: Self = ctx.data(|d| d.get_temp(id)).unwrap_or_default();for photo in session.selected() {if let Some(d) = session.develop_of(photo) {@@ -75,7 +75,7 @@ impl AppliedByPhoto {/// The preset to mark for `photo`: the one it was given, while its settings are unchanged since.fn of(ctx: &egui::Context, session: &lightcraft_engine::Session, photo: Option<lightcraft_catalog::PhotoId>) -> Option<String> {let photo = photo?;- let map: Self = ctx.data(|d| d.get_temp(egui::Id::new(Self::ID)))?;+ let map: Self = ctx.data(|d| d.get_temp(egui::Id::unique(Self::ID)))?;let (preset, then) = map.0.get(&photo)?;let now = session.develop_of(photo)?;(Arc::ptr_eq(then, &now) || **then == *now).then(|| preset.clone())@@ -121,7 +121,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {});divider(ui);// amount slider (applies to the last applied preset)- let amt_id = egui::Id::new("preset-amount");+ let amt_id = egui::Id::unique("preset-amount");let last: Option<AppliedPreset> = ui.data(|d| d.get_temp(amt_id));if let Some(last) = last.clone().filter(|last| last.is_current(&app.session)) {let spec = ControlSpec {@@ -167,7 +167,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {let visible = ui.clip_rect().expand(row_h);for grp in groups.iter() {let (g, builtin) = (grp.name.clone(), grp.builtin);- let open_id = egui::Id::new(("preset-group", &g));+ let open_id = egui::Id::unique(("preset-group", &g));let open: bool = ui.data(|d| d.get_temp(open_id)).unwrap_or(true);let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 32.0), Sense::click());crate::widgets::announce(&resp, g.to_string());@@ -236,13 +236,13 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {let label = crate::i18n::tr_format!("Preset: {name}", name = name);app.hover_preview = Some(HoverPreview { label: label.clone(), settings: s });if let Some(id) = active {- ui.data_mut(|d| d.insert_temp(egui::Id::new("last-preset-hover"), (id, pr.clone(), label)));+ ui.data_mut(|d| d.insert_temp(egui::Id::unique("last-preset-hover"), (id, pr.clone(), label)));}}if resp.clicked() && app.run("preset.apply", json!({"id": pid, "amount": 100})).is_ok() {AppliedByPhoto::remember(ui.ctx(), &app.session, &pid);ui.data_mut(|d| d.insert_temp(amt_id, AppliedPreset::new(&app.session, pid.clone(), 100.0)));- ui.data_mut(|d| d.remove::<(lightcraft_catalog::PhotoId, Preset, String)>(egui::Id::new("last-preset-hover")));+ ui.data_mut(|d| d.remove::<(lightcraft_catalog::PhotoId, Preset, String)>(egui::Id::unique("last-preset-hover")));app.toast(ui.ctx(), crate::i18n::tr_format!("Preset: {name}", name = name));}let (builtin, group) = (pr.builtin, pr.group.clone());@@ -296,7 +296,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {}ui.add_space(30.0);});- let last_hover_id = egui::Id::new("last-preset-hover");+ let last_hover_id = egui::Id::unique("last-preset-hover");let pointer_in_scroll = ui.ctx().input(|i| i.pointer.hover_pos()).is_some_and(|pos| scroll.inner_rect.contains(pos));if pointer_in_scroll {if app.hover_preview.is_none()@@ -327,7 +327,7 @@ struct Group {/// The presets by group (groups sorted by name, presets in list order), rebuilt only when the/// list changed (its generation).fn grouped(ctx: &egui::Context, presets: &PresetList) -> Arc<Vec<Group>> {- let id = egui::Id::new("presets-grouped");+ let id = egui::Id::unique("presets-grouped");if let Some((generation, groups)) = ctx.data(|d| d.get_temp::<(u64, Arc<Vec<Group>>)>(id))&& generation == presets.generation(){@@ -349,7 +349,7 @@ fn grouped(ctx: &egui::Context, presets: &PresetList) -> Arc<Vec<Group>> {/// wherever the group changes. Only the rows in view are built (10 000+ presets made an open/// picker take seconds a frame). Returns the id of the preset clicked.pub fn picker_rows(ui: &mut egui::Ui, salt: &str, presets: &PresetList, selected: Option<&str>) -> Option<String> {- let id = egui::Id::new("preset-picker-rows");+ let id = egui::Id::unique("preset-picker-rows");let rows = match ui.ctx().data(|d| d.get_temp::<(u64, Arc<Vec<PickRow>>)>(id)) {Some((generation, rows)) if generation == presets.generation() => rows,_ => {diff --git a/crates/ui-egui/src/panels/profiles.rs b/crates/ui-egui/src/panels/profiles.rsindex 8a4b08345..5bb6c341a 100644--- a/crates/ui-egui/src/panels/profiles.rs+++ b/crates/ui-egui/src/panels/profiles.rs@@ -72,7 +72,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {}for (title, tag, imported, list) in sections {// an imported folder named like a built-in group still opens and closes on its own- let open_id = egui::Id::new(("profile-group", imported, title));+ let open_id = egui::Id::unique(("profile-group", imported, title));let open: bool = ui.data(|m| m.get_temp(open_id)).unwrap_or(true);let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 32.0), Sense::click());crate::widgets::announce(&resp, title.to_string());@@ -110,7 +110,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {ui.add_space(6.0);}ui.add_space(30.0);- let last_hover_id = egui::Id::new("last-profile-hover");+ let last_hover_id = egui::Id::unique("last-profile-hover");let pointer_in_profiles = ui.ctx().input(|i| i.pointer.hover_pos()).is_some_and(|pos| ui.max_rect().contains(pos));if pointer_in_profiles {if app.hover_preview.is_none()@@ -153,7 +153,7 @@ fn cell_ui(let (p_id, p_name, p_group) = (p.0.as_str(), p.1.as_str(), p.2.as_str());let t = Tokens::get(ui.ctx());let key = if tag.is_empty() { format!("profileCell:{p_id}") } else { format!("profileCell:{tag}:{p_id}") };- let resp = ui.interact(cell, egui::Id::new(&key), Sense::click());+ let resp = ui.interact(cell, egui::Id::unique(&key), Sense::click());crate::widgets::announce(&resp, p_name.to_string());register(ui.ctx(), key, cell);let thumb = Rect::from_min_size(cell.min, vec2(cell.width(), th));@@ -187,10 +187,10 @@ fn cell_ui(if resp.hovered() && !applied && !over_star {app.hover_preview =Some(HoverPreview { label: crate::i18n::tr_format!("Profile: {}", crate::i18n::profile_label(p_id, p_name)), settings: s.clone() });- ui.data_mut(|m| m.insert_temp(egui::Id::new("last-profile-hover"), (id, p_id.to_string())));+ ui.data_mut(|m| m.insert_temp(egui::Id::unique("last-profile-hover"), (id, p_id.to_string())));} else if resp.hovered() && applied {// resting on the applied profile shows it (no preview), not the last other profile hovered- ui.data_mut(|m| m.remove::<(PhotoId, String)>(egui::Id::new("last-profile-hover")));+ ui.data_mut(|m| m.remove::<(PhotoId, String)>(egui::Id::unique("last-profile-hover")));}let resp = resp.on_hover_text(format!("{} ({})",@@ -202,7 +202,7 @@ fn cell_ui(let _ = app.run("profile.favorite", json!({"id": p_id}));} else if !applied {let _ = app.run("develop.profile", json!({"id": p_id, "amount": 100}));- ui.data_mut(|m| m.remove::<(PhotoId, String)>(egui::Id::new("last-profile-hover")));+ ui.data_mut(|m| m.remove::<(PhotoId, String)>(egui::Id::unique("last-profile-hover")));}}}diff --git a/crates/ui-egui/src/panels/right.rs b/crates/ui-egui/src/panels/right.rsindex 79cd28712..af61212ca 100644--- a/crates/ui-egui/src/panels/right.rs+++ b/crates/ui-egui/src/panels/right.rs@@ -45,13 +45,13 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {area = area.vertical_scroll_offset(offset);}// (where the pass starts: by its end egui may have pulled a shrunken panel's offset back)- let area_id = ui.data(|d| d.get_temp::<egui::Id>(egui::Id::new(AREA)));- let start = held.or_else(|| area_id.and_then(|a| egui::scroll_area::State::load(ui.ctx(), a)).map(|s| s.offset.y));+ let area_id = ui.data(|d| d.get_temp::<egui::Id>(egui::Id::unique(AREA)));+ let start = held.or_else(|| area_id.and_then(|a| egui::scroll_area::State::load(ui.ctx(), a)).map(|s| s.clamped_offset().y));ui.data_mut(|d| match start {Some(o) => {- d.insert_temp(egui::Id::new(OFFSET), o);+ d.insert_temp(egui::Id::unique(OFFSET), o);}- None => d.remove::<f32>(egui::Id::new(OFFSET)),+ None => d.remove::<f32>(egui::Id::unique(OFFSET)),});let scrolled = area.show(ui, |ui| {ui.spacing_mut().item_spacing.y = 0.0;@@ -69,7 +69,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {RightPanel::None => {}}});- ui.data_mut(|d| d.insert_temp(egui::Id::new(AREA), scrolled.id));+ ui.data_mut(|d| d.insert_temp(egui::Id::unique(AREA), scrolled.id));});}@@ -83,11 +83,11 @@ const HOLD: &str = "right-scroll-hold";/// the Keywords box grew. Set on the scroll area as it starts, so the pass drawn again shows the list/// in place (a scroll asked for during a pass only lands a frame later).fn held_offset(ctx: &egui::Context) -> Option<f32> {- let (grew, asked) = ctx.data_mut(|d| d.remove_temp::<(f32, u64)>(egui::Id::new(HOLD)))?;+ let (grew, asked) = ctx.data_mut(|d| d.remove_temp::<(f32, u64)>(egui::Id::unique(HOLD)))?;if asked.checked_add(1) != Some(ctx.cumulative_pass_nr()) {return None;}- let offset = ctx.data(|d| d.get_temp::<f32>(egui::Id::new(OFFSET)))?;+ let offset = ctx.data(|d| d.get_temp::<f32>(egui::Id::unique(OFFSET)))?;Some((offset + grew).max(0.0)).filter(|o| o.is_finite())}@@ -109,7 +109,7 @@ pub fn fold_header(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, title:pub fn fold_title(app: &mut LightcraftApp, ui: &egui::Ui, id: &str, r: Rect, resp: &egui::Response, title: &str) -> bool {let t = Tokens::get(ui.ctx());let open = !app.ui.section_folded(id);- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::CollapsingHeader, true, open, title));+ crate::widgets::announce_disclosure(resp, true, open, title);register(ui.ctx(), format!("section:{id}"), r);let p = ui.painter();if resp.hovered() {@@ -178,7 +178,7 @@ fn aspect_label(aspect: Option<(u32, u32)>, original: Option<f64>) -> String {/// "Custom" row of the aspect menu: two number fields and an Apply button (`crop.aspect` `[w, h]`).fn custom_aspect(app: &mut LightcraftApp, ui: &mut egui::Ui) {- let key = egui::Id::new("crop-custom-aspect");+ let key = egui::Id::unique("crop-custom-aspect");let (mut w, mut h): (String, String) = ui.data_mut(|d| d.get_temp(key)).unwrap_or_else(|| ("3".into(), "2".into()));let mut apply = false;ui.horizontal(|ui| {@@ -293,7 +293,7 @@ fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {// apply only a new angle// Esc keeps the old angle, but egui applies the typed text on the frame after the// one where Esc took the focus away: remember the Esc for that frame- let cancel = egui::Id::new("cropAngleFieldEscaped");+ let cancel = egui::Id::unique("cropAngleFieldEscaped");let escaped = ui.data_mut(|m| m.remove_temp::<bool>(cancel)).unwrap_or(false);if escape && r.lost_focus() {ui.data_mut(|m| m.insert_temp(cancel, true));@@ -744,7 +744,7 @@ fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {}// GPS: typed as "lat, lon" (or degrees / minutes / seconds); empty clears itlet gps = m.gps.map(|(la, lo)| format!("{la:.6}, {lo:.6}")).unwrap_or_default();- let gid = egui::Id::new("info-gps");+ let gid = egui::Id::unique("info-gps");ui.label(egui::RichText::new("GPS").size(11.5).color(t.text_dim));let mut text: String = ui.data(|d| d.get_temp(gid)).unwrap_or_else(|| gps.clone());let r = ui.add(egui::TextEdit::singleline(&mut text).hint_text(crate::i18n::tr("latitude, longitude")).desired_width(f32::INFINITY));@@ -909,6 +909,7 @@ fn copyright_status(app: &mut LightcraftApp, ui: &mut egui::Ui, current: lightcr}}});+ crate::widgets::name_combo(&r.response, crate::i18n::tr("Copyright Status"));register(ui.ctx(), "field:copyrightStatus", r.response.rect);ui.add_space(6.0);}@@ -916,7 +917,7 @@ fn copyright_status(app: &mut LightcraftApp, ui: &mut egui::Ui, current: lightcrfn meta_field(app: &mut LightcraftApp, ui: &mut egui::Ui, label: &str, key: &str, value: &str, lines: usize) {let t = Tokens::get(ui.ctx());ui.label(egui::RichText::new(crate::i18n::tr(label)).size(11.5).color(t.text_dim));- let id = egui::Id::new(("info-field", key));+ let id = egui::Id::unique(("info-field", key));let mut text: String = ui.data(|d| d.get_temp(id)).unwrap_or_else(|| value.to_string());let widget = format!("field:{key}");let field = if lines > 1 {@@ -956,7 +957,7 @@ fn keywords(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {fn keywording(app: &mut LightcraftApp, ui: &mut egui::Ui) {let t = Tokens::get(ui.ctx());padded(ui, |ui| {- let kid = egui::Id::new("kw-input");+ let kid = egui::Id::unique("kw-input");let mut text = ui.data_mut(|d| d.get_temp::<String>(kid).unwrap_or_default());// the keywords every selected photo has: those only some have are still offered and suggestedlet selection = app.session.selected();@@ -965,7 +966,7 @@ fn keywording(app: &mut LightcraftApp, ui: &mut egui::Ui) {// while the box has the cursor it offers the library's keywords for what is being typed,// right under itself; it stays for a click on one of them, which takes the cursor awaylet field = crate::text_field::id("field:keyword");- let oid = egui::Id::new("kw-offers");+ let oid = egui::Id::unique("kw-offers");let pass = ui.ctx().cumulative_pass_nr();// (remembered from the last frame: the text the highlight was for and the keyword it was// on, where the offers were drawn, and whether the box was in sight)@@ -1012,7 +1013,7 @@ fn keywording(app: &mut LightcraftApp, ui: &mut egui::Ui) {// (after an offer was taken the box starts a new edit, empty: Esc has nothing to bring back)// (asked for on the frame before this one only: a box that wasn't drawn then, its panel// switched away, doesn't claim the cursor whenever it is next drawn)- let bid = egui::Id::new("kw-begin");+ let bid = egui::Id::unique("kw-begin");let begin = ui.data_mut(|d| d.remove_temp::<u64>(bid)).is_some_and(|asked| asked.checked_add(1) == Some(pass));let r = crate::text_field::TextField::singleline("field:keyword", &mut text).hint(crate::i18n::tr("Add keyword"))@@ -1081,7 +1082,7 @@ fn keywording(app: &mut LightcraftApp, ui: &mut egui::Ui) {ui.add_space(8.0);// the painter: click photos in the grid to give them (or take away) a keywordui.horizontal(|ui| {- let pid = egui::Id::new("kw-painter");+ let pid = egui::Id::unique("kw-painter");let painting = app.ui.keyword_painter.clone();let mut k: String = ui.data(|d| d.get_temp(pid)).unwrap_or_else(|| painting.clone().unwrap_or_default());// (fixed while painting: Stop first)@@ -1139,7 +1140,7 @@ fn keywording(app: &mut LightcraftApp, ui: &mut egui::Ui) {/// while the change does not come from the box itself (the pointer on it, or typing in its field).fn hold_list_in_place(ui: &mut egui::Ui, top: f32) {let height = ui.cursor().top() - top;- let key = egui::Id::new("kw-box-height");+ let key = egui::Id::unique("kw-box-height");let pass = ui.ctx().cumulative_pass_nr();// (the height drawn on the pass before: one from an earlier visit to the panel says nothing)let before = ui.data(|d| d.get_temp::<(f32, u64)>(key)).filter(|&(_, drawn)| drawn.checked_add(1) == Some(pass)).map(|(h, _)| h);@@ -1156,7 +1157,7 @@ fn hold_list_in_place(ui: &mut egui::Ui, top: f32) {if on_box || typing {return;}- ui.data_mut(|d| d.insert_temp(egui::Id::new(HOLD), (grew, pass)));+ ui.data_mut(|d| d.insert_temp(egui::Id::unique(HOLD), (grew, pass)));// (drawn again at once at the new offset, so the list never shows a frame out of place)ui.ctx().request_discard("the Keyword List holds its place");}@@ -1216,6 +1217,7 @@ fn keyword_set(app: &mut LightcraftApp, ui: &mut egui::Ui) {let _ = app.run("keyword.deleteSet", json!({"name": current}));}});+ crate::widgets::name_combo(&combo.response, crate::i18n::tr("Keyword Set"));register(ui.ctx(), "keywordSetCombo", combo.response.rect);});let kws: Vec<String> = sets["keywords"].as_array().into_iter().flatten().filter_map(|k| k.as_str().map(str::to_string)).collect();@@ -1271,7 +1273,7 @@ fn versions(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {}ui.add_space(8.0);// Named (made by you) and Auto (made by LightCraft) versions- let tab_id = egui::Id::new("versions-tab");+ let tab_id = egui::Id::unique("versions-tab");let mut auto: bool = ui.data(|d| d.get_temp(tab_id)).unwrap_or(false);let named_n = p.versions.iter().filter(|v| !v.auto).count();let items = [("Named", "named"), ("Auto", "auto")];diff --git a/crates/ui-egui/src/panels/rules_editor.rs b/crates/ui-egui/src/panels/rules_editor.rsindex d69a8fa43..c4504fe4c 100644--- a/crates/ui-egui/src/panels/rules_editor.rs+++ b/crates/ui-egui/src/panels/rules_editor.rs@@ -51,11 +51,12 @@ fn match_combo(ui: &mut egui::Ui, salt: &str, m: &mut Match) {Match::Any => "any",Match::None => "none",};- crate::widgets::combo_box(format!("{salt}-match")).width(64.0).selected_text(crate::i18n::tr(label(*m))).show_ui(ui, |ui| {+ let combo = crate::widgets::combo_box(format!("{salt}-match")).width(64.0).selected_text(crate::i18n::tr(label(*m))).show_ui(ui, |ui| {for x in [Match::All, Match::Any, Match::None] {ui.selectable_value(m, x, crate::i18n::tr(label(x)));}});+ crate::widgets::name_combo(&combo.response, crate::i18n::tr("Match"));}fn text_value(ui: &mut egui::Ui, v: &mut Value, width: f32, hint: &str, salt: &str) {@@ -149,7 +150,7 @@ fn value_editor(ui: &mut egui::Ui, field: &str, op: &str, v: &mut Value, salt: &let mut unit = stored_unit.to_lowercase();let mut changed =ui.add(egui::DragValue::new(&mut n).range(1.0..=10_000.0).clamp_existing_to_range(false).speed(0.2).fixed_decimals(0)).changed();- crate::widgets::combo_box(format!("{salt}-unit")).width(70.0).selected_text(crate::i18n::tr(&unit)).show_ui(ui, |ui| {+ let combo = crate::widgets::combo_box(format!("{salt}-unit")).width(70.0).selected_text(crate::i18n::tr(&unit)).show_ui(ui, |ui| {for u in ["hours", "days", "weeks", "months", "years"] {if ui.selectable_label(unit.trim_end_matches('s') == u.trim_end_matches('s'), crate::i18n::tr(u)).clicked() {unit = u.to_string();@@ -157,6 +158,7 @@ fn value_editor(ui: &mut egui::Ui, field: &str, op: &str, v: &mut Value, salt: &}}});+ crate::widgets::name_combo(&combo.response, crate::i18n::tr("Unit"));if changed {*v = json!({"n": n.round(), "unit": unit});}@@ -198,26 +200,31 @@ fn value_editor(ui: &mut egui::Ui, field: &str, op: &str, v: &mut Value, salt: &(Some(Kind::Number), _) => number_value(ui, v, field),(Some(Kind::Choice(c)), _) => {let cur = v.as_str().unwrap_or("").to_string();- crate::widgets::combo_box(format!("{salt}-choice")).width(120.0).selected_text(crate::i18n::choice_text(field, &cur)).show_ui(ui, |ui| {- for (id, _) in c.iter() {- if ui.selectable_label(cur == *id, crate::i18n::choice_text(field, id)).clicked() {- *v = json!(id);+ let combo = crate::widgets::combo_box(format!("{salt}-choice"))+ .width(120.0)+ .selected_text(crate::i18n::choice_text(field, &cur))+ .show_ui(ui, |ui| {+ for (id, _) in c.iter() {+ if ui.selectable_label(cur == *id, crate::i18n::choice_text(field, id)).clicked() {+ *v = json!(id);+ }}- }- });+ });+ crate::widgets::name_combo(&combo.response, crate::i18n::tr(field_label(field).unwrap_or(field)));}(Some(Kind::Bool), _) => {// the catalog's reading of the value ("false" is no); one that is neither yes nor no is// shown as written and kept until a choice replaces it, so the dialog reports itlet cur = bool_value(v);let text = cur.map_or_else(|| v.to_string(), |b| crate::i18n::bool_text(b).to_string());- crate::widgets::combo_box(format!("{salt}-bool")).width(60.0).selected_text(text).show_ui(ui, |ui| {+ let combo = crate::widgets::combo_box(format!("{salt}-bool")).width(60.0).selected_text(text).show_ui(ui, |ui| {for b in [true, false] {if ui.selectable_label(cur == Some(b), crate::i18n::bool_text(b)).clicked() {*v = json!(b);}}});+ crate::widgets::name_combo(&combo.response, crate::i18n::tr(field_label(field).unwrap_or(field)));}(Some(Kind::Date), _) => {text_value(ui, v, 120.0, "2026-04 or 2026-04-12", salt);@@ -262,6 +269,7 @@ fn field_menu(ui: &mut egui::Ui, salt: &str, field: &mut String, op: &mut String}pick});+ crate::widgets::name_combo(&r.response, crate::i18n::tr("Field"));register(ui.ctx(), format!("ruleField:{salt}"), r.response.rect);let Some(Some(id)) = r.inner else { return };if field == id {@@ -322,17 +330,19 @@ pub fn edit(ui: &mut egui::Ui, rs: &mut RuleSet, salt: &str, depth: usize, path:field_menu(ui, &rsalt, field, op, value);let kind = field_kind(field).unwrap_or(Kind::Text);let op_label = ops_for(kind).iter().find(|o| o.0 == op.as_str()).map_or(op.as_str(), |o| o.1).to_string();- crate::widgets::combo_box(format!("{rsalt}-op")).width(110.0).selected_text(crate::i18n::tr(&op_label)).show_ui(ui, |ui| {- for (id, l) in ops_for(kind) {- if ui.selectable_label(op == id, crate::i18n::tr(l)).clicked() && op != id {- let was_special = matches!(op.as_str(), "between" | "inLast" | "notInLast" | "isEmpty" | "isNotEmpty");- *op = id.to_string();- if was_special || matches!(*id, "between" | "inLast" | "notInLast" | "isEmpty" | "isNotEmpty") {- *value = default_value(field, op);+ let combo =+ crate::widgets::combo_box(format!("{rsalt}-op")).width(110.0).selected_text(crate::i18n::tr(&op_label)).show_ui(ui, |ui| {+ for (id, l) in ops_for(kind) {+ if ui.selectable_label(op == id, crate::i18n::tr(l)).clicked() && op != id {+ let was_special = matches!(op.as_str(), "between" | "inLast" | "notInLast" | "isEmpty" | "isNotEmpty");+ *op = id.to_string();+ if was_special || matches!(*id, "between" | "inLast" | "notInLast" | "isEmpty" | "isNotEmpty") {+ *value = default_value(field, op);+ }}}- }- });+ });+ crate::widgets::name_combo(&combo.response, crate::i18n::tr("Operator"));value_editor(ui, field, op, value, &rsalt, env);// − and + at the end of the row, after the value however long it is: a// right-to-left layout put them over the value when the row had no room leftdiff --git a/crates/ui-egui/src/panels/second.rs b/crates/ui-egui/src/panels/second.rsindex 79aa31d1d..9772c43c5 100644--- a/crates/ui-egui/src/panels/second.rs+++ b/crates/ui-egui/src/panels/second.rs@@ -12,10 +12,11 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {}let vid = egui::ViewportId::from_hash_of("lightcraft-second-window");let builder = egui::ViewportBuilder::default().with_title("LightCraft — Second Window").with_inner_size([960.0, 640.0]);- ctx.show_viewport_immediate(vid, builder, |ctx, class| {+ ctx.show_viewport_immediate(vid, builder, |ui, class| {+ // 0.37 passes the viewport's root `Ui` (not a `Context`). Do not enter `root_ui` from it.// (without native windows — web, headless — egui wraps this in a floating window)- egui::CentralPanel::default().frame(egui::Frame::NONE.fill(Color32::BLACK)).show(ctx, |ui| body(app, ui));- if class != egui::ViewportClass::EmbeddedWindow && ctx.input(|i| i.viewport().close_requested()) {+ egui::CentralPanel::default().frame(egui::Frame::NONE.fill(Color32::BLACK)).show(ui, |ui| body(app, ui));+ if class != egui::ViewportClass::EmbeddedWindow && ui.ctx().input(|i| i.viewport().close_requested()) {app.ui.second_window = false;}});diff --git a/crates/ui-egui/src/panels/settings.rs b/crates/ui-egui/src/panels/settings.rsindex 2f844f4ae..51f5e778a 100644--- a/crates/ui-egui/src/panels/settings.rs+++ b/crates/ui-egui/src/panels/settings.rs@@ -203,7 +203,7 @@ fn edit_file_rows(ui: &mut egui::Ui, t: &Tokens, id: &str, file: &mut crate::sta// -------------------------------------------------------------------------------------- Import/// A preset picker: `None` = `none_label`. Returns the new choice when it changed.-fn preset_combo(app: &LightcraftApp, ui: &mut egui::Ui, id: &str, current: Option<&str>, none_label: &str) -> Option<Option<String>> {+fn preset_combo(app: &LightcraftApp, ui: &mut egui::Ui, id: &str, label: &str, current: Option<&str>, none_label: &str) -> Option<Option<String>> {let name = |pid: &str| {app.session.presets@@ -222,6 +222,7 @@ fn preset_combo(app: &LightcraftApp, ui: &mut egui::Ui, id: &str, current: Optioout = Some(Some(pid));}});+ crate::widgets::name_combo(&r.response, label);register(ui.ctx(), format!("combo:{id}"), r.response.rect);out.filter(|v| v.as_deref() != current)}@@ -246,7 +247,7 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {heading(ui, t, crate::i18n::tr("Raw defaults"));hint(ui, t, crate::i18n::tr("Settings new raw photos start from. Changing them doesn't touch photos already in the library."));row(ui, t, crate::i18n::tr("Raw photos"), |ui| {- if let Some(v) = preset_combo(app, ui, "settingsRawPreset", d.raw_preset.as_deref(), "LightCraft Default") {+ if let Some(v) = preset_combo(app, ui, "settingsRawPreset", crate::i18n::tr("Raw default"), d.raw_preset.as_deref(), "LightCraft Default") {let _ = app.run("library.preferences", json!({"import": {"rawPreset": v}}));}});@@ -295,6 +296,7 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {pick = Some(json!({"camera": cam, "preset": pid}));}});+ crate::widgets::name_combo(&r.response, crate::i18n::tr("Camera"));register(ui.ctx(), format!("combo:{id}"), r.response.rect);if let Some(c) = pick {let _ = app.run("library.preferences", json!({"camera": c}));@@ -305,7 +307,7 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {}heading(ui, t, crate::i18n::tr("Other images (JPEG, PNG, TIFF, HEIC…)"));row(ui, t, crate::i18n::tr("Non-raw photos"), |ui| {- if let Some(v) = preset_combo(app, ui, "settingsOtherPreset", d.other_preset.as_deref(), "None") {+ if let Some(v) = preset_combo(app, ui, "settingsOtherPreset", crate::i18n::tr("Other preset"), d.other_preset.as_deref(), "None") {let _ = app.run("library.preferences", json!({"import": {"otherPreset": v}}));}});@@ -315,7 +317,7 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {[("copyright", "Copyright", "© 2026 Your Name", d.copyright.clone()), ("creator", "Creator", "Your Name", d.creator.clone())]{row(ui, t, label, |ui| {- let id = egui::Id::new(("settingsMeta", key));+ let id = egui::Id::unique(("settingsMeta", key));let mut text: String = ui.data(|m| m.get_temp(id)).unwrap_or(value.clone());let r = ui.add(egui::TextEdit::singleline(&mut text).hint_text(hint_text).desired_width(240.0));register(ui.ctx(), format!("field:settings.{key}"), r.rect);@@ -346,6 +348,7 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {}}});+ crate::widgets::name_combo(&r.response, crate::i18n::tr("Metadata preset"));register(ui.ctx(), "combo:settingsMetaPreset", r.response.rect);if let Some(n) = pick {let _ = app.run("library.preferences", json!({"import": {"metadataPreset": n}}));@@ -396,7 +399,7 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {}});row(ui, t, crate::i18n::tr("Album"), |ui| {- let id = egui::Id::new("auto-album");+ let id = egui::Id::unique("auto-album");let mut name = ui.data(|m| m.get_temp::<String>(id)).unwrap_or_else(|| d.auto_album.clone().unwrap_or_default());let r = ui.add(egui::TextEdit::singleline(&mut name).hint_text(crate::i18n::tr("None")).desired_width(180.0));if r.lost_focus() {@@ -492,7 +495,7 @@ fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {#[cfg(not(target_arch = "wasm32"))]fn smart_previews(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {// listing a big folder every frame would be slow: refresh every 2 s and after a change- let cache = egui::Id::new("smart-location");+ let cache = egui::Id::unique("smart-location");let now = ui.input(|i| i.time);let loc: Value = match ui.data(|d| d.get_temp::<(f64, Value)>(cache)) {Some((at, v)) if now - at < 2.0 => v,@@ -535,7 +538,7 @@ fn smart_previews(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {);}// what happens to the previews already built when the folder changes- let mode_id = egui::Id::new("smart-existing");+ let mode_id = egui::Id::unique("smart-existing");let mut mode: u8 = ui.data(|d| d.get_temp(mode_id)).unwrap_or(0);if count > 0 {row(ui, t, crate::i18n::tr("Existing previews"), |ui| {@@ -720,6 +723,10 @@ pub(super) fn view_options(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Token}}});+ crate::widgets::name_combo(+ &r.response,+ &crate::i18n::tr_format!("{title}: {line}", title = crate::i18n::tr(title), line = crate::i18n::tr(line.label())),+ );register(ui.ctx(), format!("combo:{id}"), r.response.rect);}let r = ui.add_enabled(*lines != defaults, egui::Button::new(crate::i18n::tr("Use Defaults")));@@ -942,7 +949,7 @@ fn theme_card<V: PartialEq + Copy>(.on_hover_text(crate::i18n::tr(if favorite { "Remove from favorites" } else { "Add to favorites" }));r.widget_info(|| {egui::WidgetInfo::labeled(- egui::WidgetType::Button,+ egui::Role::Button,true,format!("{}: {}",diff --git a/crates/ui-egui/src/panels/slide_layout.rs b/crates/ui-egui/src/panels/slide_layout.rsindex 62f7626c3..5a9ddb243 100644--- a/crates/ui-egui/src/panels/slide_layout.rs+++ b/crates/ui-egui/src/panels/slide_layout.rs@@ -206,7 +206,7 @@ pub fn preview(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {let overlay_key = if overlays.any() { overlays.pixel_key() ^ shown.rotate_left(5) } else { 0 };let key = s.pixel_key() ^ id.0.rotate_left(17) ^ ((pw as u64) << 32 | ph as u64) ^ overlay_key.rotate_left(29);let now = ui.input(|i| i.time);- let mem = egui::Id::new("settingsSlideshowPreviewKey");+ let mem = egui::Id::unique("settingsSlideshowPreviewKey");let (last, since) = ui.ctx().data(|d| d.get_temp::<(u64, f64)>(mem)).unwrap_or((0, f64::NEG_INFINITY));let current = app.renderer.textures.get(&Slot::SlidePreview).filter(|tex| tex.photo == id);if last != key {@@ -256,7 +256,7 @@ fn title_preview(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, rect: Rlet compose = std::sync::Arc::new(lightcraft_engine::slide_title::TitleCompose::new(&look.titles, &look.overlays, title, pw, ph));let key = compose.key();let now = ui.input(|i| i.time);- let mem = egui::Id::new("settingsSlideshowTitlePreviewKey");+ let mem = egui::Id::unique("settingsSlideshowTitlePreviewKey");let (last, since) = ui.ctx().data(|d| d.get_temp::<(u64, f64)>(mem)).unwrap_or((0, f64::NEG_INFINITY));if last != key {ui.ctx().data_mut(|d| d.insert_temp(mem, (key, now)));diff --git a/crates/ui-egui/src/panels/slide_overlays.rs b/crates/ui-egui/src/panels/slide_overlays.rsindex 3824eeb0d..6a3976b19 100644--- a/crates/ui-egui/src/panels/slide_overlays.rs+++ b/crates/ui-egui/src/panels/slide_overlays.rs@@ -71,7 +71,7 @@ fn toggle(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, value: bool, lab/// A one-line text field (`field:{id}`), saved when the edit ends.fn text(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, value: &str, hint: &str, wrap: &dyn Fn(&str) -> Value) {- let mem = egui::Id::new(("slideshow-overlay-field", id));+ let mem = egui::Id::unique(("slideshow-overlay-field", id));let mut s: String = ui.data(|d| d.get_temp(mem)).unwrap_or_else(|| value.to_string());let widget = format!("field:{id}");let r = TextField::singleline(&widget, &mut s).hint(crate::i18n::tr(hint)).width(ui.available_width().clamp(80.0, 260.0)).show(ui);@@ -147,7 +147,7 @@ pub fn sections(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {let p = s.identity_plate.clone();let plate = |v: Value| json!({ "identityPlate": v });if toggle(app, ui, "slideshowPlate", p.enabled, "Identity plate", &|v| plate(json!({"enabled": v}))) {- let mem = egui::Id::new("slideshow-plate-graphic");+ let mem = egui::Id::unique("slideshow-plate-graphic");let mut graphic = !p.image.is_empty() || ui.data(|d| d.get_temp::<bool>(mem)).unwrap_or(false);let before = graphic;row(ui, t, "Style", |ui| choices(ui, "slideshowPlateStyle", &[(false, "Text"), (true, "Image")], &mut graphic));diff --git a/crates/ui-egui/src/panels/slide_templates.rs b/crates/ui-egui/src/panels/slide_templates.rsindex 51c27d224..51b510906 100644--- a/crates/ui-egui/src/panels/slide_templates.rs+++ b/crates/ui-egui/src/panels/slide_templates.rs@@ -23,7 +23,7 @@ use crate::widgets::register;const USER_LIST_H: f32 = 180.0;fn hovered_key() -> egui::Id {- egui::Id::new("settingsSlideshowTemplateHovered")+ egui::Id::unique("settingsSlideshowTemplateHovered")}/// The template the pointer is over in the browser (its id), which the preview shows.@@ -43,7 +43,7 @@ enum Pending {}fn pending_key() -> egui::Id {- egui::Id::new("settingsSlideshowTemplatePending")+ egui::Id::unique("settingsSlideshowTemplatePending")}fn pending(ctx: &egui::Context) -> Option<Pending> {@@ -228,7 +228,7 @@ pub fn section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {// save the current settings as a new templateui.add_space(4.0);ui.horizontal(|ui| {- let mem = egui::Id::new("settingsSlideshowTemplateNewName");+ let mem = egui::Id::unique("settingsSlideshowTemplateNewName");let mut name: String = ui.data(|d| d.get_temp(mem)).unwrap_or_default();let r = TextField::singleline("field:slideshowTemplateName", &mut name).hint(crate::i18n::tr("New template name")).width(180.0).show(ui);let save = crate::widgets::text_button(ui, "slideshowTemplateSave", "Save as Template", false).clicked()diff --git a/crates/ui-egui/src/panels/slide_titles.rs b/crates/ui-egui/src/panels/slide_titles.rsindex 257790995..4c2503569 100644--- a/crates/ui-egui/src/panels/slide_titles.rs+++ b/crates/ui-egui/src/panels/slide_titles.rs@@ -20,7 +20,7 @@ use crate::widgets::register;/// Where the preview's choice lives (egui memory): `None` = the photo's slide.fn preview_key() -> egui::Id {- egui::Id::new("settingsSlideshowPreviewShows")+ egui::Id::unique("settingsSlideshowPreviewShows")}/// What the Settings preview shows: a title screen, or (`None`) the active photo's slide.@@ -89,7 +89,7 @@ fn colour(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, t: Title, key: &/// The screen's text field (`field:{id}`), saved when the edit ends.fn text(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, t: Title, value: &str) {- let mem = egui::Id::new(("slideshow-title-field", id));+ let mem = egui::Id::unique(("slideshow-title-field", id));let mut s: String = ui.data(|d| d.get_temp(mem)).unwrap_or_else(|| value.to_string());let widget = format!("field:{id}");let r = TextField::singleline(&widget, &mut s).hint(crate::i18n::tr("Title text")).width(ui.available_width().clamp(80.0, 260.0)).show(ui);diff --git a/crates/ui-egui/src/panels/slideshow.rs b/crates/ui-egui/src/panels/slideshow.rsindex a0f7ba09f..d05d63def 100644--- a/crates/ui-egui/src/panels/slideshow.rs+++ b/crates/ui-egui/src/panels/slideshow.rs@@ -154,7 +154,7 @@ pub fn ready(app: &LightcraftApp, item: Item) -> bool {}/// Advance a running slideshow (every frame, before drawing).-pub fn tick(app: &mut LightcraftApp, ctx: &egui::Context) {+pub fn tick(app: &mut LightcraftApp, ctx: &egui::Context, now: f64) {let Some(run) = app.ui.slideshow.as_ref() else {app.renderer.release_slides(&[]);return;@@ -163,7 +163,6 @@ pub fn tick(app: &mut LightcraftApp, ctx: &egui::Context) {end(app);return;}- let now = ctx.input(|i| i.time);let mut play = run.play.clone();let t = play.tick(now, |id| ready(app, id));if let Some(run) = app.ui.slideshow.as_mut() {@@ -293,7 +292,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {// (`ui.pointer` positions are relative to it)app.image_rect = Some(canvas);let Some(run) = app.ui.slideshow.as_ref() else { return };- let now = ui.input(|i| i.time);+ let now = app.tick_now();let ppp = ui.ctx().pixels_per_point();let side = super::detail::texture_side(ui.ctx());let want = wanted(&run.play, now);diff --git a/crates/ui-egui/src/panels/topbar.rs b/crates/ui-egui/src/panels/topbar.rsindex e26d1088f..8605eb000 100644--- a/crates/ui-egui/src/panels/topbar.rs+++ b/crates/ui-egui/src/panels/topbar.rs@@ -13,13 +13,13 @@ use crate::widgets::{icon_button, register};fn window_handle(app: &LightcraftApp, ui: &mut egui::Ui, bar: Rect, search_rect: Rect) {use crate::titlebar::{Gesture, WindowState, command_for};register(ui.ctx(), "region:titlebar", bar);- let handle = egui::Id::new("titlebar-handle");+ let handle = egui::Id::unique("titlebar-handle");let resp = ui.interact(bar, handle, Sense::click_and_drag());crate::widgets::announce(&resp, crate::i18n::tr("Title bar"));// a press that began on a button or the search field is theirs: dragging off it must not move the window// (while pressing, egui hovers every widget under the pointer; once the drag starts, only the dragged one)let ctx = ui.ctx().clone();- let memo = egui::Id::new("titlebar-press-on-widget");+ let memo = egui::Id::unique("titlebar-press-on-widget");if resp.is_pointer_button_down_on() && ctx.input(|i| i.pointer.primary_pressed()) {let hovered = ctx.interaction_snapshot(|s| s.hovered.clone());let on_widget =@@ -133,7 +133,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {}// filter icon right of the search fieldlet fr = Rect::from_center_size(pos2(sr.right() + 22.0, sr.center().y), vec2(28.0, 28.0));- let fresp = ui.interact(fr, egui::Id::new("filter-btn"), Sense::click());+ let fresp = ui.interact(fr, egui::Id::unique("filter-btn"), Sense::click());crate::widgets::announce(&fresp, crate::i18n::tr("Filters"));register(ui.ctx(), "icon:filter", fr);let filtering = app.session.filter != Default::default() || app.ui.filter_bar;@@ -192,7 +192,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {("bell", Icon::Bell, "Activity", "panel.activity"),] {let r = Rect::from_center_size(pos2(x, full.center().y), vec2(28.0, 28.0));- let resp = ui.interact(r, egui::Id::new(("top", id)), Sense::click()).on_hover_text(crate::i18n::tr(tip));+ let resp = ui.interact(r, egui::Id::unique(("top", id)), Sense::click()).on_hover_text(crate::i18n::tr(tip));crate::widgets::announce(&resp, crate::i18n::tr(tip));register(ui.ctx(), format!("icon:{id}"), r);let warn = id == "cloud" && unsaved.is_some();@@ -223,7 +223,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {let (icon, mode) = appearance_icon(app.ui.settings.appearance_mode);let r = Rect::from_center_size(pos2(x, full.center().y), vec2(28.0, 28.0));let tip = format!("{}: {}", crate::i18n::tr("Appearance Mode"), crate::i18n::tr(mode));- let resp = ui.interact(r, egui::Id::new(("top", "appearance")), Sense::click()).on_hover_text(tip.clone());+ let resp = ui.interact(r, egui::Id::unique(("top", "appearance")), Sense::click()).on_hover_text(tip.clone());crate::widgets::announce(&resp, tip.clone());register(ui.ctx(), "icon:appearance", r);paint(ui.painter(), r.shrink(5.0), icon, if resp.hovered() { t.text } else { t.icon });diff --git a/crates/ui-egui/src/panels/unnamed.rs b/crates/ui-egui/src/panels/unnamed.rsindex e1ef879e2..4636ce8c1 100644--- a/crates/ui-egui/src/panels/unnamed.rs+++ b/crates/ui-egui/src/panels/unnamed.rs@@ -228,12 +228,12 @@ pub fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, list: &Unnamed, i: usizelet t = Tokens::get(ui.ctx());let key = (f.photo, f.index);let selected = app.ui.unnamed_selected.contains(&key);- let resp = ui.interact(r, egui::Id::new(("unnamed-face", f.photo, f.index)), Sense::click());+ let resp = ui.interact(r, egui::Id::unique(("unnamed-face", f.photo, f.index)), Sense::click());crate::widgets::announce_selected(&resp, crate::i18n::tr("Unnamed face"), selected);register(ui.ctx(), format!("unnamed-face:{}:{}", f.photo, f.index), r);// a suggested name along the bottom: a click accepts it for this face (added after the tile, so it wins there)let strip = Rect::from_min_max(pos2(r.left(), r.bottom() - 20.0), r.right_bottom());- let accept = f.suggestion.as_ref().map(|_| ui.interact(strip, egui::Id::new(("unnamed-accept", f.photo, f.index)), Sense::click()));+ let accept = f.suggestion.as_ref().map(|_| ui.interact(strip, egui::Id::unique(("unnamed-accept", f.photo, f.index)), Sense::click()));if let Some(a) = &accept {register(ui.ctx(), format!("unnamed-accept:{}:{}", f.photo, f.index), a.rect);}diff --git a/crates/ui-egui/src/print_view.rs b/crates/ui-egui/src/print_view.rsindex a18e1f691..46ffbcb36 100644--- a/crates/ui-egui/src/print_view.rs+++ b/crates/ui-egui/src/print_view.rs@@ -382,6 +382,7 @@ fn settings(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi,}}});+ crate::widgets::name_combo(&c.response, crate::i18n::tr("Paper"));register(ui.ctx(), "combo:printPaper", c.response.rect);});if l.page.paper.eq_ignore_ascii_case("custom") {@@ -483,6 +484,7 @@ fn print_job_color(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, color: &Pripick |= r.clicked();}});+ crate::widgets::name_combo(&c.response, crate::i18n::tr("Profile"));register(ui.ctx(), "combo:printProfile", c.response.rect);});if pick && let Some(path) = app.services.pick_display_profile.as_mut().and_then(|pick| pick().into_iter().next()) {@@ -677,7 +679,7 @@ fn package_cells(let photo = if st.layout.style == Style::CustomPackage { c.photo.map(PhotoId).or(first) } else { first };let rect = sheet.rect(&c.rect);paint_cell(app, painter, t, st, rect, photo, sheet, &c.rect);- let resp = ui.interact(rect, egui::Id::new(("print-cell", c.id)), Sense::click_and_drag());+ let resp = ui.interact(rect, egui::Id::unique(("print-cell", c.id)), Sense::click_and_drag());register(&ctx, format!("print:cell:{}", c.id), rect);if resp.clicked() || resp.drag_started() {pu.selected = Some(c.id);@@ -719,7 +721,7 @@ fn package_cells(painter.rect_stroke(rect, 0.0, Stroke::new(2.0, t.accent), StrokeKind::Outside);let handle = Rect::from_center_size(rect.right_bottom(), Vec2::splat(HANDLE));painter.rect_filled(handle, 2.0, t.accent);- let resp = ui.interact(handle, egui::Id::new(("print-resize", sel.id)), Sense::drag());+ let resp = ui.interact(handle, egui::Id::unique(("print-resize", sel.id)), Sense::drag());register(&ctx, format!("print:resize:{}", sel.id), handle);if resp.drag_started() {pu.drag = Some(Drag { cell: sel.id, origin: sel.rect, resize: true, press: press_origin(ui, &resp), total: Vec2::ZERO });diff --git a/crates/ui-egui/src/render.rs b/crates/ui-egui/src/render.rsindex 1ed1071c2..7759884b5 100644--- a/crates/ui-egui/src/render.rs+++ b/crates/ui-egui/src/render.rs@@ -662,6 +662,15 @@ impl Renderer {self.pending.len()}+ /// Test seam: make the renderer look busy without starting a job (capture deadlines).+ #[cfg(test)]+ pub(crate) fn force_in_flight_for_test(&mut self, count: usize) {+ self.pending.clear();+ for i in 0..count {+ self.pending.insert(Slot::Prefetch((i % 256) as u8), (0, 0));+ }+ }+/// Why the last render for `slot` failed (until a render with another key succeeds).pub fn failure(&self, slot: Slot) -> Option<&str> {self.failed.get(&slot).map(|f| f.1.as_str())@@ -781,9 +790,9 @@ impl Renderer {// wasm: run one job per frame on this thread, timed with the host clock#[cfg(target_arch = "wasm32")]let inline_ms = {- let t0 = crate::now_ms();+ let t0 = crate::monotonic_ms();self.pool.run_inline(1);- crate::now_ms() - t0+ crate::monotonic_ms() - t0};#[cfg(not(target_arch = "wasm32"))]let inline_ms = 0.0;diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rsindex 91e6555b9..378f65e66 100644--- a/crates/ui-egui/src/shortcuts.rs+++ b/crates/ui-egui/src/shortcuts.rs@@ -332,11 +332,10 @@ fn keyboard_owned(app: &LightcraftApp, ctx: &egui::Context) -> bool {[Key::ArrowLeft, Key::ArrowRight, Key::ArrowUp, Key::ArrowDown, Key::Enter, Key::Space].iter().any(|key| input.key_pressed(*key))});}- let chrome = app- .ui- .docking- .as_ref()- .is_some_and(|workspace| craft_ui::docking::DockArea::new(egui::Id::new("lightcraft-docking")).chrome_has_focus(ctx, &workspace.layout));+ let chrome =+ app.ui.docking.as_ref().is_some_and(|workspace| {+ craft_ui::docking::DockArea::new(egui::Id::unique("lightcraft-docking")).chrome_has_focus(ctx, &workspace.layout)+ });if !chrome {return true;}@@ -1246,7 +1245,7 @@ mod tests {},|ui| {let ctx = ui.ctx();- egui::Popup::open_id(ctx, egui::Id::new("issue1771-menu"));+ egui::Popup::open_id(ctx, egui::Id::unique("issue1771-menu"));assert!(egui::Popup::is_any_open(ctx));super::super::handle(&mut h.app, ctx);},diff --git a/crates/ui-egui/src/shortcuts/tests_filter_bar_key.rs b/crates/ui-egui/src/shortcuts/tests_filter_bar_key.rsindex 41d0b1c2d..80a904c0e 100644--- a/crates/ui-egui/src/shortcuts/tests_filter_bar_key.rs+++ b/crates/ui-egui/src/shortcuts/tests_filter_bar_key.rs@@ -36,7 +36,7 @@ fn frame(app: &mut LightcraftApp, ctx: &egui::Context, key: Option<Key>, text: Oegui::RawInput { events, screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), ..Default::default() },|ui| {if let Some(text) = text.as_deref_mut() {- ui.add(egui::TextEdit::singleline(text).id(egui::Id::new("filter-bar-key-search"))).request_focus();+ ui.add(egui::TextEdit::singleline(text).id(egui::Id::unique("filter-bar-key-search"))).request_focus();}super::handle(app, ui.ctx());},diff --git a/crates/ui-egui/src/shortcuts/tests_flag_cycle.rs b/crates/ui-egui/src/shortcuts/tests_flag_cycle.rsindex d4e6deec5..109dca607 100644--- a/crates/ui-egui/src/shortcuts/tests_flag_cycle.rs+++ b/crates/ui-egui/src/shortcuts/tests_flag_cycle.rs@@ -37,7 +37,7 @@ fn frame(app: &mut LightcraftApp, ctx: &egui::Context, key: Option<(Key, Modifieegui::RawInput { events, screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), ..Default::default() },|ui| {if let Some(text) = text.as_deref_mut() {- ui.add(egui::TextEdit::singleline(text).id(egui::Id::new("flag-cycle-search"))).request_focus();+ ui.add(egui::TextEdit::singleline(text).id(egui::Id::unique("flag-cycle-search"))).request_focus();}super::handle(app, ui.ctx());},diff --git a/crates/ui-egui/src/shortcuts/tests_relative_ratings.rs b/crates/ui-egui/src/shortcuts/tests_relative_ratings.rsindex 8ca2adc1a..94ec5098b 100644--- a/crates/ui-egui/src/shortcuts/tests_relative_ratings.rs+++ b/crates/ui-egui/src/shortcuts/tests_relative_ratings.rs@@ -44,7 +44,7 @@ fn frame(app: &mut LightcraftApp, ctx: &egui::Context, key: Option<Key>, text: Oegui::RawInput { events, screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), ..Default::default() },|ui| {if let Some(text) = text.as_deref_mut() {- ui.add(egui::TextEdit::singleline(text).id(egui::Id::new("relative-rating-search"))).request_focus();+ ui.add(egui::TextEdit::singleline(text).id(egui::Id::unique("relative-rating-search"))).request_focus();}super::handle(app, ui.ctx());},diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rsindex 8cb37d3ef..fd1e2f426 100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@ -826,10 +826,12 @@ pub struct UiState {pub external_edits: Vec<u64>,#[serde(skip)]pub was_focused: bool,- /// When the watched folder was last scanned (egui time).+ /// When the watched folder was last scanned (monotonic app time, so a hidden window keeps+ /// scanning).#[serde(skip)]pub auto_import_at: f64,- /// When the automatic XMP writes that failed were last tried again (egui time), and how many were waiting then.+ /// When the automatic XMP writes that failed were last tried again (monotonic app time), and how+ /// many were waiting then.#[serde(skip)]pub sidecar_retry_at: f64,#[serde(skip)]@@ -856,7 +858,7 @@ pub struct UiState {#[serde(skip)]pub sam_downloading: bool,/// When to start the zoomed-in detail pass of an AI mask (app time) and which mask: set by- /// each click or description, so the pass runs once the clicking stops.+ /// each click or description, so the pass runs once the clicking stops (monotonic app time).#[serde(skip)]pub detail_due: Option<(f64, u32)>,/// A mask component being renamed inline: (mask id, component index, name).diff --git a/crates/ui-egui/src/tests_activity.rs b/crates/ui-egui/src/tests_activity.rsindex e66c2b7ef..505ca4dfd 100644--- a/crates/ui-egui/src/tests_activity.rs+++ b/crates/ui-egui/src/tests_activity.rs@@ -78,7 +78,7 @@ fn more_than_three_rows_overflow_and_expand() {click(&mut h, "activity:more");assert_eq!(rows(&h), 5);// expanded, the stack grows to show them all- let stack = h.view.ctx.memory(|m| m.area_rect(egui::Id::new("activity-stack"))).expect("the stack is drawn");+ let stack = h.view.ctx.memory(|m| m.area_rect(egui::Id::unique("activity-stack"))).expect("the stack is drawn");for g in &guards {let r = rect(&h, &format!("activity:row:{}", g.id()));assert!(stack.contains_rect(r), "row {} at {r:?} is cut off by the stack at {stack:?}", g.id());@@ -504,7 +504,7 @@ fn rows_added_later_grow_the_stack() {for _ in 0..5 {h.step();}- let stack = h.view.ctx.memory(|m| m.area_rect(egui::Id::new("activity-stack"))).expect("the stack is drawn");+ let stack = h.view.ctx.memory(|m| m.area_rect(egui::Id::unique("activity-stack"))).expect("the stack is drawn");for g in [&a, &b, &c] {let r = rect(&h, &format!("activity:row:{}", g.id()));assert!(stack.contains_rect(r), "row {} at {r:?} is cut off by the stack at {stack:?}", g.id());diff --git a/crates/ui-egui/src/tests_dialog_fit.rs b/crates/ui-egui/src/tests_dialog_fit.rsindex 52d412829..e2e9dd4bf 100644--- a/crates/ui-egui/src/tests_dialog_fit.rs+++ b/crates/ui-egui/src/tests_dialog_fit.rs@@ -130,7 +130,7 @@ fn long_dialogs_fit_a_short_window() {fn a_dialog_list_shrinks_to_fit_a_short_window() {let mut h = demo([1000.0, 320.0]);open(&mut h, "app.shortcuts");- let shrink = h.view.ctx.data(|d| d.get_temp::<f32>(egui::Id::new("dialog-list-shrink"))).unwrap_or(0.0);+ let shrink = h.view.ctx.data(|d| d.get_temp::<f32>(egui::Id::unique("dialog-list-shrink"))).unwrap_or(0.0);assert!(shrink > 0.0, "the list gave up room");let dialog = rect(&h, "dialog:window");assert!(dialog.height() <= 320.0, "{dialog:?}");diff --git a/crates/ui-egui/src/tests_docking_acceptance.rs b/crates/ui-egui/src/tests_docking_acceptance.rsindex 1dc97892e..75397d1cc 100644--- a/crates/ui-egui/src/tests_docking_acceptance.rs+++ b/crates/ui-egui/src/tests_docking_acceptance.rs@@ -164,7 +164,7 @@ fn dock_tab_keeps_activation_keys_and_global_command_remains_reachable() {h.app.run("panel.crop", json!({})).unwrap();h.step();// The test chooses the renderer's actual registered tab, rather than an arbitrary focus owner.- let id = egui::Id::new("lightcraft-docking").with(("tab", Panel::Tools));+ let id = egui::Id::unique("lightcraft-docking").with(("tab", Panel::Tools));h.view.ctx.memory_mut(|memory| memory.request_focus(id));h.step();key(&mut h, egui::Key::Enter);@@ -186,7 +186,7 @@ fn content_text_edit_retains_command_keys_and_typed_text() {h.app.synthetic.push(Event::Text("dock search".into()));h.step();assert_eq!(h.app.ui.right, RightPanel::Keywords);- assert_eq!(h.view.ctx.data(|data| data.get_temp::<String>(egui::Id::new("keyword-list-filter"))).as_deref(), Some("dock search"));+ assert_eq!(h.view.ctx.data(|data| data.get_temp::<String>(egui::Id::unique("keyword-list-filter"))).as_deref(), Some("dock search"));}#[test]@@ -271,7 +271,7 @@ fn covered_keyword_rejects_hierarchy_move_and_uncovered_target_moves_exact_keywo#[test]fn reset_during_held_divider_drag_keeps_replacement_layout_on_later_movement() {let mut h = app();- let divider = egui::Id::new("lightcraft-docking").with(("split", Vec::<bool>::new()));+ let divider = egui::Id::unique("lightcraft-docking").with(("split", Vec::<bool>::new()));let from = h.view.ctx.read_response(divider).expect("the custom workspace root divider is rendered").rect.center();let before = h.app.ui.docking.as_ref().unwrap().layout.clone();h.app.synthetic.push(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });@@ -303,7 +303,7 @@ fn reset_during_held_divider_drag_keeps_replacement_layout_on_later_movement() {fn held_divider_replacement_route(route: &str) {let mut h = app();- let divider = egui::Id::new("lightcraft-docking").with(("split", Vec::<bool>::new()));+ let divider = egui::Id::unique("lightcraft-docking").with(("split", Vec::<bool>::new()));let from = h.view.ctx.read_response(divider).unwrap().rect.center();let photos = serde_json::to_value(h.app.session.catalog.photos().map(|photo| photo.as_ref()).collect::<Vec<_>>()).unwrap();h.app.synthetic.push(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });diff --git a/crates/ui-egui/src/tests_folder_drop.rs b/crates/ui-egui/src/tests_folder_drop.rsindex 1b6536242..b7a515131 100644--- a/crates/ui-egui/src/tests_folder_drop.rs+++ b/crates/ui-egui/src/tests_folder_drop.rs@@ -95,7 +95,7 @@ fn release(h: &mut Headless, at: Pos2) {/// What the dragged label says this frame instead of the count, if a drop target set it.fn hint(h: &Headless) -> Option<String> {- h.view.ctx.data(|d| d.get_temp::<(u64, String)>(egui::Id::new("drag-photos-hint"))).map(|(_, text)| text)+ h.view.ctx.data(|d| d.get_temp::<(u64, String)>(egui::Id::unique("drag-photos-hint"))).map(|(_, text)| text)}/// Click a widget the way a person does (press and release on it).diff --git a/crates/ui-egui/src/tests_lifecycle_037.rs b/crates/ui-egui/src/tests_lifecycle_037.rsnew file mode 100644index 000000000..2da8b674e--- /dev/null+++ b/crates/ui-egui/src/tests_lifecycle_037.rs@@ -0,0 +1,1011 @@+//! 0.37 lifecycle regressions: the app clock, one-consumer queues, one pending synthetic batch,+//! parent-salted panel state, bundled monochrome emoji, and bounded/stale-safe screenshot capture.++use std::sync::mpsc::{Receiver, Sender, channel};+use std::sync::{Arc, Mutex};++use crate::headless::Headless;+use crate::render::{Slot, Tex};+use crate::{ControlResponse, LightcraftApp, MAX_PENDING_SHOTS, MAX_SHOT_BYTES, PendingShot, Services, ShotGeometry};+use lightcraft_engine::slideshow::Item;++fn app() -> LightcraftApp {+ LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() })+}++fn raw(size: egui::Vec2) -> egui::RawInput {+ egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), ..Default::default() }+}++fn viewport_raw(size: egui::Vec2, visible: bool) -> egui::RawInput {+ let mut raw = raw(size);+ raw.viewports.entry(egui::ViewportId::ROOT).or_default().minimized = Some(!visible);+ raw.viewports.entry(egui::ViewportId::ROOT).or_default().occluded = Some(false);+ raw+}++fn reply_channel() -> (Sender<ControlResponse>, Receiver<ControlResponse>) {+ channel()+}++fn geometry(width: f32, height: f32) -> ShotGeometry {+ ShotGeometry { viewport: egui::vec2(width, height), pixels_per_point: 1.0, zoom: 1.0, epoch: 0 }+}++fn shot_bytes_for(width: usize, height: usize) -> usize {+ width * height * std::mem::size_of::<egui::Color32>()+}++/// One layout pass whose texture delta is consumed. 0.37's `TexturesDelta` panics when a non-empty+/// delta is dropped, so a test that only inspects input/state must still acknowledge the font atlas+/// the pass produced. `HeadlessView::run` does this with `TexturesDelta::apply`; a bare+/// `Context::run_ui` has no renderer, so clearing the delta is the explicit handling.+fn frame(ctx: &egui::Context, raw: egui::RawInput, ui: impl FnMut(&mut egui::Ui)) {+ let mut output = ctx.run_ui(raw, ui);+ output.textures_delta.clear();+}++/// An app whose screenshot encoder writes through the real file path and records the pixels it saw.+fn app_with_screenshot_files() -> (LightcraftApp, Arc<Mutex<Option<(usize, usize, Vec<u8>)>>>) {+ let mut app = app();+ let seen = Arc::new(Mutex::new(None));+ let recorder = Arc::clone(&seen);+ app.services.png = Some(Box::new(move |img: &lightcraft_raster::Rgba8| {+ *recorder.lock().unwrap() = Some((img.width, img.height, img.as_bytes()));+ vec![0x89, b'P', b'N', b'G']+ }));+ app.services.write = Some(Box::new(|path: &str, bytes: &[u8]| std::fs::write(path, bytes).map_err(|e| e.to_string())));+ app.services.write_new = Some(Box::new(|path: &str, bytes: &[u8]| lightcraft_engine::export::write_file_new(path, bytes)));+ (app, seen)+}++fn temp_png(name: &str) -> std::path::PathBuf {+ let path = std::env::temp_dir().join(format!("lightcraft-{name}-{}.png", std::process::id()));+ let _ = std::fs::remove_file(&path);+ path+}++/// Bind a pending request to the geometry/library generation a real issue would have used.+fn issue_into_slot(ctx: &egui::Context, shot: &mut PendingShot, issued: ShotGeometry, library: u64) -> egui::ScreenshotCallback {+ let (slot, callback) = craft_ui::capture::CaptureSlot::new(ctx, egui::ViewportId::ROOT, MAX_SHOT_BYTES);+ shot.slot = Some(slot);+ shot.sent_at_ms = Some(0.0);+ shot.issued = Some(issued);+ shot.issued_library = library;+ callback+}++#[test]+fn bundled_faces_include_monochrome_emoji() {+ // 0.37 moved the monochrome emoji faces behind `monochrome_emoji_fonts`, and `default_fonts`+ // is no longer an egui default. Both come from the root `egui` features (kittest's own+ // dev-dependencies do not propagate), so this test fails if either is lost.+ let definitions = crate::theme::font_definitions(&[]);+ for name in ["Hack", "Ubuntu-Light", "egui-icons", "NotoEmoji-Regular", "emoji-icon-font"] {+ assert!(definitions.font_data.contains_key(name), "bundled face {name} is missing: {:?}", definitions.font_data.keys().collect::<Vec<_>>());+ }+ let ctx = egui::Context::default();+ ctx.set_fonts(definitions);+ // `Fonts` needs a first pass for its pixels-per-point before `fonts_mut` may inspect glyphs.+ frame(&ctx, raw(egui::vec2(240.0, 120.0)), |ui| {+ // U+1F600 and U+1F44D are in the bundled font cmaps. The older bundled subset+ // does not contain U+1F642, so it cannot serve as a feature-wiring oracle.+ ui.label("😀👍");+ });+ let font = egui::FontId::proportional(16.0);+ assert!(ctx.fonts_mut(|f| f.has_glyph(&font, '\u{1F600}')), "😀 must be paintable from the bundled faces");+ assert!(ctx.fonts_mut(|f| f.has_glyph(&font, '\u{1F44D}')), "👍 must be paintable from the bundled faces");+}++#[test]+fn resizable_side_stores_panel_state_under_the_parent_salted_key() {+ let ctx = egui::Context::default();+ let raw = raw(egui::vec2(1000.0, 700.0));+ frame(&ctx, raw, |ui| {+ crate::panels::resizable_side(ui, true, "side-test", egui::Frame::NONE, 260.0, crate::state::LEFT_WIDTH, 300.0, |ui| {+ ui.label("side");+ });+ });+ let modern = ctx.viewport_id().root_ui_id().with("side-test");+ assert!(+ egui::containers::panel::PanelState::load(&ctx, modern).is_some(),+ "0.37 stores panel state under parent_ui.scope_id().with_salt(id_salt)"+ );+ assert!(+ egui::containers::panel::PanelState::load(&ctx, egui::Id::unique("side-test")).is_none(),+ "an already-built Id must not be salted a second time (the 0.36 exact-Id key)"+ );+}++#[test]+fn legacy_panel_state_is_dropped_once_and_modern_keys_survive() {+ let (ctx, mut app) = (egui::Context::default(), app());+ let state = || egui::containers::panel::PanelState { outer_rect: egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(10.0, 10.0)) };+ let modern = ctx.viewport_id().root_ui_id();+ let salts = ["top_bar", "bottom_bar", "tool_strip", "library-problem-banner"];+ for salt in salts {+ let legacy = egui::Id::unique(salt);+ ctx.data_mut(|d| d.insert_persisted(legacy, state()));+ ctx.data_mut(|d| d.insert_persisted(modern.with(salt), state()));+ }+ frame(&ctx, raw(egui::vec2(800.0, 600.0)), |_| {});+ app.logic(&ctx);+ for salt in salts {+ let legacy = egui::Id::unique(salt);+ assert!(egui::containers::panel::PanelState::load(&ctx, legacy).is_none(), "the dead 0.36 key for {salt} is removed");+ assert!(egui::containers::panel::PanelState::load(&ctx, modern.with(salt)).is_some(), "the 0.37 parent-salted key for {salt} is not touched");+ }+}++#[test]+fn capture_admission_bounds_count_and_bytes_before_issue() {+ let (ctx, mut app) = (egui::Context::default(), app());+ app.last_shot_geometry = Some(geometry(100.0, 100.0));+ for _ in 0..MAX_PENDING_SHOTS {+ let (tx, _rx) = reply_channel();+ app.admit_shot(&ctx, None, false, tx).expect("admission within all limits");+ }+ let per_image = shot_bytes_for(100, 100);+ assert_eq!(app.shot_bytes, MAX_PENDING_SHOTS * per_image);+ let (tx, _rx) = reply_channel();+ assert!(app.admit_shot(&ctx, None, false, tx).is_err(), "a fifth request is refused before issue");+ // The count gate runs before geometry admission. Free the four slots so the next check reaches+ // the byte branch instead of answering the count error again.+ app.pending_screenshots.clear();+ app.shot_bytes = 0;++ // An image over the per-image cap is refused, and nothing is reserved for it. The geometry is+ // inside the texture limit (16 384 × 2 049), so this exercises the byte branch, not `pixels()`.+ let before = app.shot_bytes;+ app.last_shot_geometry = Some(geometry(16_384.0, 2_049.0));+ let (tx, _rx) = reply_channel();+ let error = app.admit_shot(&ctx, None, false, tx).expect_err("128 MiB + one row is over the per-image cap");+ assert!(error.contains("134283264"), "the error names the image size: {error}");+ assert!(error.contains("134217728"), "the error names the per-image cap: {error}");+ assert_eq!(app.shot_bytes, before, "a refused request reserves no bytes");++ // Two 100 MB surfaces fit the 128 MiB per-image cap, but a third would exceed the 256 MiB+ // aggregate budget (completed-but-undrained images stay counted).+ let (ctx, mut app) = (egui::Context::default(), self::app());+ app.last_shot_geometry = Some(geometry(5000.0, 5000.0));+ for _ in 0..2 {+ let (tx, _rx) = reply_channel();+ app.admit_shot(&ctx, None, false, tx).expect("100 MB is under the per-image cap");+ }+ let (tx, _rx) = reply_channel();+ assert!(app.admit_shot(&ctx, None, false, tx).is_err(), "the aggregate budget bounds a third image");+ assert_eq!(app.shot_bytes, 200_000_000);+}++#[test]+fn texture_limit_and_missing_surface_have_distinct_admission_errors() {+ let (ctx, mut app) = (egui::Context::default(), app());+ app.max_texture_side = 1024;+ app.last_shot_geometry = Some(geometry(1200.0, 100.0));+ let (tx, _rx) = reply_channel();+ let error = app.admit_shot(&ctx, None, false, tx).expect_err("wider than the host's texture limit");+ assert!(error.contains("1200×100") && error.contains("1024"), "the error names the surface and the host limit: {error}");+ assert_eq!(app.shot_bytes, 0);++ app.last_shot_geometry = Some(geometry(0.0, 0.0));+ let (tx, _rx) = reply_channel();+ let error = app.admit_shot(&ctx, None, false, tx).expect_err("no laid-out surface");+ assert!(error.contains("no usable surface size"), "the error names the missing layout, not the texture limit: {error}");+ assert_eq!(app.shot_bytes, 0);+}++#[test]+fn stale_geometry_completion_is_rejected_before_any_write() {+ let (ctx, mut app) = (egui::Context::default(), app());+ let path = temp_png("stale-shot");+ let (tx, rx) = reply_channel();+ let issued = ShotGeometry { epoch: 7, ..geometry(100.0, 100.0) };+ app.last_shot_geometry = Some(issued);+ let target = app.session.pin_write_target(&path.to_string_lossy()).expect("pin the path");+ app.admit_shot(&ctx, Some(target), false, tx).expect("admitted");+ let library = app.shot_document_generation();+ let callback = {+ let shot = app.pending_screenshots.last_mut().expect("pending");+ issue_into_slot(&ctx, shot, ShotGeometry { epoch: 7, ..geometry(100.0, 100.0) }, library)+ };+ callback.complete(Arc::new(egui::ColorImage::filled([2, 2], egui::Color32::WHITE)));+ // The window changed size while the callback was in flight: the image belongs to a stale+ // generation and must be retried, never written.+ app.last_shot_geometry = Some(ShotGeometry { epoch: 8, ..geometry(100.0, 100.0) });+ app.collect_screenshots(&ctx);+ assert_eq!(app.pending_screenshots.len(), 1, "the request is retried");+ assert!(app.pending_screenshots[0].slot.is_none(), "the stale slot is dropped");+ assert!(!path.exists(), "a stale image is never written");+ assert!(rx.try_recv().is_err(), "a retry replies only when it succeeds or times out");+ assert_eq!(app.shot_bytes, shot_bytes_for(100, 100), "the reservation is kept for the retry");+}++#[test]+fn a_completed_capture_writes_once_and_releases_its_reservation() {+ let (ctx, mut app, seen) = {+ let (app, seen) = app_with_screenshot_files();+ (egui::Context::default(), app, seen)+ };+ let path = temp_png("happy-shot");+ let (tx, rx) = reply_channel();+ app.last_shot_geometry = Some(geometry(100.0, 100.0));+ let target = app.session.pin_write_target(&path.to_string_lossy()).expect("pin the path");+ app.admit_shot(&ctx, Some(target), false, tx).expect("admitted");+ let issued = geometry(100.0, 100.0);+ let generation = app.shot_document_generation();+ let callback = {+ let shot = app.pending_screenshots.last_mut().expect("pending");+ issue_into_slot(&ctx, shot, issued, generation)+ };+ callback.complete(Arc::new(egui::ColorImage::filled([2, 2], egui::Color32::from_rgb(1, 2, 3))));+ app.collect_screenshots(&ctx);++ let reply = rx.try_recv().expect("exactly one reply");+ assert_eq!(reply["ok"], true, "{reply}");+ assert_eq!(reply["result"]["width"], 2);+ assert_eq!(reply["result"]["height"], 2);+ assert_eq!(std::fs::read(&path).expect("the file is written"), vec![0x89, b'P', b'N', b'G']);+ let seen = seen.lock().unwrap().clone().expect("the encoder ran");+ assert_eq!((seen.0, seen.1), (2, 2));+ assert_eq!(seen.2, vec![1, 2, 3, 255, 1, 2, 3, 255, 1, 2, 3, 255, 1, 2, 3, 255]);+ assert!(app.pending_screenshots.is_empty());+ assert_eq!(app.shot_bytes, 0, "success returns the reservation");+ assert!(rx.try_recv().is_err(), "one reply, not two");+ let _ = std::fs::remove_file(&path);+}++#[test]+fn a_capture_completed_after_a_catalog_edit_is_still_written() {+ // Catalog edits bump `catalog.revision` on every op; that is content, not document identity.+ // Binding the capture to it retried once per edit and could only end in a timeout.+ let (ctx, mut app, _seen) = {+ let (app, seen) = app_with_screenshot_files();+ (egui::Context::default(), app, seen)+ };+ let path = temp_png("edited-shot");+ let (tx, rx) = reply_channel();+ app.last_shot_geometry = Some(geometry(100.0, 100.0));+ let target = app.session.pin_write_target(&path.to_string_lossy()).expect("pin the path");+ app.admit_shot(&ctx, Some(target), false, tx).expect("admitted");+ let generation = app.shot_document_generation();+ let issued = geometry(100.0, 100.0);+ let callback = {+ let shot = app.pending_screenshots.last_mut().expect("pending");+ issue_into_slot(&ctx, shot, issued, generation)+ };+ app.session.catalog.revision = app.session.catalog.revision.wrapping_add(1);+ assert_eq!(app.shot_document_generation(), generation, "an edit is not a new library");+ callback.complete(Arc::new(egui::ColorImage::filled([2, 2], egui::Color32::WHITE)));+ app.collect_screenshots(&ctx);+ let reply = rx.try_recv().expect("one reply");+ assert_eq!(reply["ok"], true, "{reply}");+ assert!(path.exists());+ assert_eq!(app.shot_bytes, 0);+ let _ = std::fs::remove_file(&path);+}++#[test]+fn an_image_larger_than_its_reservation_is_grown_and_written() {+ // Wayland has no `inner_rect`, so on a hidden tick the reservation can be based on the old+ // content rect while the compositor returns the resized surface. A legal image is not an error.+ let (ctx, mut app, _seen) = {+ let (app, seen) = app_with_screenshot_files();+ (egui::Context::default(), app, seen)+ };+ let path = temp_png("grown-shot");+ let (tx, rx) = reply_channel();+ app.last_shot_geometry = Some(geometry(100.0, 100.0));+ let target = app.session.pin_write_target(&path.to_string_lossy()).expect("pin the path");+ app.admit_shot(&ctx, Some(target), false, tx).expect("admitted");+ let issued = geometry(100.0, 100.0);+ let generation = app.shot_document_generation();+ let callback = {+ let shot = app.pending_screenshots.last_mut().expect("pending");+ issue_into_slot(&ctx, shot, issued, generation)+ };+ callback.complete(Arc::new(egui::ColorImage::filled([200, 200], egui::Color32::WHITE)));+ app.collect_screenshots(&ctx);+ let reply = rx.try_recv().expect("one reply");+ assert_eq!(reply["ok"], true, "{reply}");+ assert_eq!(reply["result"]["width"], 200);+ assert_eq!(app.shot_bytes, 0, "the grown reservation is released too");+ assert!(path.exists());+ let _ = std::fs::remove_file(&path);+}++#[test]+fn a_surface_that_grew_past_the_per_image_cap_is_refused_by_issue() {+ let (ctx, mut app) = (egui::Context::default(), app());+ app.set_simulated_clock(Some(0.0));+ app.ui_passes = 3;+ app.fonts_ready = true;+ app.last_shot_geometry = Some(geometry(5000.0, 5000.0));+ let (tx, rx) = reply_channel();+ app.admit_shot(&ctx, None, false, tx).expect("100 MB is admitted");+ app.set_simulated_clock(Some(1.0));+ app.ui_passes = 6;+ // The window grew after admission: 7000² × 4 = 196 MB, over the 128 MiB per-image cap.+ app.last_shot_geometry = Some(geometry(7000.0, 7000.0));+ app.issue_screenshots(&ctx);+ let reply = rx.try_recv().expect("the refusal is a reply");+ assert_eq!(reply["ok"], false, "{reply}");+ let error = reply["error"].as_str().unwrap_or_default();+ assert!(error.contains("196000000"), "the error names the new image, not the delta: {error}");+ assert!(error.contains("134217728"), "{error}");+ assert!(app.pending_screenshots.is_empty());+ assert_eq!(app.shot_bytes, 0);+}++#[test]+fn timeout_replies_once_and_a_late_callback_is_inert() {+ let (ctx, mut app) = (egui::Context::default(), app());+ app.set_simulated_clock(Some(0.0));+ app.last_shot_geometry = Some(geometry(100.0, 100.0));+ let (tx, rx) = reply_channel();+ app.admit_shot(&ctx, None, false, tx).expect("admitted");+ let issued = geometry(100.0, 100.0);+ let generation = app.shot_document_generation();+ let callback = {+ let shot = app.pending_screenshots.last_mut().expect("pending");+ issue_into_slot(&ctx, shot, issued, generation)+ };+ app.set_simulated_clock(Some(10.0));+ app.collect_screenshots(&ctx);+ let reply = rx.try_recv().expect("the timeout reply");+ assert_eq!(reply["ok"], false);+ assert!(reply["error"].as_str().unwrap_or_default().contains("timed out"), "{reply}");+ assert!(app.pending_screenshots.is_empty());+ assert_eq!(app.shot_bytes, 0, "a timed-out request returns its reservation");+ // The renderer may still deliver the cancelled one-shot: it finds no slot and changes nothing.+ callback.complete(Arc::new(egui::ColorImage::filled([2, 2], egui::Color32::WHITE)));+ app.collect_screenshots(&ctx);+ assert!(rx.try_recv().is_err(), "no second reply");+ assert_eq!(app.shot_bytes, 0);+}++#[test]+fn a_busy_renderer_cannot_turn_a_settled_capture_into_a_timeout() {+ let (tx, _rx) = reply_channel();+ let shot = PendingShot {+ token: 1,+ target: None,+ reply: tx,+ headless: false,+ admitted_passes: 3,+ not_before_ms: 120.0,+ force_ms: 3000.0,+ deadline_ms: 5120.0,+ sent_at_ms: None,+ reserved: 1,+ slot: None,+ issued: None,+ issued_library: 0,+ };+ assert!(!crate::shot_ready(100.0, &shot, false, 6), "settle time has not passed");+ assert!(crate::shot_ready(200.0, &shot, false, 6), "an idle renderer captures as soon as it is settled");+ assert!(!crate::shot_ready(200.0, &shot, true, 6), "a busy renderer still waits for the settle window");+ assert!(crate::shot_ready(3000.0, &shot, true, 6), "the forced instant captures the current frame anyway");+}++#[test]+fn a_silent_compositor_falls_back_to_the_headless_capture_once() {+ let (ctx, mut app) = (egui::Context::default(), app());+ frame(&ctx, raw(egui::vec2(800.0, 600.0)), |ui| app.logic(ui.ctx()));+ app.logic(&ctx);+ assert!(app.fonts_ready);+ app.set_simulated_clock(Some(0.0));+ app.last_shot_geometry = Some(geometry(160.0, 100.0));+ app.ui_passes = 6;+ let (tx, rx) = reply_channel();+ app.admit_shot(&ctx, None, false, tx).expect("a windowed request is admitted");+ let issued = geometry(160.0, 100.0);+ let generation = app.shot_document_generation();+ let callback = {+ let shot = app.pending_screenshots.last_mut().expect("pending");+ issue_into_slot(&ctx, shot, issued, generation)+ };+ app.ui_passes = 9;+ // Two seconds after the command went out, no compositor frame has arrived.+ app.set_simulated_clock(Some(2.5));+ app.issue_screenshots(&ctx);+ let reply = rx.try_recv().expect("the fallback answers");+ assert_eq!(reply["ok"], true, "{reply}");+ assert!(app.pending_screenshots.is_empty());+ assert_eq!(app.shot_bytes, 0);+ // The canceled compositor callback may still fire; it must not produce a second reply.+ callback.complete(Arc::new(egui::ColorImage::filled([2, 2], egui::Color32::WHITE)));+ app.collect_screenshots(&ctx);+ assert!(rx.try_recv().is_err(), "one reply from the fallback");+}++#[test]+fn a_busy_renderer_still_answers_a_headless_capture_at_the_forced_instant() {+ let (ctx, mut app) = (egui::Context::default(), app());+ // Install fonts and reach the "ready" state a real host has after its setup frame.+ frame(&ctx, raw(egui::vec2(800.0, 600.0)), |ui| app.logic(ui.ctx()));+ app.logic(&ctx);+ assert!(app.fonts_ready, "fonts are installed for the shadow frame");+ app.set_simulated_clock(Some(0.0));+ app.last_shot_geometry = Some(geometry(160.0, 100.0));+ app.ui_passes = 10;+ let (tx, rx) = reply_channel();+ app.admit_shot(&ctx, None, true, tx).expect("a headless request is admitted");+ app.ui_passes = 13;+ app.renderer.force_in_flight_for_test(1);+ app.set_simulated_clock(Some(1.0));+ app.issue_screenshots(&ctx);+ assert!(rx.try_recv().is_err(), "a busy renderer defers the capture before the forced instant");+ assert_eq!(app.pending_screenshots.len(), 1);+ app.set_simulated_clock(Some(4.0));+ app.issue_screenshots(&ctx);+ let reply = rx.try_recv().expect("the forced instant answers, it does not time out");+ assert_eq!(reply["ok"], true, "{reply}");+ assert!(app.pending_screenshots.is_empty());+ assert_eq!(app.shot_bytes, 0, "the grown/shrunk reservation is released");+}++#[cfg(not(target_arch = "wasm32"))]+#[derive(Debug)]+struct TestDropped(std::path::PathBuf);++#[cfg(not(target_arch = "wasm32"))]+impl egui::DroppedFile for TestDropped {+ fn path(&self) -> &std::path::Path {+ &self.0+ }++ fn bytes(&self) -> Result<Vec<u8>, String> {+ Ok(vec![])+ }+}++#[cfg(not(target_arch = "wasm32"))]+#[test]+fn one_synthetic_batch_until_a_completed_pass_and_drops_wait_for_the_ui_phase() {+ let mut app = app();+ app.fonts_ready = true;+ app.synthetic.push(egui::Event::PointerMoved(egui::pos2(4.0, 4.0)));+ let mut first = raw(egui::vec2(800.0, 600.0));+ app.raw_input_hook(&mut first);+ assert_eq!(first.events.len(), 1, "one pointer move is injected");+ assert!(app.synthetic_in_flight);+ let mut second = raw(egui::vec2(800.0, 600.0));+ app.raw_input_hook(&mut second);+ assert!(second.events.is_empty(), "no second step while the first waits for a UI pass");++ // Drops are queued by the hook even while a batch is in flight, but only the UI phase takes them.+ second.dropped_files.push(Arc::new(TestDropped(std::env::temp_dir().join("lightcraft-drop.txt"))));+ app.raw_input_hook(&mut second);+ assert_eq!(app.dropped_files.len(), 1);+ let ctx = egui::Context::default();+ frame(&ctx, raw(egui::vec2(800.0, 600.0)), |_| {});+ app.logic(&ctx);+ app.logic(&ctx);+ assert_eq!(app.dropped_files.len(), 1, "a hidden logic tick never replays the drop");+ assert_eq!(app.take_dropped_files().len(), 1, "the UI phase takes the queued drop exactly once");+ assert!(app.dropped_files.is_empty());++ // A completed, nondiscarded app pass (not a bare `run_ui` closure) ends the in-flight batch, so+ // the next host frame injects the next synthetic step. This fails if `finish_ui_pass` stops+ // clearing the gate.+ frame(&ctx, raw(egui::vec2(800.0, 600.0)), |ui| app.ui(ui));+ assert!(!app.synthetic_in_flight, "a completed UI pass consumed the batch");+ app.synthetic.push(egui::Event::PointerMoved(egui::pos2(9.0, 9.0)));+ let mut third = raw(egui::vec2(800.0, 600.0));+ app.raw_input_hook(&mut third);+ assert_eq!(third.events.len(), 1, "the next batch is injected after the completed pass");+}++#[test]+fn first_headless_frame_runs_logic_and_uses_its_simulated_clock() {+ let mut h = Headless::new(app(), [800.0, 600.0], 1.0);+ assert_eq!(h.time(), 0.0);+ h.step();+ assert!(h.app.styled, "the first frame at t=0 runs logic and installs fonts");+ assert_eq!(h.app.tick_now(), 0.0, "the app clock follows the headless host's simulated time");+ h.step();+ h.step();+ assert!(h.app.fonts_ready, "fonts are ready after the setup pass");+ assert_eq!(h.app.ui_passes, 2, "exactly the two steps after the setup pass were laid out");+ assert!(h.app.tick_now() > 0.0, "the simulated clock advanced with the steps");+}++#[test]+fn import_ticks_once_per_host_frame_and_once_per_hidden_tick() {+ let ctx = egui::Context::default();+ let seen = std::cell::RefCell::new(Vec::new());+ frame(&ctx, raw(egui::vec2(800.0, 600.0)), |ui| {+ seen.borrow_mut().push(crate::import_tick_allowed(ui.ctx()));+ if seen.borrow().len() == 1 {+ ui.ctx().request_discard("test: force a second layout pass");+ }+ });+ assert_eq!(*seen.borrow(), vec![true, false], "the first pass commits import batches; the discarded re-run does not");++ let hidden = viewport_raw(egui::vec2(800.0, 600.0), false);+ let mut allowed = false;+ let _ = ctx.run_logic(&hidden, |ctx| allowed = crate::import_tick_allowed(ctx));+ assert!(allowed, "a hidden logic tick reports pass index 0 and must still commit import batches");+}++#[test]+fn hidden_slideshow_pauses_and_keeps_its_remaining_time() {+ let (ctx, mut app) = (egui::Context::default(), app());+ app.set_simulated_clock(Some(10.0));+ let started = crate::panels::slideshow::start(+ &mut app,+ &serde_json::json!({"slideDuration": 2.0, "fadeDuration": 0.0, "randomOrder": false, "repeat": false}),+ 10.0,+ );+ assert!(started.is_ok(), "the demo library has slides: {started:?}");+ // Every slide is "ready": without the hidden gate, 10 hidden seconds would advance the show.+ for id in app.session.visible_cloned() {+ let tex = ctx.load_texture(format!("slide-{}", id.0), egui::ColorImage::filled([2, 2], egui::Color32::WHITE), Default::default());+ app.renderer+ .textures+ .insert(Slot::Slide(Item::Photo(id)), Tex { key: 0, photo: id, tex, size: [2, 2], histogram: None, ms: 0.0, quick: None, pixels: None });+ }+ let first = app.ui.slideshow.as_ref().unwrap().play.current();+ let selection = app.session.active();+ app.set_simulated_clock(Some(10.5));+ let remaining = app.ui.slideshow.as_ref().unwrap().play.remaining(10.5);+ assert!(remaining > 0.0);+ let pending_before = app.renderer.pending_slots();++ let hidden = viewport_raw(egui::vec2(800.0, 600.0), false);+ let _ = ctx.run_logic(&hidden, |ctx| app.logic(ctx));+ assert!(app.ui.slideshow.as_ref().unwrap().play.is_paused(), "hiding auto-pauses playback");+ app.set_simulated_clock(Some(20.0));+ let _ = ctx.run_logic(&hidden, |ctx| app.logic(ctx));+ {+ let play = &app.ui.slideshow.as_ref().unwrap().play;+ assert_eq!(play.current(), first, "a hidden slideshow does not advance");+ assert!((play.remaining(20.0) - remaining).abs() < 1e-6, "the slide keeps its remaining time while hidden");+ }+ assert_eq!(app.session.active(), selection, "a hidden slideshow does not move the selection");+ assert_eq!(app.renderer.pending_slots(), pending_before, "a hidden slideshow requests no new slide renders");++ let visible = viewport_raw(egui::vec2(800.0, 600.0), true);+ app.set_simulated_clock(Some(20.0));+ let _ = ctx.run_logic(&visible, |ctx| app.logic(ctx));+ let play = &app.ui.slideshow.as_ref().unwrap().play;+ assert!(!play.is_paused(), "showing the window resumes playback");+ assert_eq!(play.current(), first);+ assert!((play.remaining(20.0) - remaining).abs() < 1e-6, "resuming does not skip the hidden minutes");+}++#[test]+fn text_field_inherits_ime_delete_surrounding_bytes_exactly() {+ // The pinned 0.37 fork sends winit's incoming byte deletion as+ // `ImeEvent::DeleteSurroundingBytes`; the app's `TextField` wraps the built-in `TextEdit`,+ // so it must apply the range exactly (not extend it to a grapheme cluster).+ let ctx = egui::Context::default();+ let id = crate::text_field::id("ime-bytes");+ let mut text = String::from("abc");+ let pass = |events: Vec<egui::Event>, text: &mut String| {+ let raw =+ egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 200.0))), events, ..Default::default() };+ frame(&ctx, raw, |ui| {+ ui.memory_mut(|memory| memory.request_focus(id));+ let _ = crate::text_field::TextField::singleline("ime-bytes", text).show(ui);+ });+ };+ pass(vec![], &mut text);+ pass(vec![], &mut text);+ let mut state = egui::text_edit::TextEditState::load(&ctx, id).unwrap_or_default();+ state.cursor.set_char_range(Some(egui::text::CCursorRange::one(egui::text::CCursor::new(3))));+ state.store(&ctx, id);+ pass(vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 2, after_bytes: 0 })], &mut text);+ assert_eq!(text, "a", "the reported UTF-8 range is deleted exactly");++ // The same path must not split a multi-byte codepoint when the IME reports its whole width.+ let mut text = String::from("aé🙂z");+ pass(vec![], &mut text);+ pass(vec![], &mut text);+ let mut state = egui::text_edit::TextEditState::load(&ctx, id).unwrap_or_default();+ state.cursor.set_char_range(Some(egui::text::CCursorRange::one(egui::text::CCursor::new(3)))); // after 🙂+ state.store(&ctx, id);+ pass(vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 4, after_bytes: 0 })], &mut text);+ assert_eq!(text, "aéz", "the whole emoji is removed without touching the combining-free neighbours");+}++#[test]+fn text_field_ime_commit_replaces_the_selection() {+ let ctx = egui::Context::default();+ let id = crate::text_field::id("ime-commit");+ let mut text = String::from("abc");+ let pass = |events: Vec<egui::Event>, text: &mut String| {+ let raw =+ egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 200.0))), events, ..Default::default() };+ frame(&ctx, raw, |ui| {+ ui.memory_mut(|memory| memory.request_focus(id));+ let _ = crate::text_field::TextField::singleline("ime-commit", text).show(ui);+ });+ };+ pass(vec![], &mut text);+ pass(vec![], &mut text);+ let mut state = egui::text_edit::TextEditState::load(&ctx, id).unwrap_or_default();+ state.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(2))));+ state.store(&ctx, id);+ pass(vec![egui::Event::Ime(egui::ImeEvent::Commit("é".into()))], &mut text);+ assert_eq!(text, "éc", "the committed text replaces the selected range once");+}++fn shot_dir(name: &str) -> std::path::PathBuf {+ let d = std::env::temp_dir().join(format!("lightcraft-shot-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&d);+ std::fs::create_dir_all(&d).expect("temp screenshot folder");+ d+}++/// Complete one admitted capture whose slot is bound to the current geometry.+fn complete_admitted(ctx: &egui::Context, app: &mut LightcraftApp, image: egui::ColorImage) {+ let generation = app.shot_document_generation();+ let issued = geometry(100.0, 100.0);+ let callback = {+ let shot = app.pending_screenshots.last_mut().expect("pending");+ issue_into_slot(ctx, shot, issued, generation)+ };+ callback.complete(Arc::new(image));+ app.collect_screenshots(ctx);+}++#[test]+fn a_new_file_at_an_absent_screenshot_path_survives() {+ let dir = shot_dir("absent-race");+ let path = dir.join("shot.png");+ let (mut app, _seen) = app_with_screenshot_files();+ let ctx = egui::Context::default();+ app.last_shot_geometry = Some(geometry(100.0, 100.0));+ let (tx, rx) = reply_channel();+ let target = app.session.pin_write_target(&path.to_string_lossy()).expect("the path is free");+ assert!(target.was_absent());+ app.admit_shot(&ctx, Some(target), false, tx).expect("admitted");+ // A photo (or any other file) appears at the path while the capture is queued.+ std::fs::write(&path, b"new original").expect("created while queued");+ complete_admitted(&ctx, &mut app, egui::ColorImage::filled([2, 2], egui::Color32::WHITE));+ let reply = rx.try_recv().expect("one reply");+ assert_eq!(reply["ok"], false, "{reply}");+ assert!(reply["error"].as_str().unwrap_or_default().contains("appeared"), "{reply}");+ assert_eq!(std::fs::read(&path).expect("the new file is still there"), b"new original");+ assert_eq!(app.shot_bytes, 0, "the reservation is released on refusal");+ let _ = std::fs::remove_dir_all(&dir);+}++#[test]+fn an_absent_screenshot_path_that_becomes_a_hard_link_to_an_original_survives() {+ let dir = shot_dir("absent-original");+ let original = dir.join("IMG_1.jpg");+ let path = dir.join("shot.png");+ std::fs::write(&original, b"original").expect("original");+ let (mut app, _seen) = app_with_screenshot_files();+ let ctx = egui::Context::default();+ app.last_shot_geometry = Some(geometry(100.0, 100.0));+ let (tx, rx) = reply_channel();+ let target = app.session.pin_write_target(&path.to_string_lossy()).expect("the path is free");+ app.admit_shot(&ctx, Some(target), false, tx).expect("admitted");+ std::fs::hard_link(&original, &path).expect("an imported hard link appears while queued");+ complete_admitted(&ctx, &mut app, egui::ColorImage::filled([2, 2], egui::Color32::WHITE));+ let reply = rx.try_recv().expect("one reply");+ assert_eq!(reply["ok"], false, "{reply}");+ assert_eq!(std::fs::read(&original).expect("original survives"), b"original");+ assert_eq!(std::fs::read(&path).expect("the link still names the original"), b"original");+ let _ = std::fs::remove_dir_all(&dir);+}++#[test]+fn an_existing_allowed_screenshot_file_is_still_overwritten() {+ let dir = shot_dir("existing-allowed");+ let path = dir.join("shot.png");+ std::fs::write(&path, b"old screenshot").expect("old file");+ let (mut app, _seen) = app_with_screenshot_files();+ let ctx = egui::Context::default();+ app.last_shot_geometry = Some(geometry(100.0, 100.0));+ let (tx, rx) = reply_channel();+ let target = app.session.pin_write_target(&path.to_string_lossy()).expect("ordinary existing file");+ assert!(!target.was_absent());+ app.admit_shot(&ctx, Some(target), false, tx).expect("admitted");+ complete_admitted(&ctx, &mut app, egui::ColorImage::filled([2, 2], egui::Color32::WHITE));+ let reply = rx.try_recv().expect("one reply");+ assert_eq!(reply["ok"], true, "{reply}");+ assert_eq!(std::fs::read(&path).expect("written"), vec![0x89, b'P', b'N', b'G']);+ let _ = std::fs::remove_dir_all(&dir);+}++#[cfg(unix)]+#[test]+fn a_screenshot_parent_retargeted_while_queued_is_not_written() {+ use std::os::unix::fs::symlink;++ let dir = shot_dir("parent-retargeted");+ let admitted = dir.join("admitted");+ let unexpected = dir.join("unexpected");+ let link = dir.join("destination");+ std::fs::create_dir(&admitted).expect("admitted destination folder");+ std::fs::create_dir(&unexpected).expect("unexpected destination folder");+ symlink(&admitted, &link).expect("destination folder link");+ let path = link.join("shot.png");+ let (mut app, seen) = app_with_screenshot_files();+ let ctx = egui::Context::default();+ app.last_shot_geometry = Some(geometry(100.0, 100.0));+ let (tx, rx) = reply_channel();+ let target = app.session.pin_write_target(&path.to_string_lossy()).expect("free path through a folder link");+ assert!(target.was_absent());+ assert!(app.session.revalidate_write_target(&target).is_ok(), "an unchanged folder link is a valid destination");+ app.admit_shot(&ctx, Some(target), false, tx).expect("admitted");++ // The path's spelling is unchanged, but it now resolves to another folder while the real+ // capture is pending. Re-checking only the saved resolved folder would allow this write.+ std::fs::remove_file(&link).expect("unlink only the test folder link");+ symlink(&unexpected, &link).expect("retarget within the test temp folder");+ complete_admitted(&ctx, &mut app, egui::ColorImage::filled([2, 2], egui::Color32::WHITE));++ let reply = rx.try_recv().expect("one reply");+ assert_eq!(reply["ok"], false, "{reply}");+ assert!(reply["error"].as_str().unwrap_or_default().contains("destination folder changed"), "{reply}");+ assert!(!admitted.join("shot.png").exists(), "the refused capture writes nothing to the admitted folder");+ assert!(!unexpected.join("shot.png").exists(), "the refused capture writes nothing to the retargeted folder");+ assert!(seen.lock().unwrap().is_none(), "a changed destination is refused before encoding");+ assert!(app.pending_screenshots.is_empty());+ assert_eq!(app.shot_bytes, 0, "the refused capture releases its reservation");+ assert!(rx.try_recv().is_err(), "the refused capture has exactly one reply");+ let _ = std::fs::remove_dir_all(&dir);+}++#[cfg(unix)]+#[test]+fn an_existing_screenshot_target_replaced_while_queued_is_not_overwritten() {+ let dir = shot_dir("existing-replaced");+ let path = dir.join("shot.png");+ let keep = dir.join("keep.png");+ let other = dir.join("other.png");+ std::fs::write(&path, b"old screenshot").expect("old file");+ let (mut app, _seen) = app_with_screenshot_files();+ let ctx = egui::Context::default();+ app.last_shot_geometry = Some(geometry(100.0, 100.0));+ let (tx, rx) = reply_channel();+ let target = app.session.pin_write_target(&path.to_string_lossy()).expect("ordinary existing file");+ app.admit_shot(&ctx, Some(target), false, tx).expect("admitted");+ // Keep the admitted inode alive, then replace the directory entry with a different file.+ std::fs::hard_link(&path, &keep).expect("keep the admitted inode");+ std::fs::write(&other, b"new file").expect("new file");+ std::fs::rename(&other, &path).expect("replace the entry");+ complete_admitted(&ctx, &mut app, egui::ColorImage::filled([2, 2], egui::Color32::WHITE));+ let reply = rx.try_recv().expect("one reply");+ assert_eq!(reply["ok"], false, "{reply}");+ assert!(reply["error"].as_str().unwrap_or_default().contains("changed"), "{reply}");+ assert_eq!(std::fs::read(&path).expect("the replacing file survives"), b"new file");+ assert_eq!(std::fs::read(&keep).expect("the admitted file survives"), b"old screenshot");+ let _ = std::fs::remove_dir_all(&dir);+}++#[test]+fn ui_scroll_carries_validated_unit_phase_and_source() {+ let (mut app, ctx) = (app(), egui::Context::default());+ let result = crate::control::gesture_events(+ &mut app,+ &ctx,+ "ui.scroll",+ &serde_json::json!({"source": "wheel", "unit": "line", "phase": "start", "dy": 1.0}),+ )+ .expect("a wheel line step is valid");+ assert_eq!(result, serde_json::Value::Null);+ match app.synthetic.first().expect("one wheel event") {+ egui::Event::MouseWheel { unit, phase, source, .. } => {+ assert_eq!(*unit, egui::MouseWheelUnit::Line);+ assert_eq!(*phase, egui::TouchPhase::Start);+ assert_eq!(*source, egui::MouseWheelSource::Wheel);+ }+ other => panic!("expected a wheel event, got {other:?}"),+ }++ app.synthetic.clear();+ crate::control::gesture_events(+ &mut app,+ &ctx,+ "ui.scroll",+ &serde_json::json!({"source": "trackpad", "unit": "point", "phase": "end", "dy": -12.0}),+ )+ .expect("a trackpad end event is valid");+ match app.synthetic.first().expect("one wheel event") {+ egui::Event::MouseWheel { unit, phase, source, .. } => {+ assert_eq!(*unit, egui::MouseWheelUnit::Point);+ assert_eq!(*phase, egui::TouchPhase::End);+ assert_eq!(*source, egui::MouseWheelSource::Trackpad);+ }+ other => panic!("expected a wheel event, got {other:?}"),+ }++ // Omitted keys keep the pre-0.37 request meaning.+ app.synthetic.clear();+ crate::control::gesture_events(&mut app, &ctx, "ui.scroll", &serde_json::json!({"dy": 3.0})).expect("defaults are valid");+ match app.synthetic.first().expect("one wheel event") {+ egui::Event::MouseWheel { unit, phase, source, .. } => {+ assert_eq!(*unit, egui::MouseWheelUnit::Point);+ assert_eq!(*phase, egui::TouchPhase::Move);+ assert_eq!(*source, egui::MouseWheelSource::Unknown);+ }+ other => panic!("expected a wheel event, got {other:?}"),+ }++ // An invalid value is an error and queues nothing.+ app.synthetic.clear();+ let error = crate::control::gesture_events(&mut app, &ctx, "ui.scroll", &serde_json::json!({"unit": "notch"})).expect_err("unknown unit");+ assert!(error.contains("unit"), "{error}");+ assert!(app.synthetic.is_empty());+}++#[test]+fn a_gesture_never_uses_the_previous_widget_registry() {+ let ctx = egui::Context::default();+ let mut app = app();+ frame(&ctx, raw(egui::vec2(1000.0, 700.0)), |ui| app.logic(ui.ctx()));+ app.logic(&ctx);+ assert!(app.fonts_ready);+ app.widgets.push(("stale:test".into(), egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(10.0, 10.0))));+ let (tx, rx) = reply_channel();+ app.admit_gesture(&ctx, "ui.clickWidget".into(), serde_json::json!({"id": "stale:test"}), tx).expect("admitted");+ assert!(rx.try_recv().is_err(), "nothing is answered at admission");+ // A completed pass replaces the registry; the stale id is not in the fresh one.+ frame(&ctx, raw(egui::vec2(1000.0, 700.0)), |ui| {+ app.logic(ui.ctx());+ app.ui(ui);+ });+ let reply = rx.try_recv().expect("the resolution error answers once");+ assert_eq!(reply["ok"], false, "{reply}");+ assert!(reply["error"].as_str().unwrap_or_default().contains("no widget"), "{reply}");+ assert!(app.pending_gestures.is_empty());+ assert!(app.synthetic.is_empty());+}++#[test]+fn a_gesture_cancels_when_the_view_changes_before_the_fresh_layout() {+ let ctx = egui::Context::default();+ let mut app = app();+ frame(&ctx, raw(egui::vec2(1000.0, 700.0)), |ui| app.logic(ui.ctx()));+ app.logic(&ctx);+ assert!(app.fonts_ready);+ let (tx, rx) = reply_channel();+ app.admit_gesture(&ctx, "ui.move".into(), serde_json::json!({"x": 10.0, "y": 10.0}), tx).expect("admitted");+ // the app opens in Detail, so a cancellation test must move to a genuinely different view+ app.ui.view = crate::state::ViewMode::PhotoGrid;+ frame(&ctx, raw(egui::vec2(1000.0, 700.0)), |ui| {+ app.logic(ui.ctx());+ app.ui(ui);+ });+ let reply = rx.try_recv().expect("the cancel error answers once");+ assert_eq!(reply["ok"], false, "{reply}");+ assert!(reply["error"].as_str().unwrap_or_default().contains("canceled"), "{reply}");+ assert!(app.synthetic.is_empty());+}++#[test]+fn a_gesture_replies_only_after_the_completed_pass_consumed_its_event() {+ let ctx = egui::Context::default();+ let mut app = app();+ frame(&ctx, raw(egui::vec2(1000.0, 700.0)), |ui| app.logic(ui.ctx()));+ app.logic(&ctx);+ assert!(app.fonts_ready);+ app.ui.view = crate::state::ViewMode::Detail;+ let (tx, rx) = reply_channel();+ app.admit_gesture(&ctx, "ui.move".into(), serde_json::json!({"x": 12.0, "y": 14.0}), tx).expect("admitted");+ frame(&ctx, raw(egui::vec2(1000.0, 700.0)), |ui| {+ app.logic(ui.ctx());+ app.ui(ui);+ });+ assert_eq!(app.synthetic.len(), 1, "resolution queued the event");+ assert!(rx.try_recv().is_err(), "not answered before the UI consumed it");+ let mut next = raw(egui::vec2(1000.0, 700.0));+ app.raw_input_hook(&mut next);+ assert!(next.events.iter().any(|e| matches!(e, egui::Event::PointerMoved(_))), "the event is injected next frame");+ frame(&ctx, next, |ui| {+ app.logic(ui.ctx());+ app.ui(ui);+ });+ let reply = rx.try_recv().expect("the delivery reply");+ assert_eq!(reply["ok"], true, "{reply}");+ assert!(app.pending_gestures.is_empty());+}++#[test]+fn a_delivered_gesture_may_change_the_state_it_acted_on() {+ let ctx = egui::Context::default();+ let mut app = app();+ frame(&ctx, raw(egui::vec2(1000.0, 700.0)), |ui| app.logic(ui.ctx()));+ app.logic(&ctx);+ assert!(app.fonts_ready);+ let (tx, rx) = reply_channel();+ app.admit_gesture(&ctx, "ui.key".into(), serde_json::json!({"key": "j", "cmd": true}), tx).expect("admitted");+ // The first completed pass resolves the key against the Detail layout and queues it.+ frame(&ctx, raw(egui::vec2(1000.0, 700.0)), |ui| {+ app.logic(ui.ctx());+ app.ui(ui);+ });+ assert!(!app.synthetic.is_empty(), "the key is queued");+ // The pass that consumes it opens the dialog: that is the gesture doing its job, not drift.+ let mut next = raw(egui::vec2(1000.0, 700.0));+ app.raw_input_hook(&mut next);+ frame(&ctx, next, |ui| {+ app.logic(ui.ctx());+ app.ui(ui);+ });+ assert_eq!(app.ui.dialog, Some(crate::state::Dialog::ViewOptions));+ let reply = rx.try_recv().expect("the delivered gesture answers");+ assert_eq!(reply["ok"], true, "{reply}");+ assert!(app.pending_gestures.is_empty());+}++#[test]+fn a_gesture_cancels_when_the_view_changes_before_its_batch_is_injected() {+ let ctx = egui::Context::default();+ let mut app = app();+ frame(&ctx, raw(egui::vec2(1000.0, 700.0)), |ui| app.logic(ui.ctx()));+ app.logic(&ctx);+ assert!(app.fonts_ready);+ let (tx, rx) = reply_channel();+ app.admit_gesture(&ctx, "ui.move".into(), serde_json::json!({"x": 10.0, "y": 10.0}), tx).expect("admitted");+ frame(&ctx, raw(egui::vec2(1000.0, 700.0)), |ui| {+ app.logic(ui.ctx());+ app.ui(ui);+ });+ assert_eq!(app.synthetic.len(), 1, "resolution queued the event");+ // A hidden logic tick changes what the queued pointer event would mean before a visible+ // pass consumes it: fail closed instead of injecting it into the new view.+ app.ui.view = crate::state::ViewMode::PhotoGrid;+ let mut next = raw(egui::vec2(1000.0, 700.0));+ app.raw_input_hook(&mut next);+ assert!(next.events.is_empty(), "no stale event reaches the new view");+ assert!(app.synthetic.is_empty());+ let reply = rx.try_recv().expect("the cancel error answers once");+ assert_eq!(reply["ok"], false, "{reply}");+ assert!(reply["error"].as_str().unwrap_or_default().contains("canceled"), "{reply}");+ assert!(app.pending_gestures.is_empty());+}++fn queued_shot(sent_at_ms: Option<f64>) -> PendingShot {+ let (tx, _rx) = reply_channel();+ PendingShot {+ token: 1,+ target: None,+ reply: tx,+ headless: false,+ admitted_passes: 0,+ not_before_ms: 0.0,+ force_ms: 0.0,+ deadline_ms: 10_000.0,+ sent_at_ms,+ reserved: 1,+ slot: None,+ issued: None,+ issued_library: 0,+ }+}++#[test]+fn hidden_paint_requests_only_queued_shots_not_issued_ones() {+ let mut app = app();+ app.pending_screenshots.push(queued_shot(Some(1.0)));+ assert!(!app.needs_ui_pass_while_hidden(), "an issued screenshot forces its own paint");+ app.pending_screenshots.clear();+ app.pending_screenshots.push(queued_shot(None));+ assert!(app.needs_ui_pass_while_hidden(), "a queued/settling screenshot needs a UI pass");+ app.pending_screenshots.clear();+ app.synthetic.push(egui::Event::PointerMoved(egui::Pos2::ZERO));+ assert!(app.needs_ui_pass_while_hidden(), "a gesture step needs a UI pass");+}++#[test]+fn disclosure_rows_publish_expanded_not_toggled() {+ let ctx = egui::Context::default();+ ctx.enable_accesskit();+ let mut seen = Vec::new();+ frame(&ctx, raw(egui::vec2(400.0, 300.0)), |ui| {+ let (resp, _) = crate::widgets::section_header(ui, "test-section", "Light", true, None);+ seen.push(ui.ctx().accesskit_node_builder(resp.id, |node| node.is_expanded()).flatten());+ });+ frame(&ctx, raw(egui::vec2(400.0, 300.0)), |ui| {+ let (resp, _) = crate::widgets::section_header(ui, "test-section", "Light", false, None);+ seen.push(ui.ctx().accesskit_node_builder(resp.id, |node| node.is_expanded()).flatten());+ });+ assert_eq!(seen, vec![Some(true), Some(false)], "the disclosure reports Expanded, not Toggled");+}diff --git a/crates/ui-egui/src/tests_model_setup.rs b/crates/ui-egui/src/tests_model_setup.rsindex 1366b745a..22c4ca7f9 100644--- a/crates/ui-egui/src/tests_model_setup.rs+++ b/crates/ui-egui/src/tests_model_setup.rs@@ -90,7 +90,7 @@ fn amount(app: &LightcraftApp, id: PhotoId) -> f64 {app.session.develop_of(id).unwrap().enhance.denoise}fn resume(app: &mut LightcraftApp) {- model_setup::pump(app, &egui::Context::default());+ model_setup::pump(app, &egui::Context::default(), app.tick_now());}#[test]diff --git a/crates/ui-egui/src/tests_open_lightroom.rs b/crates/ui-egui/src/tests_open_lightroom.rsindex cddfa2bef..8f810fa9f 100644--- a/crates/ui-egui/src/tests_open_lightroom.rs+++ b/crates/ui-egui/src/tests_open_lightroom.rs@@ -47,6 +47,7 @@ fn open_library_on_a_lightroom_catalog_offers_its_import() {pick_folder: Some(Box::new(move || Some(picked.clone()))),png: Some(Box::new(png)),write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))),+ write_new: Some(Box::new(lightcraft_engine::export::write_file_new)),..Default::default()};let mut h = Headless::new(LightcraftApp::new(session, services), [1200.0, 800.0], 1.0);diff --git a/crates/ui-egui/src/tests_scroll.rs b/crates/ui-egui/src/tests_scroll.rsindex dd999108a..da61d4836 100644--- a/crates/ui-egui/src/tests_scroll.rs+++ b/crates/ui-egui/src/tests_scroll.rs@@ -215,6 +215,7 @@ fn notch(h: &mut Headless, dy: f32) {unit: egui::MouseWheelUnit::Line,delta: egui::vec2(0.0, dy),phase: egui::TouchPhase::Move,+ source: egui::MouseWheelSource::Unknown,modifiers: egui::Modifiers::NONE,});h.step();diff --git a/crates/ui-egui/src/text_field.rs b/crates/ui-egui/src/text_field.rsindex aed99f4d8..d9a28dadb 100644--- a/crates/ui-egui/src/text_field.rs+++ b/crates/ui-egui/src/text_field.rs@@ -65,7 +65,7 @@ pub struct TextField<'a> {/// The egui id of the field registered as `widget`, to give it the focus (⌘F to search).pub fn id(widget: &str) -> egui::Id {- egui::Id::new("lc-text-field").with(widget)+ egui::Id::unique("lc-text-field").with(widget)}/// Whether the field had an unfinished edit on the immediately preceding egui pass.@@ -210,7 +210,7 @@ impl<'a> TextField<'a> {edit = edit.text_color(color);}if let Some(align) = self.align {- edit = edit.horizontal_align(align);+ edit = edit.align(egui::Align2([align, egui::Align::Min]));}if let Some(margin) = self.margin {edit = edit.margin(margin);diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rsindex 57ee987d1..6a532f210 100644--- a/crates/ui-egui/src/theme.rs+++ b/crates/ui-egui/src/theme.rs@@ -379,7 +379,7 @@ pub const WHEEL_STRIP_SHARE: f32 = 1.0 / 3.0;pub const WHEEL_ZOOM_PER_POINT: f32 = 40.0 / 200.0 / WHEEL_LINE_POINTS;fn theme_id() -> egui::Id {- egui::Id::new("lightcraft-theme")+ egui::Id::unique("lightcraft-theme")}/// The theme `ctx` is styled with (none before the first [`apply_kind`]).diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rsindex 2db3f885e..83307df11 100644--- a/crates/ui-egui/src/widgets.rs+++ b/crates/ui-egui/src/widgets.rs@@ -9,7 +9,7 @@ use crate::icons::{Icon, paint};use crate::theme::Tokens;/// Standard dropdown chevrons, including settings, import/export and rule editors.-pub fn combo_box(id: impl egui::AsIdSalt) -> egui::ComboBox {+pub fn combo_box(id: impl egui::AsIdSalt) -> egui::ComboBox<'static> {egui::ComboBox::from_id_salt(id).icon(|ui, rect, visuals, _| {paint(ui.painter(), Rect::from_center_size(rect.center(), vec2(16.0, 16.0)), Icon::ChevronDown, visuals.fg_stroke.color);@@ -17,6 +17,13 @@ pub fn combo_box(id: impl egui::AsIdSalt) -> egui::ComboBox {.popup_style(list_style.into())}+/// Name a dropdown for screen readers. egui 0.37's `ComboBox::from_id_salt` publishes only the+/// selected text as the node's value, so an otherwise unlabelled combo has no accessible name and+/// the strict kittest check rejects it. Call this on the response returned by `show_ui`.+pub fn name_combo(response: &egui::Response, label: &str) {+ response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, response.enabled(), label));+}+/// A dropdown's list and its submenus: items without the resting border of a button, as egui's/// own menus draw them. An unhovered item gives up its border's width of padding, so with one it/// grew 2 points when hovered, and the longest name of a list sized to it wrapped (#2354).@@ -26,7 +33,9 @@ fn list_style(style: &mut egui::Style) {/// A native button with a vector arrow beside its text; egui reserves the icon's space.pub fn arrow_button<'a>(ui: &mut Ui, text: impl egui::IntoAtoms<'a>, icon: Icon, leading: bool) -> Response {- let id = ui.next_auto_id().with("arrow");+ // 0.37 atoms take a local `IdSalt` (not a root `Id`); the button reports the custom atom's+ // rect under the same salt.+ let id = egui::IdSalt::new(("lc-arrow", ui.next_auto_id()));let mut atoms = text.into_atoms();let arrow = egui::Atom::custom(id, vec2(16.0, 16.0));if leading {@@ -76,23 +85,23 @@ pub struct Registry(pub Vec<(String, Rect)>);/// Record a widget's automation id and screen rect for this frame.pub fn register(ctx: &egui::Context, id: impl Into<String>, rect: Rect) {let id = id.into();- ctx.data_mut(|d| d.get_temp_mut_or_default::<Registry>(egui::Id::new("lc-registry")).0.push((id, rect)));+ ctx.data_mut(|d| d.get_temp_mut_or_default::<Registry>(egui::Id::unique("lc-registry")).0.push((id, rect)));}/// Esc was handled this frame by something nested (an open popup closed on it): containers such/// as dialogs shouldn't close too. Keyed to the frame, so it lapses by itself on the next one.pub fn take_escape(ctx: &egui::Context) {let frame = ctx.cumulative_frame_nr();- ctx.data_mut(|d| d.insert_temp(egui::Id::new("lc-escape-taken"), frame));+ ctx.data_mut(|d| d.insert_temp(egui::Id::unique("lc-escape-taken"), frame));}/// Whether [`take_escape`] was called this frame.pub fn escape_taken(ctx: &egui::Context) -> bool {- ctx.data(|d| d.get_temp::<u64>(egui::Id::new("lc-escape-taken"))) == Some(ctx.cumulative_frame_nr())+ ctx.data(|d| d.get_temp::<u64>(egui::Id::unique("lc-escape-taken"))) == Some(ctx.cumulative_frame_nr())}pub fn take_registry(ctx: &egui::Context) -> Vec<(String, Rect)> {- ctx.data_mut(|d| std::mem::take(&mut d.get_temp_mut_or_default::<Registry>(egui::Id::new("lc-registry")).0))+ ctx.data_mut(|d| std::mem::take(&mut d.get_temp_mut_or_default::<Registry>(egui::Id::unique("lc-registry")).0))}// ------------------------------------------------------------------ preview-only raws@@ -143,7 +152,7 @@ pub fn preview_only_notice(ui: &mut Ui, key: &str, reason: &str) -> bool {}).response;let r = r.on_hover_text(crate::i18n::tr_format!("Decoder: {reason}", reason = reason));- r.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, crate::i18n::tr("Preview only: editing the camera's embedded JPEG")));+ r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, crate::i18n::tr("Preview only: editing the camera's embedded JPEG")));register(ui.ctx(), format!("notice:previewOnly:{key}"), r.rect);reload}@@ -262,7 +271,7 @@ pub fn slider(ui: &mut Ui, spec: &ControlSpec, value: f64, enabled: bool, label_let pad_r = 22.0;let label_rect = Rect::from_min_size(pos2(row.left() + pad_l, row.top() + 4.0), vec2(w - pad_l - pad_r, 18.0));let track_rect = Rect::from_min_max(pos2(row.left() + pad_l, row.top() + 22.0), pos2(row.right() - pad_r, row.top() + 40.0));- let id = ui.id().with(spec.id);+ let id = ui.scope_id().with(spec.id);let resp = ui.interact(track_rect.expand2(vec2(8.0, 2.0)), id, if enabled { Sense::click_and_drag() } else { Sense::hover() });// Keyboard focus survives leaving the row; vertical wheel edits need a fresh click or drag// in it (at most one slider is armed: `wheel_slider_key`).@@ -618,13 +627,23 @@ pub fn nudged(spec: &ControlSpec, value: f64, steps: f64) -> f64 {(((value + unit * steps) / step).round() * step).clamp(spec.min, spec.max)}+/// Announce a disclosure row with AccessKit's real `Expanded` state.+///+/// egui 0.37's `WidgetInfo::selected` maps to AccessKit `Toggled`; a custom disclosure row must+/// publish `Expanded` instead (the built-in `CollapsingHeader` does this through+/// `accesskit_node_builder`). Use one helper so section headers, flyouts and fold titles agree.+pub(crate) fn announce_disclosure(resp: &egui::Response, enabled: bool, expanded: bool, label: impl ToString) {+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::DisclosureTriangle, enabled, label.to_string()));+ resp.ctx.accesskit_node_builder(resp.id, |node| node.set_expanded(expanded));+}+/// Collapsible section header ("› Light"). Returns the response (click toggles).pub fn section_header(ui: &mut Ui, id: &str, title: &str, open: bool, enabled: Option<bool>) -> (Response, Option<bool>) {let title = crate::i18n::tr(title);let t = Tokens::get(ui.ctx());let w = ui.available_width();let (r, resp) = ui.allocate_exact_size(vec2(w, 52.0), Sense::click());- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::CollapsingHeader, true, open, title));+ announce_disclosure(&resp, true, open, title);register(ui.ctx(), format!("section:{id}"), r);let p = ui.painter();if ui.rect_contains_pointer(r) {@@ -641,7 +660,7 @@ pub fn section_header(ui: &mut Ui, id: &str, title: &str, open: bool, enabled: O&& (ui.rect_contains_pointer(r) || !on){let eye = Rect::from_center_size(pos2(r.right() - 34.0, r.center().y), vec2(18.0, 18.0));- let er = ui.interact(eye, ui.id().with(("eye", id)), Sense::click());+ let er = ui.interact(eye, ui.scope_id().with(("eye", id)), Sense::click());crate::widgets::announce_selected(&er, crate::i18n::tr("Show / hide"), on);register(ui.ctx(), format!("sectionEye:{id}"), eye);paint(ui.painter(), eye, Icon::Eye, if on { t.icon } else { t.text_disabled });@@ -670,8 +689,8 @@ pub fn flyout_row(ui: &mut Ui, id: &str, title: &str, icon: Icon, open: bool) ->let w = ui.available_width();let (outer, _) = ui.allocate_exact_size(vec2(w, 40.0), Sense::hover());let r = Rect::from_min_max(pos2(outer.left() + 16.0, outer.top() + 4.0), pos2(outer.right() - 16.0, outer.bottom() - 4.0));- let resp = ui.interact(r, ui.id().with(("flyout", id)), Sense::click());- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::CollapsingHeader, true, open, title));+ let resp = ui.interact(r, ui.scope_id().with(("flyout", id)), Sense::click());+ announce_disclosure(&resp, true, open, title);register(ui.ctx(), format!("flyout:{id}"), r);let p = ui.painter();p.rect_filled(r, 4.0, if resp.hovered() { t.hover.gamma_multiply(0.8) } else { t.inset });@@ -696,7 +715,7 @@ pub fn text_button(ui: &mut Ui, id: &str, label: &str, active: bool) -> Responselet galley = ui.painter().layout_no_wrap(label.to_string(), font, t.text);let size = vec2((galley.size().x + 18.0).max(37.0), 24.0);let (r, resp) = ui.allocate_exact_size(size, Sense::click());- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, true, active, label));+ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, active, label));register(ui.ctx(), format!("button:{id}"), r);let fill = if active {t.pressed@@ -753,7 +772,7 @@ pub fn icon_button(ui: &mut Ui, id: &str, icon: Icon, size: egui::Vec2, active:let tooltip = crate::i18n::tr(tooltip);let t = Tokens::get(ui.ctx());let (r, resp) = ui.allocate_exact_size(size, if enabled { Sense::click() } else { Sense::hover() });- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, enabled, active, tooltip));+ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, enabled, active, tooltip));register(ui.ctx(), format!("icon:{id}"), r);let p = ui.painter();let sq = Rect::from_center_size(r.center(), vec2(32.0f32.min(size.x), 32.0f32.min(size.y)));@@ -824,7 +843,7 @@ pub fn dropdown_within(ui: &mut Ui, id: &str, text: &str, font: egui::FontId, colet elided = galley.elided;let size = vec2(galley.size().x + 20.0, galley.size().y.max(20.0));let (r, resp) = ui.allocate_exact_size(size, Sense::click());- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::ComboBox, true, text));+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, text));register(ui.ctx(), format!("dropdown:{id}"), r);let c = if resp.hovered() { t.text } else { color };ui.painter().galley(pos2(r.left(), r.center().y - galley.size().y / 2.0), galley, c);@@ -1004,13 +1023,13 @@ pub(crate) fn screen_reader_name(ctx: &egui::Context, id: egui::Id, name: &str)/// A hand-drawn clickable area (an icon, a tile, a row) announced as a button named `name`.pub(crate) fn announce(resp: &egui::Response, name: impl Into<String>) {let name = name.into();- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, resp.enabled(), name.clone()));+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, resp.enabled(), name.clone()));}/// The same for one that is on or off (a toggle, a selected row or swatch).pub(crate) fn announce_selected(resp: &egui::Response, name: impl Into<String>, selected: bool) {let name = name.into();- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, resp.enabled(), selected, name.clone()));+ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, resp.enabled(), selected, name.clone()));}/// `r`, named `name` for screen readers: a plain egui field or slider whose caption is drawn@@ -1064,12 +1083,12 @@ mod numeric_entry_tests;mod slider_reset_tests;fn focused_slider_key() -> egui::Id {- egui::Id::new("lightcraft-focused-slider")+ egui::Id::unique("lightcraft-focused-slider")}/// The slider a click or drag armed for vertical wheel edits, if any.fn wheel_slider_key() -> egui::Id {- egui::Id::new("lightcraft-wheel-slider")+ egui::Id::unique("lightcraft-wheel-slider")}/// Whether the widget with keyboard focus is a develop slider selected by a click, drag or Tab.diff --git a/crates/ui-egui/src/widgets/tests_numeric_entry.rs b/crates/ui-egui/src/widgets/tests_numeric_entry.rsindex eb2e3c9b8..0bd49abae 100644--- a/crates/ui-egui/src/widgets/tests_numeric_entry.rs+++ b/crates/ui-egui/src/widgets/tests_numeric_entry.rs@@ -206,6 +206,7 @@ fn leaving_a_slider_disarms_wheel_edits_until_it_is_selected_again() {unit: egui::MouseWheelUnit::Point,delta: vec2(0.0, 120.0),phase: egui::TouchPhase::Move,+ source: egui::MouseWheelSource::Unknown,modifiers: Modifiers::NONE,};h.frame(vec![Event::PointerMoved(inside)]);@@ -232,7 +233,13 @@ fn leaving_a_slider_disarms_wheel_edits_until_it_is_selected_again() {let before_sideways = h.value;h.frame(vec![Event::PointerMoved(inside),- Event::MouseWheel { unit: egui::MouseWheelUnit::Point, delta: vec2(120.0, 0.0), phase: egui::TouchPhase::Move, modifiers: Modifiers::NONE },+ Event::MouseWheel {+ unit: egui::MouseWheelUnit::Point,+ delta: vec2(120.0, 0.0),+ phase: egui::TouchPhase::Move,+ source: egui::MouseWheelSource::Unknown,+ modifiers: Modifiers::NONE,+ },]);for _ in 0..40 {h.frame(vec![]);@@ -270,7 +277,13 @@ fn leaving_the_row_during_a_drag_keeps_dragging_but_release_disarms_the_wheel()let released = h.value;h.frame(vec![Event::PointerMoved(inside),- Event::MouseWheel { unit: egui::MouseWheelUnit::Point, delta: vec2(0.0, -120.0), phase: egui::TouchPhase::Move, modifiers: Modifiers::NONE },+ Event::MouseWheel {+ unit: egui::MouseWheelUnit::Point,+ delta: vec2(0.0, -120.0),+ phase: egui::TouchPhase::Move,+ source: egui::MouseWheelSource::Unknown,+ modifiers: Modifiers::NONE,+ },]);for _ in 0..40 {h.frame(vec![]);@@ -294,6 +307,7 @@ fn a_drag_that_leaves_and_ends_back_in_the_row_disarms_the_wheel() {unit: egui::MouseWheelUnit::Point,delta: vec2(0.0, 120.0),phase: egui::TouchPhase::Move,+ source: egui::MouseWheelSource::Unknown,modifiers: Modifiers::NONE,}]);for _ in 0..40 {@@ -308,6 +322,7 @@ fn leaving_and_returning_within_one_frame_still_disarms_the_wheel() {unit: egui::MouseWheelUnit::Point,delta: vec2(0.0, 120.0),phase: egui::TouchPhase::Move,+ source: egui::MouseWheelSource::Unknown,modifiers: Modifiers::NONE,};// a slow frame merges the moves out of the row and back (or out of the window and back)diff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex dd41bcdb8..91c2ea079 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -85,13 +85,13 @@ filmstrip is visible.| `ui.key` | `{key, cmd?, shift?, alt?, ctrl?}` | Key press || `ui.text` | `{text}` | Text input || `ui.clipboard` | `{action: cut\|copy\|paste, text?}` | Cut, copy or paste in the focused text field, as the system does for ⌘X / ⌘C / ⌘V; `paste` pastes `text`, or the system clipboard without it. Refused when no text field has the focus (outside one, ⌘C / ⌘V are the commands `develop.copy` / `develop.paste`). In the desktop app cut and copy write the system clipboard. `ui.inspect` → `copied` is the text the UI last put on the clipboard |-| `ui.scroll` | `{dx, dy, cmd?, ctrl?, shift?, alt?}` | Wheel / two-finger scroll at the current pointer; pans over the image, modifier-scroll zooms |+| `ui.scroll` | `{dx, dy, source?, unit?, phase?, cmd?, ctrl?, shift?, alt?}` | Wheel / two-finger scroll at the current pointer; pans over the image, modifier-scroll zooms. `source` is `unknown` (default), `wheel`, `trackpad` or `momentum`; `unit` is `point` (default), `line` or `page`; `phase` is `move` (default), `start`, `end` or `cancel`. Wheel/line events drive the grid/filmstrip one-third wheel step and the loupe's notch zoom; trackpad/momentum phases drive kinetic scrolling and rubber-band boundaries. Invalid values are refused and queue nothing || `ui.zoom` | `{factor}` | Pinch zoom at the current pointer (positive scale multiplier; 1 = unchanged). Position it first with `ui.move` or `ui.hoverWidget` || `ui.set` | partial UI state, e.g. `{"view": "detail"}` | Resulting UI state || `ui.dialog.confirm` / `ui.dialog.cancel` | — | Close the open dialog (confirm runs its action; Synchronize Folder on a folder that is up to date answers `{"upToDate": true}` and starts nothing) || `ui.resize` | `{width, height}` | Resize the window || `ui.zoomFactor` | `{factor}` | Set the interface scale (0.5–3; egui's zoom keys are off, Cmd+= / Cmd+- zoom the photo) |-| `ui.screenshot` | `{path?, headless?}` | `{path, width, height}` once the frame (with finished renders) is captured. `headless: true` draws the UI on the CPU (no compositor needed); a windowed capture that gets no frame within 2 s falls back to headless automatically. While the loupe still waits for a render, `ui.widgets {filter: "loupe:rendering"}` lists its "Rendering…" pill; `loupe:renderFailed` is the pill saying a render failed behind a stand-in; Compare and Reference panes have their own (`compare:rendering:<pane>`, `compare:renderFailed:<pane>`) |+| `ui.screenshot` | `{path?, headless?}` | `{path, width, height}` once the frame (with finished renders) is captured. A `path` that did not exist when the request was admitted is written with create-new semantics and is never replaced if a file (including a newly imported original) appears there while the capture is queued; an existing ordinary file may be refreshed. `headless: true` draws the UI on the CPU (no compositor needed); a windowed capture that gets no frame within 2 s falls back to headless automatically. While the loupe still waits for a render, `ui.widgets {filter: "loupe:rendering"}` lists its "Rendering…" pill; `loupe:renderFailed` is the pill saying a render failed behind a stand-in; Compare and Reference panes have their own (`compare:rendering:<pane>`, `compare:renderFailed:<pane>`) || `engine.execute {command: "app.export", params}` | export params (see `docs/mcp.md`), plus `preset`, `dir` / `path`, `ids`, `background`; `destinationMode: "sameAsOriginal"` writes each photo into its original's folder (+ `subfolder`) instead of `dir` | Writes the files and returns `{files}` (one `{path, width, height, bytes, sidecars}` per file, plus `gpuFallback` — why that render fell back from the GPU to the CPU — when it did; see `docs/gpu-pipeline.md`); with `background: true` (what the Export dialog and menus use) it returns `{background: true, total}` at once and the batch runs on a worker thread — poll `ui.inspect` → `export` || `engine.execute {command: "activity.list"}` | — | The long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first: `{tasks: [{id, kind, label, done, total, unit, detail, cancellable, cancelling, ageMs}]}`; `total` 0 = not known yet; `unit` is `count`, `bytes` or `percent`; `label` is English (the app shows it translated) || `engine.execute {command: "activity.cancel"}` | `{id}` or `{all: true}` | Asks the task (or every cancellable one) to stop at its next file or photo → `{cancelled: n}`; an unknown id (it may have just finished) or a task that can't be cancelled is an error |diff --git a/docs/egui-037-migration-plan.md b/docs/egui-037-migration-plan.mdnew file mode 100644index 000000000..f63a4dbf2--- /dev/null+++ b/docs/egui-037-migration-plan.md@@ -0,0 +1,1517 @@+# LightCraft: egui 0.37 migration plan++## Current implementation status — 2026-10-24++The implementation is now pinned to egui `173cc7375d35dc5fbc5b5d0994fdf787f547c5d1`,+winit `ae48c756a3b81125eb796c0cc6dccf60990d1181`, craft-libs+`c488caa9fbc2fb1a86e4674887e9b80b598ebbfa`, craft-fonts+`b076417b5880bd4154bd22f00695b1d28c6bea83` and craft-i18n+`e5bfe19b95d30f50f250985bdc3aeec47c05af09`. Cargo-generated lock SHA-256:+`2b6c3550997fd4962df7865ec038cc409604aafaaf2267fa416ad9d98df91da9`.+These are exact local reviewed revisions; public fetchability still requires the separately+approved foundation publication. Earlier planning and source-only validation statements below+are historical and are superseded by this status.++The mandatory `cargo xtask ci` passed all eight stages (fmt, strict clippy, HEIF, tests,+parity, layers, assets and WASM). Its log reports 4,739 passing test invocations, zero failures+and 40 ignored tests. The CI prerequisite report separately lists 149 checks that returned+without exercising their checks: corpus 137, models 8, fonts 2, GPU 1 and system 1. These are+coverage gaps, not qualified behavior. Canonical source identities were resolved through local+mirrors; no public remote-fetch acceptance is claimed.++Fresh review and regression coverage include capture-parent symlink retargeting: completion+re-resolves the lexical parent and refuses a changed destination before encoding or writing.+The two standalone packaging helpers now default to the same craft-fonts pin as release CI;+explicit font-directory overrides and existing checkouts retain their behavior.++This qualification uses source base `98702b5c446ce2791b0aab92dab65cf9da7220b7`.+Observed main `4ae3089420cb57d4c839e51a735d4f48271cbf17` adds a disjoint catalog security+fix. Integration must preserve it and pass the required gates before landing. Actual visible+UI, native platform/IME/PRIMARY, browser behavior, final release-package notices and paired+performance acceptance remain open. No branch push or PR publication is authorized.++## Historical plan and review revisions++Status: **Revision R3.2** — R3.1 plus the 2026-10-24 implementation-status amendments:+control-gesture delivery no longer re-checks the state snapshot after the gesture's own event has+applied (freshness is still checked before resolution and immediately before injection), every+dropdown now publishes a semantic accessible name, and the craft-libs reference moved to the local+`3832c47…` reconciliation base. The R3.1 concrete implementation notes for control-gesture+delivery, screenshot path identity, `ui.scroll` units/phases, the hidden-paint predicate and+disclosure `Expanded` state remain in force. R3 replaced+R2 (SHA-256 `385e46055494cc24b58e41ee08982c876eb423df314b0abffcdc28ac81cf9d24`) after the+independent review in `plan-reviews/lightcraft-v2.md`. Every review finding is resolved inline in the section+that owns it; §13 records each disposition, including the parts rejected. No production code,+manifest, lockfile, test, asset or build was changed and **no test, build, benchmark or GUI run was+performed for R3**: every source statement below is static inspection of the pinned trees. No+executed-validation, GPU-pass or browser-pass claim was made at that planning stage.++No push, pull request, release, tag, comment or other publication is authorized. Every future push+or new pull request needs explicit human approval of the exact content and the validation results+first.++This plan covers only `storytold/lightcraft` at+`23e181283cb448205d865e8cd288b56afe987986` (branch `codex/egui-037-plan-20261022` in the assigned+checkout). It does not migrate the egui fork, winit, craft-libs or a sibling app; those are separate+plans, separate review units and separate publication gates.++The root `AGENTS.md`/`CLAUDE.md` and the nested `docs/user/AGENTS.md`/`CLAUDE.md` were read. This+plan changes no user documentation, asset, contributor metadata or build artefact; the only file it+adds is this plan.++The historical diagnostics in+`/home/codex/work/ssd2/task-evidence/egui037-audit-20261022/{fork,stock}/lightcraft.errors` and+`lightcraft.log` are clues from an earlier checkout. They are not current source, not a build of this+checkout and not acceptance evidence. They show 17 library errors and 26 library-test errors plus+243 warnings from the fork trial; the source audit below found additional semantic changes (panel+IDs, capture correlation, dropped-file replay) that a compiler diagnostic cannot show.++## 1. Exact baseline and provenance++| Item | Revision or value |+|---|---|+| LightCraft source baseline | `23e181283cb448205d865e8cd288b56afe987986` (`Release 0.13.0`) |+| LightCraft lockfile | `Cargo.lock`, format version 4 |+| LightCraft Rust baseline | workspace `rust-version = "1.90"`; `lightcraft-ui-egui` declares `1.95`; inspection toolchain `rustc 1.99.0` |+| Current egui family | `egui`, `epaint`, `ecolor`, `emath`, `eframe`, `egui-wgpu`, `egui-winit`, `egui_glow`, `epaint_default_fonts`, `egui_kittest` all `0.36.2` |+| Current winit | `0.30.13` from crates.io, checksum `a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d` |+| Current accessibility/test stack | `accesskit 0.24.1`, `accesskit_consumer` 0.35/0.36/0.38, `kittest 0.4.0`, `egui_kittest 0.36.2` |+| craft-libs reconciliation base | `3832c47ef68a0e6214f2c1e85f3526b6adcb686e` | Current local shared-library tree and the base for the implemented port; it already carries PR 199's egui 0.37 API update, while the CL-2F capture helper remains uncommitted and is a publication gate. The exact reachable publish pin is still a central-publication gate |+| craft-libs historical inspection | `49190884278f16c9a9f5823d7698a8ffb5deb062`; PR 199 `8614e4a` + README `1764bca` | Earlier base and hunks; retained as history only. The port shape is already contained in the `3832c47…` base |+| Target upstream release | egui `0.37.0`, peeled commit `841a328ba2dd8f6996beb7189ebb7fc00e668a2a`; the annotated tag object SHA is not the commit SHA |+| Comparison-only egui tree | `aiongg/egui` `craft/0.37` at `a4f9a17f64a6bae61350fb85804c9df0d9865916` (E1–E21) |+| Comparison-only winit tree | `aiongg/winit` `craft/0.30.13-lang` at `8b35388bd719e8cc86a95971ba0bc026c9a8f058`; storytold base `ffae5198770d7730e718043f035a772b7dbc3b1b` |+| craft-libs stale trees | PR 199 head `b68de8c5f4f1c060904d211a7b1320aa0f7bce78` and audit merge `ec8840af8c5fda695cf195cdd05e5ae078415c07` | Evidence only, not mergeable trees: they omit current `craft-platform` and revert security/settings/docking/printer fixes |+| Language work | craft-libs issue/PR 198 is a separate proposal, not a merged dependency and not included here |++**Pin policy for this consumer.** `a4f9a17f` (egui) and `8b35388b` (winit) are *comparison and+inspection* references only. LightCraft must pin the final reviewed **storytold** egui and winit+revisions by immutable full SHA **once the fork and winit series are published**. Those revisions do+not exist yet, so this plan states no SHA for them and does not guess one. Every stage that needs+them is explicitly blocked (§9, §10). LightCraft's production dependency is the complete reviewed+and published storytold egui **P8** revision: E1–E21 plus **P2b** (E4 regular/PRIMARY with bounded+asynchronous W15P transfer completion), **P7** held-key release pairing, **P7b/E21b** outgoing IME+surrounding text, and **P7c** (the selected #8763/#8748 fixes and justified performance fixes). Its+companion is the complete published storytold winit revision with **W15P** and the **W27** IME+lifecycle. No stock 0.37 or intermediate fork stage is a production dependency; stock 0.37 is only+the measurement control. A published revision missing any of these is not acceptable for the stages+named below.++## 2. Dependency and entry-point inventory++All manifests in the checkout were inspected:++- root `Cargo.toml` (`[workspace]`, `[workspace.dependencies]`, `[workspace.lints]`, profiles);+- `apps/lightcraft/Cargo.toml`, `apps/lightcraft-cli/Cargo.toml`,+ `apps/lightcraft-web/Cargo.toml`;+- all 29 `crates/*/Cargo.toml` and `xtask/Cargo.toml`.++There is one workspace, one lockfile, no nested workspace, no Cargo `vendor/` directory and no+`[patch]` section today. `crates/raw/src/vendor/` is a set of in-tree raw-decoder modules (Sony,+Nikon, Canon, Fujifilm, …), not a Cargo vendor directory and not egui-related; it is preserved and+out of scope. There are no vendored egui/winit/egui-wgpu copies. `.cargo/config.toml` only defines+the `xtask` alias. `egui_extras` is declared in the workspace but unused and absent from the lock+graph; do not add it to production just to patch it. `egui_plot`, `egui_dock` and+`egui_inspection` are unused. `craft-ui` is the only shared UI dependency; `craft-docpath` is not+egui-related.++| Target | egui entry point | Notes |+|---|---|---|+| `lightcraft` (native) | `apps/lightcraft/src/main.rs:60` `impl eframe::App`; `logic` calls `LightCraftApp::logic`, `ui` calls `LightCraftApp::ui` | eframe features `default_fonts`, `wgpu`, `glow`, `accesskit`, `wayland`, `x11` today; native menu, GPU probe/fallback, control server (`MAX_CONNECTIONS = 16`, `MAX_LINE = 4 MiB`) |+| `lightcraft-web` | `apps/lightcraft-web/src/web.rs:652` `impl eframe::App for WebApp`; `start` at `:726` | eframe `default_fonts`, `glow`; browser-loaded Chinese face; workers; OPFS/IndexedDB; `command()` → `LightcraftApp::run`, **no control server** |+| `lightcraft-cli` | `apps/lightcraft-cli/src/main.rs`: `snapshot` at `:767`, `render`, `mcp` | headless `Headless`/`HeadlessView`; no eframe |+| `lightcraft-ui-egui` | `crates/ui-egui/src/lib.rs:1077` `LightCraftApp::logic`, `:1441` `LightCraftApp::ui`; `headless.rs:133` `HeadlessView::run`, `headless.rs:311` `Headless::step` | the UI crate and its integration tests |+| `crates/ui-egui/tests` | `accessibility.rs`, `docking_workflows.rs`, `shutdown.rs` | kittest harnesses and AccessKit assertions |+| examples | `drag_latency`, `grid_bench`, `open_timeline`, `thumb_request_bench` | existing UI/perf harnesses |++Platform-specific declarations that must stay coherent with the selected winit/egui:++- `apps/lightcraft` has direct `winit = "0.30"` with `x11` only on+ `cfg(all(unix, not(target_os = "macos")))`;+- `apps/lightcraft` has `rfd` only on non-wasm; `zbus` only on Linux; `muda`, `objc2`,+ `objc2-app-kit`, `objc2-foundation` only on macOS;+- `apps/lightcraft-web` puts eframe/egui/wasm-bindgen/web-sys under `cfg(target_arch = "wasm32")`;+- `lightcraft-ui-egui` has `rust-version = "1.95"` and dev-dependency `egui_kittest` with+ `wgpu` and `snapshot`.++### 2.1 Feature policy (explicit, per root)++egui 0.37 has **no default `default_fonts`** (`egui/Cargo.toml`: `default_fonts` off by default),+and 0.37 moved the monochrome emoji faces out of `default_fonts` into+`monochrome_emoji_fonts` (`epaint/src/text/font_definitions.rs:127-183` inserts+`NotoEmoji-Regular`/`emoji-icon-font` only under that cfg). eframe 0.37's default feature set+includes `clipboard`, and its `egui-winit` dependency is `default-features = false`, so an app that+turns eframe defaults off must add `clipboard` itself (`eframe/Cargo.toml:142-144`;+`egui-winit/Cargo.toml:44-46`, `clipboard.rs`).++| Root | Features after migration | Why |+|---|---|---|+| workspace `egui` | `default-features = false`, `features = ["default_fonts", "monochrome_emoji_fonts"]` | every resolution root needs the bundled faces: CLI snapshot, headless harnesses and unit tests never see eframe's features. Monochrome emoji are needed because user keywords/filenames carry emoji (`tests_keywording.rs:558-583` uses `🙂`) and 0.36's `default_fonts` supplied them. The workspace feature is what supplies LightCraft roots; `egui_kittest`'s own dev-dependency enables them only for upstream kittest's tests and does not propagate |+| `lightcraft` (native) | eframe: `default_fonts`, `clipboard`, `wgpu`, `glow`, `accesskit`, `wayland`, `x11`; egui: workspace `monochrome_emoji_fonts` | `clipboard` restores the real OS clipboard; without it egui-winit simulates an in-process clipboard and cut/copy/paste, `RequestPaste` and the E4/W15P Wayland path are unavailable |+| `lightcraft-web` | eframe: `default_fonts`, `glow`; egui: workspace `monochrome_emoji_fonts` | browser clipboard is not the egui-winit `clipboard` feature; the browser path is qualified separately |+| `lightcraft-cli`, `lightcraft-ui-egui` | inherit the workspace `egui` features | headless rendering and kittest must resolve the same faces |++`monochrome_emoji_fonts` adds roughly 1 MB to the binary (its own doc comment); the size impact is a+measured deliverable for both native and WASM (§7.2). Adding both faces must not weaken+`MissingGlyphPolicy`: production stays `Tofu`, kittest keeps its `Panic` default.++**kittest does not supply these faces.** Its normal `[dependencies] egui` uses the workspace entry+with `default-features = false`; only `egui_kittest`'s own `[dev-dependencies]` enables+`default_fonts`/`monochrome_emoji_fonts` (`egui_kittest/Cargo.toml:39-42,65-68`), and a dependency's+dev-dependencies do not propagate to consumers. LightCraft's workspace/root feature selection is+therefore what gives every CLI, headless and kittest root its faces; verify each produced graph with+`cargo tree -e features`, as §5.3 requires.++Current source/test gates (source-declared, not executed here): thousands of `#[test]` annotations;+`cargo xtask ci` runs fmt, clippy `--workspace --all-targets -D warnings`, the HEIF feature check,+`cargo test --workspace`, GPU probe/backends, `parity`, `layers`, `assets` and the wasm check+(`xtask/src/main.rs:295-366`). CI matrix files also cover FreeBSD (with craft-fonts), Nix, Windows+ARM64, packaging and release. `assets/ATTRIBUTION.md` matches every image, font, icon and media+path; migration screenshots stay in task evidence rather than the repository unless separately+approved and attributed.++## 3. What actually changes in 0.37 (and what does not)++The app already receives a root `egui::Ui` through `App::ui` and `Context::run_ui` on 0.36.2, and+`App::logic`/`App::ui` already exist in 0.36.2. Do not describe that split or root-Ui pass-through as+introduced by 0.37, and do not mechanically rewrite `update` into `ui` where no `update` exists.+`eframe 0.36.2` already calls `app.logic(ui.ctx())` before `app.ui(ui)` in each pass and calls+`run_logic` when hidden; the 0.37 source at `a4f9a17f` has the same shape (see §4.1). The real+incompatibilities and semantic risks are these. In the table, `egui/src/...` means+`crates/egui/src/...` in the egui checkout, and `egui_kittest/src/...` means+`crates/egui_kittest/src/...`; LightCraft paths remain repository-relative.++| Change | Effect in LightCraft | Source anchor |+|---|---|---|+| `WidgetType` replaced by `accesskit::Role` (`egui::Role`), alias deprecated | `WidgetInfo` constructors and tests must use roles; `CollapsingHeader` becomes `DisclosureTriangle`, `SelectableLabel` becomes `Button`, `Checkbox` becomes `CheckBox` | `egui/src/lib.rs` 0.37 role alias/table; PR #8555 |+| `Id::new` deprecated in favor of `Id::unique`; `AsIdSalt`/`IdSalt` are explicit | **221** `egui::Id::new` occurrences on 218 lines plus **three** bare `Id::new` calls (`menu_level.rs:19`, `canvas_keys.rs:15,20`, imported with `use egui::Id`) and **8** `Ui::id()` calls; the remaining `*Id::new` spellings are `LayerId`/`FontId`/`TextureId`, unrelated. `Id::new` and `Id::unique` hash identically, so persisted egui state does not reset | `egui/src/id.rs`; `egui/src/ui.rs:363-381`; PRs #8534/#8586/#8542 |+| `Panel` constructors take `impl AsIdSalt`; panel ID is `parent_ui.scope_id().with_salt(self.id_salt)`, and `Panel::new` stores `IdSalt::new(id_salt)` | This is a **semantic change** from 0.36's exact `Id`. Code that removes/reads `PanelState` must use the same parent-salted key, computed from the original salt source. Passing an already-built `IdSalt` to `Panel::left/right` hashes it **again** (`IdSalt::new(IdSalt)` is a distinct salt — the id_salt.rs unit test `debug_format_nested_salt` proves nesting is not identity) | `egui/src/containers/panel.rs:284-300, 974-975`; `egui/src/id_salt.rs`; PR #8592 |+| `default_fonts` is no longer an `egui`/`epaint` default; monochrome emoji moved behind `monochrome_emoji_fonts` | The CLI, headless harnesses and any graph without eframe's features lose the bundled faces and the monochrome emoji; `FontDefinitions::default()` becomes empty and the font-count test changes meaning | `egui/Cargo.toml`; `epaint/src/text/font_definitions.rs:127-183`; PR #8583; §2.1 |+| eframe `clipboard` is a separate feature | Turning eframe defaults off silently selects egui-winit's simulated clipboard | `eframe/Cargo.toml:142-144,168-170`; `egui-winit/src/clipboard.rs` |+| `ViewportCommand::Screenshot` takes a one-shot `ScreenshotCallback`; `UserData`/`Event::Screenshot` are gone | `issue_screenshots`/`collect_screenshots` move to the CL-2F completion slot; the callback runs on the renderer thread, is `Send + 'static`, and must not touch app state | `egui/src/data/screenshot_callback.rs`; `viewport.rs`; PR #8489 |+| `Event::MouseWheel` gains `source: MouseWheelSource` | Every initializer in `control.rs`, tests, examples and headless helpers needs a source; use `Unknown` for the control channel | `egui/src/data/input/event.rs:171-195`; `mouse_wheel_source.rs` |+| `scroll_area::State.offset` is private; `clamped_offset`/`unclamped_offset` are the API | `menu_level` reads `.offset` and writes `st.offset.y`; `right` reads `.offset`. Use `clamped_offset()` for reads and a next-frame scroll target for writes; no private-field workaround | `egui/src/containers/scroll_area.rs:100-148` |+| Kinetic scrolling/rubber-banding and `MouseWheelSource` are new | Menu/wheel/scroll behavior can differ; `ui.scroll` must carry a source; tests cover wheel vs trackpad/momentum and overscroll | `scroll_area.rs` 0.37 |+| `ComboBox` is `ComboBox<'a>`; `Atom::custom` takes `IdSalt`; `WidgetAtomResponse::rect` takes `IdSalt` | `widgets::combo_box` needs a named lifetime; `arrow_button` uses `IdSalt::new("arrow")` consistently | `containers/combo_box.rs:45-101`; `atomics/atom.rs:98`; `atomics/widget_atom.rs:228-240` |+| `Ui::id` renamed `scope_id`; `UiBuilder::id` renamed `scope_id` | Replace the 8 `ui.id()` uses; child UIs use `scope_id`; `id_salt` remains for local children | `ui.rs:363-381`; `ui_builder.rs:59-82` |+| `Role`/AccessKit tree and strict kittest checks | kittest 0.37 panics on an input widget with no accessible name and on a missing glyph; `HarnessBuilder` defaults are `missing_glyph_policy: Panic`, `check_accessibility: true`, and the check runs after every settle and before every snapshot | `egui_kittest/src/builder.rs:46-60`; `accessibility.rs:26-42`; PRs #8589/#8611 |+| TextEdit click-away selection regression in 0.37 | `text_field`'s custom Cut/Copy menu and toolbar actions that read the selection can see a collapsed range; keep the existing memo/store logic and add the #8763 regression | upstream #8763, open; PR #8764 open/unmerged |+| `Style` defaults are roomier, TextEdit layout changes | LightCraft pins spacing/button padding/corner radii in `theme::apply_kind`, but menus, tooltips, scrollbars and plain dialogs can shift; review geometry/pixels, never auto-refresh | PRs #8617/#8445; `theme.rs:397-448` |+| PRIMARY selection support | New middle-click paste and PRIMARY publishing; verify separately from the normal clipboard, through E4 + W15P | PR #8428; E4; #8657 |+| `egui_extras`/`egui_kittest` have independent version numbers | Do not infer versions from `egui`; `egui_plot` is unused | crate manifests at `0.37.0` |++Not a 0.37 migration item: `Context::root_ui`/`run_pass` (new in 0.37) are not needed by LightCraft's+`App::ui`, which already receives the root `Ui`. Never call `ctx.root_ui` from inside `run_ui`,+`App::ui` or `root_ui`; upstream #8535 documents the panic. Use the passed `&mut Ui`. Likewise, do+not claim `App::logic` is new or replace `App::ui` with a `Context` bridge.++## 4. Concrete source design++### 4.1 How the hosts actually call the app++Verified statically at `a4f9a17f` (and unchanged in shape from 0.36.2):++- **Native** (`eframe/src/native/epi_integration.rs`): `App::logic` and `App::ui` are both called+ **inside** the `Context::run_ui` closure, so both run **once per layout pass** (a discard can+ produce more than one). `raw_input_hook` is called once per host `update`, before `run_ui` (and+ before `run_logic` on a hidden logic-only update), not per pass.+- **Web** (`eframe/src/web/app_runner.rs`): the same — `logic` then `ui` inside the `run_ui`+ closure, per pass.+- **Headless** (`crates/ui-egui/src/headless.rs:320-325`): `Headless::step` calls+ `HeadlessView::run(raw, |ui| { app.logic(ui.ctx()); app.ui(ui) })`, which is+ `ctx.run_ui(raw, …)`; again per pass.+- **Hidden**: the integration calls `Context::run_logic`, which updates only window/focus state;+ events, input time and layout remain from the last UI pass.+- After a completed `run_ui`, `current_pass_index()` is **0** (`ContextImpl::end_pass` takes the+ output with `mem::take`; `run_dyn` restores the count only immediately before the next pass, and+ `run_logic` does not restore an old index). During a second pass it is 1, 2, ….+- `ViewportInfo::visible()` derives from minimized/occluded and is `None` when unknown. **A hidden+ window can still run a full UI pass**: `egui-winit`'s `ActionRequested::Screenshot` and+ `PaintWhileHidden` both report `wants_paint()`, and eframe treats that as `is_visible` for the+ pass (`wgpu_integration.rs:687-704`, `glow_integration.rs:680-693`). In that forced paint+ `visible()` still reports `Some(false)`.++Consequences: (a) `visible()` and fresh egui time are **not** a way to tell UI work from logic work;+(b) `current_pass_index() == 0` is a valid *known-UI-boundary* test for "first pass of this+`run_ui`", and it is also true during `run_logic`, so a hidden tick is never suppressed by it; (c) a+second pass has empty input events (`InputState::begin_pass` replaces events with `new.events`), so+event-driven code cannot run twice, while time/state-gated code can.++### 4.2 The tick contract (no `TickPhase`, no visibility classifier)++R1's `TickPhase { First, Later, Hidden }` and its time/visibility classification are **removed**.+They had no defined first-call, `visible() == None` or forced-hidden-paint branch, and their+stale-`current_pass_index` rationale was false. The replacement is a small, explicit split with a+monotonic clock and consumed queues:++```rust+impl LightcraftApp {+ /// Background/queue work. Called before layout on every host pass (native and web+ /// inside `run_ui`, headless in `Headless::step`) and from `Context::run_logic`+ /// while hidden. It may read `ctx.input(|i| i.viewport())` and `i.raw.focused` only+ /// (those `RawInput` fields are refreshed by `run_logic`; `i.focused` and `i.time`+ /// are not). Never events, dropped files or keys.+ pub fn logic(&mut self, ctx: &egui::Context) {+ i18n::set_language(self.ui.language);+ panels::library_problem::logic(self);+ panels::notices::logic(self);+ if ctx.input(|i| i.viewport().close_requested()) && !panels::notices::may_close(self) {+ ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);+ }+ let now = self.tick_now(); // monotonic; see 4.3+ self.drain_control(ctx); // control_rx.take() + try_recv: consumed once+ self.renderer.poll(ctx, &mut self.session);+ merge::poll(self, ctx);+ import::poll_scan(self, ctx);+ sync::poll(self, ctx);+ sync::poll_run(self, ctx);+ tasks::poll(self, ctx);+ import::tick(self, ctx, now); // time-gated; second pass is a no-op+ lightroom_import::tick(self, ctx, now);+ recheck::tick(self, now);+ self.slideshow_tick(ctx, now);+ self.auto_import(ctx, now);+ self.retry_sidecars(ctx, now);+ self.scan_devices(ctx, now);+ self.preview_build_status(ctx, now);+ self.save_status(ctx, now);+ self.pump_background_queues(ctx, now); // faces/denoise/model/focus worker results+ self.collect_captures(ctx); // completion slot: take once+ self.issue_captures(ctx, now); // admit/issue; deadlines use `now`+ self.session.persist_if_dirty();+ if !self.synthetic.is_empty() {+ ctx.request_repaint(); // visible gesture steps+ }+ if self.needs_paint_while_hidden(ctx) { // pending gesture, queued capture or settle+ ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaintWhileHidden);+ }+ }++ /// Input and once-per-layout-frame work: the known UI phase.+ fn ui_pass(&mut self, ui: &mut egui::Ui) {+ let ctx = ui.ctx().clone();+ if ctx.current_pass_index() == 0 {+ self.take_dropped_files(); // from the queue filled once by raw_input_hook+ self.pump_ui_input(&ctx); // the input-reading halves of faces/denoise+ self.update_perf(&ctx);+ }+ self.sync_theme(&ctx);+ self.apply_settings(&ctx);+ if self.fonts_ready {+ shortcuts::handle(self, &ctx); // fresh events only+ }+ self.check_external_editor(&ctx);+ self.resolve_pending_gestures(); // after this pass's layout, see 4.4/4.5+ }+}+```++Rules that the implementation and its tests must keep:++1. **One consumer per queue.** `drain_control` takes `control_rx` out, drains with `try_recv`,+ puts it back; replies are sent exactly once. The screenshot slot is `take`n once. Worker results+ carry a generation id and are applied once. There is no "run the queue again" path.+2. **`current_pass_index() == 0` guards once-per-host-frame work**: dropped-file consumption,+ input-reading halves (`pump_ui_input`) and perf update, and `import::tick`'s batch commit. A+ hidden `run_logic` also reports index 0, so the same gate lets import work advance on a hidden+ tick. It is *not* the gate for the other background timers: Lightroom import, slideshow,+ auto-import, sidecar retry, device scan, recheck, toasts and autosave live in `logic` behind+ monotonic deadlines. A wall-clock gate cannot substitute for the pass index: a discarded first+ pass that takes longer than the throttle would re-run it inside the same host frame. Where an+ operation needs "how many frames have actually run", use `Context::cumulative_frame_nr()` (one+ per `run_ui`), not the pass index and not `cumulative_pass_nr`.+3. **Input lives in the UI phase.** `shortcuts::handle`, dropped-file handling and the+ external-editor focus check move out of `logic_inner` into `ui_pass`. A hidden `run_logic` tick+ can no longer re-read the last pass's `dropped_files` (today it would spawn the same import+ again) and cannot consume a queued key.+4. **Only refreshed window state is safe in `logic`.** `run_logic` refreshes+ `RawInput::viewports`/`RawInput::focused` only; `InputState::focused`, `InputState::time` and+ events stay from the last pass. Read `i.viewport()`/`i.raw.focused` in `logic`, and `i.focused`/+ `i.time` only in the UI phase.+5. **No freshness inference from visibility.** `Some(false)` + a running `App::ui` is a normal forced+ paint (pending screenshot or `RequestPaintWhileHidden`); `None` is normal for headless and+ `RawInput::default()`. Visibility must not be used to tell UI work from logic work. It *is*+ used deliberately for user-facing pacing: a minimized/occluded (`Some(false)`) slideshow pauses+ instead of advancing and requesting full-size slide renders, and resumes with its remaining+ time on unhide (P2.5 in the post-port review).+6. **First call / first frame.** `tick_now` is initialised at construction and every timer is an+ `Option`/deadline comparison that is true on the first tick, so `Headless::step` at time `0.0`+ and `ctx.run_ui(RawInput::default(), …)` (whose input time is `prev + predicted_dt`, not 0) both+ run their first logic work. Add explicit tests for both, plus `visible() == None` and a forced+ hidden paint (§6.1).+7. **No `will_discard` prediction.** A later widget may request a discard after logic has already+ run; correctness comes from one-consumer queues and idempotent side effects, not from guessing.++### 4.3 Hidden-time accounting: one monotonic clock, painting stays egui time++`run_logic` leaves `ctx.input(i.time)` frozen, so any timer read from it in `logic` is stale.+Introduce an app clock and use it for everything that must progress while hidden:++```rust+/// Seconds since the app was constructed. Monotonic (`web_time::Instant`): never goes+/// backwards, even when the window is restored after hours hidden.+fn tick_now(&self) -> f64;+```++- Use `tick_now` for: `import::tick` (additionally gated by `current_pass_index() == 0` so a+ discarded pass cannot commit twice), `lightroom_import::tick`, `recheck`, slideshow playback+ (`panels/slideshow.rs:157-183`; auto-paused while `ViewportInfo::visible() == Some(false)`),+ auto-import (`lib.rs:1154-1187`), sidecar retry+ (`lib.rs:1190-1214`), device scan, screen-profile refresh (`lib.rs:1316-1322`),+ denoise/faces/focus/model timers, autosave/prefs cadence, capture settle/fallback/timeout+ deadlines, and **toast expiry**. Each stores a next deadline and advances it only when+ `now >= deadline`, so a second pass in the same host frame is a no-op.+- Toasts: store the deadline as a monotonic app-clock value; `save_status` (`lib.rs:785-808`),+ `preview_build_status` (`lib.rs:756-781`) and `panels::toast` (`panels/mod.rs:80`) read+ `tick_now`, not `ctx.input(i.time)`. A hidden toast then keeps its remaining time instead of+ expiring the instant the window is shown.+- Keep egui time for painting, animation, gestures and widget interaction (all of which only run in+ the UI phase).+- The web host's `safety::take_notices` (`apps/lightcraft-web/src/web.rs:654-656`) runs in `logic`+ and today uses `ctx.input(|i| i.time)`; give it the same monotonic deadline.+- `Headless` exposes its simulated time through the same clock (a test hook; the current+ `Headless::time` starts at `0.0`).++### 4.4 Duplicate-work inventory (narrowed)++The second pass has **empty events**, so `shortcuts::handle`, dropped-file handling and+`collect_screenshots`-style event scans cannot run twice from one gesture. The real duplicate+candidates are state/time-gated calls that `logic` runs on every pass (a monotonic deadline makes+the second pass in a host frame a no-op), and one call that is literally duplicated today:++- `panels::faces::pump` is called twice in one pass (`lib.rs:1139` and `:1228`);+- `import::tick`, `lightroom_import::tick`, slideshow timers, auto-import, sidecar retry, device+ scan, recheck and the toast/status updates are time-gated, so a slow second pass could fire them+ again;+- `WebApp::run_inbox` and `load_originals` drain queues on every call (correct — they are consumed+ queues), while `import_dropped` re-reads `raw.dropped_files` on every call and must not run in a+ hidden tick or a later pass; it moves to the UI phase and consumes an app queue filled once in+ `raw_input_hook`.+- `panels::denoise::pump` (`denoise.rs:45-52`) and `panels::faces::pump` (`faces.rs:705-712`)+ read `ctx.input` keys/pointer/`i.time` to pace background work. Split each into+ `pump_background` (download/index worker results, monotonic deadlines — safe in `logic`, including+ hidden) and `pump_ui_input` (fresh key/pointer activity and its timestamp — UI phase only). A+ hidden tick must never pace work from the previous pass's pointer state.+- `WebApp::save` stays guarded by its own `last_save` deadline, now on the monotonic clock.++There is no evidence that event-driven handlers need multi-pass guards, so do not add them.++### 4.5 Control gestures while hidden (geometry, paint requests, one reply)++Today `ui.clickWidget`/`ui.dragWidget`/`ui.hoverWidget` read `app.widgets` from the previous pass,+`ui.pointer` maps through the previous `app.image_rect`, and `raw_input_hook` injects one pointer+event (or one up-to-release key run) per host frame. A hidden request can therefore click stale+geometry, and a multi-event gesture can stall after one `RequestPaintWhileHidden`.++New contract:++- **Geometry is resolved only after a fresh layout.** Control requests that need geometry are+ admitted into a `pending_gestures` list with their original params and `admitted_epoch =+ layout_epoch`; `layout_epoch` (a monotonic counter, not a hash) is incremented at the **end** of+ every completed `App::ui` pass. A request resolves, using that pass's `app.widgets`/+ `app.image_rect`, at the end of the first pass where `layout_epoch > admitted_epoch`. If no UI+ pass has happened since admission, the request stays pending and the app sends `ViewportCommand::RequestPaintWhileHidden` (when+ `ctx.input(|i| i.viewport().visible()) != Some(true)`) so the next host iteration paints.+ If the session has never laid out a UI, reply with an explicit "no current UI frame" error at the+ deadline instead of inventing geometry.+- **One unapplied step survives repeated hidden ticks.** `raw_input_hook` is called before+ `run_ui` and before `run_logic` (`epi_integration.rs:338-365,413-430`), so a hidden logic-only tick+ can invoke it. The hook injects at most one queued gesture step and marks it in flight; it must+ not inject another step until a completed UI pass (tracked by a UI-pass counter incremented at the+ end of `ui_pass`, never by `visible()`) has consumed that step. The step remains in eframe's+ `pending_raw_input` across hidden ticks unchanged. This prevents two hidden ticks from batching a+ press and release into one later pass, and preserves key-press-through-release semantics.+- **Each gesture step keeps painting.** While `synthetic` is non-empty (a drag has many moves; a+ click is move+down+up) the app sends `RequestPaintWhileHidden` again after each step is consumed,+ so hidden gestures complete instead of waiting for the user. The hook still injects only one+ pointer move or one key sequence per host update.+- **Exactly one reply, after delivery.** The reply is deferred until the gesture's final synthetic+ event has been injected into a UI pass (a `pending_gesture.delivered` flag set at the end of that+ pass), or until the monotonic deadline, when it replies with an error. A dropped sender gets no+ reply; a canceled/closed request is removed before replying. This makes a successful reply mean+ "the UI saw the gesture", not "events were queued".+- `ui.key`, `ui.text` and `ui.scroll` need no geometry but do need a UI pass to be consumed+ (`ctx.request_repaint()` alone only runs `run_logic` while hidden), so they follow the same+ request-paint/one-reply pattern.+- `ui.screenshot` is **not** a gesture, but it has two phases. Once the+ `ViewportCommand::Screenshot` is processed, `ActionRequested::Screenshot::wants_paint()` makes the+ integration paint a hidden window. A capture that is merely queued or settling in `logic` has not+ reached that phase: while hidden it needs `RequestPaintWhileHidden` from `logic` (the same+ predicate as pending gestures) to reach a UI pass that issues the command. Test both the+ issued-command forced paint and the queued/settling hidden case; do not expect a missing+ issued-command paint to fail.++**Implementation amendment (2026-10-24, before code).** The app owns the queue described above:++- `layout_epoch` is a `u64` incremented once at the end of every **completed, nondiscarded**+ `App::ui` pass (the same place `ui_passes` advances). `PendingGesture` records `admitted_epoch`,+ an admission-time `GestureFrame` (view, active photo, library generation, dialog discriminant,+ left/right/presets/filmstrip switches), a monotonic `deadline_ms`, the original method and params,+ its reply sender, and the computed result once resolved. At most 32 may be pending; a 33rd is+ refused by a normal control error. The deadline is 5 s from admission (`GESTURE_TIMEOUT_MS`).+- `ui.clickWidget`, `ui.dragWidget`, `ui.hoverWidget`, `ui.pointer`, `ui.move`, `ui.click`,+ `ui.drag`, `ui.key`, `ui.text`, `ui.scroll`, `ui.zoom` and `ui.clipboard` are queued. Their+ existing parsing/event construction moves to one `control::gesture_events(&mut app, ctx, method,+ params)` function, called **only after** a completed layout newer than admission. Widget ids and+ `app.image_rect` therefore always come from that fresh pass, never the previous registry. A+ widget that no longer exists, a missing image rect, an invalid key/unit/phase or a removed text+ focus answers once with the existing error, after that fresh pass (not at admission).+- Resolution happens in `finish_ui_pass` after `layout_epoch += 1`. Before computing geometry the+ request's `GestureFrame` must still equal the current frame. A view, active-document, library,+ dialog or panel-layout change between admission and resolution cancels the request with one+ error instead of retargeting the new UI. The per-frame `layout_epoch` advance that makes the+ layout fresh is expected and is not itself a cancellation. A request that never sees a completed+ UI pass (hidden with no paint) answers `no completed UI frame` at its deadline.+- Resolution appends the gesture's synthetic events and marks the request resolved. It is **not**+ answered yet. The reply is sent when `app.synthetic` is empty after a completed nondiscarded pass+ (for a zero-event action such as a clipboard paste request, after the next completed pass), so+ `{"ok": true}` means the UI consumed the last event. A hidden run keeps sending+ `RequestPaintWhileHidden` while any gesture is unresolved or resolved-but-undelivered; a visible+ run keeps `request_repaint`.+- The queue is fail-closed on timeout: the request is removed, its reply error is sent once, and+ queued synthetic input is cleared so a late event cannot click after an error. This can discard+ another queued gesture's still-undelivered events; those requests are answered with their own+ timeout/cancel error rather than being retargeted. The queue is intentionally not a general+ scheduler: immediate commands (`engine.execute`, `ui.set`, `ui.inspect`, `ui.resize`,+ `ui.zoomFactor`, screenshot admission) keep their current direct semantics.+- Limit: the `GestureFrame` cancellation covers the navigation/modal/panel state that can change the+ meaning of an automation id. It cannot prove that a widget with the same id kept the same+ semantic target across an arbitrary catalog refresh inside the same frame; the fresh layout and+ the explicit view/document snapshot are the contract, not a per-widget identity guarantee.++### 4.6 Screenshot capture: the shared CL-2F weak completion slot++Anchors: `crates/ui-egui/src/lib.rs:909-987` (`drain_control`, `issue_screenshots`),+`:1034-1057` (`collect_screenshots`), `:1502-1525` (`PendingShot`), `control.rs:432-439`,+`headless.rs:133-174` and `:310-349`.++craft-libs selects one narrow completion-slot helper (`crates/ui/src/capture.rs`, CL-2) after the+DesignCraft and GridCraft adapters, then freezes the public API (CL-2F). LightCraft is one of the+craft-ui capture consumers and **adopts that helper** rather than keeping the local+`mpsc::Receiver`/token design; names and signatures come from the reviewed CL-2F revision, not from+this document. Every creative capture consumer adopts the CL-2F completion contract:+`craft-ui-consumers-exact.json` shows eleven apps whose TOML declares `craft-ui` (LightCraft among+them). All eleven require craft-libs **CL-1** and the frozen **CL-2F** API in the same atomic+dependency stage as egui/winit; only DesignCraft/GridCraft pilot the provisional CL-2 API, and their+adapters land before CL-2F freezes it. DeckCraft, FigCraft and ArtCraft Native use+contract-compatible local adapters without adding the crate, and all fourteen capture consumers+remain in scope. (The earlier "thirteen craft-ui consumers" wording was wrong; it is not repeated+here.)++LightCraft's adapter (app-owned policy, shared completion transport):++- **One record per admitted request**, owned by the app: monotonic request id, path, reply sender,+ `headless`, admission/deadlines (settle ≥3 painted frames and ≥120 ms; compositor fallback 2 s;+ hard timeout after admission), frames waited, reserved bytes, and a snapshot of capture-time+ geometry (`content_rect`, `viewport_pixels`, `pixels_per_point`, UI zoom). "Frames" means host+ frames (`Context::cumulative_frame_nr()`, incremented once per `run_ui`), not passes, so a+ multipass frame counts once and does not make a screenshot fire early. Take the geometry from the+ refreshed viewport information (`i.viewport().inner_rect`, `native_pixels_per_point`) when present,+ otherwise from the last laid-out content rect; a hidden window has no new layout, so both are the+ last known size, and the reserved bytes are revalidated against the returned image.+- **Issue** with a callback holding **only** a `Weak` reference to the app-owned completion slot;+ the app owns the strong slot and a live, owner-specific completion waker. The callback receives+ pixels only: no `Context` clone, no `&mut LightCraftApp`, no encoding, file I/O or command+ execution. On completion it locks the slot, stores the image, unlocks, and only then invokes the+ waker; it never wakes itself from inside the lock or re-enters the app. A late or canceled+ callback finds no upgradable slot and is a no-op. The renderer owns the callback until it fires,+ so this is not a `Context` reference cycle; `Weak` lets cancel/close drop the app state and makes+ a late result harmless. A pending capture keeps `request_repaint_after(16 ms)`, which also runs+ `run_logic` on a hidden native window, so the woken poll collects completion while hidden.+- **Completion**: take the slot once, release the byte reservation with a checked subtraction, and+ bind the image to the **issuance** UI geometry, DPI and zoom epoch. Any change to logical viewport+ size, surface pixels, `pixels_per_point` or UI zoom between issue and save cancels and retries (or+ replies with an error at the deadline) — even if the geometry changes back to the original values+ before the image arrives. Never combine old pixels with new geometry, and never accept an image+ merely because its dimensions happen to match. Reject an image larger than the reservation and+ release its bytes, then encode/write on the UI thread and reply exactly once. Derive the effective+ scale from the returned image dimensions and the recorded logical viewport (E2 surface fitting can+ shrink the image); record that with the result. Additive result fields (`scale`, `viewport`) are+ optional and backward compatible.+- **Admission is bounded before issue** using the shared capture defaults: at most **4**+ outstanding requests, at most **128 MiB** per image, and at most **256 MiB** aggregate reserved+ in-flight/completed bytes. App-specific caps may be stricter, never looser. Require+ `0 < width,height <= max_texture_side` (16 384 at inspection), compute the reservation with+ checked `width * height * 4` before issuing, and revalidate it after any geometry/DPI/zoom change+ before issue. Reserve the **worst surface the request can produce** — the full logical viewport ×+ `pixels_per_point` × UI zoom × 4 bytes — not the smaller E2-fitted size, and keep+ completed-but-not-yet-drained images counted until they are taken (in-flight and completed bytes+ are both checked before issue). The renderer's own readback allocation is accounted separately in+ peak RSS; a post-callback size check alone does not bound peak memory.+- **Cancel/close/drop/timeout**: remove the record first; the late callback's `upgrade()` fails and+ the image is dropped with no second reply and no panic. On shutdown all reservations return to+ zero. Tests assert retained bytes reach zero after drain/cancel.++**Implementation amendment (2026-10-24, before code): path identity at write time.** Admission pins+the destination as a `WriteTarget` owned by the app record:+`WriteTargetState::Absent` (the directory entry did not exist) or `Existing(FileIdentity)` (device+and inode on Unix; canonical path, length and creation time on Windows, whose volume/file-index+metadata is still unstable; canonical/len/mtime elsewhere; taken from `symlink_metadata` so a link+replacement is a different entry). Admission+still runs the library `OriginalGuard`. Immediately before encoding/writing, **both** the renderer+callback completion and the CPU/headless fallback call `revalidate_write_target`:+- an `Absent` target must still be absent; a file created after admission (ordinary file, imported+ original, hard link or symlink) is refused, never replaced;+- an `Existing` target must still be the same directory entry and must pass `OriginalGuard` again+ against the current catalog, so a photo imported at that path while the capture was queued is+ refused;+- an existing allowed screenshot destination keeps its normal overwrite behavior.+An absent destination is written through the new host `write_new` service+(`lightcraft_engine::export::write_file_new` → `safe_file::write_new`): it prepares a complete temp+file and publishes it with `create_new`/hard-link semantics, so the final TOCTOU window cannot+replace a file that appeared. The bounded temp file is encoded bytes only. An existing destination+uses the existing atomic writer after revalidation. Failure to configure `write_new` for an absent+target is an explicit error (fail closed), not a fallback to the destructive writer. Limits: an+existing destination can still be swapped by another process in the instant between revalidation+and the atomic rename; closing that would require an OS conditional-replace primitive. The lexical parent is now re-resolved before completion and compared with its admitted+canonical parent; a retargeted directory symlink is refused. The deterministic tests cover an absent+path that becomes an ordinary file, an absent path that becomes a catalogued original through a+hard link, an existing original/symlink refused at admission, an existing allowed overwrite, and an+existing target replaced by a new entry while queued, and a parent symlink retargeted between+admission and completion (neither destination receives a screenshot).+- **Both headless entry points change**: `HeadlessView::run` retains `ViewportCommand::Screenshot`+ callbacks and calls `callback.complete(Arc::new(self.paint()))` after the pass; `Headless::step`+ deletes its `ViewportCommand::Screenshot(user_data)` arm (it no longer compiles in 0.37) and no+ longer pushes `Event::Screenshot`. Completion happens exactly once, in the headless host.+- `headless_host` remains the CLI/headless flag; `WebApp` does not set it, and the web path has no+ control server (§4.11, §8).+- Boundary: the shared piece is only the completion slot. Request ids, paths, settle delays,+ deadlines, reply schema and `Services.write/png` stay LightCraft policy in+ `lightcraft-ui-egui`; do not grow a generic screenshot framework in craft-ui for LightCraft.++### 4.7 Panels, IDs and docking++Anchors: `crates/ui-egui/src/panels/mod.rs:52-77` (`resizable_side`),+`panels/bottombar.rs:24,371`, `panels/strip.rs:19`, `panels/topbar.rs:57`,+`panels/library_problem.rs:169`, `crates/ui-egui/src/docking.rs:430`, `shortcuts.rs:339`.++`resizable_side` must pass the **original salt source** to the panel and derive the persisted key+from the same parent scope:++```rust+// `Panel::new` stores `IdSalt::new(id)`; `Panel::id` is `parent_ui.scope_id().with_salt(store)`.+// `Id::with(salt)` is exactly `with_salt(IdSalt::new(salt))`, so this is the panel's real key.+let pid = ui.scope_id().with_salt(egui::IdSalt::new(id));+ui.ctx().data_mut(|d| d.remove::<egui::containers::panel::PanelState>(pid));+let panel = if left { egui::Panel::left(id) } else { egui::Panel::right(id) };+// ... show ...+if !ui.ctx().is_being_dragged(pid.with("__resize")) {+ return None;+}+```++Why this exact form: `Panel::left(salt)` with an already-built `IdSalt` would store+`IdSalt::new(salt)` and derive `parent.scope_id().with_salt(IdSalt::new(salt))`, which is not the+`pid` above. The `resize_widget_id` is `panel_id.with("__resize")`, so the drag check matches only+when `pid` is the panel's real key. Do **not** add a public `panel_state_id()`-style method to+production code: the mapping is a local detail, and a public helper would invite callers to use a key+that the panel never stores. Tests derive the key themselves from the same `parent_ui.scope_id()` and+salt, or assert on the returned response rect and the `panel:*` widget registration.++Scope of the risk, honestly: at this revision `resizable_side` has **no production caller** (the+shipped side panels are craft-ui `DockArea` panels and the `Panel::top/bottom/right` bars). The bug+is latent, not user-visible today; fix it anyway, and keep the mutation test so a future caller+cannot reintroduce it. The `bottombar` fixture currently reads+`PanelState::load(&ctx, Id::new("bottom_bar"))` (`bottombar.rs:371`); under 0.37 the key is+`ctx.viewport_id().root_ui_id().with_salt(IdSalt::new("bottom_bar"))` in that harness (the fixture+shows the panel in the root `Ui`), or read the response rect instead. Audit every+`Panel::top/bottom/left/right` id whose value is persisted or queried; fixed-size bars can keep+string salts, but tests must not assume the old exact key.++The first compatibility PR also migrates the old panel state explicitly: 0.36 stored+`PanelState` under the exact `Id`, 0.37 stores it under the parent-salted key, so old entries are+unreachable. Do not try to read them: at start, remove the legacy exact-`Id` `PanelState` entries for+the known panel salts (`top_bar`, `bottom_bar`, `tool_strip`, `library-problem-banner` and any+`resizable_side` caller) with `data_mut(|d| d.remove::<PanelState>(legacy_id))`, document the one-time+panel-width/layout reset in the stage notes, and assert in a test that the new keys are used. No+user-visible document, workspace JSON, catalog or XMP data is migrated; this is egui memory only.++Second window: it already uses `ctx.show_viewport_immediate`, and `CentralPanel::show` takes+`&mut Ui` in both 0.36.2 and 0.37, so this is not a 0.37 rewrite. Verify under 0.37 that embedded and+native callbacks both register `view:secondWindow`, render the active photo and close correctly.+`#8748` (running an overdue window's UI without painting so deferred children open/close while the+root is hidden) is closed upstream but **not present** in the inspected fork source (no+`PassMode::Overdue`): P7c in the required P8 revision owns the selected fix. The second window while+the root is hidden/minimized remains an explicit real-platform test, not an assumed fix. Do not call+`root_ui` from the viewport callback.++Docking stays `craft_ui::docking::DockArea`. LightCraft is an LTR application and must state that+policy explicitly at both call sites (`docking.rs:430`, `shortcuts.rs:339`) with the reviewed+`DockArea::direction(DockDirection::LeftToRight)` builder from craft-libs §7.7 (exact name from the+reviewed revision). Defaults must not be relied on. Persisted split first/second, axes, ratios,+floating rectangles and logical tab order must be unchanged, and painting, clipping, hit testing,+AccessKit order and drag insertion must use the same rectangles. `UiState.docking` format is not+migrated; verify save/reopen and `ui.dock` behavior in `tests/docking_workflows.rs`, plus that LTR+geometry is byte-identical to the current behavior.++### 4.8 Fonts, language, accessibility++Anchors: `crates/ui-egui/src/theme.rs:260-332` (`install_fonts_with_chinese`,+`font_definitions_with_chinese`), `i18n.rs:218-223`, `text_field.rs:180-235`,+`widgets.rs:1004-1020`, `tests/accessibility.rs`, `tests_keywording.rs:558-583`.++- Enable `default_fonts` **and** `monochrome_emoji_fonts` on the workspace `egui` dependency, and+ keep eframe defaults off in both apps while adding native `clipboard` (§2.1). This is a LightCraft+ root/workspace decision, not inherited from kittest: kittest's normal `egui` dependency is+ `default-features = false`, and only its own private dev-dependencies enable the fonts, which do+ not propagate. Verify every root (native, CLI/headless, kittest, wasm) resolves them through+ `cargo tree -e features`/`cargo metadata`, not through the lockfile (§5.3); a consumer test root+ without the workspace features would otherwise see an empty `FontDefinitions::default()`.+- Tests: assert `FontDefinitions::default()` contains `Hack`, `Ubuntu-Light`, `egui-icons`,+ `NotoEmoji-Regular` and `emoji-icon-font` (`epaint/src/text/font_definitions.rs:128-159`; the+ family key is `Ubuntu-Light`, not `Ubuntu`); assert U+1F642 `🙂` and U+1F44D `👍` are paintable in+ the Proportional family and that an emoji keyword/filename renders without tofu; keep the existing+ font-count relation (`theme.rs:700-705` compares against `FontDefinitions::default()`, so adding+ the two default emoji faces keeps the relation valid — re-check, do not silently update).+- Font fixtures for measurement/edge cases come from the egui plan §10.6 pins: craft-fonts+ `2481a8a324b986a45954e90045ed1f8f2efaaf3c` (Arabic/Thai/CJK SC/Japanese, manifest-recorded+ SHA256 + OFL) and the test-only Hebrew variable font and Noto Color Emoji v2.047 with their+ recorded SHA256 and licences. Fetch them into the task's fixture directory; **copy no font file+ into this repository** and do not add them to `assets/ATTRIBUTION.md` (nothing new is committed).+ `CRAFT_FONTS_DIR` stays the app's font input; a future bundled font belongs in craft-fonts.+- Keep `egui_system_font_provider`/`system_fonts` off unless a separate measured decision adopts the+ startup/coverage trade-off: the product policy is bundled Inter + craft-fonts and must stay+ deterministic. #8512's startup cost is a separate workload if that decision is revisited.+- Production `MissingGlyphPolicy` stays `Tofu`; kittest keeps `Panic` (`HarnessBuilder` defaults in+ 0.37 are `missing_glyph_policy: Panic`, `check_accessibility: true`). **All** existing harnesses+ are therefore strict from the first green compatibility stage: every unnamed input and every+ missing glyph must be fixed (names via `Response::labelled_by`/`accessible_name`/+ `ui.label_inputs_by`, real fallback faces), never by disabling the check globally. A deliberate+ tofu/unnamed probe opts out locally in that test only.+- Wire the fork's `Context::set_language` (`context.rs:2629`) from `i18n::language()` on start and+ when it changes, so the AccessKit root language and bidi runs follow the locale. Command ids,+ catalog data and user strings stay logical; this is presentation only. The in-process i18n+ remains the source of truth. Do not import craft-libs #198 or any font asset.+- Keep `TextField`'s custom menu and selection memo; add the #8763 click-away regression (§6.3).++### 4.9 Text input, IME, RTL, clipboard and PRIMARY++- `Event::MouseWheel` initializers in `control.rs`, `headless.rs`, examples and tests get+ `source: egui::MouseWheelSource::Unknown`; `ui.scroll` accepts optional+ `"source": "unknown"|"wheel"|"trackpad"|"momentum"`, `"unit": "point"|"line"|"page"` and+ `"phase": "start"|"move"|"end"|"cancel"`. Omitted values keep the pre-0.37 request meaning:+ `Unknown`, `Point`, `Move`. Every value is validated before an event is queued; an invalid value+ is a control error and changes nothing. This lets tests drive the grid/filmstrip+ `MouseWheelUnit::Line` path and trackpad/momentum `TouchPhase::Start`/`End` cycles, which the+ point/move-only API could not represent. `docs/control-protocol.md` documents the three optional+ keys. Unit tests assert wheel/line/start, trackpad/point/end and the backward-compatible omitted+ defaults.+- `raw_input_hook` keeps the §4.5 one-step-per-UI-pass contract; a logic-only tick must not drain+ another step. `Event::PasteImage` and `MiddleClickPaste` are not app shortcuts — `keymap.rs`'s+ recorder ignores them.+- **E21b/P7b is a new blocking prerequisite, not existing E21 behaviour.** Candidate egui-winit+ never calls `WindowExtWayland::set_ime_surrounding_text`, and `egui::IMEOutput` carries no logical+ text. The complete shared contract is in egui plan P7b and `ime-surrounding-gap.md`; LightCraft+ must take all of it, not a weaker subset:+ - owner/context-generation identity is present even when surrounding text is **Unavailable**. An+ available **empty** document is distinct from unavailable and is sent explicitly as an empty+ payload, not omitted;+ - changing owner or available/unavailable support clears the cached text and commits the+ protocol's disable/enable boundary (not merely empty text); same-owner ordinary updates preserve+ composition; the old preedit is canceled, not inserted into the new editor; there is no+ cross-window bleed;+ - the final completed pass's descriptor, including an authoritative `None`, is what+ `PlatformOutput::append` uses (replace `ime.or(self.ime)`); descriptor, owner and payload are+ one atomic value;+ - focus epochs and protocol serials are tracked separately: a current-epoch `done` with a+ mismatched serial applies incoming edits **once** and defers outgoing state until a matching+ serial; an obsolete owner/epoch invalidates its pending batch. Never drop valid incoming edits;+ - the payload is bounded (≤4000 UTF-8 bytes, valid boundaries, preedit excluded, byte+ cursor/anchor, explicit unavailable when a selection cannot fit) and the **new** payload path+ allocates no full-document clone. Existing `TextEdit` change-detection/undo clones are a+ separately measured baseline, not rewritten here;+ - built-in `TextEdit` produces the payload after delete/commit/cursor updates (logical model+ text, preedit removed, byte indices remapped) and the Wayland adapter sends it through W27.+ LightCraft has no custom `IMEOutput` producer: its `TextField` wraps the built-in `TextEdit` and+ other panels use `TextEdit` directly, so it **inherits** the producer and must test the inherited+ behaviour. The family's custom editors (FilmCraft `panels/graphics.rs` and the others in+ `ime-surrounding-gap.md`) need real logical-model/preedit/UTF-8-index adapters before family+ acceptance; `None` placeholders are not a completed port.+- IME tests: outgoing surrounding text immediately after deletion-only and delete+commit batches;+ preedit excluded; reversed selection; supplementary/combining/RTL text; cursor movement; a very+ long line and an over-limit selection (explicit unavailable, not a truncated claim); available+ empty vs unavailable; field and two-window switches; owner transition with committed+ disable/enable; password/no-IME clears; focus loss/reset/late serial; a current-epoch serial+ mismatch applying incoming edits once while outgoing waits, and a stale-epoch batch discarded;+ multi-pass final output including authoritative `None`. One native Wayland+ Vietnamese/predictive trace checks the outgoing protocol plus editor text and one undo+ transaction.+- Bidi: a mixed Arabic/Hebrew + Latin filename and keyword stays logical in catalog/XMP while+ painted text/caret/selection follow visual order, with no double bidi and no tofu when the+ craft-fonts face is present. The UI stays LTR; do not enable `Style::right_to_left`.+- Clipboard: native `clipboard` feature (§2.1), normal cut/copy/paste through `ui.clipboard`, the+ text-field menu, and PRIMARY middle-click. E4 and **W15P** are one compatibility unit: the+ inspected E4 uses an arboard fallback and does not provide the required winit-owned per-seat+ PRIMARY path. Require the complete P8/W15P revision: PRIMARY has its own protocol object on the+ existing connection/event queue (SCTK 0.19.2 `PrimarySelectionManagerState`/device/source/offer;+ never a second regular `wl_data_device`), and accepts a fresh trigger serial from **either a+ pointer press or keyboard focus** on the focused seat — do not impose a keyboard-only rule.+ Selection claims are synchronous while the trigger serial is fresh; serving and transfer are+ asynchronous. P2b replaces blocking reads/writes on the egui event path with caller-owned bounded+ async transfer handles: a total **2 s** deadline (not a per-`WouldBlock` poll timeout), a+ **16 MiB** byte cap, at most **four** read workers and **two** writer workers with queue depth+ **8**, an owner-specific live completion waker, and cancellation/discard of stale results when+ focus, target, owner or input generation changes. Test on wlroots/KWin/Mutter: keyboard- and+ pointer-triggered selection with valid per-seat serials, middle-click paste, password exclusion,+ no reclaim of an unchanged selection, owner/seat change, empty/absent offer, self-paste, slow+ trickle, oversized offer, cancellation, and UI event-loop responsiveness during a slow transfer.+ A compositor limitation is recorded, not papered over with a control-channel substitute.++### 4.10 GPU and renderer behavior++Anchors: `apps/lightcraft/src/window_gpu.rs:104-200` (`choose`, `base_options`, `probe`),+`main.rs:917-940`, `crates/ui-egui/src/softpaint.rs`, `crates/ui-egui/src/render.rs`.++- Keep the Windows probe/fallback design: DX12 → Vulkan → GL → glow, with error scopes and a+ non-panicking wgpu error handler. `Renderer::new(device, format, RendererOptions)` is unchanged in+ the inspected source; re-run the probe tests and the Windows startup matrix.+- E2/E3 (surface fit and configure/renderer error scopes) are required for very large or+ multi-monitor surfaces; test a window larger than the device limit via+ `LIGHTCRAFT_GPU_LIMITS=webgpu` and the fork's unit tests. A surface failure must be a typed error+ and the next renderer/CPU fallback, never a panic.+- #8736 (DX12 FXC shader-compile cost) is measured as its **own** workload: the probe's pipeline+ construction and eframe's first frame separately, fresh processes. A clamp-only shader change is+ not a valid fix (it changes Repeat/MirroredRepeat semantics); evaluate the upstream/float-`select`+ or pipeline-constant design with equivalent wrap tests.+- #8731 (plain-text tessellation) is its **own** workload: a text-heavy fixture (grid metadata,+ menu labels, panel rows) with mixed color-glyph rows, baseline/stock-0.37/fork. Do not cache or+ alter texture wrap/filter semantics to hide it.+- Photo textures remain `TextureOptions::LINEAR`; `softpaint`'s CPU mirror preserves nearest vs+ linear per `ImageDelta` and texture wrap. kittest uses `RendererOptions::PREDICTABLE`; check+ #8441's nearest-filter fix did not change preview/texture semantics.+- On DPI/zoom/resize, verify textures are updated/freed, the screenshot size contract stays+ `viewport_pixels`/`resized_viewport`, and the softpaint shadow context uses the same UI zoom.++### 4.11 Host adapters and persistence++- Native `App::logic` becomes `self.0.logic(ctx);` then the native menu and `PrefsWriter::tick`+ (both on the monotonic clock). `App::ui` stays one `self.0.ui(ui)`. Do not call `self.0.logic`+ again from `ui`. `PrefsWriter::tick` must not record `Seen::of` window geometry from a hidden+ `run_logic` pass whose `content_rect` is stale: keep the last known placement.+- Web `WebApp::logic`: `safety::take_notices` (monotonic), `run_inbox` (every call: consumed queue),+ `load_originals` (every call: drains a queue), the worker budget, then `self.app.logic(ctx)`, then+ `save` (own monotonic deadline), then the bench step (UI phase). `WebApp::ui` remains one+ `self.app.ui(ui)` plus the first-frame log. `import_dropped` moves into the UI phase and consumes+ the queue filled once by `WebApp::raw_input_hook`, so neither a later pass nor a hidden tick can+ re-import the same drop.+- Keep `raw_input_hook` once per host frame; it takes synthetic events and dropped files into+ app-owned queues, and the in-flight step gate in §4.5 prevents repeated logic-only ticks from+ draining more than one synthetic step. Do not move injection into `ui`, where it would repeat on multipass.+- Keep `PrefsWriter` and `UiState` JSON unchanged. The only visible ID change is egui memory/panel+ layout; `UiState` docking, settings, recent libraries, keymap and library catalog formats are not+ migrated. Test edit → save → close → reopen and undo semantics with the existing library tests.++## 5. Dependency graph, pin and lockfile acceptance++### 5.1 Intended graph++```text+lightcraft / lightcraft-web / lightcraft-cli / lightcraft-ui-egui+ -> egui 0.37.0 (published storytold revision, immutable SHA)+ + epaint, epaint_default_fonts, ecolor, emath+ -> eframe 0.37.0, egui-winit, egui-wgpu, egui_glow+ -> egui_kittest 0.37.0 (dev) -> kittest 0.5.0 (registry), accesskit 0.25.x+ -> winit 0.30.13 (published storytold revision, immutable SHA)+ -> craft-ui from the reviewed craft-libs revision (stock-egui-0.37 source compatible, CL-2F)+```++An incompatible `craft-ui` bump in any consumer is part of the same atomic dependency stage as the+egui/winit graph; never a separate version step that leaves the suite half-migrated.++Root `[patch.crates-io]` must name every used package at the same full SHA: `egui`, `eframe`,+`egui-winit`, `egui-wgpu`, `egui_glow`, `egui_kittest`, `epaint`, `epaint_default_fonts`, `ecolor`,+`emath`, and `winit`. Add `egui_extras` only if it enters the graph. Do not patch `egui_plot`,+`egui_dock`, `egui_inspection` or `egui_system_font_provider` unless used. Never use a branch name+or a machine-local path in a publishable manifest.++`craft-ui`'s own `[patch]` does not propagate: LightCraft's root patch is what gives+`eframe`/`egui-winit` the fork. A graph that resolves `winit` from crates.io while `egui-winit`+expects the fork API is a failure. `craft-ui` must compile against the stock egui 0.37 source API+(PR 199's role/`scope_id`/`IdSalt` edits) so the shared crate stays publishable; fork-only APIs stay+out of craft-ui. Pin `craft-ui` to the reviewed craft-libs revision and verify its `serde` feature+under LightCraft's root patch.++### 5.2 craft-libs: use the reconciled base, never the stale trees++- Current local shared-library base: `3832c47ef68a0e6214f2c1e85f3526b6adcb686e`. It already+ carries the egui 0.37 API port (the historical `8614e4a` shape and the `1764bca` README hunk);+ those commits and the earlier `49190884278f16c9a9f5823d7698a8ffb5deb062` main are history, not+ the base to apply again.+- PR 199 head `b68de8c5f4f1c060904d211a7b1320aa0f7bce78` and the audit merge+ `ec8840af8c5fda695cf195cdd05e5ae078415c07` miss `craft-platform` and revert newer+ security/settings/docking/printer fixes. Never merge either as a tree.+- Keep the `craft_ui::capture::CaptureSlot` consumer adapter on the reconciled base, preserve+ every newer fix, and re-run craft-ui's own tests and visual fixtures after the port. The CL-2F+ helper and the exact immutable publish SHA remain central-publication gates; neither is guessed+ here.++### 5.3 Checks++Add an `xtask` dependency check (for example `xtask/src/deps.rs`, invoked by `cargo xtask ci`+before clippy). The check takes its expected graph from a mode/fixture: L1 runs it in 0.36.2+baseline mode and is green today; L2a flips the expected graph to the 0.37 P8 graph in the same+atomic dependency commit. The negative fixtures run in both modes. `Cargo.lock` records packages,+versions and sources but **not resolved features**, so it can only prove identity:++- lockfile/metadata identity: exactly one `egui`/`epaint` family source and one `winit` source, all+ at the expected git URL and full revision; no registry copy beside them; `craft-ui` and+ `craft-docpath` at the reviewed revision, not a branch or a path;+- resolved features from `cargo metadata` + `cargo tree -e features` for every accepted root+ (native, headless/CLI, tests, wasm): `egui` has `default_fonts` and `monochrome_emoji_fonts`;+ native `eframe` has `clipboard`; the wasm root does not accidentally pull `wgpu`; `craft-ui`'s+ features resolve as intended. Record the raw output in the evidence;+- negative fixtures, each of which must fail: missing patch, branch pin, second registry `egui`, old+ `craft-ui`, machine-local path, feature-less `egui` (the last one only through the+ metadata/tree mechanism — a lockfile-only check cannot catch it);+- `wasm-bindgen` in the lock matches the CLI (`xtask/src/web.rs` already checks this).++Run `cargo tree -d`, `cargo tree -i [email protected]`, `cargo tree -i [email protected]`,+`cargo metadata --locked`, `cargo check --locked --workspace --all-targets` and the wasm graph under+the same pin in managed jobs (§7.1). A clean checkout must fetch every approved revision and pass+`--locked` without local overrides. Recheck remote heads before merge; an immutable SHA is required+even if the remote branch moved. Record the lockfile SHA-256 and keep the 0.36.2 lockfile for+rollback. `accesskit` moves to 0.25.x, `kittest` to 0.5.0; review that churn. Nix's `cargoLock`/+`allowBuiltinFetchGit` must fetch the git sources; run `nix build` if available, otherwise record+the explicit unavailable gate.++## 6. Regression assertions++### 6.1 Functional and lifecycle++- **One command/undo step per user action under multipass.** Use the existing+ `right.rs:1161` `request_discard` path plus a test-only forced discard, press one rating/flag key,+ and assert one catalog op/undo entry, one toast, one repaint request and identical settings.+ Repeat through the control channel.+- **Control gesture delivery and screenshot paint predicate (implementation amendment).** A queued+ `ui.clickWidget` with a stale registry answers only after a completed fresh layout; an id that+ disappears answers once; a view/dialog/document change between admission and resolution answers+ once with a cancel error; a hidden gesture receives `RequestPaintWhileHidden` while unresolved or+ undelivered and replies only after its last synthetic event is consumed; a 5 s deadline answers+ once and clears the queued events. A screenshot that is only queued/settling (`sent_at_ms ==+ None`) requests a hidden paint; one already issued (`sent_at_ms == Some`) does not, while its+ 2 s compositor fallback and hard timeout checks still run every logic tick.+- **Hidden logic continues.** Repeated `ctx.run_logic` calls while hidden advance+ import/Lightroom-import/recheck/task/autosave/persist/retry/slideshow work, do not consume a queued+ key/text/drop, and do not replay the last pass's dropped files. A hidden tick that invokes+ `raw_input_hook` leaves one queued synthetic step in flight; repeated hidden ticks must not inject+ further steps or batch press+release, and the next full pass consumes exactly one. Cover: a+ completed multipass frame followed by hidden ticks (`current_pass_index() == 0` each time, so+ nothing is skipped); `visible() == Some(false)`; a forced hidden paint with pending input and with+ a pending screenshot; restore with buffered events (each consumed once); a worker completion+ between passes.+- **First frames.** `Headless::step` at simulated time `0.0` runs logic and lays out; a harness that+ calls `ctx.run_ui(egui::RawInput::default(), …)` runs logic; `visible() == None` is treated as+ normal; the first forced hidden paint processes input.+- **Screenshot capture.** Two outstanding requests get their own image and exactly one reply; a+ queued/settling hidden request receives `RequestPaintWhileHidden` before issue while an issued+ screenshot forces its own paint;+ complete out of order; drop/cancel then complete the callback (no reply/file/panic; reservation+ back to zero); 2 s compositor fallback and hard timeout; an issued hidden-window request completes+ via the screenshot's own forced paint while a queued/settling one first needs the paint request;+ headless request completes through `HeadlessView::run` and+ `Headless::step` (both, once); a resize between issue and completion retries or errors rather than+ mixing geometry; oversized dimensions are rejected before issue.+- **Control gestures while hidden.** `ui.clickWidget`, `ui.dragWidget`, `ui.pointer` with+ `space: "image"`, and a multi-step drag each complete while the viewport reports hidden, using the+ first fresh layout after admission, send a paint request per step, and reply exactly once after+ the last event was delivered. A widget that no longer exists replies with an error once.+- **Save/reopen.** Edit exposure/keywords/mask, save/persist, close, reopen the same synthetic+ library; assert document meaning, selection/workspace and undo. Assert `UiState` JSON round-trips+ and docking/floating geometry survives unchanged.+- **Docking and second window.** Real drag → float → close → reopen and `ui.dock` invalid requests+ preserve the selected tool/layout (`tests/docking_workflows.rs`); explicit LTR direction leaves+ saved rectangles and tab order unchanged; the embedded second window renders the active photo and+ closes; the native second window focus/close/reopen is a real-platform test.++### 6.2 Geometry, hit-testing and pixels++At 1400×900 and 900×700, scales 1.0/1.5/2.0, dark/light themes:++- top bar 42 pt, bottom bar 48 pt, tool strip 48 pt, default side widths from `UiState`; panel order+ top → banner → strip → central → side panels; canvas rect equals the remaining rect within 0.5 pt;+- dragging the left/right inner edge by ±120 pt changes the stored width within 2 pt and the+ registered `panel:*` rect within 1 pt; the photo area never falls below `MIN_PHOTO_WIDTH`;+- the `resizable_side` test asserts the drag edge is live through the corrected `pid` (and fails if+ the panel is constructed with a pre-hashed `IdSalt`);+- grid/filmstrip/menu scroll offsets and hit rects agree after wheel, drag and resize; menu arrows+ scroll and stop at bounds;+- dialogs are centered and fit; a long translated title/label does not overflow (`tests_dialog_fit`,+ `tests_labels`, `tests_masking_layout`).++Pixel comparisons use 1600×1000 at 1× and 2×, deterministic `Session::with_demo()` and pinned fonts.+Keep reviewed baselines in task evidence, never `UPDATE_SNAPSHOTS=force`; compare with a predeclared+metric: region geometry exact ±0.5 pt; count of pixels differing by >2 LSB and mean absolute+difference per region; a change in the top bar, side panels, canvas or menu requires review.+Determinism alone is not acceptance.++### 6.3 Accessibility and keyboard++- The strict kittest checks are on in every harness from L2a: no unnamed input, no missing glyph.+ Extend `tests/accessibility.rs` to the roles `is_input` uses (`DisclosureTriangle`, `Splitter`,+ `Tab`, inputs) and to the second-window embedded tree. Sliders have value/range; dialogs have+ titles; hidden controls disappear.+ Custom disclosure rows use the actual 0.37 API: `WidgetInfo::labeled(Role::DisclosureTriangle,+ enabled, label)` plus `ctx.accesskit_node_builder(resp.id, |node| node.set_expanded(open))`.+ They must not use `WidgetInfo::selected`, which fills AccessKit `Toggled` rather than `Expanded`.+ A unit test asserts `is_expanded()` is `true`/`false` for `widgets::section_header`; the same+ helper is used by `widgets::flyout_row`, the panel fold headers and the sidebar section headers.+ (An accessibility-tree run over the Edit/Keywords views remains part of the broader accessibility+ suite, not this focused state test.)+- Tab order stays top-to-bottom in panels; screen-reader Increment/Decrement/SetValue and+ Enter/Space/arrow actions trigger the same commands as the pointer.+- Focus/edit/drag state does not transfer when the language changes, a panel hides, rows are+ inserted, or a menu opens. `Id::unique` preserves `Id::new`'s hash, but a wrong `IdSalt`/`scope_id`+ in a container can still move state.+- Text field: select range → click-away action uses that range (#8763); Esc restores; Return/away+ commit; IME preedit/commit/cancel one edit/undo; bidi caret/selection in logical and visual order;+ emoji keyword/filename renders without tofu.++### 6.4 Mutation/negative controls++Bounded probes that fail before the fix, kept as unit-level negative tests where cheap:++- a capture slot completed for the wrong request: no file/reply; a late callback after cancel: no+ reply/panic and released bytes;+- a deliberately duplicated command path under `request_discard`: the one-undo test fails when the+ first-pass guard is removed;+- `resizable_side` with the old exact `Id` or a pre-hashed `IdSalt`: the drag test fails to see the+ resize widget / does not store the width;+- one unnamed input in a scratch kittest harness: `check_accessibility` panics;+- one unsupported glyph: `MissingGlyphPolicy::Panic` panics and `Tofu` does not;+- a hidden `ui.clickWidget` while the widget registry is stale: the request resolves only after a+ fresh layout (test fails if the old geometry is used).++## 7. Performance protocol++### 7.1 Baseline, candidate and control++Build the baseline `23e18128`, the **stock** 0.37 control and the fork candidate in separate managed+`task.py run --kind build` allocations with distinct source/evidence paths (§8). Use the same Rust+toolchain (`1.99.0` at inspection), `--release`, same features (`denoise` default; `heif` separately),+same `CRAFT_FONTS_DIR` revision (craft-fonts `2481a8a`), same corpus files, same profile (including+`debug = "line-tables-only"`), same renderer/driver, viewport and DPI. Record full commit, lock+SHA-256, resolved features, fonts, fixtures, OS, CPU, RAM, GPU adapter/driver, renderer backend, DPI+and whether the GPU is enabled. Alternate execution order; never benchmark concurrently with a build+or another noisy workload.++Fixtures: `Session::with_demo()` (deterministic), a 10,000-photo synthetic library from the+`grid_bench` generator, and the pinned 24 MP corpus raw (`cargo xtask corpus --download`; gitignored).+No corpus or `CRAFT_FONTS_DIR` was present at inspection, so these are explicit prerequisites.++**Comparisons.** Report baseline 0.36.2 → candidate, and stock 0.37 → candidate wherever an+equivalent workflow exists in stock 0.37, so a fork-induced regression is not confused with a+0.37-induced one. The stock control uses the same fixtures, profile, fonts and environment.++### 7.2 Operations and sample counts++- **Warmups**: at least **10** warmup iterations per steady operation, discarded.+- **Steady operations**: at least **30** timed iterations (slider drag, menus, control operations,+ opening photos), 10 repetitions for cold/warm open.+- **Startup**: **20** fresh processes per side, to first UI frame and to thumbnails settled;+ separate process start, renderer/probe construction, font setup and first frame.+- **Frame distributions**: at least **1,000 actual painted frames** before any p50/p95/p99 claim+ (not synthetic logic ticks, not 20/30/50 samples), counted from `Context::cumulative_frame_nr()`+ or the equivalent painted-frame counter. Report median/p95/p99 with the actual frame count.+- **Grid**: `grid_bench` 200 and 10,000 photos, 60 unchanged frames, both grid modes, 1× and 2×;+ median/p95, per-frame UI allocations, cells visited, layout rebuilds.+- **Slider drag**: `drag_latency` on the 24 MP raw, 27 controls, `TICKS=30`, CPU and GPU separate;+ median/p95 draft texture latency and full render after release. Existing budgets: ≤16 ms draft,+ ≤60 ms loupe; export ≤1 s/24 MP JPEG.+- **Thumbnails/menus**: `thumb_request_bench` with blocked rendering for allocation counts; a long+ menu open with wheel/arrow scroll, 1,000 actual frames.+- **Opening photos**: `open_timeline` with pinned raws, warm and cold, 10 repetitions.+- **Control/UI operations**: `ui.screenshot` (headless), `ui.inspect`, grid scroll and panel drag,+ measured request → reply over 30 samples.+- **Separate workloads, never one blended number**: (a) **#8731 text tessellation** — text-heavy+ fixture, plain text vs mixed color glyphs; (b) **#8736 DX12** — fresh-process pipeline/probe+ construction and first frame on Windows DX12; (c) **#8512 font startup** — font discovery/setup+ time in a fresh process with and without the bundled faces.+- **Idle**: 60 s visible and 60 s minimized/hidden; process CPU time, `cumulative_frame_nr` (an+ additive `perf.frames` only in the instrumentation stage), repaint count, GPU work and RSS. A new+ busy loop or a repaint while hidden beyond requested work is a failure.+- **Web**: `cargo xtask web` **raw and compressed WASM size** (raw, gzip, brotli; separately record+ the effect of `monochrome_emoji_fonts`), `?bench` first frame, thumbnails, eight slider steps and+ release render, 10 fresh page loads per side, one browser/version and a software/ANGLE equivalent+ if available.++Record peak RSS, allocation/texture-upload counters, cold vs warm caches and idle CPU separately.++### 7.3 Predeclared acceptance and noise policy++Shared suite thresholds (do not loosen them): investigate a repeatable **>5 % median** or+**>10 % p95** latency regression, **>5 % peak-RSS increase**, any new idle busy loop/repaint, any+missed slider/loupe/export budget, or a visual/document regression. App-specific gates may be+stricter. Apply a documented noise floor: for sub-millisecond values require the relative increase+to exceed 0.05 ms or corroborate with stable instruction/allocation counts. The **stock 0.37+equivalent control** is required in the first report and for every regression decision, so a+0.37-induced change is not attributed to the fork; stock 0.37 remains a control, never a production+stage. Reject noisy comparisons as inconclusive and rerun; **do not widen thresholds** after seeing a+failure. #8731/#8736/#8512 figures are upstream reports, not our measurements; compile duration is+not UI performance.++## 8. Platform evidence and provisioning gates++Every row is a **provisioned environment gate**, not a claim that the current host or a previous run+passes. A row without provisioned hardware/OS/browser is recorded as unresolved, never as a pass.++| Platform | Required workflow | Acceptance |+|---|---|---|+| Linux X11 | Managed native run of the exact candidate with `--control PORT`, control script, native screenshot, edited/saved/reopened library; both themes, 1×/2×; renderer recorded. Requires a real X11 session (none is inherited by this server shell) | Real window; CPU and available GPU reported separately |+| Linux Wayland | Same on a named compositor (wlroots/KWin/Mutter) provisioned for the task; clipboard/PRIMARY, drop, IME, hidden second window | E4 + W15P matrix from §4.9; any compositor limitation recorded if reproduced |+| Windows | Owned `craft-windows` clone (own disk, UEFI, TPM, ports, 128 GiB reservation), native build of the exact candidate, visible grid/detail/edit workflow, screenshots, save/reopen, FXC/DX12 probe, software-renderer baseline and real GPU if present | Start-up/first frame measured; no panic/black window; DX12→Vulkan→GL fallback |+| Web | `cargo xtask web --serve` in a provisioned browser environment; browser automation drives observable `command(...)` actions (thumbnail/detail/slider/save state) and captures the canvas with the **browser's** screenshot facility; console errors checked; `?bench` | Real browser workflow; wasm module and CJK/emoji assets present; not just `cargo check`. There is no control server and `ui.screenshot` is not a `LightcraftApp::run` command (`web.rs:609-644` → `self.app.run`), so a browser capture is the only screenshot path unless a separate reviewed download/writer API is added |+| FreeBSD | Repo workflow with craft-fonts, if a runner is provisioned | Compile/test evidence or explicit unresolved gate |+| macOS | Real macOS hardware (not cross-compilation) for menu/IME/Metal/GL/termination/AccessKit teardown | Separate unresolved blocker |++No claim is made that this server has no GPU: read-only inspection finds an i915 PCI `8086:3E96`+render device and readable/writable `/dev/dri/renderD128`. That is **availability evidence only**,+not a qualified Vulkan/OpenGL/compositor result. No display session is inherited, and Windows+baseline rendering remains software-rendered.++Headless rendering is not proof of native focus, IME, file picker, compositor clipboard, screen+reader or GPU presentation. A windowed `ui.screenshot` that logs the "rendering headlessly" fallback+does not satisfy native acceptance.++## 9. Reviewable PR stages, dependency DAG and rollback++```text+P0 (external; BLOCKED until published)+ storytold egui immutable revision P8: E1-E21 + P2b (E4 regular/PRIMARY with bounded+ async W15P transfer) + P7 held-key pairing + P7b/E21b + P7c (#8763/#8748 and+ justified perf fixes), reviewed and published+ storytold winit immutable revision: complete W15P + W27 lifecycle (+ W15/W25/W26 series)+ craft-libs CL-1 revision, then CL-2 provisional capture slot+ CL-2 -> DesignCraft/GridCraft adapters -> CL-2F API freeze+ |+L1 baseline harness/instrumentation + baseline-aware xtask dependency check + evidence scripts+ (0.36.2 expected-graph mode; works today; no product UI change, no new pins)+ |+L2a coherent graph + compile migration (manifests, lock, patch, Id/Role/scope/ComboBox/Event+ source, default_fonts + monochrome_emoji_fonts + native clipboard, CL-2F screenshot+ callback/admission/drain/timeout/basic reply handling, scroll offset read/write, strict kittest naming/glyph fixes, all -D warnings)+ -- atomic; no unbuildable intermediate commit on main. BLOCKED on P0.+ |+L2b lifecycle/root-UI hardening (tick split, monotonic clock, dropped-file queue, panel IDs,+ hidden gesture queue, CL-2F capture stress tests, both headless hosts, second-window/docking tests)+ -- needs CL-2F (DesignCraft/GridCraft are the CL-2 pilots).+ |+L2c fonts/accessibility/language/IME/clipboard hardening (set_language, #8763, E21b/W27 tests,+ W15P/E4 PRIMARY matrix)+ |+L2d measured visual/perf acceptance, docs updates, platform evidence and final review+```++P0 is **explicitly blocked**: the final approved storytold immutable SHAs are unknown until the fork+and winit series are published, and this plan does not invent them. `a4f9a17f`/`8b35388b` are used+only to inspect behavior. L2a–L2d cannot be prepared as merge-ready changes until P0 exists.+L1 can start now in 0.36.2 expected-graph mode; L2a switches the dependency check to the 0.37 P8+graph. L2a is one atomic dependency stage: the complete egui/winit P8 graph plus the required+craft-ui revision (CL-1 and CL-2F for the eleven `craft-ui` consumers; DesignCraft/GridCraft CL-2+pilot adapters precede CL-2F). Any incompatible existing craft-ui bump belongs in that same atomic+stage. Stock 0.37 is only the measurement control, not a production stage.++Expected file ownership: L1 adds `xtask/src/deps.rs` (plus dispatch), test/bench harness scripts+under `tools/egui037/` and non-product tests; L2a changes `Cargo.toml`, `Cargo.lock`, the three app+manifests, `crates/ui-egui/Cargo.toml` and the mechanical compile sites in+`crates/ui-egui/src/{lib.rs,widgets.rs,control.rs,headless.rs,menu_level.rs,panels/*}` plus+`apps/lightcraft/src/main.rs` where an API changed; L2b owns `lib.rs`, `panels/mod.rs`,+`panels/{faces,denoise}.rs`, `panels/second.rs`, `headless.rs`, `control.rs`,+`apps/lightcraft/src/main.rs`, `apps/lightcraft-web/src/web.rs` and lifecycle tests; L2c owns+`theme.rs`, `i18n.rs`, `text_field.rs`, `widgets.rs`, `tests/accessibility.rs` and the+IME/clipboard tests; L2d owns only reviewed visual/perf evidence and progress documentation.++L2b–L2d are separate dependent PRs; they may be implemented on separate branches after L2a but merge+one at a time, re-running `cargo xtask ci` after each merge. Do not land a dependency bump that+leaves `main` unbuildable, and do not combine unrelated cleanup with the migration.++Rollback is the whole previous coherent set, not an egui version string: revert the stage range and+restore the 0.36.2 manifests/lockfile plus craft-ui `5c874d51...` and registry winit `0.30.13`; keep+the old lockfile, patch block, package IDs and source SHA in evidence; keep fork/winit/craft-libs+revisions reachable. No persistence migration: `UiState`, catalog journal/snapshot, XMP, presets and+library paths are unchanged; only egui memory/panel layout may reset. No release, tag, branch+deletion or cache cleanup until the migration is abandoned or complete and evidence is preserved.++## 10. Blocking unknowns and acceptance criteria++1. **Published pins (blocking).** The final approved storytold egui **P8** (including P2b, P7,+ P7b/E21b and P7c) and the completed winit (W15P + W27) immutable revisions do not exist until the+ fork/winit series is published and reviewed; no SHA is assumed here. Stages L2a–L2d are blocked+ on them. `a4f9a17f`/`8b35388b` are comparison references only; no stock or intermediate stage is+ a production dependency.+2. **E21b/P7b (blocking).** The complete shared contract — owner identity even when unavailable,+ available-empty distinct and explicitly sent, committed disable/enable clear, latest-pass+ authoritative `None`, current-epoch serial mismatch applying incoming edits once while outgoing+ waits, stale-epoch invalidation, bounded ≤4000-byte payload with no full-document clone — plus the+ `TextEdit` producer and W27 adapter is not in the inspected candidate. LightCraft's built-in+ `TextEdit` consumers inherit it, and the family's custom producers (e.g. FilmCraft+ `panels/graphics.rs`) need their own logical-model adapters before family acceptance.+3. **W15P + E4 + P2b (blocking for native PRIMARY).** The inspected E4 has an arboard fallback, not+ the required winit-owned per-seat PRIMARY path. Require the complete published P8/W15P revision+ with bounded asynchronous transfers (2 s total deadline, 16 MiB, four readers/two writers/queue+ 8, owner-specific waker, stale-result cancellation), pointer- or keyboard-triggered fresh serials+ and the §4.9 native matrix.+4. **craft-libs CL-1/CL-2F.** The capture slot exists only as a provisional CL-2 API until+ published; LightCraft requires the frozen CL-2F API, which only exists after the+ DesignCraft/GridCraft pilot adapters. The port sits on the reconciled+ `3832c47ef68a0e6214f2c1e85f3526b6adcb686e` base; PR 199's head and the audit merge are stale+ trees and `8614e4a`/`1764bca` are already contained in that base.+5. **Hidden viewport children.** #8748's overdue-UI behavior is not in the inspected fork; P7c is+ required to carry the selected fix. The second window while the root is hidden/minimized still+ needs native Wayland/Windows evidence.+6. **DX12 startup (#8736)** and **text tessellation (#8731)** are open upstream reports; measure on+ our fixtures as separate workloads and require a semantics-preserving fix if thresholds are+ breached. **#8512** is a separate font-startup workload, not a reason to enable system fonts.+7. **Strict kittest findings.** The number and identity of unnamed inputs/missing glyphs under 0.37+ is unknown until the first L2a run; they are real fixes, not a reason to disable the checks.+8. **Fonts.** Whether the bundled faces cover every shipped locale and script fixture without system+ fonts is a measured gate; CJK tests skip without `CRAFT_FONTS_DIR`, which is not release+ acceptance. Monochrome emoji add ~1 MB; measure native and WASM size.+9. **PRIMARY/clipboard on GNOME/Mutter** needs a real compositor; a control-channel paste is not a+ substitute.+10. **macOS**: no real hardware evidence for menu, IME, Metal/GL, termination or AccessKit teardown;+ an explicit rollout blocker, not a pass.+11. **Web workflow**: no control server and no `ui.screenshot` command; browser capture plus+ observable `command` state is the acceptance path unless a separate download/writer API is+ separately reviewed and approved.+12. **Visual deltas**: 0.37 style/scrollbar/menu changes may alter reviewed screenshots; no bulk+ golden refresh.+13. **Lock/feature drift**: `accesskit`/`kittest` movement, `wasm-bindgen` CLI matching, Nix git+ fetching and a second `egui`/`winit` source must pass the dependency check.+14. **Performance environment**: no display session, corpus or fonts are guaranteed on this host;+ Linux/Windows/browser results need the managed resources in §7/§8. The i915 render node is+ availability evidence only.++Acceptance requires a fresh independent adversarial review of this plan, then of each implementation+at its exact revision, with resolved findings and hashes recorded. It also requires all repository+gates, selected features, native Windows/Linux and browser workflows, the measured before/after+report, accessibility and visual review, and explicit human publication approval. No unresolved+correctness finding is downgraded to "later".++## 11. Research references (primary sources; proposals distinguished from merged behavior)++- egui 0.37 changelog and release commit+ [`841a328b`](https://github.com/emilk/egui/blob/841a328ba2dd8f6996beb7189ebb7fc00e668a2a/CHANGELOG.md);+ the inspected suite branch is `a4f9a17f64a6bae61350fb85804c9df0d9865916`, not `main`.+- Lifecycle: [`epi_integration.rs`](https://github.com/emilk/egui/blob/841a328ba2dd8f6996beb7189ebb7fc00e668a2a/crates/eframe/src/native/epi_integration.rs),+ [`app_runner.rs`](https://github.com/emilk/egui/blob/841a328ba2dd8f6996beb7189ebb7fc00e668a2a/crates/eframe/src/web/app_runner.rs),+ [`context.rs`](https://github.com/emilk/egui/blob/841a328ba2dd8f6996beb7189ebb7fc00e668a2a/crates/egui/src/context.rs).+- Callback screenshots: PR #8489, `crates/egui/src/data/screenshot_callback.rs` (merged).+- Roles: PR #8555; `egui/src/lib.rs` role table (merged).+- IDs/scope: PRs #8534, #8586, #8590, #8542; `id.rs`, `id_salt.rs`, `ui.rs`, `ui_builder.rs` (merged).+- Panel salts: PR #8592; `containers/panel.rs` (merged).+- Root UI/run pass: PR #8535; `context.rs` (`root_ui` panic documented) (merged).+- Default fonts / emoji features: PR #8583; `egui/Cargo.toml`, `epaint/src/text/font_definitions.rs`.+- Strict accessibility/missing glyphs: PRs #8589, #8611, #8601; `egui_kittest` source.+- PRIMARY selection: PR #8428 (merged); Wayland clipboard #8657 (open draft) and winit #4729 (open),+ paired with E4/W15P.+- Bidi/RTL: #8577 (open) and the fork's E5/E12/E13/E16/E17/E20/E21 series.+- TextEdit click-away selection: issue #8763, PR #8764 (open/unmerged at inspection).+- Text tessellation: issue #8731 (open); DX12 FXC pipeline: issue #8736 (open); system-font startup:+ #8512 discussion.+- Hidden/overdue viewport children: issue #8748 (closed upstream; absent from the inspected fork).+- IME surrounding text gap: `ime-surrounding-gap.md` and the egui plan §E21b/P7b, winit W27.++## 12. Evidence to preserve++Retain: the baseline/candidate/control commit IDs, lock SHA-256 and package/source tables,+`cargo tree -d`/`-i` and `cargo tree -e features` output, `cargo xtask ci` reports and test+counts/skips, dependency-check negative fixtures, accessibility tree dumps, reviewed+baseline/candidate screenshots and geometry JSON, performance raw samples and summaries (with+environment and separate #8731/#8736/#8512 workloads), native/browser/Windows logs and screenshots,+the exact published egui/winit/craft-libs revisions and their tests, and this plan's reviewed hash.+Do not preserve build targets as evidence; they are rebuildable and are cleaned only after all checks+and deliverables are saved.++## 13. Review disposition record++### 13.1 R1 review (`lightcraft-v1.md`)++| # | Finding | Disposition | Resolved in |+|---|---|---|---|+| 1 | `Panel::left(salt)` double-hashes; `pid` mismatch | **Accepted.** `Panel::new` stores `IdSalt::new(id_salt)` and `Panel::id` = `parent_ui.scope_id().with_salt(store)`; `IdSalt::new(IdSalt)` is a distinct salt (`id_salt.rs` nested-salt test). Fixed to pass the original source and derive `pid` with `with_salt(IdSalt::new(id))`; no public panel-state-id helper. Impact narrowed: the helper has no production caller at inspection, so the defect is latent today. | §3, §4.7 |+| 2 | eframe `clipboard` feature missing | **Accepted.** Add `clipboard` to the native app and assert it through resolved features; headless clipboard is not native acceptance. | §2.1, §4.9, §5.3 |+| 3 | `TickPhase` has no first-frame/`None`/forced-hidden branch; stale-index premise false | **Accepted, with two sub-claims rejected.** The stale-index claim and the `has_visible_pass` contradiction are correct. The specific example "`RawInput::default()` has time 0" is wrong: `InputState::begin_pass` uses `new.time.unwrap_or(prev + predicted_dt)`, so the input time is `predicted_dt`; the real zero-time first frame is `HeadlessView::raw_input(..., time = 0.0)`. The classifier is removed entirely rather than patched, so both cases are covered. | §4.1, §4.2, §6.1 |+| 4 | Hidden geometry-dependent controls use stale geometry; one paint request cannot carry a gesture | **Accepted.** Geometry resolves only after a fresh `layout_epoch`; each gesture step requests a hidden paint; exactly one reply, after delivery. | §4.5, §6.1 |+| 5 | `default_fonts` loses 0.36 emoji faces | **Accepted.** Enable `monochrome_emoji_fonts`; tests cover `🙂`/`👍` and the emoji keyword fixture; ~1 MB size is measured. | §2.1, §4.8, §7.2 |+| 6 | E4 does not provide the winit-owned PRIMARY path | **Accepted.** W15P is a prerequisite with the full native matrix; no limitation is recorded as "solved". | §1, §4.9, §10 |+| 7 | E21b/W27 outgoing IME surrounding text missing | **Accepted.** Added as a blocking prerequisite with the built-in-`TextEdit` inheritance tests and the family custom-producer requirement (FilmCraft graphics etc.). | §4.9, §10 |+| 8 | Web cannot invoke `ui.screenshot` | **Accepted.** Web `command()` only reaches `LightcraftApp::run`; browser capture plus observable commands is the workflow; no new app API unless separately reviewed. | §4.11, §8, §10 |+| 9 | A `Cargo.lock` check cannot assert features | **Accepted.** Identity from lock/metadata; features from `cargo metadata` + `cargo tree -e features`; feature-less fixture targets that mechanism. | §5.3 |+| 10 | `DockArea::direction` unspecified | **Accepted.** Explicit LTR policy at both call sites with unchanged persisted geometry/tab order. | §4.7, §6.1 |+| 11 | Screenshot design does not adopt the shared completion slot | **Accepted.** LightCraft requires the frozen CL-2F helper; request paths/deadlines/replies stay app-owned. | §4.6, §9 |+| 12 | Hidden-time accounting misses toasts/status and faces/denoise input | **Accepted.** One monotonic clock for toasts/status/timers; faces/denoise split into background drain vs UI-phase input. | §4.3, §4.4 |+| 13 | Duplicate-work claim overbroad; web inbox table contradiction | **Accepted with correction.** A second pass has empty events (`InputState::begin_pass`), so event handlers cannot duplicate; the real duplicates are time-gated ticks and the double `faces::pump`. Web inbox runs every `logic` call, dropped files only in the UI phase. | §4.2, §4.4, §4.11 |+| 14 | `Headless::step` still has the removed `Event::Screenshot` arm | **Accepted.** Both `HeadlessView::run` and `Headless::step` are updated; exactly one completion. | §4.6 |+| 15 | Count/factual issues (`221` id calls; web inbox table) | **Accepted.** 221 `egui::Id::new` occurrences (218 lines) plus three bare `Id::new`, and 8 `ui.id()` calls verified in this checkout; the table/text disagreement is removed. | §3, §4.4 |++### 13.2 R2 review (`lightcraft-v2.md`)++| # | Finding | Disposition | Resolved in |+|---|---|---|---|+| 1 | Hidden timers placed in `ui_pass` where hidden `run_logic` cannot reach them | **Accepted.** `import`/`lightroom_import`/`recheck`/slideshow/auto-import/sidecar/device/toast/autosave ticks were moved back to `logic`, with monotonic deadlines so a second pass is a no-op; only UI input/drop/perf work stays behind `current_pass_index() == 0`. | §4.2, §4.3, §4.4, §6.1 |+| 2 | E21b/W27 omission of owner/serial/epoch rules | **Accepted.** Restated the complete P7b/W27 contract: owner identity while unavailable, available-empty sent explicitly, committed disable/enable clear, latest-pass authoritative `None`, current-epoch mismatch applies incoming once and defers outgoing, stale epochs invalidate, bounded payload without a new full-document clone. | §4.9, §6.3, §10 |+| 3 | W15P required without bounded async transfer | **Accepted.** P2b is now part of the P8 prerequisite: 2 s total deadline, 16 MiB cap, four readers/two writers/queue 8, owner waker and stale cancellation, with slow/canceled-transfer and responsiveness tests. | §1, §4.9, §6.3, §10 |+| 4 | PRIMARY matrix is keyboard-only | **Accepted.** Fresh pointer-press or keyboard-focus serials are both valid; keyboard-only is explicitly rejected, and middle-click paste is tested. | §4.9, §10 |+| 5 | Hidden synthetic input can accumulate in `pending_raw_input` | **Accepted.** Hook may run in logic-only, so it injects at most one step and marks it in flight until a completed UI pass consumes it; no second injection from repeated hidden ticks and no press/release collapse. | §4.5, §6.1 |+| 6 | L1 cannot both run on 0.36.2 and enforce the 0.37 check | **Accepted.** The dependency check is baseline-aware; L1 runs in 0.36.2 expected-graph mode, and L2a flips it to the P8 graph atomically. | §5.3, §9 |+| 7 | Counts/detail inaccuracies | **Accepted, normalized.** This checkout has 218 `egui::Id::new` lines plus three bare `Id::new` calls (221 lines, 224 occurrences; the review's line/occurrence wording was slightly mixed). The font key is `Ubuntu-Light`; the `logic` doc comment now matches per-pass host calls; the weak-slot reason is corrected (the renderer owns the callback, so this is not a `Context` cycle). | §2.1, §3, §4.2, §4.6, §4.8 |+++## Local implementation update — 2026-10-23++The user clarified that reviewed plans remain local and implementation proceeds before publication. The earlier requirement to publish/land this plan first is superseded; pushes and PR publication still require explicit approval.++Canonical `storytold/lightcraft` `main` now resolves to `d5e639b3d1ad079c39a924c1b65d0a96ee2134ac`. The owned checkout was fast-forwarded to this revision. Earlier baseline SHAs and line anchors above are retained as historical review evidence; use this new revision and its exact lockfile for current-main integration and paired measurements. The original refs remain reachable.++No migration API redesign required by this delta; preserve the merged packaging, test and chrono changes where present.++The complete static delta review and exact old/new object identities are retained in the task evidence: `canonical-diffs-refresh-20261023.json` and `overnight-consumer-review-20261023.md`. This amendment claims no new build, native GUI or performance acceptance.++## Local implementation — stage L2a/L2b source migration (2026-10-23)++Status: **source changes only, not validated here.** No build, test, `cargo metadata`, fmt,+clippy, GUI, browser, Windows or performance run was made in this worktree. The parent runs the+managed jobs listed at the end. This section records exactly what changed and what is still+open; it is not acceptance evidence.++### Dependency and feature stage (L2a)++- Workspace `egui` is now `0.37` with `default-features = false` and+ `features = ["default_fonts", "monochrome_emoji_fonts"]`; `eframe` and `egui_kittest` are `0.37`+ (`egui_extras` is declared at `0.37` although LightCraft still does not use it).+- Native `eframe` adds the separate 0.37 `clipboard` feature; web keeps `default_fonts` + `glow`.+- The workspace feature choice is what gives the CLI/headless and kittest roots their faces:+ `egui_kittest`'s own dev-dependencies do not propagate. `tests_lifecycle_037` asserts the+ `Hack`, `Ubuntu-Light`, `egui-icons`, `NotoEmoji-Regular` and `emoji-icon-font` faces and that+ U+1F642/U+1F44D are paintable.+- No final storytold SHA, `[patch]` entry or lockfile was invented. The parent supplies the local+ path patch from `../PLANNING-CONTRACT.md` / `local-integration-config.toml` and generates the+ lockfile. `crates/raw/src/vendor/` is untouched.++### API migration++- `egui::Id::new` → `egui::Id::unique` (same hash, so egui state does not reset) and `Ui::id()` →+ `Ui::scope_id()` across the UI crate and tests.+- `WidgetType` → `egui::Role` with the documented variant mapping (`CollapsingHeader` →+ `DisclosureTriangle`, `SelectableLabel` → `Button`, `ComboBox` stays `ComboBox`).+- `Panel` salts: `resizable_side` now passes the original salt to `Panel::left/right`, derives the+ persisted key with `ui.scope_id().with(id)`, and checks the resize drag on that key (the old code+ passed a prebuilt `Id` and would be salted twice). 0.36 exact-`Id` `PanelState` entries for+ `top_bar`, `bottom_bar`, `tool_strip` and `library-problem-banner` are removed once at startup;+ this resets only egui panel memory, never `UiState`, docking JSON, catalog or XMP data.+- `ScrollArea::State.offset` is private: menu arrows store a one-frame `vertical_scroll_offset`+ target, and the right panel reads `clamped_offset()`.+- `Event::MouseWheel` initializers carry `source`; `ui.scroll` accepts optional+ `"source"`, `"unit"` and `"phase"` with the validated values and defaults from §4.9.+- `ComboBox` has the documented lifetime; atoms take `IdSalt` (`Atom::custom`,+ `WidgetAtomResponse::rect`).+- `ViewportCommand::Screenshot` now uses the one-shot callback and `Event::Screenshot`/`UserData`+ are gone. Both headless entry points answer the callback with their painted frame exactly once.+- The fork's `Context::set_language` is fed from `i18n::language()` (the AccessKit root language+ and bidi runs follow the UI locale; command ids and user data stay logical).++### Lifecycle and capture stage (L2b)++- `LightcraftApp` now has a monotonic `AppClock` (`web_time::Instant`, never `i.time` or+ `Date.now` for timing; `now_ms` remains wall-clock only for `library-restored-<ms>` names).+ Headless hosts feed it their simulated time; the first `Headless::step` runs at 0.0.+- `logic` keeps queues, worker polls and time-gated work. Import committing is gated on+ `current_pass_index() == 0` (once per host frame, and once per hidden logic tick), not on the+ clock; all other hidden-relevant timers (Lightroom import, slideshow, auto-import, sidecar retry, screen profile, denoise/faces/focus/model,+ autosave/prefs, toasts, captures) use the app clock.+- `ui` is split into `ui_pass` (first pass only: fresh input, dropped files, external-editor focus,+ shortcuts, perf) and `draw_window` (presentation), then `finish_ui_pass` (completed, nondiscarded+ pass; clears the synthetic in-flight gate). A hidden `run_logic` never reaches it.+- Dropped files are taken once in `raw_input_hook` into an app queue and consumed only in the UI+ phase; web consumes the same queue in `WebApp::ui` (it needs `bytes_async`). Native and web tests+ cover that a hidden logic tick leaves the queue intact.+- `raw_input_hook` injects at most one synthetic batch, refuses to inject before fonts are ready,+ marks the batch in flight until a completed pass consumes it, and keeps a hidden window painting+ with `RequestPaintWhileHidden` while a batch, settlement or queued capture is pending.+- Screenshot capture adopts `craft_ui::capture::CaptureSlot` (CL-2 local tree): four outstanding+ requests, 128 MiB per image, 256 MiB aggregate including completed-not-drained images, admission+ before issue, fresh native viewport geometry, a three-completed-frame/120 ms settle, a forced+ capture at 3 s even while renders are in flight, a 2 s compositor fallback and an 8.12 s+ admission deadline (settle + forced capture + fallback + headless settle). The strong slot stays in the app request+ record; the callback only holds a weak slot and never writes files or touches app state. A+ completion from an older geometry epoch or library generation is retried, never written; an+ image larger than its reservation is rejected; a cancel/timeout/late callback releases its bytes+ with a checked subtraction and replies once.+- Web `Bench::step`, `WebApp` notices/save and the native `PrefsWriter` use the monotonic clock.+ The native menu and window-watch no longer record a hidden pass's stale content rect.++### IME inventory and next step++LightCraft has no custom `egui::IMEOutput` producer: `TextField` wraps the built-in `TextEdit` and+every other editor uses `TextEdit`, so it will inherit the P7b/E21b logical-model/preedit/UTF-8+producer once the reviewed egui revision is pinned. No `None` placeholder was added. The next step+is to re-run the P7b outgoing-surrounding-text cases (deletion-only and delete+commit, preedit+excluded, reversed selection, supplementary/RTL text, over-limit selection, available-empty vs+unavailable, window/owner switch, password clear, stale serial) against that pinned revision. The+incoming byte-deletion path is the built-in `TextEdit` path and is not reimplemented here;+`tests_lifecycle_037` asserts that `TextField` applies `ImeEvent::DeleteSurroundingBytes`+exactly (the pinned fork's winit byte-range event).++### Tests added (source only)++`crates/ui-egui/src/tests_lifecycle_037.rs`:++- bundled monochrome emoji + explicit font-feature gate;+- parent-salted panel state (and no legacy exact-`Id` state);+- capture admission count/per-image/aggregate bounds before issue;+- stale-geometry completion rejected before any file write, reservation retained for retry;+- one synthetic batch until a completed pass, and dropped files waiting for the UI phase;+- first headless frame at simulated time 0 and the app clock following the host.++### Unresolved prerequisites and validation++- Final published storytold egui P8 (E1–E21 + P2b + P7 + P7b/E21b + P7c) and winit W15P/W27+ revisions, and the reviewed craft-libs CL-1/CL-2F revisions, do not exist as pins here.+- This source stage calls `craft_ui::capture::CaptureSlot` (the provisional CL-2 module in the+ local craft-libs tree). The parent must provide a craft-ui revision that actually contains that+ module; if CL-2F renames or changes it, the thin app adapter in `crates/ui-egui/src/lib.rs` must+ be updated rather than copied into a second helper.+- Native PRIMARY (W15P/E4), E21b/W27 outgoing IME, #8748 deferred viewport children and #8763 are+ inherited from those pins; none is claimed.+- The explicit LTR `DockArea::direction(DockDirection::LeftToRight)` policy is not added here:+ the reviewed craft-ui revision in the local tree has no `direction` builder yet. Add it in the+ same dependency stage that freezes CL-1/CL-2F; persisted splits, axes, ratios, floating+ rectangles and logical tab order must stay unchanged.+- `accesskit` 0.24 → 0.25 and `kittest` 0.4 → 0.5 churn is not pinned here; check that the+ Linux `zbus = "=5.19.0"` pin still resolves to one zbus source, and that `wasm-bindgen` in the+ generated lock matches the CLI.+- `RequestPaintWhileHidden` has no web support in the shared fork: the browser path is unqualified+ and remains a pending fork fix. Headless rendering is not native focus/IME/picker evidence.+- Strict kittest naming/missing-glyph checks may surface unnamed inputs or glyph gaps; those are+ real fixes, not reasons to disable the checks.+- Visual/style deltas from roomier 0.37 defaults, Windows software rendering, macOS and native+ compositor/PRIMARY evidence are still separate gates.+- Control gestures (`ui.pointer`, `ui.clickWidget`, `ui.dragWidget`, and the other input methods)+ now resolve only after a completed fresh layout and reply only after the final nondiscarded pass+ consumed their last event; the 5 s deadline is the fail-closed fallback. Limits are recorded in+ §4.5: cancellation covers the admission-time view/document/dialog/panel snapshot, not a+ per-widget semantic identity across an arbitrary catalog refresh in the same frame, and a+ timeout clears queued synthetic input rather than removing one gesture's events individually.++### Baseline backports and performance operations++- Backports this consumer depends on but does not own: egui P7c (#8763 click-away selection,+ #8748 overdue viewport children, the semantics-preserving text-tessellation fix) and E21b/P7b;+ winit W27 outgoing IME lifecycle and W15P bounded PRIMARY; craft-libs PR 199's API-port hunks+ (`Role`/`scope_id`/`IdSalt`) and the CL-2F capture helper on current main, never the stale PR+ tree.+- Performance operations to measure after the pins exist, each as its own workload: menu/panel+ text tessellation (#8731), DX12/FXC first-pipeline startup (#8736), system-font startup only if+ the font policy is revisited (#8512), capture settle/issue overhead and hidden idle repaint/CPU.+ Record raw samples and the environment; do not treat compile time as UI performance or refresh+ visual goldens in bulk.++### Parent-managed validation commands++Use one new resource (for example `egui037-lightcraft-candidate-20261023`) and a fresh job id per+command. `--locked` only after the parent generates the lockfile.++```sh+python3 /home/codex/work/maintenance/task.py run \+ --job-id egui037-lightcraft-20261023-check-01 --kind build \+ --task egui037-lightcraft-candidate-20261023 \+ --source "$PWD" --evidence /home/codex/work/ssd2/task-evidence/egui037-migration-20261022/lightcraft-candidate \+ -- cargo check --workspace --all-targets+python3 /home/codex/work/maintenance/task.py run \+ --job-id egui037-lightcraft-20261023-lifecycle-01 --kind build \+ --task egui037-lightcraft-candidate-20261023 \+ --source "$PWD" --evidence /home/codex/work/ssd2/task-evidence/egui037-migration-20261022/lightcraft-candidate \+ -- cargo test -p lightcraft-ui-egui --lib tests_lifecycle_037+python3 /home/codex/work/maintenance/task.py run \+ --job-id egui037-lightcraft-20261023-ci-01 --kind build \+ --task egui037-lightcraft-candidate-20261023 \+ --source "$PWD" --evidence /home/codex/work/ssd2/task-evidence/egui037-migration-20261022/lightcraft-candidate \+ -- cargo xtask ci+```++Then inspect every `status`, record `cargo tree -e features` for the native, CLI/headless, kittest+and wasm roots, run the accessibility/docking integration tests and the `cargo xtask web` browser+workflow, and only afterwards consider the measured before/after workloads (menu text tessellation,+DX12/FXC startup, capture settle cost, hidden idle repaint). Do not refresh visual goldens in bulk.++## Post-port review repairs (2026-10-23)++Source-only repair of `egui037-lightcraft-postport-review-20261023-root-v1.md`. No build, test,+fmt, clippy, `cargo metadata`, GUI, browser, Windows or performance run was made here; the parent+submits the managed jobs.++- **P1.1**: the four bare `Context::run_ui` statements in `tests_lifecycle_037.rs` bind their+ `FullOutput` (`let _ = …`) so `-D warnings` no longer sees `unused_must_use`.+- **P2.1**: a settled capture is issued at a forced instant (`SHOT_FORCE_BUSY_MS`, three seconds+ from admission) even when `renderer.in_flight()` or the merge is busy; the hard deadline (five+ seconds) stays the only timeout path. `shot_ready` is a pure helper with a busy-renderer test.+- **P2.2**: capture identity is the library generation only. `catalog.revision` (bumped by every+ applied edit/import/keyword op) no longer invalidates an in-flight image; the test applies one+ catalog op between issue and completion and still writes the image.+- **P2.3**: a surface that grows after admission is checked as an *image* against the 128 MiB+ per-image cap and only its growth against the 256 MiB aggregate. The old code compared the delta+ to the per-image cap and named the delta as the image.+- **P2.4**: a completion larger than its reservation but within the per-image cap is treated as a+ stale reservation (Wayland has no `inner_rect`), re-reserved and written, not rejected.+- **P2.5**: a slideshow auto-pauses while `ViewportInfo::visible() == Some(false)`, requests no+ playback repaint, and resumes on unhide with the slide's remaining time preserved. This replaces+ the 0.36 behavior where `i.time` froze while hidden.+- **P2.6**: the “0.37 has no `visible()`” rationale was wrong. `lib.rs` and+ `apps/lightcraft/src/main.rs` now use `ViewportInfo::visible()`; §4.1/§4.2 above are corrected.+- **P3.1**: `import::tick` is gated by `current_pass_index() == 0` (once per host frame, and once+ per hidden logic tick), not by a wall-clock throttle. The wall-clock comment was false.+- **P3.2**: the app retains the host's last `RawInput::max_texture_side` (default 16 384) and reports+ “no usable surface” and “over the host's per-side texture limit” as distinct admission errors.+- **P3.3**: screenshot encoding no longer makes the extra flat RGBA `Vec` copy; `Rgba8::from_pixels`+ fills the image's own buffer once. `MAX_SHOT_WORKING_SET_BYTES` documents the bound: reserved+ images (≤ 256 MiB) + one `Rgba8` copy + encoded PNG (each ≤ 128 MiB) + 64 KiB zlib/framing slack.+ Encoding stays on the UI thread, one image at a time. The MCP layer's decode/base64 transient is+ outside the app process path and remains bounded by its own 1600 px default.+- **P3.4**: `apps/lightcraft-web/src/bench.rs` now measures `first_frame_ms` and `thumbs_done_ms`+ from `WebApp` construction (`monotonic_ms()` origin), not navigation start. Old+ `lightcraft-bench` samples are therefore not comparable; record the origin with every sample.+ `web.rs`'s “first UI frame at perf_now()” log is a different origin in the same file and is+ diagnostic only.+- **P3.5**: `Headless::step` no longer carries a second `ViewportCommand::Screenshot` completion+ arm; `HeadlessView::run` is the only headless completion point.+- **P4**: the AccessKit language is cached instead of allocating through `Context::language()` on+ every logic pass; the wasm drop branch names `WebApp` as the queue consumer; the legacy panel+ eviction comment now says the old keys are unreachable anyway and only keeps egui memory tidy,+ with a test that the four legacy keys are removed and the parent-salted keys survive.++Still open from the review: P3.3's MCP decode/base64 transient (documented, not reserved), the+web `RequestPaintWhileHidden` gap, #8748/#8763/E21b/W15P/W27, strict kittest findings, and all+runtime/visual/performance acceptance. The tests above are deterministic source oracles, not+runtime evidence.++## Review-test repairs — 2026-10-24 (source only)++The managed review-test job `egui037-lightcraft-candidate-20261024-review-tests-13` reported+1155 library passes, 106 failures, 4 ignored, plus 7 of 8 integration tests and the shutdown test+passing. Grouping the failures gave two root causes, repaired here without relaxing a check:++- **Gesture delivery re-checked its own effect.** `reply_delivered_gestures` compared the+ admission-time view/document/dialog/panel snapshot again after the batch had been consumed. Every+ click or key whose purpose is to change that state (opening a dialog, leaving the grid, closing a+ dialog, selecting another photo) was answered with “changed before delivery” although the input+ had done its job. Delivery now requires only that a completed, nondiscarded pass consumed the+ batch. Freshness stays fail-closed twice: at resolution (a later completed layout must match the+ admission snapshot) and in `drop_gestures_stale_before_injection` immediately before a waiting+ gesture's first batch is injected, so a hidden logic tick cannot retarget it; later batches of+ the same gesture may see its own partial effect, and a concurrently queued gesture is checked+ when its events reach the head. A changed snapshot before the fresh layout still cancels, and a+ stale pre-injection batch is cleared and answered with an error.+- **Unlabelled dropdowns.** egui 0.37's `ComboBox::from_id_salt` publishes the selected text as the+ node's value but no accessible name, and kittest 0.37's strict accessibility check rejects it.+ `widgets::name_combo` now gives every dropdown a semantic label (copyright status, keyword set,+ proof profile, denoise limit, smart-album match/field/operator/value, export/contact-sheet/import/+ settings/credits/print dropdowns), so no strict check was disabled.++One lifecycle test assumed the app opened in the photo grid while `UiState` defaults to Detail, so+its “view changed” setup was a no-op; it now changes to PhotoGrid explicitly. New regression tests+cover a delivered gesture that opens a dialog (stays `ok`) and a view change between resolution and+injection (answers once with `canceled` and injects nothing).++No build, test, fmt, clippy, GUI, browser, Windows or performance run was made for this amendment;+the parent runs the managed jobs. The 106 failures and the ComboBox finding are the only failures+inspected in that output; any further finding is reported separately rather than folded in here.diff --git a/packaging/fonts.sh b/packaging/fonts.shindex 4f307d450..cab0e4350 100644--- a/packaging/fonts.sh+++ b/packaging/fonts.sh@@ -10,7 +10,7 @@ prepare_fonts() {if [[ -z "${CRAFT_FONTS_DIR:-}" ]] && [[ ! -e "$font_dir" ]]; then# Same revision as release.yml. Never update or reset an existing checkout.- local revision=3d9ab3a132ed0eff457e424226a435a901da30d3+ local revision=b076417b5880bd4154bd22f00695b1d28c6bea83echo "==> downloading craft-fonts ($revision) to $font_dir"if ! git clone --no-checkout https://github.com/storytold/craft-fonts "$font_dir" ||! git -C "$font_dir" checkout --detach "$revision"; thendiff --git a/packaging/linux/package.sh b/packaging/linux/package.shindex 6c65948ec..d42fc5fd3 100755--- a/packaging/linux/package.sh+++ b/packaging/linux/package.sh@@ -121,7 +121,6 @@ if has appimage; thenesacAPPDIR="$WORK/LightCraft.AppDir"cp -R "$STAGE" "$APPDIR"- mv "$APPDIR/usr/share/doc" "$WORK/doc-unused"ln -s usr/bin/lightcraft "$APPDIR/AppRun"cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop"cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png"diff --git a/packaging/windows/fonts.ps1 b/packaging/windows/fonts.ps1index 74f383fd8..6d22053fe 100644--- a/packaging/windows/fonts.ps1+++ b/packaging/windows/fonts.ps1@@ -6,7 +6,7 @@ function Initialize-CraftFonts([string] $WorkspaceRoot) {if (-not $env:CRAFT_FONTS_DIR -and -not (Test-Path -LiteralPath $fontDir)) {# Same revision as release.yml and packaging/fonts.sh. Existing checkouts stay untouched.- $revision = '3d9ab3a132ed0eff457e424226a435a901da30d3'+ $revision = 'b076417b5880bd4154bd22f00695b1d28c6bea83'Write-Output "==> downloading craft-fonts ($revision) to $fontDir"& git clone --no-checkout https://github.com/storytold/craft-fonts $fontDirif ($LASTEXITCODE -ne 0) { throw 'Could not download craft-fonts; provide a complete checkout with CRAFT_FONTS_DIR' }