Skip to content

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

egui037: simplify UI helpers and preserve pointer IME cancellation

skylar taylor-barrickec55f2bd8eac
diff --git a/crates/ui-egui/src/capture.rs b/crates/ui-egui/src/capture.rs
index 9259d1110..c8d69a3a2 100644
--- a/crates/ui-egui/src/capture.rs
+++ b/crates/ui-egui/src/capture.rs
@@ -11,10 +11,11 @@
//! is still settling therefore reaches its timeout. That fork gap is recorded as a prerequisite;
//! this module does not claim a hidden web capture works.
+use std::sync::Arc;
use std::sync::mpsc::Sender;
-use craft_ui::capture::CaptureSlot;
-use egui::ViewportCommand;
+use craft_ui::capture::{CaptureError, CaptureSlot};
+use egui::{ColorImage, ViewportCommand};
use serde_json::{Value, json};
use web_time::{Duration, Instant};
@@ -434,6 +435,77 @@ fn retry_geometry(app: &mut FilmcraftApp, ctx: &egui::Context, index: usize) ->
Ok(())
}
+/// Whether an unissued request has waited for enough accepted passes, including the bounded
+/// maximum when the monitor is still showing an inexact frame or the timeline is animating.
+fn shot_is_settled(now: Instant, monitor_inexact: bool, timeline_still: u32, shot: &Shot) -> bool {
+ if now < shot.ready_at || shot.frames < SETTLE_PASSES {
+ return false;
+ }
+ !((monitor_inexact || timeline_still < 2) && now < shot.ready_at + SETTLE_MAX)
+}
+
+/// The result of trying to issue one settled request. Every variant keeps the original admission
+/// order: identity failures reject, geometry changes retry, a missing crop target waits a bounded
+/// number of passes, and everything else issues in the current accepted UI pass.
+enum IssueOutcome {
+ Identity(String),
+ GeometryRetry,
+ CropDeferred,
+ Failed(String),
+ Issued,
+}
+
+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) {
+ return IssueOutcome::Identity(reason.to_string());
+ }
+ if geometry_reason(app, shot).is_some() {
+ return IssueOutcome::GeometryRetry;
+ }
+ let crop_result = match shot.crop_target.as_ref() {
+ Some(target) => target.resolve(&app.auto).map(Some),
+ None => Ok(None),
+ };
+ let resolved_crop = match crop_result {
+ Ok(crop) => crop,
+ Err(message) => {
+ let shot = &mut app.shots.requests[index];
+ if shot.crop_misses < CROP_SETTLE_PASSES {
+ // The panel may be shown by a request processed just before this admission;
+ // let the next accepted pass draw it before giving up.
+ shot.crop_misses = shot.crop_misses.saturating_add(1);
+ return IssueOutcome::CropDeferred;
+ }
+ return IssueOutcome::Failed(message);
+ }
+ };
+ let shot = &mut app.shots.requests[index];
+ let Some(callback) = shot.callback.take() else {
+ return IssueOutcome::Failed("screenshot failed: the capture callback was already consumed".into());
+ };
+ shot.crop = resolved_crop;
+ ctx.send_viewport_cmd_to(ctx.viewport_id(), ViewportCommand::Screenshot(callback));
+ shot.issued = true;
+ IssueOutcome::Issued
+}
+
+/// Reject failed requests from the highest index down, so an earlier removal cannot shift a later
+/// index and remove the wrong shot.
+fn reject_failures(app: &mut FilmcraftApp, mut failures: Vec<(usize, String)>) {
+ 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();
+ }
+ reject(shot.reply, shot.token, message);
+ }
+}
+
/// Issue settled requests. Called from every real `App::ui` pass (never from a hidden
/// `run_logic` tick), including the accepted final pass of a multipass layout. `monitor_inexact`
/// describes the pass that just drew the monitor, so consume it here: it must not stay sticky and
@@ -452,146 +524,116 @@ pub(crate) fn issue(app: &mut FilmcraftApp, ctx: &egui::Context) {
}
app.shots.requests[i].frames = app.shots.requests[i].frames.saturating_add(1);
let shot = &app.shots.requests[i];
- if now < shot.ready_at || shot.frames < SETTLE_PASSES {
- continue;
- }
- // After a seek the monitor can show the nearest cached picture until the exact frame is
- // decoded, and the Timeline can still be animating. Capture once those have settled, or
- // after the same bounded maximum the old `Ui` settle path used.
- if (monitor_inexact || app.timeline_still < 2) && now < shot.ready_at + SETTLE_MAX {
+ if !shot_is_settled(now, monitor_inexact, app.timeline_still, shot) {
continue;
}
- if let Some(reason) = identity_reason(app, ctx, shot) {
- failures.push((i, reason.to_string()));
- continue;
- }
- if geometry_reason(app, shot).is_some() {
- retries.push(i);
- continue;
+ match try_issue_shot(app, ctx, i) {
+ IssueOutcome::Identity(reason) => failures.push((i, reason)),
+ IssueOutcome::GeometryRetry => retries.push(i),
+ IssueOutcome::CropDeferred => ctx.request_repaint(),
+ IssueOutcome::Failed(message) => failures.push((i, message)),
+ IssueOutcome::Issued => {}
}
- let crop_result = match app.shots.requests[i].crop_target.as_ref() {
- Some(target) => target.resolve(&app.auto).map(Some),
- None => Ok(None),
- };
- let resolved_crop = match crop_result {
- Ok(crop) => crop,
- Err(message) => {
- let shot = &mut app.shots.requests[i];
- if shot.crop_misses < CROP_SETTLE_PASSES {
- // The panel may be shown by a request processed just before this admission;
- // let the next accepted pass draw it before giving up.
- shot.crop_misses = shot.crop_misses.saturating_add(1);
- ctx.request_repaint();
- continue;
- }
- failures.push((i, message));
- continue;
- }
- };
- let shot = &mut app.shots.requests[i];
- let Some(callback) = shot.callback.take() else {
- failures.push((i, "screenshot failed: the capture callback was already consumed".into()));
- continue;
- };
- shot.crop = resolved_crop;
- ctx.send_viewport_cmd_to(ctx.viewport_id(), ViewportCommand::Screenshot(callback));
- shot.issued = true;
}
for i in retries.into_iter().rev() {
if let Err(message) = retry_geometry(app, ctx, i) {
failures.push((i, message));
}
}
- // 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();
- }
- reject(shot.reply, shot.token, message);
- }
+ reject_failures(app, failures);
if !app.shots.is_empty() {
ctx.request_repaint_after(REPAINT_INTERVAL);
}
}
+/// The next step for one drain scan position. `Keep` advances to the next request; every removal
+/// variant leaves the index unchanged so it sees the shot shifted into place.
+enum DrainStep {
+ Keep,
+ Timeout,
+ Identity(String),
+ Geometry,
+ Complete(Result<Arc<ColorImage>, CaptureError>),
+}
+
+fn drain_step(app: &FilmcraftApp, ctx: &egui::Context, index: usize, now: Instant) -> DrainStep {
+ let shot = &app.shots.requests[index];
+ if now >= shot.deadline {
+ return DrainStep::Timeout;
+ }
+ if let Some(reason) = identity_reason(app, ctx, shot) {
+ return DrainStep::Identity(reason.to_string());
+ }
+ if geometry_reason(app, shot).is_some() {
+ if !shot.issued {
+ // The next accepted UI pass re-creates the slot against the fresh geometry.
+ return DrainStep::Keep;
+ }
+ // Geometry changed while the callback was already issued: reject stale pixels rather
+ // than pairing them with the new surface.
+ return DrainStep::Geometry;
+ }
+ if !shot.issued {
+ return DrainStep::Keep;
+ }
+ let Some(result) = shot.slot.as_ref().and_then(CaptureSlot::take) else {
+ return DrainStep::Keep;
+ };
+ DrainStep::Complete(result)
+}
+
+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 {
+ slot.cancel();
+ }
+ reject(shot.reply, shot.token, message);
+}
+
+/// Build the saved-image reply, using the rendered scale of the delivered texture for crops.
+fn image_reply(shot: &Shot, image: &ColorImage) -> Value {
+ if image.size != shot.expected {
+ return error_reply(
+ shot.token,
+ format!(
+ "screenshot is {}×{} pixels, expected {}×{}: the window changed size while it was captured",
+ image.size[0], image.size[1], shot.expected[0], shot.expected[1]
+ ),
+ );
+ }
+ let captured_ppp = shot.geometry.surface.captured_pixels_per_point();
+ let mut reply = crate::control::save_screenshot_with_ppp(image, shot.path.as_deref(), shot.crop, captured_ppp);
+ if let Some(object) = reply.as_object_mut() {
+ object.insert("request".into(), json!(shot.token));
+ }
+ reply
+}
+
+fn complete_shot(mut shot: Shot, result: Result<Arc<ColorImage>, CaptureError>) {
+ if let Some(slot) = shot.slot.take() {
+ slot.cancel();
+ }
+ let reply = match result {
+ Ok(image) => image_reply(&shot, &image),
+ Err(error) => error_reply(shot.token, error),
+ };
+ let _ = shot.reply.send(reply);
+}
+
/// Drain completed slots and expire timed-out requests. Call from every logic callback (including
/// hidden ones). The deadline is checked before taking or writing an image.
pub(crate) fn drain(app: &mut FilmcraftApp, ctx: &egui::Context) {
let mut i = 0;
while i < app.shots.requests.len() {
let now = Instant::now();
- if now >= app.shots.requests[i].deadline {
- let shot = app.shots.requests.remove(i);
- if let Some(slot) = shot.slot {
- slot.cancel();
- }
- reject(shot.reply, shot.token, "no frame was presented before the screenshot timeout");
- continue;
- }
- if let Some(reason) = identity_reason(app, ctx, &app.shots.requests[i]) {
- let shot = app.shots.requests.remove(i);
- if let Some(slot) = shot.slot {
- slot.cancel();
- }
- reject(shot.reply, shot.token, format!("screenshot failed: {reason}"));
- continue;
- }
- if geometry_reason(app, &app.shots.requests[i]).is_some() {
- if !app.shots.requests[i].issued {
- // The next accepted UI pass re-creates the slot against the fresh geometry.
- i += 1;
- continue;
- }
- // Geometry changed while the callback was already issued: reject stale pixels rather
- // than pairing them with the new surface.
- let shot = app.shots.requests.remove(i);
- if let Some(slot) = shot.slot {
- slot.cancel();
- }
- reject(shot.reply, shot.token, "screenshot failed: the window geometry changed while the capture was in flight");
- continue;
- }
- if !app.shots.requests[i].issued {
- i += 1;
- continue;
- }
- let Some(result) = app.shots.requests[i].slot.as_ref().and_then(CaptureSlot::take) else {
- i += 1;
- continue;
- };
- let shot = app.shots.requests.remove(i);
- if let Some(slot) = shot.slot {
- slot.cancel();
- }
- match result {
- Ok(image) => {
- let reply = if image.size != shot.expected {
- error_reply(
- shot.token,
- format!(
- "screenshot is {}×{} pixels, expected {}×{}: the window changed size while it was captured",
- image.size[0], image.size[1], shot.expected[0], shot.expected[1]
- ),
- )
- } else {
- let captured_ppp = shot.geometry.surface.captured_pixels_per_point();
- let mut reply = crate::control::save_screenshot_with_ppp(&image, shot.path.as_deref(), shot.crop, captured_ppp);
- if let Some(object) = reply.as_object_mut() {
- object.insert("request".into(), json!(shot.token));
- }
- reply
- };
- let _ = shot.reply.send(reply);
- }
- Err(error) => {
- let _ = shot.reply.send(error_reply(shot.token, error));
+ match drain_step(app, ctx, i, now) {
+ DrainStep::Keep => i += 1,
+ DrainStep::Timeout => remove_and_reject(app, i, "no frame was presented before the screenshot timeout"),
+ DrainStep::Identity(reason) => remove_and_reject(app, i, format!("screenshot failed: {reason}")),
+ DrainStep::Geometry => remove_and_reject(app, i, "screenshot failed: the window geometry changed while the capture was in flight"),
+ DrainStep::Complete(result) => {
+ let shot = app.shots.requests.remove(i);
+ complete_shot(shot, result);
}
}
}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 37247080b..8c085703f 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -2328,12 +2328,9 @@ pub fn install_ime_reset_callbacks(ctx: &egui::Context) {
}
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);
+ /// Install the theme once, then keep fonts ready; a saved language without its system face
+ /// falls back to English as before.
+ fn logic_theme(&mut self, ctx: &egui::Context) {
if !self.styled {
theme::install(ctx, &self.tokens);
// theme::install replaces the fonts: add the system Japanese font back (or fall back to
@@ -2351,6 +2348,11 @@ impl FilmcraftApp {
} else {
self.fonts_ready = true;
}
+ }
+
+ /// Advance the monotonic host clock and the smoothed frame rate, returning the pass time.
+ /// Hidden playback is marked so a hidden window's skipped frames are not counted as drops.
+ fn logic_clock(&mut self, ctx: &egui::Context) -> f64 {
// Monotonic host time. Native and web both call logic once per layout pass and through
// `run_logic` while hidden; `ctx.input(i.time)` is stale in that second case.
let now = self.now();
@@ -2363,6 +2365,11 @@ impl FilmcraftApp {
// Nothing is shown while the window is hidden: not a dropped frame.
self.playback.hidden = true;
}
+ now
+ }
+
+ /// Close-request handling and control-driven synthetic input, in the original order.
+ fn logic_control(&mut self, ctx: &egui::Context) {
// Quitting with unsaved changes asks to save them first.
if ctx.input(|i| i.viewport().close_requested()) && panels::clip_dialogs::intercept_quit(self) {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
@@ -2380,8 +2387,10 @@ impl FilmcraftApp {
// honours this; the pinned web runner logs it as unhandled (a recorded fork gap).
ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaintWhileHidden);
}
+ }
- // Background work: consumed queues and idempotent deadlines, safe on every logic call.
+ /// Background queues and idempotent deadlines that are safe on every logic call.
+ fn logic_background(&mut self, ctx: &egui::Context, now: f64) {
self.frames.set_context(ctx);
self.frames.pump(std::time::Duration::from_millis(if self.playback.playing { 24 } else { 40 }));
self.session.poll_persistence();
@@ -2396,6 +2405,10 @@ impl FilmcraftApp {
self.sync_pool();
#[cfg(not(target_arch = "wasm32"))]
self.tick_media_refresh(ctx, now);
+ }
+
+ /// Apply engine events that change the active sequence/view, IME target, toast or project.
+ fn logic_session_events(&mut self, now: f64) {
for ev in self.session.drain_events() {
match ev {
filmcraft_engine::Event::OpenSequence(_) => {
@@ -2417,6 +2430,10 @@ impl FilmcraftApp {
filmcraft_engine::Event::ProjectChanged { .. } => {}
}
}
+ }
+
+ /// Drain native menu/control command ids, preserving the control-only Quit exception.
+ fn logic_command_inbox(&mut self, ctx: &egui::Context) {
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)
@@ -2429,6 +2446,20 @@ impl FilmcraftApp {
}
self.command_inbox = Some(rx);
}
+ }
+
+ 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);
+ self.logic_theme(ctx);
+ let now = self.logic_clock(ctx);
+ self.logic_control(ctx);
+ self.logic_background(ctx, now);
+ self.logic_session_events(now);
+ self.logic_command_inbox(ctx);
self.advance_playback(ctx);
self.advance_source_playback(ctx);
self.poll_jobs(ctx);
diff --git a/crates/ui-egui/src/panels/effect_controls.rs b/crates/ui-egui/src/panels/effect_controls.rs
index eef9bcac1..6a9b98f0d 100644
--- a/crates/ui-egui/src/panels/effect_controls.rs
+++ b/crates/ui-egui/src/panels/effect_controls.rs
@@ -11,6 +11,7 @@ use crate::FilmcraftApp;
use crate::icons::{self, Icon};
use crate::state::KeyframeRef;
use crate::theme::Tokens;
+use crate::widgets::HotNumberOptions;
#[path = "effect_controls_selection.rs"]
mod selection;
@@ -602,22 +603,38 @@ pub(crate) fn param_row(
match (&pd.kind, &value) {
(ParamKind::Float { min, max, soft_min, soft_max, unit, decimals }, ParamValue::Float(v)) => {
let speed = ((soft_max - soft_min) / 400.0).max(0.01);
- let (_, nv) = crate::widgets::hot_number(&mut vui, crate::i18n::t(pd.label), id, *v, speed, (*min, *max), *decimals as usize, unit, &t);
+ let (_, nv) = crate::widgets::hot_number(
+ &mut vui,
+ crate::i18n::t(pd.label),
+ id,
+ *v,
+ HotNumberOptions::new(speed, (*min, *max), *decimals as usize, unit, &t),
+ );
if let Some(nv) = nv {
set = Some(json!(nv));
}
}
(ParamKind::Angle, ParamValue::Float(v)) => {
- let (_, nv) = crate::widgets::hot_number(&mut vui, crate::i18n::t(pd.label), id, *v, 0.5, (-36000.0, 36000.0), 1, "°", &t);
+ let (_, nv) = crate::widgets::hot_number(&mut vui, crate::i18n::t(pd.label), id, *v, HotNumberOptions::new(0.5, (-36000.0, 36000.0), 1, "°", &t));
if let Some(nv) = nv {
set = Some(json!(nv));
}
}
(ParamKind::Point, ParamValue::Vec2(p)) => {
- let (_, nx) =
- crate::widgets::hot_number(&mut vui, &format!("{} X", crate::i18n::t(pd.label)), id.with("x"), p.x, 1.0, (-100_000.0, 100_000.0), 1, "", &t);
- let (_, ny) =
- crate::widgets::hot_number(&mut vui, &format!("{} Y", crate::i18n::t(pd.label)), id.with("y"), p.y, 1.0, (-100_000.0, 100_000.0), 1, "", &t);
+ let (_, nx) = crate::widgets::hot_number(
+ &mut vui,
+ &format!("{} X", crate::i18n::t(pd.label)),
+ id.with("x"),
+ p.x,
+ HotNumberOptions::new(1.0, (-100_000.0, 100_000.0), 1, "", &t),
+ );
+ let (_, ny) = crate::widgets::hot_number(
+ &mut vui,
+ &format!("{} Y", crate::i18n::t(pd.label)),
+ id.with("y"),
+ p.y,
+ HotNumberOptions::new(1.0, (-100_000.0, 100_000.0), 1, "", &t),
+ );
if nx.is_some() || ny.is_some() {
set = Some(json!([nx.unwrap_or(p.x), ny.unwrap_or(p.y)]));
}
@@ -824,11 +841,7 @@ pub fn lumetri_panel(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
crate::i18n::t(pd.label),
egui::Id::unique(("lum", pd.id)),
val,
- (soft_max - soft_min) / 300.0,
- (*min, *max),
- 1,
- "",
- &t,
+ HotNumberOptions::new((soft_max - soft_min) / 300.0, (*min, *max), 1, "", &t),
);
if s.changed() {
actions.push(json!({"clip": clip.0, "effect": idx, "param": pd.id, "value": val}));
@@ -930,11 +943,7 @@ pub fn properties_panel(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
&format!("{label} X"),
egui::Id::unique(("pp", p, "x", clip.0)),
v.x,
- speed,
- range,
- 0,
- " X",
- &t,
+ HotNumberOptions::new(speed, range, 0, " X", &t),
);
vui.add_space(10.0);
let (_, ny) = crate::widgets::hot_number(
@@ -942,11 +951,7 @@ pub fn properties_panel(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
&format!("{label} Y"),
egui::Id::unique(("pp", p, "y", clip.0)),
v.y,
- speed,
- range,
- 0,
- " Y",
- &t,
+ HotNumberOptions::new(speed, range, 0, " Y", &t),
);
if nx.is_some() || ny.is_some() {
actions.push((
@@ -961,11 +966,7 @@ pub fn properties_panel(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
label,
egui::Id::unique(("pp", p, clip.0)),
v,
- speed,
- range,
- if p == "scale" { 0 } else { 1 },
- unit,
- &t,
+ HotNumberOptions::new(speed, range, if p == "scale" { 0 } else { 1 }, unit, &t),
);
if let Some(nv) = nv {
actions.push(("effects.setParam".into(), json!({"clip": clip.0, "effect": "motion", "param": p, "value": nv})));
@@ -982,7 +983,13 @@ pub fn properties_panel(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
.layout(egui::Layout::left_to_right(egui::Align::Center)),
);
if let Some(ParamValue::Float(v)) = val("opacity", "opacity") {
- let (_, nv) = crate::widgets::hot_number(&mut vui, tl!("Opacity"), egui::Id::unique(("pp-op", clip.0)), v, 0.5, (0.0, 100.0), 0, " %", &t);
+ let (_, nv) = crate::widgets::hot_number(
+ &mut vui,
+ tl!("Opacity"),
+ egui::Id::unique(("pp-op", clip.0)),
+ v,
+ HotNumberOptions::new(0.5, (0.0, 100.0), 0, " %", &t),
+ );
if let Some(nv) = nv {
actions.push(("effects.setParam".into(), json!({"clip": clip.0, "effect": "opacity", "param": "opacity", "value": nv})));
}
@@ -999,7 +1006,13 @@ pub fn properties_panel(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
.layout(egui::Layout::left_to_right(egui::Align::Center)),
);
let v = val("crop", p).and_then(|v| v.as_f64()).unwrap_or(0.0);
- let (_, nv) = crate::widgets::hot_number(&mut vui, label, egui::Id::unique(("pp-crop", p, clip.0)), v, 0.2, (0.0, 100.0), 1, " %", &t);
+ let (_, nv) = crate::widgets::hot_number(
+ &mut vui,
+ label,
+ egui::Id::unique(("pp-crop", p, clip.0)),
+ v,
+ HotNumberOptions::new(0.2, (0.0, 100.0), 1, " %", &t),
+ );
if let Some(nv) = nv {
if crop.is_none() {
actions.push(("effects.apply".into(), json!({"clips": [clip.0], "effect": "crop"})));
@@ -1023,7 +1036,13 @@ pub fn properties_panel(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
.layout(egui::Layout::left_to_right(egui::Align::Center)),
);
let v = val("volume", "level").and_then(|v| v.as_f64()).unwrap_or(0.0);
- let (_, nv) = crate::widgets::hot_number(&mut vui, tl!("Level"), egui::Id::unique(("pp-vol", clip.0)), v, 0.1, (-96.0, 15.0), 1, " dB", &t);
+ let (_, nv) = crate::widgets::hot_number(
+ &mut vui,
+ tl!("Level"),
+ egui::Id::unique(("pp-vol", clip.0)),
+ v,
+ HotNumberOptions::new(0.1, (-96.0, 15.0), 1, " dB", &t),
+ );
if let Some(nv) = nv {
actions.push(("effects.setParam".into(), json!({"clip": clip.0, "effect": "volume", "param": "level", "value": nv})));
}
@@ -1035,7 +1054,13 @@ pub fn properties_panel(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
.layout(egui::Layout::left_to_right(egui::Align::Center)),
);
let v = val("panner", "balance").and_then(|v| v.as_f64()).unwrap_or(0.0);
- let (_, nv) = crate::widgets::hot_number(&mut vui, tl!("Pan"), egui::Id::unique(("pp-pan", clip.0)), v, 0.5, (-100.0, 100.0), 0, "", &t);
+ let (_, nv) = crate::widgets::hot_number(
+ &mut vui,
+ tl!("Pan"),
+ egui::Id::unique(("pp-pan", clip.0)),
+ v,
+ HotNumberOptions::new(0.5, (-100.0, 100.0), 0, "", &t),
+ );
if let Some(nv) = nv {
actions.push(("effects.setParam".into(), json!({"clip": clip.0, "effect": "panner", "param": "balance", "value": nv})));
}
diff --git a/crates/ui-egui/src/panels/graphics.rs b/crates/ui-egui/src/panels/graphics.rs
index 8ff14fd4f..a41a7b7fd 100644
--- a/crates/ui-egui/src/panels/graphics.rs
+++ b/crates/ui-egui/src/panels/graphics.rs
@@ -36,6 +36,7 @@ use crate::FilmcraftApp;
use crate::icons::{self, Icon};
use crate::state::{GfxEdit, TextPropsDialog, Tool};
use crate::theme::Tokens;
+use crate::widgets::HotNumberOptions;
/// A graphic layer visible at the playhead, with its layer→screen transform.
pub struct LayerView {
@@ -1611,12 +1612,364 @@ fn ime_event_is_stale(app: &FilmcraftApp, target: ImeTarget) -> bool {
}
}
+/// Whether an event was fully handled or must skip the per-event IME destination update, which
+/// mirrors the original loop's `continue` paths.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum EventFlow {
+ Applied,
+ Skip,
+}
+
+/// Mutable state for one batch of text-editor events: the committed text, caret/selection, the IME
+/// receipt chain, and whether the batch contains ordinary application-origin edits.
+struct TextEditState {
+ ed: GfxEdit,
+ text: String,
+ changed: bool,
+ stop: bool,
+ application_mutation: bool,
+ custom_mutations: bool,
+ ime_before: Option<(usize, usize)>,
+ ime_after: Vec<ImeMutationStamp>,
+}
+
+impl TextEditState {
+ fn selection(&self) -> (usize, usize) {
+ (self.ed.caret.min(self.ed.anchor), self.ed.caret.max(self.ed.anchor))
+ }
+
+ fn delete_selection(&mut self) -> bool {
+ let (a, b) = self.selection();
+ if a == b {
+ return false;
+ }
+ self.text.replace_range(a..b, "");
+ self.ed.caret = a;
+ self.ed.anchor = a;
+ true
+ }
+
+ /// Record the first pre-mutation caret/anchor and the post-mutation stamp. The caller records
+ /// only after an accepted IME mutation, exactly as the original inline arms did.
+ fn record_ime_change(&mut self, before: (usize, usize)) {
+ self.ime_before.get_or_insert(before);
+ self.ime_after.push(ime_stamp(&self.text, self.ed.caret, self.ed.anchor));
+ self.changed = true;
+ }
+}
+
+/// The per-event prologue: sync the live destination, consume IME-reset completions, and reject
+/// events while a reset blocks IME input. `None` is the original loop's `continue`.
+fn begin_text_event(app: &mut FilmcraftApp, ui: &egui::Ui, state: &TextEditState, target: ImeTarget, event: &egui::Event) -> Option<(bool, bool)> {
+ let destination = local_reset_destination(app, &state.ed, &state.text, target);
+ if state.custom_mutations {
+ app.sync_live_ime_destination(ui.ctx(), destination);
+ }
+ if let egui::Event::ImeResetCompleted { request_id } = event {
+ if state.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;
+ }
+ return None;
+ }
+ if !state.custom_mutations || (app.ime_reset.blocked(ui.ctx().viewport_id()) && matches!(event, egui::Event::Ime(_))) {
+ return None;
+ }
+ let from_ime = matches!(event, egui::Event::Ime(_));
+ let terminal = matches!(event, egui::Event::Ime(egui::ImeEvent::Commit(_)));
+ Some((from_ime, terminal))
+}
+
+/// The per-event epilogue: remember or terminal-acknowledge an IME event's destination, or keep
+/// the live destination in sync for ordinary application edits.
+fn finish_text_event(app: &mut FilmcraftApp, ui: &egui::Ui, state: &TextEditState, target: ImeTarget, from_ime: bool, terminal: bool) {
+ let current = local_reset_destination(app, &state.ed, &state.text, 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 state.custom_mutations {
+ app.sync_live_ime_destination(ui.ctx(), current);
+ }
+}
+
+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() {
+ app.ime_composition = Some(crate::ImeComposition::TerminalPending(target));
+ } else {
+ app.ime_composition = Some(crate::ImeComposition::Active(target));
+ }
+}
+
+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;
+ }
+ let (a, b) = state.selection();
+ let (before, after) = surrounding_byte_deletion_ranges(&state.text, a, b, before_bytes, after_bytes);
+ if !before.is_empty() || !after.is_empty() {
+ let previous = (state.ed.caret, state.ed.anchor);
+ apply_surrounding_deletion(&mut state.text, &mut state.ed, before, after);
+ state.record_ime_change(previous);
+ }
+ EventFlow::Applied
+}
+
+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;
+ }
+ let (a, b) = state.selection();
+ let before = prev_n_chars(&state.text, a, before_chars)..a;
+ let after = b..next_n_chars(&state.text, b, after_chars);
+ if !before.is_empty() || !after.is_empty() {
+ let previous = (state.ed.caret, state.ed.anchor);
+ apply_surrounding_deletion(&mut state.text, &mut state.ed, before, after);
+ state.record_ime_change(previous);
+ }
+ EventFlow::Applied
+}
+
+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() {
+ return EventFlow::Skip;
+ }
+ state.delete_selection();
+ let at = state.ed.caret;
+ state.text.insert_str(at, &s);
+ state.ed.caret += s.len();
+ state.ed.anchor = state.ed.caret;
+ state.application_mutation = true;
+ state.changed = true;
+ EventFlow::Applied
+}
+
+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;
+ }
+ app.ime_composition = None;
+ app.ime_composition_viewport = None;
+ let s: String = input.chars().filter(|c| !c.is_control() || *c == '\n').collect();
+ let previous = (state.ed.caret, state.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 state.delete_selection() {
+ state.record_ime_change(previous);
+ }
+ } else {
+ state.delete_selection();
+ let at = state.ed.caret;
+ state.text.insert_str(at, &s);
+ state.ed.caret += s.len();
+ state.ed.anchor = state.ed.caret;
+ state.record_ime_change(previous);
+ }
+ EventFlow::Applied
+}
+
+fn apply_copy_cut(ui: &egui::Ui, state: &mut TextEditState, cut: bool) -> EventFlow {
+ let (a, b) = state.selection();
+ if a < b {
+ ui.ctx().copy_text(state.text[a..b].to_string());
+ if cut && state.delete_selection() {
+ state.application_mutation = true;
+ state.changed = true;
+ }
+ }
+ EventFlow::Applied
+}
+
+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 {
+ a
+ } else if command {
+ layout.lines[layout.caret(state.ed.caret).2].range.start
+ } else if alt {
+ word_left(&state.text, state.ed.caret)
+ } else {
+ prev_boundary(&state.text, state.ed.caret)
+ }
+}
+
+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 {
+ b
+ } else if command {
+ layout.lines[layout.caret(state.ed.caret).2].range.end
+ } else if alt {
+ word_right(&state.text, state.ed.caret)
+ } else {
+ next_boundary(&state.text, state.ed.caret)
+ }
+}
+
+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()) };
+ match target {
+ Some(next) => layout.hit(x, layout.lines[next].baseline),
+ None if up => 0,
+ None => state.text.len(),
+ }
+}
+
+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);
+ // `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.
+ state.ed.caret = char_boundary_floor(&state.text, m);
+ if !shift {
+ state.ed.anchor = state.ed.caret;
+ }
+ if previous_selection != (state.ed.caret, state.ed.anchor) {
+ app.invalidate_ime_composition();
+ }
+ }
+}
+
+fn apply_key_event(
+ app: &mut FilmcraftApp,
+ ui: &egui::Ui,
+ state: &mut TextEditState,
+ layout: &filmcraft_text::Layout,
+ key: egui::Key,
+ modifiers: egui::Modifiers,
+) -> EventFlow {
+ let shift = modifiers.shift;
+ let mut moved = None;
+ match key {
+ 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.
+ state.stop = true;
+ state.custom_mutations = false;
+ app.suspend_ime_input(ui.ctx());
+ return EventFlow::Skip;
+ }
+ egui::Key::Enter => {
+ state.delete_selection();
+ let at = state.ed.caret;
+ state.text.insert(at, '\n');
+ state.ed.caret += 1;
+ state.ed.anchor = state.ed.caret;
+ state.application_mutation = true;
+ state.changed = true;
+ }
+ egui::Key::Backspace => {
+ let mut did = state.delete_selection();
+ if !did && state.ed.caret > 0 {
+ let p = if modifiers.alt || modifiers.command { word_left(&state.text, state.ed.caret) } else { prev_boundary(&state.text, state.ed.caret) };
+ let end = state.ed.caret;
+ state.text.replace_range(p..end, "");
+ state.ed.caret = p;
+ state.ed.anchor = p;
+ did = true;
+ }
+ if did {
+ state.application_mutation = true;
+ state.changed = true;
+ }
+ }
+ egui::Key::Delete => {
+ let mut did = state.delete_selection();
+ if !did && state.ed.caret < state.text.len() {
+ let n = next_boundary(&state.text, state.ed.caret);
+ let at = state.ed.caret;
+ state.text.replace_range(at..n, "");
+ did = true;
+ }
+ if did {
+ state.application_mutation = true;
+ state.changed = true;
+ }
+ }
+ egui::Key::A if modifiers.command => {
+ let moved = (state.ed.anchor, state.ed.caret) != (0, state.text.len());
+ state.ed.anchor = 0;
+ state.ed.caret = state.text.len();
+ if moved {
+ app.invalidate_ime_composition();
+ }
+ }
+ egui::Key::ArrowLeft => {
+ moved = Some(left_target(state, layout, shift, modifiers.command, modifiers.alt));
+ }
+ egui::Key::ArrowRight => {
+ moved = Some(right_target(state, layout, shift, modifiers.command, modifiers.alt));
+ }
+ egui::Key::ArrowUp | egui::Key::ArrowDown => {
+ moved = Some(vertical_target(state, layout, key == egui::Key::ArrowUp));
+ }
+ egui::Key::Home => moved = Some(layout.lines[layout.caret(state.ed.caret).2].range.start),
+ egui::Key::End => moved = Some(layout.lines[layout.caret(state.ed.caret).2].range.end),
+ _ => {}
+ }
+ apply_moved_caret(app, state, moved, shift);
+ EventFlow::Applied
+}
+
+/// Apply one already-admitted event. The match arms keep the original order and short-circuits;
+/// `Skip` reproduces the inline `continue` for stale or empty IME/text events.
+fn apply_text_event(
+ app: &mut FilmcraftApp,
+ ui: &egui::Ui,
+ state: &mut TextEditState,
+ target: ImeTarget,
+ layout: &filmcraft_text::Layout,
+ event: egui::Event,
+) -> EventFlow {
+ let is_cut = matches!(&event, egui::Event::Cut);
+ match event {
+ egui::Event::Ime(egui::ImeEvent::Preedit { text, .. }) => {
+ apply_preedit(app, ui, target, &text);
+ EventFlow::Applied
+ }
+ // 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 }) => {
+ apply_delete_surrounding_bytes(app, state, target, before_bytes, after_bytes)
+ }
+ egui::Event::Ime(egui::ImeEvent::DeleteSurrounding { before_chars, after_chars }) => {
+ apply_delete_surrounding_chars(app, state, target, before_chars, after_chars)
+ }
+ // ordinary typing and paste are application-origin, even in the same pass as an IME event
+ egui::Event::Text(s) | egui::Event::Paste(s) => apply_text_input(state, &s),
+ // an input method (Chinese, Japanese, Korean) hands over its finished text as a commit (#1083)
+ egui::Event::Ime(egui::ImeEvent::Commit(s)) => apply_ime_commit(app, state, target, &s),
+ egui::Event::Copy | egui::Event::Cut => apply_copy_cut(ui, state, is_cut),
+ egui::Event::Key { key, pressed: true, modifiers, .. } => apply_key_event(app, ui, state, layout, key, modifiers),
+ // 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, .. } => {
+ state.custom_mutations = false;
+ app.suspend_ime_input(ui.ctx());
+ EventFlow::Applied
+ }
+ _ => EventFlow::Applied,
+ }
+}
+
/// Keyboard handling while a text layer is being edited.
fn text_edit(
app: &mut FilmcraftApp,
ui: &mut egui::Ui,
v: &LayerView,
- mut ed: GfxEdit,
+ ed: GfxEdit,
resp: &egui::Response,
actions: &mut Vec<(String, Value)>,
pending_ime: &mut Option<PendingImeEdit>,
@@ -1657,292 +2010,59 @@ fn text_edit(
app.suspended_ime_controls(ui.ctx());
return;
};
- let mut text = tp.text.clone();
+ let mut state = TextEditState {
+ ed,
+ text: tp.text.clone(),
+ changed: false,
+ stop: false,
+ application_mutation: false,
+ custom_mutations: true,
+ ime_before: None,
+ ime_after: Vec::new(),
+ };
// `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);
+ clamp_edit_offsets(&state.text, &mut state.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 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);
- if a == b {
- return false;
- }
- text.replace_range(a..b, "");
- ed.caret = a;
- ed.anchor = a;
- true
- };
+ let composition_target = graphics_ime_target(sequence, state.ed.clip, state.ed.layer, v.spec.uid, app.ime_replacement_epoch);
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;
- }
+ let Some((from_ime, terminal)) = begin_text_event(app, ui, &state, composition_target, &ev) else {
continue;
- }
- if !custom_mutations || (app.ime_reset.blocked(ui.ctx().viewport_id()) && matches!(&ev, egui::Event::Ime(_))) {
+ };
+ if apply_text_event(app, ui, &mut state, composition_target, &l, ev) == EventFlow::Skip {
continue;
}
- let from_ime = matches!(&ev, egui::Event::Ime(_));
- let terminal = matches!(&ev, egui::Event::Ime(egui::ImeEvent::Commit(_)));
- match ev {
- egui::Event::Ime(egui::ImeEvent::Preedit { text, .. }) => {
- app.ime_composition_viewport = Some(ui.ctx().viewport_id());
- if text.is_empty() {
- 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) {
- 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) {
- 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;
- }
- delete_sel(&mut text, &mut ed);
- 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) {
- 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;
- }
- } 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;
- }
- }
- egui::Event::Copy | egui::Event::Cut => {
- let (a, b) = sel(&ed);
- if a < b {
- ui.ctx().copy_text(text[a..b].to_string());
- if matches!(ev, egui::Event::Cut) && delete_sel(&mut text, &mut ed) {
- application_mutation = true;
- changed = true;
- }
- }
- }
- egui::Event::Key { key, pressed: true, modifiers, .. } => {
- let shift = modifiers.shift;
- let mut moved = None;
- match key {
- 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;
- custom_mutations = false;
- app.suspend_ime_input(ui.ctx());
- continue;
- }
- egui::Key::Enter => {
- delete_sel(&mut text, &mut ed);
- text.insert(ed.caret, '\n');
- ed.caret += 1;
- ed.anchor = ed.caret;
- application_mutation = true;
- changed = true;
- }
- egui::Key::Backspace => {
- let mut did = delete_sel(&mut text, &mut ed);
- if !did && ed.caret > 0 {
- let p = if modifiers.alt || modifiers.command { word_left(&text, ed.caret) } else { prev_boundary(&text, ed.caret) };
- text.replace_range(p..ed.caret, "");
- ed.caret = p;
- ed.anchor = p;
- did = true;
- }
- if did {
- application_mutation = true;
- changed = true;
- }
- }
- egui::Key::Delete => {
- let mut did = delete_sel(&mut text, &mut ed);
- if !did && ed.caret < text.len() {
- let n = next_boundary(&text, ed.caret);
- text.replace_range(ed.caret..n, "");
- did = true;
- }
- if did {
- application_mutation = true;
- changed = true;
- }
- }
- egui::Key::A if modifiers.command => {
- let moved = (ed.anchor, ed.caret) != (0, text.len());
- ed.anchor = 0;
- ed.caret = text.len();
- if moved {
- app.invalidate_ime_composition();
- }
- }
- egui::Key::ArrowLeft => {
- let (a, _) = sel(&ed);
- moved = Some(if !shift && ed.caret != ed.anchor {
- a
- } else if modifiers.command {
- l.lines[l.caret(ed.caret).2].range.start
- } else if modifiers.alt {
- word_left(&text, ed.caret)
- } else {
- prev_boundary(&text, ed.caret)
- });
- }
- egui::Key::ArrowRight => {
- let (_, b) = sel(&ed);
- moved = Some(if !shift && ed.caret != ed.anchor {
- b
- } else if modifiers.command {
- l.lines[l.caret(ed.caret).2].range.end
- } else if modifiers.alt {
- word_right(&text, ed.caret)
- } else {
- next_boundary(&text, ed.caret)
- });
- }
- egui::Key::ArrowUp | egui::Key::ArrowDown => {
- let (x, _, li) = l.caret(ed.caret);
- let target = if key == egui::Key::ArrowUp { li.checked_sub(1) } else { Some(li + 1).filter(|n| *n < l.lines.len()) };
- moved = Some(match target {
- Some(n) => l.hit(x, l.lines[n].baseline),
- None if key == egui::Key::ArrowUp => 0,
- None => text.len(),
- });
- }
- egui::Key::Home => moved = Some(l.lines[l.caret(ed.caret).2].range.start),
- egui::Key::End => moved = Some(l.lines[l.caret(ed.caret).2].range.end),
- _ => {}
- }
- if let Some(m) = moved {
- let previous_selection = (ed.caret, ed.anchor);
- // `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;
- }
- 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, .. } => {
- custom_mutations = false;
- app.suspend_ime_input(ui.ctx());
- }
- _ => {}
- }
- 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);
- }
+ finish_text_event(app, ui, &state, composition_target, from_ime, terminal);
}
- if changed && text != tp.text {
+ if state.changed && state.text != tp.text {
let action_index = actions.len();
+ let ime_before = state.ime_before;
let first_before =
- ime_before.and_then(|(cursor, anchor)| (!ime_after.is_empty()).then(|| ImeMutationStamp::from_committed(&tp.text, cursor, anchor, None)));
+ ime_before.and_then(|(cursor, anchor)| (!state.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,
+ clip: state.ed.clip,
+ layer: state.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,
+ before_cursor: ime_before.map_or(state.ed.caret, |(cursor, _)| cursor),
+ before_anchor: ime_before.map_or(state.ed.anchor, |(_, anchor)| anchor),
+ final_cursor: state.ed.caret,
+ final_anchor: state.ed.anchor,
+ application_mutation: state.application_mutation,
+ after: state.ime_after,
});
- actions.push(("graphics.setText".into(), json!({"clip": ed.clip, "layer": ed.layer, "text": text, "merge": true})));
+ let text = std::mem::take(&mut state.text);
+ actions.push(("graphics.setText".into(), json!({"clip": state.ed.clip, "layer": state.ed.layer, "text": text, "merge": true})));
} else {
*pending_ime = None;
}
- if stop {
+ if state.stop {
end_edit(app, ui);
} else {
- app.ui.gfx_edit = Some(ed);
+ app.ui.gfx_edit = Some(state.ed);
}
}
@@ -2082,6 +2202,15 @@ fn color32(c: [f32; 4]) -> Color32 {
Color32::from_rgba_unmultiplied(q(c[0]), q(c[1]), q(c[2]), q(c[3]))
}
+/// The formatting knobs of an inline graphics number field.
+struct NumberField<'a> {
+ id: &'a str,
+ speed: f64,
+ range: (f64, f64),
+ decimals: usize,
+ unit: &'a str,
+}
+
struct Ctx<'a> {
clip: ClipId,
layer: usize,
@@ -2162,17 +2291,29 @@ impl Ctx<'_> {
fn number(&mut self, ui: &mut egui::Ui, label: &str, id: &str, speed: f64, range: (f64, f64), dec: usize, unit: &str) {
let v = pv(self.e, id, self.mt).as_f64().unwrap_or(0.0);
let (r, mut vui) = self.row(ui, label);
- let (resp, nv) =
- crate::widgets::hot_number(&mut vui, label, egui::Id::unique(("gfxp", self.clip.0, self.layer, id)), v, speed, range, dec, unit, &self.t);
+ let (resp, nv) = crate::widgets::hot_number(
+ &mut vui,
+ label,
+ egui::Id::unique(("gfxp", self.clip.0, self.layer, id)),
+ v,
+ HotNumberOptions::new(speed, range, dec, unit, &self.t),
+ );
self.auto(id, resp.rect, label);
self.stopwatch(ui, r, id);
if let Some(nv) = nv {
self.set(id, json!(nv));
}
}
- fn number_in(&mut self, vui: &mut egui::Ui, label: &str, id: &str, speed: f64, range: (f64, f64), dec: usize, unit: &str) {
+ 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);
- let (resp, nv) = crate::widgets::hot_number(vui, label, egui::Id::unique(("gfxp", self.clip.0, self.layer, id)), v, speed, range, dec, unit, &self.t);
+ let (resp, nv) = crate::widgets::hot_number(
+ vui,
+ label,
+ egui::Id::unique(("gfxp", self.clip.0, self.layer, id)),
+ v,
+ HotNumberOptions::new(speed, range, decimals, unit, &self.t),
+ );
self.auto(id, resp.rect, id);
if let Some(nv) = nv {
self.set(id, json!(nv));
@@ -2187,11 +2328,7 @@ impl Ctx<'_> {
&format!("{label} X"),
egui::Id::unique(("gfxp", self.clip.0, self.layer, id, "x")),
v.x,
- 1.0,
- (-100_000.0, 100_000.0),
- 1,
- " X",
- &self.t,
+ HotNumberOptions::new(1.0, (-100_000.0, 100_000.0), 1, " X", &self.t),
);
vui.add_space(10.0);
let (ry, ny) = crate::widgets::hot_number(
@@ -2199,11 +2336,7 @@ impl Ctx<'_> {
&format!("{label} Y"),
egui::Id::unique(("gfxp", self.clip.0, self.layer, id, "y")),
v.y,
- 1.0,
- (-100_000.0, 100_000.0),
- 1,
- " Y",
- &self.t,
+ HotNumberOptions::new(1.0, (-100_000.0, 100_000.0), 1, " Y", &self.t),
);
self.auto(&format!("{id}.x"), rx.rect, label);
self.auto(&format!("{id}.y"), ry.rect, label);
@@ -2698,7 +2831,7 @@ pub fn properties(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
cx.check(&mut vui, on, "");
cx.color(&mut vui, col);
vui.add_space(6.0);
- cx.number_in(&mut vui, &format!("{label} width"), w, 0.2, (0.0, 1000.0), 1, "");
+ cx.number_in(&mut vui, &format!("{label} width"), NumberField { id: w, speed: 0.2, range: (0.0, 1000.0), decimals: 1, unit: "" });
vui.add_space(6.0);
cx.choice(&mut vui, kind, graphic::STROKE_OPTS, 70.0);
}
@@ -2906,4 +3039,85 @@ mod ime_byte_delete_tests {
let no_uid = graphics_ime_target(7, 11, 3, 0, 5);
assert_ne!(no_uid, graphics_ime_target(7, 11, 4, 0, 5), "without a layer uid, the index is the identity");
}
+
+ /// A pointer-down starts a new target, so later Text, Paste and IME events in the same raw
+ /// batch must not be applied to the layer that was being edited before the click. The old loop
+ /// cleared `custom_mutations` here; the extracted helper once fell through to `Applied` and
+ /// typed every later event into the old layer.
+ #[test]
+ fn pointer_press_rejects_text_paste_and_ime_later_in_the_same_raw_batch() {
+ use filmcraft_geom::{Affine, Vec2};
+ use filmcraft_project::ClipId;
+ use filmcraft_project::graphic::{Appearance, LayerContent, LayerSpec, LayerTransform, TextProps};
+
+ let mut app = crate::FilmcraftApp::new(filmcraft_engine::Session::default());
+ let ed = GfxEdit { clip: 1, layer: 0, caret: 3, anchor: 3, ..Default::default() };
+ app.ui.gfx_edit = Some(ed.clone());
+ let props = TextProps {
+ text: "old".into(),
+ font: String::new(),
+ style: String::new(),
+ size: 72.0,
+ align: 0,
+ tracking: 0.0,
+ kerning: true,
+ ligatures: true,
+ leading: 0.0,
+ baseline_shift: 0.0,
+ faux_bold: false,
+ faux_italic: false,
+ caps: 0,
+ underline: false,
+ box_width: 0.0,
+ box_height: 0.0,
+ vertical: false,
+ runs: Vec::new(),
+ };
+ let view = super::LayerView {
+ clip: ClipId(1),
+ layer: 0,
+ spec: LayerSpec {
+ name: "Text".into(),
+ enabled: true,
+ uid: 0,
+ pin: None,
+ content: LayerContent::Text(props),
+ appearance: Appearance { fill: None, gradient: None, strokes: Vec::new(), background: None, shadow: None },
+ transform: LayerTransform { position: Vec2::ZERO, anchor: Vec2::ZERO, scale: Vec2::new(1.0, 1.0), rotation: 0.0, opacity: 1.0 },
+ },
+ to_screen: Affine::IDENTITY,
+ canvas_to_screen: Affine::IDENTITY,
+ local: [-50.0, -25.0, 50.0, 25.0],
+ };
+
+ let ctx = egui::Context::default();
+ let raw = egui::RawInput {
+ focused: true,
+ events: vec![
+ egui::Event::PointerButton {
+ pos: egui::pos2(20.0, 20.0),
+ button: egui::PointerButton::Primary,
+ pressed: true,
+ modifiers: egui::Modifiers::NONE,
+ },
+ egui::Event::Text("typed".into()),
+ egui::Event::Paste("pasted".into()),
+ egui::Event::Ime(egui::ImeEvent::Commit("committed".into())),
+ ],
+ ..Default::default()
+ };
+ let mut actions = Vec::new();
+ let mut pending_ime = None;
+ let mut focused = false;
+ let mut out = ctx.run_ui(raw, |ui| {
+ let response = ui.allocate_response(egui::vec2(100.0, 100.0), egui::Sense::click());
+ super::text_edit(&mut app, ui, &view, ed.clone(), &response, &mut actions, &mut pending_ime);
+ focused = ui.memory(|m| m.has_focus(egui::Id::unique(super::TEXT_EDIT_ID)));
+ });
+ out.textures_delta.clear();
+
+ assert!(focused, "the text editor must own input for this batch");
+ assert!(actions.is_empty(), "the pointer press must stop Text, Paste and IME editing the old layer");
+ assert!(pending_ime.is_none(), "a rejected batch has no pending IME edit");
+ }
}
diff --git a/crates/ui-egui/src/panels/lumetri.rs b/crates/ui-egui/src/panels/lumetri.rs
index f7591e2ff..bd42b5d2c 100644
--- a/crates/ui-egui/src/panels/lumetri.rs
+++ b/crates/ui-egui/src/panels/lumetri.rs
@@ -17,6 +17,7 @@ use crate::FilmcraftApp;
use crate::icons::{self, Icon};
use crate::native_dialogs::FileDialog;
use crate::theme::Tokens;
+use crate::widgets::HotNumberOptions;
type Actions = Vec<Value>;
@@ -448,11 +449,7 @@ fn slider(
label,
egui::Id::unique(("lval", clip.0, id)),
v,
- (soft_max - soft_min) / 300.0,
- (min, max),
- decimals as usize,
- "",
- t,
+ HotNumberOptions::new((soft_max - soft_min) / 300.0, (min, max), decimals as usize, "", t),
);
if let Some(nv) = out.or(nv) {
actions.push(json!({"clip": clip.0, "effect": idx, "param": id, "value": (nv * 10f64.powi(decimals as i32)).round() / 10f64.powi(decimals as i32)}));
diff --git a/crates/ui-egui/src/panels/mixer.rs b/crates/ui-egui/src/panels/mixer.rs
index 0949545a2..6cbc05170 100644
--- a/crates/ui-egui/src/panels/mixer.rs
+++ b/crates/ui-egui/src/panels/mixer.rs
@@ -34,6 +34,7 @@ use serde_json::{Value, json};
use crate::FilmcraftApp;
use crate::icons::{self, Icon};
use crate::theme::Tokens;
+use crate::widgets::HotNumberOptions;
// ------------------------------------------------------------------------------------- fader law
@@ -657,7 +658,13 @@ fn strip(app: &mut FilmcraftApp, ui: &mut egui::Ui, cx: &mut Ctx, id: TrackId, s
}
let vr = Rect::from_center_size(pos2(kc.x, y + 48.0), vec2(56.0, 16.0));
let mut vui = ui.new_child(egui::UiBuilder::new().max_rect(vr).layout(egui::Layout::top_down(egui::Align::Center)));
- let (vresp, nv) = crate::widgets::hot_number(&mut vui, tl!("Pan"), egui::Id::unique((&ap, "panValue")), pan, 1.0, (-100.0, 100.0), 1, "", &t);
+ let (vresp, nv) = crate::widgets::hot_number(
+ &mut vui,
+ tl!("Pan"),
+ egui::Id::unique((&ap, "panValue")),
+ pan,
+ HotNumberOptions::new(1.0, (-100.0, 100.0), 1, "", &t),
+ );
app.auto.add(&format!("{ap}.panValue"), vresp.rect, &format!("{pan:.1}"));
if let Some(v) = nv {
cx.cmd("mixer.setValue", json!({"strip": sid, "lane": LANE_PAN, "value": v}));
@@ -793,8 +800,13 @@ fn strip(app: &mut FilmcraftApp, ui: &mut egui::Ui, cx: &mut Ctx, id: TrackId, s
// fader value (hot text)
let vr = Rect::from_min_size(pos2(x + 4.0, sr.max.y - name_h - value_h), vec2(56.0, value_h));
let mut vui = ui.new_child(egui::UiBuilder::new().max_rect(vr));
- let (vresp, nv) =
- crate::widgets::hot_number(&mut vui, tl!("Volume"), egui::Id::unique((&ap, "value")), vol.max(-96.0), 0.1, (FADER_MIN_DB, FADER_MAX_DB), 1, "", &t);
+ let (vresp, nv) = crate::widgets::hot_number(
+ &mut vui,
+ tl!("Volume"),
+ egui::Id::unique((&ap, "value")),
+ vol.max(-96.0),
+ HotNumberOptions::new(0.1, (FADER_MIN_DB, FADER_MAX_DB), 1, "", &t),
+ );
app.auto.add(&format!("{ap}.value"), vresp.rect, &db_text(vol));
if let Some(v) = nv {
cx.cmd("mixer.setValue", json!({"strip": sid, "lane": LANE_VOLUME, "value": v}));
@@ -862,7 +874,13 @@ fn pan51_panner(app: &mut FilmcraftApp, ui: &mut egui::Ui, cx: &mut Ctx, tr: &Tr
small_text(ui, pos2(col_x, r.min.y + 6.0), Align2::LEFT_CENTER, tl!("Center"), 9.0, t.text_dim);
let cr = Rect::from_min_size(pos2(col_x, r.min.y + 12.0), vec2(r.max.x - col_x, 14.0));
let mut cui = ui.new_child(egui::UiBuilder::new().max_rect(cr));
- let (cresp, nc) = crate::widgets::hot_number(&mut cui, tl!("Center"), egui::Id::unique((ap, "pan51.center")), center, 1.0, (0.0, 100.0), 0, "%", &t);
+ let (cresp, nc) = crate::widgets::hot_number(
+ &mut cui,
+ tl!("Center"),
+ egui::Id::unique((ap, "pan51.center")),
+ center,
+ HotNumberOptions::new(1.0, (0.0, 100.0), 0, "%", &t),
+ );
app.auto.add(&format!("{ap}.pan51.center"), cresp.rect, &format!("Center {center:.0} %"));
if let Some(v) = nc {
cx.cmd("mixer.setValue", json!({"strip": sid, "lane": LANE_PAN51_CENTER, "value": v}));
@@ -870,8 +888,13 @@ fn pan51_panner(app: &mut FilmcraftApp, ui: &mut egui::Ui, cx: &mut Ctx, tr: &Tr
small_text(ui, pos2(col_x, r.min.y + 32.0), Align2::LEFT_CENTER, "LFE", 9.0, t.text_dim);
let lr = Rect::from_min_size(pos2(col_x, r.min.y + 38.0), vec2(r.max.x - col_x, 14.0));
let mut lui = ui.new_child(egui::UiBuilder::new().max_rect(lr));
- let (lresp, nl) =
- crate::widgets::hot_number(&mut lui, "LFE", egui::Id::unique((ap, "pan51.lfe")), lfe.max(FADER_MIN_DB), 0.5, (FADER_MIN_DB, FADER_MAX_DB), 1, "", &t);
+ let (lresp, nl) = crate::widgets::hot_number(
+ &mut lui,
+ "LFE",
+ egui::Id::unique((ap, "pan51.lfe")),
+ lfe.max(FADER_MIN_DB),
+ HotNumberOptions::new(0.5, (FADER_MIN_DB, FADER_MAX_DB), 1, "", &t),
+ );
app.auto.add(&format!("{ap}.pan51.lfe"), lresp.rect, &format!("LFE {}", db_text(lfe)));
if let Some(v) = nl {
cx.cmd("mixer.setValue", json!({"strip": sid, "lane": LANE_PAN51_LFE, "value": v}));
@@ -1086,8 +1109,13 @@ pub fn clip_mixer(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
if !active {
vui.set_opacity(0.4);
}
- let (vresp, nv) =
- crate::widgets::hot_number(&mut vui, tl!("Volume"), egui::Id::unique((&ap, "value")), vol.max(-96.0), 0.1, (FADER_MIN_DB, FADER_MAX_DB), 1, "", &t);
+ let (vresp, nv) = crate::widgets::hot_number(
+ &mut vui,
+ tl!("Volume"),
+ egui::Id::unique((&ap, "value")),
+ vol.max(-96.0),
+ HotNumberOptions::new(0.1, (FADER_MIN_DB, FADER_MAX_DB), 1, "", &t),
+ );
app.auto.add(&format!("{ap}.value"), vresp.rect, &db_text(vol));
if let (Some(v), true) = (nv, active) {
set(&mut acts, "volume", "level", v, !vresp.dragged() || vresp.drag_started());
diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs
index f9caa667b..c7df56159 100644
--- a/crates/ui-egui/src/widgets.rs
+++ b/crates/ui-egui/src/widgets.rs
@@ -23,55 +23,80 @@ pub fn accessible_name(response: Response, name: impl Into<String>) -> Response
response
}
+/// Numeric formatting and theme context for a [`hot_number`] field.
+///
+/// Grouping the related knobs keeps the widget's call sites readable and below the argument-count
+/// limit; the fields are exactly the values the hot-number editor and drag handling need.
+pub struct HotNumberOptions<'a> {
+ /// Value change per dragged point at the normal modifier setting.
+ pub speed: f64,
+ /// Inclusive value bounds used when committing a drag or a typed calculation.
+ pub range: (f64, f64),
+ /// Digits after the decimal point in the displayed value.
+ pub decimals: usize,
+ /// Unit text drawn after the value and stripped from typed expressions.
+ pub suffix: &'a str,
+ /// Theme tokens for the hot-text colours.
+ pub tokens: &'a Tokens,
+}
+
+impl<'a> HotNumberOptions<'a> {
+ pub const fn new(speed: f64, range: (f64, f64), decimals: usize, suffix: &'a str, tokens: &'a Tokens) -> Self {
+ Self { speed, range, decimals, suffix, tokens }
+ }
+}
+
/// Premiere "hot text": a blue number you drag horizontally to scrub, click to type a number or a
/// calculation ([`crate::calc`]). `label` is the property's accessible name (for example
/// "Position X"), used when the field switches to a text editor so screen readers can tell the
/// value fields apart.
/// Returns (response, Some(new value) when changed).
-pub fn hot_number(
- ui: &mut Ui,
- label: &str,
- id: egui::Id,
- value: f64,
- speed: f64,
- range: (f64, f64),
- decimals: usize,
- suffix: &str,
- t: &Tokens,
-) -> (Response, Option<f64>) {
+pub fn hot_number(ui: &mut Ui, label: &str, id: egui::Id, value: f64, options: HotNumberOptions<'_>) -> (Response, Option<f64>) {
let editing_id = id.with("editing");
- let edit_id = id.with("edit");
- let select_all_id = id.with("select-all");
let mut editing: Option<String> = ui.data(|d| d.get_temp(editing_id));
if let Some(buf) = editing.as_mut() {
- let r = accessible_name(ui.add(egui::TextEdit::singleline(buf).id(edit_id).desired_width(56.0).font(Tokens::ui(12.0))), label);
- let mut out = None;
- if r.lost_focus() {
- // the field's own unit can be typed anywhere; calc ignores the common ones
- let typed = if suffix.trim().is_empty() { buf.clone() } else { buf.replace(suffix.trim(), "") };
- if let Some(v) = crate::calc::eval(&typed, value) {
- out = Some(v.clamp(range.0, range.1));
- }
- ui.data_mut(|d| d.remove::<String>(editing_id));
- } else {
- let b = buf.clone();
- ui.data_mut(|d| d.insert_temp(editing_id, b));
- // select the whole value once the field has focus (egui collapses a selection to a caret
- // in a field that does not have it yet), so typing replaces it as in Premiere
- let selected_now = r.has_focus() && ui.data_mut(|d| d.remove_temp::<bool>(select_all_id)).is_some();
- if selected_now {
- let mut st = egui::text_edit::TextEditState::load(ui.ctx(), edit_id).unwrap_or_default();
- st.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(buf.chars().count()))));
- st.store(ui.ctx(), edit_id);
- }
- // the focus and the selection show on the next frame, which nothing else would trigger
- if !r.has_focus() || selected_now {
- ui.ctx().request_repaint();
- }
- r.request_focus();
+ return hot_number_editor(ui, label, id, value, options.range, options.suffix, buf);
+ }
+ hot_number_display(ui, id, value, options)
+}
+
+/// The single-line text editor shown after a click on a hot number.
+fn hot_number_editor(ui: &mut Ui, label: &str, id: egui::Id, value: f64, range: (f64, f64), suffix: &str, buf: &mut String) -> (Response, Option<f64>) {
+ let editing_id = id.with("editing");
+ let edit_id = id.with("edit");
+ let select_all_id = id.with("select-all");
+ let r = accessible_name(ui.add(egui::TextEdit::singleline(buf).id(edit_id).desired_width(56.0).font(Tokens::ui(12.0))), label);
+ let mut out = None;
+ if r.lost_focus() {
+ // the field's own unit can be typed anywhere; calc ignores the common ones
+ let typed = if suffix.trim().is_empty() { buf.clone() } else { buf.replace(suffix.trim(), "") };
+ if let Some(v) = crate::calc::eval(&typed, value) {
+ out = Some(v.clamp(range.0, range.1));
+ }
+ ui.data_mut(|d| d.remove::<String>(editing_id));
+ } else {
+ let b = buf.clone();
+ ui.data_mut(|d| d.insert_temp(editing_id, b));
+ // select the whole value once the field has focus (egui collapses a selection to a caret
+ // in a field that does not have it yet), so typing replaces it as in Premiere
+ let selected_now = r.has_focus() && ui.data_mut(|d| d.remove_temp::<bool>(select_all_id)).is_some();
+ if selected_now {
+ let mut st = egui::text_edit::TextEditState::load(ui.ctx(), edit_id).unwrap_or_default();
+ st.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(buf.chars().count()))));
+ st.store(ui.ctx(), edit_id);
}
- return (r, out);
+ // the focus and the selection show on the next frame, which nothing else would trigger
+ if !r.has_focus() || selected_now {
+ ui.ctx().request_repaint();
+ }
+ r.request_focus();
}
+ (r, out)
+}
+
+/// The painted, draggable value shown while the field is not in text-edit mode.
+fn hot_number_display(ui: &mut Ui, id: egui::Id, value: f64, options: HotNumberOptions<'_>) -> (Response, Option<f64>) {
+ let HotNumberOptions { speed, range, decimals, suffix, tokens: t } = options;
let text = format!("{value:.decimals$}{suffix}");
let galley = ui.painter().layout_no_wrap(text, Tokens::ui(12.0), t.hot_text);
let (rect, resp) = ui.allocate_exact_size(galley.size() + vec2(4.0, 4.0), Sense::click_and_drag());
@@ -85,15 +110,7 @@ pub fn hot_number(
let mut out = None;
if resp.dragged() {
let dx = resp.drag_delta().x as f64;
- let mult = ui.input(|i| {
- if i.modifiers.shift {
- 10.0
- } else if i.modifiers.command {
- 0.1
- } else {
- 1.0
- }
- });
+ let mult = hot_number_drag_multiplier(ui);
let nv = (value + dx * speed * mult).clamp(range.0, range.1);
if (nv - value).abs() > f64::EPSILON {
out = Some(nv);
@@ -101,14 +118,26 @@ pub fn hot_number(
}
if resp.clicked() {
ui.data_mut(|d| {
- d.insert_temp(editing_id, format!("{value:.decimals$}"));
- d.insert_temp(select_all_id, true);
+ d.insert_temp(id.with("editing"), format!("{value:.decimals$}"));
+ d.insert_temp(id.with("select-all"), true);
});
ui.ctx().request_repaint();
}
(resp, out)
}
+fn hot_number_drag_multiplier(ui: &Ui) -> f64 {
+ ui.input(|i| {
+ if i.modifiers.shift {
+ 10.0
+ } else if i.modifiers.command {
+ 0.1
+ } else {
+ 1.0
+ }
+ })
+}
+
/// A large blue timecode readout (monitors/timeline) that moves its playhead: drag horizontally to
/// scrub (1 frame per point, Shift ×10), click to type a time (Enter or clicking away commits,
/// Escape cancels). Returns the time to go to (never before `min`), or why a typed time is invalid.
@@ -397,7 +426,7 @@ mod tests {
let input = egui::RawInput { events, ..Default::default() };
// no renderer takes the font atlas upload here; drop it explicitly (epaint panics otherwise)
ctx.run_ui(input, |ui| {
- hot_number(ui, "Value", id, 123.5, 1.0, (0.0, 1000.0), 1, "", &t);
+ hot_number(ui, "Value", id, 123.5, HotNumberOptions::new(1.0, (0.0, 1000.0), 1, "", &t));
})
.textures_delta
.clear();
@@ -417,7 +446,7 @@ mod tests {
d.insert_temp(id.with("editing"), "12.5".to_string());
d.insert_temp(id.with("select-all"), false);
});
- hot_number(ui, "Position X", id, 12.5, 1.0, (-1000.0, 1000.0), 1, "", &t);
+ hot_number(ui, "Position X", id, 12.5, HotNumberOptions::new(1.0, (-1000.0, 1000.0), 1, "", &t));
},
(),
);