Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

ime: a floating Program monitor window runs its IME check after its last body

aionggadd6bafead32
diff --git a/crates/ui-egui/src/dock_ui.rs b/crates/ui-egui/src/dock_ui.rs
index 82291617f..7a30f2c15 100644
--- a/crates/ui-egui/src/dock_ui.rs
+++ b/crates/ui-egui/src/dock_ui.rs
@@ -477,6 +477,12 @@ impl DockContent<PanelKind> for FilmContent<'_> {
}
}
+ /// A native floating window drew its last body: its end-of-pass IME check, for the Program
+ /// monitor's text editor when it is there.
+ fn window_drawn(&mut self, ui: &mut egui::Ui) {
+ self.app.finish_ime_window(ui.ctx());
+ }
+
fn logical_label(&self, panel: &PanelKind) -> String {
crate::i18n::t(panel.title()).to_string()
}
diff --git a/crates/ui-egui/src/ime_reset.rs b/crates/ui-egui/src/ime_reset.rs
index 86a01a1fc..ec1e2336d 100644
--- a/crates/ui-egui/src/ime_reset.rs
+++ b/crates/ui-egui/src/ime_reset.rs
@@ -184,11 +184,28 @@ impl State {
/// 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 custom = self.custom_output.filter(|custom| eligible && actual == Some(*custom));
+ self.settle(ctx, destination.filter(|_| custom.is_some()), custom);
+ }
+
+ /// [`Self::finish`] for a native floating window, whose descriptor docking publishes after
+ /// this call: `destination` is the eligible editor's, and `output` the identity the window
+ /// published in its previous pass ([`published`]). `None` there is a context that starts in
+ /// this pass, whose identity is not known yet: the fence waits for the next pass.
+ pub(crate) fn finish_window(&mut self, ctx: &Context, destination: Option<Destination>, output: Option<OutputContext>) {
+ if destination.is_some() && output.is_none() {
+ return;
+ }
+ self.settle(ctx, destination, output);
+ }
+
+ /// Bind or rearm the viewport's fence for the eligible `destination` and its published
+ /// `custom` output, or suspend it when there is no eligible destination.
+ fn settle(&mut self, ctx: &Context, destination: Option<Destination>, custom: Option<OutputContext>) {
+ let viewport = ctx.viewport_id();
let Some(pending) = self.pending.get_mut(&viewport) else { return };
- let Some(destination) = destination.filter(|_| eligible && custom.is_some() && actual == custom) else {
+ let Some(destination) = destination else {
self.suspend(viewport);
return;
};
@@ -229,6 +246,20 @@ pub(crate) fn in_ui_pass(ctx: &Context) -> bool {
ctx.data(|data| data.get_temp::<bool>(mode_id(ctx.viewport_id()))).unwrap_or(false)
}
+/// Temp-data key of the IME descriptor identity `viewport` published at the end of a pass.
+fn published_id(viewport: ViewportId) -> Id {
+ Id::unique(("filmcraft-ime-reset-published", viewport))
+}
+
+/// The identity of `owner`'s descriptor that `ctx`'s viewport published at the end of its
+/// previous pass; `None` when that pass published none of `owner`'s or wasn't the one before.
+pub(crate) fn published(ctx: &Context, owner: Id) -> Option<OutputContext> {
+ let viewport = ctx.viewport_id();
+ let previous = ctx.cumulative_pass_nr_for(viewport).checked_sub(1)?;
+ let (pass, output) = ctx.data(|data| data.get_temp::<(u64, Option<OutputContext>)>(published_id(viewport)))?;
+ output.filter(|output| pass == previous && output.owner == owner)
+}
+
/// 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");
@@ -247,6 +278,9 @@ pub(crate) fn install(ctx: &Context) {
Arc::new(|ui| {
let viewport = ui.ctx().viewport_id();
ui.data_mut(|data| data.insert_temp(mode_id(viewport), false));
+ // A native floating window's descriptor is complete only here, after docking wrote it.
+ let published = (ui.ctx().cumulative_pass_nr_for(viewport), ui.ctx().output(|out| out.ime.as_ref().map(OutputContext::of)));
+ ui.data_mut(|data| data.insert_temp(published_id(viewport), published));
}),
);
ctx.data_mut(|data| data.insert_temp(installed, true));
@@ -447,6 +481,38 @@ mod tests {
assert!(state.complete(&ctx, replacement, destination));
}
+ /// A native window's suspended fence waits while the window's descriptor identity is not
+ /// known, rearms on the identity the window's previous pass published, and keeps that one
+ /// request while the identity stays.
+ #[test]
+ fn window_fence_rearms_on_the_published_identity() {
+ let ctx = Context::default();
+ install(&ctx);
+ let window = ViewportId::from_hash_of("film-native-window");
+ let mut state = State { viewport: window, ..Default::default() };
+ let destination = destination();
+ state.interrupt(destination.target, Some(destination));
+ state.suspend(window);
+ let pass = |state: &mut State, f: &mut dyn FnMut(&mut State, &Context)| {
+ let mut raw = egui::RawInput { viewport_id: window, ..Default::default() };
+ raw.viewports.insert(window, egui::ViewportInfo { parent: Some(ViewportId::ROOT), ..Default::default() });
+ let mut out = ctx.run_ui(raw, |ui| {
+ ui.ctx().output_mut(|out| out.ime = Some(output(destination, 1, IMEPurpose::Normal)));
+ f(state, ui.ctx());
+ });
+ out.textures_delta.clear();
+ out.platform_output.ime.and_then(|ime| ime.reset_request)
+ };
+ let mut finish = |state: &mut State, ctx: &Context| state.finish_window(ctx, Some(destination), published(ctx, destination.target.owner));
+ assert!(pass(&mut state, &mut finish).is_none(), "the first pass's identity is not known yet");
+ assert!(state.blocked(window));
+ let request = pass(&mut state, &mut finish).expect("the next pass rearms the fence");
+ assert!(pass(&mut state, &mut finish).is_none(), "the same identity keeps the request");
+ let mut completed = false;
+ pass(&mut state, &mut |state, ctx| completed = state.complete(ctx, request, destination));
+ assert!(completed && !state.blocked(window));
+ }
+
/// UI-pass mode is scoped per viewport, `install` is idempotent, and a child viewport's
/// completion cannot release ROOT's guard.
#[test]
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index e90ba73a2..7fbd07ed4 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -838,6 +838,31 @@ impl FilmcraftApp {
self.ime_reset.finish(ctx, destination, self.ime_reset.owns_output(ctx));
}
+ /// [`Self::ui`]'s end-of-pass IME check for a native floating window, after its last panel
+ /// body: the Program monitor's editor, when it was drawn there, keeps or drops the
+ /// composer's descriptor, and the window's reset fence suspends or rearms.
+ pub(crate) fn finish_ime_window(&mut self, ctx: &egui::Context) {
+ let viewport = ctx.viewport_id();
+ if self.ime_drawn_editor.as_ref().is_none_or(|drawn| drawn.viewport != viewport) {
+ self.ime_reset.suspend(viewport);
+ return;
+ }
+ self.ime_reset.viewport = viewport;
+ let focused = ctx.input(|input| input.viewport().focused.unwrap_or(input.focused));
+ let eligible = panels::graphics::finish_graphics_ime(self, ctx, false) && focused;
+ let destination = panels::graphics::current_reset_destination(self);
+ if !eligible {
+ self.suspend_ime_input(ctx);
+ self.ime_reset.finish_window(ctx, None, None);
+ return;
+ }
+ if let Some(destination) = destination {
+ self.sync_live_ime_destination(ctx, destination);
+ }
+ let output = self.ime_composer_target.and_then(|target| ime_reset::published(ctx, target.owner));
+ self.ime_reset.finish_window(ctx, destination, output);
+ }
+
/// 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.
@@ -866,7 +891,7 @@ impl FilmcraftApp {
}
/// The main window's end-of-pass check of the Program monitor's editor, after the pass's
- /// control requests ran.
+ /// control requests ran. Native floating windows ran theirs in [`Self::finish_ime_window`].
pub(crate) fn finish_ime_pass(&mut self, ctx: &egui::Context) {
let _ = panels::graphics::finish_graphics_ime(self, ctx, true);
}
diff --git a/crates/ui-egui/tests/it/native_windows_ui.rs b/crates/ui-egui/tests/it/native_windows_ui.rs
index ab96e22fa..592f8f1ac 100644
--- a/crates/ui-egui/tests/it/native_windows_ui.rs
+++ b/crates/ui-egui/tests/it/native_windows_ui.rs
@@ -10,21 +10,48 @@ use filmcraft_ui_egui::FilmcraftApp;
use filmcraft_ui_egui::control::ControlRequest;
use serde_json::{Value, json};
+/// What the tests give the native windows and what the windows publish. A test drives at most
+/// one native window at a time.
+#[derive(Default)]
+struct WindowIo {
+ focused: bool,
+ events: Vec<egui::Event>,
+ ime: Option<egui::output::IMEOutput>,
+ reset_requests: Vec<egui::ImeResetId>,
+}
+
+thread_local! {
+ static WINDOW: std::cell::RefCell<WindowIo> = std::cell::RefCell::new(WindowIo::default());
+}
+
/// Native windows at their builders' places, reporting that place as their desktop rect.
fn native_host() {
+ WINDOW.with(|w| *w.borrow_mut() = WindowIo::default());
egui::Context::set_immediate_viewport_renderer(|ctx, mut viewport| {
let size = viewport.builder.inner_size.unwrap_or(egui::vec2(400.0, 300.0));
let place = egui::Rect::from_min_size(viewport.builder.position.unwrap_or_default(), size);
let id = viewport.ids.this;
- let info = egui::ViewportInfo { inner_rect: Some(place), outer_rect: Some(place), focused: Some(false), ..Default::default() };
+ let (focused, events) = WINDOW.with(|w| {
+ let mut w = w.borrow_mut();
+ (w.focused, std::mem::take(&mut w.events))
+ });
+ let info = egui::ViewportInfo { inner_rect: Some(place), outer_rect: Some(place), focused: Some(focused), ..Default::default() };
let input = egui::RawInput {
viewport_id: id,
viewports: std::iter::once((id, info)).collect(),
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)),
time: ctx.input(|i| Some(i.time)),
+ focused,
+ events,
..Default::default()
};
- ctx.run_ui(input, |ui| (viewport.viewport_ui_cb)(ui)).textures_delta.clear();
+ let mut out = ctx.run_ui(input, |ui| (viewport.viewport_ui_cb)(ui));
+ out.textures_delta.clear();
+ WINDOW.with(|w| {
+ let mut w = w.borrow_mut();
+ w.reset_requests.extend(out.platform_output.ime.as_ref().and_then(|ime| ime.reset_request));
+ w.ime = out.platform_output.ime;
+ });
});
}
@@ -43,7 +70,10 @@ impl Driver {
s.execute("source.open", json!({"item": source})).unwrap();
let (tx, rx) = channel();
let app = FilmcraftApp::new(s).with_control(rx);
- let harness = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_max_steps(10_000).build_eframe(move |_cc| app);
+ let harness = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_max_steps(10_000).build_eframe(move |cc| {
+ filmcraft_ui_egui::install_ime_reset_callbacks(&cc.egui_ctx);
+ app
+ });
let mut d = Driver { harness, tx };
d.harness.ctx.set_embed_viewports(false);
// A main window that reports its desktop place, as under X11: craft-ui otherwise keeps
@@ -177,3 +207,66 @@ fn a_source_drag_drops_on_a_timeline_in_its_own_window() {
d.frames(3);
assert_eq!(clips(&d), 1, "status: {}", d.app().ui.status);
}
+
+/// The window's events for its next frame, and that frame.
+fn window_frame(d: &mut Driver, events: Vec<egui::Event>) {
+ WINDOW.with(|w| w.borrow_mut().events.extend(events));
+ d.frames(1);
+}
+
+fn window_ime() -> Option<egui::output::IMEOutput> {
+ WINDOW.with(|w| w.borrow().ime.clone())
+}
+
+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()))
+}
+
+/// The Program monitor's text editor in its own OS window: the window publishes the composer's
+/// descriptor every pass, so the marked text survives; a click while composing suspends the
+/// window's reset fence, the window's next pass rearms it, and its completion admits a commit.
+#[test]
+fn a_floating_program_monitor_composes_and_rearms_its_ime_fence() {
+ let mut d = Driver::new(5);
+ let clip = d.ok("engine.execute", json!({"command": "graphics.newText", "params": {"text": "alpha", "position": [640, 360], "size": 120}}))["clip"]
+ .as_u64()
+ .unwrap();
+ d.float("Program", [900.0, 120.0, 680.0, 520.0]);
+ WINDOW.with(|w| w.borrow_mut().focused = true);
+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 5, "anchor": 5}}));
+ d.frames(3);
+ let text = |d: &mut Driver| d.ok("engine.execute", json!({"command": "graphics.list", "params": {"clip": clip}}))["layers"][0]["text"].clone();
+ let first = window_ime().expect("the floating editor publishes in its own window");
+
+ window_frame(&mut d, vec![ime_preedit("に")]);
+ for _ in 0..3 {
+ d.frames(1);
+ let ime = window_ime().expect("the window keeps publishing while composing");
+ assert_eq!((ime.owner, ime.context_generation), (first.owner, first.context_generation), "the same IME context");
+ assert!(!ime.should_interrupt_composition);
+ }
+ let preedit = d.element("program.textEdit.preedit");
+ assert_eq!(preedit["label"], json!("に"), "the marked text is drawn in the window");
+ assert!(preedit["window"].is_u64(), "{preedit}");
+ window_frame(&mut d, vec![ime_preedit(""), ime_commit("日本")]);
+ assert_eq!(text(&mut d), json!("alpha日本"));
+
+ // A click in the text while composing suspends the window's fence.
+ let at = rect(&d.element("program.textEdit")).center();
+ window_frame(&mut d, vec![ime_preedit("ご")]);
+ let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
+ WINDOW.with(|w| w.borrow_mut().reset_requests.clear());
+ window_frame(&mut d, vec![egui::Event::PointerMoved(at), press(true)]);
+ window_frame(&mut d, vec![press(false)]);
+ d.frames(2);
+ let fence = WINDOW.with(|w| w.borrow().reset_requests.last().copied()).expect("the window's next passes rearm its fence");
+ window_frame(&mut d, vec![ime_commit("x")]);
+ assert_eq!(text(&mut d), json!("alpha日本ご"), "the fence blocks a commit until it completes");
+ window_frame(&mut d, vec![egui::Event::ImeResetCompleted { request_id: fence }, ime_preedit("が"), ime_commit("が")]);
+ let after = text(&mut d);
+ assert!(after.as_str().is_some_and(|t| t.contains('が')), "the completed fence admits the commit: {after}");
+}