FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
egui037: migrate FilmCraft UI and reconcile current main
skylartaylor4ce159e1cda0
diff --cc ATTRIBUTION.mdindex e8a3a0aa2,e8a3a0aa2..2f683ae46--- a/ATTRIBUTION.md+++ b/ATTRIBUTION.md@@@ -172,3 -172,3 +172,9 @@@ SHA-256 (`crates/speech/src/models.rs`| Asset | Author | Source | Licence ||---|---|---|---|| Whisper tiny / base / small speech-recognition weights (`model.safetensors`, `config.json`, `generation_config.json`, `tokenizer.json`) | OpenAI | `https://huggingface.co/openai/whisper-{tiny,base,small}` (revisions `169d4a43…`, `e37978b9…`, `973afd24…`); weights released with `https://github.com/openai/whisper` | MIT (weights and code, github.com/openai/whisper); the Hugging Face conversion is labelled Apache-2.0 |++++## egui dependency font icons++++| Asset | Author | Source | Licence | Use |++|---|---|---|---|---|++| `epaint_default_fonts::EGUI_ICONS`, `epaint_default_fonts::EMOJI_ICON` (dependency font inputs) | John Slegers | [egui 6d518fc7](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`) | egui-icons.ttf is the five-glyph subset, included by default_fonts independently of monochrome_emoji_fonts; emoji-icon-font.ttf is the full monochrome fallback. Dependency assets unmodified here; no font file copied into this repository. |diff --cc Cargo.lockindex ce1a61540,09b966946..34d78aad8--- a/Cargo.lock+++ b/Cargo.lock@@@ -1023,7 -1027,7 +1023,7 @@@ dependencies =[[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",@@@ -1291,8 -1295,9 +1291,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",@@@ -1324,8 -1329,9 +1324,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",@@@ -1359,8 -1364,9 +1359,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",@@@ -1378,8 -1384,9 +1378,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",@@@ -1397,8 -1404,9 +1397,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",@@@ -1422,8 -1425,9 +1422,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",@@@ -1435,8 -1439,9 +1435,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 = ["eframe","egui",@@@ -1479,8 -1484,9 +1479,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",]@@@ -1540,8 -1546,9 +1540,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",@@@ -1566,8 -1571,9 +1566,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 = "equivalent"@@@ -7331,7 -7266,8 +7334,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",@@@ -7781,23 -7699,3 +7784,23 @@@ dependencies ="syn 3.0.6","winnow 1.0.4",]++[[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 da3882c92,2801176d2..fa7e1a71d--- a/Cargo.toml+++ b/Cargo.toml@@@ -77,13 -77,10 +77,13 @@@ craft-media = { version = "0.1.0", git# ui# Shared frontend components; keep this dependency above the engine boundary.- craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c488caa9fbc2fb1a86e4674887e9b80b598ebbfa", features = ["serde"] }-craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5c874d51eeb3de70e735c8ce87a59a7dedd47675", features = ["serde"] }-egui = "0.36"-eframe = { version = "0.36", default-features = false }-egui_kittest = "0.36"++craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "25da1314d443171b4adeaad2cd9454b273f35c6f", features = ["serde"] }+# egui 0.37: bundled fonts are opt-in, and the monochrome symbol/emoji faces moved to their own+# feature. FilmCraft paints ✔ ✓ ✖ ⚡ ⚠ ⚙ ♪ ☑ in panel chrome, so both features are part of the+# production font policy (system_fonts stays off).+egui = { version = "0.37", features = ["default_fonts", "monochrome_emoji_fonts"] }+eframe = { version = "0.37", default-features = false }+egui_kittest = "0.37"rfd = "0.17"[workspace.lints.rust]@@@ -156,21 -153,3 +156,21 @@@ opt-level =[profile.release]lto = "thin"codegen-units = 1++# 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 d0d113091,d0d113091..f35957a7b--- a/NOTICE+++ b/NOTICE@@@ -19,3 -19,3 +19,20 @@@ Builds made with craft-fonts (CRAFT_FONhttps://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md (BIZ UDPGothic, Shippori Mincho,BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic, Noto Sans Thai, Noto Sans Georgian) — OFL-1.1. Their licence texts ship with the packages as OFL-<family>.txt.Public-domain film and NASA frames and CC0 music shown in README screenshots (docs/images/) — public domain / CC0-1.0. See ATTRIBUTION.md.++++++egui icon font subset (dependency asset)++----------------------------------------++epaint_default_fonts 0.37 embeds egui-icons.ttf, a five-glyph subset of++emoji-icon-font by John Slegers. The full monochrome emoji-icon-font fallback++uses the same MIT license. Upstream license text follows unchanged.++++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/filmcraft-web/src/fs.rsindex a6b23b1c7,d7ec9072f..7f715b4da--- a/apps/filmcraft-web/src/fs.rs+++ b/apps/filmcraft-web/src/fs.rs@@@ -424,12 -424,8 +424,12 @@@ impl Services for WebServices}}- /// Offer bytes as a browser download named `name`. Downloads are clicked at least- /// [`crate::download_pacing::GAP_MS`] apart: Chrome drops a burst of them (#378).+thread_local! {+ static DOWNLOAD_CLOCK: web_time::Instant = web_time::Instant::now();+}++ /// Offer bytes as a browser download named `name`. Downloads are clicked at least+ /// [`crate::download_pacing::GAP_MS`] apart: Chrome drops a burst of them (#378).pub fn download(name: &str, data: &[u8]) -> Result<(), wasm_bindgen::JsValue> {let doc = web_sys::window().and_then(|w| w.document()).ok_or("no document")?;let blob = bytes_to_blob(data, "application/octet-stream")?;diff --cc apps/filmcraft-web/src/lib.rsindex 21512ccc5,21512ccc5..9a6227863--- a/apps/filmcraft-web/src/lib.rs+++ b/apps/filmcraft-web/src/lib.rs@@@ -94,12 -94,12 +94,12 @@@ impl eframe::App for WebAppself.app.raw_input_hook(ctx, raw_input);}-- fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {++ fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {let actions = ACTIONS.with(|a| std::mem::take(&mut *a.borrow_mut()));for f in actions {f(self, ctx);}-- self.app.logic(ctx, frame);++ self.app.logic_inner(ctx);api::poll_replies();// exports advance between frames (no threads)if self.app.session.pump_jobs(std::time::Duration::from_millis(30)) {@@@ -109,6 -109,6 +109,7 @@@a.pump();}self.autosave.tick(&self.app.session, ctx);++ self.app.finish_ime_reset_logic(ctx);}fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {@@@ -159,6 -159,6 +160,7 @@@ pub async fn start(canvas_id: String) -canvas,web_options,Box::new(move |cc| {++ filmcraft_ui_egui::install_ime_reset_callbacks(&cc.egui_ctx);set_context(cc.egui_ctx.clone());let ctx = cc.egui_ctx.clone();fs::set_on_data(move || ctx.request_repaint());diff --cc apps/filmcraft/src/main.rsindex 5ffec5aa2,5ffec5aa2..2f2b6f818--- a/apps/filmcraft/src/main.rs+++ b/apps/filmcraft/src/main.rs@@@ -190,6 -190,6 +190,7 @@@ fn native_options(agent: bool) -> eframfn app_creator(launch: Launch, graphics: graphics::GraphicsStart, created: Arc<AtomicBool>) -> eframe::AppCreator<'static> {let Launch { control_port, control_input_only, files, demo, startup_flag, recover, data_dir, graphics: _ } = launch;Box::new(move |cc| {++ filmcraft_ui_egui::install_ime_reset_callbacks(&cc.egui_ctx);created.store(true, Ordering::Relaxed);// A fallback graphics mode says so in the window, with a button back to the default.let notice = graphics.degraded().then(|| {diff --cc crates/format/src/lib.rsindex a68117bea,aa19bb615..b77968dd1--- a/crates/format/src/lib.rs+++ b/crates/format/src/lib.rs@@@ -216,9 -216,17 +216,20 @@@ pub fn decode(bytes: &[u8]) -> Result<L/// Refuse only values that would overflow or exhaust memory later (`Sequence::check_bounds`);/// structural rules such as overlaps are left to the editor, so projects that open today still open.fn validate_loaded(mut loaded: Loaded) -> Result<Loaded, FormatError> {+ // Graphic layers written before they carried a uid get a stable identity now, before any+ // undo history exists. The field is optional in the schema, so this is not a schema upgrade.+ loaded.project.ensure_graphic_layer_uids();+ // Embedded LUT text is rendered on the hot path. Drop oversize entries at load time so a+ // hostile project cannot retain an unrenderable multi-megabyte source or repeatedly offer it+ // to renderers. Clips that refer to one simply have no LUT, like a deleted library entry.+ let max_lut = filmcraft_project::MAX_LUT_TEXT_BYTES;+ loaded.project.luts.retain(|lut| {+ let keep = lut.text.len() <= max_lut;+ if !keep {+ log::warn!("LUT `{}`: {} bytes, dropping entry above {max_lut} byte limit", lut.name, lut.text.len());+ }+ keep+ });// Out-of-range audio stream data is repaired, not refused: failing the load would lose the// whole project over one bad index. A media item keeps its first `MAX_AUDIO_STREAMS` streams; a// clip pointing past that plays stream 0.diff --cc crates/ui-egui/src/control.rsindex 5327e414e,0fe8fb6aa..1bc44a081--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@@ -27,11 -27,16 +27,18 @@@ use serde_json::{Value, json}const MAX_CLICK_COUNT: u64 = 10;const MAX_DRAG_STEPS: u64 = 1_024;+/// Synthetic input is consumed a step per frame; bound what a client can queue ahead of that.+const MAX_SYNTHETIC_EVENTS: usize = 16_384;+ /// Read a pointer repetition count, using `default` when `key` is absent or null.+ ///+ /// Reject non-integer, negative and above-`maximum` values; raise accepted counts to `minimum`.fn bounded_repetitions(params: &Value, key: &str, default: u64, minimum: u64, maximum: u64) -> Result<u64, String> {- let value = params.get(key).map(|value| value.as_u64().ok_or_else(|| format!("`{key}` must be a non-negative integer"))).transpose()?.unwrap_or(default);+ // The MCP bridge serializes omitted optional counts as null.+ let value = match params.get(key) {+ None | Some(Value::Null) => default,+ Some(value) => value.as_u64().ok_or_else(|| format!("`{key}` must be a non-negative integer"))?,+ };if value > maximum {return Err(format!("`{key}` must not exceed {maximum}"));}diff --cc crates/ui-egui/src/ime_reset.rsindex 000000000,000000000..bc4641d33new file mode 100644--- /dev/null+++ b/crates/ui-egui/src/ime_reset.rs@@@ -1,0 -1,0 +1,441 @@@++//! Ordered admission for the Program monitor's interrupted input method.++//!++//! A reset request is not an acknowledgement. Geometry/focus/output loss retires the local++//! token, and a later actual custom descriptor requests a fresh fence even for the same caret.++++use std::sync::Arc;++++use egui::{Context, IMEPurpose, Id, ImeResetId, ImeTarget, ViewportId, ViewportIdMap};++++#[derive(Clone, Copy, Debug, PartialEq, Eq)]++pub(crate) struct Destination {++ pub document: u64,++ pub target: ImeTarget,++ pub caret: usize,++ pub anchor: usize,++ pub text: u64,++}++++#[derive(Clone, Copy, Debug, PartialEq, Eq)]++pub(crate) struct OutputContext {++ pub owner: Id,++ pub generation: u64,++ pub purpose: IMEPurpose,++}++++impl OutputContext {++ pub(crate) fn of(ime: &egui::output::IMEOutput) -> Self {++ Self { owner: ime.owner, generation: ime.context_generation, purpose: ime.purpose }++ }++}++++#[derive(Clone, Copy, Debug)]++enum Phase {++ NeedsRequest,++ Awaiting(ImeResetId),++ Suspended,++ AllocationFailed,++}++++#[derive(Clone, Copy, Debug)]++struct Pending {++ // The retired composition is separate from the current destination (A -> B releases B).++ origin: ImeTarget,++ destination: Option<Destination>,++ output: Option<OutputContext>,++ phase: Phase,++}++++#[derive(Default)]++pub(crate) struct State {++ pending: ViewportIdMap<Pending>,++ incoming: ViewportIdMap<Destination>,++ completed_origin: ViewportIdMap<ImeTarget>,++ pub viewport: ViewportId,++ custom_output: Option<OutputContext>,++}++++impl State {++ pub(crate) fn begin_pass(&mut self, ctx: &Context) {++ self.viewport = ctx.viewport_id();++ self.custom_output = None;++ }++++ pub(crate) fn blocked(&self, viewport: ViewportId) -> bool {++ self.pending.contains_key(&viewport)++ }++++ pub(crate) fn origin(&self, viewport: ViewportId) -> Option<ImeTarget> {++ self.pending.get(&viewport).map(|p| p.origin).or_else(|| self.completed_origin.get(&viewport).copied())++ }++++ pub(crate) fn incoming_changed(&self, viewport: ViewportId, destination: Destination) -> bool {++ self.incoming.get(&viewport).is_some_and(|old| *old != destination)++ }++++ pub(crate) fn remember(&mut self, viewport: ViewportId, destination: Destination) {++ self.incoming.insert(viewport, destination);++ }++++ pub(crate) fn terminal(&mut self, viewport: ViewportId) {++ self.incoming.remove(&viewport);++ self.completed_origin.remove(&viewport);++ }++++ /// Context-less commands retire an obsolete ID synchronously. Repeated unchanged++ /// reconciliation is inert; the next live local destination flushes NeedsRequest.++ pub(crate) fn interrupt(&mut self, origin: ImeTarget, destination: Option<Destination>) {++ let viewport = self.viewport;++ if let Some(pending) = self.pending.get_mut(&viewport) {++ if pending.destination != destination {++ pending.destination = destination;++ // An unavailable route cannot be rearmed by reconciliation or a control.++ // Only the actual eligible final descriptor may leave Suspended.++ if !matches!(pending.phase, Phase::Suspended) {++ pending.phase = Phase::NeedsRequest;++ }++ }++ } else {++ self.pending.insert(viewport, Pending { origin, destination, output: None, phase: Phase::NeedsRequest });++ }++ }++++ pub(crate) fn suspend(&mut self, viewport: ViewportId) {++ if let Some(pending) = self.pending.get_mut(&viewport) {++ pending.phase = Phase::Suspended;++ pending.output = None;++ }++ }++++ pub(crate) fn owns_output(&self, ctx: &Context) -> bool {++ self.custom_output.is_some() && ctx.output(|out| out.ime.as_ref().map(OutputContext::of)) == self.custom_output++ }++++ fn request(ctx: &Context, pending: &mut Pending) {++ // A new fence invalidates any output context bound to the previous fence. Clearing it++ // also lets `finish` recognize this request as already made in this pass, even when an++ // earlier pass had bound a different descriptor to the old destination.++ pending.output = None;++ pending.phase = ctx.request_ime_reset(ctx.viewport_id()).map_or(Phase::AllocationFailed, Phase::Awaiting);++ }++++ /// Must run with the live local ed/text before EACH raw event, never a staged engine copy.++ pub(crate) fn sync(&mut self, ctx: &Context, destination: Destination) {++ let Some(pending) = self.pending.get_mut(&ctx.viewport_id()) else { return };++ let changed = pending.destination != Some(destination);++ pending.destination = Some(destination);++ // A suspended route cannot admit events until an actual eligible output rearms it.++ if !matches!(pending.phase, Phase::Suspended) && (changed || matches!(pending.phase, Phase::NeedsRequest)) {++ Self::request(ctx, pending);++ }++ }++++ pub(crate) fn complete(&mut self, ctx: &Context, id: ImeResetId, destination: Destination) -> bool {++ let viewport = ctx.viewport_id();++ let Some(pending) = self.pending.get(&viewport).copied() else { return false };++ // The opaque token is necessary but not sufficient: the destination carries the owner++ // and replacement epoch, Film publishes only `IMEPurpose::Normal`, and a generation,++ // purpose or focus transition supersedes or suspends this guard before it can be rearmed. Do not read++ // `ctx.output` here: raw events are processed before this pass has published its custom++ // descriptor, so that would compare against an empty or stale output. The reducer test++ // `changed_output_context_supersedes_and_allocation_failure_stays_blocked` binds a token++ // to one live owner/generation/purpose by rejecting it after each transition.++ if id.viewport_id() != viewport || pending.destination != Some(destination) || !matches!(pending.phase, Phase::Awaiting(current) if current == id) {++ return false;++ }++ self.pending.remove(&viewport);++ self.completed_origin.insert(viewport, pending.origin);++ self.remember(viewport, destination);++ true++ }++++ pub(crate) fn produced(&mut self, key: OutputContext) {++ self.custom_output = Some(key);++ }++++ /// Actual custom eligibility and actual final app output are independent facts. Never++ /// overwrite a stock field or infer native completion from a descriptor/publication.++ pub(crate) fn finish(&mut self, ctx: &Context, destination: Option<Destination>, eligible: bool) {++ let viewport = ctx.viewport_id();++ let actual = ctx.output(|out| out.ime.as_ref().map(OutputContext::of));++ let custom = self.custom_output;++ let Some(pending) = self.pending.get_mut(&viewport) else { return };++ let Some(destination) = destination.filter(|_| eligible && custom.is_some() && actual == custom) else {++ self.suspend(viewport);++ return;++ };++ let changed = pending.destination != Some(destination) || pending.output != custom;++ let activate = matches!(pending.phase, Phase::Suspended | Phase::NeedsRequest);++ // `sync` may already have requested this pass, while `finish` is the first place the++ // actual custom output context is known. Bind that same request to the descriptor instead++ // of allocating a second, silently superseded ID for the same destination transition.++ let requested_by_sync = matches!(pending.phase, Phase::Awaiting(_)) && pending.output.is_none();++ pending.destination = Some(destination);++ if activate || (changed && !requested_by_sync) {++ Self::request(ctx, pending);++ }++ // A request clears the previous fence's binding. Bind the confirmed descriptor only++ // after requesting, so the next pass compares against this output rather than mistaking++ // an earlier pass's unbound request for a same-pass sync request.++ pending.output = custom;++ }++++ pub(crate) fn end_viewport(&mut self, viewport: ViewportId) {++ self.pending.remove(&viewport);++ self.incoming.remove(&viewport);++ self.completed_origin.remove(&viewport);++ }++}++++fn mode_id(viewport: ViewportId) -> Id {++ Id::unique(("filmcraft-ime-reset-ui-pass", viewport))++}++++pub(crate) fn in_ui_pass(ctx: &Context) -> bool {++ ctx.data(|data| data.get_temp::<bool>(mode_id(ctx.viewport_id()))).unwrap_or(false)++}++++/// Install before the first run_ui. The callbacks receive Ui and capture no Context/app.++pub(crate) fn install(ctx: &Context) {++ let installed = Id::unique("filmcraft-ime-reset-mode-installed");++ if ctx.data(|data| data.get_temp::<bool>(installed)).unwrap_or(false) {++ return;++ }++ ctx.on_begin_pass(++ "filmcraft IME reset UI entry",++ Arc::new(|ui| {++ let viewport = ui.ctx().viewport_id();++ ui.data_mut(|data| data.insert_temp(mode_id(viewport), true));++ }),++ );++ ctx.on_end_pass(++ "filmcraft IME reset UI exit",++ Arc::new(|ui| {++ let viewport = ui.ctx().viewport_id();++ ui.data_mut(|data| data.insert_temp(mode_id(viewport), false));++ }),++ );++ ctx.data_mut(|data| data.insert_temp(installed, true));++}++++#[cfg(test)]++mod tests {++ use super::*;++++ fn destination() -> Destination {++ Destination { document: 1, target: ImeTarget::new(Id::unique("film-model-editor"), 1), caret: 3, anchor: 3, text: 17 }++ }++++ fn output(destination: Destination, generation: u64, purpose: IMEPurpose) -> egui::output::IMEOutput {++ egui::output::IMEOutput::new(destination.target.owner, generation, purpose, egui::Rect::ZERO, egui::Rect::ZERO)++ }++++ // These reducer tests use real Context requests/output, not native acknowledgements.++ fn custom_pass(ctx: &Context, state: &mut State, destination: Destination, generation: u64, purpose: IMEPurpose) -> Option<ImeResetId> {++ let mut result = ctx.run_ui(egui::RawInput::default(), |ui| {++ state.begin_pass(ui.ctx());++ let ime = output(destination, generation, purpose);++ state.produced(OutputContext::of(&ime));++ ui.ctx().output_mut(|out| out.ime = Some(ime));++ state.finish(ui.ctx(), Some(destination), true);++ });++ let id = result.platform_output.ime.as_ref().and_then(|ime| ime.reset_request);++ result.textures_delta.clear();++ id++ }++++ #[test]++ fn changed_output_context_supersedes_and_allocation_failure_stays_blocked() {++ let ctx = Context::default();++ install(&ctx);++ let mut state = State::default();++ let destination = destination();++ state.interrupt(destination.target, Some(destination));++ let first = custom_pass(&ctx, &mut state, destination, 1, IMEPurpose::Normal).unwrap();++ assert!(custom_pass(&ctx, &mut state, destination, 1, IMEPurpose::Normal).is_none());++ let second = custom_pass(&ctx, &mut state, destination, 2, IMEPurpose::Normal).unwrap();++ let third = custom_pass(&ctx, &mut state, destination, 2, IMEPurpose::Password).unwrap();++ assert_ne!(first, second);++ assert_ne!(second, third);++ // The old opaque IDs are rejected even though document/target/caret/text are unchanged.++ assert!(!state.complete(&ctx, first, destination));++ assert!(!state.complete(&ctx, second, destination));++ let other_owner = Destination { target: ImeTarget::new(Id::unique("film-other-owner"), 1), ..destination };++ assert!(!state.complete(&ctx, third, other_owner), "the live destination owner is part of the admission boundary");++ assert!(state.blocked(ViewportId::ROOT));++ // Model token exhaustion explicitly; do not attempt to forge an opaque ID.++ state.pending.get_mut(&ViewportId::ROOT).unwrap().phase = Phase::AllocationFailed;++ for _ in 0..3 {++ assert!(custom_pass(&ctx, &mut state, destination, 2, IMEPurpose::Password).is_none());++ assert!(state.blocked(ViewportId::ROOT));++ }++ let changed = Destination { caret: 1, anchor: 1, ..destination };++ state.sync(&ctx, changed);++ let retry = custom_pass(&ctx, &mut state, changed, 2, IMEPurpose::Password).unwrap();++ assert!(state.complete(&ctx, retry, changed));++ assert!(!state.complete(&ctx, retry, changed));++ }++++ #[test]++ fn same_pass_sync_and_finish_keep_one_request() {++ let ctx = Context::default();++ install(&ctx);++ let mut state = State::default();++ let destination = destination();++ state.interrupt(destination.target, Some(destination));++ let mut requested = None;++ let mut result = ctx.run_ui(egui::RawInput::default(), |ui| {++ state.begin_pass(ui.ctx());++ let ime = output(destination, 1, IMEPurpose::Normal);++ state.produced(OutputContext::of(&ime));++ ui.ctx().output_mut(|out| out.ime = Some(ime));++ state.sync(ui.ctx(), destination);++ if let Phase::Awaiting(id) = state.pending[&ViewportId::ROOT].phase {++ requested = Some(id);++ }++ state.finish(ui.ctx(), Some(destination), true);++ assert!(matches!(++ state.pending[&ViewportId::ROOT].phase,++ Phase::Awaiting(id) if Some(id) == requested++ ));++ });++ assert_eq!(result.platform_output.ime.as_ref().and_then(|ime| ime.reset_request), requested);++ result.textures_delta.clear();++ }++++ #[test]++ fn stale_output_binding_does_not_force_a_second_request_on_sync_then_finish() {++ let ctx = Context::default();++ install(&ctx);++ let mut state = State::default();++ let destination = destination();++ state.interrupt(destination.target, Some(destination));++ let stale = custom_pass(&ctx, &mut state, destination, 1, IMEPurpose::Normal).unwrap();++ assert!(matches!(++ state.pending[&ViewportId::ROOT].phase,++ Phase::Awaiting(id) if id == stale++ ));++ assert!(state.pending[&ViewportId::ROOT].output.is_some());++++ // A destination transition retires the fence at the admission boundary but leaves the++ // previous output binding attached until the next actual request replaces it.++ let changed = Destination { caret: 1, anchor: 1, ..destination };++ state.interrupt(destination.target, Some(changed));++ assert!(state.pending[&ViewportId::ROOT].output.is_some(), "an old output context remains bound");++++ let mut requested_by_sync = None;++ let mut result = ctx.run_ui(egui::RawInput::default(), |ui| {++ state.begin_pass(ui.ctx());++ let ime = output(changed, 2, IMEPurpose::Normal);++ state.produced(OutputContext::of(&ime));++ ui.ctx().output_mut(|out| out.ime = Some(ime));++ state.sync(ui.ctx(), changed);++ if let Phase::Awaiting(id) = state.pending[&ViewportId::ROOT].phase {++ requested_by_sync = Some(id);++ }++ state.finish(ui.ctx(), Some(changed), true);++ assert!(++ matches!(++ state.pending[&ViewportId::ROOT].phase,++ Phase::Awaiting(id) if Some(id) == requested_by_sync++ ),++ "finish must reuse the request sync allocated for this destination transition"++ );++ });++ let replacement = requested_by_sync.expect("sync allocated the replacement request");++ assert_ne!(replacement, stale);++ assert_eq!(result.platform_output.ime.as_ref().and_then(|ime| ime.reset_request), Some(replacement));++ result.textures_delta.clear();++++ // The retired R1 is no longer the awaiting boundary and cannot release the guard.++ assert!(!state.complete(&ctx, stale, changed));++ assert!(state.blocked(ViewportId::ROOT));++ assert!(state.complete(&ctx, replacement, changed));++ assert!(!state.blocked(ViewportId::ROOT));++ }++++ #[test]++ fn queued_before_absence_token_may_reach_stock_but_cannot_release_suspended_guard() {++ let ctx = Context::default();++ install(&ctx);++ let mut state = State::default();++ let destination = destination();++ state.interrupt(destination.target, Some(destination));++ let mut queued = None;++ let mut absent = ctx.run_ui(egui::RawInput::default(), |ui| {++ state.begin_pass(ui.ctx());++ state.sync(ui.ctx(), destination);++ if let Phase::Awaiting(id) = state.pending[&ViewportId::ROOT].phase {++ queued = Some(id); // actual Context request returned by the production reducer++ }++ // A later same-pass layout/control loss prevents any descriptor publication.++ state.finish(ui.ctx(), Some(destination), false);++ });++ assert!(absent.platform_output.ime.is_none());++ absent.textures_delta.clear();++ let queued = queued.unwrap();++ let stock_id = Id::unique("film-model-stock-field");++ let mut text = String::from("stock");++ let mut stock = ctx.run_ui(egui::RawInput::default(), |ui| {++ state.begin_pass(ui.ctx());++ ui.memory_mut(|memory| memory.request_focus(stock_id));++ ui.add(egui::TextEdit::singleline(&mut text).id(stock_id));++ // Destination changes on an ineligible route cannot allocate a replacement.++ state.interrupt(destination.target, Some(Destination { caret: 0, anchor: 0, ..destination }));++ state.sync(ui.ctx(), destination);++ assert!(!state.complete(ui.ctx(), queued, destination));++ state.finish(ui.ctx(), Some(destination), false);++ });++ assert_eq!(++ stock.platform_output.ime.as_ref().and_then(|ime| ime.reset_request),++ Some(queued),++ "core may attach ONLY the already queued R1; the public app API cannot cancel it"++ );++ assert!(matches!(state.pending[&ViewportId::ROOT].phase, Phase::Suspended));++ stock.textures_delta.clear();++ ctx.memory_mut(|memory| memory.surrender_focus(stock_id));++ let replacement = custom_pass(&ctx, &mut state, destination, 1, IMEPurpose::Normal).unwrap();++ assert_ne!(replacement, queued);++ assert!(!state.complete(&ctx, queued, destination));++ assert!(state.complete(&ctx, replacement, destination));++ }++++ #[test]++ fn pass_mode_is_per_viewport_and_foreign_completion_cannot_release_a_real_guard() {++ let ctx = Context::default();++ install(&ctx);++ install(&ctx); // creator reuse must not register another pair of callbacks++ let mut state = State::default();++ let destination = destination();++ state.interrupt(destination.target, Some(destination));++ let root = custom_pass(&ctx, &mut state, destination, 1, IMEPurpose::Normal).unwrap();++++ let foreign_viewport = ViewportId::from_hash_of("film-other-window");++ // Register an actual child viewport; a request for an unlisted viewport would be dropped++ // by `Memory::begin_pass` before it could exercise the viewport check at all.++ let mut raw = egui::RawInput { viewport_id: foreign_viewport, ..Default::default() };++ raw.viewports.insert(foreign_viewport, egui::ViewportInfo { parent: Some(ViewportId::ROOT), ..Default::default() });++ let mut foreign = None;++ let mut foreign_output = ctx.run_ui(raw, |ui| {++ assert_eq!(ui.ctx().viewport_id(), foreign_viewport);++ assert!(in_ui_pass(ui.ctx()));++ foreign = ui.ctx().request_ime_reset(foreign_viewport);++ });++ foreign_output.textures_delta.clear();++ let foreign = foreign.expect("the registered child viewport allocated a real request");++++ let mut full = ctx.run_ui(egui::RawInput::default(), |ui| {++ assert!(in_ui_pass(ui.ctx()));++ assert!(!ui.data(|data| data.get_temp::<bool>(mode_id(foreign_viewport))).unwrap_or(false));++ state.begin_pass(ui.ctx());++ assert!(!state.complete(ui.ctx(), foreign, destination), "a child viewport's completion cannot release ROOT's guard");++ assert!(state.blocked(ViewportId::ROOT));++ assert!(state.complete(ui.ctx(), root, destination));++ assert!(!state.complete(ui.ctx(), foreign, destination));++ assert!(!state.blocked(ViewportId::ROOT));++ });++ full.textures_delta.clear();++ assert!(!in_ui_pass(&ctx));++ let _logic = ctx.run_logic(&egui::RawInput::default(), |ctx| assert!(!in_ui_pass(ctx)));++ }++}diff --cc crates/ui-egui/src/lib.rsindex d6bdea8d9,14d66da4c..b7bf46db8--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@@ -48,6 -47,6 +48,7 @@@ pub mod graphics_noticepub mod header;pub mod i18n;pub mod icons;++mod ime_reset;pub mod links;pub mod menus;pub mod native_dialogs;@@@ -279,30 -283,6 +280,16 @@@ pub(crate) const EXPORT_SAVE_DIALOGS: [("file.exportSelectionProject", "FilmCraft Project", "fcproj"),];- /// The IME composition currently in flight on the Program monitor.- ///- /// `TerminalPending` is an observed empty preedit: the input method cleared the visible- /// composition, but its terminal commit/delete is a separate event and may still arrive. Keeping- /// the owner means a target switch turns that state into `Stale`, so the pending old terminal- /// event is rejected instead of being applied to the replacement.- ///- /// `Stale` is a tombstone: the target was replaced or the editor closed while a composition was- /// active, so the preedit/delete/commit events of that composition are dropped instead of being- /// inserted into the replacement target. A rejected commit consumes it immediately, so a preedit- /// later in the same raw batch starts a new composition for the current target. A rejected empty- /// preedit or delete is only tentatively terminal: it keeps the tombstone through the rest of the- /// batch so its paired old commit is rejected too, and the tombstone is consumed at batch end when- /// no commit follows. A lone non-empty preedit keeps it across batches until the rejected- /// composition's commit, so a preedit/commit split across frames cannot retarget either. A later- /// composition on the new target is legitimate and must be accepted, so the tombstone is never- /// permanent (see `panels::graphics::text_edit`).++/// Incoming composition identity for the Program monitor. Interrupted compositions remain++/// Stale until the matching opaque native reset fence; output or old terminal input is not++/// acknowledgement. The retired origin and current destination live in the UI reset adapter.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum ImeComposition {+ Active(ImeTarget),+ TerminalPending(ImeTarget),+ Stale,+}+pub struct FilmcraftApp {pub session: Session,pub ui: UiState,@@@ -319,29 -299,6 +306,28 @@@/// The native file dialog the host is showing ([`Self::pick`]).native_dialog: Option<native_dialogs::PendingDialog>,pub auto: automation::Registry,+ /// IME owner/generation/cause state for the custom editors on the Program monitor. State is+ /// kept per egui viewport; a closed viewport is released in [`Self::on_exit`].+ pub(crate) ime_context: ImeContextTracker,+ /// Bumped when the custom text edit target is (re)created, a sequence/document context+ /// changes, or a control request replaces `gfxEdit`. It is the replacement epoch of the+ /// otherwise stable sequence/clip/component owner.+ pub(crate) ime_replacement_epoch: u64,+ /// The (viewport, cumulative pass) whose one IME observation has already been made.+ ime_observed_pass: Option<(egui::ViewportId, u64)>,+ /// The composition in flight (including an empty preedit awaiting its terminal event), or a+ /// tombstone for a composition whose target was replaced or caret/focus was interrupted.+ pub(crate) ime_composition: Option<ImeComposition>,- /// A known composition was interrupted locally; ask the platform to cancel it once even- /// when the same editor owner/generation remains focused after a caret-only move.- pub(crate) ime_interrupt_now: bool,++ ime_reset: ime_reset::State,++ ime_composition_viewport: Option<egui::ViewportId>,+ /// The editor drawn in this pass; the final observation runs after control drain.+ pub(crate) ime_drawn_editor: Option<panels::graphics::DrawnImeEditor>,+ /// Project document generation last seen by the UI (the engine bumps it on replacement).+ ime_document_epoch: u64,+ /// Active sequence last seen by the UI; `sequence.close` need not emit `OpenSequence`.+ ime_active_sequence: Option<filmcraft_project::ItemId>,+ /// Viewports this app's custom IME producer has observed, released when the app exits.+ ime_viewports: Vec<egui::ViewportId>,/// Named textures (monitors, thumbnails) with the key they show.textures: HashMap<String, (FrameKey, TextureHandle)>,/// The UI pass each thumbnail texture was last used in: thumbnails beyond@@@ -641,15 -567,6 +627,16 @@@ impl FilmcraftAppfile_dialogs: Default::default(),native_dialog: None,auto: Default::default(),+ ime_context: ImeContextTracker::new(),+ ime_replacement_epoch: 0,+ ime_observed_pass: None,+ ime_composition: None,- ime_interrupt_now: false,++ ime_reset: Default::default(),++ ime_composition_viewport: None,+ ime_drawn_editor: None,+ ime_document_epoch,+ ime_active_sequence,+ ime_viewports: Vec::new(),textures: HashMap::new(),thumb_used: HashMap::new(),control_rx: None,@@@ -721,81 -628,6 +708,153 @@@self}+ /// Start a new replacement epoch for the Program monitor's text edit target.+ ///+ /// The owner key names the sequence, clip and component. A recreated edit session on the+ /// same key (or a document/sequence replacement) must not inherit the previous IME context,+ /// so the app advances this epoch and the tracker resets the generation once.+ pub(crate) fn restart_ime_target(&mut self) {+ self.ime_replacement_epoch = self.ime_replacement_epoch.wrapping_add(1);+ self.invalidate_ime_composition();+ }+- /// Remember that the in-flight composition's target no longer applies. This includes an empty- /// preedit whose terminal commit/delete has not arrived yet. The next late commit or delete- /// from it is dropped; a rejected commit is a terminal boundary, so a fresh preedit after it- /// starts a new composition. A tentative boundary (empty preedit/delete) keeps the tombstone- /// through its raw input batch, so the paired old commit is rejected too.++ /// Context-less commands block immediately and retire the prior request on a real change.++ /// The next Context-bearing local event boundary requests its current destination's fence.+ pub(crate) fn invalidate_ime_composition(&mut self) {- if matches!(self.ime_composition, Some(ImeComposition::Active(_) | ImeComposition::TerminalPending(_))) {- self.ime_composition = Some(ImeComposition::Stale);- self.ime_interrupt_now = true;++ let origin = match self.ime_composition {++ Some(ImeComposition::Active(target) | ImeComposition::TerminalPending(target))++ if self.ime_composition_viewport == Some(self.ime_reset.viewport) =>++ {++ Some(target)++ }++ _ => self.ime_reset.origin(self.ime_reset.viewport),++ };++ let Some(origin) = origin else { return };++ let destination = panels::graphics::current_reset_destination(self);++ self.ime_reset.interrupt(origin, destination);++ self.ime_composition = Some(ImeComposition::Stale);++ self.ime_composition_viewport = Some(self.ime_reset.viewport);++ }++++ pub(crate) fn sync_live_ime_destination(&mut self, ctx: &egui::Context, destination: ime_reset::Destination) {++ let viewport = ctx.viewport_id();++ self.ime_reset.viewport = viewport;++ if self.ime_reset.incoming_changed(viewport, destination) {++ let origin = match self.ime_composition {++ Some(ImeComposition::Active(target) | ImeComposition::TerminalPending(target)) if self.ime_composition_viewport == Some(viewport) => {++ Some(target)++ }++ _ => self.ime_reset.origin(viewport),++ };++ if let Some(origin) = origin {++ self.ime_reset.interrupt(origin, Some(destination));++ self.ime_composition = Some(ImeComposition::Stale);++ self.ime_composition_viewport = Some(viewport);++ }++ }++ self.ime_reset.sync(ctx, destination);++ }++++ pub(crate) fn suspend_ime_input(&mut self, ctx: &egui::Context) {++ self.ime_reset.viewport = ctx.viewport_id();++ self.invalidate_ime_composition();++ self.ime_reset.suspend(ctx.viewport_id());++ }++++ /// The editor did not own this raw route. Controls stay inert after suspension; stock++ /// text/key events remain available to their widgets. Never use this before a live loop.++ fn suspended_ime_controls(&mut self, ctx: &egui::Context) {++ self.suspend_ime_input(ctx);++ ctx.input_mut(|input| input.events.retain(|event| !matches!(event, egui::Event::ImeResetCompleted { .. })));++ }++++ /// An actual modal owns input: the in-app `dialog` (Recovery, Revert, About, …) or a++ /// host-shown `native_dialog` picker. `file_dialogs` is only dialog-local state (the recovery++ /// choice); it is not an open modal on its own, so it must not block an otherwise eligible++ /// editor between frames.++ pub(crate) fn ime_modal_blocks_input(&self) -> bool {++ self.dialog.is_some() || self.native_dialog_open()++ }++++ /// Hosts with post-logic application work call this at their actual outer return.++ pub fn finish_ime_reset_logic(&mut self, ctx: &egui::Context) {++ self.ime_reset.viewport = ctx.viewport_id();++ self.sync_ime_target_context(ctx);++ if !ime_reset::in_ui_pass(ctx) {++ self.suspend_ime_input(ctx);++ }++ }++++ fn finish_ime_reset_ui(&mut self, ctx: &egui::Context) {++ let focused = ctx.input(|input| input.viewport().focused.unwrap_or(input.focused));++ let eligible = self.ime_reset.owns_output(ctx)++ && focused++ && !self.ime_modal_blocks_input()++ && ctx.memory(|memory| memory.has_focus(egui::Id::unique(panels::graphics::TEXT_EDIT_ID)));++ if !eligible {++ self.suspend_ime_input(ctx);++ let destination = panels::graphics::current_reset_destination(self);++ self.ime_reset.finish(ctx, destination, false);++ return;+ }++ let destination = panels::graphics::current_reset_destination(self);++ if let Some(destination) = destination {++ // Same-pass control work can change only the caret after the overlay drew. Do++ // not allocate until actual custom eligibility has been established above.++ self.sync_live_ime_destination(ctx, destination);++ }++ self.ime_reset.finish(ctx, destination, self.ime_reset.owns_output(ctx));+ }++ /// Notice a document replacement or an active-sequence change that did not emit+ /// `OpenSequence` (`file.newProject`, a project with no sequence, `sequence.close`). The+ /// edit target and any in-flight composition belong to the old context.+ fn sync_ime_target_context(&mut self, ctx: &egui::Context) {+ let document = self.session.document_epoch;+ let sequence = self.session.state.active_sequence;+ let replaced = document != self.ime_document_epoch;+ if !replaced && sequence == self.ime_active_sequence {+ return;+ }+ self.ime_document_epoch = document;+ self.ime_active_sequence = sequence;+ self.restart_ime_target();+ self.ui.gfx_edit = None;+ self.ime_drawn_editor = None;+ let text_edit = egui::Id::unique(panels::graphics::TEXT_EDIT_ID);+ ctx.memory_mut(|memory| memory.surrender_focus(text_edit));+ ctx.data_mut(|data| data.remove::<PanelKind>(text_edit.with("panel")));+ }++ /// Mark this viewport/pass as observed by the custom producer, so the end-of-pass fallback+ /// does not observe it a second time.+ pub(crate) fn note_ime_observed(&mut self, viewport: egui::ViewportId, pass_nr: u64) {+ self.ime_observed_pass = Some((viewport, pass_nr));+ if !self.ime_viewports.contains(&viewport) {+ self.ime_viewports.push(viewport);+ }+ }++ /// Observe `None` once for a pass where no visible, focused custom IME owner drew a+ /// descriptor. This is the explicit hidden/unfocused signal the tracker needs; a gap alone+ /// is a fallback, not a replacement for it.+ pub(crate) fn finish_ime_pass(&mut self, ctx: &egui::Context) {+ let viewport = ctx.viewport_id();+ let pass_nr = ctx.cumulative_pass_nr_for(viewport);+ // The Program monitor deferred its observation until all control requests for this pass+ // have run. It reports `true` even when it observed an explicit `None` for a hidden or+ // replaced editor.+ if panels::graphics::finish_graphics_ime(self, ctx) {+ return;+ }+ if self.ime_observed_pass == Some((viewport, pass_nr)) {+ return;+ }- // No custom descriptor already disables its platform context; do not carry a stale- // one-shot interruption into a later fresh focus session.- if !ctx.will_discard() {- self.ime_interrupt_now = false;- }++ // Availability retirement belongs to the unconditional outer reset finalizer.+ self.ime_context.observe(viewport, None);+ self.note_ime_observed(viewport, pass_nr);+ }+/// Isolate an automation-owned app from native keyboard, pointer, drop and menu input./// Window close/quit and screenshot delivery remain available.pub fn with_control_input_only(mut self, rx: Receiver<ControlRequest>) -> Self {@@@ -2243,70 -2088,49 +2302,16 @@@ fn synthesize_mac_ctrl_click(armed: &mu}}--impl eframe::App for FilmcraftApp {- fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {- fn raw_input_hook(&mut self, _ctx: &egui::Context, raw_input: &mut egui::RawInput) {-- self.native_window_focused = Some(raw_input.focused);- capture::note_raw_geometry(self, ctx, raw_input);-- #[cfg(target_os = "macos")]-- if !self.control_input_only {-- synthesize_mac_ctrl_click(&mut self.mac_ctrl_click_armed, raw_input);-- }-- if self.control_input_only {- // Screenshot results arrive through `ScreenshotCallback`, not raw input. Preserve all- // viewport lifecycle/geometry metadata and drop native input only.- raw_input.events.clear();- // Preserve screenshot responses and all viewport lifecycle/geometry metadata.- raw_input.events.retain(|event| matches!(event, egui::Event::Screenshot { .. }));-- raw_input.hovered_files.clear();-- raw_input.dropped_files.clear();-- }- if self.control_input_only || !self.synthetic.is_empty() || self.synthetic_pending_step.is_some() {- if self.control_input_only || !self.synthetic.is_empty() {-- // Native modifiers cannot replace those requested by a control gesture. A queued-- // reset runs in the frame after release, so clicked() still sees Shift/Alt.- if !self.synthetic_modifiers_offered {- raw_input.events.push(egui::Event::ModifiersChanged(self.synthetic_modifiers));- self.synthetic_modifiers_offered = true;- }- raw_input.events.push(egui::Event::ModifiersChanged(self.synthetic_modifiers));-- // Widget keyboard handling requires effective egui focus. Control input must work-- // in a background window without activating it or taking the user's OS keyboard.-- raw_input.focused = true;-- }- if self.synthetic_pending_step.is_none() && !self.synthetic.is_empty() {- if !self.synthetic.is_empty() {-- // Pointer events go one per frame so egui sees press → moves → release as a real drag-- // (all in one frame reads as a click); key/text runs go together up to a key release.-- let pointer = |e: &egui::Event| matches!(e, egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } | egui::Event::MouseWheel { .. });-- let n = if pointer(&self.synthetic[0]) {-- 1-- } else {-- self.synthetic-- .iter()-- .position(|e| pointer(e) || matches!(e, egui::Event::Key { pressed: false, .. }))-- .map_or(self.synthetic.len(), |i| if pointer(&self.synthetic[i]) { i.max(1) } else { i + 1 })-- };- let step: Vec<egui::Event> = self.synthetic.drain(..n).collect();- for event in &step {- for event in self.synthetic.drain(..n) {-- if let egui::Event::ModifiersChanged(modifiers) = event {- self.synthetic_modifiers = *modifiers;- self.synthetic_modifiers = modifiers;-- }- }- self.synthetic_pending_step = Some(step);- self.synthetic_step_offered = false;- }- if let Some(step) = &self.synthetic_pending_step {- // `raw_input_hook` also runs before hidden `run_logic` ticks, whose raw input egui does- // not feed to widgets. Keep the exact same one-step batch pending and offer it again- // on the next callback; a real UI pass clears it at `ui()` start. Never coalesce a- // press with its release and, crucially, never append a step that the integration- // already preserved in its pending raw input: the UI pass would then see two copies.- if !self.synthetic_step_offered {- raw_input.events.extend(step.iter().cloned());- self.synthetic_step_offered = true;- raw_input.events.push(event);-- }-- }-- }++/// Install once in each native/web/harness Context creator, before the first UI pass.++pub fn install_ime_reset_callbacks(ctx: &egui::Context) {++ ime_reset::install(ctx);++}-- fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {++impl FilmcraftApp {++ pub fn logic_inner(&mut self, ctx: &egui::Context) {+ // Remember the pass's clock before anything reads `now()`. A hidden logic-only tick keeps+ // the last UI time (which is stale there), so `now()` never runs behind the host clock.+ self.ui_clock = self.ui_clock.max(ctx.input(|i| i.time));// a native file dialog's answer first, so the panels draw what it chose (#260)self.poll_native_dialog(ctx);if !self.styled {@@@ -2349,87 -2172,26 +2354,75 @@@// keyboard focus) so the input is processed.self.raise_for_control(ctx);}- if !self.synthetic.is_empty() {+ if !self.synthetic.is_empty() || self.synthetic_pending_step.is_some() {ctx.request_repaint();- } else if !self.input_waiters.is_empty() {- for w in self.input_waiters.drain(..) {- let _ = w.send(json!({"ok": true, "result": null}));- }+ // The next step is consumed by a UI pass, not by another logic tick. Native eframe+ // honours this; the pinned web runner logs it as unhandled (a recorded fork gap).+ ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaintWhileHidden);}- let settled = !std::mem::take(&mut self.monitor_inexact) && self.timeline_still > 0;- self.issue_screenshots(ctx, settled);- self.collect_screenshots(ctx);- }- fn on_exit(&mut self) {- // Flush the recovery journal and stop the auto-save worker; a session with nothing unsaved- // removes its journal, one with unsaved changes keeps it for the next launch.- self.session.shutdown();+ // Background work: consumed queues and idempotent deadlines, safe on every logic call.+ self.frames.set_context(ctx);+ self.frames.pump(std::time::Duration::from_millis(if self.playback.playing { 24 } else { 40 }));+ self.session.poll_persistence();+ panels::trim_monitor::advance_at(self, now);+ if self.session.trim_play.active() {+ ctx.request_repaint();+ }+ if self.session.persistence.is_some() && self.session.is_dirty() {+ // Keep polling the auto-save worker (status, "also save the project" results) while hidden.+ ctx.request_repaint_after(std::time::Duration::from_secs(1));+ }+ self.sync_pool();+ #[cfg(not(target_arch = "wasm32"))]+ self.tick_media_refresh(ctx, now);+ for ev in self.session.drain_events() {+ match ev {+ filmcraft_engine::Event::OpenSequence(_) => {+ // A sequence switch (including opening/reverting/recovering a project, which+ // emits this event for the newly active sequence) is a new IME owner context.+ self.restart_ime_target();+ // show the sequence with its own view (or fitted, the first time)+ self.timeline_view_of = None;+ if !self.ui.floating.iter().any(|group| group.panels.contains(&PanelKind::Timeline)) {+ self.ui.dock.restore_timeline();+ }+ let _ = self.apply_dock(craft_ui::docking::Action::Activate { panel: PanelKind::Timeline });+ }+ filmcraft_engine::Event::OpenSource(_) => {+ let _ = self.apply_dock(craft_ui::docking::Action::Activate { panel: PanelKind::Source });+ }+ filmcraft_engine::Event::RevealInProject(item) => self.reveal_in_project(item),+ filmcraft_engine::Event::Toast { message, .. } => self.toast = Some((message, now)),+ filmcraft_engine::Event::ProjectChanged { .. } => {}+ }+ }+ if let Some(rx) = self.command_inbox.take() {+ while let Ok(id) = rx.try_recv() {+ // control-only mode ignores native menu commands, but Quit stays available (#1943)+ if self.control_input_only && id != "app.quit" {+ continue;+ }+ if let Err(e) = menus::invoke(self, ctx, &id, json!({})) {+ self.ui.status = e;+ }+ }+ self.command_inbox = Some(rx);+ }+ self.advance_playback(ctx);+ self.advance_source_playback(ctx);+ self.poll_jobs(ctx);+ capture::drain(self, ctx);+ capture::request_hidden_paint(self, ctx);}- fn on_exit(&mut self) {- // Late screenshot callbacks now find a dropped slot and write nothing; clients get one error.- capture::cancel_all(self);- for viewport in self.ime_viewports.drain(..) {- self.ime_context.end_viewport(viewport);- }- self.ime_observed_pass = None;- // Flush the recovery journal and stop the auto-save worker; a session with nothing unsaved- // removes its journal, one with unsaved changes keeps it for the next launch.- self.session.shutdown();- }-- fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {- fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {++ fn ui_inner(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {if !self.fonts_ready {+ // This pass did not consume the pending synthetic input; the next hook must offer it+ // again (the UI path does not preserve raw input across this early return).+ self.synthetic_step_offered = false;+ self.synthetic_modifiers_offered = false;+ self.finish_ime_pass(ui.ctx());ui.ctx().request_repaint();return;}@@@ -2502,12 -2219,12 +2495,104 @@@let _ = w.send(json!({"ok": true, "result": null}));}}- if self.frames.queue_len() > 0 {- ctx.request_repaint_after(std::time::Duration::from_millis(16));+ // Only a real, accepted UI pass may issue a capture: it observes the final layout for this+ // pass and `screenshot` itself forces the paint needed when the window is hidden.+ capture::issue(self, &ctx);+ }+}+++impl eframe::App for FilmcraftApp {++ fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {++ self.native_window_focused = Some(raw_input.focused);++ capture::note_raw_geometry(self, ctx, raw_input);++ #[cfg(target_os = "macos")]++ if !self.control_input_only {++ synthesize_mac_ctrl_click(&mut self.mac_ctrl_click_armed, raw_input);++ }++ if self.control_input_only {++ // Screenshot results arrive through `ScreenshotCallback`, not raw input. Preserve all++ // viewport lifecycle/geometry metadata and drop native input only.++ raw_input.events.clear();++ raw_input.hovered_files.clear();++ raw_input.dropped_files.clear();++ }++ if self.control_input_only || !self.synthetic.is_empty() || self.synthetic_pending_step.is_some() {++ // Native modifiers cannot replace those requested by a control gesture. A queued++ // reset runs in the frame after release, so clicked() still sees Shift/Alt.++ if !self.synthetic_modifiers_offered {++ raw_input.events.push(egui::Event::ModifiersChanged(self.synthetic_modifiers));++ self.synthetic_modifiers_offered = true;++ }++ // Widget keyboard handling requires effective egui focus. Control input must work++ // in a background window without activating it or taking the user's OS keyboard.++ raw_input.focused = true;++ }++ if self.synthetic_pending_step.is_none() && !self.synthetic.is_empty() {++ // Pointer events go one per frame so egui sees press → moves → release as a real drag++ // (all in one frame reads as a click); key/text runs go together up to a key release.++ let pointer = |e: &egui::Event| matches!(e, egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } | egui::Event::MouseWheel { .. });++ let n = if pointer(&self.synthetic[0]) {++ 1++ } else {++ self.synthetic++ .iter()++ .position(|e| pointer(e) || matches!(e, egui::Event::Key { pressed: false, .. }))++ .map_or(self.synthetic.len(), |i| if pointer(&self.synthetic[i]) { i.max(1) } else { i + 1 })++ };++ let step: Vec<egui::Event> = self.synthetic.drain(..n).collect();++ for event in &step {++ if let egui::Event::ModifiersChanged(modifiers) = event {++ self.synthetic_modifiers = *modifiers;++ }++ }++ self.synthetic_pending_step = Some(step);++ self.synthetic_step_offered = false;++ }++ if let Some(step) = &self.synthetic_pending_step {++ // `raw_input_hook` also runs before hidden `run_logic` ticks, whose raw input egui does++ // not feed to widgets. Keep the exact same one-step batch pending and offer it again++ // on the next callback; a real UI pass clears it at `ui()` start. Never coalesce a++ // press with its release and, crucially, never append a step that the integration++ // already preserved in its pending raw input: the UI pass would then see two copies.++ if !self.synthetic_step_offered {++ raw_input.events.extend(step.iter().cloned());++ self.synthetic_step_offered = true;++ }++ }++ }++++ fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {++ self.logic_inner(ctx);++ self.finish_ime_reset_logic(ctx);++ }++++ fn on_exit(&mut self) {++ // Late screenshot callbacks now find a dropped slot and write nothing; clients get one error.++ capture::cancel_all(self);++ for viewport in self.ime_viewports.drain(..) {++ self.ime_context.end_viewport(viewport);++ self.ime_reset.end_viewport(viewport);+ }++ self.ime_observed_pass = None;++ // Flush the recovery journal and stop the auto-save worker; a session with nothing unsaved++ // removes its journal, one with unsaved changes keeps it for the next launch.++ self.session.shutdown();++ }++++ fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {++ let ctx = ui.ctx().clone();++ self.ime_reset.begin_pass(&ctx);++ self.ime_drawn_editor = None;++ let focused = ctx.input(|input| input.viewport().focused.unwrap_or(input.focused));++ let another_field = ctx.memory(|memory| memory.focused().is_some_and(|id| id != egui::Id::unique(panels::graphics::TEXT_EDIT_ID)));++ if !self.fonts_ready || self.ui.gfx_edit.is_none() || self.ime_modal_blocks_input() || !focused || another_field {++ self.suspended_ime_controls(&ctx);++ }++ self.ui_inner(ui, frame);++ self.finish_ime_reset_ui(&ctx);+ }+ }+/// Effective sample rate for shuttle playback. The audio device still runs at `device_rate`,/// so at 2x its output samples represent twice the timeline duration. Reverse and/// extreme shuttle speeds remain silent rather than asking the mixer for invalid rates.diff --cc crates/ui-egui/src/panels/graphics.rsindex c2e2ffbf8,7fb91b98d..4cce6f970--- a/crates/ui-egui/src/panels/graphics.rs+++ b/crates/ui-egui/src/panels/graphics.rs@@@ -1035,145 -925,16 +1035,148 @@@ pub fn monitor_overlay(app: &mut Filmcrlet (x, base, li) = l.caret(caret);let (ascent, descent) = l.lines.get(li.min(l.lines.len().saturating_sub(1))).map_or((0.0, 0.0), |line| (line.ascent, line.descent));let (a, b) = (sp(&v.to_screen, x, base - ascent), sp(&v.to_screen, x, base + descent));+ let cursor_rect = Rect::from_two_pos(a, b);painter.line_segment([a, b], Stroke::new(1.5, Color32::WHITE));painter.line_segment([a + vec2(1.0, 0.0), b + vec2(1.0, 0.0)], Stroke::new(0.5, Color32::BLACK));- let er = Rect::from_points(&v.quad()).union(Rect::from_two_pos(a, b));+ let er = Rect::from_points(&v.quad()).union(cursor_rect);app.auto.add("program.textEdit", er, &tp.text);- ui.ctx().output_mut(|o| {+ // Do not publish yet: `drain_ui_requests` later in this pass may run a command or replace+ // `gfxEdit`. `finish_graphics_ime` observes the post-drain state with this geometry.+ note_graphics_ime_editor(app, ui, v, er, cursor_rect);+ }+}++/// Remember the focused Program monitor editor drawn in this pass. The actual observation is+/// made once by [`finish_graphics_ime`] after the pass's control requests have run.+pub(crate) fn note_graphics_ime_editor(app: &mut FilmcraftApp, ui: &egui::Ui, v: &LayerView, rect: Rect, cursor_rect: Rect) {+ let ctx = ui.ctx();+ let viewport = ctx.viewport_id();+ let pass_nr = ctx.cumulative_pass_nr_for(viewport);+ let sequence = app.session.state.active_sequence.map(|sequence| sequence.0);+ let target = graphics_ime_target(sequence.unwrap_or(0), v.clip.0, v.layer, v.spec.uid, app.ime_replacement_epoch);+ let fingerprint = current_layer_fingerprint(&app.session, v.clip.0, v.layer).unwrap_or(0);+ let layout_fingerprint = current_layer_layout_fingerprint(&app.session, v.clip.0, v.layer).unwrap_or(0);+ let text_stamp = text_of(&v.spec).map_or(0, |tp| ime_text_stamp(&tp.text));+ app.ime_drawn_editor = Some(DrawnImeEditor {+ viewport,+ pass_nr,+ document_epoch: app.session.document_epoch,+ sequence,+ target,+ clip: v.clip.0,+ layer: v.layer,+ fingerprint,+ text_stamp,+ layout_fingerprint,+ rect,+ cursor_rect,+ });+}++/// Publish this pass's final IME observation, after all commands for the pass have been drained.+///+/// The producer re-reads the committed text without evaluating/copying a full `LayerSpec`; a+/// target, document or sequence replaced since the overlay drew publishes `None` instead of+/// pairing an old owner with the new model.+pub(crate) fn finish_graphics_ime(app: &mut FilmcraftApp, ctx: &egui::Context) -> bool {+ let viewport = ctx.viewport_id();+ let pass_nr = ctx.cumulative_pass_nr_for(viewport);+ let Some(drawn) = app.ime_drawn_editor.take() else { return false };+ if drawn.viewport != viewport || drawn.pass_nr != pass_nr {+ return false;+ }+ app.note_ime_observed(viewport, pass_nr);- let should_interrupt_composition = app.ime_interrupt_now;- if !ctx.will_discard() {- app.ime_interrupt_now = false;++ if app.ime_modal_blocks_input() {++ // A picker or in-app modal opened after the overlay drew owns input for the rest of this++ // pass. Publish no custom descriptor, so this editor cannot attach an already queued reset++ // under the modal. Core may still carry that un-taken request to a later stock descriptor++ // (the accepted attachment limitation); the next eligible pass rearms this guard explicitly.++ app.ime_context.observe(viewport, None);++ return true;+ }+ if drawn.document_epoch != app.session.document_epoch || drawn.sequence != app.session.state.active_sequence.map(|sequence| sequence.0) {+ app.ime_context.observe(viewport, None);+ return true;+ }+ let eid = egui::Id::unique(TEXT_EDIT_ID);+ if ctx.memory(|m| m.focused() != Some(eid)) {+ app.ime_context.observe(viewport, None);+ return true;+ }+ let Some(ed) = app.ui.gfx_edit.clone() else {+ app.ime_context.observe(viewport, None);+ return true;+ };+ if ed.clip != drawn.clip || ed.layer != drawn.layer {+ app.ime_context.observe(viewport, None);+ return true;+ }+ let Some(sequence) = app.session.state.active_sequence else {+ app.ime_context.observe(viewport, None);+ return true;+ };+ let Some(uid) = current_layer_uid(&app.session, ed.clip, ed.layer) else {+ app.ime_context.observe(viewport, None);+ return true;+ };+ let target = graphics_ime_target(sequence.0, ed.clip, ed.layer, uid, app.ime_replacement_epoch);+ if target != drawn.target || current_layer_fingerprint(&app.session, ed.clip, ed.layer).is_none_or(|fingerprint| fingerprint != drawn.fingerprint) {+ // A control request replaced the edit target, reordered the layers, or changed the+ // document after the overlay drew. Do not pair the old owner with the new content.++ app.ime_context.observe(viewport, None);+ return true;+ }+ let Some(text) = current_layer_text(&app.session, ed.clip, ed.layer) else {+ app.ime_context.observe(viewport, None);+ return true;+ };+ if ime_text_stamp(text) != drawn.text_stamp {+ // A same-pass control request changed the text after the overlay drew. The published+ // cursor rectangle and layout belong to the old text: report no descriptor for this pass+ // and let the next pass draw and observe the correct geometry. The in-flight composition+ // belongs to the text that was replaced, so its next delete/preedit/commit must not be+ // inserted into the new text.+ app.invalidate_ime_composition();- if !ctx.will_discard() {- app.ime_interrupt_now = false;- }+ app.ime_context.observe(viewport, None);+ return true;+ }+ if current_layer_layout_fingerprint(&app.session, ed.clip, ed.layer).is_none_or(|fingerprint| fingerprint != drawn.layout_fingerprint) {+ // A same-pass control request changed a layout-affecting property (font, style,+ // alignment, spacing, box, transform, per-character style or pin) without changing the+ // committed text. The old cursor rectangle belongs to the previous layout: publish no+ // descriptor for this pass and let the next pass draw and observe the new geometry.+ app.ime_context.observe(viewport, None);+ return true;+ }+ // A caret/selection-only change after the draw keeps the committed text. Publish the new+ // selection with the owner and generation unchanged; the cursor rectangle is one pass old,+ // and the next pass refreshes it. Hostile offsets remain an explicit `Unavailable` snapshot.+ let frame_nr = ctx.cumulative_frame_nr_for(viewport);+ // FilmCraft's committed text never contains the IME pre-edit (preedit events are UI-only),+ // so there is no preedit range to remove. A hostile or not-yet-clamped `gfxEdit` offset that+ // is not a UTF-8 boundary is published as the explicit `Unavailable` snapshot, never as a+ // nearby guessed offset.+ let valid_offsets = ed.caret <= text.len() && ed.anchor <= text.len() && text.is_char_boundary(ed.caret) && text.is_char_boundary(ed.anchor);+ let observation = ImeObservation::new(frame_nr, pass_nr, target)+ .purpose(egui::IMEPurpose::Normal)+ .committed(valid_offsets.then(|| CommittedText::new(text, ed.caret, ed.anchor)));+ let update = app.ime_context.observe(viewport, Some(observation));++ if let Some(update) = update {+ let (rect, cursor_rect) = (drawn.rect, drawn.cursor_rect);++ app.ime_reset.produced(crate::ime_reset::OutputContext { owner: update.owner, generation: update.context_generation, purpose: update.purpose });+ ctx.output_mut(|o| {o.ime = Some(egui::output::IMEOutput {- purpose: Default::default(),- rect: er,- cursor_rect: Rect::from_two_pos(a, b),- should_interrupt_composition: false,+ owner: update.owner,+ context_generation: update.context_generation,+ purpose: update.purpose,+ rect,+ cursor_rect,- should_interrupt_composition,++ should_interrupt_composition: false, // core attaches the one-shot request/interrupt++ reset_request: None,+ change_cause: update.change_cause,+ surrounding_text: update.surrounding_text,})});}@@@ -1237,376 -1008,9 +1240,393 @@@ pub(crate) fn select_all_edited_text(aptrue}+/// One text edit action queued by [`text_edit`], with the accepted local IME receipt chain.+///+/// The model command is executed later in the same pass. The receipt is reported to the tracker+/// only after that command succeeds and the post-command model still matches the local result.+struct PendingImeEdit {+ action_index: usize,+ clip: u64,+ layer: usize,+ /// The committed stamp immediately before the first accepted IME mutation.+ first_before: Option<ImeMutationStamp>,+ before_cursor: usize,+ before_anchor: usize,+ /// One stamp immediately after each accepted IME commit/delete mutation.+ after: Vec<ImeMutationStamp>,+ final_cursor: usize,+ final_anchor: usize,+ /// Ordinary text/paste/key/Cut changes were mixed into the same queued edit.+ application_mutation: bool,+}++fn ime_stamp(text: &str, cursor: usize, anchor: usize) -> ImeMutationStamp {+ ImeMutationStamp::from_committed(text, cursor, anchor, None)+}++/// The effect instance of layer `layer` of `clip` when it is enabled and on screen.+///+/// This is the read-only path for the IME producer: it never evaluates a `LayerSpec` (which+/// clones the layer's full text) just to read an identity or a committed-text window.+fn current_layer_effect(session: &Session, clip: u64, layer: usize) -> Option<&EffectInstance> {+ let seq = session.active_sequence()?;+ let (_, it) = seq.find_item(ClipId(clip))?;+ if !it.enabled {+ return None;+ }+ let &effect_index = layer_indices(&it.effects).get(layer)?;+ let effect = it.effects.get(effect_index)?;+ effect.enabled.then_some(effect)+}++/// Borrowed committed text of the edited layer at the playhead (no `TextProps`/full-text copy).+fn current_layer_text(session: &Session, clip: u64, layer: usize) -> Option<&str> {+ let seq = session.active_sequence()?;+ let t = session.playhead();+ let (_, it) = seq.find_item(ClipId(clip))?;+ if !it.enabled {+ return None;+ }+ let &effect_index = layer_indices(&it.effects).get(layer)?;+ let effect = it.effects.get(effect_index)?;+ if !effect.enabled || effect.effect != graphic::TEXT_LAYER {+ return None;+ }+ effect.params.get("text")?.text_ref_at(it.source_time_at(t))+}++fn current_layer_uid(session: &Session, clip: u64, layer: usize) -> Option<u64> {+ current_layer_effect(session, clip, layer).map(|effect| effect.layer.as_ref().map_or(0, |x| x.uid))+}++/// A compact identity for a layer that survives reorder/delete/undo when the layer has no uid.+///+/// It uses static parameter values only, so a keyframed or animating position at the playhead+/// does not make the target look new, and it deliberately excludes the editable text, so typing+/// does not either.+fn layer_fingerprint(effect: &EffectInstance) -> u64 {+ let mut h: u64 = 0xcbf2_9ce4_8422_2325;+ let mut hash = |bytes: &[u8]| {+ for &b in bytes {+ h ^= u64::from(b);+ h = h.wrapping_mul(0x0000_0100_0000_01b3);+ }+ };+ hash(effect.effect.as_bytes());+ hash(&[u8::from(effect.enabled)]);+ hash(&effect.layer.as_ref().map_or(0, |x| x.uid).to_le_bytes());+ if let Some(name) = effect.params.get("name").and_then(|p| match &p.value {+ ParamValue::Text(s) => Some(s.as_str()),+ _ => None,+ }) {+ hash(name.as_bytes());+ }+ for id in ["position", "size", "box_width", "box_height", "shape", "sides", "corner_radius", "vertical"] {+ let Some(value) = effect.params.get(id).map(|p| &p.value) else { continue };+ match value {+ ParamValue::Float(v) => hash(&v.to_bits().to_le_bytes()),+ ParamValue::Vec2(v) => {+ hash(&v.x.to_bits().to_le_bytes());+ hash(&v.y.to_bits().to_le_bytes());+ }+ ParamValue::Choice(v) => hash(&u64::from(*v).to_le_bytes()),+ ParamValue::Bool(v) => hash(&[u8::from(*v)]),+ ParamValue::Text(s) => hash(s.as_bytes()),+ _ => {}+ }+ }+ h+}++fn current_layer_fingerprint(session: &Session, clip: u64, layer: usize) -> Option<u64> {+ current_layer_effect(session, clip, layer).map(layer_fingerprint)+}++/// Stable uid and identity fingerprint of the layer currently at `layer`.+///+/// A control request that explicitly names a clip and numeric layer means that index now, not+/// whichever layer an older edit session happened to own at that index.+pub(crate) fn current_layer_identity(session: &Session, clip: u64, layer: usize) -> Option<(u64, u64)> {+ current_layer_effect(session, clip, layer).map(|effect| (effect.layer.as_ref().map_or(0, |extra| extra.uid), layer_fingerprint(effect)))+}++/// Properties that change a text or shape layer's layout, and therefore the caret and candidate+/// rectangle, without necessarily changing its committed text or stable identity. Both static+/// values and keyframes at the playhead are included.+const LAYOUT_PARAMS: &[&str] = &[+ // Text layout.+ "font",+ "font_style",+ "size",+ "align",+ "tracking",+ "kerning",+ "ligatures",+ "leading",+ "baseline_shift",+ "faux_bold",+ "faux_italic",+ "caps",+ "underline",+ "box_width",+ "box_height",+ "vertical",+ // Shape geometry.+ "shape",+ "sides",+ "corner_radius",+ "points",+ // Transform.+ "position",+ "anchor",+ "scale",+ "scale_width",+ "uniform_scale",+ "rotation",+];++fn hash_bytes(h: &mut u64, bytes: &[u8]) {+ for &b in bytes {+ *h ^= u64::from(b);+ *h = h.wrapping_mul(0x0000_0100_0000_01b3);+ }+}++fn hash_f64(h: &mut u64, v: f64) {+ // Normalise non-finite values: NaN is "auto" for point parameters and must not make the+ // fingerprint depend on payload bits or an evaluation detail.+ if v.is_finite() {+ hash_bytes(h, &v.to_bits().to_le_bytes());+ } else {+ hash_bytes(h, b"non-finite");+ }+}++fn hash_f32(h: &mut u64, v: f32) {+ hash_f64(h, f64::from(v));+}++fn hash_option<T>(h: &mut u64, value: Option<T>, hash: impl FnOnce(&mut u64, T)) {+ match value {+ Some(v) => {+ hash_bytes(h, &[1]);+ hash(h, v);+ }+ None => hash_bytes(h, &[0]),+ }+}++fn hash_param_value(h: &mut u64, value: &ParamValue) {+ match value {+ ParamValue::Float(v) => {+ hash_bytes(h, b"f");+ hash_f64(h, *v);+ }+ ParamValue::Vec2(v) => {+ hash_bytes(h, b"v");+ hash_f64(h, v.x);+ hash_f64(h, v.y);+ }+ ParamValue::Color(c) => {+ hash_bytes(h, b"c");+ for v in c {+ hash_f32(h, *v);+ }+ }+ ParamValue::Bool(v) => {+ hash_bytes(h, b"b");+ hash_bytes(h, &[u8::from(*v)]);+ }+ ParamValue::Choice(v) => {+ hash_bytes(h, b"o");+ hash_bytes(h, &u64::from(*v).to_le_bytes());+ }+ ParamValue::Text(v) => {+ hash_bytes(h, b"t");+ hash_bytes(h, v.as_bytes());+ }+ ParamValue::Curve(points) => {+ hash_bytes(h, b"u");+ hash_bytes(h, &(points.len() as u64).to_le_bytes());+ for p in points {+ hash_f32(h, p[0]);+ hash_f32(h, p[1]);+ }+ }+ // Mask paths are not used by layer layout parameters.+ ParamValue::Path(_) => hash_bytes(h, b"p"),+ }+}++fn layout_fingerprint(effect: &EffectInstance, t: Tick) -> u64 {+ let mut h: u64 = 0x9e37_79b9_7f4a_7c15;+ hash_bytes(&mut h, effect.effect.as_bytes());+ hash_bytes(&mut h, &[u8::from(effect.enabled)]);+ for id in LAYOUT_PARAMS {+ let Some(param) = effect.params.get(*id) else { continue };+ hash_bytes(&mut h, id.as_bytes());+ hash_param_value(&mut h, ¶m.value_at(t));+ }+ if let Some(extra) = &effect.layer {+ hash_bytes(&mut h, b"runs");+ hash_bytes(&mut h, &(extra.runs.len() as u64).to_le_bytes());+ for run in &extra.runs {+ hash_bytes(&mut h, &(run.start as u64).to_le_bytes());+ hash_bytes(&mut h, &(run.end as u64).to_le_bytes());+ hash_option(&mut h, run.style.font.as_ref(), |h, v| hash_bytes(h, v.as_bytes()));+ hash_option(&mut h, run.style.font_style.as_ref(), |h, v| hash_bytes(h, v.as_bytes()));+ hash_option(&mut h, run.style.size, hash_f32);+ hash_option(&mut h, run.style.fill, |h, v| {+ for c in v {+ hash_f32(h, c);+ }+ });+ hash_option(&mut h, run.style.faux_bold, |h, v| hash_bytes(h, &[u8::from(v)]));+ hash_option(&mut h, run.style.faux_italic, |h, v| hash_bytes(h, &[u8::from(v)]));+ hash_option(&mut h, run.style.underline, |h, v| hash_bytes(h, &[u8::from(v)]));+ hash_option(&mut h, run.style.tracking, hash_f32);+ hash_option(&mut h, run.style.baseline_shift, hash_f32);+ hash_option(&mut h, run.style.caps, |h, v| hash_bytes(h, &u64::from(v).to_le_bytes()));+ }+ hash_bytes(&mut h, b"pin");+ match &extra.pin {+ Some(pin) => {+ hash_bytes(&mut h, &[1]);+ match pin.to {+ filmcraft_project::graphic_design::PinTarget::Frame => hash_bytes(&mut h, b"frame"),+ filmcraft_project::graphic_design::PinTarget::Layer(uid) => {+ hash_bytes(&mut h, b"layer");+ hash_bytes(&mut h, &uid.to_le_bytes());+ }+ }+ hash_bytes(&mut h, &[u8::from(pin.left), u8::from(pin.top), u8::from(pin.right), u8::from(pin.bottom)]);+ for offset in pin.offsets {+ hash_f64(&mut h, offset);+ }+ }+ None => hash_bytes(&mut h, &[0]),+ }+ }+ h+}++fn current_layer_layout_fingerprint(session: &Session, clip: u64, layer: usize) -> Option<u64> {+ let sequence = session.active_sequence()?;+ let t = session.playhead();+ let (_, item) = sequence.find_item(ClipId(clip))?;+ let &effect_index = layer_indices(&item.effects).get(layer)?;+ let effect = item.effects.get(effect_index)?;+ Some(layout_fingerprint(effect, item.source_time_at(t)))+}++/// Follow the edited layer through a real project edit (reorder, delete, undo/redo).+///+/// A stable uid wins. For a uid-less layer the compact fingerprint finds the same layer at its+/// new index; with no candidate the layer was deleted (or replaced), so the edit is ended rather+/// than silently retargeted to whatever now occupies the old index.+fn resolve_gfx_edit(session: &Session, ed: &GfxEdit) -> Option<(usize, u64, u64)> {+ let seq = session.active_sequence()?;+ let (_, it) = seq.find_item(ClipId(ed.clip))?;+ let indices = layer_indices(&it.effects);+ let resolved = if ed.uid != 0 {+ indices.iter().position(|&ei| it.effects.get(ei).and_then(|e| e.layer.as_ref()).is_some_and(|x| x.uid == ed.uid))+ } else {+ let at = |i: usize| it.effects.get(indices[i]).map(layer_fingerprint);+ let mut found = indices.get(ed.layer).and_then(|_| at(ed.layer)).filter(|fp| ed.fingerprint == 0 || *fp == ed.fingerprint).map(|_| ed.layer);+ if found.is_none() && ed.fingerprint != 0 {+ let mut best: Option<(usize, usize)> = None;+ for i in 0..indices.len() {+ if at(i) == Some(ed.fingerprint) {+ let distance = i.abs_diff(ed.layer);+ if best.is_none_or(|(d, _)| distance < d) {+ best = Some((distance, i));+ }+ }+ }+ found = best.map(|(_, i)| i);+ }+ found+ }?;+ let effect = it.effects.get(*indices.get(resolved)?)?;+ let uid = effect.layer.as_ref().map_or(0, |x| x.uid);+ Some((resolved, uid, layer_fingerprint(effect)))+}++/// Keep `gfx_edit` on the layer it started on. Called before the overlay draws, so a command run+/// between two passes (arrange/delete/undo or a control edit) cannot shift the caret into another+/// layer.+fn reconcile_gfx_edit(app: &mut FilmcraftApp) {+ let Some(ed) = app.ui.gfx_edit.clone() else { return };+ match resolve_gfx_edit(&app.session, &ed) {+ Some((layer, uid, fingerprint)) => {+ // A uid-less owner key includes the index, so an index change is a new context. A+ // stable uid layer keeps the same owner and its composition may continue.+ if layer != ed.layer && ed.uid == 0 {+ app.invalidate_ime_composition();+ }+ app.ui.gfx_edit = Some(GfxEdit { layer, uid, fingerprint, ..ed });+ }+ None => {+ app.ui.gfx_edit = None;+ app.invalidate_ime_composition();+ }+ }+}++fn graphics_ime_target(sequence: u64, clip: u64, layer: usize, uid: u64, replacement_epoch: u64) -> ImeTarget {+ // The owner excludes caret, selection, text, revision, geometry, visual order and pointers.+ // `uid` is the stable layer component id; zero means "none", where the layer index is the+ // only component identity available.+ let component_uid = (uid != 0).then_some(uid);+ let component_index = (uid == 0).then_some(layer as u64);+ ImeTarget::new(egui::Id::unique(("filmcraft.graphics.ime", sequence, clip, component_uid, component_index)), replacement_epoch)+}++fn current_graphics_ime_target(app: &FilmcraftApp, clip: u64, layer: usize) -> Option<ImeTarget> {+ let sequence = app.session.state.active_sequence?.0;+ let uid = current_layer_uid(&app.session, clip, layer)?;+ Some(graphics_ime_target(sequence, clip, layer, uid, app.ime_replacement_epoch))+}+++/// Outside the keyboard reducer the actual engine/UI edit state is authoritative.++pub(crate) fn current_reset_destination(app: &FilmcraftApp) -> Option<crate::ime_reset::Destination> {++ let ed = app.ui.gfx_edit.as_ref()?;++ let target = current_graphics_ime_target(app, ed.clip, ed.layer)?;++ let text = current_layer_text(&app.session, ed.clip, ed.layer)?;++ Some(local_reset_destination(app, ed, text, target))++}++++fn local_reset_destination(app: &FilmcraftApp, ed: &GfxEdit, text: &str, target: ImeTarget) -> crate::ime_reset::Destination {++ crate::ime_reset::Destination { document: app.session.document_epoch, target, caret: ed.caret, anchor: ed.anchor, text: ime_text_stamp(text) }++}+++/// Is this IME commit/delete left over from a composition whose target or caret/focus was+/// interrupted? A terminal-pending composition still owns its pending commit/delete after an empty+/// preedit. `None` (no preedit was seen) still accepts a direct commit.+fn ime_event_is_stale(app: &FilmcraftApp, target: ImeTarget) -> bool {+ match app.ime_composition {+ Some(crate::ImeComposition::Stale) => true,+ Some(crate::ImeComposition::Active(active) | crate::ImeComposition::TerminalPending(active)) => active != target,+ None => false,+ }+}+/// Keyboard handling while a text layer is being edited.-fn text_edit(app: &mut FilmcraftApp, ui: &mut egui::Ui, v: &LayerView, mut ed: GfxEdit, resp: &egui::Response, actions: &mut Vec<(String, Value)>) {+fn text_edit(+ app: &mut FilmcraftApp,+ ui: &mut egui::Ui,+ v: &LayerView,+ mut ed: GfxEdit,+ resp: &egui::Response,+ actions: &mut Vec<(String, Value)>,+ pending_ime: &mut Option<PendingImeEdit>,+) {let _ = resp;++ let window_focused = ui.input(|input| input.viewport().focused.unwrap_or(input.focused));++ if !window_focused || app.ime_modal_blocks_input() || !ui.is_enabled() {++ app.suspended_ime_controls(ui.ctx());++ return;++ }// moving to another panel ends the edit; Properties and Essential Graphics style the text// being edited, so working there keeps it (#683). Only a move counts: an edit started with// another panel focused (an agent's `ui.set`) goes on until the focus moves.@@@ -1616,45 -1020,29 +1636,42 @@@ui.data_mut(|d| d.insert_temp(panel_id, app.ui.focused));if before.is_some_and(|b| b != app.ui.focused) && !matches!(app.ui.focused, PanelKind::Program | PanelKind::Properties | PanelKind::EssentialGraphics) {end_edit(app, ui);++ app.suspended_ime_controls(ui.ctx());return;}- let eid = egui::Id::new(TEXT_EDIT_ID);+ let eid = egui::Id::unique(TEXT_EDIT_ID);// a real (non-clickable) widget holds keyboard focus so shortcuts pause while typinglet fr = ui.interact(Rect::from_points(&v.quad()), eid, Sense::focusable_noninteractive());- fr.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::TextEdit, true, "Text layer"));+ fr.widget_info(|| egui::WidgetInfo::labeled(egui::Role::TextInput, true, "Text layer"));// while another field has the keyboard (a value typed in Properties) the keys are its own;// the text takes the keyboard back once nothing has it (#683)if ui.memory(|m| m.focused().is_some_and(|f| f != eid)) {- app.invalidate_ime_composition();++ app.suspended_ime_controls(ui.ctx());return;}ui.memory_mut(|m| {m.request_focus(eid);m.set_focus_lock_filter(eid, egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: true });});-- let Some(tp) = text_of(&v.spec) else { return };++ let Some(tp) = text_of(&v.spec) else {++ app.suspended_ime_controls(ui.ctx());++ return;++ };let mut text = tp.text.clone();- ed.caret = ed.caret.min(text.len());- ed.anchor = ed.anchor.min(text.len());+ // `ui.set.gfxEdit` accepts arbitrary byte offsets. Clamp both ends to UTF-8 boundaries here,+ // before any slice/replace_range/insert_str, so hostile offsets can never panic the editor.+ clamp_edit_offsets(&text, &mut ed);let l = text_layout(tp);let events = ui.input(|i| i.events.clone());+ let sequence = app.session.state.active_sequence.map_or(0, |sequence| sequence.0);+ let composition_target = graphics_ime_target(sequence, ed.clip, ed.layer, v.spec.uid, app.ime_replacement_epoch);let mut changed = false;let mut stop = false;+ let mut application_mutation = false;- // A stale event was rejected in this raw input batch. A rejected commit is the composition's- // terminal boundary: consume the tombstone immediately, so a preedit later in the same raw- // batch starts a new composition. A stale empty preedit or delete is only tentatively- // terminal: keep the tombstone through the batch so its paired old commit is rejected too,- // then clear it at batch end when no commit followed. A lone non-empty preedit is only an- // update of the old composition: keep the tombstone across batches so its later commit is- // still dropped.- let mut stale_batch = false;- let mut stale_preedit_only = false;++ // A break becomes an ordered controls-only suffix, never a marker pre-scan.++ let mut custom_mutations = true;+ let mut ime_before: Option<(usize, usize)> = None;+ let mut ime_after: Vec<ImeMutationStamp> = Vec::new();let sel = |ed: &GfxEdit| (ed.caret.min(ed.anchor), ed.caret.max(ed.anchor));let delete_sel = |text: &mut String, ed: &mut GfxEdit| -> bool {let (a, b) = sel(ed);@@@ -1666,75 -1054,10 +1683,67 @@@ed.anchor = a;true};- 'events: for ev in events {+ for ev in events {++ let destination = local_reset_destination(app, &ed, &text, composition_target);++ if custom_mutations {++ app.sync_live_ime_destination(ui.ctx(), destination);++ }++ if let egui::Event::ImeResetCompleted { request_id } = ev {++ if custom_mutations && app.ime_reset.complete(ui.ctx(), request_id, destination) && app.ime_composition_viewport == Some(ui.ctx().viewport_id()) {++ app.ime_composition = None;++ app.ime_composition_viewport = None;++ }++ continue;++ }++ if !custom_mutations || (app.ime_reset.blocked(ui.ctx().viewport_id()) && matches!(&ev, egui::Event::Ime(_))) {++ continue;++ }++ let from_ime = matches!(&ev, egui::Event::Ime(_));++ let terminal = matches!(&ev, egui::Event::Ime(egui::ImeEvent::Commit(_)));match ev {- // The platform IME owns a composition between a non-empty preedit and its terminal- // commit; an empty preedit leaves that terminal event pending. Remember which target- // it belongs to; an event after the target was replaced must not edit the new layer.- // an input method (Chinese, Japanese, Korean) hands over its finished text as a commit (#1083)- egui::Event::Text(s) | egui::Event::Paste(s) | egui::Event::Ime(egui::ImeEvent::Commit(s)) => {+ egui::Event::Ime(egui::ImeEvent::Preedit { text, .. }) => {++ app.ime_composition_viewport = Some(ui.ctx().viewport_id());+ if text.is_empty() {- // Dismissing a pre-edit clears the visible composition, but its terminal- // commit/delete may arrive in a later event. Keep the owner as- // terminal-pending so a target switch still rejects that event. A stale- // empty preedit must not lift the tombstone before a paired old commit.- if matches!(app.ime_composition, Some(crate::ImeComposition::Stale)) {- stale_batch = true;- stale_preedit_only = false;- } else {- app.ime_composition = Some(crate::ImeComposition::TerminalPending(composition_target));- }- } else if matches!(app.ime_composition, Some(crate::ImeComposition::Stale)) {- // This pre-edit belongs to the composition whose target was replaced: an- // input method can emit further non-empty pre-edits before its final- // commit. Do not revive the old composition on the replacement target.- // Keep the tombstone past this batch: the old composition may commit in a- // later raw batch; a later empty preedit, delete or commit ends it.- stale_batch = true;- stale_preedit_only = true;++ app.ime_composition = Some(crate::ImeComposition::TerminalPending(composition_target));+ } else {+ app.ime_composition = Some(crate::ImeComposition::Active(composition_target));+ }+ }+ // text-input-v3/Wayland delete-surrounding arrives in UTF-8 bytes. Only whole+ // characters fully inside the reported range are deleted: a byte count that ends+ // inside a character leaves that character (the fork's contract), so a combining+ // accent or the letter next to an emoji is preserved.+ egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes, after_bytes }) => {+ if ime_event_is_stale(app, composition_target) {- // Keep the tombstone for the commit paired with this delete.- stale_batch = true;- stale_preedit_only = false;+ continue;+ }+ let (a, b) = sel(&ed);+ let (before, after) = surrounding_byte_deletion_ranges(&text, a, b, before_bytes, after_bytes);+ if !before.is_empty() || !after.is_empty() {+ let (before_caret, before_anchor) = (ed.caret, ed.anchor);+ apply_surrounding_deletion(&mut text, &mut ed, before, after);+ ime_before.get_or_insert((before_caret, before_anchor));+ ime_after.push(ime_stamp(&text, ed.caret, ed.anchor));+ changed = true;+ }+ }+ egui::Event::Ime(egui::ImeEvent::DeleteSurrounding { before_chars, after_chars }) => {+ if ime_event_is_stale(app, composition_target) {- stale_batch = true;- stale_preedit_only = false;+ continue;+ }+ let (a, b) = sel(&ed);+ let before = prev_n_chars(&text, a, before_chars)..a;+ let after = b..next_n_chars(&text, b, after_chars);+ if !before.is_empty() || !after.is_empty() {+ let (before_caret, before_anchor) = (ed.caret, ed.anchor);+ apply_surrounding_deletion(&mut text, &mut ed, before, after);+ ime_before.get_or_insert((before_caret, before_anchor));+ ime_after.push(ime_stamp(&text, ed.caret, ed.anchor));+ changed = true;+ }+ }+ // ordinary typing and paste are application-origin, even in the same pass as an IME event+ egui::Event::Text(s) | egui::Event::Paste(s) => {let s: String = s.chars().filter(|c| !c.is_control() || *c == '\n').collect();if s.is_empty() {continue;@@@ -1743,42 -1066,8 +1752,37 @@@text.insert_str(ed.caret, &s);ed.caret += s.len();ed.anchor = ed.caret;+ application_mutation = true;changed = true;}+ // an input method (Chinese, Japanese, Korean) hands over its finished text as a commit (#1083)+ egui::Event::Ime(egui::ImeEvent::Commit(s)) => {+ if ime_event_is_stale(app, composition_target) {- // A commit is the composition's terminal boundary. Consume the tombstone now,- // so a preedit later in this same raw batch starts a new composition. The- // earlier empty preedit/delete already rejected the old composition's edits.- app.ime_composition = None;- stale_batch = true;- stale_preedit_only = false;+ continue;+ }+ app.ime_composition = None;++ app.ime_composition_viewport = None;+ let s: String = s.chars().filter(|c| !c.is_control() || *c == '\n').collect();+ let (before_caret, before_anchor) = (ed.caret, ed.anchor);+ if s.is_empty() {+ // A commit replaces the selection even when the input method produced no text+ // (for example DeleteSurroundingBytes followed by an empty commit). An empty+ // commit with no selection stays a no-op.+ if delete_sel(&mut text, &mut ed) {+ ime_before.get_or_insert((before_caret, before_anchor));+ ime_after.push(ime_stamp(&text, ed.caret, ed.anchor));+ changed = true;+ }- continue;++ } else {++ delete_sel(&mut text, &mut ed);++ text.insert_str(ed.caret, &s);++ ed.caret += s.len();++ ed.anchor = ed.caret;++ ime_before.get_or_insert((before_caret, before_anchor));++ ime_after.push(ime_stamp(&text, ed.caret, ed.anchor));++ changed = true;+ }- delete_sel(&mut text, &mut ed);- text.insert_str(ed.caret, &s);- ed.caret += s.len();- ed.anchor = ed.caret;- ime_before.get_or_insert((before_caret, before_anchor));- ime_after.push(ime_stamp(&text, ed.caret, ed.anchor));- changed = true;+ }egui::Event::Copy | egui::Event::Cut => {let (a, b) = sel(&ed);if a < b {@@@ -1793,12 -1081,7 +1797,14 @@@let shift = modifiers.shift;let mut moved = None;match key {- egui::Key::Escape => stop = true,+ egui::Key::Escape => {+ // Escape cancels the edit now: a commit later in the same raw batch must+ // not still be inserted after the user cancelled.+ stop = true;- break 'events;++ custom_mutations = false;++ app.suspend_ime_input(ui.ctx());++ continue;+ }egui::Key::Enter => {delete_sel(&mut text, &mut ed);text.insert(ed.caret, '\n');@@@ -1884,52 -1151,13 +1890,51 @@@if !shift {ed.anchor = ed.caret;}+ if previous_selection != (ed.caret, ed.anchor) {+ app.invalidate_ime_composition();+ }}}+ // A pointer press is handled later in this pass (caret placement, another layer, or+ // ending the edit). Events after it in the same raw batch belong to the new target+ // and must not be applied to the old one.- egui::Event::PointerButton { pressed: true, .. } => break 'events,++ egui::Event::PointerButton { pressed: true, .. } => {++ custom_mutations = false;++ app.suspend_ime_input(ui.ctx());++ }_ => {}}- }- if stale_batch {- // A tentatively terminal empty preedit/delete with no following commit ended the rejected- // composition: clear the tombstone so a later composition on the replacement target is- // accepted. A lone non-empty preedit keeps it for that composition's later commit. An- // active or terminal-pending composition recorded for another target is equally stale; a- // fresh pre-edit on this target is kept.- match app.ime_composition {- Some(crate::ImeComposition::Stale) if !stale_preedit_only => app.ime_composition = None,- Some(crate::ImeComposition::Active(active) | crate::ImeComposition::TerminalPending(active)) if active != composition_target => {- app.ime_composition = None;++ let current = local_reset_destination(app, &ed, &text, composition_target);++ if from_ime {++ if terminal {++ app.ime_reset.terminal(ui.ctx().viewport_id());++ } else {++ app.ime_reset.remember(ui.ctx().viewport_id(), current);+ }- _ => {}++ } else if custom_mutations {++ app.sync_live_ime_destination(ui.ctx(), current);+ }}if changed && text != tp.text {+ let action_index = actions.len();+ let first_before =+ ime_before.and_then(|(cursor, anchor)| (!ime_after.is_empty()).then(|| ImeMutationStamp::from_committed(&tp.text, cursor, anchor, None)));++ *pending_ime = Some(PendingImeEdit {+ action_index,+ clip: ed.clip,+ layer: ed.layer,+ first_before,+ before_cursor: ime_before.map_or(ed.caret, |(cursor, _)| cursor),+ before_anchor: ime_before.map_or(ed.anchor, |(_, anchor)| anchor),+ after: ime_after,+ final_cursor: ed.caret,+ final_anchor: ed.anchor,+ application_mutation,+ });actions.push(("graphics.setText".into(), json!({"clip": ed.clip, "layer": ed.layer, "text": text, "merge": true})));+ } else {+ *pending_ime = None;}if stop {end_edit(app, ui);diff --cc crates/ui-egui/src/panels/misc.rsindex f5bc5f1e9,2196c1c81..a1fdc5418--- a/crates/ui-egui/src/panels/misc.rs+++ b/crates/ui-egui/src/panels/misc.rs@@@ -50,6 -50,76 +50,76 @@@ pub fn history(app: &mut FilmcraftApp,}}+ /// Egui memory key of the open Delete Redoable Actions confirmation.+ const CONFIRM_DELETE_REDOABLE: &str = "history-delete-redoable";++ /// The History panel's ≡ menu: Delete Redoable Actions and Clear History (automation ids+ /// `panel.menu.History.deleteRedoable` and `panel.menu.History.clear`). Returns true to close it.+ pub fn history_panel_menu(app: &mut FilmcraftApp, ui: &mut egui::Ui) -> bool {+ let ctx = ui.ctx().clone();+ let mut close = false;+ for (id, label, command) in [("deleteRedoable", tl!("Delete Redoable Actions"), "history.deleteRedoable"), ("clear", tl!("Clear History"), "history.clear")]+ {+ let r = ui.add_enabled(app.session.is_enabled(command), egui::Button::new(label));+ app.auto.add_response(&format!("panel.menu.History.{id}"), &r, label);+ if r.clicked() {+ if let Err(e) = crate::menus::invoke(app, &ctx, command, serde_json::json!({})) {+ app.ui.status = e;+ }+ close = true;+ }+ }+ close+ }++ /// Delete Redoable Actions from the panel menu or a key (no parameters) asks for OK first, as in+ /// Premiere. Returns None for other ids, and for calls with parameters, which run the command.+ pub fn route_history(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: &serde_json::Value) -> Option<Result<serde_json::Value, String>> {+ if id != "history.deleteRedoable" || !params.as_object().is_none_or(|m| m.is_empty()) {+ return None;+ }+ if !app.session.history.can_redo() {+ return Some(Err("nothing to redo".into()));+ }- ctx.data_mut(|d| d.insert_temp(egui::Id::new(CONFIRM_DELETE_REDOABLE), true));++ ctx.data_mut(|d| d.insert_temp(egui::Id::unique(CONFIRM_DELETE_REDOABLE), true));+ Some(Ok(serde_json::json!({"dialog": "deleteRedoable"})))+ }++ /// The Delete Redoable Actions confirmation (automation ids `history.deleteRedoable.cancel` and+ /// `history.deleteRedoable.ok`). It closes by itself when nothing is left to redo.+ pub fn history_dialogs(app: &mut FilmcraftApp, ctx: &egui::Context) {- let key = egui::Id::new(CONFIRM_DELETE_REDOABLE);++ let key = egui::Id::unique(CONFIRM_DELETE_REDOABLE);+ if !ctx.data(|d| d.get_temp::<bool>(key)).unwrap_or(false) {+ return;+ }+ let mut close = !app.session.history.can_redo();+ egui::Window::new(tl!("Delete Redoable Actions"))+ .id(key.with("window"))+ .collapsible(false)+ .resizable(false)+ .pivot(Align2::CENTER_CENTER)+ .default_pos(crate::widgets::dialog_center(ctx))+ .show(ctx, |ui| {+ ui.label(tl!("Delete the dimmed actions after the current state? They cannot be redone."));+ ui.horizontal(|ui| {+ let r = ui.button(tl!("Cancel"));+ app.auto.add("history.deleteRedoable.cancel", r.rect, "Cancel");+ close |= r.clicked();+ let r = ui.button(tl!("OK"));+ app.auto.add("history.deleteRedoable.ok", r.rect, "OK");+ if r.clicked() {+ if let Err(e) = app.session.execute("history.deleteRedoable", serde_json::json!({})) {+ app.ui.status = e.to_string();+ }+ close = true;+ }+ });+ });+ if close || crate::widgets::escape_closes(ctx) {+ ctx.data_mut(|d| d.remove::<bool>(key));+ }+ }+/// The marker colours of the Markers panel filter (each chip stands for the labels that share its/// marker colour).pub const MARKER_FILTER: [filmcraft_project::Label; 7] = {diff --cc crates/ui-egui/src/panels/mixer.rsindex 0bf72e724,aea3b830e..ecbe13411--- a/crates/ui-egui/src/panels/mixer.rs+++ b/crates/ui-egui/src/panels/mixer.rs@@@ -87,9 -87,9 +87,9 @@@ pub const INPUT_METER: u64 = u64::MAX/// Per-strip meter state, `strip id → [level, peak]` per channel (dBFS; 2 channels, or 6 for 5.1/// strips), fed by the playing mix ([`filmcraft_render::mixer::LiveMix`]) with fast attack and a- /// 20 dB/s fall. [`INPUT_METER`] holds the voice-over input.+ /// 20 dB/s fall (peak holds 6 dB/s) while live, dropping within a quarter second after Stop. [`INPUT_METER`] holds the voice-over input.pub fn poll_meters(app: &mut FilmcraftApp, ui: &egui::Ui) -> HashMap<u64, Vec<[f32; 2]>> {- let id = egui::Id::new("mixer-meters");+ let id = egui::Id::unique("mixer-meters");let frame = ui.ctx().cumulative_frame_nr();let (last, mut st): (u64, HashMap<u64, Vec<[f32; 2]>>) = ui.data(|d| d.get_temp(id)).unwrap_or_default();if last == frame && frame != 0 {diff --cc crates/ui-egui/src/panels/text.rsindex 1fcc611d6,9702bd8b7..8852aa68e--- a/crates/ui-egui/src/panels/text.rs+++ b/crates/ui-egui/src/panels/text.rs@@@ -178,6 -178,9 +178,9 @@@ fn captions(app: &mut FilmcraftApp, uilet q = app.ui.caption_search.to_lowercase();let mut child = ui.new_child(egui::UiBuilder::new().max_rect(list.shrink(4.0)).id_salt("caption-list"));let current = track.caption_at(ph).map(|c| c.id);+ if current.is_none() {- ui.data_mut(|d| d.remove::<u64>(egui::Id::new("caption-follow")));++ ui.data_mut(|d| d.remove::<u64>(egui::Id::unique("caption-follow")));+ }egui::ScrollArea::vertical().auto_shrink([false, false]).id_salt("caption-scroll").show(&mut child, |ui| {ui.set_width(list.width() - 12.0);let mut shown = 0;@@@ -272,6 -269,13 +275,13 @@@let row = fr.response.rect;if current == Some(c.id) {ui.painter().rect_stroke(row, 3.0, Stroke::new(1.0, t.accent), StrokeKind::Inside);+ // the list follows the playhead: each caption it reaches is brought to the middle+ // once, but never while a field is being edited- let follow = egui::Id::new("caption-follow");++ let follow = egui::Id::unique("caption-follow");+ if ui.data(|d| d.get_temp::<u64>(follow)) != Some(c.id.0) && ui.memory(|m| m.focused().is_none()) {+ ui.scroll_to_rect(row, Some(egui::Align::Center));+ ui.data_mut(|d| d.insert_temp(follow, c.id.0));+ }}app.auto.add(&format!("text.captions.{}.row", c.id.0), row, &c.text);ui.add_space(2.0);diff --cc crates/ui-egui/src/panels/timeline.rsindex e8583b803,3d59a0c6c..7e79c2a7a--- a/crates/ui-egui/src/panels/timeline.rs+++ b/crates/ui-egui/src/panels/timeline.rs@@@ -1627,6 -1629,27 +1636,27 @@@ fn draw_top(app: &mut FilmcraftApp, ui});}}+ // work area bar: between the markers row and the time labels, as dragged while a drag of it runs+ let shown = match app.tl.drag {+ Some(Drag::WorkArea { start, end, .. }) => Some(TimeRange::from_bounds(start, end)),+ _ => seq.work_area,+ };+ if let Some(area) = shown {+ let r = work_area_rect(layout, area);+ clip.rect_filled(r, 1.0, t.text_dim);+ for x in [r.min.x, r.max.x] {+ clip.rect_filled(Rect::from_center_size(pos2(x, r.center().y), vec2(3.0, r.height() + 2.0)), 1.0, t.text);+ }+ app.auto.add("timeline.workArea", r.intersect(ruler), "Work Area Bar");+ let fmt = |tick: Tick| format_time(tick, rate, seq.settings.drop_frame, TimeDisplay::Timecode, 48000);+ if ui.rect_contains_pointer(r.expand2(vec2(EDGE_PX, 1.0)).intersect(ruler)) {- egui::Tooltip::always_open(ui.ctx().clone(), ui.layer_id(), egui::Id::new("work-area-tip"), egui::PopupAnchor::Pointer).show(|ui| {++ egui::Tooltip::always_open(ui.ctx().clone(), ui.layer_id(), egui::Id::unique("work-area-tip"), egui::PopupAnchor::Pointer).show(|ui| {+ ui.label(tlf!("Start: {tc}", tc = fmt(area.start)));+ ui.label(tlf!("End: {tc}", tc = fmt(area.end())));+ ui.label(tlf!("Duration: {tc}", tc = fmt(area.duration)));+ });+ }+ }// markers: 8 × 12 pt pentagons in the marker colour, on the top rowfor m in &seq.markers {let x = layout.x_of(m.start);diff --cc crates/ui-egui/src/panels/timeline_captions.rsindex 643286adb,eb5869356..4643c0d33--- a/crates/ui-egui/src/panels/timeline_captions.rs+++ b/crates/ui-egui/src/panels/timeline_captions.rs@@@ -188,6 -206,45 +206,45 @@@ pub fn interact(app: &mut FilmcraftApprun(app, ui, actions);}+ /// The Razor tool over a caption: a white line where it would cut, and a click splits the caption+ /// there (Shift: every caption on an unlocked caption track at that time), as it cuts clips.+ #[allow(clippy::too_many_arguments)]+ fn razor_block(+ app: &mut FilmcraftApp,+ ui: &mut egui::Ui,+ seq: &Sequence,+ layout: &Layout,+ tr: &CaptionTrack,+ c: &filmcraft_project::Caption,+ r: Rect,+ row: Rect,+ actions: &mut Vec<(String, Value)>,+ ) {+ let ctx = ui.ctx().clone();- let resp = ui.interact(r, egui::Id::new(("caption-block", c.id.0)), Sense::click_and_drag());++ let resp = ui.interact(r, egui::Id::unique(("caption-block", c.id.0)), Sense::click_and_drag());+ if tr.locked {+ return;+ }+ let rate = seq.settings.frame_rate;+ let at = |app: &mut FilmcraftApp, x: f32| super::timeline::snap(app, seq, layout, rate.snap_nearest(layout.tick_at(x)), &[]);+ if let Some(p) = resp.hover_pos() {+ ctx.set_cursor_icon(CursorIcon::Crosshair);+ let x = layout.x_of(at(app, p.x));+ ui.painter().with_clip_rect(layout.content).line_segment([pos2(x, row.min.y), pos2(x, row.max.y)], Stroke::new(1.0, Color32::WHITE));+ }+ // a press that starts a drag cuts as well, as on clips+ if (resp.clicked() || resp.drag_started())+ && let Some(p) = ctx.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos())+ {+ let t = at(app, p.x);+ if ctx.input(|i| i.modifiers.shift) {+ actions.push(("captions.split".into(), json!({"time": t.0})));+ } else if c.start < t && t < c.end() {+ actions.push(("captions.split".into(), json!({"caption": c.id.0, "time": t.0})));+ }+ }+ }+fn interact_block(app: &mut FilmcraftApp,ui: &mut egui::Ui,@@@ -250,7 -307,10 +307,10 @@@&& let (Some((id, g, _)), Some(p)) = (drag_state(&ctx), resp.interact_pointer_pos())&& id == c.id.0{+ if g == 0 && ctx.input(|i| i.modifiers.alt) {+ ctx.set_cursor_icon(CursorIcon::Copy);+ }- let x0 = ctx.data(|d| d.get_temp::<f32>(egui::Id::new("caption-drag-origin"))).unwrap_or(p.x);+ let x0 = ctx.data(|d| d.get_temp::<f32>(egui::Id::unique("caption-drag-origin"))).unwrap_or(p.x);let pps = app.ui.timeline.pps;let d = rate.snap_nearest(Tick::from_seconds_f64((p.x - x0) as f64 / pps));ctx.data_mut(|dd| dd.insert_temp(drag_id(), (id, g, d.0)));diff --cc crates/ui-egui/tests/it/graphics_handles_ui.rsindex b850368f4,f3c03fb51..716576a77--- a/crates/ui-egui/tests/it/graphics_handles_ui.rs+++ b/crates/ui-egui/tests/it/graphics_handles_ui.rs@@@ -16,21 -16,21 +16,31 @@@ struct Driverharness: Harness<'static, FilmcraftApp>,tx: Sender<ControlRequest>,shots: Option<std::path::PathBuf>,++ // Real Context output tokens, retained across later idle/control-channel frames.++ reset_requests: Vec<egui::ImeResetId>,}impl Driver {fn new() -> Self {++ Self::new_with(|_| {})++ }++++ fn new_with(configure: impl FnOnce(&mut FilmcraftApp)) -> Self {let mut s = Session::default();s.execute("file.openDemoProject", json!({})).unwrap();let (tx, rx) = channel();-- let app = FilmcraftApp::new(s).with_control(rx);++ let mut app = FilmcraftApp::new(s).with_control(rx);++ configure(&mut app);let shots = std::env::var_os("FILMCRAFT_UI_SHOTS").map(std::path::PathBuf::from);let mut b = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_step_dt(1.0 / 60.0).with_max_steps(10_000);if shots.is_some() {b = b.wgpu().with_pixels_per_point(1.0);}-- let harness = b.build_eframe(move |_cc| app);-- let mut d = Driver { harness, tx, shots };++ let harness = b.build_eframe(move |cc| {++ filmcraft_ui_egui::install_ime_reset_callbacks(&cc.egui_ctx);++ app++ });++ let mut d = Driver { harness, tx, shots, reset_requests: Vec::new() };d.frames(4);d}@@@ -43,9 -43,9 +53,16 @@@eframe::App::raw_input_hook(self.harness.state_mut(), &ctx, &mut raw);*self.harness.input_mut() = raw;self.harness.step();++ if let Some(request) = self.harness.output().platform_output.ime.as_ref().and_then(|ime| ime.reset_request) {++ self.reset_requests.push(request);++ }}}++ fn reset_completed(&self) -> egui::Event {++ egui::Event::ImeResetCompleted { request_id: *self.reset_requests.last().expect("a real Context reset request was published") }++ }++fn call(&mut self, method: &str, params: Value) -> Value {let (req, reply) = ControlRequest::new(method, params.clone());self.tx.send(req).unwrap();@@@ -375,839 -357,6 +392,1289 @@@ fn text_committed_by_an_input_method_isassert_eq!(list["layers"][0]["text"], "A你好");}+/// The Program monitor's custom IME producer reports committed logical text, a reversed UTF-8+/// selection, ignores preedit-only updates, and labels an accepted commit `InputMethod` while+/// ordinary typing remains `Other`.+#[test]+fn ime_output_reports_committed_text_selection_and_cause() {+ let mut d = Driver::new();+ let clip = d.start_point_text();+ d.ok("ui.type", json!({"text": "café😀"}));+ d.frames(3);++ let first = d.ime().expect("the focused text layer publishes an IME context");+ let first_payload = ime_payload(&first);+ assert_eq!(first_payload.text, "café😀");+ assert_eq!(first_payload.cursor, "café😀".len());+ assert_eq!(first_payload.anchor, "café😀".len());+ assert_eq!(first.change_cause, egui::output::ImeChangeCause::Other);+ let (owner, generation) = (first.owner, first.context_generation);++ // Primary caret 5 (after é), anchor 2: a reversed selection of "fé".+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 5, "anchor": 2}}));+ d.frames(3);+ let selected = d.ime().expect("selection keeps the context");+ assert_eq!(selected.owner, owner);+ assert_eq!(selected.context_generation, generation, "ordinary caret/selection moves keep the generation");+ let p = ime_payload(&selected);+ assert_eq!((p.cursor, p.anchor), (5, 2), "direction is preserved");++ // A pre-edit alone is not committed text and must not be sent.+ d.harness.input_mut().events.push(egui::Event::Ime(egui::ImeEvent::Preedit { text: "に".into(), active_range_chars: Some(0..1) }));+ d.frames(2);+ let preedit = d.ime().expect("preedit does not remove the context");+ let p = ime_payload(&preedit);+ assert_eq!(p.text, "café😀");+ assert_eq!((p.cursor, p.anchor), (5, 2));++ // The commit replaces the selected "fé"; only this accepted mutation is InputMethod.+ d.harness.input_mut().events.push(egui::Event::Ime(egui::ImeEvent::Commit("語".into())));+ d.frames(1);+ let committed = d.ime().expect("the commit is observed after its action");+ assert_eq!(committed.owner, owner);+ assert_eq!(committed.context_generation, generation);+ assert_eq!(committed.change_cause, egui::output::ImeChangeCause::InputMethod);+ let p = ime_payload(&committed);+ assert_eq!(p.text, "ca語😀");+ assert_eq!((p.cursor, p.anchor), (5, 5));++ // An empty (no-op) commit must not claim InputMethod for the unchanged snapshot.+ d.harness.input_mut().events.push(egui::Event::Ime(egui::ImeEvent::Commit(String::new())));+ d.frames(1);+ let no_op = d.ime().expect("a no-op commit leaves the context in place");+ assert_eq!(no_op.change_cause, egui::output::ImeChangeCause::Other);++ // Repeated passes rebuild the same post-mutation descriptor without resetting the context.+ d.frames(2);+ let repeated = d.ime().expect("the committed editor is still observed");+ assert_eq!(repeated.owner, owner);+ assert_eq!(repeated.context_generation, generation);+ let p = ime_payload(&repeated);+ assert_eq!(p.text, "ca語😀");+ assert_eq!((p.cursor, p.anchor), (5, 5));++ // Ordinary typing in a later frame is application-origin, never InputMethod.+ d.ok("ui.type", json!({"text": "X"}));+ d.frames(2);+ let typed = d.ime().expect("typing keeps the context");+ assert_eq!(typed.context_generation, generation);+ assert_eq!(typed.change_cause, egui::output::ImeChangeCause::Other);+ assert_eq!(ime_payload(&typed).text, "ca語X😀", "typing inserts at the retained caret before the emoji");+ assert_eq!((ime_payload(&typed).cursor, ime_payload(&typed).anchor), (6, 6));+}++/// Delete-surrounding excludes the selection, rounds partial UTF-8 ranges inward, and keeps a+/// reversed selection's direction while the queued edit is accepted.+#[test]+fn ime_delete_surrounding_keeps_selection_direction_and_unicode() {+ let mut d = Driver::new();+ let clip = d.start_point_text();+ d.ok("ui.type", json!({"text": "aé😀z"}));+ d.frames(3);+ // Select é (bytes 1..3), primary caret at its end (reversed).+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 3, "anchor": 1}}));+ d.frames(3);+ d.harness.input_mut().events.push(egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 1, after_bytes: 4 }));+ d.frames(1);+ let ime = d.ime().expect("delete-surrounding publishes the edited context");+ assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod);+ let p = ime_payload(&ime);+ assert_eq!(p.text, "éz", "one byte before and the four-byte emoji after are deleted; é is kept");+ assert_eq!((p.cursor, p.anchor), (2, 0), "primary caret stays after the anchor");+ assert_eq!(d.exec("graphics.list", json!({}))["layers"][0]["text"], "éz");+}++/// An available empty layer is `Available("", 0, 0)`, while a selection over the 4000-byte+/// protocol limit is an explicit `Unavailable`, never a truncated or fabricated snapshot.+#[test]+fn ime_surrounding_text_distinguishes_empty_from_unavailable_and_is_bounded() {+ let mut d = Driver::new();+ let clip = d.start_point_text();+ let empty = d.ime().expect("an empty new text layer is still a focused IME owner");+ let p = ime_payload(&empty);+ assert!(p.text.is_empty());+ assert_eq!((p.cursor, p.anchor), (0, 0));++ d.exec("graphics.setText", json!({"clip": clip, "layer": 0, "text": "a".repeat(5001)}));+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 4000, "anchor": 0}}));+ d.frames(3);+ let at_limit = d.ime().expect("the edit context remains focused");+ let p = ime_payload(&at_limit);+ assert_eq!(p.text.len(), 4000);+ assert_eq!((p.cursor, p.anchor), (4000, 0));++ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 4001, "anchor": 0}}));+ d.frames(3);+ let over = d.ime().expect("an unavailable snapshot still has an owner and generation");+ assert!(over.surrounding_text.available().is_none(), "a too-wide selection is explicitly Unavailable");+ assert_eq!(over.owner, at_limit.owner);+}++/// Losing focus ends the output; reopening the same layer keeps the stable owner but resets the+/// generation exactly once. A plain caret move does not reset it.+#[test]+fn ime_owner_is_stable_across_edits_and_resets_on_refocus() {+ let mut d = Driver::new();+ d.start_point_text();+ d.ok("ui.type", json!({"text": "Title"}));+ d.frames(3);+ let first = d.ime().expect("text editing has an IME context");+ let (owner, generation) = (first.owner, first.context_generation);++ d.ok("ui.key", json!({"key": "ArrowLeft"}));+ d.frames(2);+ let moved = d.ime().expect("caret movement keeps the context");+ assert_eq!(moved.owner, owner);+ assert_eq!(moved.context_generation, generation, "ordinary caret movement does not reset");++ d.ok("ui.key", json!({"key": "Escape"}));+ d.frames(2);+ assert!(d.ime().is_none(), "an unfocused, closed editor publishes no descriptor");++ let pic = d.rect("program.picture");+ d.ok("ui.click", json!({"x": pic[0] + pic[2] * 0.3, "y": pic[1] + pic[3] * 0.2}));+ d.frames(3);+ let reopened = d.ime().expect("the reopened editor publishes again");+ assert_eq!(reopened.owner, owner, "the sequence/clip/component owner is stable");+ assert_ne!(reopened.context_generation, generation, "a replacement session resets the generation once");+}++/// An ordinary text event in the same pass as an accepted commit makes the whole frame `Other`.+#[test]+fn ime_mixed_application_and_ime_mutation_is_other() {+ let mut d = Driver::new();+ d.start_point_text();+ d.frames(2);+ let before = d.ime().expect("the empty editor is focused");+ d.harness.input_mut().events.extend([egui::Event::Text("A".into()), egui::Event::Ime(egui::ImeEvent::Commit("B".into()))]);+ d.frames(1);+ let mixed = d.ime().expect("the mixed edit is observed");+ assert_eq!(ime_payload(&mixed).text, "AB");+ assert_eq!(mixed.change_cause, egui::output::ImeChangeCause::Other);+ assert_eq!(mixed.context_generation, before.context_generation);++ // A toolbar/control edit of the same target is application-origin too, even after a commit.+ let clip = d.exec("graphics.list", json!({}))["clip"].as_u64().unwrap();+ d.exec("graphics.setText", json!({"clip": clip, "layer": 0, "text": "toolbar"}));+ d.frames(2);+ let toolbar = d.ime().expect("the toolbar edit keeps the owner");+ assert_eq!(ime_payload(&toolbar).text, "toolbar");+ assert_eq!(toolbar.change_cause, egui::output::ImeChangeCause::Other);+}++fn ime_preedit(text: &str) -> egui::Event {+ egui::Event::Ime(egui::ImeEvent::Preedit { text: text.into(), active_range_chars: None })+}++fn ime_commit(text: &str) -> egui::Event {+ egui::Event::Ime(egui::ImeEvent::Commit(text.into()))+}++fn key_press(key: egui::Key) -> egui::Event {+ egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }+}++fn layer_texts(d: &mut Driver, clip: u64) -> Vec<String> {+ d.exec("graphics.list", json!({"clip": clip}))["layers"]+ .as_array()+ .map(|layers| layers.iter().map(|layer| layer["text"].as_str().unwrap_or("").to_string()).collect())+ .unwrap_or_default()+}++fn new_text_layer(d: &mut Driver, clip: Option<u64>, text: &str, x: f64) -> u64 {+ let mut p = json!({"text": text, "position": [x, 400], "size": 100});+ if let Some(clip) = clip {+ p["clip"] = json!(clip);+ }+ d.exec("graphics.newText", p)["clip"].as_u64().unwrap()+}++/// A commit from a composition whose target was replaced (`ui.set.gfxEdit`) must be dropped: the+/// text belongs to the old layer, not to whatever layer the new edit target names.+#[test]+fn ime_commit_after_target_replacement_is_dropped() {+ let mut d = Driver::new();+ let clip = new_text_layer(&mut d, None, "alpha", 500.0);+ new_text_layer(&mut d, Some(clip), "beta", 900.0);+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 5, "anchor": 5}}));+ d.frames(3);+ d.harness.input_mut().events.push(ime_preedit("に"));+ d.frames(1);+ // The edit target moves to the other layer while the IME is still composing.+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 1, "caret": 4, "anchor": 4}}));+ d.frames(2);+ d.harness.input_mut().events.push(ime_commit("x"));+ d.frames(2);+ assert_eq!(layer_texts(&mut d, clip), vec!["alpha".to_string(), "beta".to_string()]);+}++/// A composition whose target was replaced can emit another non-empty pre-edit before its final+/// commit. That late pre-edit must not revive the old composition on the replacement layer, while+/// a genuinely new composition in a later raw batch must still work.+#[test]+fn ime_late_preedit_after_target_replacement_cannot_retarget() {+ let mut d = Driver::new();+ let clip = new_text_layer(&mut d, None, "alpha", 500.0);+ new_text_layer(&mut d, Some(clip), "beta", 900.0);+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 5, "anchor": 5}}));+ d.frames(3);+ d.harness.input_mut().events.push(ime_preedit("に"));+ d.frames(1);+ // The edit target moves to the other layer while the old composition is still live.+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 1, "caret": 4, "anchor": 4}}));+ d.frames(2);+ // A late pre-edit from the replaced composition. The input method commits it in a later raw+ // batch, so the tombstone must survive the pre-edit batch.+ d.harness.input_mut().events.push(ime_preedit("にに"));+ d.frames(1);+ d.harness.input_mut().events.push(ime_commit("x"));+ d.frames(2);+ assert_eq!(layer_texts(&mut d, clip), vec!["alpha".to_string(), "beta".to_string()], "the late pre-edit and paired commit stayed on the old target");+ assert!(+ d.ime().is_none_or(|ime| ime.change_cause != egui::output::ImeChangeCause::InputMethod),+ "a rejected stale composition is not an InputMethod receipt"+ );+- // The rejected composition's commit ended the tombstone: a fresh composition on the- // replacement layer is legitimate and must be accepted.- d.harness.input_mut().events.extend([ime_preedit("よ"), ime_commit("y")]);++ // Only the matching reset completion releases the old composition guard.++ let fence = d.reset_completed();++ d.harness.input_mut().events.extend([fence, ime_preedit("よ"), ime_commit("y")]);+ d.frames(2);+ assert_eq!(layer_texts(&mut d, clip), vec!["alpha".to_string(), "betay".to_string()], "a new composition on the current target still works");+}++/// An empty pre-edit clears the visible composition but not ownership of its pending terminal+/// commit. Switching targets before that commit arrives must still reject it.+#[test]+fn ime_empty_preedit_keeps_pending_commit_from_retargeting() {+ let mut d = Driver::new();+ let clip = new_text_layer(&mut d, None, "alpha", 500.0);+ new_text_layer(&mut d, Some(clip), "beta", 900.0);+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 5, "anchor": 5}}));+ d.frames(3);+ d.harness.input_mut().events.push(ime_preedit("に"));+ d.frames(1);+ // The empty pre-edit dismisses the visible composition. Its commit is a separate event.+ d.harness.input_mut().events.push(ime_preedit(""));+ d.frames(1);+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 1, "caret": 4, "anchor": 4}}));+ d.frames(2);+ d.harness.input_mut().events.push(ime_commit("x"));+ d.frames(2);+ assert_eq!(+ layer_texts(&mut d, clip),+ vec!["alpha".to_string(), "beta".to_string()],+ "the pending commit of the dismissed composition stayed on the old target"+ );+- // The rejected commit ended that composition; a direct commit on the current target works.- d.harness.input_mut().events.push(ime_commit("y"));++ // An old terminal is not acknowledgement; the exact fence admits a fresh direct commit.++ let fence = d.reset_completed();++ d.harness.input_mut().events.extend([fence, ime_commit("y")]);+ d.frames(2);+ assert_eq!(layer_texts(&mut d, clip), vec!["alpha".to_string(), "betay".to_string()], "a direct commit after the terminal boundary is accepted");+}+- /// A rejected old commit is a terminal boundary even when the same raw batch immediately starts a- /// new pre-edit. That new composition must survive to its later commit.++/// A matching opaque fence is an ordered boundary; the fresh preedit after it survives to its++/// later commit, while the old terminal before it remains rejected.+#[test]- fn ime_preedit_after_stale_commit_in_one_batch_is_accepted() {++fn ime_preedit_after_reset_completion_in_one_batch_is_accepted() {+ let mut d = Driver::new();+ let clip = new_text_layer(&mut d, None, "alpha", 500.0);+ new_text_layer(&mut d, Some(clip), "beta", 900.0);+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 5, "anchor": 5}}));+ d.frames(3);+ d.harness.input_mut().events.push(ime_preedit("に"));+ d.frames(1);+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 1, "caret": 4, "anchor": 4}}));+ d.frames(2);- // Wayland can coalesce the old terminal events and a new pre-edit into one raw batch.- d.harness.input_mut().events.extend([ime_preedit(""), ime_commit("x"), ime_preedit("よ")]);++ // Preserve original raw order: old terminal, actual completion, then fresh preedit.++ let fence = d.reset_completed();++ d.harness.input_mut().events.extend([ime_preedit(""), ime_commit("x"), fence, ime_preedit("よ")]);+ d.frames(1);+ assert_eq!(layer_texts(&mut d, clip), vec!["alpha".to_string(), "beta".to_string()], "the old commit was still rejected");+ d.harness.input_mut().events.push(ime_commit("y"));+ d.frames(2);+ assert_eq!(+ layer_texts(&mut d, clip),+ vec!["alpha".to_string(), "betay".to_string()],+ "the pre-edit after the old terminal commit started a new composition"+ );+}++/// A same-pass control text mutation replaces the text the composition belonged to. The old+/// descriptor must not be published (existing behaviour) and the composition's next commit must+/// not be inserted into the replacement text.+#[test]+fn ime_same_pass_control_text_mutation_invalidates_composition() {+ let mut d = Driver::new();+ let clip = d.start_point_text();+ d.ok("ui.type", json!({"text": "one"}));+ d.frames(3);+ d.harness.input_mut().events.push(ime_preedit("に"));+ d.frames(1);+ // `ui.menu.invoke` is drained after the overlay drew and changes the committed text.+ d.ok("ui.menu.invoke", json!({"id": "graphics.setText", "params": {"clip": clip, "layer": 0, "text": "changed"}}));+ assert!(d.ime().is_none(), "the old cursor rectangle must not be published for the changed text");++ d.harness.input_mut().events.push(ime_commit("x"));+ d.frames(2);+ assert_eq!(layer_texts(&mut d, clip), vec!["changed".to_string()], "the old composition's commit must not edit the replacement text");+ assert!(d.ime().is_none_or(|ime| ime.change_cause != egui::output::ImeChangeCause::InputMethod), "a rejected stale commit is not an InputMethod receipt");+ // The control replacement keeps the editor's existing numeric byte offsets (the editor only+ // clamps them into the new text, as it did before this migration), so place the caret at the+ // end explicitly: this regression tests that the rejected composition's tombstone retires,+ // not the unrelated caret policy.+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 7, "anchor": 7}}));+ d.frames(1);+- // The rejected commit ended the tombstone: the next composition on the same target is- // legitimate and must still be accepted.- d.harness.input_mut().events.extend([ime_preedit("よ"), ime_commit("z")]);++ let fence = d.reset_completed();++ d.harness.input_mut().events.extend([fence, ime_preedit("よ"), ime_commit("z")]);+ d.frames(2);+ assert_eq!(layer_texts(&mut d, clip), vec!["changedz".to_string()], "a new composition still starts after the text mutation");+}++/// A same-pass control request can change layout (font size, style, alignment, spacing, box,+/// transform) without changing the committed text or the layer identity. The pass must not+/// publish the cursor rectangle of the previous layout.+#[test]+fn ime_control_layout_change_does_not_publish_stale_cursor_rect() {+ let mut d = Driver::new();+ let clip = d.start_point_text();+ d.ok("ui.type", json!({"text": "one"}));+ d.frames(3);+ let before = d.ime().expect("the editor is observed before the layout change");+ d.ok("ui.menu.invoke", json!({"id": "graphics.set", "params": {"clip": clip, "layer": 0, "props": {"tracking": 200.0}}}));+ assert!(d.ime().is_none(), "the old cursor rectangle must not be published with the new layout");+ d.frames(1);+ let after = d.ime().expect("the next pass observes the new layout");+ assert_ne!(after.cursor_rect, before.cursor_rect, "the candidate rectangle moved with the wider tracking");+}++/// An explicit `ui.set.gfxEdit` names the layer at that numeric index now. A uid belonging to a+/// layer that a reorder moved elsewhere must not silently retarget the request.+#[test]+fn explicit_gfx_edit_index_selects_the_current_layer_not_a_stale_uid() {+ let mut d = Driver::new();+ let clip = new_text_layer(&mut d, None, "one", 400.0);+ new_text_layer(&mut d, Some(clip), "two", 900.0);+ let uids: Vec<u64> = d.exec("graphics.list", json!({"clip": clip}))["layers"].as_array().unwrap().iter().map(|l| l["uid"].as_u64().unwrap()).collect();+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 3, "anchor": 3}}));+ d.frames(2);+ assert_eq!(d.harness.state().ui.gfx_edit.as_ref().map(|e| (e.layer, e.uid)), Some((0, uids[0])));++ d.exec("graphics.arrangeLayer", json!({"clip": clip, "layer": 0, "to": "front"}));+ d.frames(2);+ assert_eq!(d.harness.state().ui.gfx_edit.as_ref().map(|e| (e.layer, e.uid)), Some((1, uids[0])), "the edit follows the reordered layer");++ // Index 0 now holds "two", but the request still carries the old "one" uid. The explicit+ // index wins: the current layer at index 0 is selected.+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 3, "anchor": 3, "uid": uids[0]}}));+ d.frames(2);+ assert_eq!(d.harness.state().ui.gfx_edit.as_ref().map(|e| (e.layer, e.uid)), Some((0, uids[1])), "the stale uid must not retarget the request");+ d.ok("ui.type", json!({"text": "X"}));+ d.frames(2);+ assert_eq!(layer_texts(&mut d, clip), vec!["twoX".to_string(), "one".to_string()]);+}++/// The fork sends `DeleteSurroundingBytes` immediately before the `Commit` it belongs to. A stale+/// delete must not lift the tombstone, or the paired commit would be inserted into the replacement- /// layer. The tombstone is bounded to this input batch: a later direct commit (no pre-edit) on the- /// new target is legitimate and must still be accepted.++/// layer. The request-bound guard survives the input batch; its exact completion admits a later++/// direct commit (no pre-edit) on the new target.+#[test]+fn stale_delete_and_commit_pair_cannot_retarget_the_replacement_layer() {+ let mut d = Driver::new();+ let clip = new_text_layer(&mut d, None, "alpha", 500.0);+ new_text_layer(&mut d, Some(clip), "beta", 900.0);+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 5, "anchor": 5}}));+ d.frames(3);+ d.harness.input_mut().events.push(ime_preedit("に"));+ d.frames(1);+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 1, "caret": 4, "anchor": 4}}));+ d.frames(2);+ d.harness.input_mut().events.extend([egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 0, after_bytes: 0 }), ime_commit("x")]);+ d.frames(2);+ assert_eq!(+ layer_texts(&mut d, clip),+ vec!["alpha".to_string(), "beta".to_string()],+ "neither the delete nor its paired commit touched the replacement layer"+ );+ assert!(d.ime().is_none_or(|ime| ime.change_cause != egui::output::ImeChangeCause::InputMethod), "a rejected stale pair is not an InputMethod receipt");+- // The tombstone ends with that batch: a later commit-only composition is accepted on the- // layer the user is editing now.- d.harness.input_mut().events.push(ime_commit("y"));++ // The old pair does not release admission; the exact native fence does.++ let fence = d.reset_completed();++ d.harness.input_mut().events.extend([fence, ime_commit("y")]);+ // One pass: the receipt belongs to the frame that observed the change. A later unchanged+ // frame reports `Other`, per the tracker contract.+ d.frames(1);+ // Reading through the control channel advances a frame; capture the receipt first.+ let receipt = d.ime().expect("the accepted direct commit is observed");+ assert_eq!(layer_texts(&mut d, clip), vec!["alpha".to_string(), "betay".to_string()]);+ assert_eq!(receipt.change_cause, egui::output::ImeChangeCause::InputMethod);+}++/// An empty pre-edit is the input method dismissing its composition. When it arrives after the+/// target was replaced it must not clear the tombstone before the paired commit, but it also must+/// not poison the next legitimate commit-only composition.+#[test]+fn stale_empty_preedit_and_commit_pair_cannot_retarget_the_replacement_layer() {+ let mut d = Driver::new();+ let clip = new_text_layer(&mut d, None, "alpha", 500.0);+ new_text_layer(&mut d, Some(clip), "beta", 900.0);+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 5, "anchor": 5}}));+ d.frames(3);+ d.harness.input_mut().events.push(ime_preedit("に"));+ d.frames(1);+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 1, "caret": 4, "anchor": 4}}));+ d.frames(2);+ d.harness.input_mut().events.extend([ime_preedit(""), ime_commit("x")]);+ d.frames(2);+ assert_eq!(layer_texts(&mut d, clip), vec!["alpha".to_string(), "beta".to_string()]);+ assert!(d.ime().is_none_or(|ime| ime.change_cause != egui::output::ImeChangeCause::InputMethod));+- d.harness.input_mut().events.push(ime_commit("y"));++ let fence = d.reset_completed();++ d.harness.input_mut().events.extend([fence, ime_commit("y")]);+ d.frames(2);+ assert_eq!(layer_texts(&mut d, clip), vec!["alpha".to_string(), "betay".to_string()], "later commit-only input still works");+}++/// A composition belongs to its layer's uid, not to the numeric index it was started at: a real+/// reorder moves the editor (and the commit) with the same layer.+#[test]+fn composition_follows_a_reordered_layer_by_uid() {+ let mut d = Driver::new();+ let clip = new_text_layer(&mut d, None, "one", 400.0);+ new_text_layer(&mut d, Some(clip), "two", 900.0);+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 3, "anchor": 3}}));+ d.frames(3);+ d.harness.input_mut().events.push(ime_preedit("に"));+ d.frames(1);+ d.exec("graphics.arrangeLayer", json!({"clip": clip, "layer": 0, "to": "front"}));+ d.frames(2);+ assert_eq!(d.harness.state().ui.gfx_edit.as_ref().map(|e| e.layer), Some(1));+ d.harness.input_mut().events.push(ime_commit("x"));+ d.frames(2);+ assert_eq!(layer_texts(&mut d, clip), vec!["two".to_string(), "onex".to_string()], "the composition stayed on the layer it began on");+}++/// `DeleteSurroundingBytes { 0, 0 }` followed by an empty commit is the IME's way of replacing a+/// selection with nothing. The selection must be deleted and the mutation labelled `InputMethod`.+#[test]+fn empty_ime_commit_replaces_the_selection() {+ let mut d = Driver::new();+ let clip = d.start_point_text();+ d.ok("ui.type", json!({"text": "abc"}));+ d.frames(2);+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 0, "anchor": 3}}));+ d.frames(2);+ d.harness.input_mut().events.extend([egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 0, after_bytes: 0 }), ime_commit("")]);+ d.frames(1);+ // Capture the receipt before graphics.list pumps the next control-channel frame.+ let ime = d.ime().expect("the accepted empty commit is observed");+ assert_eq!(layer_texts(&mut d, clip), vec![String::new()], "the selected text is replaced by the empty commit");+ assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod);+ assert_eq!(ime_payload(&ime).text, "");+}++/// Escape in the same raw batch as a commit cancels the edit; the later commit must not be typed.+#[test]+fn escape_before_a_commit_in_the_same_batch_cancels_it() {+ let mut d = Driver::new();+ let clip = d.start_point_text();+ d.ok("ui.type", json!({"text": "a"}));+ d.frames(2);+ d.harness.input_mut().events.extend([key_press(egui::Key::Escape), ime_commit("x")]);+ d.frames(2);+ assert_eq!(layer_texts(&mut d, clip), vec!["a".to_string()]);+ assert!(d.harness.state().ui.gfx_edit.is_none(), "Escape ended the edit");+ assert!(d.ime().is_none(), "the closed editor publishes no descriptor");+}++/// A pointer press later in the batch is handled after `text_edit`; a commit after that press+/// belongs to the new target and must not be inserted into the old one.+#[test]+fn pointer_press_before_a_commit_does_not_edit_the_old_layer() {+ let mut d = Driver::new();+ let clip = new_text_layer(&mut d, None, "alpha", 500.0);+ new_text_layer(&mut d, Some(clip), "beta", 900.0);+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 5, "anchor": 5}}));+ d.frames(3);+ let rect = d.rect(&format!("program.layer.{clip}.1"));+ d.harness.input_mut().events.extend([+ egui::Event::PointerButton {+ pos: egui::pos2((rect[0] + rect[2] / 2.0) as f32, (rect[1] + rect[3] / 2.0) as f32),+ button: egui::PointerButton::Primary,+ pressed: true,+ modifiers: egui::Modifiers::NONE,+ },+ ime_commit("x"),+ ]);+ d.frames(2);+ assert_eq!(layer_texts(&mut d, clip), vec!["alpha".to_string(), "beta".to_string()]);+}++/// Moving within the same layer keeps its owner, but a known composition belongs to the old+/// caret. Real press/release input moves it; the late replacement arrives in a separate batch.+#[test]+fn ime_pointer_caret_move_rejects_next_batch_old_composition() {+ for terminal_pending in [false, true] {+ for bytes in [false, true] {+ let mut d = Driver::new();+ let clip = new_text_layer(&mut d, None, "alpha", 500.0);+ d.ok("ui.set", json!({"tool": "Type", "gfxEdit": {"clip": clip, "layer": 0, "caret": 5, "anchor": 5}}));+ d.frames(3);+ let rect = d.rect(&format!("program.layer.{clip}.0"));+ let pos = egui::pos2((rect[0] + 1.0) as f32, (rect[1] + rect[3] / 2.0) as f32);+ d.harness.input_mut().events.push(ime_preedit("に"));+ d.frames(1);+ if terminal_pending {+ d.harness.input_mut().events.push(ime_preedit(""));+ d.frames(1);+ }+ let before = d.ime().expect("a live graphics owner");+ d.harness.input_mut().events.extend([+ egui::Event::PointerMoved(pos),+ egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE },+ ]);+ d.frames(1);+ // A focus loss already disables the platform context; otherwise record its+ // one-shot interruption even when the release frame no longer repeats it.+ let press_interrupted = d.ime().is_none_or(|ime| ime.should_interrupt_composition);+ d.harness.input_mut().events.push(egui::Event::PointerButton {+ pos,+ button: egui::PointerButton::Primary,+ pressed: false,+ modifiers: egui::Modifiers::NONE,+ });+ d.frames(1);+ let edit = d.harness.state().ui.gfx_edit.as_ref().expect("same-layer edit remains active");+ let caret = edit.caret;+ assert!(caret < 5 && edit.anchor == caret, "the real click must actually move the caret");+ let moved = d.ime().expect("same owner after pointer movement");+ assert_eq!(moved.owner, before.owner, "moving the caret does not replace the layer owner");+ assert!(press_interrupted || moved.should_interrupt_composition, "the platform cancels the known old composition");+ let undo = d.harness.state().session.history.undo.len();+ let delete = if bytes {+ egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 0, after_bytes: 1 })+ } else {+ egui::Event::Ime(egui::ImeEvent::DeleteSurrounding { before_chars: 0, after_chars: 1 })+ };+ d.harness.input_mut().events.extend([delete, ime_commit("stale")]);+ d.frames(1);+ assert_eq!(layer_texts(&mut d, clip), vec!["alpha".to_string()], "old composition cannot edit the clicked caret");+ assert_eq!(d.harness.state().session.history.undo.len(), undo, "rejection creates no Undo transaction");- // A fresh composition after the rejected terminal commit still applies to that caret.- d.harness.input_mut().events.extend([ime_preedit("fresh"), ime_commit("X")]);++ // Rejected terminals do not release the guard. The actual reset fence does.++ let fence = d.reset_completed();++ d.harness.input_mut().events.extend([fence, ime_preedit("fresh"), ime_commit("X")]);+ d.frames(1);+ assert_eq!(layer_texts(&mut d, clip), vec![format!("{}X{}", &"alpha"[..caret], &"alpha"[caret..])]);+ }+ }+}++/// Control and keyboard caret moves are application-origin too, without changing stable owner+/// identity. A direct commit remains valid when no old composition was interrupted.+#[test]+fn ime_same_owner_selection_move_rejects_only_a_known_composition() {+ for control_move in [false, true] {+ for composing in [false, true] {+ let mut d = Driver::new();+ let clip = new_text_layer(&mut d, None, "alpha", 500.0);+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 5, "anchor": 5}}));+ d.frames(3);+ let before = d.ime().expect("initial owner");+ if composing {+ d.harness.input_mut().events.push(ime_preedit("に"));+ d.frames(1);+ }+ if control_move {+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 0, "anchor": 0}}));+ } else {+ d.harness.input_mut().events.push(key_press(egui::Key::Home));+ d.frames(1);+ }+ assert_eq!(d.harness.state().ui.gfx_edit.as_ref().map(|e| (e.caret, e.anchor)), Some((0, 0)));+ let moved = d.ime().expect("same owner after caret movement");+ assert_eq!((moved.owner, moved.context_generation), (before.owner, before.context_generation));+ assert_eq!(moved.should_interrupt_composition, composing);+ let undo = d.harness.state().session.history.undo.len();+ d.harness.input_mut().events.push(ime_commit("X"));+ d.frames(1);+ assert_eq!(layer_texts(&mut d, clip), vec![if composing { "alpha" } else { "Xalpha" }.to_string()]);+ if composing {+ assert_eq!(d.harness.state().session.history.undo.len(), undo);+ }+ }+ }+}++/// A focused custom text widget consumes raw Ctrl/Cmd+A itself, rather than the menu helper.+/// Its new selection must not receive the terminal event of an older composition next batch.+#[test]+fn ime_raw_select_all_rejects_old_terminal_input_and_preserves_direct_and_fresh_commits() {+ for phase in ["none", "active", "terminal_pending"] {+ for bytes in [false, true] {+ let mut d = Driver::new();+ let clip = new_text_layer(&mut d, None, "alpha", 500.0);+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 5, "anchor": 5}}));+ d.frames(3);+ if phase != "none" {+ d.harness.input_mut().events.push(ime_preedit("に"));+ d.frames(1);+ if phase == "terminal_pending" {+ d.harness.input_mut().events.push(ime_preedit(""));+ d.frames(1);+ }+ }+ let before = d.ime().expect("the custom graphics editor is focused");+ assert_eq!(d.harness.ctx.memory(|m| m.focused()), Some(egui::Id::unique("gfx-text-edit")));+ assert!(d.harness.ctx.egui_wants_keyboard_input(), "raw Select All must reach the focused-widget path");+ let command = egui::Modifiers { ctrl: !cfg!(target_os = "macos"), mac_cmd: cfg!(target_os = "macos"), command: true, ..egui::Modifiers::NONE };+ d.harness.input_mut().events.extend([+ egui::Event::ModifiersChanged(command),+ egui::Event::Key { key: egui::Key::A, physical_key: Some(egui::Key::A), pressed: true, repeat: false, modifiers: command },+ ]);+ d.frames(1);+ assert_eq!(d.harness.state().ui.gfx_edit.as_ref().map(|e| (e.anchor, e.caret)), Some((0, 5)), "the raw key really selects all text");+ let selected = d.ime().expect("the same custom owner reports its selection");+ assert_eq!((selected.owner, selected.context_generation), (before.owner, before.context_generation));+ assert_eq!(selected.should_interrupt_composition, phase != "none", "only the known old composition is interrupted");+ let undo = d.harness.state().session.history.undo.len();+ let deletion = if bytes {+ egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 1, after_bytes: 0 })+ } else {+ egui::Event::Ime(egui::ImeEvent::DeleteSurrounding { before_chars: 1, after_chars: 0 })+ };+ // Surrounding deletion excludes the selected range; the terminal commit would replace+ // the whole selection if the old composition were not rejected. Release is in this+ // later batch too, so no control/menu invocation can stand in for the actual key.+ d.harness.input_mut().events.extend([+ egui::Event::Key { key: egui::Key::A, physical_key: Some(egui::Key::A), pressed: false, repeat: false, modifiers: command },+ egui::Event::ModifiersChanged(egui::Modifiers::NONE),+ deletion,+ ime_commit("X"),+ ]);+ d.frames(1);+ if phase == "none" {+ assert_eq!(layer_texts(&mut d, clip), vec!["X".to_string()], "without old preedit a direct commit replaces the selection");+ assert_eq!(d.harness.state().session.history.undo.len(), undo + 1);+ } else {+ assert_eq!(layer_texts(&mut d, clip), vec!["alpha".to_string()], "old terminal input cannot replace the new selection");+ assert_eq!(d.harness.state().session.history.undo.len(), undo, "rejected input creates no Undo transaction");+ assert!(!d.ime().expect("the unchanged selected editor remains focused").should_interrupt_composition, "the interruption is one-shot");- d.harness.input_mut().events.extend([ime_preedit("fresh"), ime_commit("Y")]);++ let fence = d.reset_completed();++ d.harness.input_mut().events.extend([fence, ime_preedit("fresh"), ime_commit("Y")]);+ d.frames(1);+ assert_eq!(layer_texts(&mut d, clip), vec!["Y".to_string()], "a fresh composition replaces the selection normally");+ assert_eq!(d.harness.state().session.history.undo.len(), undo + 1);+ }+ }+ }+}++/// A surrounding replacement at the original composing caret is still accepted and classified+/// as the input method's own change; the interruption guard is not a blanket commit filter.+#[test]+fn ime_uninterrupted_same_owner_replacement_still_applies() {+ let mut d = Driver::new();+ let clip = new_text_layer(&mut d, None, "alpha", 500.0);+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 5, "anchor": 5}}));+ d.frames(3);+ d.harness.input_mut().events.push(ime_preedit("に"));+ d.frames(1);+ d.harness.input_mut().events.extend([egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 1, after_bytes: 0 }), ime_commit("X")]);+ d.frames(1);+ let ime = d.ime().expect("accepted replacement observation");+ assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod);+ assert!(!ime.should_interrupt_composition);+ assert_eq!(layer_texts(&mut d, clip), vec!["alphX".to_string()]);+}+++/// Adapter acceptance with real Context output IDs; these injected controls are not an OS test.++#[test]++fn ime_reset_fence_admits_the_first_fresh_composition_without_an_old_terminal() {++ for terminal_pending in [false, true] {++ for split in [false, true] {++ let mut d = Driver::new();++ let clip = new_text_layer(&mut d, None, "alpha", 500.0);++ new_text_layer(&mut d, Some(clip), "beta", 900.0);++ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 5, "anchor": 5}}));++ d.frames(2);++ d.harness.input_mut().events.push(ime_preedit("に"));++ d.frames(1);++ if terminal_pending {++ d.harness.input_mut().events.push(ime_preedit(""));++ d.frames(1);++ }++ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 1, "caret": 4, "anchor": 4}}));++ d.frames(2);++ let fence = d.reset_completed();++ let requests = d.reset_requests.len();++ let undo = d.harness.state().session.history.undo.len();++ // A nonterminal stale update/deletion and arbitrary idle time cannot release it.++ d.harness++ .input_mut()++ .events++ .extend([ime_preedit("old"), egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 1, after_bytes: 0 })]);++ d.frames(5);++ assert_eq!(d.reset_requests.len(), requests, "unchanged waiting passes must not issue new requests");++ assert_eq!(layer_texts(&mut d, clip), vec!["alpha".to_owned(), "beta".to_owned()]);++ assert_eq!(d.harness.state().session.history.undo.len(), undo);++ d.harness.input_mut().events.push(fence);++ if split {++ d.frames(1); // F alone, with no fabricated old commit before it.++ }++ d.harness.input_mut().events.extend([ime_preedit("が"), ime_commit("が")]);++ d.frames(1);++ assert_eq!(layer_texts(&mut d, clip), vec!["alpha".to_owned(), "betaが".to_owned()], "terminal_pending={terminal_pending}, split={split}");++ assert_eq!(d.harness.state().session.history.undo.len(), undo + 1);++ d.exec("edit.undo", json!({}));++ assert_eq!(layer_texts(&mut d, clip), vec!["alpha".to_owned(), "beta".to_owned()]);++ }++ }++}++++#[test]++fn ime_reset_local_caret_changes_supersede_a_completed_fence_before_the_next_event() {++ for two_moves in [false, true] {++ let mut d = Driver::new();++ let clip = new_text_layer(&mut d, None, "alpha", 500.0);++ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 5, "anchor": 5}}));++ d.frames(2);++ d.harness.input_mut().events.push(ime_preedit("に"));++ d.frames(1);++ d.harness.input_mut().events.push(key_press(egui::Key::Home));++ d.frames(1);++ let first = d.reset_completed();++ let first_id = *d.reset_requests.last().unwrap();++ let undo = d.harness.state().session.history.undo.len();++ let mut events = vec![first.clone(), key_press(egui::Key::End)];++ if two_moves {++ events.push(key_press(egui::Key::Home));++ }++ events.extend([first, egui::Event::Ime(egui::ImeEvent::DeleteSurrounding { before_chars: 1, after_chars: 1 }), ime_commit("stale")]);++ d.harness.input_mut().events.extend(events);++ d.frames(1);++ let final_id = *d.reset_requests.last().unwrap();++ assert_ne!(first_id, final_id, "the locally staged caret superseded the already completed request");++ let caret = if two_moves { 0 } else { 5 };++ assert_eq!(d.harness.state().ui.gfx_edit.as_ref().map(|e| (e.caret, e.anchor)), Some((caret, caret)));++ assert_eq!(layer_texts(&mut d, clip), vec!["alpha".to_owned()]);++ assert_eq!(d.harness.state().session.history.undo.len(), undo);++ let foreign = egui::Context::default().request_ime_reset(egui::ViewportId::from_hash_of("foreign-film-window")).unwrap();++ d.harness.input_mut().events.extend([++ egui::Event::ImeResetCompleted { request_id: first_id },++ egui::Event::ImeResetCompleted { request_id: foreign },++ ime_commit("still stale"),++ egui::Event::ImeResetCompleted { request_id: final_id },++ ime_preedit("が"),++ egui::Event::ImeResetCompleted { request_id: final_id }, // duplicate during fresh Active++ ime_commit("が"),++ ]);++ d.frames(1);++ assert_eq!(layer_texts(&mut d, clip), vec![if two_moves { "がalpha" } else { "alphaが" }.to_owned()]);++ assert_eq!(d.harness.state().session.history.undo.len(), undo + 1);++ }++}++++#[test]++fn ime_reset_hidden_logic_or_missing_geometry_rearms_the_same_model_caret_once() {++ for hidden_logic in [false, true] {++ let mut d = Driver::new();++ let clip = new_text_layer(&mut d, None, "alpha", 500.0);++ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 5, "anchor": 5}}));++ d.frames(2);++ d.harness.input_mut().events.push(ime_preedit("に"));++ d.frames(1);++ d.harness.input_mut().events.push(key_press(egui::Key::Home));++ d.frames(1);++ let first = *d.reset_requests.last().unwrap();++ let request_count = d.reset_requests.len();++ let edit = d.harness.state().ui.gfx_edit.clone();++ d.frames(4);++ assert_eq!(d.reset_requests.len(), request_count, "logic before normal UI cannot suspend/rearm every frame");++ if hidden_logic {++ let ctx = d.harness.ctx.clone();++ for _ in 0..3 {++ let output = ctx.run_logic(&egui::RawInput::default(), |ctx| {++ d.harness.state_mut().logic_inner(ctx);++ d.harness.state_mut().finish_ime_reset_logic(ctx);++ });++ assert!(output.platform_output.ime.is_none());++ }++ } else {++ d.harness.state_mut().ui.mode = filmcraft_ui_egui::state::Mode::Import;++ d.frames(3);++ assert!(d.ime().is_none());++ d.harness.state_mut().ui.mode = filmcraft_ui_egui::state::Mode::Edit;++ }++ assert_eq!(d.harness.state().ui.gfx_edit, edit, "the model target/caret stayed the same");++ d.frames(1);++ let current = *d.reset_requests.last().unwrap();++ assert_ne!(current, first, "reactivation must publish a NEW token even for the unchanged caret");++ let after_activation = d.reset_requests.len();++ d.frames(4);++ assert_eq!(d.reset_requests.len(), after_activation);++ d.harness.input_mut().events.extend([egui::Event::ImeResetCompleted { request_id: first }, ime_commit("old")]);++ d.frames(1);++ assert_eq!(layer_texts(&mut d, clip), vec!["alpha".to_owned()]);++ d.harness.input_mut().events.push(egui::Event::ImeResetCompleted { request_id: current });++ d.frames(1);++ d.harness.input_mut().events.extend([ime_preedit("が"), ime_commit("が")]);++ d.frames(1);++ assert_eq!(layer_texts(&mut d, clip), vec!["がalpha".to_owned()]);++ }++}++++#[test]++fn ime_reset_discarded_request_then_no_descriptor_rearms_on_return() {++ use std::sync::{++ Arc, Mutex,++ atomic::{AtomicUsize, Ordering},++ };++ struct OutputWitness(Arc<Mutex<Vec<egui::ImeResetId>>>);++ impl egui::Plugin for OutputWitness {++ fn debug_name(&self) -> &'static str {++ "Film reset output witness"++ }++ fn output_hook(&mut self, _ctx: &egui::Context, output: &mut egui::FullOutput) {++ if let Some(id) = output.platform_output.ime.as_ref().and_then(|ime| ime.reset_request) {++ self.0.lock().unwrap().push(id);++ }++ }++ }++ let mut d = Driver::new();++ let clip = new_text_layer(&mut d, None, "alpha", 500.0);++ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 5, "anchor": 5}}));++ d.frames(2);++ d.harness.input_mut().events.push(ime_preedit("に"));++ d.frames(1);++ let observed = Arc::new(Mutex::new(Vec::new()));++ d.harness.ctx.add_plugin(OutputWitness(Arc::clone(&observed)));++ let phase = Arc::new(AtomicUsize::new(0));++ let begin_phase = Arc::clone(&phase);++ let stock = egui::Id::unique("film-reset-missing-custom-geometry");++ d.harness.ctx.on_begin_pass(++ "Film reset discarded second-pass absence",++ Arc::new(move |ui| {++ if begin_phase.load(Ordering::Relaxed) == 1 {++ ui.memory_mut(|memory| memory.request_focus(stock));++ begin_phase.store(2, Ordering::Relaxed);++ }++ }),++ );++ d.harness.ctx.on_end_pass(++ "Film reset discard first request output",++ Arc::new(move |ui| {++ if phase.compare_exchange(0, 1, Ordering::Relaxed, Ordering::Relaxed).is_ok() {++ ui.ctx().request_discard("exercise actual request consumption followed by final None");++ }++ }),++ );++ d.harness.input_mut().events.push(key_press(egui::Key::Home));++ d.frames(1);++ assert!(d.harness.output().platform_output.num_completed_passes >= 2);++ assert!(d.ime().is_none(), "the final discarded rerun published no custom descriptor");++ let first = *observed.lock().unwrap().last().expect("the first discarded pass carried an actual request");++ assert_eq!(d.harness.state().ui.gfx_edit.as_ref().map(|e| (e.caret, e.anchor)), Some((0, 0)));++ d.harness.ctx.memory_mut(|memory| memory.surrender_focus(stock));++ d.frames(1);++ let current = *d.reset_requests.last().expect("returning custom output rearms");++ assert_ne!(first, current);++ d.harness.input_mut().events.extend([++ egui::Event::ImeResetCompleted { request_id: first },++ ime_commit("old"),++ egui::Event::ImeResetCompleted { request_id: current },++ ime_preedit("が"),++ ime_commit("が"),++ ]);++ d.frames(1);++ assert_eq!(layer_texts(&mut d, clip), vec!["がalpha".to_owned()]);++}++++/// The ordinary multipass case: the first pass's request is discarded, but the final rerun++/// publishes the same custom editor. Core must carry R1 (not a newly allocated token or an++/// untokened interrupt), and that exact fence then admits a fresh suffix without an old terminal.++#[test]++fn ime_reset_discarded_pass_keeps_the_same_custom_request_and_admits_a_fresh_suffix() {++ use std::sync::{++ Arc, Mutex,++ atomic::{AtomicUsize, Ordering},++ };++ struct OutputWitness(Arc<Mutex<Vec<(egui::ImeResetId, bool)>>>);++ impl egui::Plugin for OutputWitness {++ fn debug_name(&self) -> &'static str {++ "Film reset carried-request witness"++ }++ fn output_hook(&mut self, _ctx: &egui::Context, output: &mut egui::FullOutput) {++ if let Some(ime) = output.platform_output.ime.as_ref()++ && let Some(id) = ime.reset_request++ {++ self.0.lock().unwrap().push((id, ime.should_interrupt_composition));++ }++ }++ }++ let mut d = Driver::new();++ let clip = new_text_layer(&mut d, None, "alpha", 500.0);++ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 5, "anchor": 5}}));++ d.frames(2);++ d.harness.input_mut().events.push(ime_preedit("に"));++ d.frames(1);++ let owner = d.ime().expect("the custom editor published its descriptor").owner;++ let observed = Arc::new(Mutex::new(Vec::new()));++ d.harness.ctx.add_plugin(OutputWitness(Arc::clone(&observed)));++ let phase = Arc::new(AtomicUsize::new(0));++ let end_phase = Arc::clone(&phase);++ d.harness.ctx.on_end_pass(++ "Film reset discard one same-custom pass",++ Arc::new(move |ui| {++ if end_phase.compare_exchange(0, 1, Ordering::Relaxed, Ordering::Relaxed).is_ok() {++ ui.ctx().request_discard("exercise request carry into a same-custom final pass");++ }++ }),++ );++ d.harness.input_mut().events.push(key_press(egui::Key::Home));++ d.frames(1);++ assert!(d.harness.output().platform_output.num_completed_passes >= 2);++ let ime = d.ime().expect("the final custom descriptor was published");++ assert_eq!(ime.owner, owner, "the final descriptor is the same custom editor");++ let id = ime.reset_request.expect("the final custom descriptor carries R1");++ assert!(ime.should_interrupt_composition);++ let seen = observed.lock().unwrap();++ // `output_hook` runs per pass, before core applies the discarded-pass carry in++ // `FullOutput::append`. Only the discarded pass publishes R1 here; the final rerun's own++ // pass output has no request, and the combined output above proves the carry.++ assert_eq!(seen.as_slice(), &[(id, true)], "exactly the discarded pass emitted R1 as a real interruption");++ drop(seen);++ // No fabricated old terminal: only the exact completion boundary and a fresh composition.++ d.harness.input_mut().events.extend([egui::Event::ImeResetCompleted { request_id: id }, ime_preedit("が"), ime_commit("が")]);++ d.frames(1);++ assert_eq!(layer_texts(&mut d, clip), vec!["がalpha".to_owned()]);++}++++/// A host picker and an in-app modal own input. Entering either must retire/suspend the guard++/// without allocating a NEW request; leaving it rearms exactly one fresh boundary.++#[test]++fn ime_reset_native_picker_and_in_app_modal_do_not_allocate_a_new_request() {++ use filmcraft_ui_egui::Dialog;++ use filmcraft_ui_egui::native_dialogs::FileDialog;++ use std::sync::{Arc, Mutex};++ let senders: Arc<Mutex<Vec<Sender<Vec<String>>>>> = Arc::new(Mutex::new(Vec::new()));++ let picker_senders = Arc::clone(&senders);++ let mut d = Driver::new_with(move |app| {++ app.hooks.run_dialog = Some(Box::new(move |_dialog| {++ let (tx, rx) = channel();++ picker_senders.lock().unwrap().push(tx);++ rx++ }));++ });++ let clip = new_text_layer(&mut d, None, "alpha", 500.0);++ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 5, "anchor": 5}}));++ d.frames(2);++ d.harness.input_mut().events.push(ime_preedit("に"));++ d.frames(1);++ d.harness.input_mut().events.push(key_press(egui::Key::Home));++ d.frames(1);++ let first = *d.reset_requests.last().expect("the interruption published a fence");++++ let opened = d.harness.state_mut().pick(FileDialog::OpenProject, |_, _| Ok(Value::Null)).unwrap();++ assert_eq!(opened["dialog"], json!("open"));++ d.frames(3);++ assert!(d.harness.state().native_dialog_open());++ let requests = d.reset_requests.len();++ assert!(d.ime().is_none_or(|ime| ime.reset_request.is_none()), "an open picker cannot publish a NEW reset");++ assert_eq!(d.reset_requests.len(), requests, "an open picker cannot allocate a NEW reset");++ d.harness.input_mut().events.extend([ime_preedit("old"), ime_commit("old")]);++ d.frames(2);++ assert_eq!(d.reset_requests.len(), requests);++ assert_eq!(layer_texts(&mut d, clip), vec!["alpha".to_owned()], "picker-owned input cannot edit the editor");++ if let Some(tx) = senders.lock().unwrap().pop() {++ tx.send(Vec::new()).unwrap();++ }++ d.frames(2);++ assert!(!d.harness.state().native_dialog_open());++ let after_picker = *d.reset_requests.last().expect("returning from the picker rearms");++ assert_ne!(after_picker, first);++ let request_count = d.reset_requests.len();++ d.frames(3);++ assert_eq!(d.reset_requests.len(), request_count, "waiting after rearm must not churn IDs");++++ d.harness.state_mut().dialog = Some(Dialog::About);++ d.frames(3);++ assert_eq!(d.reset_requests.len(), request_count, "an in-app modal cannot allocate a NEW reset");++ d.harness.state_mut().dialog = None;++ d.frames(2);++ let latest = *d.reset_requests.last().expect("leaving the in-app modal rearms");++ assert_ne!(latest, after_picker);++ d.harness.input_mut().events.extend([++ egui::Event::ImeResetCompleted { request_id: after_picker },++ ime_commit("old"),++ egui::Event::ImeResetCompleted { request_id: latest },++ ime_preedit("が"),++ ime_commit("が"),++ ]);++ d.frames(1);++ assert_eq!(layer_texts(&mut d, clip), vec!["がalpha".to_owned()]);++}++++#[test]++fn ime_reset_pointer_and_escape_suffix_controls_cannot_edit_the_abandoned_target() {++ for escape in [false, true] {++ let mut d = Driver::new();++ let clip = new_text_layer(&mut d, None, "alpha", 500.0);++ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 5, "anchor": 5}}));++ d.frames(2);++ d.harness.input_mut().events.push(ime_preedit("に"));++ d.frames(1);++ d.harness.input_mut().events.push(key_press(egui::Key::Home));++ d.frames(1);++ let old = *d.reset_requests.last().unwrap();++ let boundary = if escape {++ key_press(egui::Key::Escape)++ } else {++ egui::Event::PointerButton { pos: egui::pos2(-20.0, -20.0), button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }++ };++ let undo = d.harness.state().session.history.undo.len();++ d.harness.input_mut().events.extend([++ ime_commit("old prefix"),++ egui::Event::ImeResetCompleted { request_id: old },++ boundary,++ egui::Event::Text("wrong caret".into()),++ egui::Event::Paste("wrong paste".into()),++ egui::Event::Cut,++ egui::Event::ImeResetCompleted { request_id: old },++ ime_preedit("が"),++ ime_commit("が"),++ ]);++ d.frames(1);++ assert_eq!(layer_texts(&mut d, clip), vec!["alpha".to_owned()]);++ assert_eq!(d.harness.state().session.history.undo.len(), undo);++ if escape {++ assert!(d.harness.state().ui.gfx_edit.is_none());++ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 0, "anchor": 0}}));++ } else {++ d.harness.input_mut().events.push(egui::Event::PointerButton {++ pos: egui::pos2(-20.0, -20.0),++ button: egui::PointerButton::Primary,++ pressed: false,++ modifiers: egui::Modifiers::NONE,++ });++ }++ d.frames(2);++ let current = *d.reset_requests.last().unwrap();++ assert_ne!(old, current);++ d.harness.input_mut().events.extend([++ egui::Event::ImeResetCompleted { request_id: old },++ ime_commit("old suffix"),++ egui::Event::ImeResetCompleted { request_id: current },++ ime_preedit("が"),++ ime_commit("が"),++ ]);++ d.frames(1);++ assert_eq!(layer_texts(&mut d, clip), vec!["がalpha".to_owned()]);++ }++}++++#[test]++fn ime_reset_stock_text_edit_keeps_its_output_and_custom_return_gets_a_new_fence() {++ use std::sync::{++ Arc,++ atomic::{AtomicBool, Ordering},++ };++ struct StockField {++ enabled: Arc<AtomicBool>,++ text: String,++ id: egui::Id,++ }++ impl egui::Plugin for StockField {++ fn debug_name(&self) -> &'static str {++ "Film reset stock-field control"++ }++ fn on_begin_pass(&mut self, ui: &mut egui::Ui) {++ if self.enabled.load(Ordering::Relaxed) {++ ui.memory_mut(|memory| memory.request_focus(self.id));++ ui.add(egui::TextEdit::singleline(&mut self.text).id(self.id));++ }++ }++ }++ let mut d = Driver::new();++ let clip = new_text_layer(&mut d, None, "alpha", 500.0);++ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 5, "anchor": 5}}));++ d.frames(2);++ let owner = d.ime().unwrap().owner;++ d.harness.input_mut().events.push(ime_preedit("に"));++ d.frames(1);++ d.harness.input_mut().events.push(key_press(egui::Key::Home));++ d.frames(1);++ let first = *d.reset_requests.last().unwrap();++ let edit = d.harness.state().ui.gfx_edit.clone();++ let enabled = Arc::new(AtomicBool::new(true));++ let id = egui::Id::unique("film-reset-stock-text-field");++ d.harness.ctx.add_plugin(StockField { enabled: Arc::clone(&enabled), text: String::new(), id });++ d.harness.input_mut().events.extend([egui::Event::ImeResetCompleted { request_id: first }, egui::Event::Text("stock".into())]);++ d.frames(1);++ let stock = d.ime().expect("the actual stock TextEdit retains its descriptor");++ assert_ne!(stock.owner, owner);++ assert!(stock.reset_request.is_none(), "a previously dispatched custom request cannot cause a NEW stock request");++ assert_eq!(ime_payload(&stock).text, "stock");++ assert_eq!(d.harness.state().ui.gfx_edit, edit);++ assert_eq!(layer_texts(&mut d, clip), vec!["alpha".to_owned()]);++ enabled.store(false, Ordering::Relaxed);++ d.harness.ctx.memory_mut(|memory| memory.surrender_focus(id));++ d.frames(2);++ let current = *d.reset_requests.last().unwrap();++ assert_ne!(current, first);++ assert_eq!(d.ime().unwrap().owner, owner);++ d.harness.input_mut().events.extend([++ egui::Event::ImeResetCompleted { request_id: first },++ ime_commit("old"),++ egui::Event::ImeResetCompleted { request_id: current },++ ime_preedit("が"),++ ime_commit("が"),++ ]);++ d.frames(1);++ assert_eq!(layer_texts(&mut d, clip), vec!["がalpha".to_owned()]);++}+++/// The concrete collision the uid-less fingerprint missed: two layers with identical static+/// geometry (position, size, no name) but different text. Reordering, deleting and undoing must+/// keep typing in the layer the user started editing, not in whatever now occupies its index.+#[test]+fn identical_layers_with_different_text_keep_the_edit_on_the_started_layer() {+ let mut d = Driver::new();+ let clip = d.exec("graphics.newText", json!({"text": "one", "position": [960, 540], "size": 100}))["clip"].as_u64().unwrap();+ d.exec("graphics.newText", json!({"text": "two", "position": [960, 540], "size": 100, "clip": clip}));+ let uids: Vec<u64> = d.exec("graphics.list", json!({"clip": clip}))["layers"].as_array().unwrap().iter().map(|l| l["uid"].as_u64().unwrap()).collect();+ assert_eq!(uids.len(), 2);+ assert!(uids.iter().all(|uid| *uid != 0));+ assert_ne!(uids[0], uids[1], "identical geometry and different text get distinct identities");+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 3, "anchor": 3}}));+ d.frames(3);+ assert_eq!(d.harness.state().ui.gfx_edit.as_ref().map(|e| (e.layer, e.uid)), Some((0, uids[0])));++ // Move the edited layer to the front. The other layer now sits at index 0 (same fingerprint).+ d.exec("graphics.arrangeLayer", json!({"clip": clip, "layer": 0, "to": "front"}));+ d.frames(2);+ assert_eq!(d.harness.state().ui.gfx_edit.as_ref().map(|e| (e.layer, e.uid)), Some((1, uids[0])));+ d.ok("ui.type", json!({"text": "X"}));+ d.frames(2);+ assert_eq!(layer_texts(&mut d, clip), vec!["two".to_string(), "oneX".to_string()], "typing followed the uid, not index 0");++ // Delete the layer below it; the edit stays on "oneX" and keeps typing there.+ d.exec("graphics.deleteLayer", json!({"clip": clip, "layer": 0}));+ d.frames(2);+ assert_eq!(d.harness.state().ui.gfx_edit.as_ref().map(|e| (e.layer, e.uid)), Some((0, uids[0])));+ d.ok("ui.type", json!({"text": "Y"}));+ d.frames(2);+ assert_eq!(layer_texts(&mut d, clip), vec!["oneXY".to_string()]);++ // Undo the typing and then the deletion: the same uid is edited at its restored index.+ d.exec("edit.undo", json!({}));+ d.frames(2);+ d.exec("edit.undo", json!({}));+ d.frames(2);+ assert_eq!(d.harness.state().ui.gfx_edit.as_ref().map(|e| (e.layer, e.uid)), Some((1, uids[0])));+ d.ok("ui.type", json!({"text": "Z"}));+ d.frames(2);+ assert_eq!(layer_texts(&mut d, clip), vec!["two".to_string(), "oneXZ".to_string()]);+}++/// Every graphic layer created by `graphics.newText` has a stable uid. The edit target follows+/// that uid through a real reorder, a real deletion below it, and undo/redo.+#[test]+fn edit_target_follows_reorder_delete_and_undo() {+ let mut d = Driver::new();+ let clip = new_text_layer(&mut d, None, "one", 400.0);+ new_text_layer(&mut d, Some(clip), "two", 800.0);+ new_text_layer(&mut d, Some(clip), "three", 1200.0);+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 3, "anchor": 3}}));+ d.frames(3);+ let uid = d.harness.state().ui.gfx_edit.as_ref().map(|e| e.uid).unwrap_or(0);+ assert_ne!(uid, 0, "the created layer has a stable uid");+ assert_eq!(d.harness.state().ui.gfx_edit.as_ref().map(|e| e.layer), Some(0));++ // Reorder layer 0 (the edited "one") to the front, then type: the text must follow it.+ d.exec("graphics.arrangeLayer", json!({"clip": clip, "layer": 0, "to": "front"}));+ d.frames(2);+ assert_eq!(d.harness.state().ui.gfx_edit.as_ref().map(|e| e.layer), Some(2), "the edit follows the reordered layer");+ d.ok("ui.type", json!({"text": "A"}));+ d.frames(2);+ assert_eq!(layer_texts(&mut d, clip), vec!["two".to_string(), "three".to_string(), "oneA".to_string()]);++ // Undo the typing and then the arrange: the edit follows the same layer back to index 0.+ d.exec("edit.undo", json!({}));+ d.frames(2);+ d.exec("edit.undo", json!({}));+ d.frames(2);+ assert_eq!(d.harness.state().ui.gfx_edit.as_ref().map(|e| e.layer), Some(0));+ d.ok("ui.type", json!({"text": "B"}));+ d.frames(2);+ assert_eq!(layer_texts(&mut d, clip), vec!["oneB".to_string(), "two".to_string(), "three".to_string()]);++ // Edit "two" (index 1), delete the layer below it, and keep typing into "two".+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 1, "caret": 3, "anchor": 3}}));+ d.frames(2);+ d.exec("graphics.deleteLayer", json!({"clip": clip, "layer": 0}));+ d.frames(2);+ assert_eq!(d.harness.state().ui.gfx_edit.as_ref().map(|e| e.layer), Some(0));+ d.ok("ui.type", json!({"text": "D"}));+ d.frames(2);+ assert_eq!(layer_texts(&mut d, clip), vec!["twoD".to_string(), "three".to_string()]);+}++/// Replacing the project clears the edit and the IME owner even though `file.newProject` emits+/// only `ProjectChanged`, and a project with no sequence has no editor to observe.+#[test]+fn new_project_without_a_sequence_clears_the_ime_edit() {+ let mut d = Driver::new();+ d.start_point_text();+ d.ok("ui.type", json!({"text": "x"}));+ d.frames(2);+ assert!(d.ime().is_some(), "the text editor owns the IME before the replacement");+ d.exec("file.newProject", json!({"name": "Fresh"}));+ d.frames(3);+ assert!(d.harness.state().ui.gfx_edit.is_none(), "the replaced document has no edit target");+ assert!(d.ime().is_none(), "no sequence means no visible editor and no descriptor");+}++/// `engine.execute`/`ui.menu.invoke` run after the UI pass. A same-pass text or caret change+/// leaves the drawn cursor rectangle stale, so that pass publishes Unavailable; the next pass+/// draws and observes the new text at the new caret geometry.+#[test]+fn ime_observation_follows_control_text_mutations_in_the_same_pass() {+ let mut d = Driver::new();+ let clip = d.start_point_text();+ d.ok("ui.type", json!({"text": "one"}));+ d.frames(3);+ let before = d.ime().expect("the editor is observed");+ assert_eq!(ime_payload(&before).text, "one");+ // `ui.menu.invoke` is one of the requests drained after the frame, unlike `engine.execute`.+ d.ok("ui.menu.invoke", json!({"id": "graphics.setText", "params": {"clip": clip, "layer": 0, "text": "a much longer line"}}));+ assert!(d.ime().is_none(), "the old cursor rectangle must not be published with the changed text");+ d.frames(1);+ let after = d.ime().expect("the next pass observes the new layout");+ assert_eq!(ime_payload(&after).text, "a much longer line", "the final observation runs after the control request");+ assert_ne!(after.cursor_rect, before.cursor_rect, "the candidate window moved with the longer line");+ d.frames(1);+ let stable = d.ime().expect("a settled pass observes again");+ assert_eq!(stable.cursor_rect, after.cursor_rect, "the published geometry matches the next pass");+}++/// A hostile `ui.set.gfxEdit` offset is reported as the explicit `Unavailable` snapshot before+/// the next pass clamps it, rather than being silently floored before observation.+#[test]+fn invalid_gfx_edit_offsets_are_unavailable_before_clamping() {+ let mut d = Driver::new();+ let clip = d.start_point_text();+ d.ok("ui.type", json!({"text": "é😀"}));+ d.frames(3);+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 1, "anchor": 2}}));+ let ime = d.ime().expect("the editor is still observed");+ assert!(ime.surrounding_text.available().is_none(), "an offset inside a code point is Unavailable");+ d.frames(1);+ let clamped = d.ime().expect("the clamped editor is observed");+ assert!(clamped.surrounding_text.available().is_some(), "the editor clamps on its next pass");+ assert_eq!(layer_texts(&mut d, clip), vec!["é😀".to_string()]);+}+/// #2430: a click (no drag) in the text being edited on the monitor puts the caret there; before,/// only a press that moved a little did, and typing went on at the end.#[test]diff --cc crates/ui-egui/tests/it/mixer_ui.rsindex da3127d79,3166d6ca9..c42bbccf2--- a/crates/ui-egui/tests/it/mixer_ui.rs+++ b/crates/ui-egui/tests/it/mixer_ui.rs@@@ -478,6 -478,13 +478,13 @@@ fn paused_meters_repaint_without_input_d.ok("ui.playback", json!({"action": "stop"}));assert!(!d.harness.state().playback.playing);d.snapshot(&format!("meters-{workspace}-paused-start"), None);+ // A slow release after Stop reads as audio still playing: silent within 0.4 s.+ for _ in 0..4 {+ d.harness.step();+ }+ let (_, meters): (u64, std::collections::HashMap<u64, Vec<[f32; 2]>>) =- d.harness.ctx.data(|data| data.get_temp(egui::Id::new("mixer-meters"))).unwrap();++ d.harness.ctx.data(|data| data.get_temp(egui::Id::unique("mixer-meters"))).unwrap();+ assert!(meters.values().flatten().all(|meter| *meter == [-90.0; 2]), "{workspace}: still falling 0.4 s after Stop: {meters:?}");// Harness::run follows immediate repaint requests, adding no mouse or keyboard input.let steps = d.harness.run();// Inspect both values that drive the bars: a silent level alone must not strand itsdiff --cc docs/contributing.mdindex b1e1222c7,b1e1222c7..3ad802bff--- a/docs/contributing.md+++ b/docs/contributing.md@@@ -8,7 -8,7 +8,7 @@@ of the crate you will change| | All platforms ||---|---|--| Rust | stable ≥ 1.95 (edition 2024; egui 0.36 requires it), via [rustup](https://rustup.rs) |++| Rust | stable ≥ 1.95 (edition 2024; egui 0.37 requires it), via [rustup](https://rustup.rs) || wasm target | `rustup target add wasm32-unknown-unknown` (for `cargo xtask wasm`) || Components | `rustup component add rustfmt clippy` || ffmpeg + ffprobe (optional) | test oracle and fixture generator only; tests skip without it |diff --cc docs/egui-037-migration-plan.mdindex 7e2b2f923,000000000..63ef9069emode 100644,000000..100644--- a/docs/egui-037-migration-plan.md+++ b/docs/egui-037-migration-plan.md@@@ -1,1563 -1,0 +1,1572 @@@+# FilmCraft — egui 0.37 migration plan+++Current landing status, 2026-10-25: the migration integrates main `bfc23840b603e69c782302c6ed04d4a9f6ec26a8` and uses egui `6d518fc799681571963842f95b55a6b68431b15a`, winit `a517b3846ee8457d84ee4975110bfda6797c44dc` and craft-ui `25da1314d443171b4adeaad2cd9454b273f35c6f`. Cargo.lock SHA-256 is `8ddb2d92ec359928491b47c084501bbecaa9ff708d678156dab99d1cbd24642e`; the independent media/document-path pins remain 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-filmcraft-oracle8-full-ci-20261025-0570` passed formatting, strict lint, workspace tests and doctests, layers, assets and the 49-crate WASM check, including the web app. It recorded 3,733 passing test executions, zero failures and 45 ignored across 164 summaries. 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.++++External oracle checks ran with `FILMCRAFT_REQUIRE_ORACLES=1`, checksum-pinned FFmpeg 8.1.3 (`n8.1.3-24-g92611900bb`) and fresh generated fixtures. An earlier run using FFmpeg 7.1.5 failed ten codec/oracle/workflow tests. All ten passed unchanged with the new tools in managed job0567, before the full suite passed in0570; no decoder, tolerance or fixture-source changes were made to clear them. The newer tool provides the required APV, half-float, SVT-AV1 and Kvazaar capabilities. It remains a private external oracle, not an app dependency or distributed asset.++++The original planning and earlier qualification record follows. Its pins, hashes, paths and passing counts are historical.+++++Status: local implementation revision after the independent adversarial reviews of+`plan-reviews/filmcraft-v1.md` and `filmcraft-v2.md`. The owned checkout now contains the+0.37 migration work; commits, pushes, publications, and final immutable pins/lock remain+gated. This document is the implementation contract, not publication acceptance. Every+statement about runtime behavior below is source inspection at the recorded revisions unless+it is explicitly labelled a proposed test or a proposed command.++This revision resolves the review findings inline, including the dependency DAG. Section 17+is a disposition index only; it does not override any section.++## 1. Scope and exact baseline++| Item | Value |+|---|---|+| Repository | `storytold/filmcraft` |+| Assigned checkout | `/home/codex/work/CraftApps/egui037-migration-20261022/filmcraft-implementation` |+| Current branch HEAD | `fa550ce2d07bdfee6b1d7b6835e8abc8c6913d00` (2026-10-24; migration work is uncommitted on this base) |+| Planning baseline (historical) | `abf44fda9015f4b7a96dc338f6042499bf8e9d9f` (2026-10-22, "Reject non-hex characters in colour hex parsing (#2600)") |+| `Cargo.toml` SHA-256 (current checkout) | `b41244b83b0aff71ab6e122826d20a49a2d59c35e87da57c8dfd228a962ec2cf` |+| `Cargo.lock` SHA-256 (current checkout) | `67528fa8486c963dadbaf04e487ab5a8af59ac8f98dac97e1d51f40b953b5bb5` |+| Workspace | resolver 3, edition 2024, Rust 1.95, 50 crates plus 3 apps and `xtask` |+| Current UI stack | `egui`, `eframe`, `egui-wgpu`, `egui-winit`, `egui_glow`, `egui_kittest`, `emath`, `epaint`, `epaint_default_fonts` at `0.37.0`; `winit 0.30.13`; `wgpu 30.0.1`; `accesskit 0.24.1`; `arboard 3.6.1` |+| Shared UI dependency | Current manifest: `craft-ui` at `5c874d51eeb3de70e735c8ce87a59a7dedd47675`, `craft-media` at `f0ad6c1e1d297908915f4be315b0fcfc9be7b5d4`, `craft-docpath` at `82a24b006eefa036b43c09a67fb9a3fbd17ffe63`. Reconciled PR #199 base: `3832c47ef68a0e6214f2c1e85f3526b6adcb686e`; final immutable pins and lock remain G-PINS/G-CL2F/G-CRAFT-LIBS gates. |+| Target release | `egui 0.37.0` = upstream commit `841a328ba2dd8f6996beb7189ebb7fc00e668a2a` |+| Research candidate | `aiongg/egui` `craft/0.37` = `a4f9a17f64a6bae61350fb85804c9df0d9865916`; `aiongg/winit` `craft/0.30.13-lang` = `8b35388bd719e8cc86a95971ba0bc026c9a8f058` |+| Production fork pins | **Unknown and deliberately not invented.** They become valid only after reviewed, published immutable `storytold/egui` and `storytold/winit` commits exist. See §3.2 and §15 gate G-PINS. |+| Evidence directory | `/home/codex/work/ssd2/task-evidence/egui037-migration-20261022` |+| Historical diagnostics | `/home/codex/work/ssd2/task-evidence/egui037-audit-20261022/{fork,stock}/filmcraft.errors` — older checkout (FilmCraft manifest 0.10.0), clues only, never acceptance |++The existing `App::logic` / `App::ui` split and root-`Ui` architecture are **not** introduced+by 0.37 and must not be rewritten as if they were. This plan changes where frame side effects+run and how input is handled across layout passes; it does not change the command, undo,+project or persistence model. Do not add a FilmCraft-specific `egui` compatibility crate. Use+the new APIs directly, and add a helper to `craft-ui` only for semantics that at least two+consumers need with the same contract.++This repository has:++- one root workspace (`Cargo.toml`) with `members = ["crates/*", "apps/*", "xtask"]`;+- one workspace lockfile (`Cargo.lock`, 708 packages);+- no `[patch]` section, no `vendor/` directory, no source replacement and no local crate copy;+ `.cargo/config.toml` contains only the `xtask` alias;+- exactly four manifests that mention `egui`: the workspace, `crates/ui-egui/Cargo.toml`,+ `apps/filmcraft/Cargo.toml` and `apps/filmcraft-web/Cargo.toml`;+- a native entry point (`apps/filmcraft/src/main.rs`), a wasm entry point+ (`apps/filmcraft-web/src/lib.rs`), a CLI app and a web app;+- no `egui_plot`, `egui_extras` or `egui_dock`; all other crate manifests scanned for `egui`,+ `eframe`, `winit`, `rfd` and `egui_*` contain none;+- `crates/ui-egui/Cargo.toml` has the only relevant target cfgs: `rustix` for Unix+ thread/process clocks and `cpu-time` for Windows;+- `craft-libs` vendors `krilla`/`hayro` for PDF work, unrelated to the windowing stack; this+ plan does not touch them.++### 1.1 Reverse dependency: EffectCraft++EffectCraft (`9581b53c3f8945683252af0eb5fac79e0e43aed4` in the owned checkout) pins fifteen+`filmcraft-*` crates to `2c5ba7a72619935f0481f99d59409e0d1844b234` in `effectcraft/Cargo.toml`.+That revision is not an ancestor of FilmCraft baseline `abf44fda`; it is reachable from+`origin/effectcraft/webm-alpha`. None of those crates (`media`, `codecs`, `frame`, `color`,+`time`, `project`, `interchange`, `geom`, the encoders/decoders and the muxer) contains+`egui`, and EffectCraft does not depend on `filmcraft-ui-egui`.++Decision: EffectCraft needs no change for this migration. Retain its separate branch pin.+Re-audit only if (a) the pin moves to FilmCraft main or another revision that changes a+shared public type, or (b) EffectCraft starts consuming `filmcraft-ui-egui` (directly or+through another crate). The re-audit must check the actual Cargo identities, not just a+version string. This is the required explicit cross-repository check; it is not a silent+deferral of FilmCraft's own compatibility work.++## 2. Current architecture and lifecycle++### 2.1 Entry points++| Target | Entry point / symbol | Notes |+|---|---|---|+| Native desktop | `apps/filmcraft/src/main.rs:80` `main`, `:139` `eframe::run_native`, `:168` `native_options`, `:190` `app_creator` | wgpu only; features `default_fonts`, `wgpu`, `accesskit`, `wayland`, `x11`; no `system_fonts`, no `links` |+| macOS native | `apps/filmcraft/Cargo.toml` target deps `muda`, `objc2-*`, `winit`; `main.rs:430` `agent_event_loop`; `native_menu.rs` | custom titlebar and menu; `--control` must not activate the app |+| Linux native | `apps/filmcraft/Cargo.toml` `zbus`; `main.rs` `run_dialog_off_thread` | X11 and Wayland at runtime; XDG portal dialogs |+| Windows native | `apps/filmcraft/Cargo.toml` `winresource`; `graphics.rs` DX12/default/software ladder | DX12 FXC shader compilation is relevant to startup measurement |+| Browser | `apps/filmcraft-web/src/lib.rs:125` `start`, `:156` `WebRunner::start`, `:92` `impl eframe::App for WebApp` | wasm32 only; WebGPU with WebGL2 fallback; WebCodecs; OPFS |+| Headless UI | `crates/ui-egui/tests/scripted.rs` and the other `tests/*_ui.rs` `Harness::builder().build_eframe(...)` | `egui_kittest` drives the same `FilmcraftApp` |++### 2.2 The app object++`FilmcraftApp` is in `crates/ui-egui/src/lib.rs`. The UI code is already split:++- `crates/ui-egui/src/lib.rs:2133` `impl eframe::App for FilmcraftApp::logic`;+- `crates/ui-egui/src/lib.rs:2193` `impl eframe::App for FilmcraftApp::ui`;+- `crates/ui-egui/src/lib.rs:1807` private `FilmcraftApp::frame(&mut self, ui: &mut egui::Ui)`,+ called from `App::ui` and wrapped in `catch_unwind`;+- `cargo xtask` only builds/tests; FilmCraft does not implement a second `update` path;+- the main workspace is custom-drawn: `App::ui` receives the root `Ui`, then calls+ `header::show`, `dock_area`, `panels::*` and dialog functions. It does not use+ `egui::TopBottomPanel`, `SidePanel` or `CentralPanel`;+- floating panels are `egui::Area`s managed by `crates/ui-egui/src/dock.rs` and `dock_ui.rs`,+ not native viewports. There is no `show_viewport_deferred` and no child-window dock;+- dialogs use `egui::Window::new(...).show(ctx, ...)`, valid only inside a pass.++### 2.3 Where side effects live (exhaustive inventory)++These are the behaviours that must survive hidden logic-only calls, forced hidden paint and+multi-pass layout without duplication. All clock-driven entries use a monotonic host clock+after migration; no hidden work may read `ctx.input(|i| i.time)`.++| Effect | Current location | Required migration decision |+|---|---|---|+| Theme/font installation and language fallback | `lib.rs:2133` `logic` (`theme::install`, `i18n::install_japanese_font`, `chinese_font_available`, `korean_font_available`) | Keep in logic; once-per-process state, not per pass; never call `Context::root_ui` |+| Control channel, deferred requests, input waiters | `lib.rs:1672` `drain_control`, retry deadlines `:1682`, `now - last_ui_time > 0.25` raise heuristic `:1679` | Logic; consumed `try_recv` queue; monotonic `now`; `ui.*` requests that need composition send `ViewportCommand::RequestPaintWhileHidden` (see §4.5) |+| Screenshot settle / issue / collect | `lib.rs:1702` settle timestamp, `:1714` `issue_screenshots`, `:1744` `collect_screenshots`; `queued_screenshots` `*frames += 1` (`lib.rs:1717-1720`), `monitor_inexact` `mem::take` (`:2182`), `timeline_still` increment (`:2163`) | Logic; monotonic deadline; `ScreenshotCallback` plus the CL-2 completion slot. Settle counters advance once per rendered frame/pass identity, not per logic call; a queued-but-not-yet-issued hidden request repeats `RequestPaintWhileHidden` until issued, after which the screenshot command itself forces the paint. |+| FPS, frame time, close interception | `lib.rs:2133` `logic` (`ctx.input(i.time)`, `visible()`, `close_requested()`) | Logic; monotonic host clock; viewport metadata is fresh in `run_logic`, input time is not |+| Frame worker pump | `lib.rs:2193` `ui` calls `self.frames.pump(...)` | Logic/background tick; do not rely on paint |+| Persistence polling | `lib.rs:1825` `frame` calls `session.poll_persistence()` | Logic; once per state transition, not per pass |+| Engine event drain | `lib.rs:1826` `session.drain_events()` | Logic; drain the one-shot queue; an event is consumed exactly once regardless of pass count |+| Toast timestamp | `lib.rs:1840` `Event::Toast` stamps `ctx.input(i.time)` while `drain_events` moves to logic | Stamp with the monotonic host clock; repeated logic calls must not re-time or duplicate the toast |+| Media refresh and pool sync | `lib.rs:1822` `sync_pool`, `:1825` `tick_media_refresh` (`:1777`) | Logic; monotonic deadlines and `request_repaint_after`; consumed scan state |+| Preferences application | `lib.rs:717` `apply_prefs`, called from `frame` | Logic or known UI pass 0; idempotent; font/visual side effects once |+| Drop import | `lib.rs:1473` `handle_drops` | `App::ui` pass 0 only; uses `RawInput` events; never `run_logic` |+| Native menu / command inbox | `lib.rs:1846` command inbox and `menus::invoke`; `:1860` `sync_native_menu` | Command inbox in logic (consumed channel); native menu sync in UI pass 0; `menus::invoke` must not run twice per frame |+| Keyboard shortcuts and focus/IME | `lib.rs:1546` `handle_shortcuts` | `App::ui` pass 0 only; `consume_key` remains the anti-duplication mechanism; fork E19 Latin-layout handling |+| Playback/source playback/scrub audio | `lib.rs:1128` `advance_playback`, `advance_source_playback`, `scrub_audio` | Logic; monotonic host clock; set playhead from anchor + elapsed, never accumulate per call |+| Undo press transaction | `lib.rs:2000` `begin_press` | `App::ui` pass 0 before UI; one press transaction per user gesture |+| Escape drag rollback | `lib.rs:2011` `cancel_value_drag` | Latch Escape and the press mark in UI pass 0; apply rollback exactly once after the final UI pass (§4.4) |+| TTS selection following | `lib.rs:1865` `panels::tts::follow_selection` | Logic or UI pass 0; idempotent selection identity |+| Job watch / auto-play after render | `lib.rs:1916` `watch_jobs` | Logic; consumed job results; status-bar drawing remains in UI |+| Auto-save dirty poll | `lib.rs:1818` `session.is_dirty()` and `request_repaint_after` | Logic; monotonic deadlines; worker stays alive while hidden |+| Dynamic trim / loop playback (`trim.tick`) | `lib.rs:1817` `panels::trim_monitor::advance`; `panels/trim_monitor.rs:39-48` executes `session.execute("trim.tick", {"clock": ctx.input(i.time)})` on every frame | Move to logic; monotonic host clock; compute an idempotent target time (same target called twice is a no-op), not one tick per pass; keep `request_repaint` |+| Metadata selection follow | `lib.rs:1814` `panels::metadata::follow_selection` | UI pass 0 or idempotent logic state; follows selection identity |+| Auto/undo frame bookkeeping | `lib.rs:1813` `self.auto.begin_frame()` | UI pass 0 once; no second call in a discarded pass |+| Timeline view sync | `lib.rs:1844` `self.sync_timeline_view()` | UI pass 0; idempotent |+| Native menu sync | `lib.rs:1860` `self.sync_native_menu()` | UI pass 0; idempotent |+| `last_ui_time` update | `lib.rs:2213` `self.last_ui_time = ctx.input(i.time)` | UI pass 0; monotonic host clock; drives the control raise heuristic and screenshot settle heuristics |+| Input waiters drain | `lib.rs:2193` `App::ui` tail and synthetic queue | UI pass; consumed waiter vector; respond once |+| Synthetic input / control input | `raw_input_hook` `lib.rs:2092`, synthetic queue | `raw_input_hook` runs before every `run_ui` frame and before `update_logic_only` ticks. Keep one unapplied synthetic gesture step in app state across repeated hidden logic ticks until a full UI pass consumes it; never collapse a press into its release or inject the same step twice. |++Additional deadline/side-effect calls found by the review and covered by this table:+`drain_control`'s `now + 3.0` retry deadline, its `now - last_ui_time > 0.25` raise decision,+`issue_screenshots`'s `settle` and timeout, `tick_media_refresh`'s persisted `last` timestamp,+the auto-save `request_repaint_after(1s)`, TTS `request_repaint_after(100ms)`, the synthetic+input repaint, and the `monitor_inexact`/`timeline_still` settle counters. None may use stale+`ctx.input(i.time)` after the lifecycle split; the toast stamp and settle counters have explicit+rows above.++### 2.4 Actual multi-pass exposure++- FilmCraft does not call `Context::request_discard` (verified by grep).+- egui 0.37 components used by FilmCraft can request it: `Grid` on first show+ (`crates/egui/src/grid.rs`, "new Grid" path), `Aligned` on size change+ (`containers/aligned.rs`), and `Resize` on a sizing pass (`containers/resize.rs`). FilmCraft+ uses `Grid` in many dialogs, `ResizeHandle` through `craft_ui::layout`, and `Aligned` only if+ a dependency introduces it.+- Both native `crates/eframe/src/native/epi_integration.rs::update` and web+ `crates/eframe/src/web/app_runner.rs` call `app.logic` **and** `app.ui` inside the+ `Context::run_ui` closure. Both call logic once per layout pass, not once per frame.+ When the root window/tab is hidden and no paint is requested, native+ `update_logic_only` and the web runner call `Context::run_logic` with no UI pass.+- `run_ui` may run a second pass after a discard. `RawInput::take()` moves `events` out, so+ pass 1+ receives an empty event list; `InputState` recomputes pointer clicks and+ `key_pressed` only from `new.events`. A click or key seen in pass 0 is therefore not+ re-derived in pass 1.+- After a normally completed `run_ui`, `current_pass_index()` is **zero**, including after+ multiple passes: `end_pass` takes the output. Do not claim or test a stale nonzero index.+ A pass-index first-pass guard is valid only for genuinely once-per-layout-frame UI state+ under this pinned integration, and needs a regression proving hidden calls still run. It+ must not suppress fresh asynchronous results, control commands or widget actions merely+ because a later pass has a nonzero index.+- `InputState::viewport().visible() == Some(false)` does **not** prove that the current+ callback has no fresh input. A pending screenshot or `RequestPaintWhileHidden` can force a+ real UI pass while minimized/occluded, and that pass can carry fresh input. Do not infer a+ "logic-only" phase from visibility.++## 3. Dependency and pin strategy++### 3.1 Shared `craft-libs` baseline — corrected facts++- The reconciled shared-library base is the merged PR #199 squash+ `3832c47ef68a0e6214f2c1e85f3526b6adcb686e` on `storytold/craft-libs`. The implementation+ checkouts use that base; `49190884278f16c9a9f5823d7698a8ffb5deb062` and its verification+ below are historical planning evidence.+- GitHub `repos/storytold/craft-libs/branches/main` returned+ `49190884278f16c9a9f5823d7698a8ffb5deb062` at approximately 06:25 UTC on 2026-10-23. This was+ the shared-library baseline at planning time.+- The local `origin/main` ref (`b1401e3`) is stale. A stale remote-tracking ref **does not+ prove** that `4919088` is unpublished. The review's "unpublished local/audit branch" claim+ is rejected; the corrected evidence is the GitHub main verification above.+- FilmCraft's current manifest pins `craft-ui` at+ `5c874d51eeb3de70e735c8ce87a59a7dedd47675`, `craft-media` at+ `f0ad6c1e1d297908915f4be315b0fcfc9be7b5d4`, and `craft-docpath` separately at+ `82a24b006eefa036b43c09a67fb9a3fbd17ffe63`. The old `5c874d51` commit was fetched exactly+ into the owned `craft-libs` checkout for inspection without changing HEAD or any source.+ These manifest pins are not the final publication pins.+- Between `5c874d51` and `4919088`, `crates/ui` changes seven files, **607 insertions and two+ deletions**: `README`, `docking/model.rs`, `docking/surface.rs`, `docking/tests.rs`,+ `lib.rs`, new `printing.rs` and `printing/tests.rs`. `Cargo.toml` is unchanged.+ - The docking change is the protected-group fix: `MoveFloating` now requires every+ floating-group member to be movable, including the resize grip. Preserve the tests from+ `d66e345`, `fd9cf54` and `c67b1e1`; this intentional security behavior must not be+ reverted to match the old FilmCraft baseline.+ - Printing is additive and lazy. Enabling the updated crate must not start discovery at+ startup. Relevant print commits include `b700ae7`, `d27646a`, `4cae45d`, `2bbef53` and+ `4f85efb`.+- `craft-docpath` has no `egui` dependency. Keep it at `82a24b0` unless a later actual+ cross-type or feature reason requires the move; do not fold it into the `craft-ui` bump.+- PR 199 is **not** mergeable as a tree. Its head `b68de8c` and historical audit tree+ `ec8840a` are stale relative to `4919088`, omit current `craft-platform`, and revert+ security, settings, docking and printer fixes. Reuse only the API port hunks from+ `8614e4a04fae516fba16c22b31ff1008cb6be10b` and the relevant README changes from+ `1764bca`, applied onto current `4919088`. Preserve intervening fixes and provenance.+ Never merge `b68de8c` or `ec8840a` as a tree.+- The shared 0.37 port and the CL-2 capture helper will produce a later published+ `craft-libs` revision. FilmCraft's final compatibility review must compare its actual old+ API/use sites against that final published revision, not against `b68de8c` or a branch+ point.++### 3.2 One coherent production graph, not a stock-0.37 stage++Stock 0.37 is a **local comparison** and CI control only. It is not a landable production+stage. The production landing uses one coherent graph: the final reviewed immutable+`storytold/egui` family, the final reviewed immutable `storytold/winit`, and the matching+published `craft-libs` revision. The previous coherent 0.36.2 graph remains the rollback+target.++The exact production pins are **not known yet** and must not be invented. `a4f9a17f` and+`8b35388b` are aiongg research candidates and comparison sources, not approved production+pins. Gate G-PINS (§15) blocks the entire landing stage until:++1. the complete reviewed/published `storytold/egui` P8 commit is immutable: E1-E21,+ P2b bounded async W15P routing, P7 held-key pairing, P7b/E21b, P7c selected #8763/#8748+ fixes and justified performance fixes;+2. the completed reviewed/published `storytold/winit` commit contains the bounded W15P+ transfer path, the W27 owner/support lifecycle and the required W1-W27 behavior;+3. the matching published `storytold/craft-libs` commit contains CL-1 (the PR-199 API hunks+ and one coherent fork graph) and the frozen CL-2F helper;+4. the exact SHAs, feature sets, provenance and test mappings are recorded in the suite pin+ manifest and the ledger.++Until then, no `[patch]` block in FilmCraft names a fabricated or guessed revision. The+eventual block must name the same immutable revision for every egui-family package that can+resolve, plus `winit`; a patch section inside `craft-libs` does not propagate into this root.+`egui_extras` is unused. `egui_plot` does not exist in FilmCraft; do not add it because its+version numbering differs. `winit` stays exactly `0.30.13`.++The final production manifest will look like the following shape, with `REPLACE_WITH_*`+resolved only after G-PINS:++```toml+[patch.crates-io]+egui = { git = "https://github.com/storytold/egui", rev = "REPLACE_WITH_APPROVED_EGUI_SHA" }+eframe = { git = "https://github.com/storytold/egui", rev = "REPLACE_WITH_APPROVED_EGUI_SHA" }+egui-winit = { git = "https://github.com/storytold/egui", rev = "REPLACE_WITH_APPROVED_EGUI_SHA" }+egui-wgpu = { git = "https://github.com/storytold/egui", rev = "REPLACE_WITH_APPROVED_EGUI_SHA" }+egui_glow = { git = "https://github.com/storytold/egui", rev = "REPLACE_WITH_APPROVED_EGUI_SHA" }+egui_kittest = { git = "https://github.com/storytold/egui", rev = "REPLACE_WITH_APPROVED_EGUI_SHA" }+epaint = { git = "https://github.com/storytold/egui", rev = "REPLACE_WITH_APPROVED_EGUI_SHA" }+emath = { git = "https://github.com/storytold/egui", rev = "REPLACE_WITH_APPROVED_EGUI_SHA" }+ecolor = { git = "https://github.com/storytold/egui", rev = "REPLACE_WITH_APPROVED_EGUI_SHA" }+epaint_default_fonts = { git = "https://github.com/storytold/egui", rev = "REPLACE_WITH_APPROVED_EGUI_SHA" }+winit = { git = "https://github.com/storytold/winit", rev = "REPLACE_WITH_APPROVED_WINIT_SHA" }+```++If a stock-0.37 comparison is needed, it lives in a separate local/CI branch or harness with+its own lockfile and evidence. It is never merged to main as an intermediate production+state, and it does not change the production pin policy.++### 3.3 Capture-helper sequence (CL-2 -> adapters -> CL-2F -> consumers)++The suite capture contract is one completion slot per admitted request: the app holds it+strongly and the callback holds it weakly.++1. **CL-2** in `craft-libs` (`crates/ui/src/capture.rs`): provisional bounded completion-slot+ prototype and tests. The app owns the request ID, path, deadline, settling policy,+ capture-frame geometry, DPI/scale identity and reply schema.+2. **DesignCraft and GridCraft adapters** against that exact provisional revision. DesignCraft+ exercises multiple viewports; GridCraft exercises a single window. Their tokens, paths,+ settle delays, deadlines and replies remain app-owned.+3. **CL-2F** freezes the helper API after joint review of those adapters.+4. **FilmCraft and the other consumers** pin the published revision containing CL-1 and+ CL-2F in one atomic dependency stage, not a branch head and not a path dependency.++All fourteen capture consumers adopt this contract. The eleven apps that already declare+`craft-ui` (CADCraft, DesignCraft, EffectCraft, FilmCraft, GridCraft, LightCraft, PdfCraft,+PhotoCraft, SoundCraft, VectorCraft and WordCraft) import the helper from the published+revision that contains both CL-1 and CL-2F in the same atomic dependency stage. DesignCraft+and GridCraft are the pilot adapters against the reviewed CL-2 provisional revision before+CL-2F freezes the API. DeckCraft, FigCraft and ArtCraft Native do not declare `craft-ui`;+they use contract-compatible local adapters unless they choose to add the dependency. Any+consumer that already carries an incompatible `craft-ui` bump must reconcile it in that same+atomic dependency stage, not a separate registry-only state. The earlier "thirteen `craft-ui`+consumers" wording was based on substring matches and is superseded by the exact TOML-key+inventory.++The helper contract, which every adapter must satisfy:++- the app's live request record owns the completion slot and a strong viewport waker; the+ callback holds only a `Weak` reference to that slot, never a strong `Context` or app+ reference and never a cycle back into the owning context. `ScreenshotCallback::new` does+ not request a new frame when data arrives (`egui/src/data/screenshot_callback.rs:22-24`),+ so the live slot's waker must request the repaint after the slot lock is released;+- the request record owns one slot; correlation is by ownership, not callback order or a+ second global token map;+- admission uses the shared defaults of **four outstanding requests, 128 MiB per image and+ 256 MiB aggregate reserved in-flight/completed bytes**; a stricter documented app cap is+ permitted (the shared SoundCraft example is 64 MiB/image and 192 MiB aggregate with the+ same four-request count). Check the count and aggregate budget before issue, reserve+ checked `width * height * 4` bytes, and do not evict an earlier admitted request;+- record the target-UI logical bounds and a geometry epoch at issuance and bind the returned+ pixels to that epoch. Cancel/retry on any intervening resize, DPI, zoom or surface-epoch+ change before save, **even a change back**; with an unchanged epoch derive pixel scale+ from the returned image dimensions and verify aspect/rounding. A callback carries pixels+ only, not capture metadata;+- cancel, close, drop and late callbacks release the image and send no reply/file; release+ the slot lock before waking the owning viewport. The callback has no repaint request of its+ own; the live slot's waker is the only wake path and runs after unlocking;+- the app keeps the request ID, output path, serialization, timeout, settling and reply+ schema; the callback does no PNG encoding, file I/O, command execution or long locking;+- retained image bytes return to zero after drain/shutdown; a post-hoc size check does not+ substitute for pre-issue accounting.++### 3.4 Lockfile and reachability checks++Before publication, run these against a clean checkout and a fresh `CARGO_HOME` (or with+`--locked` after fetching). These are proposed checks, not executed here:++```sh+cargo metadata --locked --format-version 1 > /dev/null+cargo tree -i [email protected] # must report no match+cargo tree -i egui # exactly one 0.37.0 source+cargo tree -i winit # exactly one pinned source+cargo tree -d -i winit # no duplicate winit+cargo tree -d -i wgpu # one resolved wgpu source/version+cargo tree -e features -i egui | grep -E 'default_fonts|monochrome_emoji_fonts|clipboard'+```++Add a CI/`xtask` check that fails if:++- an egui-family package has a source other than the chosen immutable fork;+- `winit` has more than one source or a version other than 0.30.13;+- a published manifest contains `path = "/home/`, `path = "/Users/` or an uncommitted local+ checkout;+- a git pin changes revision without the same change in the suite pin record;+- the required `clipboard` or `monochrome_emoji_fonts` feature is absent from the selected+ native/egui feature set.++The lockfile is committed. A fresh clone with `cargo fetch --locked` is the publication+reachability test.++### 3.5 Feature policy++The current feature lists are explicit. Migrate to 0.37 with these decisions:++- workspace `egui`: `default-features = false` and features `["default_fonts",+ "monochrome_emoji_fonts"]`;+- native `apps/filmcraft`: keep `default_fonts`, `wgpu`, `accesskit`, `wayland`, `x11`, and+ **add `clipboard`**. Without `clipboard`, eframe 0.37's `egui-winit` uses the in-app+ fallback clipboard, so cross-application text copy/paste silently stops working;+- `crates/ui-egui`: keep `default_fonts`, `wgpu`, `accesskit`; the native app root is+ authoritative for OS clipboard;+- web `apps/filmcraft-web`: keep `default_fonts`, `wgpu`; the eframe `clipboard` feature is+ native (`egui-winit`) and is not added to wasm. Verify browser clipboard behavior in the+ browser workflow instead;+- do **not** add `system_fonts`; do **not** add `links` or `web_screen_reader` by accident.+ Record them as deliberate opt-outs in the PR (`links` is not used; `web_screen_reader` is+ a separate speech/accessibility decision, not part of this migration). Revisit only with+ measured evidence.++`monochrome_emoji_fonts` is not implied by `default_fonts` in 0.37. It must be explicit;+otherwise the bundled `NotoEmoji-Regular`/`emoji-icon-font` faces disappear and symbols such+as `✔ ✓ ✖ ⚡ ⚠ ⚙ ♪ ☑` can become tofu or switch to a platform face.++These feature decisions apply to production roots. They do **not** flow through+`egui_kittest`: its normal `egui` dependency is `default-features = false`, and only its own+dev-dependencies enable fonts, which do not propagate. Test roots must enable the features+explicitly or install controlled fonts (§11.1).++## 4. Lifecycle and root-Ui design++### 4.1 Rule: logic is idempotent background; UI is composition; input is pass-0 only++Introduce private `FilmcraftApp::run_logic_frame(&mut self, ctx: &egui::Context)` and+`FilmcraftApp::run_ui_frame(&mut self, ui: &mut egui::Ui)`:++- `App::logic` runs `run_logic_frame` on **every** call. Under this pinned eframe/egui+ integration, native and web call `App::logic` once per `run_ui` layout pass, and also call+ it through `run_logic` for hidden ticks. Therefore `run_logic_frame` must be safe to call+ more than once per frame:+ - background queues are consumed (`try_recv`, `drain`, `Option::take`), so a second call+ sees no work;+ - playback/trim/autosave/deadline work compares a monotonic host time and computes an+ idempotent target; calling it twice at the same instant does not advance twice;+ - engine events are drained once and processed as values, not replayed;+ - no logic path reads UI input events, `consume_key`, `Response`, or stale input time.+- `App::ui` runs only `run_ui_frame`. Fresh-input handling (drops, shortcuts, `begin_press`,+ Escape, IME/focus, synthetic queue, screenshot request dispatch) runs in **pass 0** of a+ UI pass, where events are fresh. Pass 1+ has no events and must not re-derive them.+- `raw_input_hook` runs before each UI frame **and** before each `update_logic_only` tick+ (eframe `prepare_raw_input`). It must therefore advance at most one synthetic gesture step+ per call and leave that step in app state until a full UI pass consumes it; repeated hidden+ logic ticks must not drain a whole press/release sequence or inject it twice.+- `run_logic_frame` is wrapped in `catch_unwind` with a latch: an unwinding logic pass sets+ `ui_error`, stops playback and does not re-run the same panicking code every tick or+ re-log it every pass. `run_ui_frame` keeps its catch around `frame(ui)` and the graphics+ notice.+- `on_exit` stays in `FilmcraftApp` and calls `session.shutdown()` exactly once.++No `ui_pass`/`hidden_tick` predicate based on `viewport.visible()` is used. Visibility is+used only for presentation policy (for example whether a hidden window should be raised),+never to infer that the current pass has no input or that background work is complete.++### 4.2 Hidden work and monotonic time++`Context::run_logic` leaves `InputState` events and time at the previous pass. Therefore:++- all background code uses a monotonic host clock (`web_time::Instant` on all targets, or a+ small `Clock` wrapper around it); no hidden work uses `ctx.input(|i| i.time)`;+- background code never reads `i.raw.events`, never calls `consume_key`, and never polls+ `Response`/`read_response`;+- input-dependent work is in `App::ui` pass 0, not in logic and not inferred from a+ visibility flag;+- `Window::show`, `Area::show`, and any other widget construction run only inside a UI pass;+ they are never called from `run_logic_frame`;+- control `ui.*` requests and gesture stages that need composition while hidden use+ `ViewportCommand::RequestPaintWhileHidden` (see §4.5). A screenshot request already causes+ the needed paint.++A regression test exercises visible single/multipass, repeated hidden logic ticks, a forced+hidden UI paint, restore with buffered events, a background completion between passes, and+one gesture yielding one command/undo.++### 4.3 Do not use `Context::root_ui` recursively++`Context::root_ui` panics if called while `App::ui`/`Context::run_ui` already holds the root+`Ui` (upstream #8535). FilmCraft does not need it. Keep passing the existing `&mut egui::Ui`+to `header::show`, `dock_area`, `panels::*` and dialogs. Where a helper takes+`&egui::Context` only to add widgets, change it to take `&mut egui::Ui` (or return an+action/shape), not a `Context` bridge.++### 4.4 Multi-pass actions: no clearing on a no-event pass++Immediate mode plus `request_discard` means a UI handler can run in a pass whose output is+discarded. FilmCraft's project mutations must run once, and must not be lost.++Design:++- Add a frame-scoped `pending_ui_actions` queue and an `input_generation` counter in+ `crates/ui-egui/src/lib.rs`. Each action carries a stable `ActionKey` (command, target+ identity, payload digest) and the generation in which it was queued.+- Input-driven handlers queue only in UI pass 0. Pass 1+ receives no events, so it cannot+ re-derive a click or key.+- **Never clear the queue at the start of pass 1+.** There is no reliable way to predict a+ future discard from inside pass 0; `ctx.will_discard()` describes the current pass's+ output, not the next pass.+- Dispatch policy:+ - input-driven actions execute at the end of pass 0 (the pass that saw the events); the+ empty-event pass cannot recreate them, so this is exactly once;+ - actions that must observe final layout (dialog OK/Apply/close, dock reflow, actions that+ close a panel) stay queued across discarded passes and are drained at the end of the+ first pass whose `ctx.will_discard()` is false;+ - a duplicate enqueue in a later pass coalesces by `ActionKey`; it is never used as a+ reason to drop the original;+ - if a frame ends with deferred actions still pending (for example an abnormal maximum-pass+ exit or a caught panic), do not silently drop them: keep them, surface a visible status+ error, and dispatch once at the next safe pass. A test forces this path.+- `cancel_value_drag` (Escape drag rollback) is also pass-0-aware. In pass 0, if+ `pointer.any_down() && key_pressed(Escape)`, latch `escape_cancel` together with the undo+ mark. Apply the rollback once after the final UI pass (or after pass 0 when no discard+ occurred), then clear the latch. The final pass has no key event, so it must use the latch,+ not re-read `ctx.input`. The latch is scoped to the active press transaction; it does not+ cancel unrelated queued actions.+- `begin_press` runs before UI in pass 0; `cancel_value_drag` sees the corresponding mark and+ runs once.++Tests: click + forced discard = exactly one command/undo step; click on a `Grid` first-show+frame; key shortcut + forced discard; Escape drag + forced discard; two queued actions with+the same key coalesce; an abnormal pending queue is surfaced and dispatched exactly once.++This replaces the reviewed design that cleared the queue on `pass_index > 0`; that design+would have lost the user's click on every discarded frame.++### 4.5 Screenshot callback, hidden paint and CL-2++0.37 removes `egui::UserData` and `Event::Screenshot`; `ViewportCommand::Screenshot` takes a+`ScreenshotCallback` (`crates/egui/src/data/screenshot_callback.rs`).++Replace `lib.rs:1714 issue_screenshots` and `lib.rs:1744 collect_screenshots` with:++- one CL-2 completion slot per request, owned by the request record; the live slot holds the+ strong viewport waker (`Context` clone plus `ViewportId`, or `request_repaint` callback),+ and the callback holds only a `Weak` slot;+- `ViewportCommand::Screenshot(ScreenshotCallback::new(move |image| { /* complete the weak slot once, unlock, then wake */ }))`;+- `ScreenshotCallback::new` does not request a frame when the data arrives. Completion must+ unlock the slot and then call the stored waker; the callback has no repaint path of its own+ and does not hold a strong `Context` or app reference;+- `collect_screenshots` drains the result in logic and calls `control::save_screenshot(ctx,+ &image, path, crop)` as today; after timeout/close/cancel, release the slot and ignore a+ late image;+- token/correlation still required: two queued screenshots may complete out of order; use+ ownership plus the request ID, not callback order;+- admission and memory limits from §3.3: four outstanding requests, 128 MiB per image, 256+ MiB aggregate (a stricter documented cap is allowed), checked `width * height * 4`+ reservation before issue, and revalidation/rejection after any resize/DPI/zoom epoch+ change;+- the issuance record binds the target-UI logical bounds and geometry epoch to the returned+ pixels; a change back to the old geometry does not restore validity.++Hidden-window semantics are the 0.37 behavior, not the old assumption:++- `ViewportCommand::Screenshot` maps to `ActionRequested::Screenshot`/`PaintWhileHidden` and+ makes the integration run a UI pass even when hidden; the callback is then completed from+ that forced paint. A hidden pending screenshot is therefore expected to deliver an image.+- A request that is still queued and not yet issued — settling frames or a hidden logic tick+ — has no screenshot command to force its paint. Logic must send+ `ViewportCommand::RequestPaintWhileHidden` while such a request is pending so the UI pass+ that advances settling can run; once issued, the screenshot command itself forces paint.+- `ViewportCommand::RequestPaintWhileHidden` is also the supported way to force a UI pass for+ other stages that need composition/gesture handling while hidden (for example control+ `ui.*` requests that need fresh layout or settling without a screenshot).+- The screenshot timeout (`SCREENSHOT_TIMEOUT_S`) is a renderer/readback failure guard, not a+ "hidden never presents" path. A test must not encode "hidden returns timeout" as normal+ behavior. Test both branches: hidden + pending screenshot → image delivered, including the+ queued-but-not-yet-issued settling case; hidden + no capture request → no capture (and,+ where a request is admitted but the renderer cannot complete, the documented timeout+ error).+- `raw_input_hook` (`lib.rs:2092`) no longer preserves `Event::Screenshot`; it clears input+ events as it already clears hovered/dropped files. Update+ `crates/ui-egui/tests/ui_control_input.rs:153`: assert close/viewport metadata survive and+ no screenshot event is expected; add a native/VM check that the callback still delivers.+- `raise_for_control` (`lib.rs:1665-1673`) remains for occluded macOS raising without focus;+ pair it with `RequestPaintWhileHidden` where a UI pass is required, rather than assuming a+ hidden window never runs UI.++### 4.6 Playback, audio, autosave, jobs, trim and deadlines++- `advance_playback` (`lib.rs:1128`) sets the playhead from `anchor_tick + elapsed`; use a+ monotonic host clock and do not accumulate dt. Repeated calls at the same time are+ idempotent.+- `playback_mix` remains the live project snapshot; audio callbacks are outside egui. Logic+ keeps polling `audio.played_frames()` while hidden.+- `FilmcraftApp::frames.pump` moves from `App::ui` to logic. The web runner's `WebApp::logic`+ also pumps jobs/audio; its per-frame work must be idempotent because web calls logic per+ pass.+- Auto-save: `Session::poll_persistence` and `session.is_dirty` move to logic; the recovery+ journal worker must not depend on painted frames.+- `watch_jobs` splits: `poll_jobs` in logic handles completion and `play_after_render`; the+ status-bar `job_status` remains in UI.+- `trim_monitor::advance` (`lib.rs:1817`; `panels/trim_monitor.rs:39-48`) moves to logic and+ uses a monotonic clock. `trim.tick` receives an idempotent target time/step, so a second+ logic call for the same pass does not advance edits twice; it still requests repaint.+- Metadata follow, `auto.begin_frame`, `sync_timeline_view` and `sync_native_menu` run once+ in UI pass 0 (or are made idempotent if moved to logic).+- Screenshot settling still waits for `monitor_inexact` and `timeline_still`, both updated in+ logic/UI with the monotonic clock.+- Add a CI grep that rejects direct `session.execute`, `menus::invoke` and `trim.tick`+ execution from UI-only modules outside the queue/dispatch module and an explicit+ allow-list. Until that check is green, the one-action guarantee is not claimed.++## 5. Concrete API migration catalogue++These are the source-grounded incompatibilities. Line numbers are baseline line numbers.++### 5.1 `FontData` is a shared blob++0.37 `epaint` has `pub type Blob = Arc<dyn AsRef<[u8]> + Send + Sync>` and+`FontData::from_blob(Blob, index)` (`crates/epaint/src/text/font_data.rs`). Replace literal+`FontData { font: Cow::... }` in:++| File:symbol | Current code | Migration |+|---|---|---|+| `crates/ui-egui/src/cjk.rs:53` `find_system_font` | `FontData { font: Cow::Owned(face.data()?), index: face.info.index, ... }` | `FontData::from_blob(Arc::new(face.data()?), face.info.index)` |+| `crates/ui-egui/src/i18n/mod.rs:292` `system_japanese_font` | `FontData { font: Cow::Borrowed(bytes), index: face.info.index, ... }` | `FontData::from_static(bytes)` (bytes are already leaked and shared) |+| `crates/ui-egui/src/rtl.rs:92` `system_fonts` | `FontData { font: Cow::Owned(data), index: face.info.index, ... }` | `FontData::from_blob(Arc::new(data), face.info.index)` |++Keep `Arc<FontData>` in `font_data` maps; `FontData` is cheap to clone now. Add a regression+that a TTC face index is preserved (non-zero `info.index`), because the literal construction+was the only place that carried it.++### 5.2 `MouseWheel` gained `source`++0.37 `Event::MouseWheel` has a required `source: MouseWheelSource`. Add+`source: MouseWheelSource::Wheel` for the control-channel synthetic wheel in+`crates/ui-egui/src/control.rs:370`, and to the two tests that construct it:+`crates/ui-egui/tests/monitor_geometry.rs:176` and `crates/ui-egui/tests/panels_ui.rs:249`.+Use `Wheel` rather than `Unknown` so ScrollArea behavior and kinetic-scroll policies match a+real mouse wheel. Add a test that the timeline wheel path (`panels/timeline.rs:2221`) still+steps one tab per notch and does not start kinetic scrolling in headless tests.++### 5.3 `WidgetType` -> `Role`, and one role per control++`WidgetType` is a deprecated alias of `accesskit::Role`; `SelectableLabel` no longer exists+and `TextEdit` is `TextInput`. Replace the ten sites:++| File:line | Current role | New role |+|---|---|---|+| `crates/ui-egui/src/dock.rs:673` | `WidgetType::Button` | `Role::Button` |+| `crates/ui-egui/src/dock.rs:725` | `WidgetType::SelectableLabel` | `Role::Tab` with `selected(active)`; the code already overrides the node role to `Tab` |+| `crates/ui-egui/src/dock.rs:765`, `:779` | `Button` | `Button` |+| `crates/ui-egui/src/dock_ui.rs:326` | `Button` (floating-panel resize grip) | `Role::Button` with the accessible name "Resize panel". Do **not** expose `Splitter` here; a floating-window grip is not a pane divider. Dock split dividers use `Role::Splitter`; update `crates/ui-egui/tests/shared_docking_ui.rs:201` to the chosen role in the same PR |+| `crates/ui-egui/src/panels/graphics.rs:1028` | `TextEdit` | `Role::TextInput` with a name |+| `crates/ui-egui/src/panels/tools.rs:27` | `SelectableLabel` | `Role::Button` with `selected`; a radio-group model is a later accessibility change |+| `crates/ui-egui/src/panels/monitor.rs:1013` | `Button` | `Button` |+| `crates/ui-egui/src/panels/source_drag.rs:46` | `Button` | `Button` |+| `crates/ui-egui/src/theme_favorites.rs:4` | `Button` | `Button` (favorite toggle; `CheckBox` is a later semantic change) |++The previous `Button` vs `Splitter` contradiction is resolved: floating grip = `Button`;+dock pane divider = `Splitter`. The test is updated once, not left ambiguous.++### 5.4 `ScrollArea::State::offset` is private++0.37 provides `clamped_offset()` and `unclamped_offset()`; the old `offset` field is private.+Replace `crates/ui-egui/src/panels/media_browser.rs:576` and+`crates/ui-egui/src/panels/project_views.rs:516` (`out.state.offset.x`) with+`clamped_offset().x` for header alignment. Add a test that scrolls the project list+horizontally to the end and asserts the header’s first column x matches the last visible+row’s column x within one point.++### 5.5 `Context::run_ui` callback is `&mut Ui`++`crates/ui-egui/src/lib.rs:2411` currently writes:++```rust+let mut out = ctx.run_ui(raw, |ctx| secondary = ctx.input(|i| i.pointer.secondary_clicked()));+```++Change to:++```rust+let mut out = ctx.run_ui(raw, |ui| secondary = ui.ctx().input(|i| i.pointer.secondary_clicked()));+```++The other `run_ui` call sites already use `|ui|`. Do not call `Context::root_ui` inside these+closures.++### 5.6 `Id::new` and `Ui::id`++0.37 deprecates `Id::new` and `Ui::id` (`Id::unique` / `Ui::scope_id`). FilmCraft has 403+`Id::new` occurrences across `crates/ui-egui/src` and tests. Under `clippy -- -D warnings`,+deprecation is a hard failure.++- `egui::Id::new(x)` -> `egui::Id::unique(x)` for every root id; same hash, same identity.+- `Id::new(parent).with(child)` -> `Id::unique(parent).with(child)`.+- `UiBuilder::id(x)` -> `UiBuilder::scope_id(x)`; FilmCraft uses `id_salt` and has no+ `UiBuilder::id` (verified), but `craft-ui` PR #199 performs its own conversion.+- `Ui::id()` -> `Ui::scope_id()`; FilmCraft has no `ui.id()` call (verified).+- Keep `id_salt` for child UIs; do not replace every `id_salt` with a global id.++Add a grep-based CI check that no `Id::new(` remains in FilmCraft or its tests.++### 5.7 `Event::PasteImage`++0.37 emits `Event::PasteImage(Arc<ColorImage>)` when the clipboard has no text. Update+`crates/ui-egui/src/lib.rs:2299` `clipboard_events_as_keys` to map `PasteImage` with+`command` to `Key::V`, with `shift` to `Key::Insert`, and plain to `Key::Paste`, exactly as+`Event::Paste`. Add tests alongside `ctrl_c_x_v_become_key_presses`.++The native app’s `clipboard_media` hook (arboard) still supplies files/images to the Paste+command. On wasm, either keep the existing “FilmCraft clips only” path or extend+`ClipboardMedia` with the `PasteImage` bytes; that is a separate feature decision. Do not+double-read the clipboard if the event already carries an image.++### 5.8 `Event::Screenshot` / `UserData`++Covered in §4.5. Remove `egui::UserData::new` at `lib.rs:1721` and the `Event::Screenshot`+matches at `lib.rs:1753` and `lib.rs:2100`.++### 5.9 Other 0.37 changes that are compile-compatible but visible++- `default_fonts` off by default: explicit feature; `monochrome_emoji_fonts` explicit (§3.5,+ §6.1).+- `clipboard` opt-in in eframe/egui-winit: native feature added (§3.5).+- `Id` deprecations (§5.6).+- `Panel` constructors take `impl AsIdSalt`: FilmCraft does not use `egui::Panel`, but+ `craft-ui` and any new panel code must use the new form.+- `UiBuilder::scope_id`: see PR #199.+- `ComboBox` is built from atoms and takes `IntoAtoms`; existing `selected_text`/`show_ui`+ calls remain source-compatible, but styling/measurement changes must be reviewed.+- `WidgetType::TextEdit` renamed to `Role::TextInput`; `TextEdit` itself uses+ `Role::TextInput`.+- `Context::root_ui`/`run_pass`: not adopted; no recursive root UI.+- `ViewportCommand::Screenshot` callback and `RequestPaintWhileHidden`: adopted as above.+- `egui::Event::PasteImage`, `MouseWheelSource`, PRIMARY selection: adopted as above.+- kittest 0.37 hard-fails input widgets without accessible names (#8589/#8611). The first+ green compatibility stage must name all input widgets, including all 56 `TextEdit`+ construction sites; do not disable strict naming globally.++## 6. Fonts, glyph coverage, language and RTL++### 6.1 Font installation and bundled coverage++`crates/ui-egui/src/theme.rs:420` `install` builds `FontDefinitions`, inserts Inter/JetBrains+Mono, then appends Japanese craft-fonts (`add_craft_fonts`), Chinese (`cjk::install`) and RTL+(`rtl::install`). Keep that order.++The explicit `default_fonts` feature preserves egui’s built-in fallback, but in 0.37 the+monochrome emoji faces moved behind `monochrome_emoji_fonts`. Enable it explicitly. FilmCraft+starts from `FontDefinitions::default()` and uses `✔ ✓ ✖ ⚡ ⚠ ⚙ ♪ ☑` (20 occurrences across+10 files); with `system_fonts` off, those symbols can otherwise become tofu or switch to a+platform face. Add a glyph-coverage assertion for exactly these characters plus a screenshot+diff.++`FontData` construction is §5.1. Keep the process-wide caches (`OnceLock`) and the single+system scan; do not call `filmcraft_text::fonts::scan_system()` in a UI pass.++`eframe` 0.37 adds an optional `system_fonts` feature (fontique provider, #8512) and a+`system_font_fallback` option. **Do not enable it in the migration.** It changes startup cost+and the fallback face chosen for a missing glyph; the current explicit CJK/RTL fallback is+part of FilmCraft’s visual contract. Record it as an opt-in follow-up with measured startup+and glyph coverage, especially for color emoji; do not accept clamp-only as a substitute for+texture wrap/filter semantics.++Pinned test fixtures are the exact set from the egui plan §10.6, fetched into the task’s+evidence fixture directory with their licence files. **Do not copy font binaries into this+repository.** The fixture set is:++| Fixture | Source | SHA-256 | License |+|---|---|---|---|+| Arabic | craft-fonts `2481a8a324b986a45954e90045ed1f8f2efaaf3c` `fonts/noto-sans-arabic/NotoSansArabic.ttf` | `63111b5b2e074dd48cc67692e0a2726d86ee94c1c37fe8598257b7b4e87e869e` | OFL-1.1, adjacent `OFL.txt` |+| Thai | same craft-fonts `fonts/noto-sans-thai/NotoSansThai.ttf` | `5a1c559bb539583c8a1fd99d1c5b9491e5e14478c9cd2bd0970d5c3096cc9ef8` | OFL-1.1 |+| CJK SC | same craft-fonts `fonts/noto-sans-cjk-sc/NotoSansCJKsc-Regular.otf` | `2c76254f6fc379fddfce0a7e84fb5385bb135d3e399294f6eeb6680d0365b74b` | OFL-1.1 |+| Japanese | same craft-fonts `fonts/biz-ud-pgothic/BIZUDPGothic-Regular.ttf` | `258d7156c165f2ff774b6efee637c22c3b950de0d8a10e501137061bc8085d01` | OFL-1.1 |+| Hebrew | google/fonts `8b0a1d0f5983c89bc2b93f1b5fb55f9e252744b5` `ofl/notosanshebrew/NotoSansHebrew[wdth,wght].ttf` | `7ef36a2c3593758cdb622e1bdef4f84523e92fbc3ccc667438dd80ff54c2de88` | OFL-1.1; fix axes weight 400/width 100 |+| Color emoji | googlefonts/noto-emoji `22e564626297b4df0a40570ad81d6c05cc7c38bd` `fonts/NotoColorEmoji.ttf` | `39ee3c587e10e89669b9ff32703261d10d5f9c4dd5ad147b6b5a1c5200591817` | OFL-1.1 |+| Bundled Latin/emoji | candidate `epaint_default_fonts` `Ubuntu-Light.ttf` | `80307b8da7649aa4ee4d484b232140e3ce1ec0ca093073d3c53c8f5a5ced7a70` | Ubuntu Font License, adjacent `UFL.txt` |+| Bundled mono emoji | candidate `epaint_default_fonts` `NotoEmoji-Regular.ttf` | `415dc6290378574135b64c808dc640c1df7531973290c4970c51fdeb849cb0c5` | OFL-1.1 |++The fixture bytes and licence hashes enter the evidence manifest. A controlled comparison+uses a fixed common set; a separate default-policy visual comparison records each+baseline/candidate policy. System-provider tests are a nondeterministic integration row with+OS/font inventory recorded, not pixel-golden input.++### 6.2 UI language and AccessKit language++FilmCraft’s `i18n::Language` is a private list (`crates/ui-egui/src/i18n/mod.rs`,+`Language::ALL`; 12 languages, no Arabic/Hebrew UI). Add `Language::bcp47()` returning proper+tags (`en`, `ja`, `es`, `pt-BR`, `uk`, `zh-CN`, `de`, `ru`, `fr`, `id`, `it`, `ko`). Call+`ctx.set_language(Some(tag))` when the language changes and `frame.set_ui_language(Some(tag))`+in `App::ui` (fork E18) so the AccessKit root and the web hidden IME input use the same tag.+In kittest, `Frame::set_ui_language` is a no-op; the `ctx.set_language` call is the tested+path.++Do not enable `Style::right_to_left` (fork E9) yet: FilmCraft offers no RTL interface+language, and mirroring the custom-drawn workspace without a full RTL audit would be worse+than leaving it LTR. Document RTL UI as a future feature gated on real translated layouts.++### 6.3 Document RTL and the fork’s bidi work++`crates/ui-egui/src/rtl.rs` currently compensates for 0.36’s lack of bidi: `line_sections`+splits RTL runs into words, reverses them, mirrors brackets and gives each word its own+`LayoutSection`. The fork (E5/E12) performs UAX #9 shaping and visual ordering itself. Keeping+both is a double-reversal bug.++In P1, in the same stage that pins the fork, change `rtl::Lines`:++- keep `has_rtl` and the `rtl` alignment flag;+- build one `LayoutJob` with `direction: TextDirection::Auto`,+ `halign: if rtl { Align::RIGHT } else { Align::LEFT }`, `halign_min_is_start: true`, one+ section, and the requested wrap width;+- delete `line_sections`, `mirror`, `in_word`, `line_ranges` and their unit tests once the+ fork is pinned; replace them with tests on `Row::rtl_paragraph`, `Row::visual_order`, glyph+ order and right alignment;+- keep `paint`/`paint_line` API so `timeline_captions.rs:152` and `text.rs:239` do not change+ contracts.++The fork's E5/E12 path and the removal of the manual reversal must ship in the same P1+commit set; there is no intermediate state with both active. A negative regression first+demonstrates the double ordering (Arabic caption with the fork produces reversed words), then+P1 removes it. Test `"كلمة أخرى"`, `"قال FilmCraft 0.6 جيد"`, Arabic-Indic digits, brackets+and an LTR paragraph containing an RTL phrase; assert the leftmost drawn glyph of the first+visual word, not just “some Arabic glyph exists”.++`TextEdit` keeps logical order; fork E13/E16 add grapheme/bidi-safe caret movement. Test+caption text editing (logical caret, Delete/Backspace, Home/End) and selection rendering.++## 7. Input, IME, clipboard and PRIMARY++### 7.1 Keyboard++`handle_shortcuts` (`lib.rs:1546`) already uses `i.consume_key` and a panel/app-wide+specificity sort. Fork E19 adds `RawInput::keyboard_layout_is_latin` and+`latin_layout_chars`; `handle_shortcuts` must use the Latin-layout character for letter+shortcuts when the active layout is not Latin, so `Ctrl+Z` still undoes on a+Russian/Arabic/Hebrew layout and an unmodified `Z` does not become a tool shortcut. P7+held-key pairing keeps a key's emitted egui identity for its release when the layout or+modifiers change, clears it on focus loss/IME/destruction, and does not redefine winit's+live `logical_key`. Add a kittest that constructs `RawInput` with+`keyboard_layout_is_latin: Some(false)` and+`latin_layout_chars: vec![(Key::Q, 'q'), ...]`, sends a physical key, and asserts the command+fires only for a Latin-letter key. Do not hard-code a platform.++Input handling remains in `App::ui` pass 0, where the event list is fresh; pass 1+ must not+re-run it.++### 7.2 IME and outgoing surrounding text (E21b/P7b)++Fork E6 (request_focus does not interrupt composition), E8 (TextEdit glyph clipping), E21+(`ImeEvent::DeleteSurroundingBytes`) and winit W18-W27 cover Windows/X11/Wayland/macOS IME.+The candidate has a confirmed gap: winit W27 exposes+`WindowExtWayland::set_ime_surrounding_text`, but egui-winit never calls it, and+`egui::IMEOutput` carries no logical text. E21 alone carries incoming deletion/commit only.++This migration therefore requires **E21b/P7b** before acceptance. The authoritative+contract is the complete E21b section of `egui/docs/egui-037-migration-plan.md` plus+`winit-review-triage.md`; these bullets are FilmCraft's adoption summary, not a weaker+restatement:++- `IMEOutput` carries one atomic descriptor: owner/context-generation identity plus the+ surrounding-text state and payload. The owner generation is present **even when the state+ is `Unavailable`**; an available empty document is distinct from unavailable support and+ is sent as an explicit empty payload, not omitted.+- add a bounded transient payload of at most **4000 UTF-8 bytes**, extracted at valid UTF-8+ boundaries **without allocating a full document copy**, with indices remapped after+ excluding preedit. If the selection cannot fit, emit explicit `Unavailable` rather than+ presenting a truncated selection as complete. Keep `Clone`/`Eq`, update `Copy`-dependent+ callers, and keep transient text out of Debug, serialization and persistence.+- built-in `TextEdit` produces committed logical text after applying deletion/commit/cursor+ updates, excluding preedit, with UTF-8 byte cursor/anchor indices; password fields emit no+ text. Normal-to-password, no-IME, focus-loss/reset, owner-change and unavailable+ transitions clear old backend text; each payload belongs to the current IME-owning+ widget/viewport.+- W27 gains an explicit owner/support transition: clear its cache and commit a+ disable/enable boundary before publishing a new owner or support state. Merely changing+ purpose or sending empty text does not clear protocol state. Available-empty maps to+ `set_surrounding_text("", 0, 0)` plus commit; unavailable omits `set_surrounding_text` and+ uses the committed clear boundary; when support returns, enable plus the full payload+ precedes commit. Cancel the old preedit without inserting it into the new owner.+- egui-winit appends the latest completed pass's IME descriptor, owner and payload together,+ including an authoritative `None`; a previous payload must not survive a later+ non-text/password/`None` pass. The same finalized output and payload are appended+ together across passes.+- on a current-epoch text-input-v3 `done` with a mismatched serial, apply the incoming edits+ **once** and defer outgoing state until a matching serial. Obsolete owner/focus epochs+ invalidate their pending batch; a current-generation serial mismatch is not a reason to+ drop valid edits.+- the egui-winit Wayland adapter calls W27 with the transient payload on text, selection or+ IME-owner change, per window and owner; macOS NSRange conversion remains a separate W26+ path, not a claim of a new macOS API.++FilmCraft’s own custom `IMEOutput` producer is at+`crates/ui-egui/src/panels/graphics.rs:933-940`. It must supply the logical model text, the+preedit, and UTF-8 byte cursor/anchor ranges from its own scalar/grapheme coordinates; it must+not pass display-bidi text or a `None` placeholder. Its integration test must reject a+split-UTF-8 range and verify the model range maps to the emitted byte range. Built-in+`TextEdit` consumers in FilmCraft (caption, notes, search, metadata) inherit the producer and+need tests rather than custom adapters; the same inheritance applies to LightCraft’s built-in+consumers. The suite inventory of custom producers is WordCraft `canvas.rs` (two),+VectorCraft `canvas.rs`, FigCraft `shortcuts.rs`, EffectCraft `viewer_text.rs`, FilmCraft+`graphics.rs`, DesignCraft `canvas.rs`, DeckCraft `canvas.rs` and PhotoCraft `type_tool.rs`;+each needs its own adapter and test.++Required tests: outgoing text changes immediately after delete+commit and deletion-only+batches; scalar/grapheme vs byte indices; supplementary emoji/combining marks/RTL logical+order; preedit exclusion and caret movement; long selection/window limits; same-window field+switch; two windows; focus loss/reset/late serial; initial empty, available-empty → non-empty+and unavailable/password → available transitions; multi-pass final-output selection where+pass 1 is text and pass 2 is password, non-text or `None`. Native Wayland Vietnamese/+predictive IME verifies the protocol trace and editor content/undo. Headless tests cannot+prove native IME focus/composition.++#### Film graphics IME ownership lifecycle++Incoming `ImeEvent` carries no owner or epoch, so the custom Program-monitor editor keeps a+local causal lifecycle: `Active(owner)`, `TerminalPending(owner)` and `Stale`. A non-empty+preedit records `Active`; an empty preedit clears the visible composition but records+`TerminalPending`, because its commit/delete is a separate event. A target change or editor+close turns either state into `Stale`, so that pending terminal event cannot edit the+replacement target. A rejected stale commit is itself the terminal boundary and consumes the+tombstone immediately, allowing a preedit later in the same raw batch to start a new+composition. A stale empty preedit or delete is only tentatively terminal: the tombstone is+kept through the batch so a paired old delete+commit is rejected, and is consumed at batch end+when no commit follows. A lone stale non-empty preedit keeps the tombstone across batches, so a+preedit/commit pair split across batches cannot retarget either. This uses observed event order+only, never frame/time heuristics. Regressions cover an empty preedit followed by a target+switch before its commit, and a coalesced stale commit followed by a new preedit in the same raw+batch. An entirely unobserved platform reset remains indistinguishable from a new composition;+the first ambiguous composition after it may be dropped rather than claiming provenance.++Platform rows:++- Windows: Japanese and Korean IME in a caption/notes/search `TextEdit`; caret follows+ composition; a key the IME consumes is not also a tool shortcut; commit adds exactly one+ undo step.+- X11: Vietnamese Telex; one input context per window; no duplicate letters.+- Wayland: text-input-v3 surrounding text and delete-surrounding; no double commit; outgoing+ bytes observed after commit/delete.+- macOS: press-and-hold accents, dictation, ideographic space, first Korean key; real+ hardware required.+- Web: named keys are not typed as text; `lang` on the hidden input; IME commit in a text+ field.++### 7.3 Clipboard and PRIMARY++0.37 adds PRIMARY selection (#8428). The production graph must integrate **both** E4 and+W15P:++- W15P adds a winit-owned PRIMARY path on the existing Wayland connection/event queue and+ per-seat lifecycle, using SCTK 0.19.2’s existing `PrimarySelectionManagerState`, device,+ source and offer support. PRIMARY is a distinct protocol object; do not bind a second+ regular `wl_data_device`.+- Egui 0.37 `get_primary`/`set_primary` routes through that path. E4 preserves password+ exclusion and does not reclaim ownership for an unchanged selection.+- FilmCraft also uses `arboard` directly for files/images (`apps/filmcraft/src/main.rs`+ `clipboard_media`). The arboard/smithay PRIMARY path is a measured fallback only if the+ winit path cannot meet a proven requirement; it is not the planned end state and it is not+ accepted merely by documenting a GNOME limitation.++Required native matrix, on X11 and Wayland, under wlroots (Hyprland/Sway), KWin and Mutter+with supported capabilities recorded:++- keyboard- and pointer-triggered selection plus middle-click paste at the clicked position.+ A PRIMARY request uses a fresh serial from the event that triggered it; the protocol+ explicitly allows pointer-driven selection and `set_selection` takes the triggering+ event's serial. Do not impose a keyboard-only serial rule;+- serial freshness, owner/seat changes, empty/absent offers, self-paste;+- password selection never offered;+- unchanged selection does not reclaim ownership;+- bounded asynchronous transfer: total deadline **2 s**, **16 MiB** cap, at most **4 read+ workers** and **2 writer threads** with queue depth **8**. Copy/PRIMARY ownership claims+ stay synchronous on the fresh triggering input turn (validate serial/seat, reserve bytes,+ create the source, call `set_selection`); only pipe serving and potentially blocking reads+ are asynchronous;+- a caller-owned live completion handle records the target window, input generation and an+ owner-specific waker, wakes only that viewport, and is held weakly by workers. Canceled,+ stale or superseded results are discarded and release their resources; no arbitrary+ first-seat fallback;+- slow, trickling, oversized, canceled and failed transfers release/complete exactly once;+- text copy/cut/paste and Paste/Paste Insert/Paste Attributes;+- file list and image paste through arboard, not duplicated by egui’s image paste;+- Windows `Ctrl+Insert`, `Shift+Insert`, `Shift+Delete` still map through+ `clipboard_events_as_keys`;+- `Event::PasteImage` maps to `Key::V` and does not produce two Paste commands.++## 8. Panels, geometry, docking, viewports and GPU resources++- `dock_ui.rs:190` `dock_area` calls `dock::layout_with_actions` for a manual rect tree, then+ `panel_body` (`:144`) creates `ui.new_child(... id_salt(...))` and sets clip rects. 0.37’s+ `Panel` API is not used; keep the manual layout, but verify that `Ui::new_child`/`scope_id`+ and the improved panel clip rect (#8562) do not change body rects.+- Floating groups use `egui::Area` with `Order::Middle`; layer order is read through+ `ctx.memory(|m| m.layer_ids())` (`dock_ui.rs:173` `floating_order`). Check the 0.37 layer+ iteration API and z-order after the bump; `ui_dock_resize.rs` and `shared_docking_ui.rs`+ cover focus, resize, detach, close/reopen and tab reorder.+- `dock.rs` draws custom tabs and registers automation ids. Keep stable ids+ (`panel.tab.*`, `timeline.tab.*`, `panel.menu.*`, `panel.float.*.resize`) and use+ `Role::Tab`/`Role::Button` semantics. The `Tabs` tab strip is not an `egui::TabBar`; do not+ replace it.+- `ViewportCommand` usage remains root-only: `Close`, `InnerSize`, `Focus`, `CancelClose`,+ `Maximized`, `Fullscreen`, `StartDrag`, `CursorPosition`, `Screenshot`, and the new+ `RequestPaintWhileHidden` for hidden composition stages. `ui.resize` and `ui.focus`+ control methods keep their behavior; `control_input_only` must still preserve close and+ viewport lifecycle metadata.+- GPU: `FilmcraftApp::set_wgpu` receives `CreationContext::wgpu_render_state`;+ `TextureHandle` and `GpuState`/`uploadedBytes` remain. `egui-wgpu` fork E2/E3 add surface+ fitting and error scopes; they are relevant to large/odd windows. Do not change the+ FilmCraft `wgpu 30.0.1` pin or the GPU compositor in the migration PR. The candidate’s own+ lock resolves `wgpu 30.0.0`; FilmCraft’s lock is authoritative. Record the actual resolved+ version and prove there is one source; do not claim the candidate lock’s version.+ `perf.stats` `gpu.uploadedBytes`, transitions, `submitMs` and frame-cache counters are the+ upload/GPU observables.++## 9. Commands, undo, save and reopen++The public contracts are:++- every interactive action is a command registered in `crates/engine`; UI, CLI, MCP and the+ control channel use the same ids;+- `menus::invoke` dispatches UI-only commands and engine commands;+- drag gestures are one undo step via `begin_press` and `cancel_value_drag`;+- `file.save`, `file.saveAs`, `file.open`, `file.closeProject`, `file.revert` and recovery are+ unchanged;+- UI state (tool, workspace, dock layout, zoom, scroll, monitor settings) is serde in+ `crates/ui-egui/src/state.rs`; project state is not UI state.++Migration rules:++- `begin_press` runs in UI pass 0 before any UI; `cancel_value_drag` runs once after the+ final UI pass using the pass-0 Escape latch (§4.4).+- Input-driven UI mutations dispatch once in pass 0; actions that must see final layout are+ queued and drained on the first non-discarded pass. Engine commands from control/MCP/CLI+ remain one-shot channel work in logic.+- A forced two-pass click adds exactly one undo step and one project revision. A forced+ two-pass click on a first-show `Grid` does the same. A forced discard during a drag with+ Escape cancels once.+- Save/reopen preserves an edit, an effect, a caption, and the dock/tab layout. Existing+ `timeline_tabs_ui.rs:258` and `scripted.rs:548` patterns are the starting point; add an+ effect/trim/save/reopen assertion and compare `sequence.inspect` and `project.inspect`.++## 10. Fork and vendor patch provenance++FilmCraft has no vendor directory. The suite forks carry behavior that FilmCraft either uses+or must consciously not use. Keep the pins; do not delete unrelated fixes. The tables below+name the aiongg research candidate for provenance only; production pins are G-PINS.++### 10.1 `aiongg/egui` `craft/0.37` (`a4f9a17f`, research)++| Patch | Decision in this plan | Validation |+|---|---|---|+| E2+E3 egui-wgpu surface fit/error scopes | Keep; use for large windows and odd surfaces | Windows/Linux resize/VM; `ui.resize` to a large size; no `Wgpu` error |+| E4 Wayland clipboard/PRIMARY | Keep; must be paired with W15P; the filmcraft#1115 problem is exactly this | Hyprland/KWin/Mutter copy/paste, PRIMARY matrix, file/image paste |+| E5, E8, E12, E13, E14, E15, E16, E17, E20 | Keep; use them; remove FilmCraft’s manual bidi | Arabic/Hebrew captions, editing, alignment, screenshots |+| E6, E21 IME | Keep; E21 alone is incoming only; E21b is mandatory | native IME rows plus outgoing-state tests |+| E7, E19 non-Latin shortcuts and P7 held-key pairing | Keep; adapt `handle_shortcuts` to Latin-layout chars; retain the emitted egui key identity for a held physical key across layout/modifier changes and clear it on focus loss/IME/destruction | kittest + native layouts, repeat/unidentified keys |+| E9 RTL UI mirroring | Keep in fork but do not enable `Style::right_to_left` | no RTL UI language yet |+| E10 web key/lang fixes | Keep; test browser IME and named keys | `smoke.mjs` + manual browser |+| E11 vello_cpu multithreading | Not exercised by FilmCraft; no local feature change | none |+| E1 viewport hooks | Not used by FilmCraft; keep the fork patch | no FilmCraft test |+| E18 `Frame::set_ui_language` | Use with `ctx.set_language` | language switch + AccessKit root |+| E15 `LineBreaker`/`LayoutJob::language` | Optional; use only if document line breaking needs it | caption wrapping tests |+| E21b/P7b outgoing IME surrounding text (P7b) | **Required new prerequisite**: the complete shared owner/support/serial contract, 4000-byte bounded payload without a full-document copy, TextEdit producer, Film graphics adapter and Wayland delivery | §7.2 tests; native Wayland trace |+| P7c selected #8763/#8748 fixes | P7c owns the selected, tested #8763 selection-action and #8748 hidden parent/child fixes. #8764 remains an unmerged proposal at `6eb460a2a6d537d312a80579cb801895509deaed`, not a release fix | selection/pointer/keyboard and hidden-parent regressions |++There is no E22. Do not invent fork APIs. A local workaround for #8763 needs a specific+reason and removal condition.++### 10.2 `aiongg/winit` `craft/0.30.13-lang` (`8b35388b`, research)++Keep the whole pinned branch because E4/E19/E21/E21b require W15/W15P/W25/W26/W27,+including the bounded W15P transfer path and the W27 owner/support lifecycle. For FilmCraft,+exercise at least:++- W1 mixed-DPI window rect; W3/W4 Windows IME/hidden maximized; W5/W20/W21 X11 IME;+ W6-W10 macOS IME; W11 X11 DPI; W12 macOS titlebar drag; W13 Wayland scroll phase;+ W15 Wayland drops/clipboard; W15P PRIMARY; W18/W19 Windows IME; W22-W27 language/IME.+- W15P is required with E4 as described in §7.3, including per-seat lifecycle, password+ exclusion, unchanged-owner behavior and slow/canceled transfer tests.+- W14 macOS cancelable termination is opt-in; FilmCraft does not call that platform extension,+ and its own close interception remains.+- Do not enable W16 pinch/rotation or tablet input; no `craft-tablet` dependency exists.++If the suite later replaces these forks with upstream releases containing the fixes, drop the+corresponding patch rows only after the same tests pass; do not remove a patch just because a+release number moved.++### 10.3 `craft-libs` port++Port only the selected PR-199 API hunks (`8614e4a`) and README changes (`1764bca`) onto the+current published `4919088` tree. Preserve newer security/settings/docking/printing fixes,+including the protected-group docking tests. Never merge `b68de8c` or `ec8840a` as trees. The+CL-2/CL-2F helper is a separate reviewed addition, not part of the stale PR tree.++## 11. Tests and observable assertions++### 11.1 Required repository gates (managed, proposed)++Every new host build/test and owned-VM command must use+`maintenance/task.py run/status/finish` with its own task, job ID, source and evidence. The+commands below are proposals for the parent to submit; they were not executed during this+planning pass. Capacity must be inspected first; the suite snapshot had less than one default+64 GiB build reservation available after existing reservations.++```sh+python3 /home/codex/work/maintenance/task.py run \+ --job-id filmcraft-egui037-ci-01 --kind build \+ --task filmcraft-egui037-migration \+ --source /home/codex/work/CraftApps/egui037-migration-20261022/filmcraft-implementation \+ --evidence /home/codex/work/ssd2/task-evidence/egui037-migration-20261022/filmcraft \+ -- cargo xtask ci+python3 /home/codex/work/maintenance/task.py status filmcraft-egui037-ci-01 --tail-bytes 8192+python3 /home/codex/work/maintenance/task.py finish filmcraft-egui037-ci-01 --artifact-manifest /home/codex/work/ssd2/task-evidence/egui037-migration-20261022/filmcraft/artifacts.json+# after inspecting the plan and preserving evidence:+python3 /home/codex/work/maintenance/task.py finish filmcraft-egui037-ci-01 \+ --artifact-manifest /home/codex/work/ssd2/task-evidence/egui037-migration-20261022/filmcraft/artifacts.json \+ --apply --owner-confirmed --checks-complete --evidence-preserved+python3 /home/codex/work/maintenance/task.py status filmcraft-egui037-ci-01 --tail-bytes 8192+```++Every job uses one unique resource task/fresh job ID/`--source`/`--evidence`; poll `status`+until both the command and the finish outcome are known, and never treat `ok: true` alone as+success.++`cargo xtask ci` already runs fmt, clippy, tests, layers, assets and wasm; keep it as the+authoritative gate. Also run, as separate managed jobs where a selected feature is not in+default CI:++- `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`,+ `cargo test --workspace`, `cargo xtask layers`, `cargo xtask assets`, `cargo xtask wasm`;+- with and without `CRAFT_FONTS_DIR` (pinned craft-fonts `abb83316d96aa59c1cf64784289e378fe9fa5695`);+- `FILMCRAFT_REQUIRE_ORACLES=1` when ffmpeg is available;+- `cargo metadata --locked`, the graph checks from §3.4, and the native `clipboard` ++ `monochrome_emoji_fonts` feature assertions.++Strict kittest naming and glyph behavior is part of the first green compatibility stage.+Do not add a global `allow`/disable for missing names or missing glyphs. If a name/glyph is+missing, fix the widget or fixture.++**Font features do not propagate through kittest.** `egui_kittest`'s normal `[dependencies]+egui` uses `default-features = false`; only kittest's own `[dev-dependencies]` enable+`default_fonts` and `monochrome_emoji_fonts`, and a dependency's dev-dependencies do not+propagate into a consumer. Every kittest/FilmCraft test root that needs the bundled faces must+enable those egui features explicitly or install controlled fonts, and each actual graph must+be inspected. The production feature policy in §3.5 does not reach the harness by itself.++Windows uses a uniquely owned clone and the VM run/status/finish workflow, with the clone’s+`Build-DesignCraft.ps1` equivalent for FilmCraft or the repository’s documented build helper.+The baseline VM is not adopted or reused across tasks.++### 11.2 UI, lifecycle and workflow tests++Existing anchors to extend or keep:++- `crates/ui-egui/tests/scripted.rs` `Driver::demo`, `frames`, `call`, `ok`, `exec`; add+ multi-pass and save/reopen cases.+- `crates/ui-egui/tests/ui_control_input.rs:153` screenshot/control isolation.+- `crates/ui-egui/tests/ui_dock_resize.rs`, `shared_docking_ui.rs`, `timeline_tabs_ui.rs`.+- `crates/ui-egui/tests/interface_zoom_ui.rs`, `settings_ui.rs`, `panels_ui.rs`,+ `monitor_geometry.rs`, `timeline_trim_ui.rs`, `clipboard_paste_ui.rs`, `project_panel_ui.rs`.+- `crates/ui-egui/tests/perf_ui.rs` monitor lag.+- `crates/ui-egui/tests/robustness_ui.rs` hostile UI state.++New/extended assertions:++1. **Lifecycle:** visible single/multipass; logic called per pass but background effects are+ idempotent; hidden `run_logic` ticks advance playback/autosave/workers/jobs without reading+ input; forced hidden paint with a screenshot delivers an image; buffered input survives a+ hidden tick and is handled once on the next visible pass; repeated hidden logic ticks keep+ one synthetic gesture step pending and do not collapse press/release; a forced two-pass+ click (including a first-show `Grid`) adds exactly one undo step; Escape drag cancels once.+2. **Root UI/geometry:** at 1600×980 and 1920×1080, `ui.elements` rects for+ `panel.Timeline`, `panel.Program`, `panel.Project`, `tools.Razor`, dock split handles and+ floating grips match the baseline within 1 point; panel bodies never overlap the+ header/status bar; tab overflow still reaches every tab.+3. **Screenshot callback:** two queued `ui.screenshot` requests with different panel crops+ return matching images/paths; a hidden screenshot delivers both when already issued and+ when still settling (queued-but-not-issued), using `RequestPaintWhileHidden` in the latter+ case; the weak callback wakes the live slot's waker after unlocking and never wakes itself;+ a callback after timeout/close is ignored; the completion slot is dropped exactly once; any+ resize/DPI/zoom change, including a change back, either retries within the deadline or+ errors, never pairs old pixels with new geometry. Native VM test; headless test of the+ correlation helper.+4. **Scroll header sync:** after horizontal scroll, media-browser/project-list headers align+ with rows (≤1 point); after rubber-band overshoot, the header uses clamped offset.+5. **Accessibility:** for the demo workspace assert `Role::Tab`/selected on panel tabs,+ `Role::Button`/selected on tool buttons, `Role::Button` "Resize panel" on the floating grip,+ `Role::Splitter` on dock split dividers, and `Role::TextInput` with a non-empty accessible+ name on caption/metadata/search fields. Use `Harness::get_by_label`,+ `accesskit_node().role()`, `label()`, `toggled()`. All 56 `TextEdit` sites must be named;+ add a negative control that removes a name and fails the strict kittest gate.+6. **Fonts:** with `CRAFT_FONTS_DIR` and without, assert Japanese/Chinese/Korean/Arabic/Hebrew+ sample text produces no missing-glyph UV and preserves the expected family/weight; assert+ `✔ ✓ ✖ ⚡ ⚠ ⚙ ♪ ☑` coverage; assert a non-zero TTC face index survives `FontData`+ construction. Fixtures and licences are pinned in §6.1.+7. **RTL:** Arabic/Hebrew caption visual order, right alignment, bracket mirroring, digits and+ a mixed LTR paragraph; editing caret/Home/End/Delete; compare glyph order, not just “text+ present”.+8. **IME/clipboard:** outgoing surrounding text after commit/deletion, preedit exclusion,+ grapheme/byte boundaries, password clearing, same-window switch, two windows, late serial,+ owner generation present when unavailable, available-empty vs unavailable and a+ pass-1-text/pass-2-`None` final pass; synthetic `PasteImage` maps to Paste once; native+ PRIMARY (keyboard and pointer serials, bounded transfer) and text/file/image paste matrix+ from §7.3.+9. **Save/reopen:** edit + effect + caption + tab layout, `file.saveAs`, `file.open`, equal+ `sequence.inspect`/`project.inspect` and reopened tab order; undo/redo count exactly.+10. **Mutation/negative probes:** a deliberately broken test-only flag that repeats a queued+ action must fail the one-undo-step assertion; a screenshot with a wrong token/slot must not+ be delivered to the wrong request; a scroll offset beyond content must clamp; a font face+ with the wrong index must produce a distinct glyph or missing glyph and fail the coverage+ test; removing an accessible name must fail strict kittest.++### 11.3 Visual comparisons and tolerances++Do not add committed screenshots unless they are needed; if added, they are original+FilmCraft captures and need `.attribution` sidecars and `ATTRIBUTION.md` rows+(`cargo xtask assets`). Prefer writing review PNGs to the durable evidence directory.++For before/after review:++- workspace chrome is custom-painted: mask only volatile monitor/video regions; use+ PSNR ≥ 45 dB, max channel difference ≤ 12, p99 ≤ 2 for unchanged regions, and exact layout+ rects within 1 point. These thresholds are provisional until the baseline report records+ the noise floor of an unchanged build; record the reference measurement that sets them.+- egui-drawn dialogs may move/resize because 0.37 changes button spacing and corner radius+ (#8617, #8445): mask the dialog region or use p99 ≤ 8/max ≤ 32, and require human visual+ review; do not auto-bless a changed golden.+- Arabic/Hebrew captions get both a pixel check and a glyph-order assertion; pixel-only+ comparison would hide double reversal.+- A changed golden is never accepted merely to make CI pass; re-run and review.++### 11.4 Native and browser workflows++Native Linux (proposed, through the managed adapter; no raw `cargo run` outside task.py):++```sh+python3 /home/codex/work/maintenance/task.py run \+ --job-id filmcraft-egui037-linux-ui-01 --kind build \+ --task filmcraft-egui037-migration \+ --source /home/codex/work/CraftApps/egui037-migration-20261022/filmcraft-implementation \+ --evidence /home/codex/work/ssd2/task-evidence/egui037-migration-20261022/filmcraft \+ -- cargo run --release -p filmcraft -- --control 9876+python3 /home/codex/work/maintenance/task.py status filmcraft-egui037-linux-ui-01 --tail-bytes 8192+# after the UI workflow, evidence capture and review:+python3 /home/codex/work/maintenance/task.py finish filmcraft-egui037-linux-ui-01 \+ --apply --owner-confirmed --checks-complete --evidence-preserved+python3 /home/codex/work/maintenance/task.py status filmcraft-egui037-linux-ui-01 --tail-bytes 8192+```++Drive `ui.inspect`, `ui.screenshot`, `ui.resize`, dock actions, clipboard/PRIMARY, and review+every PNG. Repeat under X11 and Wayland (and Hyprland for E4/W15P). Native Windows through a+uniquely owned clone: build the task checkout, run `filmcraft-ui-egui` UI tests, launch with+`--control`, capture screenshots, exercise IME and DX12/software graphics modes. macOS: real+hardware for Cmd shortcuts, titlebar drag, Japanese/Korean IME and header drag; if no Mac is+available, record macOS as unresolved, not passed.++Browser (proposed; `cargo xtask web --serve` is a long-running server, so all steps run in+one managed `task.py run` job with a trap that stops the server, then `status` and an attested+`finish` after evidence review):++```sh+# payload inside the managed job, with exact --task/--source/--evidence and a fresh job ID:+cargo xtask web --serve 8765 &+SERVER=$!+trap 'kill "$SERVER" 2>/dev/null' EXIT+ffmpeg -f lavfi -i testsrc2=size=640x360:rate=30 -f lavfi -i sine -t 3 -c:v libx264 -pix_fmt yuv420p -c:a aac target/web/dist/web-test.mp4+node apps/filmcraft-web/tests/smoke.mjs --url http://127.0.0.1:8765/ --media web-test.mp4 --out target/web/smoke+```++Run WebGPU and `?webgl`; inspect `report.json` and steps `01-demo` … `05-modes`; check+`filmcraft.info()` for backend/compositor. A wasm compile is not runtime evidence; headless+browser tests do not prove native focus/IME/file pickers.++### 11.5 Environment provisioning gates++No current runtime acceptance exists. The following are gates, not passes:++| Environment | Current evidence | Required before claiming a pass |+|---|---|---|+| Linux X11 | No inherited `DISPLAY`; no Xvfb/window manager observed | Provision an isolated display/window manager, record versions, qualify native focus/clipboard/PRIMARY |+| Linux Wayland | No inherited `WAYLAND_DISPLAY`; no compositor/input-method observed | Provision Weston/Sway/Hyprland/KWin/Mutter and an IME, record capabilities; run text-input and PRIMARY matrix |+| Linux GPU | Parent inspection found i915 PCI `8086:3E96` and readable/writable `/dev/dri/renderD128`; worker sandbox may hide it; **do not claim the server has no GPU** | Managed renderer/device probe must identify the actual driver/backend; access alone is not GPU acceptance |+| Windows | Sealed baseline uses Microsoft Basic Render Driver; a full clone may not fit current capacity | Allocate a unique full clone or a baseline-backed overlay with an adequate reservation; run visible edited/saved/reopened workflows, IME, DX12/software |+| Browser | Wasm compile is not runtime evidence | Pin browser and adapter; run interactive WebGPU and WebGL2 fixtures; record raw/compressed wasm sizes and backend identity |+| macOS / physical Windows audio/video | No qualified environment in this task | Real hardware access and owned evidence; software VM results do not qualify these rows |++These rows remain explicit rollout blockers where unavailable. Do not report a GPU absent,+a current runtime pass, or a platform gate as satisfied from source inspection alone.++## 12. Performance: baseline, paired runs, thresholds++### 12.1 Baseline before production edits++Record before changing production code, on the exact baseline SHA and lockfile, as managed+`task.py run` jobs (fresh job ID, exact `--source`/`--evidence`, `status`, then attested+`finish --apply`). Submit each payload as+`task.py run --job-id <unique> --kind build --task filmcraft-egui037-migration --source+<checkout> --evidence <evidence> -- <payload>`; the commands below are payloads, not a+raw-command exception:++- `cargo xtask bench` with `--sections timeline,playback,scrub`, `--label+ filmcraft-egui036-baseline`; GPU and `--cpu` runs. The timeline harness currently defaults+ to 120 frames per view, 8 warmups (the `--repeat` value is a **run count**, not a sample+ count) and emits only p50/p95, so extend `crates/ui-egui/examples/bench/sections.rs` to+ accept the frame/warmup counts and emit p99 with exact sample counts **before** using it as+ acceptance evidence. Run at least 10 warmups, 30 timed iterations per steady configuration+ and at least 1,000 actual captured frames per view for any p99;+- `cargo xtask bench-playback` for `demo`, `stack3`, `stack3-blend`, `h264-1080`, `h264-2160`,+ `after-preview`, `seek-storm`, `--res full,half`, GPU and `--cpu`, with 10 warmups / 30+ timed iterations per configuration where the harness supports them; p99 requires at least+ 1,000 frames;+- native idle: no playback, no input, 60 s; record repaint count, process CPU, RSS;+- startup: first present and `Renderer::new` timing on Windows DX12 and Linux Vulkan, from+ 20 fresh processes;+- `perf.stats` before/after a fixed operation script (open demo, razor, undo, apply effect,+ play 5 s, screenshot);+- wasm raw and compressed sizes for the exact feature set.++Record: exact SHA, `Cargo.lock` hash, feature set, `CRAFT_FONTS_DIR` revision, fixture names+and hashes, OS/driver, GPU adapter/backend, DPI/scale factor, viewport size, profile (release),+thread count, theme, warmups and repetitions, raw samples, median/p95/p99, peak RSS, idle+repaint/CPU, operation latency, `gpu.uploadedBytes`, frame-cache entries, shapes/vertices, and+load average. For allocation counts use `heaptrack` or `valgrind --tool=massif` on the Linux+bench process; record peak/total allocations separately from product metrics. GPU uploads are+reported by `perf.stats` (`gpu.uploadedBytes`) and frame-cache counters.++### 12.2 Paired candidate runs++Run the same commands against the candidate on the same machine and environment, alternating+baseline/candidate where possible. Separate software-renderer (`--cpu`, llvmpipe/WARP) from+real-GPU results; do not mix rows. Never benchmark concurrently with builds or another noisy+workload and claim a small improvement. Preserve raw samples and the exact source/lock+identity for both sides.++Where the operation is equivalent, include a **stock 0.37 control** alongside 0.36 and the+selected fork. Fork-only app code need not compile unchanged on stock; use the same operation+in a pinned minimal adapter/harness and explain remaining semantic differences. Record all+three source/lock identities; unavailable equivalence is an attribution limitation, not proof+that an upstream regression is unavoidable.++### 12.3 Predefined thresholds and noise policy++These are the shared suite minimums; FilmCraft may tighten them, never silently loosen them.+The stock-0.37 equivalent control and the first baseline report are required before any+regression claim; thresholds and goldens are never auto-widened or auto-blessed to make a run+pass.++- **Sampling:** at least 10 warmups and 30 timed iterations for steady operations; at least 20+ fresh processes for startup; at least **1,000 actual captured frames** per configuration for+ any frame-distribution p99. A p99 from 20/30/50 samples is not a tail estimate. Report the+ exact frame count and sample count in the report schema.+- **Timeline UI** (headless kittest, 1000 clips/20 tracks, 1920×1080): median update/tessellation+ ≤ +5%, p95 ≤ +10%, p99 reported and reviewed. Vertices/shapes must not grow without+ explanation.+- **Playback CPU** (`bench-playback` CPU ms/frame, worker/source columns): ≤ +3% median;+ shown/dropped may vary with load and is not a gate alone.+- **Peak RSS:** FilmCraft gate is ≤ +5% for the same scenario after subtracting the measured+ noise floor; investigate any repeatable increase above the floor. Report absolute MB.+- **Idle:** no extra repaint requests and no extra CPU when nothing is playing; a hidden window+ keeps auto-save/playback semantics without busy-looping.+- **Startup:** report first-present and `Renderer::new`; on Windows DX12 a +20 ms median or+ more is a regression to investigate against #8736; do not silently accept it.+- **Wasm:** record raw and compressed sizes; a size regression is reviewed, not hidden by a+ compile-only check.++If a threshold is exceeded, re-run alternating; if still exceeded, profile (`perf`, `tracy`,+`heaptrack`/massif) and report. Never auto-accept a changed golden or call compile time UI+performance.++### 12.4 Separate workload rows++Do not merge these into one number:++- **#8731 text tessellation:** plain-text timeline/fixture workload (1000 clips/20 tracks,+ 1920×1080), compare unchanged 0.36, stock 0.37 and the fork; measure tessellation time and+ text-heavy frame time separately. If confirmed, evaluate a row-level fast path and cached+ color-glyph metadata; test mixed/color rows. Do not bless a regression.+- **#8736 DX12 FXC shader compile:** Windows VM, measure `Renderer::new`/pipeline creation and+ first present separately from steady frames, with predictable filtering disabled. Compare an+ override-constant design with semantically equivalent wrap arithmetic only if needed;+ clamp-only is not a valid Repeat/MirroredRepeat fix.+- **#8512 system-font startup:** measure discovery/startup separately. The migration keeps+ `system_fonts` off, so this is a controlled opt-in experiment, not a default change; preserve+ glyph coverage and record provider inventory.+- **Wasm/browser:** raw and compressed wasm size plus WebGPU/WebGL2 runtime frame timings from+ the pinned browser environment; compile time is not UI performance.++## 13. Implementation PR stages and dependency DAG++No production stock-0.37 stage exists. The first production stage is the coherent fork graph.++| Stage | Contents | Depends on | Rollback |+|---|---|---|---|+| P0 | This plan only; no code | — | delete document |+| **P1** | **Atomic compatibility landing on the final fork graph.** Manifests/lockfile: final approved `storytold/egui` P8 + `storytold/winit` pins, final `storytold/craft-libs` revision (CL-1 + CL-2F), explicit `default_fonts`, `monochrome_emoji_fonts`, native `clipboard`, no `system_fonts`/`links`. API migration: `FontData`, `Role`/names, `ScrollArea`, `MouseWheelSource`, `run_ui` signature, `Id::unique`, screenshot callback + CL-2 helper, `PasteImage`, E21b custom IME adapter, bounded E4/W15P clipboard/PRIMARY routing, lifecycle split/multi-pass queue, strict kittest names/glyphs, and **removal of the manual `rtl::Lines` reversal and its unit tests**. Tests from §11. | P0; **G-PINS**, **G-CL2F**, published/reachable pins; capacity for gates | revert to the coherent 0.36.2 graph (`Cargo.toml`/`Cargo.lock` and source); keep old craft-libs `5c874d51` and `craft-docpath 82a24b0` |+| P2 | Language and the full native input matrix: Latin-layout shortcuts, `ctx.set_language`/`set_ui_language`, and the full W15P/E4 PRIMARY and E21b native rows against the P1 integration. Fork bidi is already active in P1; P2 does not introduce a second bidi state. | P1 (fork already pinned) | revert P2; restore prior language/input behavior without changing the P1 dependency graph or re-introducing manual reversal |+| P3 | Accessibility semantics beyond first-green naming: radio-group/tool semantics, richer role/value/label assertions, AccessKit language screenshots. | P1 | revert P3 |+| P4 | Evidence hardening: visual/geometry/screenshot regression harness, mutation probes, performance baseline/candidate and stock control, wasm sizes, environment provisioning. | P1–P3 | revert P4; keep earlier behavior |+| P5 | Documentation/rollout notes and optional measured experiments (`system_fonts`, color emoji, macOS). | P4 | revert P5 |++Publication is not part of P0. Each future push/new PR requires fresh direct human approval+after the parent shows the exact contents and validation. Do not include agent/model/tool+signatures in PR text or commits.++### Rollback set++Keep the old coherent set recoverable:++- `egui/eframe/egui_kittest = 0.36.2`;+- `craft-ui` rev `5c874d51eeb3de70e735c8ce87a59a7dedd47675`;+- `craft-docpath` rev `82a24b006eefa036b43c09a67fb9a3fbd17ffe63`;+- registry `winit 0.30.13`, `wgpu 30.0.1`.++A rollback is `git revert` of the stage commits plus restoring the baseline+`Cargo.toml`/`Cargo.lock` (or `git checkout abf44fda -- Cargo.toml Cargo.lock` after reverting+source changes). Do not keep a machine-local path patch as a fallback. A rollback rehearsal+uses the preserved baseline executable/source and a separate managed allocation.++## 14. CI, compatibility and publication checks++- `.github/workflows/ci.yml` runs `cargo xtask ci` with pinned `CRAFT_FONTS_REF`; add the pin+ checks from §3.4 and a `cargo metadata --locked` step.+- Keep `freebsd.yml`’s skip-tests policy and `windows-arm64.yml` as-is; do not weaken them.+- `cargo xtask wasm` must still check `filmcraft-ui-egui` and `filmcraft-web`; `egui_kittest`+ is a dev dependency and remains native-only.+- The web crate’s `wasm-bindgen` exact pin (`=0.2.129`) must match the installed CLI. The+ candidate’s own lock uses `wasm-bindgen 0.2.126` and `web-sys 0.3.103`; FilmCraft currently+ pins `web-sys 0.3.106` and `wasm-bindgen 0.2.129`. The `0.2`/`0.3` ranges are compatible,+ but the final FilmCraft lock is authoritative: record the resolved versions and run+ `wasm-bindgen --version` before `cargo xtask web`.+- `rfd 0.17`, `arboard 3.6.1`, `wgpu 30.0.1`, `accesskit 0.25`/`0.24` transitive and `winit+ 0.30.13` compatibility were checked from manifests; a fresh `cargo metadata --locked` and a+ clean lockfile resolution are still required.+- The candidate’s own lock resolves `wgpu 30.0.0`; FilmCraft pins 30.0.1. Record the actual+ resolved candidate/FilmCraft version in the evidence and ensure one source; do not claim the+ candidate lock is FilmCraft’s.+- New 0.37 dependencies include `wl-clipboard-rs`, `tree_magic_mini`, `petgraph`, `nom`,+ `send_wrapper`, `unicode-properties`, `vello_cpu 0.2`, `glifo 0.3`, `kittest 0.5` and updated+ `accesskit*`/`phf`. Review their licences (all expected MIT/Apache-2.0/BSD/ISC); no GPL/LGPL+ may enter.+- Do not commit local screenshots as assets without sidecars/index rows. Keep review PNGs+ under the task evidence directory.+- No agent/model/tool attribution in PR titles, descriptions, commits or comments. Contributor+ credit stays username-only (`@skylartaylor`); do not add a name entry.++## 15. Blocking unknowns and acceptance criteria++These are gates, not future nice-to-haves. A failed or unavailable gate is an explicit blocker,+not a passing result.++1. **G-PINS — production fork pins.** The reviewed, published, immutable `storytold/egui`+ commit (E1-E21 + E21b/P7b + selected #8763/#8748 fixes) and `storytold/winit` commit+ (W15P + W27 + required W1-W27 behavior) are not known at planning time. Do not invent a SHA,+ do not use an aiongg branch as a production pin, and do not land a stock-0.37 intermediate.+ The exact SHAs, feature sets and provenance must be recorded before P1.+2. **G-CL2F — shared capture helper.** `craft-libs` must publish the CL-2 helper, DesignCraft+ and GridCraft adapters must be reviewed against it, and CL-2F must freeze the API before+ FilmCraft pins the revision. A branch head or path dependency is not acceptable.+3. **G-CRAFT-LIBS — shared baseline and port.** The final published `craft-libs` revision must+ build on the merged PR #199 base `3832c47ef68a0e6214f2c1e85f3526b6adcb686e` with the+ protected-group docking fix and lazy printing preserved; the PR-199 hunks+ (`8614e4a`/README `1764bca`) are historical provenance. `5c874d51` is the old FilmCraft+ manifest pin; `4919088` is historical GitHub main. `craft-docpath` stays at `82a24b0`+ unless a concrete cross-type reason appears.+4. **G-IME — native IME and E21b.** E21b/P7b must exist in the pinned fork with the complete+ shared contract: owner generation present even when `Unavailable`, available-empty distinct+ and explicitly sent, committed W27 disable/enable transitions with cache clear,+ authoritative completed-pass `None`, current-epoch serial-mismatch edits applied once with+ outgoing state deferred, and a 4000-byte payload extracted without a full-document copy.+ The FilmCraft graphics adapter must supply logical model/preedit/UTF-8 bytes, and Windows+ Japanese/Korean, X11 Vietnamese, Wayland text-input-v3 and macOS rows must run on real+ environments. No headless test is a substitute. macOS without hardware is explicitly+ unresolved.+5. **G-PRIMARY — W15P + E4.** The winit-owned PRIMARY path must be integrated, with native+ per-seat keyboard- **and pointer-triggered** selection using a fresh triggering serial,+ owner/seat changes, empty/absent offers, password exclusion, unchanged-owner non-reclaim,+ self-paste, and slow/trickling/oversized/canceled transfers under wlroots, KWin and Mutter.+ The transfer path is bounded (2 s total deadline, 16 MiB, 4 read workers, 2 writers with+ queue depth 8), claims ownership synchronously on the fresh input turn, serves+ asynchronously, and discards stale/canceled completions. The arboard/smithay path is a+ measured fallback only.+6. **G-SEL — P7c #8763/#8748.** Reproduce selection loss with a caption/metadata field and a+ custom toolbar action; P7c owns the selected, tested #8763 and #8748 fixes. #8764 is an+ unmerged proposal, not a release fix. A local workaround needs a reason and removal+ condition.+7. **G-PERF — performance and stock control.** Baseline and candidate runs must meet §12+ sampling and thresholds, with separate #8731 text, #8736 DX12, #8512 font and wasm rows, and+ a stock-0.37 control where equivalent. Compile duration is not UI performance.+8. **G-ENV — real environments.** Linux X11/Wayland compositors and IME, a browser with a+ pinned adapter, a unique Windows clone, and macOS hardware must be provisioned. The i915+ device’s presence is availability evidence only; the worker sandbox may hide it. No current+ runtime pass is claimed.+9. **G-ACCESS — accessibility names and glyphs.** All 56 `TextEdit` sites and other input+ widgets have names; strict kittest naming/glyph behavior is green without a global disable;+ monochrome emoji coverage is asserted.+10. **G-LIFECYCLE — multi-pass audit.** The input-action design, Escape latch, monotonic+ deadlines, one-step synthetic gesture retention across hidden logic ticks, idempotent+ toast/settle counters and grep allow-list are implemented and tested; until then the+ one-action and hidden-work guarantees are not met.+11. **G-SCREENSHOT — capture matrix.** The callback is delivered for a visible capture and+ for a hidden capture, including queued-but-not-yet-issued settling; timeout/close/+ late-callback behavior is correct. The CL-2 slot holds the strong waker, the callback is+ weak and does not wake itself, and admission bounds four outstanding requests, 128 MiB per+ image and 256 MiB aggregate with checked `width * height * 4` before issue and after any+ resize/DPI/zoom epoch change (including a change back).+12. **G-RTL — bidi.** P1 must land the fork's E5/E12 together with the simplified+ `rtl::Lines`, and validate visual order/alignment/editing. Do not ship both the manual+ reorder and fork bidi, and do not leave the removal to P2.++## 16. Limitations of this planning pass++- No build, test, benchmark, screenshot or app launch was run. All behavior statements are+ source review and upstream documentation, not fresh validation. No command in §11 was+ executed.+- The historical compiler diagnostics are from an earlier checkout and only identify likely+ sites; current line numbers and new errors must be discovered by implementation gates.+- The production fork pins and the final `craft-libs` revision are unknown until the fork and+ shared helper are published; no SHA is invented.+- The i915 device was observed on the host but no display session is inherited and the worker+ sandbox may hide it. Windows baseline is software-rendered. macOS, browser runtime and real+ Wayland compositor behavior remain unproven until the environment gates run.+- The exact stock-0.37 control harness may need small adapters for fork-only operations; such+ differences are recorded as attribution limitations, not ignored.++## 17. Review finding dispositions++This table is an index; the body sections above are authoritative.++| Finding | Disposition | Where resolved |+|---|---|---|+| F1 deferred-action clearing loses clicks | **Accepted.** No clear on pass 1+; input actions dispatch once in the pass with events; deferred actions persist and drain on the first non-discarded pass; duplicates coalesce; no silent drop. | §4.4, §9, §11.2 |+| F2 Escape rollback cannot fire on a multi-pass frame | **Accepted.** Latch Escape and the undo mark in pass 0; apply once after the final pass. | §2.3, §4.4, §9 |+| F3 hidden window never presents | **Accepted.** The screenshot command already requests paint while hidden; `RequestPaintWhileHidden` also covers queued-but-not-issued settling and other composition stages; timeout is not the normal hidden path; no visibility-based phase inference. | §4.2, §4.5, §11.2, §11.5 |+| F4 OS clipboard feature lost | **Accepted.** Add native `clipboard`; cross-application paste tests on X11/Wayland/Windows; web checked separately. | §3.5, §7.3, §11.1 |+| F5 stock 0.37 landable stage | **Accepted.** Stock is a local/CI comparison only; one coherent fork landing; final pins gated. | §3.2, §13 |+| F6 `default_fonts` not monochrome emoji | **Accepted.** Explicit `monochrome_emoji_fonts`, exact glyph set, screenshot diff. | §3.5, §6.1, §11.2 |+| F7 E21b/P7b IME gap | **Accepted.** Full owner/support/serial contract, 4000-byte no-full-copy payload, TextEdit producer, Film graphics adapter, tests; native rows required. | §7.2, §10.1, §11.2, §15 G-IME |+| F8 PRIMARY downgraded | **Accepted.** W15P + E4 required; keyboard/pointer serials, bounded transfer, native per-seat/password/unchanged-owner/slow-cancel matrix; arboard fallback measured only. | §7.3, §10.1-10.2, §15 G-PRIMARY |+| F9 effects catalogue incomplete | **Accepted.** Enumerates `trim.tick`, native menus, metadata/auto/sync sites, all monotonic deadline calls; trim idempotent; grep guard. | §2.3, §4.1, §4.6 |+| F10 performance protocol weak | **Accepted.** 10 warmups, 30 steady, 20 startup, ≥1,000 actual frames for p99; shared 5%/10%; stock control; separate #8731/#8736/#8512 rows; wasm sizes. | §12 |+| F11 unmanaged commands | **Accepted.** All validation uses `task.py run/status/finish` with task/source/evidence; proposals only. | §11.1, §11.4 |+| F12 EffectCraft reverse dependency absent | **Accepted.** Exact `2c5ba7a` pin, UI-free proof, separate branch retained, re-audit triggers. | §1.1 |+| F13 4919088 unpublished / PR 199 premise | **Premise rejected.** GitHub main verified `4919088`; stale `origin/main` `b1401e3` does not prove otherwise. Old `5c874d51` fetched; seven-file +607/−2 diff audited; printing and protected-group docking preserved; `craft-docpath` stays separate; PR 199 only hunks `8614e4a`/README `1764bca`. The actionable audit requirements are accepted. | §3.1, §10.3, §15 |+| F14 accessibility role contradiction | **Accepted.** Floating grip = `Button` "Resize panel"; dock split divider = `Splitter`; test updated once. | §5.3, §11.2 |+| F15 minor accuracy/robustness | **Accepted.** Catch-unwind latch; no `Window::show` in logic; wgpu/candidate versions stated; thresholds require a noise reference; strict kittest names are an ordering constraint. | §4.1, §4.2, §11.1, §11.3, §12.1, §14 |++### 17.1 Fresh v2 review findings++| Finding | Disposition | Where resolved |+|---|---|---|+| v2-1 P1 lands manual bidi reversal with fork bidi | **Accepted.** P1 now pins the fork, removes `rtl::Lines` reversal and its tests, and validates visual order; P2 no longer ships a second bidi state. | §6.3, §13, §15 G-RTL |+| v2-2 E21b contract incomplete | **Accepted.** Full owner/context identity, available-empty vs unavailable, committed W27 transitions, authoritative `None`, serial-mismatch-once/deferred-outgoing, no full-document copy. | §7.2, §10.1, §15 G-IME |+| v2-3 keyboard-only PRIMARY and no bounded transfer | **Accepted.** Keyboard and pointer triggering serials; 2 s/16 MiB/4 readers/2 writers/queue 8; synchronous claim, async serving, owner-specific waker, stale discard. | §7.3, §15 G-PRIMARY |+| v2-4 no screenshot wakeup/collection path | **Accepted.** Strong waker in the live slot, weak callback, unlock before wake, callback has no repaint path of its own; queued hidden requests use `RequestPaintWhileHidden`. | §3.3, §4.5, §15 G-SCREENSHOT |+| v2-5 performance commands contradict sampling rule | **Accepted.** Harness must emit p99 and exact counts, 1,000+ frames/10 warmups/30 iterations; `--repeat` is not a sample count. | §12.1, §12.3 |+| v2-6 validation mixes managed and raw commands | **Accepted.** Bench and browser payloads run inside `task.py run/status/finish`; the Linux UI job has an attested finish and the long-running server has a stop step. | §11.1, §11.4, §12.1 |+| v2-7 effect catalogue misses Toast and settle counters | **Accepted.** Toast uses monotonic time; settle counters are per rendered frame/pass identity; synthetic hook retains one step across hidden logic ticks. | §2.3, §4.1, §4.5, §15 G-LIFECYCLE |+| v2-8 consumer count and P7c traceability | **Accepted.** Fourteen capture consumers (eleven craft-ui + three local adapters); P7c explicitly owns #8763/#8748. | §3.3, §8, §10.1, §15 G-SEL |++## 18. Primary sources reviewed++- Upstream `egui 0.37.0` changelog and release commit `841a328b`; source inspected through+ `git -C /home/codex/work/CraftApps/egui037-migration-20261022/egui show 0.37.0:…`.+- Upstream API changes: emilk/egui#8489 (screenshot callback), #8555 (`WidgetType` -> `Role`),+ #8583 (`default_fonts` off), #8534 (Id deprecations), #8535 (`root_ui`), #8428 (PRIMARY),+ #8512 (system fonts), #8631/#8748 (logic-only/overdue windows), #8577 (bidi), #8731 (text+ tessellation), #8736 (DX12 shader compile), #8763 (TextEdit click-away) and proposed #8764+ (`6eb460a2a6d537d312a80579cb801895509deaed`, open/unmerged).+- Lifecycle source audit: `/home/codex/work/ssd2/task-evidence/egui037-migration-20261022/lifecycle-source-audit.md`.+- IME gap: `/home/codex/work/ssd2/task-evidence/egui037-migration-20261022/ime-surrounding-gap.md`,+ `.../winit-review-triage.md` for the W15P/W27/E21b serial and owner/support corrections, and+ egui plan §10.6 for pinned font fixtures.+- Shared baseline audit: `/home/codex/work/ssd2/task-evidence/egui037-migration-20261022/filmcraft-shared-baseline-audit.md`.+- Suite rollout: `craft-libs/docs/egui-037-suite-rollout.md` and+ `craft-libs/docs/egui-037-migration-plan.md` (CL-2/CL-2F, §7.8, §10.6).+- Fork provenance: `aiongg/egui` `craft/0.37` `PATCHES.md` (E1-E21) and `aiongg/winit`+ `craft/0.30.13-lang` `PATCHES.md` (W1-W27), inspected read-only in+ `/home/codex/work/CraftApps/egui037-migration-20261022/{egui,winit}`.+- Shared migration: `storytold/craft-libs#199` (port hunks `8614e4a`, README `1764bca`;+ stale heads `b68de8c`/`ec8840a` are not mergeable trees), current main `4919088`, old+ FilmCraft pin `5c874d51`, language work `storytold/craft-libs#198`.+- Local evidence: `/home/codex/work/ssd2/task-evidence/craft-fork-plan-20261020/PLAN.md`,+ `/home/codex/work/ssd2/task-evidence/craft-fork-ai-lines-20261022/SURVEY.md`,+ `/home/codex/work/ssd2/task-evidence/craft-fork-egui037-20261021/RESULTS.md`,+ `/home/codex/work/ssd2/task-evidence/egui037-migration-20261022/upstream-discussions.json`,+ `upstream-8764-fresh.json`, `craft-ui-consumers-exact.json`.+- Repository rules and commands: `AGENTS.md`, `CLAUDE.md`, `docs/architecture.md`,+ `docs/testing.md`, `docs/web.md`, `docs/agents.md`, `.github/workflows/ci.yml`,+ `xtask/src/main.rs`.+++## 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.++The owned checkout's current branch HEAD is `fa550ce2d07bdfee6b1d7b6835e8abc8c6913d00`; the migration work is uncommitted on that base. The 2026-10-23 note that the checkout was fast-forwarded to `c5c16939896277ab332280a6d3f1d7283d0d0c4e` and earlier baseline SHAs above are retained as historical review evidence. Use the current HEAD and its exact manifest/lock hashes (table in §1) for local integration and paired measurements; remote main is not asserted here. The original refs remain reachable.++Preserve isolated MCP screenshot temporary directories and caller-path desktop captures; rejected synthetic gestures enqueue nothing (click 0–10, drag 2–1024). Retain the new typography/contrast/clip regressions and random benchmark output directories.++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.+++## Final source review repair — 2026-10-24++The reviewed cumulative source identity and two findings are preserved in the external+`final-landing/filmcraft-final-review.md/json` evidence. Same-owner application caret/selection+moves (pointer, keyboard, Select All and explicit gfxEdit offsets) and another field taking+focus now invalidate only a known active/terminal-pending graphics composition before its late+replacement can mutate the moved selection. Stable owner/generation identity is preserved;+commit-only input without an old composition and uninterrupted replacement chains stay valid.+A private one-shot interruption asks the platform to cancel the old composition and survives+discarded passes until a final observation. No public IME protocol was added.++Automation lookup now uses the current registry whenever it is populated, so a removed control+cannot resolve to its previous-pass coordinates. The pre-draw previous-registry fallback stays.+New regressions cover removed IDs, real pointer press/release plus next-batch char/byte deletion+and commit, terminal-pending composition, same-owner control/keyboard moves, direct-commit and+valid-chain positive controls. These checks and fresh independent review are pending managed+validation; the earlier18-test result predates this repair. Canonical manifests/lock are unchanged.diff --cc packaging/env.shindex 702318cde,702318cde..64e4c3d75--- a/packaging/env.sh+++ b/packaging/env.sh@@@ -48,7 -48,7 +48,7 @@@ warn()# craft-fonts fonts the build embedded (only when built with CRAFT_FONTS_DIR).copy_docs() {local dest="$1" f-- for f in README.md LICENSE LICENSE-MIT LICENSE-APACHE COPYRIGHT; do++ for f in README.md LICENSE LICENSE-MIT LICENSE-APACHE COPYRIGHT NOTICE; doif [[ -f "$ROOT/$f" ]]; then cp "$ROOT/$f" "$dest/"; fidonecopy_font_licences "$dest"diff --cc packaging/linux/flatpak/ai.storyteller.filmcraft.ymlindex ef8addc75,ef8addc75..cf7667ff8--- a/packaging/linux/flatpak/ai.storyteller.filmcraft.yml+++ b/packaging/linux/flatpak/ai.storyteller.filmcraft.yml@@@ -56,6 -56,6 +56,7 @@@ modulesbuild-commands:- cargo --offline build --release --locked -p filmcraft -p filmcraft-cli- install -Dm755 target/release/filmcraft /app/bin/filmcraft++ - install -Dm644 NOTICE /app/share/doc/filmcraft/NOTICE# The headless CLI and its stdio MCP server, as in the release bundle (#346).- install -Dm755 target/release/filmcraft-cli /app/bin/filmcraft-cli- install -Dm644 packaging/linux/ai.storyteller.filmcraft.desktop /app/share/applications/ai.storyteller.filmcraft.desktopdiff --cc packaging/macos/package.shindex c84028b59,c84028b59..609dd7376--- a/packaging/macos/package.sh+++ b/packaging/macos/package.sh@@@ -103,6 -103,6 +103,7 @@@ mkdir -p "$APP/Contents/MacOS" "$APP/Co# Executable and icon carry the display name (CFBundleExecutable / CFBundleIconFile).cp "$WORK/bin/filmcraft" "$APP/Contents/MacOS/FilmCraft"cp "$ROOT/assets/app-icon/filmcraft.icns" "$APP/Contents/Resources/FilmCraft.icns"++cp "$ROOT/NOTICE" "$APP/Contents/Resources/"sed -e "s/@VERSION@/$VERSION/g" -e "s/@SHORT_VERSION@/$SHORT_VERSION/g" \-e "s/@BUILD_SHA@/${FILMCRAFT_BUILD_SHA:-unknown}/g" \"$HERE/Info.plist.in" >"$APP/Contents/Info.plist"diff --cc packaging/windows/filmcraft.wxsindex 44114a4b3,91eb71de6..19f1c7b5c--- a/packaging/windows/filmcraft.wxs+++ b/packaging/windows/filmcraft.wxs@@@ -45,13 -39,8 +45,14 @@@</Package><Fragment>+ <?if $(var.HasCraftFontLicences) = 1 ?>+ <ComponentGroup Id="CraftFontLicences" Directory="INSTALLFOLDER">+ <Files Include="$(var.DocsDir)\**" />+ </ComponentGroup>+ <?endif ?><ComponentGroup Id="FilmcraftFiles" Directory="INSTALLFOLDER"><Component Id="FilmcraftApp" Guid="15933017-925B-4963-8992-52000EB26AAA">++ <File Id="FilmcraftNotice" Source="$(var.BinDir)\NOTICE" KeyPath="no" /><File Id="FilmcraftExe" Source="$(var.BinDir)\filmcraft.exe" KeyPath="yes"><Shortcut Id="StartMenuShortcut" Directory="ProgramMenuFolder" Name="FilmCraft"Description="FilmCraft video editor" WorkingDirectory="INSTALLFOLDER" Advertise="yes"diff --cc packaging/windows/package.ps1index 786fea80e,faa4b8638..4fc87aa8e--- a/packaging/windows/package.ps1+++ b/packaging/windows/package.ps1@@@ -86,6 -86,6 +86,8 @@@ foreach ($check in @(@('filmcraft.exe'$Stage = Join-Path $TargetDir "windows-package\$Arch"Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinueNew-Item -ItemType Directory -Force -Path $Stage | Out-Null++# Dependency font notices are required even without optional craft-fonts.++Copy-Item -LiteralPath (Join-Path $Root 'NOTICE') -Destination $StageCopy-Item (Join-Path $Bin 'filmcraft.exe'), (Join-Path $Bin 'filmcraft-cli.exe') $Stage& (Join-Path $PSScriptRoot 'sign.ps1') (Join-Path $Stage 'filmcraft.exe') (Join-Path $Stage 'filmcraft-cli.exe')@@@ -125,7 -111,7 +127,7 @@@ Set-Content -Encoding ascii -Path (Join'FilmCraft portable: preferences, presets, logs and crash recovery are kept in the data folder','next to filmcraft.exe. Delete this file to use %APPDATA%\FilmCraft instead.')--foreach ($f in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE') {++foreach ($f in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE') {$p = Join-Path $Root $fif (Test-Path $p) { Copy-Item $p $Portable }}