Skip to content

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

egui037: Document capture and IME lifecycle contracts

skylar taylor-barricke447a189c92c
diff --git a/crates/ui-egui/src/capture.rs b/crates/ui-egui/src/capture.rs
index c8d69a3a2..617845643 100644
--- a/crates/ui-egui/src/capture.rs
+++ b/crates/ui-egui/src/capture.rs
@@ -69,12 +69,20 @@ pub(crate) struct SurfaceGeometry {
}
impl PartialEq for SurfaceGeometry {
+ /// Compares only the fields that change captured pixels: viewport size, pixels per point and
+ /// the GPU texture limit. The presentation-only minimized/occluded flags are deliberately
+ /// ignored, so minimizing, occluding or losing window focus does not invalidate an issued
+ /// capture.
fn eq(&self, other: &Self) -> bool {
self.viewport == other.viewport && self.pixels_per_point == other.pixels_per_point && self.max_texture_side == other.max_texture_side
}
}
impl SurfaceGeometry {
+ /// Snapshot the surface from a raw-input callback, reading the fresh `viewports`/`screen_rect`
+ /// geometry rather than the stale `InputState`. Missing or hostile fields fall back to
+ /// `previous` where possible; `None` means no usable zoom and pixels-per-point pair could be
+ /// established.
fn from_raw(raw: &egui::RawInput, ctx: &egui::Context, previous: Option<Self>) -> Option<Self> {
let info = raw.viewports.get(&raw.viewport_id).cloned().unwrap_or_default();
let rect = info.inner_rect.or(raw.screen_rect);
@@ -99,6 +107,11 @@ impl SurfaceGeometry {
Some(Self { viewport, pixels_per_point, max_texture_side, minimized, occluded })
}
+ /// Pixel size the backend will present: viewport points scaled by pixels per point and
+ /// rounded. If either axis exceeds the texture limit, both axes shrink by the same factor to
+ /// a positive limit, matching wgpu's `surface_fit`; per-axis clamping would predict the wrong
+ /// image. A zero/unknown texture limit disables shrinking.
+ /// `None` when the viewport is missing, non-finite, empty or the size overflows `usize`.
fn expected_size(self) -> Option<[usize; 2]> {
let viewport = self.viewport?;
if !viewport.x.is_finite() || !viewport.y.is_finite() || viewport.x <= 0.0 || viewport.y <= 0.0 {
@@ -158,6 +171,8 @@ impl SurfaceGeometry {
if effective.is_finite() && effective > 0.0 { effective } else { native }
}
+ /// Raw RGBA bytes of [`Self::expected_size`], checked for multiplication overflow; `None`
+ /// when the surface has no capturable size.
fn expected_bytes(self) -> Option<usize> {
let [width, height] = self.expected_size()?;
width.checked_mul(height)?.checked_mul(std::mem::size_of::<egui::Color32>())
@@ -180,10 +195,13 @@ pub(crate) struct CaptureGeometry {
}
impl CaptureGeometry {
+ /// Pixel size implied by the bound surface geometry; `None` when it is not capturable.
fn expected_size(self) -> Option<[usize; 2]> {
self.surface.expected_size()
}
+ /// Raw RGBA byte count implied by the bound surface, with the same overflow rule as
+ /// [`SurfaceGeometry::expected_bytes`].
fn expected_bytes(self) -> Option<usize> {
self.surface.expected_bytes()
}
@@ -198,6 +216,9 @@ pub enum CropTarget {
}
impl CropTarget {
+ /// Resolve the named element against the accepted pass's automation registry. Only an element
+ /// drawn in the current pass with a finite, non-empty rectangle is accepted; a stale
+ /// previous-pass rectangle or an unknown id is an error, never a fallback to the whole window.
fn resolve(&self, registry: &crate::automation::Registry) -> Result<[f32; 4], String> {
let Self::Element(id) = self;
let element = registry
@@ -243,19 +264,25 @@ pub(crate) struct Shots {
}
impl Shots {
+ /// True when no request is queued, in flight or completed-but-not-yet-drained.
pub(crate) fn is_empty(&self) -> bool {
self.requests.is_empty()
}
+ /// True while at least one admitted request has not been handed to a `Screenshot` callback.
fn has_unissued(&self) -> bool {
self.requests.iter().any(|shot| !shot.issued)
}
+ /// Sum of every request's byte reservation, including completed-but-undrained captures;
+ /// saturates instead of overflowing.
fn reserved(&self) -> usize {
self.requests.iter().fold(0usize, |sum, shot| sum.saturating_add(shot.reserved))
}
}
+/// Allocate the next request token, wrapping after `u64::MAX` and skipping zero so a token is
+/// always usable as a presence marker.
fn next_token(shots: &mut Shots) -> u64 {
let mut token = shots.token.wrapping_add(1);
if token == 0 {
@@ -265,18 +292,24 @@ fn next_token(shots: &mut Shots) -> u64 {
token
}
+/// Build the JSON error reply carrying `token`, so the client can match a rejection to the
+/// request it sent.
fn error_reply(token: u64, message: impl std::fmt::Display) -> Value {
json!({"ok": false, "error": message.to_string(), "request": token})
}
+/// Send an error reply for `token`, ignoring a client that has already disconnected.
fn reject(reply: Sender<Value>, token: u64, message: impl std::fmt::Display) {
let _ = reply.send(error_reply(token, message));
}
+/// The active sequence id (none when no sequence is open) and project revision that a capture
+/// is bound to.
fn active_document(app: &FilmcraftApp) -> DocumentId {
DocumentId { sequence: app.session.state.active_sequence.map(|id| id.0), revision: app.session.revision }
}
+/// The widget currently holding keyboard focus, part of the capture identity.
fn current_focus(ctx: &egui::Context) -> Option<egui::Id> {
ctx.memory(|memory| memory.focused())
}
@@ -385,6 +418,9 @@ pub(crate) fn admit(app: &mut FilmcraftApp, ctx: &egui::Context, path: Option<St
ctx.request_repaint();
}
+/// Why the request's bound document/revision or keyboard focus no longer matches. `None`
+/// means identity is unchanged; a mismatch must reject rather than save pixels from another
+/// document or focus.
fn identity_reason(app: &FilmcraftApp, ctx: &egui::Context, shot: &Shot) -> Option<&'static str> {
if active_document(app) != shot.document {
Some("the document or project revision changed while the capture was queued")
@@ -395,6 +431,8 @@ fn identity_reason(app: &FilmcraftApp, ctx: &egui::Context, shot: &Shot) -> Opti
}
}
+/// Why the live surface snapshot or capture epoch differs from the one this request was
+/// admitted or issued against. `None` means the geometry is still the one it reserved for.
fn geometry_reason(app: &FilmcraftApp, shot: &Shot) -> Option<&'static str> {
if app.capture_geometry != Some(shot.geometry) || app.capture_epoch != shot.geometry_epoch {
Some("the window geometry changed while the capture was queued")
@@ -403,6 +441,10 @@ fn geometry_reason(app: &FilmcraftApp, shot: &Shot) -> Option<&'static str> {
}
}
+/// Re-admit an unissued request against the current geometry: cancel its old slot, check the
+/// per-image and aggregate budgets including every other request, and reset its settled
+/// frames, crop misses and ready time. On failure nothing is changed and the caller rejects
+/// it; on success the request is unissued again and must collect fresh settling passes.
fn retry_geometry(app: &mut FilmcraftApp, ctx: &egui::Context, index: usize) -> Result<(), String> {
let now = Instant::now();
let current = app.capture_geometry.ok_or_else(|| "the window geometry is no longer known".to_string())?;
@@ -455,6 +497,10 @@ enum IssueOutcome {
Issued,
}
+/// Decide one settled request: reject on identity change, ask for a geometry retry, defer a
+/// not-yet-drawn crop target for a bounded number of accepted passes, or issue the screenshot
+/// with the crop resolved from this pass. The callback is taken at most once and `issued` is
+/// set only when the viewport command was sent.
fn try_issue_shot(app: &mut FilmcraftApp, ctx: &egui::Context, index: usize) -> IssueOutcome {
let shot = &app.shots.requests[index];
if let Some(reason) = identity_reason(app, ctx, shot) {
@@ -556,6 +602,10 @@ enum DrainStep {
Complete(Result<Arc<ColorImage>, CaptureError>),
}
+/// Classify one drain position before removing anything: check the deadline first, then
+/// identity, then geometry (an unissued request keeps waiting for a retry, while in-flight
+/// stale pixels are rejected), and finally take a completed slot. `Keep` leaves the request
+/// in place and advances the scan.
fn drain_step(app: &FilmcraftApp, ctx: &egui::Context, index: usize, now: Instant) -> DrainStep {
let shot = &app.shots.requests[index];
if now >= shot.deadline {
@@ -582,6 +632,8 @@ fn drain_step(app: &FilmcraftApp, ctx: &egui::Context, index: usize, now: Instan
DrainStep::Complete(result)
}
+/// Remove one request, cancel its slot and send its error reply; later requests shift down by
+/// one index.
fn remove_and_reject(app: &mut FilmcraftApp, index: usize, message: impl std::fmt::Display) {
let shot = app.shots.requests.remove(index);
if let Some(slot) = shot.slot {
@@ -609,6 +661,9 @@ fn image_reply(shot: &Shot, image: &ColorImage) -> Value {
reply
}
+/// Cancel any remaining callback, turn the captured image or error into the reply and send it
+/// exactly once. A pixel size that differs from the reserved size becomes an error reply
+/// instead of writing an image for the wrong surface.
fn complete_shot(mut shot: Shot, result: Result<Arc<ColorImage>, CaptureError>) {
if let Some(slot) = shot.slot.take() {
slot.cancel();
@@ -672,10 +727,12 @@ mod tests {
use crate::automation::Registry;
use filmcraft_engine::Session;
+ /// App with a default session, for capture-state unit tests.
fn app() -> FilmcraftApp {
FilmcraftApp::new(Session::default())
}
+ /// A fixed 800×600, 1 px/pt capture identity for the app's current document with no focus.
fn geometry(app: &FilmcraftApp) -> CaptureGeometry {
CaptureGeometry {
surface: SurfaceGeometry {
@@ -690,14 +747,19 @@ mod tests {
}
}
+ /// Raw input reporting an 800×600 root viewport.
fn raw() -> egui::RawInput {
egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), ..Default::default() }
}
+ /// Admit one uncropped in-memory capture at the default test surface; return its reply
+ /// receiver and token.
fn admit_one(app: &mut FilmcraftApp, ctx: &egui::Context) -> (Receiver<Value>, u64) {
admit_with_surface(app, ctx, geometry(app).surface)
}
+ /// Bind `surface` as the current capture geometry, admit one uncropped in-memory capture and
+ /// return its reply receiver and token.
fn admit_with_surface(app: &mut FilmcraftApp, ctx: &egui::Context, surface: SurfaceGeometry) -> (Receiver<Value>, u64) {
app.capture_geometry = Some(CaptureGeometry { surface, document: active_document(app), focus: None });
let (tx, rx) = channel();
@@ -706,6 +768,8 @@ mod tests {
(rx, token)
}
+ /// `note_raw_geometry` uses the fresh raw 2x viewport (1600×1200) rather than the previous
+ /// pass's input and bumps the capture epoch.
#[test]
fn raw_geometry_uses_the_fresh_surface_not_the_previous_pass() {
let ctx = egui::Context::default();
@@ -718,6 +782,8 @@ mod tests {
assert!(app.capture_epoch > 0);
}
+ /// Oversized surfaces shrink both axes by one factor to the texture limit and crop at the
+ /// matching rendered scale; a surface within the limit keeps the exact native scale.
#[test]
fn oversized_windows_predict_the_backends_uniformly_scaled_surface() {
let app = app();
@@ -734,6 +800,8 @@ mod tests {
assert_eq!(surface.captured_pixels_per_point(), 1.0, "an uncapped surface keeps the native scale exactly");
}
+ /// Unusable viewport data preserves a valid native scale, while an invalid native scale falls
+ /// back to 1.0 so a crop can never divide by zero.
#[test]
fn captured_scale_falls_back_when_geometry_is_unusable() {
let app = app();
@@ -752,6 +820,8 @@ mod tests {
assert_eq!(surface.captured_pixels_per_point(), 1.0);
}
+ /// A crop in points selects the region where a uniformly downscaled surface actually drew it,
+ /// using the rendered rather than the native scale.
#[test]
fn downscaled_capture_crops_with_the_rendered_scale() {
let ctx = egui::Context::default();
@@ -798,6 +868,8 @@ mod tests {
);
}
+ /// A 1.5x surface whose point size rounds up by one window pixel is still uncapped, so its
+ /// crop keeps the exact 1.5 scale instead of a slightly shrunk one.
#[test]
fn uncapped_hidpi_capture_keeps_the_native_scale() {
let ctx = egui::Context::default();
@@ -838,6 +910,8 @@ mod tests {
assert!(decoded.pixels().all(|pixel| *pixel == image::Rgba([0, 255, 0, 255])), "the HiDPI crop must select the green region at the native scale");
}
+ /// Minimized, occluded and window-focus flags do not bump the epoch or reject an already
+ /// issued capture; its pixels are still delivered once.
#[test]
fn presentation_flags_do_not_invalidate_an_issued_capture() {
let ctx = egui::Context::default();
@@ -867,6 +941,8 @@ mod tests {
assert_eq!(reply["ok"], true, "{reply}");
}
+ /// Admission counts completed-but-undrained requests, so a new request over `MAX_REQUESTS`
+ /// is rejected instead of replacing a slot that still owes a reply.
#[test]
fn admission_counts_outstanding_and_completed_but_undrained_requests() {
let ctx = egui::Context::default();
@@ -883,6 +959,7 @@ mod tests {
assert!(reply["error"].as_str().unwrap_or_default().contains("outstanding"), "{reply}");
}
+ /// A timed-out request replies once; its late callback cannot produce a second reply.
#[test]
fn a_late_completion_after_timeout_does_not_write_or_reply_twice() {
let ctx = egui::Context::default();
@@ -899,6 +976,8 @@ mod tests {
assert!(rx.try_recv().is_err(), "a late image must not produce another reply");
}
+ /// A near-per-image-limit surface is rejected before any slot exists because its crop/encode
+ /// reservation alone exceeds the aggregate bound.
#[test]
fn near_limit_images_are_rejected_for_encode_buffer_memory() {
let ctx = egui::Context::default();
@@ -925,6 +1004,8 @@ mod tests {
assert!(admitted_bytes([8000, 4000]).is_some_and(|bytes| bytes > MAX_TOTAL_BYTES));
}
+ /// A crop resolves only from the current pass's registry; a stale rect and a missing id both
+ /// error rather than using old coordinates.
#[test]
fn a_crop_is_resolved_from_the_current_pass_not_the_previous_one() {
let mut registry = Registry::default();
@@ -939,6 +1020,8 @@ mod tests {
assert!(CropTarget::Element("panel.missing".into()).resolve(&registry).is_err());
}
+ /// Issuing waits for the accepted final pass of a multipass layout, not the discarded first
+ /// pass.
#[test]
fn issue_runs_on_the_accepted_final_pass_of_a_multipass_layout() {
let ctx = egui::Context::default();
@@ -960,6 +1043,8 @@ mod tests {
assert!(app.shots.requests[0].issued, "the accepted pass must issue the capture");
}
+ /// `issue` consumes `monitor_inexact`, so the signal cannot stay sticky and delay later
+ /// screenshots until the five-second settle maximum.
#[test]
fn monitor_inexact_is_consumed_by_each_issue_attempt() {
let ctx = egui::Context::default();
@@ -969,6 +1054,8 @@ mod tests {
assert!(!app.monitor_inexact, "a sticky flag would delay every later screenshot by up to five seconds");
}
+ /// An unissued request follows a geometry change: its expected size and budget are recomputed
+ /// and it waits for fresh settling passes before issuing.
#[test]
fn a_geometry_change_retries_an_unissued_capture_with_new_budget() {
let ctx = egui::Context::default();
@@ -987,6 +1074,8 @@ mod tests {
assert!(!app.shots.requests[0].issued, "the retry waits for its own settling passes");
}
+ /// When a resize pushes both queued shots over the aggregate budget, each is rejected with
+ /// its own token and removal of the first cannot shift the second's index.
#[test]
fn mixed_order_geometry_failures_reject_every_shot_without_shifting_indices() {
let ctx = egui::Context::default();
diff --git a/crates/ui-egui/src/i18n/mod.rs b/crates/ui-egui/src/i18n/mod.rs
index 3fc984673..fb3314562 100644
--- a/crates/ui-egui/src/i18n/mod.rs
+++ b/crates/ui-egui/src/i18n/mod.rs
@@ -269,7 +269,7 @@ pub fn fmt(template: &str, args: &[(&str, &str)]) -> String {
const JAPANESE_SAMPLE: &str = "日本語ファイル編集あア";
/// Installed families preferred for Japanese interface text, best first (Gothic / sans-serif faces
-/// read best at menu sizes). Any other installed face that covers [`JAPANESE_SAMPLE`] is used if
+/// read best at menu sizes). Any other installed face that covers `JAPANESE_SAMPLE` is used if
/// none of these is present.
const PREFERRED_JAPANESE: &[&str] = &[
"Hiragino Sans",
@@ -314,7 +314,7 @@ pub fn system_japanese_font() -> Option<Arc<egui::FontData>> {
}
/// Whether the craft-fonts build input (empty unless built with `CRAFT_FONTS_DIR`) supplies a
-/// Japanese interface font: some craft-fonts face covers [`JAPANESE_SAMPLE`]. `theme::install` adds
+/// Japanese interface font: some craft-fonts face covers `JAPANESE_SAMPLE`. `theme::install` adds
/// these faces to every font family, so nothing else needs installing (and no system scan runs).
pub fn craft_japanese_font() -> bool {
filmcraft_text::fonts::craft_japanese().next().is_some()
diff --git a/crates/ui-egui/src/ime_reset.rs b/crates/ui-egui/src/ime_reset.rs
index bc4641d33..86a01a1fc 100644
--- a/crates/ui-egui/src/ime_reset.rs
+++ b/crates/ui-egui/src/ime_reset.rs
@@ -24,6 +24,8 @@ pub(crate) struct OutputContext {
}
impl OutputContext {
+ /// Snapshot the owner/generation/purpose triple that identifies one published custom IME
+ /// output.
pub(crate) fn of(ime: &egui::output::IMEOutput) -> Self {
Self { owner: ime.owner, generation: ime.context_generation, purpose: ime.purpose }
}
@@ -56,27 +58,39 @@ pub(crate) struct State {
}
impl State {
+ /// Start a pass for `ctx`'s viewport and clear the per-pass published-output record, so
+ /// `finish` cannot mistake a previous pass's descriptor for this pass's.
pub(crate) fn begin_pass(&mut self, ctx: &Context) {
self.viewport = ctx.viewport_id();
self.custom_output = None;
}
+ /// Whether a reset fence still guards `viewport`. While blocked, IME input for the custom
+ /// editor must not be admitted.
pub(crate) fn blocked(&self, viewport: ViewportId) -> bool {
self.pending.contains_key(&viewport)
}
+ /// The composition target being retired for `viewport`: the pending origin, or the last
+ /// completed origin until `terminal` clears it.
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())
}
+ /// Whether `destination` differs from the last one remembered for `viewport`; false when
+ /// nothing has been remembered yet.
pub(crate) fn incoming_changed(&self, viewport: ViewportId, destination: Destination) -> bool {
self.incoming.get(&viewport).is_some_and(|old| *old != destination)
}
+ /// Record the latest destination for `viewport`, so the next event can distinguish a real
+ /// target change from repeated observation of the same target.
pub(crate) fn remember(&mut self, viewport: ViewportId, destination: Destination) {
self.incoming.insert(viewport, destination);
}
+ /// Acknowledge a terminal IME event for `viewport`: forget the incoming destination and
+ /// completed origin so stale targets cannot be reused.
pub(crate) fn terminal(&mut self, viewport: ViewportId) {
self.incoming.remove(&viewport);
self.completed_origin.remove(&viewport);
@@ -100,6 +114,8 @@ impl State {
}
}
+ /// Move a pending fence to `Suspended` and drop its old output binding. Only an actually
+ /// eligible final descriptor in `finish` may rearm it; `sync`/`interrupt` reconciliation cannot.
pub(crate) fn suspend(&mut self, viewport: ViewportId) {
if let Some(pending) = self.pending.get_mut(&viewport) {
pending.phase = Phase::Suspended;
@@ -107,10 +123,15 @@ impl State {
}
}
+ /// Whether the custom output published in this pass is the one recorded by `produced`.
+ /// False when no custom output was produced in this pass.
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
}
+ /// Allocate a reset fence for the current viewport after clearing the previous fence's
+ /// output binding. Allocation failure leaves the phase `AllocationFailed`, which still
+ /// blocks input; a later real destination change can request again.
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
@@ -130,6 +151,11 @@ impl State {
}
}
+ /// Validate a completion token and release the viewport's guard. The token must belong to
+ /// this viewport and equal the current `Awaiting` id, and `destination` must equal the
+ /// pending destination; `ctx.output` is deliberately not consulted because raw events run
+ /// before this pass publishes its descriptor. Any mismatch returns false and keeps the
+ /// guard. Success records the origin and destination for the next observation.
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 };
@@ -149,6 +175,8 @@ impl State {
true
}
+ /// Record the custom output descriptor published in this pass, for `finish` and
+ /// `owns_output` to compare against the actual output.
pub(crate) fn produced(&mut self, key: OutputContext) {
self.custom_output = Some(key);
}
@@ -180,6 +208,8 @@ impl State {
pending.output = custom;
}
+ /// Forget all reset state for a closed viewport: pending fence, incoming destination and
+ /// completed origin.
pub(crate) fn end_viewport(&mut self, viewport: ViewportId) {
self.pending.remove(&viewport);
self.incoming.remove(&viewport);
@@ -187,10 +217,14 @@ impl State {
}
}
+/// Temp-data key marking whether `viewport` is inside a UI pass rather than a hidden logic
+/// callback.
fn mode_id(viewport: ViewportId) -> Id {
Id::unique(("filmcraft-ime-reset-ui-pass", viewport))
}
+/// Whether the current callback is a UI pass (between the installed begin/end-pass hooks)
+/// for this viewport, rather than `run_logic`. Defaults to false when no hook ran.
pub(crate) fn in_ui_pass(ctx: &Context) -> bool {
ctx.data(|data| data.get_temp::<bool>(mode_id(ctx.viewport_id()))).unwrap_or(false)
}
@@ -222,15 +256,20 @@ pub(crate) fn install(ctx: &Context) {
mod tests {
use super::*;
+ /// A fixed destination for one editor owner with caret 3 and committed-text stamp 17.
fn destination() -> Destination {
Destination { document: 1, target: ImeTarget::new(Id::unique("film-model-editor"), 1), caret: 3, anchor: 3, text: 17 }
}
+ /// Build the IME output a custom producer publishes for `destination` with the given
+ /// generation and purpose.
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.
+ /// Run one real UI pass that publishes a custom `output` and calls `finish` as eligible;
+ /// return the reset request the Context attached, if any.
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());
@@ -244,6 +283,8 @@ mod tests {
id
}
+ /// A generation or purpose change supersedes the old fence, old tokens cannot complete, an
+ /// allocation failure stays blocked, and a later real destination change retries.
#[test]
fn changed_output_context_supersedes_and_allocation_failure_stays_blocked() {
let ctx = Context::default();
@@ -276,6 +317,8 @@ mod tests {
assert!(!state.complete(&ctx, retry, changed));
}
+ /// `sync` followed by `finish` in the same pass allocates exactly one request and keeps it
+ /// as the awaiting boundary.
#[test]
fn same_pass_sync_and_finish_keep_one_request() {
let ctx = Context::default();
@@ -303,6 +346,8 @@ mod tests {
result.textures_delta.clear();
}
+ /// `finish` reuses the replacement request allocated by `sync` instead of allocating a
+ /// second one, and the stale token cannot release the guard.
#[test]
fn stale_output_binding_does_not_force_a_second_request_on_sync_then_finish() {
let ctx = Context::default();
@@ -354,6 +399,8 @@ mod tests {
assert!(!state.blocked(ViewportId::ROOT));
}
+ /// If custom eligibility is lost after `sync`, stock IME may echo the queued token but it
+ /// cannot release the suspended guard; only a later eligible descriptor can.
#[test]
fn queued_before_absence_token_may_reach_stock_but_cannot_release_suspended_guard() {
let ctx = Context::default();
@@ -400,6 +447,8 @@ mod tests {
assert!(state.complete(&ctx, replacement, destination));
}
+ /// UI-pass mode is scoped per viewport, `install` is idempotent, and a child viewport's
+ /// completion cannot release ROOT's guard.
#[test]
fn pass_mode_is_per_viewport_and_foreign_completion_cannot_release_a_real_guard() {
let ctx = Context::default();
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 8c085703f..772999358 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -206,7 +206,7 @@ pub enum Dialog {
NewSequence,
/// Settings (Preferences window; page in `UiState::settings`).
Preferences,
- /// "Recover unsaved changes from <time>?" (shown at startup when a dead session left some).
+ /// "Recover unsaved changes from `<time>`?" (shown at startup when a dead session left some).
Recovery,
/// "Are you sure you want to discard your changes?" (File ▸ Revert).
RevertConfirm,
@@ -307,7 +307,7 @@ pub struct FilmcraftApp {
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`].
+ /// kept per egui viewport; a closed viewport is released in [`eframe::App::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
@@ -742,6 +742,10 @@ impl FilmcraftApp {
self.ime_composition_viewport = Some(self.ime_reset.viewport);
}
+ /// Feed the live local edit destination to the reset reducer before each raw event. When an
+ /// origin exists, a changed destination retires the old composition token and marks the
+ /// composition stale; an unchanged destination only re-arms a pending `NeedsRequest`. Call
+ /// with the editor's actual text, never a staged engine copy.
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;
@@ -761,6 +765,9 @@ impl FilmcraftApp {
self.ime_reset.sync(ctx, destination);
}
+ /// Retire the current composition and suspend this viewport's IME fence. UI paths that lose
+ /// the editor route through this; context-less control commands call
+ /// `invalidate_ime_composition` directly. Only an eligible final descriptor can re-arm the guard.
pub(crate) fn suspend_ime_input(&mut self, ctx: &egui::Context) {
self.ime_reset.viewport = ctx.viewport_id();
self.invalidate_ime_composition();
@@ -791,6 +798,10 @@ impl FilmcraftApp {
}
}
+ /// End-of-UI-pass reconciliation. Suspend and finish as ineligible when the custom output is
+ /// absent, the window is unfocused, a modal owns input, or the text edit lacks focus;
+ /// otherwise sync the live destination and let `finish` bind or allocate only for actual
+ /// custom eligibility.
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)
@@ -888,6 +899,7 @@ impl FilmcraftApp {
host.max(self.ui_clock)
}
+ /// Override `now()` with a deterministic value for tests; compiled only under `cfg(test)`.
#[cfg(test)]
pub(crate) fn set_now_for_test(&mut self, now: f64) {
self.test_now = Some(now);
@@ -1491,6 +1503,8 @@ impl FilmcraftApp {
self.upload_frame(ctx, name, key, img, true)
}
+ /// Fetch or create the named texture and upload only when `key` changed; `alpha` selects
+ /// transparent or opaque conversion. Returns the texture's stable id.
fn upload_frame(&mut self, ctx: &egui::Context, name: &str, key: FrameKey, img: &frames::Rgba, alpha: bool) -> egui::TextureId {
let image = || img.color_image(alpha);
if let Some((k, tex)) = self.textures.get_mut(name) {
@@ -2448,6 +2462,9 @@ impl FilmcraftApp {
}
}
+ /// Run one logic pass in order: retain the later UI clock, poll the native dialog, apply the
+ /// logic subsystems, advance playback, poll jobs, then drain completed screenshots and ask
+ /// for hidden paints. Safe on hidden logic-only callbacks.
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.
@@ -2467,6 +2484,10 @@ impl FilmcraftApp {
capture::request_hidden_paint(self, ctx);
}
+ /// Draw one real UI pass. Establish the UI clock offset once, run first-pass input handling,
+ /// draw panels under a panic guard, drain UI requests and observe the IME editor only after
+ /// this pass's commands ran. Screenshots are offered to `capture::issue`, which issues only
+ /// on an accepted pass.
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);
@@ -2562,6 +2583,9 @@ impl FilmcraftApp {
}
impl eframe::App for FilmcraftApp {
+ /// Snapshot this callback's fresh surface geometry, optionally synthesize macOS ctrl-click
+ /// and agent input, and offer at most one queued synthetic step. A step already preserved by
+ /// hidden logic callbacks is not appended twice; a real UI pass clears it.
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);
@@ -2621,11 +2645,15 @@ impl eframe::App for FilmcraftApp {
}
}
+ /// Eframe's hidden logic callback: run the logic pass, sync the IME target context, then
+ /// suspend reset state because a logic-only callback is never a UI pass.
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
self.logic_inner(ctx);
self.finish_ime_reset_logic(ctx);
}
+ /// Cancel outstanding screenshots with one error reply each, end per-viewport IME tracker and
+ /// reset state, and shut the session down so its recovery journal is flushed or removed.
fn on_exit(&mut self) {
// Late screenshot callbacks now find a dropped slot and write nothing; clients get one error.
capture::cancel_all(self);
@@ -2639,6 +2667,8 @@ impl eframe::App for FilmcraftApp {
self.session.shutdown();
}
+ /// Eframe's UI entry: begin this pass's IME reset state, suspend custom controls when no
+ /// eligible editor owns input, draw `ui_inner`, then run end-of-pass IME reconciliation.
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
let ctx = ui.ctx().clone();
self.ime_reset.begin_pass(&ctx);
@@ -3438,6 +3468,7 @@ mod lifecycle_synthetic_tests {
use super::FilmcraftApp;
+ /// Extract the pointer-moved positions from a raw event batch, for synthetic-input tests.
fn pointer_events(events: &[Event]) -> Vec<egui::Pos2> {
events
.iter()
diff --git a/crates/ui-egui/src/native_dialogs.rs b/crates/ui-egui/src/native_dialogs.rs
index a18ae8bf8..e1445155a 100644
--- a/crates/ui-egui/src/native_dialogs.rs
+++ b/crates/ui-egui/src/native_dialogs.rs
@@ -5,7 +5,7 @@
//! the desktop app on Linux, where the XDG portal call would otherwise hold the UI thread until the
//! user chooses, and GNOME offers to force-quit the window after about five seconds) gets the
//! dialog and answers on a channel; the frame loop keeps running, and the continuation runs on the
-//! frame the answer arrives ([`FilmcraftApp::poll_native_dialog`]). Without it the host's
+//! frame the answer arrives (`FilmcraftApp::poll_native_dialog`). Without it the host's
//! synchronous pickers (`pick_files`, `pick_save_as`, …) are called and the continuation runs at
//! once, as before: headless tests, the control channel's stand-ins and other hosts are unchanged.
//!
diff --git a/crates/ui-egui/src/panels/graphics.rs b/crates/ui-egui/src/panels/graphics.rs
index 9bce6b83a..4e5ca21f5 100644
--- a/crates/ui-egui/src/panels/graphics.rs
+++ b/crates/ui-egui/src/panels/graphics.rs
@@ -10,7 +10,7 @@
//! field. Double-clicking a text layer with the Selection tool also edits it.
//! - **Selection tool:** click selects a layer (bounding box with handles and anchor point); drag
//! moves it; drag the anchor point to move that alone. What a handle does depends on the layer
-//! (see [`HandleDrag`]): point text scales about its anchor point, a paragraph-text box is
+//! (see `HandleDrag`): point text scales about its anchor point, a paragraph-text box is
//! resized and its text re-wraps, a shape stretches away from its opposite side. A rectangle
//! also has four small circles just inside its corners: dragging one rounds all four corners.
//! - **Rectangle / Ellipse tools:** drag out a shape. **Pen tool:** click points; click the first
@@ -205,7 +205,7 @@ fn next_boundary(s: &str, i: usize) -> usize {
#[derive(Clone, Copy, Debug)]
enum DragKind {
Move,
- /// Handle `n` of the layer's box (see [`handle_points`] and [`HandleDrag`]).
+ /// Handle `n` of the layer's box (see [`handle_points`] and `HandleDrag`).
Handle(usize),
/// The layer's anchor point: it moves, the layer stays where it is.
Anchor,
@@ -1261,6 +1261,7 @@ struct PendingImeEdit {
application_mutation: bool,
}
+/// Build the receipt for committed `text` at `cursor`/`anchor`; no preedit text is attached.
fn ime_stamp(text: &str, cursor: usize, anchor: usize) -> ImeMutationStamp {
ImeMutationStamp::from_committed(text, cursor, anchor, None)
}
@@ -1296,6 +1297,8 @@ fn current_layer_text(session: &Session, clip: u64, layer: usize) -> Option<&str
effect.params.get("text")?.text_ref_at(it.source_time_at(t))
}
+/// Stable uid of the enabled layer at index `layer`, or 0 when that layer has no uid; `None`
+/// when the clip, item or layer is missing or disabled.
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))
}
@@ -1339,6 +1342,8 @@ fn layer_fingerprint(effect: &EffectInstance) -> u64 {
h
}
+/// Static-identity fingerprint of the enabled layer at `layer`, or `None` when it is not
+/// present. Editable text is excluded by [`layer_fingerprint`], so typing does not change it.
fn current_layer_fingerprint(session: &Session, clip: u64, layer: usize) -> Option<u64> {
current_layer_effect(session, clip, layer).map(layer_fingerprint)
}
@@ -1386,6 +1391,7 @@ const LAYOUT_PARAMS: &[&str] = &[
"rotation",
];
+/// Fold `bytes` into the FNV-1a-style hash accumulator `h`, allowing callers to chain fields.
fn hash_bytes(h: &mut u64, bytes: &[u8]) {
for &b in bytes {
*h ^= u64::from(b);
@@ -1393,6 +1399,8 @@ fn hash_bytes(h: &mut u64, bytes: &[u8]) {
}
}
+/// Hash the bits of a finite `f64`; all non-finite values share one representation so NaN
+/// payloads or evaluation details cannot change a layout identity.
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.
@@ -1403,10 +1411,13 @@ fn hash_f64(h: &mut u64, v: f64) {
}
}
+/// Hash an `f32` widened to `f64`, keeping the non-finite normalization of [`hash_f64`].
fn hash_f32(h: &mut u64, v: f32) {
hash_f64(h, f64::from(v));
}
+/// Hash an optional value with an explicit presence byte, followed by the inner value only
+/// when it is present. This keeps `None` distinct from any hashed `Some` payload.
fn hash_option<T>(h: &mut u64, value: Option<T>, hash: impl FnOnce(&mut u64, T)) {
match value {
Some(v) => {
@@ -1417,6 +1428,9 @@ fn hash_option<T>(h: &mut u64, value: Option<T>, hash: impl FnOnce(&mut u64, T))
}
}
+/// Hash a layout parameter by kind and value. Non-finite floats normalize through
+/// [`hash_f64`]; path payloads contribute only a tag because layout parameters do not use
+/// mask paths.
fn hash_param_value(h: &mut u64, value: &ParamValue) {
match value {
ParamValue::Float(v) => {
@@ -1459,6 +1473,10 @@ fn hash_param_value(h: &mut u64, value: &ParamValue) {
}
}
+/// Fingerprint every layout-affecting value of `effect` at tick `t`: the layout parameters
+/// evaluated at the playhead, character runs and pin data. Non-finite floats normalize, and
+/// the committed text bytes are not hashed directly, so caret/selection changes do not churn
+/// the fingerprint; a value or run change that can move the caret does.
fn layout_fingerprint(effect: &EffectInstance, t: Tick) -> u64 {
let mut h: u64 = 0x9e37_79b9_7f4a_7c15;
hash_bytes(&mut h, effect.effect.as_bytes());
@@ -1511,6 +1529,8 @@ fn layout_fingerprint(effect: &EffectInstance, t: Tick) -> u64 {
h
}
+/// Layout fingerprint of the layer at `layer` evaluated at the playhead's source time;
+/// `None` when the sequence, clip or layer is missing.
fn current_layer_layout_fingerprint(session: &Session, clip: u64, layer: usize) -> Option<u64> {
let sequence = session.active_sequence()?;
let t = session.playhead();
@@ -1574,6 +1594,10 @@ fn reconcile_gfx_edit(app: &mut FilmcraftApp) {
}
}
+/// Owner for the graphics text editor: sequence, clip and stable layer uid, falling back to
+/// the numeric layer index only when `uid` is 0. The replacement epoch is explicit. Caret,
+/// selection, text, revision, geometry, visual order and pointers are excluded so those
+/// changes do not churn the IME owner.
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
@@ -1583,6 +1607,8 @@ fn graphics_ime_target(sequence: u64, clip: u64, layer: usize, uid: u64, replace
ImeTarget::new(egui::Id::unique(("filmcraft.graphics.ime", sequence, clip, component_uid, component_index)), replacement_epoch)
}
+/// Current editor owner for the layer, using its live uid and the app's replacement epoch;
+/// `None` when there is no active sequence or the layer is unavailable.
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)?;
@@ -1597,6 +1623,8 @@ pub(crate) fn current_reset_destination(app: &FilmcraftApp) -> Option<crate::ime
Some(local_reset_destination(app, ed, text, target))
}
+/// Build the admission destination from the local edit and current document epoch, stamping
+/// the committed `text` while carrying the caret and anchor separately.
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) }
}
@@ -1634,10 +1662,13 @@ struct TextEditState {
}
impl TextEditState {
+ /// The caret/anchor pair sorted into a forward `(start, end)` selection range.
fn selection(&self) -> (usize, usize) {
(self.ed.caret.min(self.ed.anchor), self.ed.caret.max(self.ed.anchor))
}
+ /// Delete the sorted selection in place, collapse caret and anchor to its start and report
+ /// whether anything was removed. This does not set the batch's changed flags; callers do.
fn delete_selection(&mut self) -> bool {
let (a, b) = self.selection();
if a == b {
@@ -1696,6 +1727,8 @@ fn finish_text_event(app: &mut FilmcraftApp, ui: &egui::Ui, state: &TextEditStat
}
}
+/// Track this viewport's IME preedit target. Empty preedit becomes `TerminalPending` so a
+/// following empty commit still belongs to the same composition; non-empty becomes `Active`.
fn apply_preedit(app: &mut FilmcraftApp, ui: &egui::Ui, target: ImeTarget, text: &str) {
app.ime_composition_viewport = Some(ui.ctx().viewport_id());
if text.is_empty() {
@@ -1705,6 +1738,9 @@ fn apply_preedit(app: &mut FilmcraftApp, ui: &egui::Ui, target: ImeTarget, text:
}
}
+/// Apply a UTF-8 byte-count surrounding deletion after the staleness check. Only whole
+/// characters fully inside the reported byte ranges are removed, the selection is preserved
+/// and accepted deletions record an IME receipt; a stale event skips.
fn apply_delete_surrounding_bytes(app: &FilmcraftApp, state: &mut TextEditState, target: ImeTarget, before_bytes: usize, after_bytes: usize) -> EventFlow {
if ime_event_is_stale(app, target) {
return EventFlow::Skip;
@@ -1719,6 +1755,9 @@ fn apply_delete_surrounding_bytes(app: &FilmcraftApp, state: &mut TextEditState,
EventFlow::Applied
}
+/// Apply a character-count surrounding deletion after the staleness check. The selection is
+/// preserved, deletion stops at either text end and an accepted deletion records an IME
+/// receipt; a stale event skips.
fn apply_delete_surrounding_chars(app: &FilmcraftApp, state: &mut TextEditState, target: ImeTarget, before_chars: usize, after_chars: usize) -> EventFlow {
if ime_event_is_stale(app, target) {
return EventFlow::Skip;
@@ -1734,6 +1773,9 @@ fn apply_delete_surrounding_chars(app: &FilmcraftApp, state: &mut TextEditState,
EventFlow::Applied
}
+/// Insert application-origin typing or paste: strip control characters except newline,
+/// replace the selection, move the caret to the end and mark the batch as an ordinary
+/// application mutation. Input that sanitizes to nothing is skipped.
fn apply_text_input(state: &mut TextEditState, input: &str) -> EventFlow {
let s: String = input.chars().filter(|c| !c.is_control() || *c == '\n').collect();
if s.is_empty() {
@@ -1749,6 +1791,9 @@ fn apply_text_input(state: &mut TextEditState, input: &str) -> EventFlow {
EventFlow::Applied
}
+/// Apply an IME commit after the staleness check: clear the composition, insert sanitized
+/// committed text, or delete the selection when the commit is empty. Text changes record an
+/// IME receipt; a stale commit skips.
fn apply_ime_commit(app: &mut FilmcraftApp, state: &mut TextEditState, target: ImeTarget, input: &str) -> EventFlow {
if ime_event_is_stale(app, target) {
return EventFlow::Skip;
@@ -1775,6 +1820,8 @@ fn apply_ime_commit(app: &mut FilmcraftApp, state: &mut TextEditState, target: I
EventFlow::Applied
}
+/// Copy the sorted selection, and for Cut delete it and mark an application mutation. An
+/// empty selection is a no-op.
fn apply_copy_cut(ui: &egui::Ui, state: &mut TextEditState, cut: bool) -> EventFlow {
let (a, b) = state.selection();
if a < b {
@@ -1787,6 +1834,8 @@ fn apply_copy_cut(ui: &egui::Ui, state: &mut TextEditState, cut: bool) -> EventF
EventFlow::Applied
}
+/// Caret destination for Left: with no Shift collapse a selection to its start, otherwise
+/// move to the line start (Command), previous word (Alt) or previous character boundary.
fn left_target(state: &TextEditState, layout: &filmcraft_text::Layout, shift: bool, command: bool, alt: bool) -> usize {
let (a, _) = state.selection();
if !shift && state.ed.caret != state.ed.anchor {
@@ -1800,6 +1849,8 @@ fn left_target(state: &TextEditState, layout: &filmcraft_text::Layout, shift: bo
}
}
+/// Caret destination for Right: with no Shift collapse a selection to its end, otherwise
+/// move to the line end (Command), next word (Alt) or next character boundary.
fn right_target(state: &TextEditState, layout: &filmcraft_text::Layout, shift: bool, command: bool, alt: bool) -> usize {
let (_, b) = state.selection();
if !shift && state.ed.caret != state.ed.anchor {
@@ -1813,6 +1864,8 @@ fn right_target(state: &TextEditState, layout: &filmcraft_text::Layout, shift: b
}
}
+/// Caret destination for Up/Down: hit-test the same x on the adjacent line's baseline,
+/// clamping to the text start/end when there is no line in that direction.
fn vertical_target(state: &TextEditState, layout: &filmcraft_text::Layout, up: bool) -> usize {
let (x, _, line) = layout.caret(state.ed.caret);
let target = if up { line.checked_sub(1) } else { Some(line + 1).filter(|next| *next < layout.lines.len()) };
@@ -1823,6 +1876,9 @@ fn vertical_target(state: &TextEditState, layout: &filmcraft_text::Layout, up: b
}
}
+/// Apply a layout-derived caret destination after re-clamping it to a UTF-8 boundary in the
+/// current (possibly already edited) text. Without Shift the anchor collapses to the caret;
+/// any actual selection change invalidates the IME composition.
fn apply_moved_caret(app: &mut FilmcraftApp, state: &mut TextEditState, moved: Option<usize>, shift: bool) {
if let Some(m) = moved {
let previous_selection = (state.ed.caret, state.ed.anchor);
@@ -1839,6 +1895,9 @@ fn apply_moved_caret(app: &mut FilmcraftApp, state: &mut TextEditState, moved: O
}
}
+/// Apply one non-IME key press to the local edit: Enter/Backspace/Delete mutate text,
+/// Command+A selects all and arrows/Home/End move the caret. Text edits mark an application
+/// mutation; Escape stops editing and suspends IME input. Only Escape returns `Skip`.
fn apply_key_event(
app: &mut FilmcraftApp,
ui: &egui::Ui,
@@ -2132,6 +2191,8 @@ fn char_boundary_ceil(s: &str, mut i: usize) -> usize {
i
}
+/// Move `i` to a character boundary and then back up to `n` whole characters, stopping at
+/// the start. Hostile offsets and counts are clamped instead of slicing inside a character.
fn prev_n_chars(s: &str, mut i: usize, n: usize) -> usize {
i = char_boundary_floor(s, i);
for _ in 0..n {
@@ -2146,6 +2207,8 @@ fn prev_n_chars(s: &str, mut i: usize, n: usize) -> usize {
i
}
+/// Move `i` to a character boundary and then forward up to `n` whole characters, stopping at
+/// the end. Hostile offsets and counts are clamped instead of slicing inside a character.
fn next_n_chars(s: &str, mut i: usize, n: usize) -> usize {
i = char_boundary_ceil(s, i);
for _ in 0..n {
@@ -2304,6 +2367,8 @@ impl Ctx<'_> {
self.set(id, json!(nv));
}
}
+ /// Draw an inline numeric field without a label row or stopwatch, register it for automation
+ /// and emit the edited value through `Ctx::set` when it changes.
fn number_in(&mut self, vui: &mut egui::Ui, label: &str, field: NumberField<'_>) {
let NumberField { id, speed, range, decimals, unit } = field;
let v = pv(self.e, id, self.mt).as_f64().unwrap_or(0.0);
@@ -2363,6 +2428,9 @@ impl Ctx<'_> {
self.set(id, json!(format!("#{r8:02x}{g8:02x}{b8:02x}")));
}
}
+ /// Draw a combo box for a choice parameter, register it for automation and emit the selected
+ /// index through `Ctx::set` when it changes. An out-of-range current value displays as an
+ /// empty selection.
fn choice(&mut self, vui: &mut egui::Ui, id: &str, label: &str, opts: &[&str], width: f32) {
let cur = match pv(self.e, id, self.mt) {
ParamValue::Choice(c) => c as usize,
@@ -2950,6 +3018,8 @@ mod ime_byte_delete_tests {
surrounding_byte_deletion_ranges,
};
+ /// Floor/ceil byte offsets clamp to UTF-8 character boundaries, including offsets past the
+ /// end and offsets inside a multi-byte character.
#[test]
fn byte_boundaries_never_split_a_code_point() {
let s = "aé😀z"; // 1 + 2 + 4 + 1 bytes
@@ -2960,6 +3030,8 @@ mod ime_byte_delete_tests {
assert_eq!(char_boundary_floor(s, 999), s.len());
}
+ /// Byte-count surrounding deletion removes only whole characters: a partial é or emoji byte
+ /// count deletes nothing, and the selection itself is always excluded.
#[test]
fn deleting_surrounding_bytes_leaves_partial_characters() {
let s = "aé😀z"; // a=1, é=1..3, 😀=3..7, z=7..8
@@ -2978,6 +3050,8 @@ mod ime_byte_delete_tests {
assert_eq!(surrounding_byte_deletion_ranges(s, 1, 3, 1, 4), (0..1, 3..7));
}
+ /// Applying before/after surrounding deletions preserves a reversed selection's direction
+ /// while shifting both endpoints by the preceding deletion.
#[test]
fn surrounding_deletion_keeps_reversed_selection_direction() {
let mut text = "aé😀z".to_string();
@@ -2988,6 +3062,8 @@ mod ime_byte_delete_tests {
assert_eq!((ed.caret, ed.anchor), (2, 0), "primary caret stays after the anchor");
}
+ /// Hostile `gfxEdit` caret/anchor offsets inside multi-byte characters clamp to boundaries
+ /// without panicking.
#[test]
fn hostile_edit_offsets_are_clamped_to_char_boundaries() {
let s = "é😀";
@@ -2997,6 +3073,8 @@ mod ime_byte_delete_tests {
assert_eq!(s.get(ed.caret..ed.anchor), Some("é"));
}
+ /// Character-count deletion stops at both text ends and never splits a character, even for
+ /// counts larger than the text.
#[test]
fn character_deletion_is_bounded() {
let s = "aé😀z".to_string();
@@ -3006,6 +3084,8 @@ mod ime_byte_delete_tests {
assert_eq!(next_n_chars(&s, 1, 1), 3);
}
+ /// The IME context tracker keeps per-viewport generations, leaves other viewports untouched
+ /// and drops a closed viewport's state when it is observed again.
#[test]
fn tracker_state_is_scoped_per_viewport_and_closed_viewports_are_dropped() {
use egui::ViewportId;
@@ -3028,6 +3108,8 @@ mod ime_byte_delete_tests {
assert_ne!(reopened.context_generation, second.context_generation, "closed viewport state is dropped");
}
+ /// The graphics IME owner prefers stable uid identity, falls back to the layer index only
+ /// without a uid, and separates sequence and replacement epochs.
#[test]
fn ime_owner_uses_stable_component_identity_and_explicit_replacement() {
let a = graphics_ime_target(7, 11, 3, 42, 5);
diff --git a/crates/ui-egui/src/panels/settings.rs b/crates/ui-egui/src/panels/settings.rs
index 5838e3449..f7e1b36ab 100644
--- a/crates/ui-egui/src/panels/settings.rs
+++ b/crates/ui-egui/src/panels/settings.rs
@@ -1,4 +1,4 @@
-//! The Settings dialog (app menu ▸ Settings ▸ <category>; Edit ▸ Preferences in the in-window
+//! The Settings dialog (app menu ▸ Settings ▸ `<category>`; Edit ▸ Preferences in the in-window
//! menu bar; General is Cmd+,). One window titled "Preferences": the category list on the left,
//! the category's fields on the right, Help / Reset… / Cancel / OK at the bottom. The page layout
//! comes from the engine's field schema ([`filmcraft_engine::settings::categories`]); edits go to a
diff --git a/crates/ui-egui/src/scrub.rs b/crates/ui-egui/src/scrub.rs
index 714e9731c..66dcdeea0 100644
--- a/crates/ui-egui/src/scrub.rs
+++ b/crates/ui-egui/src/scrub.rs
@@ -57,7 +57,7 @@ impl FilmcraftApp {
}
}
- /// [`FilmcraftApp::scrub_audio`] with the clock and the button state given. Returns whether
+ /// `FilmcraftApp::scrub_audio` with the clock and the button state given. Returns whether
/// the scrub stream is still open.
pub fn scrub_tick(&mut self, now: f64, down: bool) -> bool {
let ph = self.session.playhead();
diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs
index 36b57165c..38ba08237 100644
--- a/crates/ui-egui/src/theme.rs
+++ b/crates/ui-egui/src/theme.rs
@@ -415,7 +415,7 @@ pub fn font_families() -> Vec<FontFamily> {
}
/// Install the Latin UI fonts, Chinese fallback (craft-fonts or an installed face), Japanese
-/// craft-fonts, Arabic and Hebrew fallbacks (craft-fonts or installed faces, [`crate::rtl`]) and
+/// craft-fonts, Arabic and Hebrew fallbacks (craft-fonts or installed faces, `crate::rtl`) and
/// egui visuals. Document names keep their glyphs in every interface language.
pub fn install(ctx: &egui::Context, t: &Tokens) {
let mut fonts = FontDefinitions::default();