FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
ui: add an eyedropper to colour parameters
Guilhermeb-Ferrarezic2bde2e6fd47
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex a39dc82ea..9cef2af07 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -973,6 +973,8 @@Edit… Editar…Show graphs Mostrar gráficosToggle animation Activar/desactivar animación+ Eyedropper (pick a color from the Program monitor) Cuentagotas (tomar un color del monitor de programa)+ Eyedropper: no picture to sample Cuentagotas: no hay imagen de la que tomar el colorAdd/Remove Keyframe Añadir/quitar fotograma claveTemporal Interpolation Interpolación temporalLinear Linealdiff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rsindex 32cfa3e42..d302d2f4c 100644--- a/crates/ui-egui/src/icons.rs+++ b/crates/ui-egui/src/icons.rs@@ -114,6 +114,8 @@ pub enum Icon {Network,/// Media Browser: recent directories (a clock face).Clock,+ /// Colour parameters: pick a colour from the Program monitor (a pipette).+ Eyedropper,}pub struct Pen16<'a> {@@ -725,6 +727,13 @@ pub fn paint(painter: &Painter, rect: Rect, icon: Icon, color: Color32) {pen.circle(8.0, 8.0, 6.0);pen.line(&[(8.0, 4.5), (8.0, 8.0), (10.5, 9.5)]);}+ Eyedropper => {+ // a pipette: bulb at the top right, glass tube running to a tip at the bottom left+ pen.closed(&[(10.0, 4.5), (11.5, 3.0), (13.0, 3.0), (13.0, 4.5), (11.5, 6.0)]);+ pen.line(&[(8.2, 6.2), (10.8, 8.8)]);+ pen.line(&[(9.5, 7.5), (3.5, 12.5)]);+ pen.line(&[(3.5, 12.5), (2.5, 13.5)]);+ }}}@@ -853,6 +862,7 @@ mod tests {Drive,Network,Clock,+ Eyedropper,];/// Paint `icon` at `ppp` device pixels per point into a rect of `size` points whose corner isdiff --git a/crates/ui-egui/src/panels/effect_controls.rs b/crates/ui-egui/src/panels/effect_controls.rsindex e3ae049c4..8b87b6524 100644--- a/crates/ui-egui/src/panels/effect_controls.rs+++ b/crates/ui-egui/src/panels/effect_controls.rs@@ -466,6 +466,14 @@ pub(crate) fn param_row(if egui::color_picker::color_edit_button_rgba(&mut vui, &mut rgba, egui::color_picker::Alpha::Opaque).changed() {set = Some(json!([rgba.r(), rgba.g(), rgba.b(), rgba.a()]));}+ // Eyedropper: arm it, then click a pixel in the Program monitor (Esc cancels)+ let target = crate::state::Eyedropper { clip: clip.0, effect: idx, param: pd.id.to_string(), mask };+ let armed = app.ui.eyedropper.as_ref() == Some(&target);+ let drop = icons::button(&mut vui, Icon::Eyedropper, 18.0, armed, &t, tl!("Eyedropper (pick a color from the Program monitor)"));+ app.auto.add(&format!("effectControls.{}.{}.eyedropper", e.effect, pkey), drop.rect, "Eyedropper");+ if drop.clicked() {+ app.ui.eyedropper = if armed { None } else { Some(target) };+ }}(ParamKind::Path, _) => {crate::panels::masks::path_value(app, &mut vui, clip, idx, mask, actions);diff --git a/crates/ui-egui/src/panels/monitor.rs b/crates/ui-egui/src/panels/monitor.rsindex 39034bfaa..475bf9b6d 100644--- a/crates/ui-egui/src/panels/monitor.rs+++ b/crates/ui-egui/src/panels/monitor.rs@@ -284,6 +284,7 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)monitor_view::pan_input(app, ui, which, video_area, pic);}if which == Which::Program && show_picture {+ eyedropper(app, ui, &pic_resp, pic, target, rate, time);crate::panels::graphics::monitor_overlay(app, ui, pic, frame_size);crate::panels::masks::monitor_overlay(app, ui, pic, frame_size);}@@ -455,6 +456,97 @@ fn cpu_texture(}}+/// A click of an armed eyedropper waiting for its frame to render.+#[derive(Clone)]+struct EyedropperPick {+ /// The clicked point in the picture, 0..1 across and down.+ uv: (f32, f32),+ key: FrameKey,+ time: Tick,+ /// The project with the armed effect switched off, so a colour that effect keys out can be picked.+ project: std::sync::Arc<filmcraft_project::Project>,+}++/// Output scale of the frame an eyedropper samples (half size is plenty and quick to render).+const EYEDROPPER_SCALE: f32 = 0.5;++/// Eyedropper: while a colour parameter's eyedropper is armed (Effect Controls), the Program picture+/// takes a crosshair and a click fills that parameter with the colour under the pointer. The colour is+/// read from a render of the sequence at the playhead with the armed effect switched off (an Ultra Key+/// has already removed the green it is asked to key); Esc disarms.+fn eyedropper(app: &mut FilmcraftApp, ui: &mut egui::Ui, resp: &egui::Response, pic: Rect, target: Target, rate: filmcraft_time::FrameRate, time: Tick) {+ let Some(armed) = app.ui.eyedropper.clone() else { return };+ let ctx = ui.ctx().clone();+ let pending_id = egui::Id::new("eyedropper-pending");+ if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {+ app.ui.eyedropper = None;+ ctx.data_mut(|d| d.remove::<EyedropperPick>(pending_id));+ return;+ }+ if resp.hovered() {+ ctx.set_cursor_icon(egui::CursorIcon::Crosshair);+ }+ if resp.clicked()+ && let (Some(pos), Target::Sequence(seq)) = (resp.interact_pointer_pos(), target)+ && pic.width() > 0.0+ && pic.height() > 0.0+ {+ let uv = (((pos.x - pic.min.x) / pic.width()).clamp(0.0, 1.0), ((pos.y - pic.min.y) / pic.height()).clamp(0.0, 1.0));+ let mut project = (*app.session.project).clone();+ if let Some(e) = project.sequence_mut(seq).and_then(|q| q.find_item_mut(filmcraft_project::ClipId(armed.clip))).and_then(|(_, it)| it.effects.get_mut(armed.effect)) {+ e.enabled = false;+ }+ let frame = rate.frame_at(time);+ // a revision of its own, so this render never replaces what the monitor caches+ let revision = app.session.revision ^ 0x5eed_d70b_0000_0000 ^ armed.clip.rotate_left(17) ^ armed.effect as u64;+ let key = FrameKey { target, frame, size: (EYEDROPPER_SCALE * 1000.0) as u32, revision, draft: false };+ ctx.data_mut(|d| d.insert_temp(pending_id, EyedropperPick { uv, key, time: rate.tick_of(frame), project: std::sync::Arc::new(project) }));+ }+ let Some(pick) = ctx.data(|d| d.get_temp::<EyedropperPick>(pending_id)) else { return };+ app.frames.request(pick.key, pick.time, EYEDROPPER_SCALE, &pick.project, 0);+ let Some(img) = app.frames.get(&pick.key) else {+ ctx.request_repaint();+ return;+ };+ ctx.data_mut(|d| d.remove::<EyedropperPick>(pending_id));+ app.ui.eyedropper = None;+ let Some(rgb) = sample_rgb(&img, pick.uv) else {+ app.ui.status = tl!("Eyedropper: no picture to sample").to_string();+ return;+ };+ // the parameter stores linear values, like the colour picker beside it+ let lin = egui::Rgba::from(Color32::from_rgb(rgb[0], rgb[1], rgb[2]));+ let mut params = json!({"clip": armed.clip, "effect": armed.effect, "param": armed.param, "value": [lin.r(), lin.g(), lin.b(), 1.0]});+ if let Some(k) = armed.mask {+ params["mask"] = json!(k);+ }+ if let Err(e) = app.session.execute("effects.setParam", params) {+ app.ui.status = e.to_string();+ }+}++/// The average colour of the 5×5 pixels around `uv` (0..1 across and down) of a frame, so a noisy+/// green screen gives its true green. `None` for an empty frame.+fn sample_rgb(img: &crate::frames::Rgba, uv: (f32, f32)) -> Option<[u8; 3]> {+ if img.w == 0 || img.h == 0 || img.px.len() < img.w.saturating_mul(img.h).saturating_mul(4) {+ return None;+ }+ let cx = ((uv.0 * img.w as f32) as usize).min(img.w - 1);+ let cy = ((uv.1 * img.h as f32) as usize).min(img.h - 1);+ let (mut sum, mut n) = ([0u32; 3], 0u32);+ for y in cy.saturating_sub(2)..=(cy + 2).min(img.h - 1) {+ for x in cx.saturating_sub(2)..=(cx + 2).min(img.w - 1) {+ let i = (y * img.w + x) * 4;+ for (c, s) in sum.iter_mut().enumerate() {+ *s += u32::from(*img.px.get(i + c)?);+ }+ n += 1;+ }+ }+ let avg = |c: usize| u8::try_from(sum[c].checked_div(n)?).ok();+ Some([avg(0)?, avg(1)?, avg(2)?])+}+pub fn quantize_scale(s: f32) -> f32 {// Buckets keep the cache effective while resizing the panel.let buckets = [1.0 / 32.0, 1.0 / 16.0, 1.0 / 8.0, 0.1875, 0.25, 0.375, 0.5, 0.75, 1.0];@@ -679,3 +771,35 @@ fn source_nav(app: &mut FilmcraftApp, cmd: &str) {};let _ = app.session.execute("source.setPlayhead", json!({"time": t.0}));}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::frames::Rgba;++ fn flat(w: usize, h: usize, rgba: [u8; 4]) -> Rgba {+ Rgba { w, h, px: rgba.iter().copied().cycle().take(w * h * 4).collect() }+ }++ #[test]+ fn eyedropper_averages_the_pixels_around_the_point() {+ let mut img = flat(8, 8, [0, 200, 0, 255]);+ // one noisy pixel next to the centre is averaged away, not picked+ img.px[(4 * 8 + 5) * 4 + 1] = 0;+ assert_eq!(sample_rgb(&img, (0.5, 0.5)), Some([0, 192, 0]));+ }++ #[test]+ fn eyedropper_clamps_to_the_picture_edges() {+ let img = flat(4, 3, [10, 20, 30, 255]);+ for uv in [(0.0, 0.0), (1.0, 1.0), (0.999, 0.0), (0.0, 0.999)] {+ assert_eq!(sample_rgb(&img, uv), Some([10, 20, 30]));+ }+ }++ #[test]+ fn eyedropper_rejects_empty_and_truncated_frames() {+ assert_eq!(sample_rgb(&Rgba { w: 0, h: 0, px: vec![] }, (0.5, 0.5)), None);+ assert_eq!(sample_rgb(&Rgba { w: 4, h: 4, px: vec![0; 10] }, (0.5, 0.5)), None);+ }+}diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rsindex 140d60ccc..a8f12b8a5 100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@ -359,6 +359,15 @@ pub enum GuideDialog {},}+/// The colour parameter an armed eyedropper fills (`effects.setParam` arguments).+#[derive(Clone, Debug, PartialEq)]+pub struct Eyedropper {+ pub clip: u64,+ pub effect: usize,+ pub param: String,+ pub mask: Option<usize>,+}+#[derive(Clone, Debug, Serialize, Deserialize)]pub struct UiState {#[serde(default)]@@ -395,6 +404,10 @@ pub struct UiState {pub show_scopes: bool,/// Transient status line shown in the footer.pub status: String,+ /// The colour parameter an armed eyedropper will fill with the next pixel clicked in the Program+ /// monitor (Esc or a click elsewhere disarms it). Never saved.+ #[serde(skip)]+ pub eyedropper: Option<Eyedropper>,/// Essential Sound sub-tab: "Edit" or "Browse".#[serde(default)]pub essential_sound_tab: String,@@ -875,6 +888,7 @@ impl Default for UiState {dark: true,show_scopes: false,status: String::new(),+ eyedropper: None,essential_sound_tab: "Edit".into(),export: Default::default(),text_tab: captions_tab(),