LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
Migrate LightCraft to egui 0.37 and reconcile dependency and font locks
skylartaylorc057ccc23f0b
diff --cc Cargo.lockindex 8eab2b93f,78de058c3..4c745676a--- a/Cargo.lock+++ b/Cargo.lock@@@ -1085,7 -1089,7 +1085,7 @@@ source = "git+https://github.com/storyt[[package]]name = "craft-ui"version = "0.1.0"- source = "git+https://github.com/storytold/craft-libs?rev=c488caa9fbc2fb1a86e4674887e9b80b598ebbfa#c488caa9fbc2fb1a86e4674887e9b80b598ebbfa"-source = "git+https://github.com/storytold/craft-libs?rev=5c874d51eeb3de70e735c8ce87a59a7dedd47675#5c874d51eeb3de70e735c8ce87a59a7dedd47675"++source = "git+https://github.com/storytold/craft-libs?rev=25da1314d443171b4adeaad2cd9454b273f35c6f#25da1314d443171b4adeaad2cd9454b273f35c6f"dependencies = ["egui","serde",@@@ -1346,8 -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"++source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"dependencies = ["bytemuck","emath",@@@ -1379,8 -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"++source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"dependencies = ["ahash","bytemuck",@@@ -1415,8 -1420,9 +1415,8 @@@[[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"++source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"dependencies = ["accesskit","ahash",@@@ -1434,8 -1440,9 +1434,8 @@@[[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"++source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"dependencies = ["ahash","bytemuck",@@@ -1453,8 -1460,9 +1453,8 @@@[[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"++source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"dependencies = ["accesskit_winit","arboard",@@@ -1478,8 -1481,9 +1478,8 @@@[[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"++source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"dependencies = ["bytemuck","egui",@@@ -1491,8 -1495,9 +1491,8 @@@[[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"++source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"dependencies = ["dify","eframe",@@@ -1538,8 -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"++source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"dependencies = ["bytemuck",]@@@ -1585,8 -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"++source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"dependencies = ["ahash","bytemuck",@@@ -1611,8 -1616,9 +1611,8 @@@[[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"++source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"[[package]]name = "equator"@@@ -6933,7 -6860,8 +6925,7 @@@ checksum = "d6bbff5f0aada427a1e5a6da5f1[[package]]name = "winit"version = "0.30.13"- source = "git+https://github.com/storytold/winit.git?rev=ae48c756a3b81125eb796c0cc6dccf60990d1181#ae48c756a3b81125eb796c0cc6dccf60990d1181"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d"++source = "git+https://github.com/storytold/winit.git?rev=a517b3846ee8457d84ee4975110bfda6797c44dc#a517b3846ee8457d84ee4975110bfda6797c44dc"dependencies = ["ahash","android-activity",@@@ -7415,23 -7325,3 +7407,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"++source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"++[[patch.unused]]+name = "egui_extras"+version = "0.37.0"- source = "git+https://github.com/storytold/egui.git?rev=173cc7375d35dc5fbc5b5d0994fdf787f547c5d1#173cc7375d35dc5fbc5b5d0994fdf787f547c5d1"++source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"++[[patch.unused]]+name = "egui_inspection"+version = "0.37.0"- source = "git+https://github.com/storytold/egui.git?rev=173cc7375d35dc5fbc5b5d0994fdf787f547c5d1#173cc7375d35dc5fbc5b5d0994fdf787f547c5d1"++source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"++[[patch.unused]]+name = "egui_system_font_provider"+version = "0.37.0"- source = "git+https://github.com/storytold/egui.git?rev=173cc7375d35dc5fbc5b5d0994fdf787f547c5d1#173cc7375d35dc5fbc5b5d0994fdf787f547c5d1"++source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"diff --cc Cargo.tomlindex aca12d197,c22395b8a..76a6ad78d--- a/Cargo.toml+++ b/Cargo.toml@@@ -10,7 -10,7 +10,7 @@@ rust-version = "1.95repository = "https://github.com/storytold/lightcraft"[workspace.dependencies]- craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c488caa9fbc2fb1a86e4674887e9b80b598ebbfa", features = ["serde"] }-craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "5c874d51eeb3de70e735c8ce87a59a7dedd47675", features = ["serde"] }++craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "25da1314d443171b4adeaad2cd9454b273f35c6f", features = ["serde"] }craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "82a24b006eefa036b43c09a67fb9a3fbd17ffe63" }# internallightcraft-denoise-core = { path = "crates/denoise-core" }@@@ -172,21 -169,3 +172,21 @@@ jpeg-decoder = { opt-level = 3jpeg-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" }++ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }++emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }++epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }++epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }++egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }++egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }++egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }++egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }++egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }++egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }++egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }++eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }++egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }++egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }++winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }diff --cc NOTICEindex 8b16eeba0,8b16eeba0..c18729355--- a/NOTICE+++ b/NOTICE@@@ -50,11 -50,11 +50,15 @@@ maintainer decision. The ONNX reader anno darktable, RawSpeed, LibRaw or other GPL decoder/runtime code is included.Builds made with craft-fonts (the optional CRAFT_FONTS_DIR build input; all official releases)--also embed the fonts listed in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md--(BIZ UDPGothic, BIZ UDMincho, Shippori Mincho, Noto Sans CJK SC, Noto Sans Arabic and Noto Sans--Thai), under the SIL Open Font License 1.1. The web build embeds BIZ UDPGothic Regular and Noto--Sans Thai Regular, and loads Noto Sans CJK SC separately. Release packages include each font's--licence as OFL-<family>.txt; Windows installers include their texts in FONT-LICENCES.txt.++also embed the default fonts listed in++https://github.com/storytold/craft-fonts/blob/b076417b5880bd4154bd22f00695b1d28c6bea83/ATTRIBUTION.md (BIZ UDPGothic, BIZ UDMincho,++Shippori Mincho, Noto Sans CJK SC, Noto Sans Arabic, Noto Sans Thai, Noto Sans Georgian,++NanumGothic, Noto Sans Symbols, Noto Sans Symbols 2, Noto Sans Hebrew and++Noto Sans Devanagari), under the SIL Open Font License 1.1. The opt-in LXGW WenKai Lite face++(fonts/simplified-chinese-manifest.txt in craft-fonts) is not embedded. The web build embeds++BIZ UDPGothic Regular, Noto Sans Thai Regular and Noto Sans Georgian Regular, and loads Noto Sans++CJK SC separately. Release packages include each font's licence as OFL-<family>.txt; Windows++installers include their texts in FONT-LICENCES.txt.Place names for reverse geocoding (Photo > Fill Location from GPS) are not part of LightCraft andare never distributed with it. On the user's request (Photo > Download Place Names) the app@@@ -62,3 -62,3 +66,21 @@@ downloads cities15000.zip, admin1CodesA(https://download.geonames.org/export/dump/) into the settings folder. GeoNames data is licensedunder Creative Commons Attribution 4.0 (https://creativecommons.org/licenses/by/4.0/);attribution: "GeoNames, geonames.org". The lookup code (crates/geocode) is our own.++++++The UI's egui-icons.ttf subset and emoji-icon-font.ttf fallback are provided by epaint_default_fonts++and registered through egui's default font definitions. They derive from emoji-icon-font by++John Slegers, under the MIT License. The subset and full face share the following upstream notice.++Source: https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts++Original: https://github.com/jslegers/emoji-icon-font++The following text is reproduced verbatim from emoji-icon-font-mit-license.txt:++++MIT License++++Copyright (c) 2014 John Slegers++++Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:++++The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.++++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.diff --cc apps/lightcraft-web/src/web.rsindex 4f8059c53,827b367f8..656f8645d--- a/apps/lightcraft-web/src/web.rs+++ b/apps/lightcraft-web/src/web.rs@@@ -509,17 -515,21 +518,23 @@@ 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();+ // a dialog is on screen (the card said so while the files hovered): nothing is read or imported+ // (files read from an earlier drop still finish below)+ if !dropped.is_empty() && self.app.ui.dialog.is_some() {+ self.app.toast(ctx, lightcraft_ui_egui::i18n::tr("Close the open dialog, then drop the files again"));+ return;+ }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}"),+ Err(e) => notice(lightcraft_ui_egui::i18n::dropped_file_unreadable(&name, &e.to_string())),}});}@@@ -676,26 -712,15 +703,34 @@@ 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);+ // eframe's web runner ignores `ViewportCommand::Title`: name the open photo in the page title+ let title = self.app.page_title(self.files.is_dirty() || self.flushing.get());+ if title != self.title+ && let Some(doc) = window().and_then(|w| w.document())+ {+ doc.set_title(&title);+ self.title = title;+ }+ // 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 --cc assets/ATTRIBUTION.mdindex 30eea5654,30eea5654..3bb745457--- a/assets/ATTRIBUTION.md+++ b/assets/ATTRIBUTION.md@@@ -8,6 -8,6 +8,7 @@@ covers a whole directory), or if a lice| Path | Asset | Creator | Source | Licence | Added | Modifications ||---|---|---|---|---|---|---|++| `epaint_default_fonts::EGUI_ICONS`, `epaint_default_fonts::EMOJI_ICON` (dependency font inputs) | egui icon subset and monochrome fallback | John Slegers | [egui 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [emoji-icon-font](https://github.com/jslegers/emoji-icon-font) | MIT (Copyright (c) 2014 John Slegers; full upstream text in `NOTICE`) | 2026-10-24 (notice audit) | egui-icons.ttf is the five-glyph subset; emoji-icon-font.ttf is the full fallback. Registered by production default font definitions; dependency assets unmodified here, no font file copied into this repository. || `assets/fonts/Inter-*.ttf` (Regular, Medium, SemiBold) | Inter | Rasmus Andersson | https://github.com/rsms/inter | SIL Open Font License 1.1 (`assets/fonts/OFL-Inter.txt`) | 2026-09-30 | none || `assets/app-icon/` (`lightcraft.svg` and the PNG/ICNS/ICO/SVG files derived from it) | LightCraft app icon (lynx) | LightCraft project owner (drawn in ArtCraft) | original work (vectorised from the owner's drawing; see `assets/app-icon/README.md`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | 2026-10-02 | vectorised to SVG; rendered to PNG/ICNS/ICO by `packaging/icons.sh` || `assets/camera-profiles/*.json` | Camera colour profiles (matrix + hue/saturation/value table), built into LightCraft | ILCE-7M4: Harald Hoyer | original work: fitted by `lightcraft-cli calibrate` to the contributor's own raw photos and their in-camera JPEGs (597 ILCE-7M4 photos, 2026); aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-07 | none |@@@ -29,7 -29,7 +30,7 @@@| `docs/images/*-blue-marble.jpg`, `docs/images/grid-pd.jpg` | "The Blue Marble" (AS17-148-22727) | NASA, Apollo 17 crew (1972) | https://commons.wikimedia.org/wiki/File:The_Earth_seen_from_Apollo_17.jpg | Public domain (NASA) | 2026-09-30 | developed in LightCraft; shown inside app screenshots || `docs/images/*.jpg` (UI) | LightCraft application screenshots | LightCraft contributors | original work (captured with `docs/showcase/`) | MIT OR Apache-2.0 | 2026-09-30 | n/a || `docs/brand/` (artcraft-logo and artcraft-mark, SVG and PNG) | ArtCraft wordmark and mark | ArtCraft Team | original work (https://getartcraft.com/) | ArtCraft trademark, see `docs/brand/LICENSE-brand.txt` (not open source) | 2026-10-01 | none |--| craft-fonts: optional build input, not files in this repository | BIZ UDPGothic (Regular, Bold), BIZ UDMincho Regular, Shippori Mincho Regular, Noto Sans CJK SC Regular, Noto Sans Arabic Regular, Noto Sans Thai Regular | The Noto Project Authors (Arabic and Thai); Morisawa Inc. / The BIZ UDGothic and BIZ UDMincho Project Authors; The Shippori Mincho Project Authors; Google and Adobe (Noto Sans CJK, maintainer-approved exception; see AGENTS.md) (per craft-fonts' attribution) | https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md | SIL Open Font License 1.1 (each font's OFL.txt in craft-fonts; release packages ship it as OFL-<family>.txt) | 2026-10-06 | none; native builds made with `CRAFT_FONTS_DIR` embed the manifest fonts (all official releases); the web build embeds BIZ UDPGothic Regular and Noto Sans Thai Regular and ships Noto Sans CJK SC Regular as a separate font file |++| craft-fonts: optional build input, not files in this repository | BIZ UDPGothic (Regular, Bold), BIZ UDMincho Regular, Shippori Mincho Regular, Noto Sans CJK SC Regular, Noto Sans Arabic Regular, Noto Sans Thai Regular, Noto Sans Georgian Regular, NanumGothic Regular, Noto Sans Symbols Regular, Noto Sans Symbols 2 Regular, Noto Sans Hebrew Regular, Noto Sans Devanagari Regular | The Noto Project Authors (Arabic, Thai, Georgian, Symbols, Symbols 2, Hebrew and Devanagari); Morisawa Inc. / The BIZ UDGothic and BIZ UDMincho Project Authors; The Shippori Mincho Project Authors; NHN Corporation and Sandoll Communications (NanumGothic); Google and Adobe (Noto Sans CJK, maintainer-approved exception; see AGENTS.md) (per craft-fonts' attribution) | https://github.com/storytold/craft-fonts/blob/b076417b5880bd4154bd22f00695b1d28c6bea83/ATTRIBUTION.md | SIL Open Font License 1.1 (each font's OFL.txt in craft-fonts; release packages ship it as OFL-<family>.txt) | 2026-10-06 | none; native builds made with `CRAFT_FONTS_DIR` embed the default `fonts/manifest.txt` set (all official releases; the opt-in LXGW WenKai Lite face in `fonts/simplified-chinese-manifest.txt` is not embedded); the web build embeds BIZ UDPGothic Regular, Noto Sans Thai Regular and Noto Sans Georgian Regular and ships Noto Sans CJK SC Regular as a separate font file || `crates/ui-egui/locales/uk.json`, `crates/ui-egui/locales/uk-formats.json` | Ukrainian interface catalogs | @dmatviichuk with Codex; PhotoCraft, FilmCraft and VectorCraft translation contributors for reused labels | original translations from English source; 337 initial English-key matches reviewed from [PhotoCraft 69c41f3](https://github.com/storytold/photocraft/blob/69c41f3523e147eb215da8c7b4c29b18b35d1c63/crates/ui-egui/src/i18n/uk.tsv), [FilmCraft 4854c27](https://github.com/storytold/filmcraft/blob/4854c277536fe8118257362304b6a7d82d8e704b/crates/ui-egui/src/i18n/uk.tsv), [VectorCraft 4b44265](https://github.com/storytold/vectorcraft/blob/4b44265965fdd6ffedfd6182a892c1a6c360d344/crates/ui-egui/src/i18n/uk.tsv) | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`, also the source repositories' licences) | 2026-10-09 | adapted to LightCraft photo-development context, completed catalogs, reviewed spelling and placeholders || `crates/ui-egui/locales/cs.json`, `crates/ui-egui/locales/cs-formats.json` | Czech interface catalogs | @Losminek with AI assistance (Codex) | original work: translations of English source phrases, reviewed against the app UI conventions; no external translation material | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 2026-10-11 | catalog coverage, Czech dates and count-neutral wording; independent scope/terminology review; native-speaker proofreading pending || `crates/ui-egui/locales/it.json`, `crates/ui-egui/locales/it-formats.json` | Italian interface catalogs | @GabrielePecchioli with Claude Code; PhotoCraft, VectorCraft, PdfCraft and WordCraft translation contributors for reused labels | original translations from English source; 410 initial English-key matches reviewed from [PhotoCraft da3da09](https://github.com/storytold/photocraft/blob/da3da0942c14c1159f40c652afcf33584332c733/crates/ui-egui/src/i18n/it.tsv), [VectorCraft 5432821](https://github.com/storytold/vectorcraft/blob/543282148007bcb5633c493a5374cd26b0339c8d/crates/ui-egui/src/i18n/it.tsv), [PdfCraft e8e275c](https://github.com/storytold/pdfcraft/blob/e8e275cbd40ccd0dc6b56f82b16a575571043702/crates/ui-egui/src/i18n/it.tsv) and the Italian WordCraft catalog ([storytold/wordcraft#598](https://github.com/storytold/wordcraft/pull/598)); 46 of them retranslated where the sibling's meaning didn't fit a photo app | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`, also the source repositories' licences) | 2026-10-12 | adapted to LightCraft photo-development context, count-neutral labels for Italian plural agreement, reviewed placeholders |diff --cc crates/ui-egui/src/button.rsindex 5ada0b038,4e23f1c16..ee397a78c--- a/crates/ui-egui/src/button.rs+++ b/crates/ui-egui/src/button.rs@@@ -331,9 -341,23 +341,23 @@@ impl<'a> Button<'a>};// a button in a disabled part of the window is disabled toolet enabled = self.enabled && ui.is_enabled();- let resp = ui.interact(rect, id, if enabled { Sense::click() } else { Sense::hover() });+ let resp = ui.interact(+ rect,+ id,+ if !enabled {+ Sense::hover()+ } else if self.busy {+ // still reachable by the keyboard, but nothing to press+ Sense::focusable_noninteractive()+ } else {+ Sense::click()+ },+ );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 self.busy {+ ui.ctx().accesskit_node_builder(resp.id, |node| node.set_busy());+ }if let Some(w) = &self.widget {crate::widgets::register(ui.ctx(), w.clone(), rect);}diff --cc crates/ui-egui/src/control.rsindex f52589a7d,7e04f1356..e53b02ad1--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@@ -227,13 -217,145 +227,30 @@@ pub fn handle(app: &mut LightcraftApp,app.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.dropFiles" => {+ // every entry must be a string: a script is not told `ok` for a part of what it sent+ let Some(paths) =+ p.get("paths").and_then(Value::as_array).and_then(|a| a.iter().map(|v| v.as_str().map(str::to_string)).collect::<Option<Vec<_>>>())+ else {+ return err("ui.dropFiles: paths must be an array of strings");+ };+ if p.get("hover").and_then(Value::as_bool).unwrap_or(false) {+ app.drop_hover = paths;+ } else {+ // the drag ends with the drop, as it does for the OS+ app.drop_hover.clear();+ app.drop_pending = paths;+ }+ 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() {diff --cc crates/ui-egui/src/drop_overlay.rsindex 000000000,0e4825988..501b99903mode 000000,100644..100644--- a/crates/ui-egui/src/drop_overlay.rs+++ b/crates/ui-egui/src/drop_overlay.rs@@@ -1,0 -1,99 +1,99 @@@+ //! What dropping the files dragged over the window will do: the same sorting the drop applies,+ //! shown on a veil over the whole window while the drag lasts.++ use egui::{Align2, Color32, Context, Order, Rect, Stroke, StrokeKind, vec2};++ use crate::LightcraftApp;+ use crate::theme::Tokens;++ /// Dropped paths by what becomes of them.+ #[derive(Default, Debug, PartialEq)]+ pub struct Sorted {+ /// Face models (`.onnx`): the first opens the licence dialog.+ pub models: Vec<String>,+ /// Preset files: imported as presets.+ pub presets: Vec<String>,+ /// Everything else: photos and folders, for the import.+ pub photos: Vec<String>,+ }++ /// Sort `paths` as a drop does.+ pub fn classify(paths: Vec<String>) -> Sorted {+ let (models, rest): (Vec<String>, Vec<String>) = paths.into_iter().partition(|p| crate::is_model_file(p));+ let (presets, photos) = crate::split_presets(rest);+ Sorted { models, presets, photos }+ }++ /// The lines the card shows for files hovering over the window (`unknown`: how many have no path+ /// to look at, as on some platforms and in browsers), for the current settings.+ fn lines(app: &LightcraftApp, paths: Vec<String>, unknown: bool) -> Vec<String> {+ if app.ui.dialog.is_some() {+ return vec![crate::i18n::tr("Close the open dialog to drop files here").to_string()];+ }+ let drop = classify(paths);+ let mut out = Vec::new();+ if !drop.models.is_empty() {+ out.push(crate::i18n::tr("Drop to open the face model").to_string());+ }+ let plural = |n: usize| if n == 1 { "" } else { "s" };+ // no library open yet (desktop: the web build's drops import into its session as before):+ // photos wait for the library chosen, presets are refused (the drop handler does the same)+ let waiting = crate::panels::library_problem::holds_drops(app) && !cfg!(target_arch = "wasm32");+ if !drop.presets.is_empty() && waiting {+ out.push(crate::i18n::tr("Open a library first, then drop the presets again").to_string());+ } else if !drop.presets.is_empty() {+ let n = drop.presets.len();+ out.push(crate::i18n::tr_format!("Drop to import {n} preset{}", plural(n), n = n));+ }+ if !drop.photos.is_empty() && waiting {+ out.push(crate::i18n::tr("The photos are imported once a library is open").to_string());+ } else if !drop.photos.is_empty() && app.lightroom.is_some() && !cfg!(target_arch = "wasm32") {+ // the drop is refused while a Lightroom catalog import owns the catalog+ out.push(crate::i18n::tr("Finish Lightroom catalog import before adding photos").to_string());+ } else if !drop.photos.is_empty() && crate::import::running(app) && !cfg!(target_arch = "wasm32") {+ out.push(crate::i18n::tr("An import is running. Drop photos when it has finished").to_string());+ } else if !drop.photos.is_empty() {+ let n = drop.photos.len();+ // the web build has no review to open: its drops import at once+ if app.ui.settings.import_dropped_directly || cfg!(target_arch = "wasm32") {+ out.push(crate::i18n::tr_format!("Drop to import {n} item{}", plural(n), n = n));+ } else {+ out.push(crate::i18n::tr_format!("Drop to review {n} item{} for import", plural(n), n = n));+ }+ }+ if out.is_empty() || unknown {+ out.push(crate::i18n::tr("Drop to import").to_string());+ }+ out+ }++ /// Veil and card while files are dragged over the window.+ pub fn show(app: &LightcraftApp, ctx: &Context) {+ let count = ctx.input(|i| i.raw.hovered_files.len());+ if count == 0 {+ return;+ }+ let known: Vec<String> = ctx.input(|i| {+ i.raw.hovered_files.iter().filter_map(|f| f.path.as_ref()).map(|p| p.to_string_lossy().to_string()).filter(|p| !p.is_empty()).collect()+ });+ let lines = lines(app, known.clone(), known.len() < count);+ let t = Tokens::get(ctx);+ let screen = ctx.content_rect();- let painter = ctx.layer_painter(egui::LayerId::new(Order::Tooltip, egui::Id::new("drop-overlay")));++ let painter = ctx.layer_painter(egui::LayerId::new(Order::Tooltip, egui::Id::unique("drop-overlay")));+ painter.rect_filled(screen, 0.0, Color32::from_black_alpha(150));+ painter.rect_stroke(screen.shrink(10.0), 12.0, Stroke::new(2.0, t.accent), StrokeKind::Inside);+ let galleys: Vec<_> = lines.into_iter().map(|l| painter.layout(l, t.semibold(18.0), t.text, (screen.width() - 120.0).max(200.0))).collect();+ let (w, h) = galleys.iter().fold((0.0f32, 0.0f32), |(w, h), g| (w.max(g.size().x), h + g.size().y + 8.0));+ let card = Rect::from_center_size(screen.center(), vec2(w + 64.0, h + 40.0));+ painter.rect_filled(card, 10.0, t.chrome);+ painter.rect_stroke(card, 10.0, Stroke::new(1.0, t.accent), StrokeKind::Inside);+ let mut y = card.top() + 24.0;+ for g in galleys {+ let at = egui::pos2(card.center().x, y);+ let height = g.size().y;+ painter.galley(Align2::CENTER_TOP.anchor_size(at, g.size()).min, g, t.text);+ y += height + 8.0;+ }+ crate::widgets::register(ctx, "dropOverlay", card);+ ctx.request_repaint();+ }diff --cc crates/ui-egui/src/frame_rate.rsindex 000000000,62132744a..69424e958mode 000000,100644..100644--- a/crates/ui-egui/src/frame_rate.rs+++ b/crates/ui-egui/src/frame_rate.rs@@@ -1,0 -1,312 +1,312 @@@+ //! Help ▸ Debug ▸ Frame Rate (`view.frameRate`; `LIGHTCRAFT_FPS=1` starts with it on): a+ //! frame-rate display in the window's top-right corner, to watch how a slider drag or a zoom holds+ //! up. It shows where a frame's time goes: the UI+ //! thread's CPU time (layout, painting, texture uploads) and the rest of the frame interval, which+ //! is waiting — for vsync, or for the GPU when render work is ahead of the window's frame. A+ //! tick over the graph marks each frame in which a render arrived, so spikes can be put next to+ //! renders. While it shows, the window repaints continuously, so the rate is the one a drag gets.++ use std::collections::VecDeque;++ use crate::LightcraftApp;+ use crate::render::Slot;++ /// Frames kept for the graph (about two seconds at 120 Hz).+ const KEEP: usize = 240;++ /// A gap between frames longer than this is a pause (window hidden or occluded, the machine+ /// asleep), not a frame: the display starts counting again instead of showing it as a spike.+ const PAUSE: f64 = 2.0;++ #[derive(Clone, Copy)]+ pub(crate) struct Frame {+ at: f64,+ /// Seconds since the previous frame.+ pub(crate) dt: f64,+ /// The previous frame's CPU time on the UI thread, seconds.+ cpu: f64,+ /// Renders that arrived this frame.+ renders: u64,+ /// Of those, thrown away (superseded by a newer request).+ discarded: u64,+ }++ /// The display's state, kept in the context's temp data (one per window or headless view) and+ /// dropped while the display is off, so turning it back on starts a fresh count.+ #[derive(Clone, Default)]+ struct Hud {+ last: Option<f64>,+ completed: u64,+ discarded: u64,+ frames: VecDeque<Frame>,+ /// When the numbers were last logged.+ logged: Option<f64>,+ }++ fn hud_id() -> egui::Id {- egui::Id::new("fps-hud-state")++ egui::Id::unique("fps-hud-state")+ }++ /// The display is off: drop its state, so the time it was off never shows as one long frame.+ pub(crate) fn forget(ctx: &egui::Context) {+ ctx.data_mut(|d| d.remove::<Hud>(hud_id()));+ }++ /// Record a frame at `now` (`completed`/`discarded`: the renderer's running totals; `cpu`: the+ /// previous frame's UI CPU time, seconds). Returns the frames kept for the display, and whether+ /// the numbers are due in the log (once a second; A/B runs read them).+ fn record(ctx: &egui::Context, now: f64, completed: u64, discarded: u64, cpu: f64) -> (Vec<Frame>, bool) {+ ctx.data_mut(|d| {+ let hud = d.get_temp_mut_or_default::<Hud>(hud_id());+ match hud.last {+ Some(prev) if now - prev > PAUSE || now < prev => hud.frames.clear(),+ Some(prev) => {+ let renders = completed.saturating_sub(hud.completed);+ let thrown = discarded.saturating_sub(hud.discarded);+ hud.frames.push_back(Frame { at: now, dt: (now - prev).max(1e-6), cpu, renders, discarded: thrown });+ while hud.frames.len() > KEEP {+ hud.frames.pop_front();+ }+ }+ None => {}+ }+ hud.last = Some(now);+ hud.completed = completed;+ hud.discarded = discarded;+ let log = hud.logged.is_none_or(|t| now - t >= 1.0 || now < t);+ if log {+ hud.logged = Some(now);+ }+ (hud.frames.iter().copied().collect(), log)+ })+ }++ /// The frames the display holds now (tests).+ #[cfg(test)]+ pub(crate) fn frames(ctx: &egui::Context) -> Vec<Frame> {+ ctx.data_mut(|d| d.get_temp::<Hud>(hud_id())).map(|h| h.frames.into_iter().collect()).unwrap_or_default()+ }++ fn mb(bytes: u64) -> f64 {+ bytes as f64 / (1 << 20) as f64+ }++ /// Count this frame and draw the display over everything.+ pub fn show(ctx: &egui::Context, app: &LightcraftApp) {+ let now = ctx.input(|i| i.time);+ let cpu = app.perf.host_frame_ms.unwrap_or(0.0) / 1e3;+ let (frames, log) = record(ctx, now, app.renderer.completed, app.renderer.discarded, cpu);++ let recent: Vec<&Frame> = frames.iter().filter(|f| now - f.at <= 1.0).collect();+ let fps_now = frames.last().map_or(0.0, |f| 1.0 / f.dt);+ let worst = recent.iter().copied().max_by(|a, b| a.dt.total_cmp(&b.dt));+ let avg_fps = if recent.is_empty() { 0.0 } else { recent.len() as f64 / recent.iter().map(|f| f.dt).sum::<f64>().max(1e-6) };+ let slow = recent.iter().filter(|f| f.dt > 1.0 / 50.0).count();+ let renders_s: u64 = recent.iter().map(|f| f.renders).sum();+ let discarded_s: u64 = recent.iter().map(|f| f.discarded).sum();+ let window = app.renderer.textures.get(&Slot::Region);+ let mem = lightcraft_engine::gpu::memory();+ // (`ready` first: `available` would wait for a device still being created)+ let device = match lightcraft_engine::gpu::unavailable_reason() {+ Some(why) => format!("off ({why})"),+ None if lightcraft_engine::gpu::ready() && lightcraft_engine::gpu::available() => {+ lightcraft_engine::gpu::adapter_name().unwrap_or_else(|| "on".into())+ }+ None => "starting…".into(),+ };+ if log {+ let (wdt, wcpu) = worst.map_or((0.0, 0.0), |w| (w.dt * 1e3, w.cpu * 1e3));+ let p95 = {+ let mut d: Vec<f64> = recent.iter().map(|f| f.dt * 1e3).collect();+ d.sort_by(f64::total_cmp);+ d.get(d.len().saturating_sub(1) * 95 / 100).copied().unwrap_or(0.0)+ };+ log::info!(+ "fps-hud: frames {} slow>20ms {slow} p95 {p95:.1} worst {wdt:.1} (cpu {wcpu:.1}) renders {renders_s} discarded {discarded_s} window {:.1} gpu {device}",+ recent.len(),+ window.map_or(0.0, |t| t.ms)+ );+ }+ let lines = [+ format!("{fps_now:>4.0} fps avg {avg_fps:.0} {slow} frames > 20 ms in 1 s"),+ match worst {+ Some(w) => format!("worst {:.1} ms = CPU {:.1} + wait {:.1}", w.dt * 1e3, w.cpu * 1e3, (w.dt - w.cpu).max(0.0) * 1e3),+ None => "worst –".to_string(),+ },+ format!("UI CPU {:.1} ms (update {:.1})", app.perf.host_frame_ms.unwrap_or(0.0), app.perf.update_ms),+ format!("render frame {:.1} ms", app.renderer.last_main_ms),+ match window {+ Some(t) => format!("render window {:.1} ms", t.ms),+ None => "render window –".to_string(),+ },+ format!("renders: {} queued, {} running, {renders_s}/s ({discarded_s} thrown away)", app.renderer.queued(), app.renderer.in_flight()),+ format!("GPU: {device}"),+ format!("GPU mem {:.0} MB (+{:.0} pooled)", mb(mem.allocated), mb(mem.pooled)),+ ];++ let screen = ctx.content_rect();+ let width = 300.0;- egui::Area::new(egui::Id::new("fps-hud"))++ egui::Area::new(egui::Id::unique("fps-hud"))+ .order(egui::Order::Tooltip)+ .fixed_pos(egui::pos2(screen.right() - width - 24.0, screen.top() + 56.0))+ .interactable(false)+ .show(ctx, |ui| {+ egui::Frame::new().fill(egui::Color32::from_black_alpha(210)).corner_radius(6.0).inner_margin(8.0).show(ui, |ui| {+ ui.set_width(width);+ ui.spacing_mut().item_spacing.y = 1.0;+ for l in &lines {+ ui.label(egui::RichText::new(l).monospace().size(11.0).color(egui::Color32::from_gray(230)));+ }+ ui.add_space(4.0);+ graph(ui, &frames, width);+ ui.label(+ egui::RichText::new("bars: blue = UI CPU, orange/red = waiting · ticks = a render arrived · line = 60 fps")+ .size(9.0)+ .color(egui::Color32::from_gray(160)),+ );+ });+ });+ // a rate the drag gets, not the idle one+ ctx.request_repaint();+ }++ /// Frame intervals, 0 at the bottom and 50 ms at the top: the UI thread's CPU part in blue and+ /// the waiting part above it (green within 60 fps, orange within 30, red beyond), with a tick+ /// over each frame in which a render arrived.+ fn graph(ui: &mut egui::Ui, frames: &[Frame], width: f32) {+ let (rect, _) = ui.allocate_exact_size(egui::vec2(width, 70.0), egui::Sense::hover());+ let p = ui.painter_at(rect);+ let plot = egui::Rect::from_min_max(egui::pos2(rect.left(), rect.top() + 6.0), rect.max);+ let y = |ms: f64| plot.bottom() - (ms / 50.0).clamp(0.0, 1.0) as f32 * plot.height();+ let w = rect.width() / KEEP as f32;+ let start = KEEP.saturating_sub(frames.len());+ for (i, f) in frames.iter().enumerate() {+ let (ms, cpu) = (f.dt * 1e3, (f.cpu * 1e3).min(f.dt * 1e3));+ let x = rect.left() + (start + i) as f32 * w;+ let bar = |from: f64, to: f64, c: egui::Color32| {+ p.rect_filled(egui::Rect::from_min_max(egui::pos2(x, y(to)), egui::pos2(x + w.max(1.0), y(from))), 0.0, c);+ };+ let wait = if ms > 33.4 {+ egui::Color32::from_rgb(230, 80, 70)+ } else if ms > 17.5 {+ egui::Color32::from_rgb(235, 160, 60)+ } else {+ egui::Color32::from_rgb(110, 190, 110)+ };+ bar(cpu, ms, wait);+ bar(0.0, cpu, egui::Color32::from_rgb(90, 150, 240));+ if f.renders > 0 {+ p.rect_filled(+ egui::Rect::from_min_max(egui::pos2(x, rect.top()), egui::pos2(x + w.max(1.0), rect.top() + 4.0)),+ 0.0,+ egui::Color32::WHITE,+ );+ }+ }+ p.hline(rect.x_range(), y(1000.0 / 60.0), egui::Stroke::new(1.0, egui::Color32::from_rgb(90, 200, 90)));+ p.hline(rect.x_range(), y(1000.0 / 30.0), egui::Stroke::new(1.0, egui::Color32::from_rgb(200, 90, 80).gamma_multiply(0.6)));+ }++ #[cfg(test)]+ mod tests {+ use std::time::Duration;++ use serde_json::json;++ use crate::headless::Headless;+ use crate::menubar::{MenuNode, menu_bar};+ use crate::{LightcraftApp, Services};++ const T: Duration = Duration::from_secs(20);++ fn set(h: &mut Headless, params: serde_json::Value) -> Option<bool> {+ let r = h.request("engine.execute", json!({"command": "view.frameRate", "params": params}), T);+ assert_eq!(r["ok"], true, "{r}");+ r["result"]["show"].as_bool()+ }++ /// The Help ▸ Debug item for it, and its checkmark.+ fn debug_item(app: &LightcraftApp) -> Option<Option<bool>> {+ let help = menu_bar(app).into_iter().find(|(t, _)| t == "Help").map(|(_, items)| items).unwrap_or_default();+ help.into_iter().find_map(|n| match n {+ MenuNode::Submenu { label, children } if label == "Debug" => children.into_iter().find_map(|c| match c {+ MenuNode::Item { id, checked, .. } if id == "view.frameRate" => Some(checked),+ _ => None,+ }),+ _ => None,+ })+ }++ /// Help ▸ Debug ▸ Frame Rate toggles the display (a checked menu item), `{show}` sets it,+ /// and frames draw with it on.+ #[test]+ fn show_frame_rate_is_a_debug_toggle() {+ let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() });+ let mut h = Headless::new(app, [1200.0, 800.0], 1.0);+ let was = h.app.ui.frame_rate;+ assert_eq!(debug_item(&h.app), Some(Some(was)), "Help ▸ Debug lists it, checked as it is");+ assert_eq!(set(&mut h, json!({})), Some(!was));+ assert_eq!(debug_item(&h.app), Some(Some(!was)));+ // frames with the display on draw (and keep the window repainting)+ assert_eq!(set(&mut h, json!({"show": true})), Some(true));+ for _ in 0..3 {+ h.step();+ }+ assert_eq!(set(&mut h, json!({"show": false})), Some(false));+ assert!(!h.app.ui.frame_rate);+ }++ fn worst_ms(h: &Headless) -> f64 {+ super::frames(&h.view.ctx).iter().map(|f| f.dt * 1e3).fold(0.0, f64::max)+ }++ /// Turned off and on again later, the display starts a fresh count: the time it was off is not+ /// one long frame (a red spike and a "worst" of the whole time off).+ #[test]+ fn turning_it_back_on_shows_no_spike_for_the_time_it_was_off() {+ let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() });+ let mut h = Headless::new(app, [1200.0, 800.0], 1.0);+ set(&mut h, json!({"show": true}));+ for _ in 0..3 {+ h.step();+ }+ assert!(!super::frames(&h.view.ctx).is_empty(), "frames are counted while it shows");+ set(&mut h, json!({"show": false}));+ h.step();+ h.time += 1.5;+ set(&mut h, json!({"show": true}));+ for _ in 0..3 {+ h.step();+ }+ assert!(worst_ms(&h) < 1000.0, "worst frame {} ms after turning it back on", worst_ms(&h));+ }++ /// A pause while it shows (window hidden, machine asleep) starts a fresh count too.+ #[test]+ fn a_long_pause_while_it_shows_is_not_a_frame() {+ let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() });+ let mut h = Headless::new(app, [1200.0, 800.0], 1.0);+ set(&mut h, json!({"show": true}));+ for _ in 0..3 {+ h.step();+ }+ h.time += 30.0;+ for _ in 0..3 {+ h.step();+ }+ assert!(worst_ms(&h) < 1000.0, "worst frame {} ms after a pause", worst_ms(&h));+ }++ /// Each window (egui context) keeps its own count.+ #[test]+ fn each_context_keeps_its_own_count() {+ let (a, b) = (egui::Context::default(), egui::Context::default());+ for t in [0.0, 0.016, 0.033] {+ super::record(&a, t, 0, 0, 0.0);+ }+ assert_eq!(super::frames(&a).len(), 2);+ assert!(super::frames(&b).is_empty());+ let (frames, _) = super::record(&b, 100.0, 0, 0, 0.0);+ assert!(frames.is_empty(), "a new context's first frame has no interval: {}", frames.len());+ }+ }diff --cc crates/ui-egui/src/lib.rsindex daeb3de74,026c5866d..69aa14554--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@@ -123,8 -140,8 +140,10 @@@ mod tests_layout_image#[cfg(test)]mod tests_library_problem;#[cfg(test)]+mod tests_lifecycle_037;+#[cfg(test)]+ mod tests_lightroom_destination;+ #[cfg(test)]mod tests_lights_out;#[cfg(test)]mod tests_mask_effects;@@@ -548,22 -551,11 +588,24 @@@ impl LightcraftAppquit_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![],+ drop_hover: vec![],+ drop_pending: vec![],copied: None,pending_picks: vec![],synthetic_mods: egui::Modifiers::NONE,@@@ -1622,35 -1136,16 +1667,34 @@@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();- panels::library_problem::logic(self, ctx);- self.logic_inner(ctx);- self.perf.logic_ms = now_ms() - t0;+ // 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_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);@@@ -1796,129 -1286,71 +1840,158 @@@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);++ // Recent-library checks and launch-list keys read focus/time/keys: they belong to the UI++ // phase, not the hidden-capable `logic` tick (plan §4.5 / migration input contract).++ panels::library_problem::logic(self, 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"))]- self.handle_dropped_files(ctx);++ self.handle_dropped_files(ctx, dropped);++ #[cfg(target_arch = "wasm32")]++ let _ = (dropped, ctx);+ }++ /// Files dropped on the window: face models open their licence dialog, presets import as+ /// presets, photos and folders go to the import review (or straight in, Settings ▸ Import).+ #[cfg(not(target_arch = "wasm32"))]- fn handle_dropped_files(&mut self, ctx: &egui::Context) {++ fn handle_dropped_files(&mut self, ctx: &egui::Context, dropped: Vec<egui::DroppedFileHandle>) {+ 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();+ if dropped.is_empty() {+ return;+ }+ // a dialog is on screen: the review would replace it, losing what it holds+ if self.ui.dialog.is_some() {+ self.toast(ctx, crate::i18n::tr("Close the open dialog, then drop the files again"));+ return;+ }+ let drop = drop_overlay::classify(dropped);+ if let Some(model) = drop.models.first()+ && let Err(e) = panels::faces::open_dialog(self, model){- let dropped: Vec<String> =- 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 before- let (models, dropped): (Vec<String>, Vec<String>) = dropped.into_iter().partition(|p| is_model_file(p));- if let Some(model) = models.first()- && let Err(e) = panels::faces::open_dialog(self, model)- {- self.toast(ctx, e);- }- let (presets, photos) = split_presets(dropped);- if !presets.is_empty() {- let _ = self.run("file.importPresets", serde_json::json!({"paths": presets}));+ self.toast(ctx, e);+ }+ if !drop.presets.is_empty() {+ // presets live in a library: with none open they would go with the session it replaces+ if panels::library_problem::holds_drops(self) {+ self.toast(ctx, crate::i18n::tr("Open a library first, then drop the presets again"));+ } else {+ let _ = self.run("file.importPresets", serde_json::json!({"paths": drop.presets}));}+ }+ if drop.photos.is_empty() {+ return;+ }+ // no library open yet (the launch list, a library that failed to open): they wait for one+ let Some(photos) = panels::library_problem::hold_dropped(self, ctx, drop.photos) else { return };+ if self.lightroom.is_some() {+ self.toast(ctx, crate::i18n::tr("Finish Lightroom catalog import before adding photos"));+ return;+ }+ if import::running(self) {+ self.toast(ctx, crate::i18n::tr("An import is running"));+ return;+ }+ let started = if self.ui.settings.import_dropped_directly {// read and added on a worker thread (dropped folders can be large, or on a slow drive)- if !photos.is_empty() {- if self.lightroom.is_some() {- self.toast(ctx, "Finish Lightroom catalog import before adding photos");- } else if let Err(e) = import::start_paths(self, photos) {- self.toast(ctx, e);- }- }+ import::start_paths(self, photos).map(|_| ())+ } else {+ import::open(self, photos).map(|_| ())+ };+ if let Err(e) = started {+ self.toast(ctx, e);}- // 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.fn apply_settings(&mut self, ctx: &egui::Context) {if self.gpu_applied != Some(self.ui.settings.gpu) {@@@ -2001,25 -1433,23 +2074,36 @@@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) {- // the frame after a synthetic release / key: modifiers back up- if std::mem::take(&mut self.synthetic_mods_release) && self.synthetic_mods != egui::Modifiers::NONE {- self.synthetic_mods = egui::Modifiers::NONE;- raw.events.push(egui::Event::ModifiersChanged(egui::Modifiers::NONE));- }+ let file = |p: &String| (!p.is_empty()).then(|| std::path::PathBuf::from(p));+ if !self.drop_pending.is_empty() {+ raw.dropped_files = std::mem::take(&mut self.drop_pending)+ .into_iter()+ .map(|p| std::sync::Arc::new(InjectedDrop(p.into())) as egui::DroppedFileHandle)+ .collect();+ }+ if !self.drop_hover.is_empty() {+ raw.hovered_files = self.drop_hover.iter().map(|p| egui::HoveredFile { path: file(p), ..Default::default() }).collect();+ }++ // Queue after injecting, so a `ui.dropFiles` request is consumed exactly once by the UI phase.+ 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 up+ if std::mem::take(&mut self.synthetic_mods_release) && self.synthetic_mods != egui::Modifiers::NONE {+ self.synthetic_mods = egui::Modifiers::NONE;+ raw.events.push(egui::Event::ModifiersChanged(egui::Modifiers::NONE));+ }if self.synthetic.is_empty() {return;}@@@ -2117,8 -1551,19 +2213,20 @@@}}+ /// The browser page's title: "<file name>[ •] — LightCraft" for the active photo (• while+ /// `unsaved`: changes not yet written to storage), else the window title. The web build has no+ /// window for `ViewportCommand::Title`; a host embedding it reads this title to tell which+ /// document a drop opened and whether it is saved (issue #2397).+ pub fn page_title(&self, unsaved: bool) -> String {+ let dot = if unsaved { " •" } else { "" };+ match self.session.active().and_then(|id| self.session.catalog.photo(id)) {+ Some(p) => format!("{}{dot} — LightCraft", p.file_name),+ None => format!("{}{dot}", self.window_title()),+ }+ }+- /// 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();diff --cc crates/ui-egui/src/panels/denoise.rsindex 9a0385639,bcd77176a..d070f5b74--- a/crates/ui-egui/src/panels/denoise.rs+++ b/crates/ui-egui/src/panels/denoise.rs@@@ -177,10 -182,15 +194,15 @@@ pub fn detail_status(app: &mut LightcraPhotoState::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));+ egui::Frame::NONE.inner_margin(pad).show(ui, |ui| {+ ui.horizontal(|ui| {+ crate::progress::spinner(ui, 12.0);+ note(ui, "Waiting to start…", t.text_dim);+ })+ });} else if amount > 0.0 {egui::Frame::NONE.inner_margin(pad).show(ui, |ui| {note(ui, "Its denoised picture is not made yet, and pictures are not made on their own (Settings, AI Denoise).", t.text_dim);diff --cc crates/ui-egui/src/panels/detail.rsindex 4d050235e,444ef7e73..30086369b--- a/crates/ui-egui/src/panels/detail.rs+++ b/crates/ui-egui/src/panels/detail.rs@@@ -2846,8 -2923,9 +2923,9 @@@ pub(crate) fn filmstrip(app: &mut Lightif !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());+ let failed = app.renderer.thumb(*id).is_none() && app.renderer.failure(Slot::Thumb(*id)).is_some();+ crate::widgets::announce(&resp, film_spoken(app.session.catalog.photo(*id).map_or("", |p| p.file_name.as_str()), failed));register(ui.ctx(), format!("film:{}", id.0), cr);let state = app.session.selection.state_of(*id);let sel = state == lightcraft_engine::SelectionState::Active;diff --cc crates/ui-egui/src/panels/dialogs.rsindex 9527ab8c2,f14d7338b..19e87d6c4--- a/crates/ui-egui/src/panels/dialogs.rs+++ b/crates/ui-egui/src/panels/dialogs.rs@@@ -1514,9 -1585,50 +1587,50 @@@ pub fn show(app: &mut LightcraftApp, ctif app.ui.dialog.as_ref().is_some_and(|now| *now != at_start) {return;}+ if !close {+ let frame = ctx.cumulative_frame_nr();- ctx.data_mut(|d| d.insert_temp(egui::Id::new(BACKDROP_SHOWN), frame));++ ctx.data_mut(|d| d.insert_temp(egui::Id::unique(BACKDROP_SHOWN), frame));+ }app.ui.dialog = if close { None } else { Some(dlg) };}+ /// The last frame a dialog was drawn and stayed open, for [`clicked_backdrop`].+ const BACKDROP_SHOWN: &str = "dialog-backdrop-shown";++ /// A click on the dimmed backdrop around the dialog: it closes the dialog like Esc. Pressed and+ /// released outside the window, so a slider dragged past its edge doesn't close it; a press while a+ /// popup is open (a dropdown, a date picker's calendar) only closes the popup: `popup_was_open` is+ /// read before the window is drawn, since drawing it already closes the popup. Only a press made+ /// while the dialog is shown counts: in the frame a dialog appears, its input is the click that+ /// opened it (a quick click on a slow frame presses and releases in that one frame), so it never+ /// closes it. (Read from the raw events: egui forgets the press origin on release.)+ fn clicked_backdrop(ctx: &egui::Context, window: egui::Rect, popup_was_open: bool) -> bool {- let press_id = egui::Id::new("dialog-backdrop-press");++ let press_id = egui::Id::unique("dialog-backdrop-press");+ let frame = ctx.cumulative_frame_nr();+ // the same frame too: a second pass of it gets no input- let shown = ctx.data(|d| d.get_temp::<u64>(egui::Id::new(BACKDROP_SHOWN))).is_some_and(|f| f + 1 >= frame);++ let shown = ctx.data(|d| d.get_temp::<u64>(egui::Id::unique(BACKDROP_SHOWN))).is_some_and(|f| f + 1 >= frame);+ if !shown {+ ctx.data_mut(|d| d.remove_temp::<bool>(press_id));+ return false;+ }+ let (press, release, clicked) = ctx.input(|i| {+ let at = |down: bool| {+ i.events.iter().rev().find_map(|e| match e {+ egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, .. } if *pressed == down => Some(*pos),+ _ => None,+ })+ };+ (at(true), at(false), i.pointer.primary_clicked())+ });+ if let Some(p) = press {+ let outside = !window.contains(p) && !popup_was_open;+ ctx.data_mut(|d| d.insert_temp(press_id, outside));+ }+ let Some(release) = release else { return false };+ let pressed_outside = ctx.data_mut(|d| d.remove_temp::<bool>(press_id)).unwrap_or(false);+ clicked && pressed_outside && !window.contains(release)+ }+/// Room kept free above and below a dialog (#781).const DIALOG_SCREEN_MARGIN: f32 = 12.0;/// A dialog's title bar, frame and button row before the first frame measures them.diff --cc crates/ui-egui/src/panels/edit.rsindex 03062d0c4,2063580ae..2ce723857--- a/crates/ui-egui/src/panels/edit.rs+++ b/crates/ui-egui/src/panels/edit.rs@@@ -723,16 -731,14 +731,14 @@@ fn histogram(app: &mut LightcraftApp, ulet mut clicked = resp.clicked();// the panel's floating scroll bar widens over the right edge when hovered: both buttons keep// clear of it, the left one too so they stay symmetric (#1640)- let scroll = ui.spacing().scroll;- let inset = 20.0 + scroll.bar_width + scroll.bar_outer_margin;- for (name, x, label, clipped) in [- ("shadows", plot.left() + inset, "Shadow clipping", clipping.map(|(lo, _)| lo > 0.003)),- ("highlights", plot.right() - inset, "Highlight clipping", clipping.map(|(_, hi)| hi > 0.003)),+ let [shadow_rect, highlight_rect] = super::histogram::clipping_rects(ui, plot);+ for (name, rect, label, clipped) in [+ ("shadows", shadow_rect, "Shadow clipping", clipping.map(|(lo, _)| lo > 0.003)),+ ("highlights", highlight_rect, "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.@@@ -930,6 -938,115 +939,115 @@@ fn draw_curve_histogram(p: &egui::Paintp.add(mesh);}+ /// Segments the graph's curve line is drawn with.+ pub(crate) const CURVE_SAMPLES: i32 = 96;++ /// Close a graph drag's `develop` interaction, as one undo step.+ ///+ /// It is closed when the drag ends *or* the pointer comes up without egui reporting `drag_stopped`+ /// for this widget (released outside the window, over a popup, or on a frame the widget does not+ /// run). A dangling interaction would make every later edit a silent preview — Undo would then+ /// appear to do nothing at all. Returns whether the drag is over, so the caller clears its state.+ fn commit_interaction(app: &mut LightcraftApp, ui: &egui::Ui, dragging: bool, stopped: bool) -> bool {+ let released = ui.input(|i| i.pointer.any_released()) || !ui.input(|i| i.pointer.primary_down());+ if !dragging || !(stopped || released) {+ return false;+ }+ let _ = app.run("develop.endInteraction", json!({}));+ true+ }++ /// How close (screen points) to the curve a press counts as grabbing it.+ const PARAM_GRAB: f32 = 14.0;++ /// The parametric curve's own drag: the graph shows the curve and nothing else, and dragging the+ /// line bends the region the pointer is over, with that region's slider following on the same frame.+ ///+ /// The whole gesture runs inside one `develop` interaction, so it is one undo step (Ctrl+Z takes the+ /// gesture back, not the last frame of it), and every write goes through `develop.set`, so the+ /// slider, the curve and what is drawn are the same state rather than three things kept in step.+ fn param_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect, resp: &egui::Response, d: &DevelopSettings) {+ if r.width() <= 1.0 || r.height() <= 1.0 {+ return;+ }+ let t = Tokens::get(ui.ctx());+ let model = ParametricCurve::new(&d.curve);+ let to_screen = |x: f64, y: f64| pos2(r.left() + x as f32 * r.width(), r.bottom() - y as f32 * r.height());+ let from_screen_x = |q: Pos2| ((q.x - r.left()) / r.width()).clamp(0.0, 1.0) as f64;+ // the graph x of a point, and how far it is from the drawn curve (in screen points)+ let near_curve = |q: Pos2| {+ let x = from_screen_x(q);+ to_screen(x, model.at(x)).distance(q)+ };- let drag_id = egui::Id::new("curve-param-drag");- let cursor_id = egui::Id::new("curve-param-cursor");++ let drag_id = egui::Id::unique("curve-param-drag");++ let cursor_id = egui::Id::unique("curve-param-cursor");+ // (region, x, initial_amount, start_y): the region being dragged, the graph x the drag is anchored+ // at, the region's starting amount, and the starting screen Y position.+ let mut dragged: Option<(usize, f64, f64, f32)> = ui.data(|dd| dd.get_temp::<Option<(usize, f64, f64, f32)>>(drag_id)).flatten();+ let hovered = dragged.is_none() && resp.hover_pos().is_some_and(|q| near_curve(q) <= PARAM_GRAB);+ let mut set: Option<(&'static str, f64)> = None;+ // the press, not where the pointer is once the drag threshold has passed: a press slightly off+ // the line is still a grab, and the pointer has usually left that spot by the time it starts+ let press = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos());+ if resp.drag_started()+ && let Some(q) = press+ && near_curve(q) <= PARAM_GRAB+ {+ let x = from_screen_x(q);+ let _ = app.run("develop.beginInteraction", json!({"label": "Parametric Curve"}));+ let region = model.region_at(x);+ let initial_amount = model.amounts.get(region).copied().unwrap_or(0.0);+ let start_pos = to_screen(x, model.at(x));+ dragged = Some((region, x, initial_amount, start_pos.y));+ ui.data_mut(|dd| dd.insert_temp(cursor_id, start_pos));+ }+ if let Some((region, x, initial_amount, start_y)) = dragged+ && resp.dragged()+ {+ // Follow the pointer's motion from where the curve was grabbed, so the press itself moves+ // nothing and the line tracks the hand. ⌥ = a tenth of the motion, as the point curve does.+ let alt = ui.input(|i| i.modifiers.alt);+ let dd = ui.input(|i| i.pointer.delta());+ let step = if alt { vec2(dd.x * 0.1, dd.y * 0.1) } else { vec2(dd.x, dd.y) };+ let cursor = ui.data(|d| d.get_temp::<Pos2>(cursor_id)).unwrap_or(pos2(0.0, start_y)) + step;+ ui.data_mut(|d| d.insert_temp(cursor_id, cursor));+ let delta_y = start_y - cursor.y;+ let delta_level = (delta_y / r.height()) as f64;+ let per_unit = model.level_per_unit(region, x);+ let new_amount =+ if per_unit.abs() > f64::EPSILON { (initial_amount + delta_level / per_unit).clamp(-100.0, 100.0).round() } else { initial_amount };+ if let Some(&id) = PARAM_AMOUNTS.get(region) {+ set = Some((id, new_amount));+ }+ }+ if let Some((id, v)) = set {+ let _ = app.run("develop.set", json!({"control": id, "value": v}));+ }+ let dropped = resp.drag_stopped();+ if commit_interaction(app, ui, dragged.is_some(), dropped) {+ dragged = None;+ ui.data_mut(|d| {+ d.remove::<Pos2>(cursor_id);+ d.remove::<Option<(usize, f64, f64, f32)>>(drag_id);+ });+ }+ ui.data_mut(|dd| dd.insert_temp(drag_id, dragged));+ if dragged.is_some() {+ ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);+ } else if hovered {+ ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);+ }+ // the region under the pointer (or the one in hand), named as its slider below reads it+ let shown = dragged.map(|(region, ..)| region).or_else(|| hovered.then(|| resp.hover_pos()).flatten().map(|q| model.region_at(from_screen_x(q))));+ if let Some(region) = shown+ && let Some(&id) = PARAM_AMOUNTS.get(region)+ && let Some(v) = set.and_then(|(s_id, v)| (s_id == id).then_some(v)).or_else(|| controls::get(d, id))+ {+ let name = controls::find(id).map_or("", |s| s.label);+ ui.painter().text(r.left_top() + vec2(6.0, 4.0), Align2::LEFT_TOP, format!("{name} {v:.0}"), t.font(11.0), t.text_dim);+ }+ }+fn curve_editor(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, d: &DevelopSettings) {let t = Tokens::get(ui.ctx());// channel selector@@@ -1551,9 -1658,10 +1659,10 @@@ fn grading_wheel(app: &mut LightcraftAp// 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() {+ let pointer = wheel_pointer(ui, &resp);+ let grab = match pointer {Some(q) if resp.dragged() || resp.clicked() => {let held = ui.data(|m| m.get_temp::<WheelGrab>(grab_id)).filter(|g| g.mods == mods && !resp.drag_started());Some(held.unwrap_or_else(|| {@@@ -1600,6 -1708,13 +1709,13 @@@if resp.drag_stopped() || resp.clicked() {let _ = app.run("develop.endInteraction", json!({}));}+ // released, or Esc (egui ends a drag on it)+ if resp.drag_stopped()- && let Some(held) = ui.ctx().data_mut(|m| m.remove_temp::<WheelCapture>(egui::Id::new(WHEEL_CAPTURE)))++ && let Some(held) = ui.ctx().data_mut(|m| m.remove_temp::<WheelCapture>(egui::Id::unique(WHEEL_CAPTURE)))+ && !held.dropped+ {+ give_pointer_back(ui.ctx(), held.origin);+ }if resp.double_clicked() {let _ = app.run("develop.set", json!({"values": {format!("grading.{key}.hue"): 0, format!("grading.{key}.sat"): 0}}));}@@@ -1703,6 -1818,99 +1819,99 @@@ impl WheelGrab}}+ /// A wheel drag holds the pointer, as in Lightroom (issue #1899): it is hidden for the drag, the+ /// puck follows the mouse's own travel, and on release the pointer is back where the button went+ /// down, so a long (Alt) drag doesn't leave it far from the wheels. On macOS the pointer is locked+ /// in place for the drag; elsewhere it moves unseen and is put back. The browser can't move it+ /// (eframe's web host ignores the command), so there it only shows again where the drag ended.+ #[derive(Clone, Copy, Debug, Default, PartialEq)]+ struct WheelCapture {+ /// Where the button went down: the pointer goes back there.+ origin: Pos2,+ /// Where the pointer would be had it been free: where the drag began plus the travel since.+ pos: Pos2,+ /// Let go early (the window lost focus): the rest of this drag leaves the wheel alone.+ dropped: bool,+ /// The pass that last drew the dragged wheel.+ pass: u64,+ }++ /// One wheel is dragged at a time, so one capture for them all.+ const WHEEL_CAPTURE: &str = "wheelCapture";++ /// The mouse's travel this frame: the pointer's, or, while the pointer stands still (locked, or+ /// against a screen edge), the raw motion the host reports.+ fn wheel_travel(delta: egui::Vec2, motion: Option<egui::Vec2>) -> egui::Vec2 {+ if delta != egui::Vec2::ZERO {+ return delta;+ }+ motion.filter(|m| m.x.is_finite() && m.y.is_finite()).unwrap_or(egui::Vec2::ZERO)+ }++ /// Where the wheel `resp` reads the pointer this frame: where it clicked, or for a drag the held+ /// pointer ([`WheelCapture`]), `None` once a lost focus let go of it (Esc ends the drag itself:+ /// egui stops a drag on Esc).+ fn wheel_pointer(ui: &egui::Ui, resp: &egui::Response) -> Option<Pos2> {+ let q = resp.interact_pointer_pos()?;+ if !resp.dragged() {+ return Some(q);+ }+ let ctx = ui.ctx();- let id = egui::Id::new(WHEEL_CAPTURE);++ let id = egui::Id::unique(WHEEL_CAPTURE);+ let held = ctx.data(|m| m.get_temp::<WheelCapture>(id)).filter(|_| !resp.drag_started());+ let mut cap = held.unwrap_or_else(|| {+ if cfg!(target_os = "macos") {+ ctx.send_viewport_cmd(egui::ViewportCommand::CursorGrab(egui::CursorGrab::Locked));+ }+ WheelCapture { origin: ui.input(|i| i.pointer.press_origin()).unwrap_or(q), pos: q, ..Default::default() }+ });+ cap.pass = ctx.cumulative_pass_nr();+ if !cap.dropped {+ let (travel, unfocused) = ui.input(|i| {+ // the event, not `focused`: a click that activates the window may land before its focus+ let unfocused = i.events.iter().any(|e| matches!(e, egui::Event::WindowFocused(false)));+ (wheel_travel(i.pointer.delta(), i.pointer.motion()), unfocused)+ });+ if !resp.drag_started() {+ cap.pos += travel;+ }+ if unfocused {+ give_pointer_back(ctx, cap.origin);+ cap.dropped = true;+ } else {+ ctx.set_cursor_icon(egui::CursorIcon::None);+ }+ }+ ctx.data_mut(|m| m.insert_temp(id, cap));+ (!cap.dropped).then_some(cap.pos)+ }++ /// Unlock and show the pointer a wheel drag held, back at `origin`.+ fn give_pointer_back(ctx: &egui::Context, origin: Pos2) {+ if cfg!(target_os = "macos") {+ ctx.send_viewport_cmd(egui::ViewportCommand::CursorGrab(egui::CursorGrab::None));+ }+ if cfg!(not(target_arch = "wasm32")) {+ ctx.send_viewport_cmd(egui::ViewportCommand::CursorPosition(origin));+ }+ }++ /// Once a frame, after the panels: a held pointer stays hidden over whatever set its own cursor,+ /// and is given back if no wheel drew this pass (the flyout closed or the view changed under the+ /// drag), so it is never left locked or hidden.+ pub(crate) fn wheel_pointer_frame_end(ctx: &egui::Context) {- let id = egui::Id::new(WHEEL_CAPTURE);++ let id = egui::Id::unique(WHEEL_CAPTURE);+ let Some(cap) = ctx.data(|m| m.get_temp::<WheelCapture>(id)) else { return };+ if cap.pass != ctx.cumulative_pass_nr() {+ ctx.data_mut(|m| m.remove::<WheelCapture>(id));+ if !cap.dropped {+ give_pointer_back(ctx, cap.origin);+ }+ } else if !cap.dropped {+ ctx.set_cursor_icon(egui::CursorIcon::None);+ }+ }+/// Hue (degrees) and saturation (0..100) for a pointer at offset `v` from a wheel's centre./// `lock`: hold the hue (the saturation is `v` projected onto that hue's spoke) or hold the/// saturation (the hue is the angle of `v`). A non-finite `v` gives a finite answer (the lockeddiff --cc crates/ui-egui/src/panels/library_problem.rsindex ac0dff431,3081bc80c..32e308145--- a/crates/ui-egui/src/panels/library_problem.rs+++ b/crates/ui-egui/src/panels/library_problem.rs@@@ -31,13 -112,347 +112,366 @@@ impl LibraryProblemLibraryProblem { path: path.into(), error: error.into(), can_retry: true, ..Default::default() }}+ /// The window listing the recent libraries, each checked now without writing anything+ /// ([`unavailable`]): one that is gone, isn't a LightCraft library any more or can't be read+ /// is greyed out with the reason. The last library opened is selected, or else the first one+ /// that can be opened.+ #[cfg(test)]+ pub(crate) fn choose(settings: &AppSettings) -> LibraryProblem {+ let mut p = LibraryProblem::choose_later(settings);+ if let Some(c) = p.chooser.as_mut() {+ for l in &mut c.libraries {+ l.unavailable = unavailable(&l.path).map(|u| u.text());+ l.checking = false;+ }+ c.selected = initial_selection(&c.libraries, &settings.library_path);+ c.asked = true;+ }+ p+ }++ /// [`LibraryProblem::choose`] without looking at any folder: every row is "Checking…" until+ /// [`logic`] has the answers from a worker ([`RecentChecks`]). The last library opened is+ /// selected meanwhile (or the first row); once every answer is in, the selection follows the+ /// same rule as [`LibraryProblem::choose`] unless the person moved it.+ pub fn choose_later(settings: &AppSettings) -> LibraryProblem {+ // as many as File ▸ Open Recent Library keeps (a hand-edited settings file may hold more)+ let libraries: Vec<RecentLibrary> = settings+ .recent_libraries+ .iter()+ .take(crate::state::RECENT_LIBRARIES)+ .map(|path| RecentLibrary {+ path: path.clone(),+ opened: settings.recent_opened.get(path).cloned(),+ unavailable: None,+ checking: true,+ slow: false,+ })+ .collect();+ let selected = libraries.iter().position(|l| l.path == settings.library_path).or((!libraries.is_empty()).then_some(0));+ LibraryProblem { chooser: Some(Chooser { libraries, selected, over: None, touched: false, asked: false }), ..Default::default() }+ }++ /// The session promises to save nothing (the failed-library window or Continue Without+ /// Saving): the host writes no settings meanwhile. The launch list is not such a session.+ pub fn saves_nothing(&self) -> bool {+ self.chooser.is_none()+ }+/// `ui.inspect` → `libraryProblem`.pub fn to_json(&self) -> serde_json::Value {- json!({"path": self.path, "error": self.error, "temporarySession": self.dismissed, "pendingImport": self.pending_import.len()})+ let chooser = self.chooser.as_ref().map(|c| {+ let libraries: Vec<serde_json::Value> = c+ .libraries+ .iter()+ .map(|l| json!({"path": l.path, "lastOpened": l.opened, "available": l.unavailable.is_none(), "checking": l.checking, "reason": l.unavailable}))+ .collect();+ json!({"libraries": libraries, "selected": c.selected, "libraryOpen": c.over.is_some()})+ });+ json!({"path": self.path, "error": self.error, "temporarySession": self.dismissed, "pendingImport": self.pending_import.len(), "chooser": chooser})+ }+ }++ /// The row first selected: the last library opened if it can be opened, else the first one that+ /// can, else the first row.+ fn initial_selection(libraries: &[RecentLibrary], last: &str) -> Option<usize> {+ let can = |l: &RecentLibrary| l.unavailable.is_none();+ libraries.iter().position(|l| l.path == last && can(l)).or_else(|| libraries.iter().position(can)).or((!libraries.is_empty()).then_some(0))+ }++ /// Why a recent library can't be opened, found on a worker and put into words on the UI thread+ /// (the interface language is per thread).+ #[derive(Clone, Debug, PartialEq)]+ pub enum Unavailable {+ /// Nothing at that path (moved, renamed, or on a disconnected drive).+ NotFound,+ /// A file, not a folder.+ NotAFolder,+ /// The folder can't be listed (the system's reason).+ Unreadable(String),+ /// The folder holds no LightCraft library any more.+ NoLibrary,+ /// The library's catalog file can't be opened (the system's reason).+ CatalogUnreadable(String),+ /// The check itself failed (its worker stopped, or couldn't start).+ CheckFailed(String),+ /// Looking at the path failed without saying it is gone (a parent folder it may not read, a+ /// share that timed out; the system's reason).+ LookupFailed(String),+ }++ impl Unavailable {+ /// The folder isn't a library that is there to open (gone, a file, or not a library any more):+ /// what greys out File ▸ Open Recent Library and makes `app.recentLibraries` say `exists: false`.+ /// A folder that can't be listed, an unreadable catalog or a check that failed doesn't say the+ /// library is gone (the launch window still shows why, and offers Open only for one it checked).+ pub fn is_missing(&self) -> bool {+ // a folder that refuses to list is there (permissions, macOS privacy): opening it says why+ matches!(self, Unavailable::NotFound | Unavailable::NotAFolder | Unavailable::NoLibrary)+ }++ /// In the interface language.+ pub fn text(&self) -> String {+ match self {+ Unavailable::NotFound => crate::i18n::tr("Not found: moved, renamed or on a disconnected drive").to_string(),+ Unavailable::NotAFolder => crate::i18n::tr("This is a file, not a library folder").to_string(),+ Unavailable::Unreadable(e) => format!("{} {e}", crate::i18n::tr("This folder can't be read:")),+ Unavailable::NoLibrary => crate::i18n::tr("There is no LightCraft library in this folder any more").to_string(),+ Unavailable::CatalogUnreadable(e) => format!("{} {e}", crate::i18n::tr("The library's catalog can't be read:")),+ Unavailable::CheckFailed(e) => e.clone(),+ Unavailable::LookupFailed(e) => format!("{} {e}", crate::i18n::tr("This library couldn't be checked:")),+ }+ }+ }++ /// How old an answer must be to be asked again: a library not found, on its own (a drive plugged+ /// back in); any other, when the window comes back to the front (a library moved away meanwhile).+ /// Only "not found" goes on a timer: looking again at the others would wake every external drive+ /// and network share in the list over and over.+ pub const RECHECK_AFTER: std::time::Duration = std::time::Duration::from_secs(30);+ /// How long a row stays "Checking…" before it says the drive isn't answering (it can still be+ /// opened: opening says why if it can't).+ pub const SLOW_AFTER: std::time::Duration = std::time::Duration::from_secs(5);++ /// The activity stack's row for a check (English: the stack translates it).+ const CHECK_LABEL: &str = "Checking recent libraries";++ /// One path's answer and when it came.+ #[derive(Clone, Debug)]+ struct Answer {+ why: Option<Unavailable>,+ at: web_time::Instant,++ /// The root UI frame that applied this answer ([`egui::Context::cumulative_frame_nr_for`]).++ /// Scheduling must not ask about a check answer again in the frame that delivered it, which++ /// also covers every layout pass of that frame; `None` for an answer no check worker made++ /// (`opened`, or a check that couldn't start).++ delivered_frame: Option<u64>,++}++++impl Answer {++ /// An answer from a check worker, delivered in root UI frame `delivered_frame`.++ fn from_check(why: Option<Unavailable>, delivered_frame: u64) -> Answer {++ Answer { why, at: web_time::Instant::now(), delivered_frame: Some(delivered_frame) }++ }++++ /// An answer no check worker made, with no publication fence: it may be asked about again on++ /// the next frame as before.++ fn local(why: Option<Unavailable>) -> Answer {++ Answer { why, at: web_time::Instant::now(), delivered_frame: None }++ }+ }++ /// Answers to "can this recent library be opened?", each found on a worker thread of its own (a+ /// library on a network share whose server is gone, or on a sleeping disk, can take seconds or+ /// never answer; the others don't wait for it).+ pub struct RecentChecks {+ known: std::collections::HashMap<String, Answer>,+ /// Paths being checked, and since when.+ pending: std::collections::HashMap<String, web_time::Instant>,+ /// How one path is checked ([`unavailable`]; tests put a slow one here).+ check: std::sync::Arc<dyn Fn(&str) -> Option<Unavailable> + Send + Sync>,+ /// [`RECHECK_AFTER`] (shorter in tests).+ recheck_after: std::time::Duration,+ /// Whether the window had the focus on the last frame: answers are refreshed when it comes back.+ pub(crate) focused: bool,+ }++ impl Default for RecentChecks {+ /// Nothing known yet, checking with [`unavailable`].+ fn default() -> Self {+ RecentChecks {+ known: Default::default(),+ pending: Default::default(),+ check: std::sync::Arc::new(unavailable),+ recheck_after: RECHECK_AFTER,+ focused: false,+ }+ }+ }++ impl RecentChecks {+ /// Why `path` can't be opened, if a check said so (`None`: it can, or it isn't known yet).+ pub fn reason(&self, path: &str) -> Option<&Unavailable> {+ self.known.get(path).and_then(|a| a.why.as_ref())+ }++ /// Whether the library at `path` is there: `Some(false)` when a check found it missing+ /// ([`Unavailable::is_missing`]), `Some(true)` when one found it, `None` when no check could tell.+ pub fn exists(&self, path: &str) -> Option<bool> {+ match self.known.get(path)?.why.as_ref() {+ None => Some(true),+ Some(why) if why.is_missing() => Some(false),+ Some(_) => None,+ }+ }++ /// Whether a check of `path` has answered.+ pub fn is_known(&self, path: &str) -> bool {+ self.known.contains_key(path)+ }++ /// Whether `path` is being checked.+ pub fn is_checking(&self, path: &str) -> bool {+ self.pending.contains_key(path)+ }++ /// Since when `path` has been checked, if it is.+ fn checking_since(&self, path: &str) -> Option<web_time::Instant> {+ self.pending.get(path).copied()+ }++ /// A check is running.+ pub fn is_running(&self) -> bool {+ !self.pending.is_empty()+ }++ /// Check paths with another function (tests).+ pub fn with_check(check: impl Fn(&str) -> Option<Unavailable> + Send + Sync + 'static) -> RecentChecks {+ RecentChecks { check: std::sync::Arc::new(check), ..Default::default() }+ }++ /// Ask again about answers older than `after` when the window comes back (tests).+ #[cfg(test)]+ pub fn recheck_after(mut self, after: std::time::Duration) -> RecentChecks {+ self.recheck_after = after;+ self+ }++ /// `path` was just opened (or made): it can be opened.+ pub fn opened(&mut self, path: &str) {- self.known.insert(path.to_string(), Answer { why: None, at: web_time::Instant::now() });++ self.known.insert(path.to_string(), Answer::local(None));+ }++ /// Opening `path` from the launch window failed. That says nothing about whether it is there+ /// (another program may have it open): its answer is dropped, so it is checked again on the next+ /// frame. The launch list keeps the open's error on that row for as long as it shows.+ pub fn failed(&mut self, path: &str) {+ self.known.remove(path);+ }++ /// `path` left the list: forget its answer.+ pub fn forget(&mut self, path: &str) {+ self.known.remove(path);}}+ /// Check each of `paths` on a worker of its own (one that is being checked already is left to+ /// finish). The activity stack lists each check while it runs (a quick one doesn't show: rows+ /// appear after half a second); none can be stopped, as a stat that hangs can't be.+ fn start_checks(app: &mut LightcraftApp, paths: Vec<String>) {+ for path in paths {+ if app.recent_checks.pending.contains_key(&path) {+ continue;+ }+ // asked again about an answer it has (not after a failed open, which dropped it and says why+ // on its row)+ let recheck = app.recent_checks.known.contains_key(&path);+ let check = app.recent_checks.check.clone();+ let p = path.clone();+ let started = crate::tasks::spawn(app, CHECK_LABEL, Some("library"), move || check(&p), {+ let path = path.clone();+ move |app, ctx, why| {+ app.recent_checks.pending.remove(&path);- app.recent_checks.known.insert(path, Answer { why, at: web_time::Instant::now() });++ let delivered_frame = ctx.cumulative_frame_nr_for(egui::ViewportId::ROOT);++ app.recent_checks.known.insert(path, Answer::from_check(why, delivered_frame));+ apply_answers(app);+ ctx.request_repaint();+ }+ });+ match started {+ Ok(()) => {+ // a row of the launch list waits for this answer again (a library not found looked for+ // again, a window back to the front): without it, the row kept its old answer+ if recheck+ && let Some(l) =+ app.library_problem.as_mut().and_then(|p| p.chooser.as_mut()).and_then(|c| c.libraries.iter_mut().find(|l| l.path == path))+ {+ l.checking = true;+ l.slow = false;+ l.unavailable = None;+ }+ app.recent_checks.pending.insert(path, web_time::Instant::now());+ }+ // no worker thread: say so on the row, and don't try again every frame+ Err(e) => {+ log::warn!("{e}");- app.recent_checks.known.insert(path, Answer { why: Some(Unavailable::CheckFailed(e)), at: web_time::Instant::now() });++ app.recent_checks.known.insert(path, Answer::local(Some(Unavailable::CheckFailed(e))));+ apply_answers(app);+ }+ }+ }+ }++ /// Checks whose worker stopped without answering (it panicked: `tasks::poll` already said so)+ /// end as failed, so the row and the menu don't wait for them forever.+ fn reap_checks(app: &mut LightcraftApp) {+ // (every check has the same label: when none is listed any more, the ones still pending died)+ if app.recent_checks.pending.is_empty() || app.tasks.is_running(CHECK_LABEL) {+ return;+ }+ let dead: Vec<String> = app.recent_checks.pending.keys().cloned().collect();+ for path in dead {+ app.recent_checks.pending.remove(&path);+ let why = Unavailable::CheckFailed(crate::i18n::tr("This library couldn't be checked").to_string());- app.recent_checks.known.insert(path, Answer { why: Some(why), at: web_time::Instant::now() });++ app.recent_checks.known.insert(path, Answer::local(Some(why)));+ }+ apply_answers(app);+ }++ /// Put the answers in into the launch list; once none is missing, select as+ /// [`LibraryProblem::choose`] does unless the person moved the highlight.+ fn apply_answers(app: &mut LightcraftApp) {+ let last = app.ui.settings.library_path.clone();+ let checks = &app.recent_checks;+ let Some(c) = app.library_problem.as_mut().and_then(|p| p.chooser.as_mut()) else { return };+ let checking_before = c.libraries.iter().any(|l| l.checking);+ for l in &mut c.libraries {+ if l.checking && !checks.is_checking(&l.path) && checks.is_known(&l.path) {+ l.unavailable = checks.reason(&l.path).map(Unavailable::text);+ l.checking = false;+ }+ }+ if checking_before && !c.libraries.iter().any(|l| l.checking) && !c.touched {+ c.selected = initial_selection(&c.libraries, &last);+ }+ }++ /// Why the library at `path` can't be opened (`None`: as far as can be told without opening it).+ ///+ /// Read-only: the folder and its catalog file are looked at, never locked or written (the list+ /// may name libraries on other drives, network shares or sleeping disks). A library another+ /// program has open is therefore found when Open is pressed: the open fails and the window says+ /// who has it. Runs on a worker: the reason is put into words on the UI thread.+ fn unavailable(path: &str) -> Option<Unavailable> {+ let dir = Path::new(path);+ // only a definite answer marks it missing: a lookup that fails otherwise (a parent folder it may+ // not read, a share that timed out) is "couldn't check", and the library can still be opened+ match std::fs::metadata(dir) {+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Some(Unavailable::NotFound),+ Err(e) => return Some(Unavailable::LookupFailed(e.to_string())),+ Ok(m) if !m.is_dir() => return Some(Unavailable::NotAFolder),+ Ok(_) => {}+ }+ match std::fs::read_dir(dir) {+ Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => return Some(Unavailable::Unreadable(e.to_string())),+ Err(e) => return Some(Unavailable::LookupFailed(e.to_string())),+ Ok(_) => {}+ }+ // opening would make a new, empty library in it+ if !lightcraft_engine::library::is_library(dir) {+ return Some(Unavailable::NoLibrary);+ }+ // the catalog the open reads first: the snapshot, else the log alone (opened to read, not read)+ let snapshot = dir.join(lightcraft_catalog::journal::SNAPSHOT);+ let catalog = if snapshot.is_file() { snapshot } else { dir.join(lightcraft_catalog::journal::LOG) };+ if let Err(e) = std::fs::File::open(&catalog) {+ return Some(Unavailable::CatalogUnreadable(e.to_string()));+ }+ None+ }+/// What the user chose.+ #[derive(Clone, Copy, Debug, PartialEq)]enum Choice {Retry,Choose,@@@ -75,23 -533,151 +552,156 @@@ fn open(app: &mut LightcraftApp, path:}}- /// Clear the problem once a library is open (e.g. through Settings → Open Library…).- pub fn logic(app: &mut LightcraftApp) {- if app.library_problem.is_some() && app.session.library.is_some() {- app.library_problem = None;+ /// Clear the problem once a library is open (e.g. through Settings → Open Library…) — another+ /// one than the launch list was opened over; offer the list when Alt/Option is held as the window+ /// appears; and the list's keys.+ pub fn logic(app: &mut LightcraftApp, ctx: &egui::Context) {+ if let Some(p) = &app.library_problem+ && app.session.library.is_some()+ && p.chooser.as_ref().and_then(|c| c.over) != Some(app.session.library_generation())+ {+ // files from the command line go into the library opened another way (New Library…,+ // File ▸ Open Library…), as through the window's own buttons+ let files = app.library_problem.take().map(|p| p.pending_import).unwrap_or_default();+ if !files.is_empty()+ && let Err(e) = crate::import::start_paths(app, files)+ {+ log::warn!("import: {e}");+ }+ }+ alt_at_launch(app, ctx);+ reap_checks(app);+ // the launch list asks for fresh answers once+ let listed: Option<Vec<String>> =+ app.library_problem.as_mut().and_then(|p| p.chooser.as_mut()).and_then(|c| {+ (!std::mem::replace(&mut c.asked, true)).then(|| c.libraries.iter().filter(|l| l.checking).map(|l| l.path.clone()).collect())+ });+ if let Some(listed) = listed {+ for path in &listed {+ if !app.recent_checks.is_checking(path) {+ app.recent_checks.forget(path);+ }+ }+ start_checks(app, listed);+ apply_answers(app);+ }+ // File ▸ Open Recent Library: paths never checked; libraries not found, every RECHECK_AFTER (a+ // drive plugged back in; looking at a path that isn't there wakes nothing); the others when the+ // window comes back to the front and their answer is that old. The list as shown (at most+ // RECENT_LIBRARIES).+ let focused = ctx.input(|i| i.focused);+ let regained = focused && !std::mem::replace(&mut app.recent_checks.focused, focused);+ let after = app.recent_checks.recheck_after;++ // The frame whose UI phase is scheduling now. An answer applied during this frame (by++ // `logic_background`'s `tasks::poll`, or a hidden logic tick just before the first visible UI)++ // has this number too, so it is shown for at least this whole frame: scheduling it again in++ // the same frame would erase it before any completed frame showed it, and a discarded layout++ // pass must not change that. Unknown paths have no answer and still start immediately.++ let frame = ctx.cumulative_frame_nr_for(egui::ViewportId::ROOT);+ let stale: Vec<String> = app+ .ui+ .settings+ .recent_libraries+ .iter()+ .take(crate::state::RECENT_LIBRARIES)+ .filter(|p| {+ !app.recent_checks.is_checking(p)- && app- .recent_checks- .known- .get(*p)- .is_none_or(|a| (regained || matches!(a.why, Some(Unavailable::NotFound))) && a.at.elapsed() > after)++ && app.recent_checks.known.get(*p).is_none_or(|a| {++ a.delivered_frame != Some(frame) && (regained || matches!(a.why, Some(Unavailable::NotFound))) && a.at.elapsed() > after++ })+ })+ .cloned()+ .collect();+ start_checks(app, stale);+ if app.recent_checks.is_running() {+ // rows still checking say so once it takes long+ let checks = &app.recent_checks;+ if let Some(c) = app.library_problem.as_mut().and_then(|p| p.chooser.as_mut()) {+ for l in c.libraries.iter_mut().filter(|l| l.checking) {+ l.slow = checks.checking_since(&l.path).is_some_and(|t| t.elapsed() > SLOW_AFTER);+ }+ }+ ctx.request_repaint_after(std::time::Duration::from_millis(250));}+ chooser_keys(app, ctx);}- /// The blocking window (until a choice is made).- pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {- let Some(problem) = app.library_problem.clone() else { return };- if problem.dismissed {+ /// Alt/Option held during the first [`ALT_SECONDS`] after the window appears opens the launch list+ /// once, over the library that opened (opening another one closes it). Not while files from the+ /// command line are importing into that library.+ fn alt_at_launch(app: &mut LightcraftApp, ctx: &egui::Context) {+ if !app.alt_asks_for_library {return;}- let t = Tokens::get(ctx);+ let (alt, time) = ctx.input(|i| (i.modifiers.alt, i.time));+ if time > ALT_SECONDS || app.library_problem.is_some() {+ app.alt_asks_for_library = false;+ return;+ }+ if !alt {+ return;+ }+ app.alt_asks_for_library = false;+ if crate::panels::settings::can_switch_library(app).is_err() {+ return;+ }+ let mut p = LibraryProblem::choose_later(&app.ui.settings);+ if let Some(c) = p.chooser.as_mut() {+ c.over = app.session.library.as_ref().map(|_| app.session.library_generation());+ }+ app.library_problem = Some(p);+ ctx.request_repaint();+ }++ /// The launch list on screen (no dialog over it, e.g. New Library's name).+ fn chooser_shown(app: &LightcraftApp) -> Option<&Chooser> {+ let p = app.library_problem.as_ref().filter(|p| !p.dismissed)?;+ p.chooser.as_ref().filter(|_| app.ui.dialog.is_none())+ }++ /// ↑ / ↓ move the selection, Return opens it (unless a button has the keyboard focus: it acts+ /// itself), Esc quits — or, over a library already open, keeps it. Taken before the shortcuts.+ fn chooser_keys(app: &mut LightcraftApp, ctx: &egui::Context) {+ let Some(c) = chooser_shown(app) else { return };+ let (n, selected, over) = (c.libraries.len(), c.selected, c.over.is_some());+ let focused = ctx.memory(|m| m.focused().is_some());+ use egui::{Key, Modifiers};+ let (up, down, enter, esc) = ctx.input_mut(|i| {+ let up = i.consume_key(Modifiers::NONE, Key::ArrowUp);+ let down = i.consume_key(Modifiers::NONE, Key::ArrowDown);+ let enter = !focused && i.consume_key(Modifiers::NONE, Key::Enter);+ (up, down, enter, i.consume_key(Modifiers::NONE, Key::Escape))+ });+ if (up || down) && n > 0 {+ let at = match selected {+ Some(s) if up => s.saturating_sub(1),+ Some(s) => (s + 1).min(n - 1),+ None => 0,+ };+ select(app, at);+ }+ if enter {+ act(app, Choice::Open);+ } else if esc {+ act(app, if over { Choice::Keep } else { Choice::Quit });+ }+ }++ /// Highlight row `at` of the launch list.+ fn select(app: &mut LightcraftApp, at: usize) {+ if let Some(c) = app.library_problem.as_mut().and_then(|p| p.chooser.as_mut())+ && at < c.libraries.len()+ {+ c.selected = Some(at);+ c.touched = true;+ }+ }++ /// Dim everything behind the window; it swallows clicks, so nothing there can be used meanwhile.+ fn dim(ctx: &egui::Context) {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));});@@@ -154,9 -797,135 +821,135 @@@ fn act(app: &mut LightcraftApp, choicelog::warn!("import: {e}");}}- Some(Choice::Quit) => app.ui.quit = true,- None => {}+ Choice::Quit => app.ui.quit = true,+ }+ }++ /// The launch list (issue #1290): the recent libraries, greyed out with the reason when they+ /// can't be opened, and Open / Open Another… / New Library… / Remove from List / Quit.+ fn show_chooser(app: &mut LightcraftApp, ctx: &egui::Context, problem: &LibraryProblem, chooser: &Chooser) {+ let t = Tokens::get(ctx);+ dim(ctx);+ let mut choice = None;+ let mut clicked_row = None;+ let can_pick = app.services.pick_folder.is_some();+ let open_now = app.session.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.clone());+ let frame = egui::Frame::window(&ctx.global_style()).inner_margin(egui::Margin::symmetric(18, 14));+ egui::Window::new(crate::i18n::tr("Open a Library"))- .id(egui::Id::new("library-chooser"))++ .id(egui::Id::unique("library-chooser"))+ .order(egui::Order::Foreground)+ .collapsible(false)+ .resizable(false)+ .frame(frame)+ .anchor(Align2::CENTER_CENTER, [0.0, 0.0])+ .default_width(520.0)+ .show(ctx, |ui| {+ // a fixed width: a wrapped label in an auto-sized, centred window would move it every frame+ ui.set_width(500.0);+ ui.spacing_mut().item_spacing.y = 8.0;+ ui.label(RichText::new(crate::i18n::tr("Choose the library to open.")).color(t.text_label));+ if chooser.libraries.is_empty() {+ let r = ui.label(RichText::new(crate::i18n::tr("No recent libraries. Open one from a folder, or make a new one.")).color(t.text_dim));+ register(ui.ctx(), "indicator:noRecentLibraries", r.rect);+ }+ egui::ScrollArea::vertical().max_height(300.0).auto_shrink([false, true]).show(ui, |ui| {+ ui.spacing_mut().item_spacing.y = 2.0;+ for (i, library) in chooser.libraries.iter().enumerate() {+ let r = recent_row(ui, &t, i, library, chooser.selected == Some(i), open_now.as_deref() == Some(Path::new(&library.path)));+ if r.double_clicked() {+ clicked_row = Some((i, true));+ } else if r.clicked() {+ clicked_row = Some((i, false));+ }+ }+ });+ if !problem.error.is_empty() {+ ui.add(egui::Label::new(RichText::new(&problem.error).color(t.caution)).wrap());+ }+ let selected = chooser.selected.and_then(|i| chooser.libraries.get(i));+ let mut button = |ui: &mut egui::Ui, id: &str, label: &str, enabled: bool, c: Choice| {+ let r = ui.add_enabled(enabled, egui::Button::new(crate::i18n::tr(label)).min_size(vec2(0.0, 26.0)));+ register(ui.ctx(), format!("button:{id}"), r.rect);+ if r.clicked() {+ choice = Some(c);+ }+ };+ ui.horizontal(|ui| {+ button(ui, "libraryForget", "Remove from List", selected.is_some(), Choice::Remove);+ ui.label(RichText::new(crate::i18n::tr("The library itself stays where it is.")).size(11.0).color(t.text_dim));+ });+ ui.add_space(4.0);+ ui.horizontal(|ui| {+ button(ui, "libraryOpen", "Open", selected.is_some_and(|l| l.unavailable.is_none()), Choice::Open);+ button(ui, "libraryOpenAnother", "Open Another…", can_pick, Choice::Choose);+ button(ui, "libraryNew", "New Library…", can_pick, Choice::New);+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ button(ui, "libraryQuit", "Quit", true, Choice::Quit);+ });+ });+ });+ if let Some((i, open)) = clicked_row {+ select(app, i);+ if open {+ act(app, Choice::Open);+ }+ }+ if let Some(c) = choice {+ act(app, c);+ }+ }++ /// One row of the launch list: the library's name and when it was last opened, the folder it is+ /// in, and why it can't be opened (then greyed out). Registered as `libraryRecent:<index>`.+ fn recent_row(ui: &mut egui::Ui, t: &Tokens, i: usize, library: &RecentLibrary, selected: bool, open: bool) -> egui::Response {+ let dir = Path::new(&library.path);+ let name = crate::panels::settings::library_name(dir);+ let parent = dir.parent().map(|p| p.display().to_string()).unwrap_or_default();+ let ok = library.unavailable.is_none();+ let (main, dim) = if ok { (t.text, t.text_dim) } else { (t.text_disabled, t.text_disabled) };+ let background = ui.painter().add(egui::Shape::Noop);+ let inner = egui::Frame::NONE.inner_margin(egui::Margin::symmetric(8, 5)).show(ui, |ui| {+ ui.set_width(ui.available_width());+ ui.spacing_mut().item_spacing.y = 1.0;+ ui.horizontal(|ui| {+ ui.add(egui::Label::new(RichText::new(name).font(t.semibold(12.5)).color(main)).truncate().selectable(false));+ let when = if open {+ Some(crate::i18n::tr("Open now").to_string())+ } else {+ library+ .opened+ .as_deref()+ .and_then(|iso| iso.get(..10))+ .map(|day| format!("{} {}", crate::i18n::tr("Last opened"), crate::i18n::date_group_label(day, false)))+ };+ if let Some(when) = when {+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ ui.add(egui::Label::new(RichText::new(when).size(11.0).color(dim)).selectable(false));+ });+ }+ });+ ui.add(egui::Label::new(RichText::new(parent).size(11.0).color(dim)).truncate().selectable(false));+ if let Some(why) = &library.unavailable {+ ui.add(egui::Label::new(RichText::new(why).size(11.0).color(t.caution)).wrap().selectable(false));+ } else if library.checking {+ let text =+ if library.slow { crate::i18n::tr("Not answering yet: the drive may be asleep or offline") } else { crate::i18n::tr("Checking…") };+ ui.add(egui::Label::new(RichText::new(text).size(11.0).color(dim)).wrap().selectable(false));+ }+ });- let r = ui.interact(inner.response.rect, egui::Id::new(("library-recent", i)), egui::Sense::click());++ let r = ui.interact(inner.response.rect, egui::Id::unique(("library-recent", i)), egui::Sense::click());+ register(ui.ctx(), format!("libraryRecent:{i}"), r.rect);+ let fill = if selected {+ Some(t.tool_active)+ } else if r.hovered() {+ Some(t.hover)+ } else {+ None+ };+ if let Some(fill) = fill {+ ui.painter().set(background, egui::Shape::rect_filled(r.rect, 4.0, fill));}+ r}/// The banner under the top bar while the session is temporary (Continue Without Saving).diff --cc crates/ui-egui/src/panels/presets.rsindex fc8eee09c,b4b753d68..e34230cfc--- a/crates/ui-egui/src/panels/presets.rs+++ b/crates/ui-egui/src/panels/presets.rs@@@ -166,8 -168,9 +168,9 @@@ pub fn show(app: &mut LightcraftApp, ui// imported whole is 10 000+ presets, and building every row each frame took seconds.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::unique(("preset-group", &g));+ let (g, builtin, favorites) = (grp.name.clone(), grp.builtin, grp.favorites);+ // the Favorites section opens and closes apart from a user group named "Favorites"- let open_id = egui::Id::new(("preset-group", favorites, &g));++ let open_id = egui::Id::unique(("preset-group", favorites, &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());diff --cc crates/ui-egui/src/panels/slide_layout.rsindex 5a9ddb243,802e62a5c..1acb2efa4--- a/crates/ui-egui/src/panels/slide_layout.rs+++ b/crates/ui-egui/src/panels/slide_layout.rs@@@ -178,11 -190,23 +190,23 @@@ pub fn preview(app: &mut LightcraftAppp.rect_stroke(rect, 0.0, Stroke::new(1.0, t.text_dim.gamma_multiply(0.5)), egui::StrokeKind::Outside);super::slide_titles::preview_choice(ui);if let Some(tpl) = &template {+ // (said over the bottom of the preview and not below it, which would move the page)let name = if tpl.builtin { crate::i18n::tr(&tpl.name).to_string() } else { tpl.name.clone() };- ui.label(egui::RichText::new(crate::i18n::tr_format!("Template preview: {name}", name = name)).size(11.0).color(t.accent));+ let mut said = crate::i18n::tr_format!("Template preview: {name}", name = name).to_string();if !tpl.description.is_empty() {- hint(ui, t, &tpl.description);+ said = format!("{said}\n{}", tpl.description);}+ let galley = ui.painter().layout(said, t.font(11.0), Color32::WHITE, (room.width() - 8.0).max(1.0));+ let band = Rect::from_min_size(+ pos2(room.left(), (room.bottom() - galley.size().y - 6.0).max(room.top())),+ vec2(room.width(), galley.size().y + 6.0),+ );+ let paint = ui+ .ctx()- .layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("settingsSlideshowTemplateSaid")))++ .layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("settingsSlideshowTemplateSaid")))+ .with_clip_rect(room.intersect(ui.clip_rect()));+ paint.rect_filled(band, 0.0, Color32::from_black_alpha(190));+ paint.galley(pos2(band.left() + 4.0, band.top() + 3.0), galley, Color32::WHITE);}if let Some(title) = super::slide_titles::preview_shows(ui.ctx()) {title_preview(app, ui, t, rect, title, &look);diff --cc crates/ui-egui/src/progress.rsindex 000000000,0f2dce012..9db1f8c25mode 000000,100644..100644--- a/crates/ui-egui/src/progress.rs+++ b/crates/ui-egui/src/progress.rs@@@ -1,0 -1,191 +1,191 @@@+ //! Work in progress, shown one way everywhere: a [`Progress`] bar (a known fraction, or a gentle+ //! sweep when nothing is known yet) and a [`spinner`] for short waits beside text or in a busy+ //! [`crate::button::Button`]. It replaces `egui::ProgressBar` and `ui.spinner()`.+ //!+ //! ```ignore+ //! Progress::new(Some(done as f32 / total as f32)).label(text).widget("denoise:progress").show(ui);+ //! Progress::new(None).label(tr("Starting…")).show(ui);+ //! ui.horizontal(|ui| { spinner(ui, 14.0); ui.label(tr("Selecting…")); });+ //! ```+ //!+ //! A bar announces itself to screen readers as a progress indicator with its percentage. Motion+ //! asks for repaints only while it is on screen. There is no reduced-motion setting in the app,+ //! so the motion is kept slow and small: one gentle sweep, one slow turning arc.++ use std::f32::consts::TAU;++ use egui::{Color32, Pos2, Rect, Response, Sense, Shape, Stroke, Ui, pos2, vec2};++ use crate::theme::Tokens;++ /// A bar in a model row: it leaves the row's Cancel button its place.+ pub const ROW_WIDTH: f32 = 260.0;+ /// The narrowest a bar that fills the available width is drawn.+ const MIN_WIDTH: f32 = 96.0;+ /// Height of a bar that carries text.+ const HEIGHT_WITH_TEXT: f32 = 18.0;+ /// Height of a bar without text.+ const HEIGHT_PLAIN: f32 = 6.0;+ /// Seconds an indeterminate bar takes to sweep across and back.+ const SWEEP_SECONDS: f64 = 1.8;+ /// Seconds a spinner takes for one turn.+ const TURN_SECONDS: f64 = 1.2;+ /// How often moving things redraw.+ const FRAME: std::time::Duration = std::time::Duration::from_millis(33);++ /// `fraction` as a number from 0 to 1: NaN counts as nothing done, and out-of-range values stop at+ /// the ends.+ pub fn clamp_fraction(fraction: f32) -> f32 {+ if fraction.is_nan() { 0.0 } else { fraction.clamp(0.0, 1.0) }+ }++ /// `done` of `total` as a fraction, or `None` while the total is not known (0): an unknown total+ /// is a bar that sweeps, not one stuck at 0 %.+ pub fn fraction_of(done: u64, total: u64) -> Option<f32> {+ (total > 0).then(|| clamp_fraction(done as f32 / total as f32))+ }++ /// The whole percent a bar says for `fraction`: rounded down, so 100 comes only at exactly 1.0, but+ /// with a little slack so a fraction that is exact in decimals (53 of 100, held as 0.52999997)+ /// still says 53. A bar's text and its accessible value both come from here, so they agree.+ pub fn percent(fraction: f32) -> u32 {+ let f = clamp_fraction(fraction);+ let whole = (f64::from(f) * 100.0 + 1e-3).floor() as u32;+ if f < 1.0 { whole.min(99) } else { 100 }+ }++ /// A progress bar, built and then shown with [`Progress::show`].+ #[derive(Clone, Debug)]+ pub struct Progress {+ fraction: Option<f32>,+ label: Option<String>,+ widget: Option<String>,+ width: Option<f32>,+ dimmed: bool,+ }++ impl Progress {+ /// `Some(fraction)` of the work done (clamped to 0..=1, NaN as 0), or `None` while it is not+ /// known how much there is.+ pub fn new(fraction: Option<f32>) -> Self {+ Progress { fraction: fraction.map(clamp_fraction), label: None, widget: None, width: None, dimmed: false }+ }++ /// The fraction drawn, once clamped (`None` for an indeterminate bar).+ pub fn fraction(&self) -> Option<f32> {+ self.fraction+ }++ /// Text on the bar (a percentage, a count, a file's name), already translated.+ pub fn label(mut self, text: impl Into<String>) -> Self {+ self.label = Some(text.into());+ self+ }++ /// Registered under this id for scripts, tests and `ui.clickWidget` (e.g. `progress:samDownload`).+ pub fn widget(mut self, id: impl Into<String>) -> Self {+ self.widget = Some(id.into());+ self+ }++ /// Drawn in the quiet text colour instead of the accent (work that is being stopped).+ pub fn dimmed(mut self, dimmed: bool) -> Self {+ self.dimmed = dimmed;+ self+ }++ /// This wide; by default the bar fills the width the layout has left.+ pub fn width(mut self, width: f32) -> Self {+ self.width = Some(width);+ self+ }++ /// Show it where the layout puts it.+ pub fn show(self, ui: &mut Ui) -> Response {+ let t = Tokens::get(ui.ctx());+ let label = self.label.as_deref().filter(|s| !s.is_empty());+ let width = self.width.unwrap_or_else(|| ui.available_size_before_wrap().x.max(MIN_WIDTH));+ let height = if label.is_some() { HEIGHT_WITH_TEXT } else { HEIGHT_PLAIN };+ let (rect, resp) = ui.allocate_exact_size(vec2(width, height), Sense::hover());+ resp.widget_info(|| {+ let mut info = match label {- Some(l) => egui::WidgetInfo::labeled(egui::WidgetType::ProgressIndicator, ui.is_enabled(), l),- None => egui::WidgetInfo::new(egui::WidgetType::ProgressIndicator),++ Some(l) => egui::WidgetInfo::labeled(egui::Role::ProgressIndicator, ui.is_enabled(), l),++ None => egui::WidgetInfo::new(egui::Role::ProgressIndicator),+ };+ info.value = self.fraction.map(|f| f64::from(percent(f)));+ info+ });+ if let Some(w) = &self.widget {+ crate::widgets::register(ui.ctx(), w.clone(), rect);+ }+ if !ui.is_rect_visible(rect) {+ return resp;+ }+ let p = ui.painter_at(rect);+ let radius = height / 2.0;+ p.rect_filled(rect, radius, t.inset);+ p.rect_stroke(rect, radius, Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside);+ let inner = rect.shrink(1.0);+ let fill = match self.fraction {+ Some(f) => Rect::from_min_size(inner.min, vec2(inner.width() * f, inner.height())),+ None => {+ // a short bar sweeping across and back, eased so it slows at the ends+ let phase = (ui.input(|i| i.time) / SWEEP_SECONDS).fract() as f32;+ let eased = 0.5 - 0.5 * (phase * TAU).cos();+ let len = inner.width() * 0.3;+ let x = inner.left() + (inner.width() - len) * eased;+ ui.ctx().request_repaint_after(FRAME);+ Rect::from_min_size(pos2(x, inner.top()), vec2(len, inner.height()))+ }+ };+ if fill.width() > 0.0 {+ p.with_clip_rect(inner).rect_filled(fill, radius - 1.0, if self.dimmed { t.text_dim } else { t.accent });+ }+ if let Some(l) = label {+ // the text reads on the track in the theme's colour, and in white where the fill is+ let font = t.font(11.5);+ let on_track = p.layout_no_wrap(l.to_string(), font.clone(), t.text);+ let on_fill = p.layout_no_wrap(l.to_string(), font, Color32::WHITE);+ let at = pos2(rect.center().x - on_track.size().x / 2.0, rect.center().y - on_track.size().y / 2.0);+ let clipped = ui.painter_at(rect);+ clipped.galley(at, on_track, t.text);+ clipped.with_clip_rect(rect.intersect(fill)).galley(at, on_fill, Color32::WHITE);+ }+ resp+ }+ }++ /// The arc a spinner draws at `time` seconds: points on a circle of `radius` around `center`,+ /// covering three quarters of the turn and rotating once per [`TURN_SECONDS`].+ fn arc_points(center: Pos2, radius: f32, time: f64) -> Vec<Pos2> {+ let start = ((time / TURN_SECONDS).fract() as f32) * TAU;+ let steps = 24;+ (0..=steps)+ .map(|i| {+ let a = start + TAU * 0.75 * (i as f32 / steps as f32);+ center + vec2(a.cos(), a.sin()) * radius+ })+ .collect()+ }++ /// Draw a spinner of `size` points centred in `rect`, in `color`, at `time` seconds. Callers that+ /// draw by hand (a busy button) use this; it asks for no repaint itself.+ pub fn paint_spinner(p: &egui::Painter, rect: Rect, color: Color32, time: f64) {+ let size = rect.width().min(rect.height());+ let width = (size / 8.0).max(1.5);+ let radius = ((size - width) / 2.0).max(0.5);+ p.add(Shape::line(arc_points(rect.center(), radius, time), Stroke::new(width, color)));+ }++ /// A small turning arc beside text that says what is being waited for. It is drawn as a vector+ /// arc, not a glyph, and asks for repaints only while it is on screen.+ pub fn spinner(ui: &mut Ui, size: f32) -> Response {+ let t = Tokens::get(ui.ctx());+ let (rect, resp) = ui.allocate_exact_size(vec2(size, size), Sense::hover());- resp.widget_info(|| egui::WidgetInfo::new(egui::WidgetType::ProgressIndicator));++ resp.widget_info(|| egui::WidgetInfo::new(egui::Role::ProgressIndicator));+ if ui.is_rect_visible(rect) {+ paint_spinner(ui.painter(), rect, t.text_dim, ui.input(|i| i.time));+ ui.ctx().request_repaint_after(FRAME);+ }+ resp+ }diff --cc crates/ui-egui/src/rating.rsindex 000000000,16cd611d2..4faf48b9emode 000000,100644..100644--- a/crates/ui-egui/src/rating.rs+++ b/crates/ui-egui/src/rating.rs@@@ -1,0 -1,256 +1,256 @@@+ //! One star rating for the whole interface: the clickable row of five stars ([`Rating`]) and the+ //! painter-only helpers for stars drawn onto photos and captions ([`paint_rating`], [`paint_star`]).+ //! It replaces `widgets::stars` and the private star-painting loops of the grid badge, the film+ //! badges, the compare caption and the filter bar.+ //!+ //! ```ignore+ //! if let Some(r) = Rating::new("bottom", photo.rating).show(ui) { … }+ //! paint_rating(ui.painter(), pos, 3, RatingSize::Small, color);+ //! ```+ //!+ //! Hovering a star previews the rating a click would set; clicking the current rating clears it.+ //! The row is one Tab stop (the star of the current rating, or the first when unrated); inside it, ← and →+ //! lower and raise the rating (0 to 5) and the focus follows.++ use egui::{Color32, Key, Modifiers, Painter, Pos2, Rect, Sense, Ui, pos2, vec2};++ use crate::icons::{Icon, paint};+ use crate::theme::Tokens;+ use crate::widgets::{announce_selected, register};++ /// Number of stars in a rating.+ const STARS: u8 = 5;++ /// How big a rating is drawn. Each size matches one of the renderers it replaced.+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]+ pub enum RatingSize {+ /// Film badges: 8 px stars every 9 px.+ Small,+ /// Grid badges and compare captions: 12 px stars every 13 px.+ Medium,+ /// The clickable row (bottom bar, Info panel, filter bar): 14 px stars in 19 px cells.+ Large,+ }++ impl RatingSize {+ /// Side of one painted star.+ pub fn icon(self) -> f32 {+ match self {+ Self::Small => 8.0,+ Self::Medium => 12.0,+ Self::Large => 14.0,+ }+ }++ /// Distance from one painted star to the next in [`paint_rating`].+ pub fn step(self) -> f32 {+ match self {+ Self::Small => 9.0,+ Self::Medium => 13.0,+ Self::Large => 17.0,+ }+ }++ /// Side of one clickable cell in a [`Rating`] row.+ fn cell(self) -> f32 {+ self.step() + 2.0+ }+ }++ /// Paint one star (outline or filled) centred in `rect`.+ pub fn paint_star(painter: &Painter, rect: Rect, filled: bool, color: Color32) {+ paint(painter, rect, if filled { Icon::StarFilled } else { Icon::Star }, color);+ }++ /// Paint `rating` filled stars in a row, the first one's left edge at `pos.x` and its vertical centre+ /// at `pos.y`. Returns the width the row takes (0 for no stars), so the caller can lay out what follows.+ pub fn paint_rating(painter: &Painter, pos: Pos2, rating: u8, size: RatingSize, color: Color32) -> f32 {+ let n = rating.min(STARS);+ let side = size.icon();+ for i in 0..n {+ let left = pos.x + f32::from(i) * size.step();+ paint_star(painter, Rect::from_min_size(pos2(left, pos.y - side / 2.0), vec2(side, side)), true, color);+ }+ f32::from(n) * size.step()+ }++ /// What the stars show once hovering is taken into account: the hovered star's rating previews over+ /// the current one.+ fn star_lit(i: u8, rating: u8, hover: Option<u8>) -> bool {+ i < hover.unwrap_or(rating)+ }++ /// The rating a click on star `n` (1 to 5) sets: clicking the current rating clears it.+ fn clicked_rating(current: u8, n: u8) -> u8 {+ if current == n { 0 } else { n }+ }++ /// The rating the arrow keys move to from `current`, if any.+ fn nudged_rating(current: u8, left: bool, right: bool) -> Option<u8> {+ match (left, right) {+ (true, false) if current > 0 => Some(current - 1),+ (false, true) if current < STARS => Some(current + 1),+ _ => None,+ }+ }++ /// A row of five stars. Build it, then [`Rating::show`].+ pub struct Rating {+ id: String,+ rating: u8,+ ids_prefix: Option<String>,+ }++ impl Rating {+ /// A rating of `rating` (0 to 5) whose stars are reachable as `star:{id}:{n}`.+ pub fn new(id: impl Into<String>, rating: u8) -> Self {+ Self { id: id.into(), rating: rating.min(STARS), ids_prefix: None }+ }++ /// Register the stars under `{prefix}{n}` instead of `star:{id}:{n}`, for rows that already have+ /// published automation ids (the filter bar's `filter:star3`).+ pub fn automation_ids(mut self, prefix: impl Into<String>) -> Self {+ self.ids_prefix = Some(prefix.into());+ self+ }++ fn widget_id(&self, n: u8) -> String {+ match &self.ids_prefix {+ Some(prefix) => format!("{prefix}{n}"),+ None => format!("star:{}:{n}", self.id),+ }+ }++ fn star_id(&self, ui: &Ui, i: u8) -> egui::Id {- ui.id().with(("rating-star", &self.id, i))++ ui.scope_id().with(("rating-star", &self.id, i))+ }++ /// Draw the row. Returns the new rating when a click or an arrow key changed it.+ pub fn show(self, ui: &mut Ui) -> Option<u8> {+ let t = Tokens::get(ui.ctx());+ let cell = RatingSize::Large.cell();+ let mut out = None;+ let mut hover_n = None;+ let mut focused_at = None;+ let mut cells = [Rect::NOTHING; STARS as usize];+ // One Tab stop for the row, like a radio group: the star of the current rating (the first when+ // unrated), plus whichever star already has the focus so it keeps it+ let stop = self.rating.max(1) - 1;+ for (i, slot) in (0..STARS).zip(cells.iter_mut()) {+ let id = self.star_id(ui, i);+ let (r, _) = ui.allocate_exact_size(vec2(cell, cell), Sense::hover());+ let sense = if i == stop || ui.memory(|m| m.has_focus(id)) { Sense::click() } else { Sense::CLICK };+ let resp = ui.interact(r, id, sense);+ announce_selected(&resp, format!("{} ★", i + 1), i < self.rating);+ register(ui.ctx(), self.widget_id(i + 1), r);+ if resp.hovered() {+ hover_n = Some(i + 1);+ }+ if resp.clicked() {+ out = Some(clicked_rating(self.rating, i + 1));+ }+ if resp.has_focus() {+ focused_at = Some(i);+ // ← and → step the rating instead of moving the focus to the neighbouring widget+ ui.memory_mut(|m| {+ m.set_focus_lock_filter(resp.id, egui::EventFilter { horizontal_arrows: true, ..Default::default() });+ });+ ui.painter().rect_stroke(r.expand(1.0), 6.0, egui::Stroke::new(2.0, t.accent), egui::StrokeKind::Outside);+ }+ *slot = r;+ }+ let focused = focused_at.is_some();+ if focused && out.is_none() {+ let (left, right) = ui.input_mut(|i| (i.consume_key(Modifiers::NONE, Key::ArrowLeft), i.consume_key(Modifiers::NONE, Key::ArrowRight)));+ if left || right {+ // egui picked the neighbour to focus from this same key before the lock above could apply (the+ // first arrow after Tab): cancel that move+ ui.memory_mut(|m| m.move_focus(egui::FocusDirection::None));+ }+ out = nudged_rating(self.rating, left, right);+ if let Some(n) = out {+ // keep the focus on the star that is now the row's Tab stop+ let to = self.star_id(ui, n.max(1) - 1);+ ui.memory_mut(|m| m.request_focus(to));+ } else if focused_at != Some(stop) {+ // the rating changed from outside (undo, a shortcut, another photo): the focus follows the Tab stop+ let to = self.star_id(ui, stop);+ ui.memory_mut(|m| m.request_focus(to));+ }+ }+ // The hovered star also gets the icon-button hover square, so hovering the current rating (where+ // the preview looks the same) still shows feedback.+ let side = RatingSize::Large.icon();+ for (i, r) in (0..STARS).zip(cells) {+ if hover_n == Some(i + 1) {+ ui.painter().rect_filled(r, 4.0, t.hover.gamma_multiply(0.7));+ }+ let filled = star_lit(i, self.rating, hover_n);+ paint_star(ui.painter(), Rect::from_center_size(r.center(), vec2(side, side)), filled, if filled { t.star } else { t.icon });+ }+ out+ }+ }++ /// A frameless star toggle for favourites: filled when `favorite`, named `name` for screen readers and as+ /// its tooltip, reachable as `widget` (a full automation id). A square one line tall.+ pub fn favorite_button(ui: &mut Ui, widget: String, favorite: bool, name: &str) -> egui::Response {+ let t = Tokens::get(ui.ctx());+ let side = ui.spacing().interact_size.y;+ let (r, resp) = ui.allocate_exact_size(vec2(side, side), Sense::click());+ announce_selected(&resp, name, favorite);+ // (rows scrolled out of view can't be clicked)+ if ui.is_rect_visible(r) {+ register(ui.ctx(), widget, r);+ }+ if resp.hovered() {+ ui.painter().rect_filled(r, 4.0, t.hover.gamma_multiply(0.7));+ }+ if resp.has_focus() {+ ui.painter().rect_stroke(r.expand(1.0), 6.0, egui::Stroke::new(2.0, t.accent), egui::StrokeKind::Outside);+ }+ let icon = RatingSize::Medium.icon();+ paint_star(ui.painter(), Rect::from_center_size(r.center(), vec2(icon, icon)), favorite, if favorite { t.star } else { t.icon });+ resp.on_hover_text(name)+ }++ #[cfg(test)]+ mod tests {+ use super::*;++ #[test]+ fn the_hovered_star_previews_its_rating() {+ let lit = |rating, hover| (0..STARS).filter(|&i| star_lit(i, rating, hover)).count();+ assert_eq!(lit(2, None), 2, "no hover shows the rating");+ assert_eq!(lit(2, Some(4)), 4);+ assert_eq!(lit(5, Some(1)), 1);+ assert_eq!(lit(0, Some(3)), 3);+ }++ #[test]+ fn arrows_stay_between_zero_and_five() {+ assert_eq!(nudged_rating(0, true, false), None);+ assert_eq!(nudged_rating(5, false, true), None);+ assert_eq!(nudged_rating(3, true, false), Some(2));+ assert_eq!(nudged_rating(3, false, true), Some(4));+ assert_eq!(nudged_rating(3, true, true), None);+ }++ #[test]+ fn rows_scrolled_out_of_view_are_not_registered() {+ let ctx = egui::Context::default();+ crate::theme::install_fonts(&ctx);+ let mut out =+ ctx.run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(300.0, 100.0))), ..Default::default() }, |ui| {+ egui::ScrollArea::vertical().max_height(60.0).show(ui, |ui| {+ for i in 0..30 {+ favorite_button(ui, format!("effectStar:{i}"), false, "Favorite");+ }+ });+ });+ out.textures_delta.clear();+ let ids: Vec<String> = crate::widgets::take_registry(&ctx).into_iter().map(|(id, _)| id).collect();+ assert!(ids.contains(&"effectStar:0".to_string()), "{ids:?}");+ assert!(!ids.contains(&"effectStar:29".to_string()), "{ids:?}");+ }+ }diff --cc crates/ui-egui/src/tests_launch_library.rsindex 000000000,b0b3bec6b..e99ee8d44mode 000000,100644..100644--- a/crates/ui-egui/src/tests_launch_library.rs+++ b/crates/ui-egui/src/tests_launch_library.rs@@@ -1,0 -1,991 +1,1017 @@@+ //! Issue #1290: what opens at launch. Settings ▸ General ▸ At launch opens the last library or+ //! asks with a window listing the recent ones (greyed out with the reason when they can't be+ //! opened); Alt/Option held as the window appears asks once; one recent entry can be forgotten from+ //! File ▸ Open Recent Library, the window and `app.recentLibraries {remove}`.++ use std::path::{Path, PathBuf};+ use std::time::Duration;++ use serde_json::json;++ use crate::headless::Headless;+ use crate::panels::library_problem::{ALT_SECONDS, Launch, LibraryProblem, launch_plan};+ use crate::state::{AppSettings, LaunchLibrary};+ use crate::{LightcraftApp, Services};++ const T: Duration = Duration::from_secs(20);++ /// A fresh scratch folder for one test.+ fn temp(tag: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!("lc-ui-launch-{tag}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ dir+ }++ /// A library on disk at `dir` (written, then closed: as left by an earlier run).+ fn make_library(dir: &Path) -> String {+ let mut s = lightcraft_engine::Session::new().with_fs();+ s.open_library(dir, false).unwrap();+ s.close_library().unwrap();+ drop(s);+ assert!(lightcraft_engine::library::is_library(dir));+ dir.to_string_lossy().into_owned()+ }++ /// Enough frames for a synthetic click (move, press, release) and what it starts.+ fn settle(h: &mut Headless) {+ for _ in 0..6 {+ h.step();+ }+ }++ /// The widget `id` was drawn in the last frame.+ fn has(h: &Headless, id: &str) -> bool {+ h.app.widgets.iter().any(|(w, _)| w == id)+ }++ /// `Some(s)` as a path, for the launch plan's arguments.+ fn path(s: &str) -> Option<PathBuf> {+ Some(PathBuf::from(s))+ }++ /// `--library`, then `LIGHTCRAFT_LIBRARY`, then the setting; `--memory` never asks.+ #[test]+ fn the_launch_plan_puts_the_flag_and_the_variable_before_the_setting() {+ let ask = AppSettings { at_launch: LaunchLibrary::Ask, library_path: "/last".into(), ..AppSettings::default() };+ let last = AppSettings { library_path: "/last".into(), recent_libraries: vec!["/last".into(), "/older".into()], ..AppSettings::default() };+ let fresh = AppSettings::default();+ let open = |dir: &str, alt_asks| Launch::Open { dir: path(dir), alt_asks };+ // --library, then LIGHTCRAFT_LIBRARY, whatever the setting says; neither asks on Alt+ for s in [None, Some(&ask), Some(&last)] {+ assert_eq!(launch_plan(false, path("/flag"), path("/env"), s, path("/default")), open("/flag", false));+ assert_eq!(launch_plan(false, None, path("/env"), s, path("/default")), open("/env", false));+ }+ // Ask me asks, with or without a recent list+ assert_eq!(launch_plan(false, None, None, Some(&ask), path("/default")), Launch::Ask);+ let ask_empty = AppSettings { at_launch: LaunchLibrary::Ask, ..AppSettings::default() };+ assert_eq!(launch_plan(false, None, None, Some(&ask_empty), None), Launch::Ask);+ // Open the last library: the last one, else the default place; Alt can still ask+ assert_eq!(launch_plan(false, None, None, Some(&last), path("/default")), open("/last", true));+ assert_eq!(launch_plan(false, None, None, Some(&fresh), path("/default")), open("/default", true));+ assert_eq!(launch_plan(false, None, None, None, path("/default")), open("/default", true));+ assert_eq!(launch_plan(false, None, None, None, None), Launch::Open { dir: None, alt_asks: true });+ // --memory never asks and opens no folder+ assert_eq!(launch_plan(true, None, None, Some(&ask), path("/default")), Launch::Open { dir: None, alt_asks: false });+ assert_eq!(launch_plan(true, path("/flag"), None, Some(&last), None), Launch::Open { dir: None, alt_asks: false });+ }++ /// Each listed library is checked when the window opens; the last one opened is selected.+ #[test]+ fn the_list_checks_each_library_and_selects_the_last_one() {+ let dir = temp("choose");+ let (a, b, held, plain) = (dir.join("A"), dir.join("B"), dir.join("Held"), dir.join("Plain"));+ let (a, b, held_path) = (make_library(&a), make_library(&b), make_library(&held));+ std::fs::create_dir_all(&plain).unwrap();+ std::fs::write(plain.join("notes.txt"), b"not a library").unwrap();+ let file = dir.join("a-file.txt");+ std::fs::write(&file, b"a file").unwrap();+ let (gone, plain, file) =+ (dir.join("Gone").to_string_lossy().into_owned(), plain.to_string_lossy().into_owned(), file.to_string_lossy().into_owned());+ // another program has it open: listing doesn't take locks, so it is found when opened+ let lock = lightcraft_catalog::LibraryLock::acquire(Path::new(&held_path), "another LightCraft").unwrap();++ let mut settings = AppSettings {+ recent_libraries: vec![gone.clone(), held_path.clone(), a.clone(), plain.clone(), file.clone(), b.clone()],+ library_path: b.clone(),+ ..AppSettings::default()+ };+ settings.recent_opened.insert(b.clone(), "2026-10-20T08:30:00".into());+ let p = LibraryProblem::choose(&settings);+ assert!(!p.saves_nothing(), "the launch list is not a temporary session: removals are saved");+ let c = p.chooser.as_ref().unwrap();+ let why: Vec<Option<&str>> = c.libraries.iter().map(|l| l.unavailable.as_deref()).collect();+ assert!(why[0].unwrap().contains("Not found"), "{why:?}");+ assert_eq!(why[1], None, "a lock is not probed: {why:?}");+ assert_eq!(why[2], None);+ assert!(why[3].unwrap().contains("no LightCraft library"), "{why:?}");+ assert!(why[4].unwrap().contains("not a library folder"), "{why:?}");+ assert_eq!(why[5], None);+ assert_eq!(c.selected, Some(5), "the last library opened");+ assert_eq!(c.libraries[5].opened.as_deref(), Some("2026-10-20T08:30:00"));+ assert_eq!(c.libraries[2].opened, None, "no time known");+ let json = p.to_json();+ assert_eq!(json["chooser"]["libraries"][0]["available"], false);+ assert_eq!(json["chooser"]["selected"], 5);++ // the last library can't be opened: the first one that can is selected+ settings.library_path = plain.clone();+ assert_eq!(LibraryProblem::choose(&settings).chooser.unwrap().selected, Some(1));+ // none can: the first row, Open greyed out+ settings.recent_libraries = vec![gone.clone(), file.clone()];+ assert_eq!(LibraryProblem::choose(&settings).chooser.unwrap().selected, Some(0));+ // an empty list selects nothing+ settings.recent_libraries.clear();+ let c = LibraryProblem::choose(&settings).chooser.unwrap();+ assert!(c.libraries.is_empty() && c.selected.is_none());+ assert!(LibraryProblem::new("/x", "e").saves_nothing(), "the failed-library window still saves nothing");+ drop(lock);+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// Every file under `dir`: relative path → (contents, modification time).+ fn snapshot(dir: &Path) -> std::collections::BTreeMap<PathBuf, (Vec<u8>, std::time::SystemTime)> {+ let mut out = std::collections::BTreeMap::new();+ let mut todo = vec![dir.to_path_buf()];+ while let Some(d) = todo.pop() {+ for e in std::fs::read_dir(&d).unwrap() {+ let p = e.unwrap().path();+ let m = std::fs::metadata(&p).unwrap();+ if m.is_dir() {+ todo.push(p.clone());+ }+ let bytes = if m.is_file() { std::fs::read(&p).unwrap() } else { Vec::new() };+ out.insert(p.strip_prefix(dir).unwrap().to_path_buf(), (bytes, m.modified().unwrap()));+ }+ }+ out+ }++ /// Listing the recent libraries (and drawing the window) writes nothing into any of them: no+ /// lock file, no owner file, nothing modified — free, held by another program or not a library.+ #[test]+ fn listing_the_libraries_leaves_every_folder_byte_identical() {+ let dir = temp("readonly");+ let (free, fresh, held) = (dir.join("Free"), dir.join("Fresh"), dir.join("Held"));+ let (free, held_path) = (make_library(&free), make_library(&held));+ // a library whose lock files were never made (copied over from elsewhere, say)+ let fresh_path = make_library(&fresh);+ for f in [lightcraft_catalog::lock::LOCK, lightcraft_catalog::lock::OWNER] {+ let _ = std::fs::remove_file(fresh.join(f));+ }+ std::fs::create_dir_all(dir.join("Plain")).unwrap();+ let lock = lightcraft_catalog::LibraryLock::acquire(Path::new(&held_path), "another LightCraft").unwrap();+ let recent = vec![free.clone(), fresh_path.clone(), held_path.clone(), dir.join("Plain").to_string_lossy().into_owned()];+ let before = snapshot(&dir);+ // (mtime granularity: a write in the same instant would still change contents or add files)+ let settings = AppSettings { recent_libraries: recent.clone(), library_path: free.clone(), ..AppSettings::default() };+ let p = LibraryProblem::choose(&settings);+ assert_eq!(snapshot(&dir), before, "checking the rows must not create or change any file");+ assert!(p.chooser.as_ref().unwrap().libraries.iter().take(3).all(|l| l.unavailable.is_none()));+ let mut h = asking(recent, &free, None);+ settle(&mut h);+ assert!(has(&h, "libraryRecent:2"));+ drop(h);+ assert_eq!(snapshot(&dir), before, "listing must not create or change any file");+ assert!(!fresh.join(lightcraft_catalog::lock::LOCK).exists() && !fresh.join(lightcraft_catalog::lock::OWNER).exists());+ drop(lock);+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// The app as the desktop host starts it with *Ask me*: no library open, the list showing.+ fn asking(recent: Vec<String>, last: &str, picked: Option<String>) -> Headless {+ let session = lightcraft_engine::Session::new().with_fs();+ // (an encoder for the screenshots LIGHTCRAFT_TEST_SHOTS asks for)+ let png = |img: &lightcraft_raster::Rgba8| {+ lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(img), &lightcraft_codecs::EncodeMeta::default()).unwrap_or_default()+ };+ let services = Services {+ png: Some(Box::new(png)),+ write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))),+ ..Default::default()+ };+ let mut app = LightcraftApp::new(session, services);+ app.ui.settings.recent_libraries = recent;+ app.ui.settings.library_path = last.to_string();+ app.ui.settings.at_launch = LaunchLibrary::Ask;+ if let Some(p) = picked {+ app.services.pick_folder = Some(Box::new(move || Some(p.clone())));+ }+ app.library_problem = Some(LibraryProblem::choose(&app.ui.settings));+ let mut h = Headless::new(app, [1300.0, 900.0], 1.0);+ settle(&mut h);+ h+ }++ /// The window lists every recent library, greys out a missing one and opens the chosen one.+ #[test]+ fn the_window_lists_the_libraries_and_opens_the_chosen_one() {+ let dir = temp("window");+ let (a, b) = (make_library(&dir.join("Alpha")), make_library(&dir.join("Beta")));+ let gone = dir.join("Gone").to_string_lossy().into_owned();+ let mut h = asking(vec![a.clone(), gone.clone(), b.clone()], &a, None);+ assert!(h.app.session.library.is_none(), "nothing opened before the choice");+ for id in ["libraryRecent:0", "libraryRecent:1", "libraryRecent:2", "button:libraryOpen", "button:libraryOpenAnother", "button:libraryNew"] {+ assert!(has(&h, id), "{id}");+ }+ assert!(has(&h, "button:libraryQuit") && has(&h, "button:libraryForget"));+ assert!(!has(&h, "button:libraryRetry"), "not the failed-library window");+ if let Some(p) = std::env::var_os("LIGHTCRAFT_TEST_SHOTS") {+ let r = h.request("ui.screenshot", json!({"path": Path::new(&p).join("launch-list.png").to_string_lossy(), "headless": true}), T);+ assert_eq!(r["ok"], true, "{r}");+ }+ let inspect = h.request("ui.inspect", json!({}), T);+ let c = &inspect["result"]["libraryProblem"]["chooser"];+ assert_eq!(c["selected"], 0, "{c}");+ assert_eq!(c["libraries"][1]["available"], false, "{c}");++ // ↓ onto the missing one: Return does nothing there (Open is greyed out)+ assert_eq!(h.request("ui.key", json!({"key": "ArrowDown"}), T)["ok"], true);+ settle(&mut h);+ assert_eq!(h.app.library_problem.as_ref().unwrap().chooser.as_ref().unwrap().selected, Some(1));+ h.request("ui.key", json!({"key": "Enter"}), T);+ settle(&mut h);+ assert!(h.app.session.library.is_none() && h.app.library_problem.is_some());+ // ↓ again, then Open: Beta opens and the window goes away+ h.request("ui.key", json!({"key": "ArrowDown"}), T);+ settle(&mut h);+ assert_eq!(h.request("ui.clickWidget", json!({"id": "button:libraryOpen"}), T)["ok"], true);+ settle(&mut h);+ assert_eq!(h.app.session.library.as_ref().map(|l| l.dir.to_string_lossy().into_owned()), Some(b.clone()));+ assert!(h.app.library_problem.is_none());+ assert!(!has(&h, "button:libraryOpen"));+ assert_eq!(h.app.ui.settings.library_path, b);+ drop(h);+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// Return opens the selection; a library taken meanwhile stays listed with the reason.+ #[test]+ fn return_opens_the_selected_library_and_a_failure_says_why() {+ let dir = temp("return");+ let (a, b) = (make_library(&dir.join("Alpha")), make_library(&dir.join("Beta")));+ let mut h = asking(vec![a.clone(), b.clone()], &b, None);+ assert_eq!(h.app.library_problem.as_ref().unwrap().chooser.as_ref().unwrap().selected, Some(1));+ // another program takes Beta after the window opened: Open says so and keeps the window+ let lock = lightcraft_catalog::LibraryLock::acquire(Path::new(&b), "another LightCraft").unwrap();+ h.request("ui.key", json!({"key": "Enter"}), T);+ settle(&mut h);+ assert!(h.app.session.library.is_none());+ let p = h.app.library_problem.as_ref().unwrap();+ assert!(p.error.contains("already open in another LightCraft"), "who has it: {}", p.error);+ assert!(p.chooser.as_ref().unwrap().libraries[1].unavailable.is_some(), "greyed out now");+ drop(lock);+ // ↑ to Alpha, Return: it opens+ h.request("ui.key", json!({"key": "ArrowUp"}), T);+ settle(&mut h);+ h.request("ui.key", json!({"key": "Enter"}), T);+ settle(&mut h);+ assert_eq!(h.app.session.library.as_ref().map(|l| l.dir.to_string_lossy().into_owned()), Some(a));+ assert!(h.app.library_problem.is_none());+ drop(h);+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// Quit and Esc quit without opening anything.+ #[test]+ fn quit_and_esc_quit_from_the_window() {+ let dir = temp("quit");+ let a = make_library(&dir.join("Alpha"));+ let mut h = asking(vec![a.clone()], &a, None);+ h.request("ui.key", json!({"key": "Escape"}), T);+ settle(&mut h);+ assert!(h.quit_requested(), "Esc quits when no library is open");+ assert!(h.app.session.library.is_none(), "and opens nothing");+ drop(h);++ let mut h = asking(vec![a.clone()], &a, None);+ assert_eq!(h.request("ui.clickWidget", json!({"id": "button:libraryQuit"}), T)["ok"], true);+ settle(&mut h);+ assert!(h.quit_requested());+ assert!(h.app.session.library.is_none());+ drop(h);+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// Open Another… runs the folder dialog of `app.openLibrary`, also with an empty list.+ #[test]+ fn open_another_asks_for_a_folder_and_an_empty_list_still_offers_it() {+ let dir = temp("another");+ let other = make_library(&dir.join("Elsewhere"));+ let mut h = asking(Vec::new(), "", Some(other.clone()));+ assert!(has(&h, "indicator:noRecentLibraries"));+ assert!(!has(&h, "libraryRecent:0"));+ assert_eq!(h.request("ui.clickWidget", json!({"id": "button:libraryOpenAnother"}), T)["ok"], true);+ settle(&mut h);+ assert_eq!(h.app.session.library.as_ref().map(|l| l.dir.to_string_lossy().into_owned()), Some(other.clone()));+ assert!(h.app.library_problem.is_none());+ assert_eq!(h.app.ui.settings.recent_libraries.first(), Some(&other), "remembered once opened");+ drop(h);++ // without a folder dialog (the browser) Open Another… and New Library… are greyed out+ let mut h = asking(Vec::new(), "", None);+ h.request("ui.clickWidget", json!({"id": "button:libraryOpenAnother"}), T);+ h.request("ui.clickWidget", json!({"id": "button:libraryNew"}), T);+ settle(&mut h);+ assert!(h.app.library_problem.is_some() && h.app.ui.dialog.is_none());+ drop(h);+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// New Library… asks for a name in front of the window; command-line photos go into it.+ #[test]+ fn new_library_from_the_window_asks_for_a_name_and_the_list_returns_if_cancelled() {+ let dir = temp("newlib");+ let a = make_library(&dir.join("Alpha"));+ let mut h = asking(vec![a.clone()], &a, Some(dir.to_string_lossy().into_owned()));+ // a photo given on the command line waits for the library chosen+ let img = lightcraft_raster::Rgba8 { width: 8, height: 8, data: vec![[90, 3, 9, 255]; 64] };+ let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap();+ let photo = dir.join("a.png");+ std::fs::write(&photo, png).unwrap();+ h.app.library_problem.as_mut().unwrap().pending_import = vec![photo.to_string_lossy().into_owned()];+ assert_eq!(h.request("ui.clickWidget", json!({"id": "button:libraryNew"}), T)["ok"], true);+ settle(&mut h);+ assert!(matches!(h.app.ui.dialog, Some(crate::state::Dialog::TextPrompt { .. })), "{:?}", h.app.ui.dialog);+ assert!(!has(&h, "button:libraryOpen"), "the name prompt is in front");+ h.request("ui.dialog.cancel", json!({}), T);+ settle(&mut h);+ assert!(has(&h, "button:libraryOpen"), "the list is back");+ // what the prompt's OK runs: the library is made where the folder dialog says, and opens+ h.app.run("app.newLibrary", json!({"name": "Fresh"})).unwrap();+ settle(&mut h);+ assert_eq!(h.app.session.library.as_ref().map(|l| l.dir.clone()), Some(dir.join("Fresh")));+ assert!(h.app.library_problem.is_none());+ h.step_until(T, |h| h.app.import.is_none() && h.app.session.catalog.len() == 1);+ assert_eq!(h.app.session.catalog.len(), 1, "the command-line photo is imported into the new library");+ drop(h);+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// Remove from List in the window forgets the selected entry and deletes nothing.+ #[test]+ fn remove_from_list_forgets_one_library_and_deletes_nothing() {+ let dir = temp("forget");+ let (a, b) = (make_library(&dir.join("Alpha")), make_library(&dir.join("Beta")));+ let gone = dir.join("Gone").to_string_lossy().into_owned();+ let mut h = asking(vec![a.clone(), gone.clone(), b.clone()], &a, None);+ h.app.ui.settings.recent_opened.insert(gone.clone(), "2026-01-01T00:00:00".into());+ // the window: the missing one can be selected and removed+ h.request("ui.clickWidget", json!({"id": "libraryRecent:1"}), T);+ settle(&mut h);+ assert_eq!(h.app.library_problem.as_ref().unwrap().chooser.as_ref().unwrap().selected, Some(1));+ assert_eq!(h.request("ui.clickWidget", json!({"id": "button:libraryForget"}), T)["ok"], true);+ settle(&mut h);+ assert_eq!(h.app.ui.settings.recent_libraries, [a.clone(), b.clone()]);+ assert!(!h.app.ui.settings.recent_opened.contains_key(&gone), "its time goes too");+ let c = h.app.library_problem.as_ref().unwrap().chooser.clone().unwrap();+ assert_eq!(c.libraries.len(), 2);+ assert_eq!(c.selected, Some(1));+ // removing an existing library leaves its folder and catalog alone+ h.request("ui.clickWidget", json!({"id": "button:libraryForget"}), T);+ settle(&mut h);+ assert_eq!(h.app.ui.settings.recent_libraries, vec![a.clone()]);+ assert!(lightcraft_engine::library::is_library(Path::new(&b)), "nothing is deleted on disk");+ settle(&mut h);+ assert!(!has(&h, "libraryRecent:1"));+ drop(h);+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// File ▸ Open Recent Library's items.+ fn open_recent(app: &LightcraftApp) -> Vec<crate::menubar::MenuNode> {+ use crate::menubar::MenuNode;+ let bar = crate::menubar::menu_bar(app);+ let file = &bar.iter().find(|(t, _)| t == "File").unwrap().1;+ match file.iter().find(|n| matches!(n, MenuNode::Submenu { label, .. } if label == "Open Recent Library")) {+ Some(MenuNode::Submenu { children, .. }) => children.clone(),+ _ => panic!("no Open Recent Library submenu in {file:?}"),+ }+ }++ /// File ▸ Open Recent Library ▸ Remove from List and `app.recentLibraries {remove}`.+ #[test]+ fn open_recent_library_and_the_command_remove_one_entry() {+ use crate::menubar::MenuNode;+ let dir = temp("menu");+ let mut session = lightcraft_engine::Session::new().with_fs();+ session.open_library(dir.join("first"), false).unwrap();+ let mut app = LightcraftApp::new(session, Services::default());+ let (first, gone) = (dir.join("first").to_string_lossy().into_owned(), dir.join("gone").to_string_lossy().into_owned());+ app.ui.settings.recent_libraries = vec![first.clone(), gone.clone(), "/elsewhere/third".into()];++ let items = open_recent(&app);+ let Some(MenuNode::Submenu { children, .. }) = items.iter().find(|n| matches!(n, MenuNode::Submenu { label, .. } if label == "Remove from List"))+ else {+ panic!("no Remove from List in {items:?}")+ };+ assert_eq!(children.len(), 3, "every entry, missing ones too");+ let MenuNode::Item { id, params, label, enabled, .. } = &children[1] else { panic!("{children:?}") };+ assert_eq!((id.as_str(), params, *enabled), ("app.recentLibraries", &json!({"remove": gone}), true));+ assert!(label.starts_with("gone — "), "{label}");+ assert_eq!(crate::menubar::display_item_label(id, params, label), label, "a path is never translated");+ // what clicking it runs+ let list = app.run(id, params.clone()).unwrap();+ assert_eq!(list.as_array().unwrap().len(), 2);+ assert_eq!(app.ui.settings.recent_libraries, [first.clone(), "/elsewhere/third".to_string()]);++ // the command: the open library can be forgotten too (it stays open), and nothing is deleted+ let list = app.run("app.recentLibraries", json!({"remove": first})).unwrap();+ // (no frame ran: nothing checked yet, so `exists` is not known; the command never looks itself)+ assert_eq!(list, json!([{"path": "/elsewhere/third", "name": "third", "exists": null, "checking": false, "open": false, "lastOpened": null}]));+ assert!(app.session.library.is_some() && lightcraft_engine::library::is_library(&dir.join("first")));+ let e = app.run("app.recentLibraries", json!({"remove": first})).unwrap_err();+ assert!(e.contains("not in the recent libraries"), "{e}");+ let e = app.run("app.recentLibraries", json!({"remove": 3})).unwrap_err();+ assert!(e.contains("remove must be"), "{e}");+ app.run("app.recentLibraries", json!({"remove": "/elsewhere/third"})).unwrap();+ // an empty list has nothing to remove+ let items = open_recent(&app);+ assert!(!items.iter().any(|n| matches!(n, MenuNode::Submenu { .. })), "{items:?}");+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// `atLaunch` and `recentLibrariesOpened` round-trip, and older or odd files still load.+ #[test]+ fn the_setting_and_the_open_times_are_kept_in_the_settings_file() {+ // files from earlier versions: no key, the default; a value from a later version: the default+ let old: crate::UiState = serde_json::from_str(r#"{"settings": {"recentLibraries": ["/a"], "startupView": "detail"}}"#).unwrap();+ assert_eq!(old.settings.at_launch, LaunchLibrary::Last);+ assert!(old.settings.recent_opened.is_empty());+ assert_eq!(old.settings.recent_libraries, ["/a"]);+ let odd: crate::UiState =+ serde_json::from_str(r#"{"settings": {"atLaunch": "someday", "recentLibrariesOpened": 7, "startupView": "detail"}}"#).unwrap();+ assert_eq!(odd.settings.at_launch, LaunchLibrary::Last);+ assert!(odd.settings.recent_opened.is_empty());+ assert_eq!(odd.settings.startup_view, crate::state::StartupView::Detail, "the rest of the file still loads");++ let mut ui = crate::UiState::default();+ ui.settings.at_launch = LaunchLibrary::Ask;+ ui.settings.recent_libraries = vec!["/a".into()];+ ui.settings.recent_opened.insert("/a".into(), "2026-10-23T09:00:00".into());+ let saved = serde_json::to_value(&ui).unwrap();+ assert_eq!(saved["settings"]["atLaunch"], "ask");+ assert_eq!(saved["settings"]["recentLibraries"], json!(["/a"]), "the list keeps its old shape");+ assert_eq!(saved["settings"]["recentLibrariesOpened"], json!({"/a": "2026-10-23T09:00:00"}));+ let back: crate::UiState = serde_json::from_value(saved).unwrap();+ assert_eq!(back.settings, ui.settings);+ }++ /// The Settings choice and `ui.set` change the setting; an opened library gets its time.+ #[test]+ fn settings_choose_ask_me_and_opening_a_library_records_when() {+ let dir = temp("settings");+ let mut session = lightcraft_engine::Session::new().with_fs();+ session.open_library(dir.join("first"), false).unwrap();+ let mut app = LightcraftApp::new(session, Services::default());+ app.services.pick_folder = Some(Box::new(|| None));+ app.ui.settings.recent_opened.insert("/forgotten".into(), "2020-01-01T00:00:00".into());+ let mut h = Headless::new(app, [1300.0, 900.0], 1.0);+ settle(&mut h);+ let first = dir.join("first").to_string_lossy().into_owned();+ // the session clock's time (tests: a fixed one), only for listed libraries+ assert_eq!(h.app.ui.settings.recent_opened.get(&first).map(String::as_str), Some("2026-09-30T12:00:00"));+ assert!(!h.app.ui.settings.recent_opened.contains_key("/forgotten"));++ h.request("engine.execute", json!({"command": "app.settings", "params": {"tab": "general"}}), T);+ settle(&mut h);+ assert_eq!(h.request("ui.clickWidget", json!({"id": "button:settingsAtLaunch-1"}), T)["ok"], true);+ settle(&mut h);+ assert_eq!(h.app.ui.settings.at_launch, LaunchLibrary::Ask);+ h.request("ui.clickWidget", json!({"id": "button:settingsAtLaunch-0"}), T);+ settle(&mut h);+ assert_eq!(h.app.ui.settings.at_launch, LaunchLibrary::Last);+ // also through ui.set, as scripts change settings+ let r = h.request("ui.set", json!({"settings": {"atLaunch": "ask"}}), T);+ assert_eq!(r["ok"], true, "{r}");+ assert_eq!(h.app.ui.settings.at_launch, LaunchLibrary::Ask);+ drop(h);+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// The app as the host starts it with *Open the last library*: `first` open, Alt watched.+ fn opened_last(dir: &Path) -> (Headless, String, String) {+ let (first, second) = (make_library(&dir.join("first")), make_library(&dir.join("second")));+ let mut session = lightcraft_engine::Session::new().with_fs();+ session.open_library(&first, false).unwrap();+ let mut app = LightcraftApp::new(session, Services::default());+ app.ui.settings.recent_libraries = vec![first.clone(), second.clone()];+ app.ui.settings.library_path = first.clone();+ app.alt_asks_for_library = true;+ (Headless::new(app, [1300.0, 900.0], 1.0), first, second)+ }++ /// Alt held as the window appears shows the list once over the open library; Esc keeps it.+ #[test]+ fn alt_held_as_the_window_appears_asks_once_over_the_last_library() {+ let dir = temp("alt");+ let (mut h, first, _) = opened_last(&dir);+ settle(&mut h);+ assert!(h.app.library_problem.is_none(), "no Alt: the last library, no window");+ h.app.synthetic.push(egui::Event::ModifiersChanged(egui::Modifiers::ALT));+ settle(&mut h);+ let c = h.app.library_problem.as_ref().and_then(|p| p.chooser.clone()).expect("the list shows");+ assert_eq!(c.selected, Some(0));+ assert!(c.over.is_some(), "over the library that opened");+ assert!(c.libraries[0].unavailable.is_none(), "the open library itself can be chosen");+ assert!(has(&h, "button:libraryOpen"));+ // Esc keeps the library that opened+ h.request("ui.key", json!({"key": "Escape"}), T);+ settle(&mut h);+ assert!(!h.quit_requested(), "Esc doesn't quit while a library is open");+ assert!(h.app.library_problem.is_none());+ assert_eq!(h.app.session.library.as_ref().map(|l| l.dir.to_string_lossy().into_owned()), Some(first.clone()));+ // once only+ h.app.synthetic.push(egui::Event::ModifiersChanged(egui::Modifiers::NONE));+ h.app.synthetic.push(egui::Event::ModifiersChanged(egui::Modifiers::ALT));+ settle(&mut h);+ assert!(h.app.library_problem.is_none());+ drop(h);++ // choosing another library from it switches to that one+ let dir2 = temp("alt-switch");+ let (mut h, _, second2) = opened_last(&dir2);+ h.app.synthetic.push(egui::Event::ModifiersChanged(egui::Modifiers::ALT));+ settle(&mut h);+ h.request("ui.key", json!({"key": "ArrowDown"}), T);+ settle(&mut h);+ h.request("ui.key", json!({"key": "Enter"}), T);+ settle(&mut h);+ assert_eq!(h.app.session.library.as_ref().map(|l| l.dir.to_string_lossy().into_owned()), Some(second2));+ assert!(h.app.library_problem.is_none());+ drop(h);+ let _ = std::fs::remove_dir_all(&dir);+ let _ = std::fs::remove_dir_all(&dir2);+ }++ /// The Alt watch ends after the first seconds and needs the host to arm it.+ #[test]+ fn alt_is_only_watched_while_the_window_first_appears_and_when_armed() {+ let frame = |app: &mut LightcraftApp, ctx: &egui::Context, time: f64, alt: bool| {+ let modifiers = if alt { egui::Modifiers::ALT } else { egui::Modifiers::NONE };+ let raw = egui::RawInput { time: Some(time), events: vec![egui::Event::ModifiersChanged(modifiers)], ..Default::default() };+ ctx.run_ui(raw, |ui| crate::panels::library_problem::logic(app, ui.ctx())).textures_delta.clear();+ };+ let new_app = |armed| {+ let mut app = LightcraftApp::new(lightcraft_engine::Session::new(), Services::default());+ app.alt_asks_for_library = armed;+ app+ };+ // too late: the watch ends, a later Alt does nothing+ let (mut app, ctx) = (new_app(true), egui::Context::default());+ frame(&mut app, &ctx, ALT_SECONDS + 0.5, false);+ assert!(!app.alt_asks_for_library);+ frame(&mut app, &ctx, ALT_SECONDS + 0.6, true);+ assert!(app.library_problem.is_none());+ // not armed (--library, LIGHTCRAFT_LIBRARY, --memory, the browser)+ let (mut app, ctx) = (new_app(false), egui::Context::default());+ frame(&mut app, &ctx, 0.1, true);+ assert!(app.library_problem.is_none());+ // armed, in time+ let (mut app, ctx) = (new_app(true), egui::Context::default());+ frame(&mut app, &ctx, 0.1, false);+ assert!(app.alt_asks_for_library && app.library_problem.is_none());+ frame(&mut app, &ctx, 0.2, true);+ assert!(app.library_problem.as_ref().is_some_and(|p| p.chooser.is_some()));+ assert!(!app.alt_asks_for_library);+ }++ /// A check that waits until the test lets it go (a network share whose server is gone), then+ /// answers like the real one for a missing folder. `release` lets every waiting check go.+ fn slow_checks() -> (+ crate::panels::library_problem::RecentChecks,+ std::sync::Arc<(std::sync::Mutex<bool>, std::sync::Condvar)>,+ std::sync::Arc<std::sync::atomic::AtomicUsize>,+ ) {+ let gate = std::sync::Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new()));+ let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let (g, n) = (gate.clone(), calls.clone());+ let checks = crate::panels::library_problem::RecentChecks::with_check(move |p| {+ n.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ let (lock, cv) = &*g;+ let open = lock.lock().unwrap();+ // (bounded: a test that forgets to release still ends)+ let _unused = cv.wait_timeout_while(open, Duration::from_secs(10), |open| !*open).unwrap();+ (!Path::new(p).exists()).then_some(crate::panels::library_problem::Unavailable::NotFound)+ });+ (checks, gate, calls)+ }++ /// Let every check waiting in [`slow_checks`] answer.+ fn release(gate: &std::sync::Arc<(std::sync::Mutex<bool>, std::sync::Condvar)>) {+ let (lock, cv) = &**gate;+ *lock.lock().unwrap() = true;+ cv.notify_all();+ }++ /// Review of #2701: the launch list never waits on a folder. Its rows show "Checking…" while a+ /// worker looks (the activity stack lists it), the window keeps drawing frames meanwhile, and the+ /// answers grey out a missing library and move the selection to one that can be opened.+ #[test]+ fn a_slow_check_never_holds_the_launch_window() {+ let dir = temp("slow");+ let a = make_library(&dir.join("A"));+ let gone = dir.join("Gone").to_string_lossy().into_owned();+ let mut app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services::default());+ app.ui.settings.recent_libraries = vec![gone.clone(), a.clone()];+ app.ui.settings.library_path = gone.clone();+ let (checks, gate, _) = slow_checks();+ app.recent_checks = checks;+ app.library_problem = Some(LibraryProblem::choose_later(&app.ui.settings));+ let mut h = Headless::new(app, [1300.0, 900.0], 1.0);+ let t0 = std::time::Instant::now();+ settle(&mut h);+ assert!(t0.elapsed() < Duration::from_secs(5), "frames went on while the check waited: {:?}", t0.elapsed());+ let c = h.app.library_problem.as_ref().and_then(|p| p.chooser.clone()).unwrap();+ assert!(c.libraries.iter().all(|l| l.checking && l.unavailable.is_none()), "{c:?}");+ assert_eq!(c.selected, Some(0), "the last library opened, until the answers say otherwise");+ assert!(h.painted_text().iter().any(|t| t == "Checking…"), "{:?}", h.painted_text());+ assert!(h.app.session.activity.list().iter().any(|t| t.label == "Checking recent libraries"), "the activity stack lists the check");++ release(&gate);+ let done =+ h.step_until(T, |h| h.app.library_problem.as_ref().and_then(|p| p.chooser.as_ref()).is_some_and(|c| c.libraries.iter().all(|l| !l.checking)));+ assert!(done, "the answers came back");+ let c = h.app.library_problem.as_ref().and_then(|p| p.chooser.clone()).unwrap();+ assert!(c.libraries[0].unavailable.as_deref().is_some_and(|w| w.contains("Not found")), "{c:?}");+ assert_eq!(c.libraries[1].unavailable, None);+ assert_eq!(c.selected, Some(1), "the first library that can be opened, once known");+ assert!(h.app.session.activity.list().iter().all(|t| t.label != "Checking recent libraries"), "the row goes with the check");+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// Answers that arrive after the person moved the highlight leave it where they put it.+ #[test]+ fn late_answers_keep_the_row_the_person_chose() {+ let dir = temp("touched");+ let a = make_library(&dir.join("A"));+ let gone = dir.join("Gone").to_string_lossy().into_owned();+ let mut app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services::default());+ app.ui.settings.recent_libraries = vec![a.clone(), gone.clone()];+ app.ui.settings.library_path = a.clone();+ let (checks, gate, _) = slow_checks();+ app.recent_checks = checks;+ app.library_problem = Some(LibraryProblem::choose_later(&app.ui.settings));+ let mut h = Headless::new(app, [1300.0, 900.0], 1.0);+ settle(&mut h);+ h.request("ui.key", json!({"key": "ArrowDown"}), T);+ settle(&mut h);+ release(&gate);+ h.step_until(T, |h| h.app.library_problem.as_ref().and_then(|p| p.chooser.as_ref()).is_some_and(|c| c.libraries.iter().all(|l| !l.checking)));+ let c = h.app.library_problem.as_ref().and_then(|p| p.chooser.clone()).unwrap();+ assert_eq!(c.selected, Some(1), "still the row moved to, though it can't be opened");+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// File ▸ Open Recent Library is rebuilt every frame: it never looks at a folder itself. A+ /// library is greyed out only once a worker found it missing, and each path is checked once.+ #[test]+ fn the_recent_menu_takes_its_answers_from_a_worker() {+ use crate::menubar::MenuNode;+ let dir = temp("menu-worker");+ let gone = dir.join("Gone").to_string_lossy().into_owned();+ let mut app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services::default());+ app.ui.settings.recent_libraries = vec![gone.clone()];+ let (checks, gate, calls) = slow_checks();+ app.recent_checks = checks;+ let mut h = Headless::new(app, [1300.0, 900.0], 1.0);+ let enabled = |h: &Headless| match open_recent(&h.app).first() {+ Some(MenuNode::Item { enabled, .. }) => *enabled,+ other => panic!("{other:?}"),+ };+ for _ in 0..30 {+ h.step();+ assert!(enabled(&h), "not known yet: kept enabled (opening says why if it can't)");+ }+ release(&gate);+ assert!(h.step_until(T, |h| !h.app.recent_checks.is_running() && h.app.recent_checks.is_known(&gone)), "answered");+ for _ in 0..30 {+ h.step();+ }+ assert!(!enabled(&h), "found missing: greyed out");+ assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1, "checked once, not every frame");+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// The reasons are put into words on the UI thread, in the interface language (the worker that+ /// found them has none of its own).+ #[test]+ fn the_reasons_are_in_the_interface_language() {+ let dir = temp("lang");+ let gone = dir.join("Gone").to_string_lossy().into_owned();+ let mut app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services::default());+ app.ui.language = crate::i18n::Locale::Fr;+ app.ui.settings.recent_libraries = vec![gone.clone()];+ app.library_problem = Some(LibraryProblem::choose_later(&app.ui.settings));+ let mut h = Headless::new(app, [1300.0, 900.0], 1.0);+ assert!(+ h.step_until(T, |h| h.app.library_problem.as_ref().and_then(|p| p.chooser.as_ref()).is_some_and(|c| c.libraries.iter().all(|l| !l.checking)))+ );+ let c = h.app.library_problem.as_ref().and_then(|p| p.chooser.clone()).unwrap();+ let why = c.libraries[0].unavailable.clone().unwrap_or_default();+ let english = "Not found: moved, renamed or on a disconnected drive";+ crate::i18n::set_language(crate::i18n::Locale::Fr);+ assert_eq!(why, crate::i18n::tr(english), "translated on the UI thread");+ assert_ne!(why, english, "the French catalog has this reason");+ crate::i18n::set_language(crate::i18n::Locale::En);+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// One drive that never answers doesn't hold the others: each path has its own worker, and the+ /// row that waits says the drive isn't answering once it takes long.+ #[test]+ fn one_hung_drive_doesnt_hold_the_other_libraries() {+ let dir = temp("hung");+ let a = make_library(&dir.join("A"));+ let hung = dir.join("Hung").to_string_lossy().into_owned();+ let gate = std::sync::Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new()));+ let g = gate.clone();+ let h_path = hung.clone();+ let mut app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services::default());+ app.recent_checks = crate::panels::library_problem::RecentChecks::with_check(move |p| {+ if p == h_path {+ let (lock, cv) = &*g;+ let open = lock.lock().unwrap();+ let _unused = cv.wait_timeout_while(open, Duration::from_secs(10), |open| !*open).unwrap();+ }+ None+ });+ app.ui.settings.recent_libraries = vec![hung.clone(), a.clone()];+ app.library_problem = Some(LibraryProblem::choose_later(&app.ui.settings));+ let mut h = Headless::new(app, [1300.0, 900.0], 1.0);+ let a_done = h.step_until(T, |h| h.app.library_problem.as_ref().and_then(|p| p.chooser.as_ref()).is_some_and(|c| !c.libraries[1].checking));+ assert!(a_done, "the reachable library answered while the other one hangs");+ let c = h.app.library_problem.as_ref().and_then(|p| p.chooser.clone()).unwrap();+ assert!(c.libraries[0].checking, "the hung one is still checking");+ release(&gate);+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// A check whose worker dies (a panic) ends as "couldn't be checked" instead of leaving the row,+ /// and every later check, waiting forever.+ #[test]+ fn a_check_that_dies_doesnt_leave_the_list_waiting() {+ let dir = temp("dies");+ let a = make_library(&dir.join("A"));+ let mut app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services::default());+ app.recent_checks = crate::panels::library_problem::RecentChecks::with_check(|_| panic!("a check that dies"));+ app.ui.settings.recent_libraries = vec![a.clone()];+ app.library_problem = Some(LibraryProblem::choose_later(&app.ui.settings));+ let mut h = Headless::new(app, [1300.0, 900.0], 1.0);+ let done = h.step_until(T, |h| h.app.library_problem.as_ref().and_then(|p| p.chooser.as_ref()).is_some_and(|c| !c.libraries[0].checking));+ assert!(done, "the row stopped waiting");+ assert!(!h.app.recent_checks.is_running(), "no check is left running");+ let c = h.app.library_problem.as_ref().and_then(|p| p.chooser.clone()).unwrap();+ assert!(c.libraries[0].unavailable.as_deref().is_some_and(|w| w.contains("couldn't be checked")), "{c:?}");+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// A library found missing comes back once it is opened again (a drive plugged back in): the+ /// menu no longer greys it out.+ #[test]+ fn opening_a_library_clears_an_old_missing_answer() {+ use crate::menubar::MenuNode;+ let dir = temp("back");+ let a = make_library(&dir.join("A"));+ let mut app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services::default());+ app.ui.settings.recent_libraries = vec![a.clone()];+ app.recent_checks = crate::panels::library_problem::RecentChecks::with_check(|_| Some(crate::panels::library_problem::Unavailable::NotFound));+ let ctx = egui::Context::default();+ crate::panels::library_problem::logic(&mut app, &ctx);+ assert!(crate::tasks::wait(&mut app, &ctx, T), "checked");+ assert_eq!(app.recent_checks.exists(&a), Some(false), "found missing (the drive was disconnected)");+ let mut h = Headless::new(app, [1300.0, 900.0], 1.0);+ h.app.run("app.openLibrary", json!({"path": a})).unwrap();+ for _ in 0..4 {+ h.step();+ }+ assert!(matches!(open_recent(&h.app).first(), Some(MenuNode::Item { enabled: true, .. })), "{:?}", open_recent(&h.app));+ assert_eq!(h.app.recent_checks.reason(&a), None);+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// Review of #2701: a library that fails to open from the launch window because another program+ /// has it is there all the same. The row shows the open's error, but the menu keeps it enabled and+ /// `app.recentLibraries` says it exists; an unreadable catalog doesn't say the library is gone+ /// either (`exists: null`).+ #[test]+ fn a_failed_open_or_an_unreadable_catalog_doesnt_mark_a_library_missing() {+ use crate::menubar::MenuNode;+ let dir = temp("held");+ let held = make_library(&dir.join("Held"));+ let mut app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services::default());+ app.ui.settings.recent_libraries = vec![held.clone()];+ app.ui.settings.library_path = held.clone();+ app.library_problem = Some(LibraryProblem::choose_later(&app.ui.settings));+ let mut h = Headless::new(app, [1300.0, 900.0], 1.0);+ let answered =+ |h: &Headless| h.app.library_problem.as_ref().and_then(|p| p.chooser.as_ref()).is_some_and(|c| c.libraries.iter().all(|l| !l.checking));+ assert!(h.step_until(T, answered));+ assert_eq!(h.app.recent_checks.exists(&held), Some(true));+ // another program has it: Open from the launch window fails+ let lock = lightcraft_catalog::LibraryLock::acquire(Path::new(&held), "another LightCraft").unwrap();+ settle(&mut h);+ let r = h.request("ui.clickWidget", json!({"id": "button:libraryOpen"}), T);+ assert_eq!(r["ok"], true, "{r} {:?}", h.app.widgets.iter().map(|(w, _)| w.clone()).filter(|w| w.contains("library")).collect::<Vec<_>>());+ settle(&mut h);+ let c = h.app.library_problem.as_ref().and_then(|p| p.chooser.clone()).unwrap();+ assert!(c.libraries[0].unavailable.is_some(), "the row shows why it didn't open: {c:?}");+ assert!(h.step_until(T, |h| !h.app.recent_checks.is_running() && h.app.recent_checks.is_known(&held)), "checked again");+ assert_eq!(h.app.recent_checks.exists(&held), Some(true), "a failed open doesn't mark it missing");+ let list = h.app.run("app.recentLibraries", json!({})).unwrap();+ assert_eq!(list[0]["exists"], true, "{list}");+ assert!(matches!(open_recent(&h.app).first(), Some(MenuNode::Item { enabled: true, .. })), "{:?}", open_recent(&h.app));+ drop(lock);++ // an unreadable catalog: not known to be gone+ h.app.recent_checks = crate::panels::library_problem::RecentChecks::with_check(|_| {+ Some(crate::panels::library_problem::Unavailable::CatalogUnreadable("denied".into()))+ });+ assert!(h.step_until(T, |h| h.app.recent_checks.is_known(&held) && !h.app.recent_checks.is_running()));+ assert_eq!(h.app.run("app.recentLibraries", json!({})).unwrap()[0]["exists"], serde_json::Value::Null);+ assert!(matches!(open_recent(&h.app).first(), Some(MenuNode::Item { enabled: true, .. })));+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// Photos dropped on the launch list wait for the library chosen (CodeRabbit on #2689): before,+ /// they went into the session the library then replaced, and were gone from view.+ #[test]+ fn photos_dropped_on_the_launch_list_go_into_the_library_chosen() {+ let dir = temp("drop");+ let a = make_library(&dir.join("Alpha"));+ let mut h = asking(vec![a.clone()], &a, None);+ let img = lightcraft_raster::Rgba8 { width: 8, height: 8, data: vec![[90, 3, 9, 255]; 64] };+ let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap();+ let photo = dir.join("a.png");+ std::fs::write(&photo, png).unwrap();+ // frames with nothing dropped (the drop code runs every frame) hold nothing and say nothing+ settle(&mut h);+ assert!(h.app.ui.toast.is_none(), "{:?}", h.app.ui.toast);+ let ctx = h.view.ctx.clone();+ assert_eq!(crate::panels::library_problem::hold_dropped(&mut h.app, &ctx, Vec::new()), Some(Vec::new()));+ assert!(h.app.ui.toast.is_none(), "an empty drop says nothing: {:?}", h.app.ui.toast);+ let photos = vec![photo.to_string_lossy().into_owned()];+ assert!(crate::panels::library_problem::holds_drops(&h.app));+ assert_eq!(crate::panels::library_problem::hold_dropped(&mut h.app, &ctx, photos.clone()), None, "held while no library is open");+ assert_eq!(h.app.library_problem.as_ref().map(|p| p.pending_import.clone()), Some(photos.clone()));+ assert!(h.app.ui.toast.as_ref().is_some_and(|t| t.0.contains("once a library is open")), "{:?}", h.app.ui.toast);+ assert_eq!(h.app.session.catalog.len(), 0, "nothing goes into the session the library replaces");+ assert_eq!(h.request("ui.clickWidget", json!({"id": "button:libraryOpen"}), T)["ok"], true);+ settle(&mut h);+ h.step_until(T, |h| h.app.import.is_none() && h.app.session.catalog.len() == 1);+ assert_eq!(h.app.session.catalog.len(), 1, "the dropped photo is imported into the library opened");+ // with a library open, a drop is the usual import+ assert!(!crate::panels::library_problem::holds_drops(&h.app));+ assert_eq!(crate::panels::library_problem::hold_dropped(&mut h.app, &ctx, photos.clone()), Some(photos));+ drop(h);+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// A lookup that fails without saying the library is gone (here a parent folder it may not read;+ /// a network share that timed out is the same) is "couldn't check", not "not found": the entry+ /// isn't greyed out in File ▸ Open Recent Library (CodeRabbit on #2689).+ #[cfg(unix)]+ #[test]+ fn a_failed_lookup_doesnt_mark_a_recent_library_missing() {+ use std::os::unix::fs::PermissionsExt;+ /// Gives the folder its permissions back and removes the test's folder, also when an assertion+ /// fails (a folder left at mode 000 can't be removed).+ struct Cleanup(std::path::PathBuf, std::path::PathBuf);+ impl Drop for Cleanup {+ fn drop(&mut self) {+ let _ = std::fs::set_permissions(&self.1, std::fs::Permissions::from_mode(0o755));+ let _ = std::fs::remove_dir_all(&self.0);+ }+ }+ let dir = temp("lookup");+ let locked = dir.join("Locked");+ let _cleanup = Cleanup(dir.clone(), locked.clone());+ let inside = make_library(&locked.join("Inside"));+ let gone = dir.join("Gone").to_string_lossy().into_owned();+ std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();+ if std::fs::read_dir(&locked).is_ok() {+ // running as root (some CI containers): the mode bits don't stop it, so no lookup fails+ lightcraft_testkit::skip!(System, "a folder with no permissions can still be read (running as root)");+ return;+ }+ let mut app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services::default());+ app.ui.settings.recent_libraries = vec![inside.clone(), gone.clone()];+ let mut h = Headless::new(app, [900.0, 600.0], 1.0);+ let answered = h.step_until(T, |h| h.app.recent_checks.is_known(&inside) && h.app.recent_checks.is_known(&gone));+ assert!(answered);+ assert_eq!(h.app.recent_checks.exists(&gone), Some(false), "a library that isn't there is missing");+ assert_eq!(h.app.recent_checks.exists(&inside), None, "one that couldn't be looked at isn't");+ let why = h.app.recent_checks.reason(&inside).map(|w| w.text()).unwrap_or_default();+ assert!(why.starts_with("This library couldn't be checked:"), "{why}");+ // nor is a folder that is there but refuses to be listed (permissions, macOS privacy)+ use crate::panels::library_problem::Unavailable;+ assert!(!Unavailable::Unreadable("denied".into()).is_missing() && !Unavailable::LookupFailed("timed out".into()).is_missing());+ assert!(Unavailable::NotFound.is_missing());+ drop(h);+ }++ /// A library found is asked about again when the window comes back to the front, not on a timer: a+ /// timer would wake every external drive and network share in the list over and over. One not+ /// found is looked for again on its own (a drive plugged back in with the app in front).+ #[test]+ fn recent_libraries_are_checked_again_only_when_the_window_comes_back() {+ use std::sync::atomic::{AtomicUsize, Ordering};+ let dir = temp("recheck");+ let a = make_library(&dir.join("A"));+ let gone = dir.join("Gone").to_string_lossy().into_owned();+ let (calls, gone_calls) = (std::sync::Arc::new(AtomicUsize::new(0)), std::sync::Arc::new(AtomicUsize::new(0)));+ let (c, g, gone_path) = (calls.clone(), gone_calls.clone(), gone.clone());+ let mut app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services::default());+ app.recent_checks = crate::panels::library_problem::RecentChecks::with_check(move |p| {+ if p == gone_path {+ g.fetch_add(1, Ordering::SeqCst);+ return Some(crate::panels::library_problem::Unavailable::NotFound);+ }+ c.fetch_add(1, Ordering::SeqCst);+ None+ })+ .recheck_after(Duration::ZERO);+ app.ui.settings.recent_libraries = vec![a.clone(), gone.clone()];+ let mut h = Headless::new(app, [900.0, 600.0], 1.0);+ assert!(h.step_until(T, |h| h.app.recent_checks.exists(&a) == Some(true)));+ assert!(h.step_until(T, |_| gone_calls.load(Ordering::SeqCst) >= 3), "the one not found is looked for again on its own");+ // focused all along, every answer "old": nothing is asked again+ for _ in 0..30 {+ h.step();+ }+ assert_eq!(calls.load(Ordering::SeqCst), 1, "no check on a timer");+ // the window went to the back and comes to the front again+ h.app.recent_checks.focused = false;+ assert!(h.step_until(T, |_| calls.load(Ordering::SeqCst) == 2), "asked again when the window comes back");+ for _ in 0..10 {+ h.step();+ }+ assert_eq!(calls.load(Ordering::SeqCst), 2, "once");+ drop(h);+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// A library the launch list showed as not found comes back to it once found again (a drive plugged+ /// back in while the list is up): the row waits for the new check instead of keeping its old answer+ /// (FredApps on #2689, #2774).+ #[test]+ fn a_library_found_again_comes_back_to_the_launch_list() {++ found_again(false);++}++++/// The same when every frame is laid out twice (`request_discard`): an answer applied in a frame is++/// visible through all of its passes, and scheduling does not ask about it again in that frame.++#[test]++fn a_library_found_again_comes_back_to_the_launch_list_across_a_multipass_frame() {++ found_again(true);++}++++fn found_again(multipass: bool) {+ use std::sync::atomic::{AtomicBool, Ordering};- let dir = temp("found-again");++ let dir = temp(if multipass { "found-again-multipass" } else { "found-again" });+ let a = make_library(&dir.join("A"));+ let plugged = std::sync::Arc::new(AtomicBool::new(false));+ let p = plugged.clone();+ let mut app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services::default());+ app.recent_checks = crate::panels::library_problem::RecentChecks::with_check(move |_| {+ (!p.load(Ordering::SeqCst)).then_some(crate::panels::library_problem::Unavailable::NotFound)+ })+ .recheck_after(Duration::ZERO);+ app.ui.settings.recent_libraries = vec![a.clone()];+ app.library_problem = Some(LibraryProblem::choose_later(&app.ui.settings));+ let mut h = Headless::new(app, [1300.0, 900.0], 1.0);++ if multipass {++ // The existing context hook egui calls at the start of every pass: ask for the second layout++ // pass on every pass 0 (which egui otherwise does only for e.g. a Grid sizing change).++ h.view.ctx.on_begin_pass(++ "test: force a second layout pass",++ std::sync::Arc::new(|ui: &mut egui::Ui| {++ if ui.ctx().current_pass_index() == 0 {++ ui.ctx().request_discard("test: force a second layout pass");++ }++ }),++ );++ let passes = h.view.ctx.cumulative_pass_nr();++ h.step();++ assert_eq!(h.view.ctx.cumulative_pass_nr() - passes, 2, "the hook forced the second pass");++ }+ let row = |h: &Headless| h.app.library_problem.as_ref().and_then(|p| p.chooser.as_ref()).map(|c| c.libraries[0].clone()).unwrap();+ assert!(+ h.step_until(T, |h| {+ let r = row(h);+ !r.checking && r.unavailable.is_some()+ }),+ "not found first"+ );+ plugged.store(true, Ordering::SeqCst);+ assert!(+ h.step_until(T, |h| {+ let r = row(h);+ !r.checking && r.unavailable.is_none()+ }),+ "found again: it can be opened, {:?}",+ row(&h)+ );+ drop(h);+ let _ = std::fs::remove_dir_all(&dir);+ }diff --cc crates/ui-egui/src/tests_progress.rsindex 000000000,476b8a1a6..09e9234a0mode 000000,100644..100644--- a/crates/ui-egui/src/tests_progress.rs+++ b/crates/ui-egui/src/tests_progress.rs@@@ -1,0 -1,284 +1,284 @@@+ //! Progress bars, spinners and busy buttons: the fraction is always a sane number, a bar is+ //! announced as progress with its percentage and reachable by its id, a busy button is announced+ //! busy, ignores clicks and keeps its width, and a thumbnail's placeholder stands apart from what+ //! it sits on in every theme.++ use egui::{Pos2, Rect, pos2, vec2};++ use crate::button::{Button, contrast};+ use crate::icons::Icon;+ use crate::progress::{Progress, clamp_fraction, fraction_of, spinner};+ use crate::theme::{ThemeKind, Tokens};++ /// What a screen reader gets for one node.+ #[derive(Debug, Clone, PartialEq)]+ struct Node {+ role: String,+ label: String,+ busy: bool,+ value: Option<f64>,+ }++ /// Run three frames of `draw` (pointer `events` in the second); return the nodes of the last+ /// frame with an accessibility tree, the automation ids registered in the last frame, and what+ /// `draw` returned.+ fn frames<T: Default>(events: Vec<egui::Event>, mut draw: impl FnMut(&mut egui::Ui) -> T) -> (Vec<Node>, Vec<(String, Rect)>, T) {+ let ctx = egui::Context::default();+ crate::theme::install_fonts(&ctx);+ ctx.enable_accesskit();+ let (mut nodes, mut ids, mut last) = (Vec::new(), Vec::new(), T::default());+ for frame in 0..3 {+ let raw = egui::RawInput {+ screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))),+ events: if frame == 1 { events.clone() } else { Vec::new() },+ ..Default::default()+ };+ let mut out = ctx.run_ui(raw, |ui| last = draw(ui));+ out.textures_delta.clear();+ ids = crate::widgets::take_registry(&ctx);+ if let Some(update) = out.platform_output.accesskit_update.take() {+ nodes = update+ .nodes+ .iter()+ .map(|(_, n)| Node {+ role: format!("{:?}", n.role()),+ label: n.label().unwrap_or_default().to_string(),+ busy: n.is_busy(),+ value: n.numeric_value(),+ })+ .collect();+ }+ }+ (nodes, ids, last)+ }++ #[test]+ fn the_fraction_is_always_between_nothing_and_all() {+ assert_eq!(clamp_fraction(f32::NAN), 0.0);+ assert_eq!(clamp_fraction(-3.0), 0.0);+ assert_eq!(clamp_fraction(7.5), 1.0);+ assert_eq!(clamp_fraction(f32::INFINITY), 1.0);+ assert_eq!(clamp_fraction(f32::NEG_INFINITY), 0.0);+ assert_eq!(clamp_fraction(0.25), 0.25);+ assert_eq!(Progress::new(Some(f32::NAN)).fraction(), Some(0.0));+ assert_eq!(Progress::new(Some(2.0)).fraction(), Some(1.0));+ assert_eq!(Progress::new(None).fraction(), None);+ }++ #[test]+ fn an_unknown_total_is_an_indeterminate_bar_not_an_empty_one() {+ assert_eq!(fraction_of(0, 0), None);+ assert_eq!(fraction_of(5, 0), None);+ assert_eq!(fraction_of(0, 10), Some(0.0));+ assert_eq!(fraction_of(5, 10), Some(0.5));+ assert_eq!(fraction_of(20, 10), Some(1.0));+ }++ #[test]+ fn a_bar_is_progress_with_a_value_and_reachable_by_its_id() {+ let (nodes, ids, _) = frames(Vec::new(), |ui| {+ Progress::new(Some(0.42)).label("Making the denoised picture… 42%").widget("denoise:progress").show(ui);+ });+ let bar = nodes.iter().find(|n| n.role == "ProgressIndicator").unwrap_or_else(|| panic!("no progress node: {nodes:?}"));+ assert_eq!(bar.label, "Making the denoised picture… 42%");+ assert_eq!(bar.value, Some(42.0));+ assert!(ids.iter().any(|(id, r)| id == "denoise:progress" && r.width() > 0.0), "{ids:?}");+ }++ #[test]+ fn an_indeterminate_bar_says_progress_without_a_value_and_is_drawn() {+ let (nodes, ids, width) = frames(Vec::new(), |ui| Progress::new(None).label("Starting…").widget("p:x").show(ui).rect.width());+ let bar = nodes.iter().find(|n| n.role == "ProgressIndicator").unwrap_or_else(|| panic!("{nodes:?}"));+ assert_eq!(bar.value, None);+ assert!(ids.iter().any(|(id, _)| id == "p:x"));+ assert!(width >= 96.0, "fills the width the layout has");+ }++ #[test]+ fn a_bar_fills_the_layout_unless_given_a_width() {+ let (_, _, (fill, fixed, tiny_room)) = frames(Vec::new(), |ui| {+ let fill = Progress::new(Some(0.5)).show(ui).rect.width();+ let fixed = Progress::new(Some(0.5)).width(150.0).show(ui).rect.width();+ let tiny_room = ui.scope(|ui| {+ ui.set_max_width(40.0);+ Progress::new(Some(0.5)).show(ui).rect.width()+ });+ (fill, fixed, tiny_room.inner)+ });+ assert!(fill > 300.0, "fills: {fill}");+ assert_eq!(fixed, 150.0);+ assert!(tiny_room >= 96.0, "never a sliver: {tiny_room}");+ }++ #[test]+ fn a_spinner_takes_the_room_it_is_given() {+ let (_, _, size) = frames(Vec::new(), |ui| spinner(ui, 14.0).rect.size());+ assert_eq!(size, vec2(14.0, 14.0));+ }++ fn click_at(at: Pos2) -> Vec<egui::Event> {+ vec![+ egui::Event::PointerMoved(at),+ egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() },+ egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() },+ ]+ }++ #[test]+ fn a_busy_button_ignores_clicks_and_is_announced_busy() {+ let place = Rect::from_min_size(Pos2::ZERO, vec2(120.0, 30.0));+ let click = |busy: bool| {+ let mut clicked = false;+ let (nodes, _, ()) = frames(click_at(pos2(40.0, 15.0)), |ui| clicked |= Button::new("Analyze").busy(busy).show_at(ui, place).clicked());+ (nodes, clicked)+ };+ let (nodes, clicked) = click(true);+ assert!(!clicked, "a busy button does nothing");+ let node = nodes.iter().find(|n| n.role == "Button" && n.label == "Analyze").unwrap_or_else(|| panic!("{nodes:?}"));+ assert!(node.busy, "announced busy");++ let (nodes, clicked) = click(false);+ assert!(clicked, "the same button, not busy, is clicked");+ assert!(!nodes.iter().any(|n| n.busy), "{nodes:?}");+ }++ #[test]+ fn a_busy_button_stays_reachable_by_the_keyboard() {+ let place = Rect::from_min_size(Pos2::ZERO, vec2(120.0, 30.0));+ let mut asked = false;+ let (_, _, focused) = frames(Vec::new(), |ui| {+ let r = Button::new("Analyze").busy(true).show_at(ui, place);+ if !std::mem::replace(&mut asked, true) {+ r.request_focus();+ }+ r.has_focus()+ });+ assert!(focused, "focus is kept while it works");+ }++ #[test]+ fn a_button_keeps_its_width_while_busy() {+ for (text, icon) in [("Analyze", None), ("Analyze", Some(Icon::Trash)), ("", Some(Icon::Trash))] {+ for small in [false, true] {+ let (_, _, (idle, busy)) = frames(Vec::new(), |ui| {+ let mut make = |b: bool| {+ let mut btn = if text.is_empty() { Button::icon_only(Icon::Trash, "Remove") } else { Button::new(text) };+ if let Some(i) = icon {+ btn = btn.icon(i);+ }+ if small {+ btn = btn.small();+ }+ btn.busy(b).show(ui).rect.size()+ };+ (make(false), make(true))+ });+ assert_eq!(idle, busy, "{text:?} {icon:?} small={small}");+ }+ }+ }++ #[test]+ fn the_thumbnail_placeholder_stands_apart_in_every_theme() {+ for kind in ThemeKind::ALL {+ let t = Tokens::for_kind(kind);+ for (name, behind) in [("grid", t.grid_bg), ("cell", t.cell), ("selected cell", t.cell_selected), ("canvas", t.canvas)] {+ let c = contrast(t.skeleton, behind);+ // the light themes' surfaces are close together, so the placeholder has to be set+ // further off them to read at all+ let floor = if matches!(kind, ThemeKind::Silver | ThemeKind::Paper) { 1.15 } else { 1.1 };+ assert!(c >= floor, "{kind:?}: the placeholder on the {name} is {c:.2}:1");+ }+ let mark = contrast(t.text, t.skeleton);+ assert!(mark >= 3.0, "{kind:?}: the failure mark on the placeholder is {mark:.2}:1");+ }+ }++ #[test]+ fn a_failed_filmstrip_thumbnail_is_announced_with_its_reason() {+ let spoken = |failed: bool| {+ let (nodes, _, _) = frames(Vec::new(), |ui| {- let resp = ui.interact(Rect::from_min_size(pos2(10.0, 10.0), vec2(120.0, 80.0)), egui::Id::new("film-test"), egui::Sense::click());++ let resp = ui.interact(Rect::from_min_size(pos2(10.0, 10.0), vec2(120.0, 80.0)), egui::Id::unique("film-test"), egui::Sense::click());+ crate::widgets::announce(&resp, crate::panels::detail::film_spoken("IMG_0001.jpg", failed));+ });+ nodes.into_iter().find(|n| n.role == "Button").map(|n| n.label)+ };+ assert_eq!(spoken(false).as_deref(), Some("IMG_0001.jpg"));+ assert_eq!(spoken(true).as_deref(), Some("IMG_0001.jpg, This photo can't be opened"));+ }++ #[test]+ fn a_failed_filmstrip_thumbnail_without_a_file_name_has_no_leading_comma() {+ assert_eq!(crate::panels::detail::film_spoken("", true), "This photo can't be opened");+ assert_eq!(crate::panels::detail::film_spoken("", false), "");+ }++ #[test]+ fn the_sam_bar_keeps_its_name_and_height_while_the_size_is_unknown() {+ let (nodes, _, (known, unknown)) = frames(Vec::new(), |ui| {+ let known = crate::panels::masking::sam_download_bar(ui, 5, 10, 200.0).rect.height();+ let unknown = crate::panels::masking::sam_download_bar(ui, 0, 0, 200.0).rect.height();+ (known, unknown)+ });+ assert_eq!(known, unknown);+ let bars: Vec<_> = nodes.iter().filter(|n| n.role == "ProgressIndicator").collect();+ assert_eq!(bars.len(), 2, "{nodes:?}");+ assert!(bars.iter().all(|b| b.label.starts_with("SAM 3")), "{bars:?}");+ }++ #[test]+ fn the_denoise_bars_keep_their_widths_in_a_wide_container() {+ let (_, ids, (detail, settings, unknown)) = frames(Vec::new(), |ui| {+ let detail = crate::panels::denoise::detail_bar(ui, 3, 10).rect.width();+ let settings = crate::panels::denoise::settings_bar(ui, 3, 10, "Denoising a.jpg: 3 of 10 tiles".into()).rect.width();+ let unknown = crate::panels::denoise::detail_bar(ui, 0, 0).rect.width();+ (detail, settings, unknown)+ });+ assert_eq!((detail, settings, unknown), (240.0, 380.0, 240.0));+ assert!(ids.iter().any(|(id, _)| id == "denoise:settingsProgress"));+ }++ #[test]+ fn the_denoise_bar_label_and_its_accessible_value_agree() {+ // the number drawn on the bar is the one announced, and exact decimals stay exact+ for (done, total, says) in+ [(3, 7, 42.0), (53, 100, 53.0), (59, 100, 59.0), (29, 100, 29.0), (99, 100, 99.0), (100, 100, 100.0), (999, 1000, 99.0)]+ {+ let (nodes, _, _) = frames(Vec::new(), |ui| {+ crate::panels::denoise::detail_bar(ui, done, total);+ });+ let bar = nodes.iter().find(|n| n.role == "ProgressIndicator").unwrap_or_else(|| panic!("{nodes:?}"));+ let shown: f64 = bar.label.rsplit(' ').next().unwrap().trim_end_matches('%').parse().unwrap();+ assert_eq!((shown, bar.value), (says, Some(says)), "{done}/{total}: {bar:?}");+ }+ }++ #[test]+ fn the_sam_bar_text_and_its_accessible_value_agree() {+ for (done, total, says) in [(53, 100, 53.0), (59, 100, 59.0), (29, 100, 29.0), (999, 1000, 99.0), (100, 100, 100.0)] {+ let (nodes, _, _) = frames(Vec::new(), |ui| crate::panels::masking::sam_download_bar(ui, done, total, 200.0).rect.width());+ let bar = nodes.iter().find(|n| n.role == "ProgressIndicator").unwrap_or_else(|| panic!("{nodes:?}"));+ assert_eq!(bar.label, format!("SAM 3: {says} %"), "{done}/{total}");+ assert_eq!(bar.value, Some(says), "{done}/{total}");+ }+ }++ #[test]+ fn an_activity_bar_is_named_after_its_task() {+ let task = lightcraft_engine::activity::TaskInfo {+ id: 1,+ kind: "export",+ label: "Exporting".into(),+ done: 3,+ total: 25,+ unit: lightcraft_engine::activity::Unit::Count,+ detail: String::new(),+ cancellable: true,+ cancelling: false,+ age_ms: 600,+ };+ let (nodes, _, _) = frames(Vec::new(), |ui| crate::panels::activity::bar(ui, &task, 200.0).rect.width());+ let bar = nodes.iter().find(|n| n.role == "ProgressIndicator").unwrap_or_else(|| panic!("{nodes:?}"));+ assert_eq!(bar.label, "Exporting");+ assert_eq!(bar.value, Some(12.0));+ }diff --cc crates/ui-egui/src/tests_rating.rsindex 000000000,f89d1267b..d473508d3mode 000000,100644..100644--- a/crates/ui-egui/src/tests_rating.rs+++ b/crates/ui-egui/src/tests_rating.rs@@@ -1,0 -1,238 +1,238 @@@+ //! The star rating: clicking sets the rating, clicking the current one clears it, the row is one+ //! Tab stop, the arrow keys step it, and screen readers hear every star.++ use egui::{Pos2, Rect, vec2};++ use crate::rating::Rating;++ /// Draw `build` for a few frames. After the first, click the centre of star `click` (1 to 5) if given,+ /// then press `keys`. Returns every value `build` reported and the AccessKit+ /// (role, name) pairs.+ fn drive(click: Option<u8>, keys: &[egui::Key], build: impl Fn(&mut egui::Ui) -> Option<u8>) -> (Vec<u8>, Vec<(String, String)>) {+ let ctx = egui::Context::default();+ crate::theme::install_fonts(&ctx);+ ctx.enable_accesskit();+ let mut reported = Vec::new();+ let mut nodes = Vec::new();+ let mut rects: Vec<(String, Rect)> = Vec::new();+ for frame in 0..6 {+ let mut events = Vec::new();+ if frame == 1+ && let Some(n) = click+ {+ let want = format!("star:t:{n}");+ let at = rects.iter().find(|(id, _)| *id == want).map(|(_, r)| r.center()).unwrap_or(Pos2::ZERO);+ events.push(egui::Event::PointerMoved(at));+ events.push(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() });+ events.push(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() });+ }+ // one key per frame from the third on, so Tab has moved the focus before an arrow arrives+ if frame >= 2+ && let Some(k) = keys.get(frame - 2)+ {+ events.push(egui::Event::Key { key: *k, physical_key: Some(*k), pressed: true, repeat: false, modifiers: Default::default() });+ }+ let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 200.0))), events, ..Default::default() };+ let mut out = ctx.run_ui(raw, |ui| {+ if let Some(v) = build(ui) {+ reported.push(v);+ }+ });+ out.textures_delta.clear();+ let seen = crate::widgets::take_registry(&ctx);+ if rects.is_empty() {+ rects = seen;+ }+ if let Some(update) = out.platform_output.accesskit_update.take() {+ nodes = update.nodes.iter().map(|(_, n)| (format!("{:?}", n.role()), n.label().unwrap_or_default().to_string())).collect();+ }+ }+ (reported, nodes)+ }++ fn row(rating: u8) -> Rating {+ Rating::new("t", rating)+ }++ #[test]+ fn clicking_a_star_sets_that_rating() {+ let (got, _) = drive(Some(4), &[], |ui| row(2).show(ui));+ assert_eq!(got, vec![4]);+ }++ #[test]+ fn clicking_the_current_rating_clears_it() {+ let (got, _) = drive(Some(3), &[], |ui| row(3).show(ui));+ assert_eq!(got, vec![0]);+ }++ #[test]+ fn hovering_alone_changes_nothing() {+ // the preview is only painted; the rating is reported on click+ let (got, _) = drive(None, &[], |ui| row(2).show(ui));+ assert!(got.is_empty());+ }++ /// How many stars `Rating::show` paints filled (in the star colour) after the pointer has moved to+ /// the centre of star `hover` (1 to 5), if given. A filled star is ten triangles of one colour.+ fn filled_stars(rating: u8, hover: Option<u8>) -> usize {+ fn count(shape: &egui::Shape, colour: egui::Color32) -> usize {+ match shape {+ egui::Shape::Path(path) => usize::from(path.fill == colour),+ egui::Shape::Vec(shapes) => shapes.iter().map(|shape| count(shape, colour)).sum(),+ _ => 0,+ }+ }+ let ctx = egui::Context::default();+ crate::theme::install_fonts(&ctx);+ let colour = crate::theme::Tokens::get(&ctx).star;+ let mut at = None;+ let mut filled = 0;+ for frame in 0..4 {+ let mut events = Vec::new();+ if frame >= 1+ && let Some(at) = at+ {+ events.push(egui::Event::PointerMoved(at));+ }+ let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 200.0))), events, ..Default::default() };+ let mut out = ctx.run_ui(raw, |ui| {+ let _ = row(rating).show(ui);+ });+ out.textures_delta.clear();+ let seen = crate::widgets::take_registry(&ctx);+ if let (Some(n), true) = (hover, frame == 0) {+ let want = format!("star:t:{n}");+ at = seen.iter().find(|(id, _)| *id == want).map(|(_, r)| r.center());+ assert!(at.is_some(), "star {n} is registered");+ }+ filled = out.shapes.iter().map(|clipped| count(&clipped.shape, colour)).sum::<usize>() / 10;+ }+ filled+ }++ #[test]+ fn hovering_a_star_paints_the_rating_a_click_would_set() {+ // the row shows 2 filled stars; the pointer over star 4 shows 4, and over star 1 shows 1+ assert_eq!(filled_stars(2, None), 2);+ assert_eq!(filled_stars(2, Some(4)), 4);+ assert_eq!(filled_stars(2, Some(1)), 1, "hovering a lower star previews the lower rating");+ }++ #[test]+ fn a_screen_reader_hears_every_star_with_its_state() {+ let (_, nodes) = drive(None, &[], |ui| row(2).show(ui));+ for n in 1..=5 {+ let name = format!("{n} ★");+ assert!(nodes.iter().any(|(role, label)| role == "Button" && *label == name), "{name}: {nodes:?}");+ }+ }++ #[test]+ fn the_arrow_keys_step_the_rating_of_a_focused_star() {+ // Tab focuses the first star; the row shows 3, so → asks for 4 and ← for 2+ let (got, _) = drive(None, &[egui::Key::Tab, egui::Key::ArrowRight], |ui| row(3).show(ui));+ assert_eq!(got, vec![4], "{got:?}");+ let (got, _) = drive(None, &[egui::Key::Tab, egui::Key::ArrowLeft], |ui| row(3).show(ui));+ assert_eq!(got, vec![2], "{got:?}");+ }++ #[test]+ fn arrow_keys_do_nothing_when_no_star_is_focused() {+ let (got, _) = drive(None, &[egui::Key::ArrowRight], |ui| row(3).show(ui));+ assert!(got.is_empty(), "{got:?}");+ }++ /// Feed the shown rating back each frame, with other focusable widgets on both sides.+ fn step_with_neighbours(start: u8, keys: &[egui::Key]) -> Vec<u8> {+ let ctx = egui::Context::default();+ crate::theme::install_fonts(&ctx);+ let rating = std::cell::Cell::new(start);+ let mut seen = Vec::new();+ // a key every frame, Tab then an arrow straight away+ for frame in 0..keys.len() + 3 {+ let mut events = Vec::new();+ if let Some(k) = frame.checked_sub(1).and_then(|f| keys.get(f)) {+ events.push(egui::Event::Key { key: *k, physical_key: Some(*k), pressed: true, repeat: false, modifiers: Default::default() });+ }+ let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(600.0, 200.0))), events, ..Default::default() };+ let mut out = ctx.run_ui(raw, |ui| {+ ui.horizontal(|ui| {+ let _ = ui.button("left neighbour");+ if let Some(r) = row(rating.get()).show(ui) {+ rating.set(r);+ }+ let _ = ui.button("right neighbour");+ });+ });+ out.textures_delta.clear();+ seen.push(rating.get());+ }+ seen+ }++ #[test]+ fn arrows_keep_stepping_between_other_focusable_widgets() {+ use egui::Key::*;+ // Tab, Tab: the left neighbour, then star 1+ let seen = step_with_neighbours(5, &[Tab, Tab, ArrowLeft, ArrowLeft, ArrowLeft, ArrowLeft, ArrowLeft]);+ assert_eq!(seen.last(), Some(&0), "{seen:?}");+ let seen = step_with_neighbours(0, &[Tab, Tab, ArrowRight, ArrowRight, ArrowRight, ArrowRight, ArrowRight, ArrowLeft]);+ assert_eq!(seen.last(), Some(&4), "{seen:?}");+ }++ #[test]+ fn a_rating_row_is_one_tab_stop() {+ use egui::Key::Tab;+ // left neighbour, one stop for the five stars, right neighbour: the third Tab is already past the row+ let ctx = egui::Context::default();+ crate::theme::install_fonts(&ctx);+ let mut focused = Vec::new();+ for frame in 0..5 {+ let events = if frame >= 1 {+ vec![egui::Event::Key { key: Tab, physical_key: Some(Tab), pressed: true, repeat: false, modifiers: Default::default() }]+ } else {+ Vec::new()+ };+ let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(600.0, 200.0))), events, ..Default::default() };+ let mut right = None;+ let mut out = ctx.run_ui(raw, |ui| {+ ui.horizontal(|ui| {+ let _ = ui.button("left neighbour");+ let _ = row(3).show(ui);+ right = Some(ui.button("right neighbour").id);+ });+ });+ out.textures_delta.clear();+ focused.push(right.is_some_and(|id| ctx.memory(|m| m.has_focus(id))));+ }+ // frames 1 to 3 press Tab: left neighbour, the row, right neighbour+ assert_eq!(focused, vec![false, false, false, true, false], "{focused:?}");+ }++ #[test]+ fn a_rating_changed_from_outside_moves_the_focus_to_the_tab_stop() {+ use egui::Key::Tab;+ let ctx = egui::Context::default();+ crate::theme::install_fonts(&ctx);+ let rating = std::cell::Cell::new(2u8);+ let mut stars_focused = Vec::new();+ for frame in 0..5 {+ // frame 1: Tab focuses the row's stop (star 2); frame 2: the rating changes elsewhere to 5+ if frame == 2 {+ rating.set(5);+ }+ let events = if frame == 1 {+ vec![egui::Event::Key { key: Tab, physical_key: Some(Tab), pressed: true, repeat: false, modifiers: Default::default() }]+ } else {+ Vec::new()+ };+ let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(600.0, 200.0))), events, ..Default::default() };+ let mut out = ctx.run_ui(raw, |ui| {+ let _ = row(rating.get()).show(ui);- stars_focused = (0..5).map(|i| ctx.memory(|m| m.has_focus(ui.id().with(("rating-star", "t", i as u8))))).collect();++ stars_focused = (0..5).map(|i| ctx.memory(|m| m.has_focus(ui.scope_id().with(("rating-star", "t", i as u8))))).collect();+ });+ out.textures_delta.clear();+ }+ assert_eq!(stars_focused, vec![false, false, false, false, true], "{stars_focused:?}");+ }diff --cc docs/control-protocol.mdindex 91c2ea079,7a8033aa5..d45a76cb2--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@@ -90,8 -90,9 +90,9 @@@ filmstrip is visible| `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.dropFiles` | `{paths: [..], hover?}` | Files dragged from the file manager. `hover: true` makes every following frame report `paths` as hovered over the window (the drop card appears, `ui.widgets` lists `dropOverlay`) until another `ui.dropFiles` replaces them; `{paths: [], hover: true}` ends the hover. Without `hover` the files are dropped: the hover ends and the next frame receives them as dropped files, exactly as an OS drop arrives (photos and folders open the import review, or import at once with Settings ▸ Import ▸ Import dropped files without review). An empty path stands for a file whose path the platform doesn't tell || `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 --cc docs/egui-037-migration-plan.mdindex 22417aa6f,000000000..d34b931cemode 100644,000000..100644--- a/docs/egui-037-migration-plan.md+++ b/docs/egui-037-migration-plan.md@@@ -1,1523 -1,0 +1,1536 @@@+# LightCraft: egui 0.37 migration plan+++Current landing status, 2026-10-25: the migration integrates main `38f8d2508700fa4938295e865d3fc21be07266ba` and uses egui `6d518fc799681571963842f95b55a6b68431b15a`, winit `a517b3846ee8457d84ee4975110bfda6797c44dc` and craft-ui `25da1314d443171b4adeaad2cd9454b273f35c6f`. Cargo.lock SHA-256 is `6336b4aa2ac9df57cb8feaafb097b30fa7228ef427f5e213fac1a2a7875e4181`; the independent craft-docpath pin remains selected in the lockfile. Release workflows use craft-fonts `b076417b5880bd4154bd22f00695b1d28c6bea83`.++++Fresh static review verified preservation of the captured main and the final dependency graph. The final managed CI run `egui037-lightcraft-library-frame-ci-20261025-0551` passed all eight stages. Including its focused library tests, the log records 5,083 passing test executions, zero failures and 42 ignored across 142 summaries. The CI prerequisite report separately identifies 149 tests that returned without exercising their checks (corpus137, models8, fonts2, GPU1, system1); these are coverage gaps. Earlier passing counts below qualify their historical snapshots only. The icon-font attribution URL now identifies the selected egui source; font bytes are unchanged. Visible GUI, browser/platform runtime, native IME, final packages and paired performance remain separate acceptance gates. Human review and human merge are required.++++The review packet separately records inherited default-font notice coverage and Inter licence staging gaps. Nix font-pin drift is fixed as described below; the other inherited gaps are not established as fixed by the migration or by source-level notice routing checks.++++Current status note (2026-10-25): `flake.nix` now points at craft-fonts `b076417b5880bd4154bd22f00695b1d28c6bea83`, matching CI, the release workflow and the standalone packaging helpers, and `flake.lock` was regenerated by Nix 2.26.3 using `nix flake update craft-fonts` against the canonical GitHub revision. Only the craft-fonts node changed; nixpkgs stayed pinned. Linux x86_64 flake evaluation passed with `nix flake check --no-build --no-write-lock-file` (job `egui037-lightcraft-nix-eval-20261025-0495`). No Nix package build, executed formatting derivation, or other architecture is claimed. The inherited gaps above (egui default-font licence coverage for Hack, Ubuntu-Light and NotoEmoji-Regular; the Inter OFL packaging omission) are not migration-introduced, and this landing updates the craft-fonts notices and attribution text only.++++Library-check results now remain visible for the frame in which they arrive, so a zero-delay refresh cannot immediately replace a fresh missing-library answer. The scheduling fence uses the root UI frame number across all layout passes; focused regressions cover the single-pass and forced-multipass cases with isolated temporary directories. Fresh static review accepted the delivery-frame behavior.++++The original planning and earlier qualification record follows. Its pins, hashes, paths and passing counts are historical.+++++## 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,747 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.++The current-main integration includes `4ae3089420cb57d4c839e51a735d4f48271cbf17` and+preserves its catalog hardening and other changes. Independent review caught a bad-chain+memoization error: a descendant visited before a broken ancestor could be detached unnecessarily.+The repair caches only proven valid chains and removes the offending parent edge, preserving+valid descendants. Regressions cover child-before-cycle, child-before-missing-parent and a valid+513-folder chain through actual catalog snapshot/reopen paths. All nine focused catalog repair+tests passed before the full eight-stage CI run on the merged source. The only formatting change+after the source review wraps one let-chain condition; the lockfile remains unchanged.++Actual visible UI, native platform/IME/PRIMARY, browser behavior, final release-package notices+and paired performance acceptance remain open. This application branch has not been published.++## 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 --cc docs/releasing.mdindex 914a7ad84,914a7ad84..1704492d1--- a/docs/releasing.md+++ b/docs/releasing.md@@@ -66,7 -66,7 +66,7 @@@ the web build requires BIZ UDPGothic ReLocal macOS, Linux and Windows packaging scripts automatically use the sibling `../craft-fonts`checkout. If it is absent, they clone it at revision--`3d9ab3a132ed0eff457e424226a435a901da30d3` (keep the pins in `packaging/fonts.sh` and++`b076417b5880bd4154bd22f00695b1d28c6bea83` (keep the pins in `packaging/fonts.sh` and`packaging/windows/fonts.ps1` in sync with the release workflow). Existing checkouts are left untouched.Set `CRAFT_FONTS_DIR` to use anothercheckout; relative paths resolve from the workspace root. The script requires the Chinese and Japanesediff --cc flake.lockindex a9953fd12,a9953fd12..29faf1a7c--- a/flake.lock+++ b/flake.lock@@@ -3,17 -3,17 +3,17 @@@"craft-fonts": {"flake": false,"locked": {-- "lastModified": 1791722036,-- "narHash": "sha256-mNnDzBcOp1X10dzmiW0iBAkb74QjuzMO4slWudxXCTE=",++ "lastModified": 1792808533,++ "narHash": "sha256-jZ3VBAJDofB6RvsS7GGV5lLT4xiShIjpz5XHBCD2oUc=","owner": "storytold","repo": "craft-fonts",-- "rev": "3d9ab3a132ed0eff457e424226a435a901da30d3",++ "rev": "b076417b5880bd4154bd22f00695b1d28c6bea83","type": "github"},"original": {"owner": "storytold","repo": "craft-fonts",-- "rev": "3d9ab3a132ed0eff457e424226a435a901da30d3",++ "rev": "b076417b5880bd4154bd22f00695b1d28c6bea83","type": "github"}},diff --cc flake.nixindex 51dd933f9,7f838ebda..faa7e1d2e--- a/flake.nix+++ b/flake.nix@@@ -6,13 -6,13 +6,17 @@@# release channel can retarget it: `inputs.lightcraft.inputs.nixpkgs.follows = "nixpkgs";`nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";-- # Optional build input of the repository: the CJK fonts (BIZ UDPGothic, BIZ UDMincho, Noto Sans CJK SC,-- # Shippori Mincho) that `crates/engine/build.rs` embeds when `CRAFT_FONTS_DIR` is set. Official-- # releases always build with them; without them everything works but Japanese text has no-- # glyphs. Pinned to the revision the release workflow uses — bump deliberately-- # (`nix flake update craft-fonts`); craftrules standards/fonts.md.++ # Optional build input of the repository: the default fonts (BIZ UDPGothic Regular/Bold, BIZ UDMincho,++ # Shippori Mincho, Noto Sans CJK SC, Noto Sans Arabic, Noto Sans Thai, Noto Sans Georgian,++ # NanumGothic, Noto Sans Symbols, Noto Sans Symbols 2, Noto Sans Hebrew and Noto Sans Devanagari)++ # listed in craft-fonts' `fonts/manifest.txt`, which `crates/engine/build.rs` embeds when++ # `CRAFT_FONTS_DIR` is set. The opt-in LXGW WenKai Lite face in `fonts/simplified-chinese-manifest.txt`++ # is not part of that default set and is not embedded. Official releases always build with the++ # default fonts; without them everything works but non-Latin text lacks glyphs. Pinned to the same++ # revision CI, the release workflow and the standalone packaging helpers use — bump all of them++ # together (`nix flake update craft-fonts`); craftrules standards/fonts.md.craft-fonts = {-- url = "github:storytold/craft-fonts/3d9ab3a132ed0eff457e424226a435a901da30d3";++ url = "github:storytold/craft-fonts/b076417b5880bd4154bd22f00695b1d28c6bea83";flake = false;};};diff --cc packaging/linux/flatpak/ai.storyteller.lightcraft.ymlindex e9dbd244b,e9dbd244b..c983daae8--- a/packaging/linux/flatpak/ai.storyteller.lightcraft.yml+++ b/packaging/linux/flatpak/ai.storyteller.lightcraft.yml@@@ -52,6 -52,6 +52,8 @@@ modules- install -Dm644 packaging/linux/ai.storyteller.lightcraft.desktop /app/share/applications/ai.storyteller.lightcraft.desktop- install -Dm644 packaging/linux/ai.storyteller.lightcraft.mime.xml /app/share/mime/packages/ai.storyteller.lightcraft.xml- mkdir -p /app/share/icons && cp -R assets/app-icon/hicolor /app/share/icons/++ - install -Dm644 NOTICE /app/share/doc/lightcraft/NOTICE++ - install -Dm644 assets/ATTRIBUTION.md /app/share/doc/lightcraft/ATTRIBUTION.md- >-version=$(awk '/^\[/{p=($0=="[workspace.package]");next} p&&$1=="version"{gsub(/[" ]/,"",$3);print $3;exit}' Cargo.toml);install -d /app/share/metainfo;diff --cc packaging/windows/lightcraft.wxsindex 533c24d20,533c24d20..9e23e5430--- a/packaging/windows/lightcraft.wxs+++ b/packaging/windows/lightcraft.wxs@@@ -206,6 -206,6 +206,9 @@@<Component Id="LightcraftCli"><File Id="LightcraftCliExe" Source="$(var.BinDir)\lightcraft-cli.exe" KeyPath="yes" /></Component>++ <Component Id="LightcraftNotice">++ <File Id="LightcraftNoticeFile" Source="$(var.BinDir)\NOTICE" KeyPath="yes" />++ </Component><Component Id="LightcraftFontLicences"><File Id="LightcraftFontLicencesFile" Source="$(var.BinDir)\FONT-LICENCES.txt" KeyPath="yes" /></Component>diff --cc packaging/windows/package.ps1index 50aa77ea8,50aa77ea8..110d8b60c--- a/packaging/windows/package.ps1+++ b/packaging/windows/package.ps1@@@ -116,6 -116,6 +116,8 @@@ $Stage = Join-Path $TargetDir "windows-Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinueNew-Item -ItemType Directory -Force -Path $Stage | Out-NullCopy-Item (Join-Path $Bin 'lightcraft.exe'), (Join-Path $Bin 'lightcraft-cli.exe') $Stage++# The bundled egui font MIT notice is required even without optional craft-fonts.++Copy-Item -LiteralPath (Join-Path $Root 'NOTICE') -Destination $Stage# Include the embedded fonts' unmodified OFL texts in both installer and portable releases.. (Join-Path $PSScriptRoot 'font-licences.ps1')Write-FontLicences (Join-Path $Stage 'FONT-LICENCES.txt') (Join-Path $Root 'assets\fonts\OFL-Inter.txt') $env:CRAFT_FONTS_DIR