Skip to content

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

egui-037: fix capture failures, UTF-8 input and hidden timing

skylar taylor-barricka46b7fa0d62e
diff --git a/crates/ui-egui/src/capture.rs b/crates/ui-egui/src/capture.rs
index 94234f500..d089969b2 100644
--- a/crates/ui-egui/src/capture.rs
+++ b/crates/ui-egui/src/capture.rs
@@ -469,7 +469,14 @@ pub(crate) fn issue(app: &mut FilmcraftApp, ctx: &egui::Context) {
failures.push((i, message));
}
}
- for (i, message) in failures.into_iter().rev() {
+ // Failures arrive from the ascending admission scan and the reverse geometry-retry scan, so
+ // sort them by index and remove from the highest index down: an earlier removal must not shift
+ // a later index (which could remove the wrong shot or panic).
+ failures.sort_unstable_by_key(|(i, _)| std::cmp::Reverse(*i));
+ for (i, message) in failures {
+ if i >= app.shots.requests.len() {
+ continue;
+ }
let shot = app.shots.requests.remove(i);
if let Some(slot) = shot.slot {
slot.cancel();
@@ -615,7 +622,7 @@ mod tests {
app.capture_geometry = Some(geometry(app));
let (tx, rx) = channel();
admit(app, ctx, None, None, tx);
- let token = app.shots.requests.first().map(|shot| shot.token).unwrap_or_default();
+ let token = app.shots.requests.last().map(|shot| shot.token).unwrap_or_default();
(rx, token)
}
@@ -792,4 +799,39 @@ mod tests {
assert_eq!(app.shots.requests[0].expected, [1024, 768]);
assert!(!app.shots.requests[0].issued, "the retry waits for its own settling passes");
}
+
+ #[test]
+ fn mixed_order_geometry_failures_reject_every_shot_without_shifting_indices() {
+ let ctx = egui::Context::default();
+ let mut app = app();
+ let (rx0, token0) = admit_one(&mut app, &ctx);
+ let (rx1, token1) = admit_one(&mut app, &ctx);
+ for shot in &mut app.shots.requests {
+ shot.ready_at = Instant::now() - Duration::from_millis(1);
+ shot.frames = SETTLE_PASSES;
+ }
+ app.timeline_still = 2;
+ // A resize makes both queued shots need more crop/encode buffers than the aggregate
+ // budget, so the geometry retry fails for the last shot first.
+ app.capture_geometry = Some(CaptureGeometry {
+ surface: SurfaceGeometry {
+ viewport: Some(vec2(8000.0, 4000.0)),
+ pixels_per_point: 1.0,
+ max_texture_side: 16384,
+ minimized: false,
+ occluded: false,
+ },
+ document: active_document(&app),
+ focus: None,
+ });
+ app.capture_epoch += 1;
+ issue(&mut app, &ctx);
+ assert!(app.shots.requests.is_empty(), "both failed shots were removed");
+ for (rx, token) in [(rx0, token0), (rx1, token1)] {
+ let reply = rx.try_recv().expect("each failed shot gets its own reply");
+ assert_eq!(reply["request"], token);
+ assert_eq!(reply["ok"], false, "{reply}");
+ assert!(reply["error"].as_str().unwrap_or_default().contains("aggregate"), "{reply}");
+ }
+ }
}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index ea5a56f62..37247080b 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -369,6 +369,11 @@ pub struct FilmcraftApp {
/// later of this and the host clock keeps simulated tests on their clock while a hidden
/// logic tick (whose `InputState::time` is stale) still advances by host time.
ui_clock: f64,
+ /// Non-negative `ui_clock - host_elapsed`, captured on the first real UI pass. Native eframe
+ /// starts its `RawInput::time` at its own integration beginning, which can precede
+ /// `clock_start`; without this offset, `max` would hold `now()` at the stale UI time during
+ /// hidden logic and then jump by the startup offset when the next UI pass arrives.
+ ui_clock_offset: Option<f64>,
#[cfg(test)]
test_now: Option<f64>,
/// macOS: a Control+Click already translated to a secondary (context) click, so its release is
@@ -654,6 +659,7 @@ impl FilmcraftApp {
pasted_image: None,
clock_start: web_time::Instant::now(),
ui_clock: 0.0,
+ ui_clock_offset: None,
#[cfg(test)]
test_now: None,
mac_ctrl_click_armed: false,
@@ -877,7 +883,9 @@ impl FilmcraftApp {
if let Some(now) = self.test_now {
return now;
}
- self.clock_start.elapsed().as_secs_f64().max(self.ui_clock)
+ let host = self.clock_start.elapsed().as_secs_f64();
+ let host = self.ui_clock_offset.map_or(host, |offset| host + offset);
+ host.max(self.ui_clock)
}
#[cfg(test)]
@@ -2429,6 +2437,15 @@ impl FilmcraftApp {
}
fn ui_inner(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
+ if self.ui_clock_offset.is_none() {
+ let egui_time = ui.ctx().input(|input| input.time);
+ if egui_time.is_finite() {
+ let host = self.clock_start.elapsed().as_secs_f64();
+ // Never move host time backwards when a harness clock starts behind it; the host
+ // clock stays authoritative in that case.
+ self.ui_clock_offset = Some((egui_time - host).max(0.0));
+ }
+ }
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).
@@ -2881,6 +2898,26 @@ mod gpu_fallback_tests {
}
}
+#[cfg(test)]
+mod clock_tests {
+ use super::*;
+
+ /// The egui clock starts at the integration's beginning, which can precede `clock_start`.
+ /// Applying the captured offset to host time keeps hidden logic moving instead of freezing at
+ /// the last UI time and then jumping when the next UI pass arrives.
+ #[test]
+ fn now_applies_the_ui_clock_offset_and_keeps_the_test_override_first() {
+ let mut app = FilmcraftApp::new(Session::default());
+ app.ui_clock = 123.0;
+ app.ui_clock_offset = Some(1_000.0);
+ assert!(app.now() >= 1_000.0, "the captured offset moves the host clock to egui time");
+ app.ui_clock = 2_000.0;
+ assert_eq!(app.now(), 2_000.0, "an egui clock ahead of host+offset still wins");
+ app.set_now_for_test(7.0);
+ assert_eq!(app.now(), 7.0, "the deterministic test override keeps precedence");
+ }
+}
+
#[cfg(test)]
mod audio_recovery_tests {
use super::*;
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 0ead242e2..e0b26c104 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -678,11 +678,21 @@ fn paste_clipboard_media(app: &mut FilmcraftApp, insert: bool) -> Option<Result<
Some(app.session.execute("edit.pasteMedia", params).map_err(|e| e.to_string()))
}
+/// Upper bound on the RGBA copy made from a clipboard image, matching the screenshot per-image
+/// bound. The event's own `ColorImage` is still alive while this copy is encoded, so reject before
+/// allocating it rather than only checking for integer overflow.
+const MAX_CLIPBOARD_IMAGE_BYTES: usize = 128 * 1024 * 1024;
+
/// The RGBA bytes of an image delivered by `egui::Event::PasteImage`.
fn paste_image_media(image: &egui::ColorImage) -> Result<crate::ClipboardMedia, String> {
let [width, height] = image.size;
let len =
width.checked_mul(height).and_then(|pixels| pixels.checked_mul(4)).ok_or_else(|| "the pasted image size overflows the clipboard buffer".to_string())?;
+ if len > MAX_CLIPBOARD_IMAGE_BYTES {
+ return Err(format!(
+ "the pasted image is too large: {width}×{height} needs {len} RGBA bytes, over the {MAX_CLIPBOARD_IMAGE_BYTES}-byte clipboard image limit"
+ ));
+ }
let mut rgba = Vec::with_capacity(len);
for c in &image.pixels {
// `Color32` is premultiplied internally; PNG/RgbaImage expect straight alpha. Round-trip
@@ -1137,6 +1147,14 @@ mod tests {
assert_eq!(decoded.get_pixel(0, 0).0, [255, 0, 0, 128]);
}
+ #[test]
+ fn oversized_clipboard_images_are_rejected_before_allocating_rgba() {
+ let side = 100_000;
+ let image = egui::ColorImage { size: [side, side], source_size: egui::vec2(100_000.0, 100_000.0), pixels: Vec::new() };
+ let Err(error) = paste_image_media(&image) else { panic!("an oversized clipboard image was accepted") };
+ assert!(error.contains("too large"), "{error}");
+ }
+
/// What `cargo xtask parity` measures: every item sits under a top-level menu, and Window ▸
/// Workspaces lists the built-in workspaces before the layout commands, none checked.
#[test]
diff --git a/crates/ui-egui/src/panels/graphics.rs b/crates/ui-egui/src/panels/graphics.rs
index 4cce6f970..8ff14fd4f 100644
--- a/crates/ui-egui/src/panels/graphics.rs
+++ b/crates/ui-egui/src/panels/graphics.rs
@@ -1886,7 +1886,10 @@ fn text_edit(
}
if let Some(m) = moved {
let previous_selection = (ed.caret, ed.anchor);
- ed.caret = m.min(text.len());
+ // `m` comes from the layout of the text at the start of this batch, but an
+ // earlier Text/Paste/IME event may already have changed `text`; clamp to a
+ // UTF-8 boundary in the current text before a later event slices or inserts.
+ ed.caret = char_boundary_floor(&text, m);
if !shift {
ed.anchor = ed.caret;
}
diff --git a/crates/ui-egui/src/panels/transition_controls.rs b/crates/ui-egui/src/panels/transition_controls.rs
index a6f05ad50..1b12fd3ad 100644
--- a/crates/ui-egui/src/panels/transition_controls.rs
+++ b/crates/ui-egui/src/panels/transition_controls.rs
@@ -168,8 +168,9 @@ pub fn effect_controls(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, id
for pd in def.map(|d| d.params.as_slice()).unwrap_or(&[]) {
let value = x.effect.params.get(pd.id).map_or(&pd.default, |p| &p.value);
- ui.label(crate::i18n::t(pd.label));
- if let Some(v) = param_widget(ui, &mut elems, pd.id, &pd.kind, value, (fw, fh)) {
+ let label = crate::i18n::t(pd.label);
+ ui.label(label);
+ if let Some(v) = param_widget(ui, &mut elems, pd.id, label, &pd.kind, value, (fw, fh)) {
changes.push(v);
}
ui.end_row();
@@ -470,7 +471,7 @@ fn paint_ruler(p: &egui::Painter, ruler: Rect, view: (Tick, Tick), rate: FrameRa
}
/// One of a transition's own settings. Returns the change, as `sequence.setTransition` params.
-fn param_widget(ui: &mut egui::Ui, elems: &mut Elems, pid: &str, kind: &ParamKind, value: &ParamValue, frame: (f64, f64)) -> Option<Value> {
+fn param_widget(ui: &mut egui::Ui, elems: &mut Elems, pid: &str, label: &str, kind: &ParamKind, value: &ParamValue, frame: (f64, f64)) -> Option<Value> {
let eid = format!("effectControls.transition.param.{pid}");
let drag = |r: &egui::Response| json!({"merge": true, "begin": r.drag_started() || !r.dragged()});
match (kind, value) {
@@ -497,7 +498,7 @@ fn param_widget(ui: &mut egui::Ui, elems: &mut Elems, pid: &str, kind: &ParamKin
}
(ParamKind::Bool, ParamValue::Bool(b)) => {
let mut b = *b;
- let r = crate::widgets::accessible_name(ui.checkbox(&mut b, ""), eid.clone());
+ let r = crate::widgets::accessible_name(ui.checkbox(&mut b, ""), label);
elems.push((eid, r.rect, b.to_string()));
r.changed().then(|| json!({"params": { pid: b }}))
}
@@ -515,7 +516,7 @@ fn param_widget(ui: &mut egui::Ui, elems: &mut Elems, pid: &str, kind: &ParamKin
}
});
elems.extend(options);
- let response = crate::widgets::accessible_name(r.response, eid.clone());
+ let response = crate::widgets::accessible_name(r.response, label);
elems.push((eid, response.rect, shown.to_string()));
picked.map(|i| json!({"params": { pid: i }}))
}
diff --git a/crates/ui-egui/tests/it/graphics_handles_ui.rs b/crates/ui-egui/tests/it/graphics_handles_ui.rs
index 716576a77..384ec0d7c 100644
--- a/crates/ui-egui/tests/it/graphics_handles_ui.rs
+++ b/crates/ui-egui/tests/it/graphics_handles_ui.rs
@@ -562,6 +562,25 @@ fn ime_mixed_application_and_ime_mutation_is_other() {
assert_eq!(toolbar.change_cause, egui::output::ImeChangeCause::Other);
}
+/// An Arrow key later in a raw batch uses the layout of the text from the start of that batch.
+/// Text typed earlier in the same batch can move the caret onto a byte inside a multi-byte
+/// character; the following Text/Paste/Cut must clamp it to a boundary instead of panicking.
+#[test]
+fn arrow_from_the_old_layout_does_not_split_text_inserted_in_the_same_batch() {
+ let mut d = Driver::new();
+ let clip = d.start_point_text();
+ d.exec("graphics.setText", json!({"clip": clip, "layer": 0, "text": "ab\ncd"}));
+ d.ok("ui.set", json!({"gfxEdit": {"clip": clip, "layer": 0, "caret": 0, "anchor": 0}}));
+ d.frames(2);
+
+ // After "éé" the caret is at byte 4, on the old layout's second line. ArrowUp maps its x to
+ // byte 1 of that old line, which is inside the first "é" in the current text; "x" then inserts
+ // there. Before the fix this panicked on the non-boundary insert.
+ d.harness.input_mut().events.extend([egui::Event::Text("éé".into()), key_press(egui::Key::ArrowUp), egui::Event::Text("x".into())]);
+ d.frames(2);
+ assert_eq!(d.exec("graphics.list", json!({"clip": clip}))["layers"][0]["text"], json!("xééab\ncd"));
+}
+
fn ime_preedit(text: &str) -> egui::Event {
egui::Event::Ime(egui::ImeEvent::Preedit { text: text.into(), active_range_chars: None })
}