FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
Monitors: Transparency Grid shows the picture's transparent areas
dotCooCoo34f882992ee6
diff --git a/crates/render/src/image.rs b/crates/render/src/image.rsindex 194ac2fff..449560fcf 100644--- a/crates/render/src/image.rs+++ b/crates/render/src/image.rs@@ -197,4 +197,20 @@ impl Image {});out}++ /// [`Self::over_black_rgba8`] with each pixel's alpha in the fourth byte: the color bytes are+ /// the same (the sRGB of the premultiplied linear color), so the picture still shows over+ /// black, and the alpha says where it is transparent.+ pub fn over_black_with_alpha_rgba8(&self) -> Vec<u8> {+ let mut out = vec![0u8; self.w * self.h * 4];+ out.par_chunks_mut(self.w * 4).zip(self.px.par_chunks(self.w * 4)).for_each(|(o, s)| {+ for (o, s) in o.as_chunks_mut::<4>().0.iter_mut().zip(s.as_chunks::<4>().0) {+ o[0] = filmcraft_color::linear_to_srgb_u8(s[0]);+ o[1] = filmcraft_color::linear_to_srgb_u8(s[1]);+ o[2] = filmcraft_color::linear_to_srgb_u8(s[2]);+ o[3] = (s[3].clamp(0.0, 1.0) * 255.0).round() as u8;+ }+ });+ out+ }}diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rsindex 31eed64ca..9b6b5e1e8 100644--- a/crates/render/src/tests.rs+++ b/crates/render/src/tests.rs@@ -79,6 +79,19 @@ fn half_resolution_matches_full_downsampled() {}}+/// The monitor conversion with alpha has the color of the opaque one and the image's alpha.+#[test]+fn over_black_with_alpha_keeps_the_color_and_the_alpha() {+ let img = Image { w: 3, h: 1, px: vec![1.0, 0.5, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.25, 0.0, 0.5] };+ let opaque = img.over_black_rgba8();+ let with_alpha = img.over_black_with_alpha_rgba8();+ for i in 0..3 {+ assert_eq!(with_alpha[i * 4..i * 4 + 3], opaque[i * 4..i * 4 + 3], "pixel {i}");+ }+ assert_eq!([with_alpha[3], with_alpha[7], with_alpha[11]], [255, 0, 128]);+ assert_eq!([opaque[3], opaque[7], opaque[11]], [255, 255, 255]);+}+#[test]fn motion_scale_and_position() {let (mut p, red, _o, seq, map) = setup();diff --git a/crates/ui-egui/src/frames.rs b/crates/ui-egui/src/frames.rsindex 496372e05..e3818ed61 100644--- a/crates/ui-egui/src/frames.rs+++ b/crates/ui-egui/src/frames.rs@@ -33,6 +33,10 @@ pub enum Target {MulticamGrid(ItemId, u8, u16),/// One angle of a multi-camera source (Edit Cameras thumbnails).MulticamAngle(ItemId, u32),+ /// Composite of a sequence rendered live, never from a render preview: previews are+ /// flattened over black, and the monitors' Transparency Grid and Alpha display mode need the+ /// frame's alpha.+ SequenceLive(ItemId),}/// Item jobs at this priority or a larger number are background work: thumbnails of the Project@@ -71,12 +75,42 @@ pub fn draft_playback(playing: bool, scale: f32, enabled: bool) -> bool {enabled && playing && scale <= 0.5}+/// A rendered frame as sRGB RGBA8: the color is the picture over black and the fourth byte is+/// its alpha ([`filmcraft_render::Image::over_black_with_alpha_rgba8`]).pub struct Rgba {pub w: usize,pub h: usize,pub px: Vec<u8>,}+impl Rgba {+ /// The frame as a texture image: opaque (the picture over black), or with its alpha, so what+ /// is painted under it shows through its transparent areas.+ pub fn color_image(&self, alpha: bool) -> egui::ColorImage {+ let pixels = if alpha {+ self.px.as_chunks::<4>().0.iter().map(|p| gamma_premultiplied(*p)).collect()+ } else {+ self.px.as_chunks::<4>().0.iter().map(|p| egui::Color32::from_rgb(p[0], p[1], p[2])).collect()+ };+ egui::ColorImage::new([self.w, self.h], pixels)+ }+}++/// A frame pixel (sRGB of the linear color premultiplied by alpha) as egui's color, which is the+/// sRGB of the straight color multiplied by alpha.+fn gamma_premultiplied([r, g, b, a]: [u8; 4]) -> egui::Color32 {+ use egui::ecolor::{gamma_u8_from_linear_f32, linear_f32_from_gamma_u8};+ match a {+ 255 => egui::Color32::from_rgb(r, g, b),+ 0 => egui::Color32::TRANSPARENT,+ _ => {+ let k = f32::from(a) / 255.0;+ let straight = |v: u8| gamma_u8_from_linear_f32((linear_f32_from_gamma_u8(v) / k).min(1.0));+ egui::Color32::from_rgba_unmultiplied(straight(r), straight(g), straight(b), a)+ }+ }+}+struct Job {key: FrameKey,queued: Instant,@@ -951,12 +985,14 @@ fn render_job(job: &Job, pool: &Arc<MediaPool>, services: &Arc<dyn Services>, pro.composite_onto(&mut img.px, w, h);}}- return (Rgba { w: img.w, h: img.h, px: img.over_black_rgba8() }, true);+ return (Rgba { w: img.w, h: img.h, px: img.over_black_with_alpha_rgba8() }, true);}let provider = provider(job, pool, services);let opts = filmcraft_render::RenderOptions { scale: job.scale, captions: true, ..Default::default() };let img = match job.key.target {- Target::Sequence(seq) | Target::SequencePlan(seq) => Some(filmcraft_render::render_sequence(&job.project, seq, job.time, opts, &provider)),+ Target::Sequence(seq) | Target::SequencePlan(seq) | Target::SequenceLive(seq) => {+ Some(filmcraft_render::render_sequence(&job.project, seq, job.time, opts, &provider))+ }Target::Item(item) => filmcraft_render::render_item(&job.project, item, job.time, job.scale, &provider),Target::MulticamGrid(item, side, page) => {let side = (side > 0).then_some(side as usize);@@ -967,7 +1003,7 @@ fn render_job(job: &Job, pool: &Arc<MediaPool>, services: &Arc<dyn Services>, pr}};let rgba = match img {- Some(img) => Rgba { w: img.w, h: img.h, px: img.over_black_rgba8() },+ Some(img) => Rgba { w: img.w, h: img.h, px: img.over_black_with_alpha_rgba8() },None => Rgba { w: 1, h: 1, px: vec![0, 0, 0, 255] },};(rgba, false)@@ -991,6 +1027,16 @@ mod tests {assert!(!background_work(50, Target::SequencePlan(ItemId(1))));}+ #[test]+ fn a_frame_goes_up_opaque_or_with_its_alpha() {+ use egui::Color32;+ // opaque red, transparent, and half-transparent white: linear 0.5 over black is sRGB 188+ let img = super::Rgba { w: 3, h: 1, px: vec![255, 0, 0, 255, 0, 0, 0, 0, 188, 188, 188, 128] };+ assert_eq!(img.color_image(false).pixels, [Color32::from_rgb(255, 0, 0), Color32::BLACK, Color32::from_rgb(188, 188, 188)]);+ // egui's colors are the sRGB of the straight color times alpha: white at half is 128+ assert_eq!(img.color_image(true).pixels, [Color32::from_rgb(255, 0, 0), Color32::TRANSPARENT, Color32::from_rgba_premultiplied(128, 128, 128, 128)]);+ }+#[test]fn draft_decoding_only_for_reduced_resolution_playback() {use super::draft_playback;diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex b13e79d6e..c6383384f 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -347,6 +347,7 @@Transcribe Sequence… Transcribir secuencia…Transcribe… Transcribir…Transcript Transcripción+ Transparency Grid Cuadrícula de transparenciaTransparent Video… Video transparente…Trim Edit Edición de recorteTrim… Recorte…diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex eacaa51a2..3c3e6c823 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -348,6 +348,7 @@Transcribe Sequence… シーケンスを文字起こし…Transcribe… 文字起こし…Transcript 文字起こし+ Transparency Grid 透明グリッドTransparent Video… 透明ビデオ…Trim Edit トリム編集Trim… トリム…diff --git a/crates/ui-egui/src/i18n/zh-cn.tsv b/crates/ui-egui/src/i18n/zh-cn.tsvindex 3e3e2f5bf..d8adb1921 100644--- a/crates/ui-egui/src/i18n/zh-cn.tsv+++ b/crates/ui-egui/src/i18n/zh-cn.tsv@@ -342,6 +342,7 @@Transcribe Sequence… 转录序列…Transcribe… 转录…Transcript 转录文稿+ Transparency Grid 透明网格Transparent Video… 透明视频…Trim Edit 修剪编辑Trim… 修剪…diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 14d66da4c..8a6299c4b 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -1224,16 +1224,28 @@ impl FilmcraftApp {// ---------------------------------------------------------------- textures- /// Upload a rendered frame into a named texture (only when the key changed).+ /// Upload a rendered frame into a named texture (only when the key changed), opaque: the+ /// picture over black.pub fn texture_for(&mut self, ctx: &egui::Context, name: &str, key: FrameKey, img: &frames::Rgba) -> egui::TextureId {+ self.upload_frame(ctx, name, key, img, false)+ }++ /// Like [`Self::texture_for`], keeping the frame's alpha, so what is painted under the+ /// texture (the monitors' Transparency Grid) shows through its transparent areas.+ pub fn texture_with_alpha(&mut self, ctx: &egui::Context, name: &str, key: FrameKey, img: &frames::Rgba) -> egui::TextureId {+ self.upload_frame(ctx, name, key, img, true)+ }++ 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) {if *k != key {- tex.set(egui::ColorImage::from_rgba_unmultiplied([img.w, img.h], &img.px), TextureOptions::LINEAR);+ tex.set(image(), TextureOptions::LINEAR);*k = key;}return tex.id();}- let tex = ctx.load_texture(name, egui::ColorImage::from_rgba_unmultiplied([img.w, img.h], &img.px), TextureOptions::LINEAR);+ let tex = ctx.load_texture(name, image(), TextureOptions::LINEAR);let id = tex.id();self.textures.insert(name.to_string(), (key, tex));iddiff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 2ee0a8e0a..26b972e1c 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -91,6 +91,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[uic!("view.addGuide", "Add Guide…", ["View"], None),uic!("view.clearGuides", "Clear Guides", ["View"], None),uic!("view.snapInProgramMonitor", "Snap in Program Monitor", ["View"], None),+ uic!("view.transparencyGrid", "Transparency Grid", ["View"], None),uic!("view.safeMargins", "Safe Margins", ["View", "Guide Templates"], None),uic!("view.guideTemplates.save", "Save Guides as Template…", ["View", "Guide Templates"], None),uic!("view.guideTemplates.manage", "Manage Guides…", ["View", "Guide Templates"], None),diff --git a/crates/ui-egui/src/panels/monitor.rs b/crates/ui-egui/src/panels/monitor.rsindex e1f4d4766..f2fef2b96 100644--- a/crates/ui-egui/src/panels/monitor.rs+++ b/crates/ui-egui/src/panels/monitor.rs@@ -174,7 +174,11 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)let saved_clip = ui.clip_rect();ui.set_clip_rect(saved_clip.intersect(if mv.zoom.is_some() && !compare { video_area } else { picture_area.expand(12.0) }));if show_picture {- ui.painter().rect_filled(pic, 0.0, t.monitor_bg);+ if mv.transparency_grid {+ monitor_view::transparency_grid(ui.painter(), pic, ui.clip_rect());+ } else {+ ui.painter().rect_filled(pic, 0.0, t.monitor_bg);+ }let playing = if which == Which::Program { app.playback.playing } else { app.source_playback.clock.playing };let res = mv.effective_res(playing);// frame pixels per screen pixel along the axis that needs the most of them@@ -187,10 +191,15 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)};let size_key = (scale * 1000.0) as u32;let channel = display.is_channel();- let use_gpu = which == Which::Program && app.gpu.is_some() && !channel && !crate::panels::menu_dialogs::software_renderer(app);+ // the GPU compositor's output is opaque, so the Transparency Grid takes the CPU frames+ let grid = mv.transparency_grid && !channel;+ let use_gpu = which == Which::Program && app.gpu.is_some() && !channel && !grid && !crate::panels::menu_dialogs::software_renderer(app);+ // render previews are opaque, so the grid and Display Mode ▸ Alpha take live renders+ let live = grid || display == DisplayMode::Alpha;let cpu_target = target;let target = match (use_gpu, target) {(true, Target::Sequence(s)) => Target::SequencePlan(s),+ (false, Target::Sequence(s)) if live => Target::SequenceLive(s),(_, t) => t,};// Draft decoding (opt-in): only while playing at 1/2 resolution or lower.@@ -208,7 +217,13 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)app.frames.request(key, rate.tick_of(frame), scale, &project, 0);}let asked = asked_before(app, prefix, key, playing);- let tex_name = if channel { format!("monitor-{prefix}-{display:?}") } else { format!("monitor-{prefix}") };+ let tex_name = if channel {+ format!("monitor-{prefix}-{display:?}")+ } else if grid {+ format!("monitor-{prefix}-grid")+ } else {+ format!("monitor-{prefix}")+ };let (shown, on_screen) = if use_gpu {let found = app.frames@@ -220,6 +235,8 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)Some((k, plan)) => (app.gpu_present(k, &plan).map(|(id, _)| id), Some(k)),None => (app.gpu.as_ref().and_then(|g| g.texture), app.gpu.as_ref().and_then(|g| g.last_key)),}+ } else if grid {+ cpu_texture_as(app, &ctx, &tex_name, key, &asked, display, true)} else {cpu_texture(app, &ctx, &tex_name, key, &asked, display)};@@ -244,11 +261,24 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)if let Some(ra) = ref_area {// the reference frame (CPU path)let rf = rate.frame_at(Tick(mv.compare_ref.unwrap_or(time.0)));- let rkey = FrameKey { target: cpu_target, frame: rf, size: size_key, revision: rev, draft: false };+ let rtarget = match cpu_target {+ Target::Sequence(s) if mv.transparency_grid => Target::SequenceLive(s),+ t => t,+ };+ let rkey = FrameKey { target: rtarget, frame: rf, size: size_key, revision: rev, draft: false };app.frames.request(rkey, rate.tick_of(rf), scale, &project, 1);let rpic = fit(ra, display_w, frame_size.1 as f32);- ui.painter().rect_filled(rpic, 0.0, t.monitor_bg);- if let (Some(tex), _) = cpu_texture(app, &ctx, &format!("monitor-{prefix}-ref"), rkey, &[], DisplayMode::Composite) {+ if mv.transparency_grid {+ monitor_view::transparency_grid(ui.painter(), rpic, ui.clip_rect());+ } else {+ ui.painter().rect_filled(rpic, 0.0, t.monitor_bg);+ }+ let (reference, _) = if mv.transparency_grid {+ cpu_texture_as(app, &ctx, &format!("monitor-{prefix}-ref-grid"), rkey, &[], DisplayMode::Composite, true)+ } else {+ cpu_texture(app, &ctx, &format!("monitor-{prefix}-ref"), rkey, &[], DisplayMode::Composite)+ };+ if let Some(tex) = reference {ui.painter().image(tex, rpic, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);}app.auto.add("program.compare.reference", rpic, "reference frame");@@ -486,6 +516,19 @@ fn cpu_texture(key: FrameKey,asked: &[FrameKey],mode: DisplayMode,+) -> (Option<egui::TextureId>, Option<FrameKey>) {+ cpu_texture_as(app, ctx, name, key, asked, mode, false)+}++/// [`cpu_texture`], keeping the frame's alpha when `alpha` is set (the Transparency Grid).+fn cpu_texture_as(+ app: &mut FilmcraftApp,+ ctx: &egui::Context,+ name: &str,+ key: FrameKey,+ asked: &[FrameKey],+ mode: DisplayMode,+ alpha: bool,) -> (Option<egui::TextureId>, Option<FrameKey>) {let found = app.frames@@ -497,6 +540,8 @@ fn cpu_texture(Some((k, img)) => {let tex = if mode.is_channel() {app.texture_for_mapped(ctx, name, k, &img, |i| monitor_view::channel_view(i, mode))+ } else if alpha {+ app.texture_with_alpha(ctx, name, k, &img)} else {app.texture_for(ctx, name, k, &img)};diff --git a/crates/ui-egui/src/panels/monitor_view.rs b/crates/ui-egui/src/panels/monitor_view.rsindex 5afc7e635..433ae7a1f 100644--- a/crates/ui-egui/src/panels/monitor_view.rs+++ b/crates/ui-egui/src/panels/monitor_view.rs@@ -3,8 +3,9 @@//! Multi-Camera, Audio Waveform, Comparison View, Video and Audio Waveform Split), Magnification//! (Fit, 10%…1600%, the wheel zooming about the pointer, middle-button or Hand-tool panning),//! rulers, guides (dragged out of the rulers, Add-//! Guide…, Clear Guides, Lock Guides, templates saved in the user preferences) and Snap in Program-//! Monitor (graphic drags snap to guides, the frame edges and centre).+//! Guide…, Clear Guides, Lock Guides, templates saved in the user preferences), Snap in Program+//! Monitor (graphic drags snap to guides, the frame edges and center) and Transparency Grid (a+//! checkerboard behind the picture shows its transparent areas).//!//! Everything is [`MonitorView`] state (serde: `ui.inspect`, `ui.set {"program": {…}}`) changed//! through the `view.*` UI commands, which [`route`] handles for `menus::invoke`. Commands act on@@ -145,6 +146,11 @@ pub fn route(app: &mut FilmcraftApp, id: &str, params: &Value) -> Option<Result<v.safe_margins = toggled(v.safe_margins, params);Ok(json!({"monitor": pfx, "safeMargins": v.safe_margins}))}+ "transparencyGrid" => {+ let v = view_mut(app, w);+ v.transparency_grid = toggled(v.transparency_grid, params);+ Ok(json!({"monitor": pfx, "transparencyGrid": v.transparency_grid}))+ }"showRulers" => {let v = view_mut(app, w);v.show_rulers = toggled(v.show_rulers, params);@@ -304,6 +310,7 @@ pub fn checked(app: &FilmcraftApp, id: &str) -> Option<bool> {match rest {"highQualityPlayback" => Some(v.high_quality),"safeMargins" => Some(v.safe_margins),+ "transparencyGrid" => Some(v.transparency_grid),"showRulers" => Some(v.show_rulers),"showGuides" => Some(v.show_guides),"lockGuides" => Some(v.lock_guides),@@ -321,17 +328,17 @@ pub fn enabled(app: &FilmcraftApp, id: &str) -> bool {}}-/// A channel of a frame as greyscale (Alpha, Red, Green, Blue display modes); colour channels are-/// shown premultiplied, so transparent areas are black.+/// A channel of a frame as grayscale (Alpha, Red, Green, Blue display modes). The frame's color+/// is already premultiplied (the picture over black), so transparent areas are black in the+/// color channels.pub fn channel_view(img: &Rgba, mode: DisplayMode) -> Rgba {let mut px = Vec::with_capacity(img.px.len());for p in img.px.as_chunks::<4>().0 {- let a = p[3] as u32;let v = match mode {DisplayMode::Alpha => p[3],- DisplayMode::Red => (p[0] as u32 * a / 255) as u8,- DisplayMode::Green => (p[1] as u32 * a / 255) as u8,- DisplayMode::Blue => (p[2] as u32 * a / 255) as u8,+ DisplayMode::Red => p[0],+ DisplayMode::Green => p[1],+ DisplayMode::Blue => p[2],_ => {px.extend_from_slice(p);continue;@@ -342,6 +349,58 @@ pub fn channel_view(img: &Rgba, mode: DisplayMode) -> Rgba {Rgba { w: img.w, h: img.h, px }}+/// The Transparency Grid's square size (points) and its two grays.+pub const GRID_CELL: f32 = 8.0;+pub const GRID_LIGHT: Color32 = Color32::from_gray(0xff);+pub const GRID_DARK: Color32 = Color32::from_gray(0xcc);++/// The dark squares of the Transparency Grid behind `pic` that overlap `area`, cut to `area`. The+/// squares start at the picture's top-left corner, which is light.+pub fn grid_cells(pic: Rect, area: Rect) -> Vec<Rect> {+ let area = pic.intersect(area);+ let mut out = Vec::new();+ if !area.is_positive() || !pic.min.is_finite() || !pic.max.is_finite() {+ return out;+ }+ let first = |lo: f32, origin: f32| ((lo - origin) / GRID_CELL).floor() as i64;+ let (c0, c1) = (first(area.min.x, pic.min.x), first(area.max.x, pic.min.x));+ let (r0, r1) = (first(area.min.y, pic.min.y), first(area.max.y, pic.min.y));+ // no screen holds more squares than this across or down+ const MAX_SQUARES: i64 = 4096;+ if c1.saturating_sub(c0) > MAX_SQUARES || r1.saturating_sub(r0) > MAX_SQUARES {+ return out;+ }+ for row in r0..=r1 {+ for col in c0..=c1 {+ // light where row + col is even (`^` gives the parity without an overflowing sum)+ if (row ^ col) & 1 == 0 {+ continue;+ }+ let min = pos2(pic.min.x + col as f32 * GRID_CELL, pic.min.y + row as f32 * GRID_CELL);+ let cell = Rect::from_min_size(min, vec2(GRID_CELL, GRID_CELL)).intersect(area);+ if cell.is_positive() {+ out.push(cell);+ }+ }+ }+ out+}++/// Paint the Transparency Grid behind the picture `pic`, where it overlaps `visible`: light+/// squares as one rectangle, the dark ones as one mesh.+pub fn transparency_grid(p: &egui::Painter, pic: Rect, visible: Rect) {+ let area = pic.intersect(visible);+ if !area.is_positive() {+ return;+ }+ p.rect_filled(area, 0.0, GRID_LIGHT);+ let mut mesh = egui::Mesh::default();+ for cell in grid_cells(pic, area) {+ mesh.add_colored_rect(cell, GRID_DARK);+ }+ p.add(egui::Shape::mesh(mesh));+}+/// The on-screen picture rect: fitted, or magnified about the area centre plus the (clamped) pan.pub fn picture_rect(area: Rect, fw: f32, fh: f32, v: &MonitorView, ppp: f32) -> Rect {match v.zoom {@@ -761,6 +820,7 @@ pub fn wrench_items(app: &mut FilmcraftApp, ui: &mut egui::Ui, w: Which) {if w == Which::Program {pick(ui, &mut out, "snapInProgramMonitor", tl!("Snap in Program Monitor"), v.snap);}+ pick(ui, &mut out, "transparencyGrid", tl!("Transparency Grid"), v.transparency_grid);ui.separator();let pfx = prefix(w);for (key, r, label, clicked) in out {@@ -933,12 +993,31 @@ mod tests {assert_eq!(snap_axis([10.0, 20.0, 30.0], &[8.0, 21.0], 6.0), Some((1.0, 21.0)));}+ #[test]+ fn grid_cells_alternate_from_a_light_corner_and_stay_in_view() {+ let pic = Rect::from_min_size(pos2(100.0, 50.0), vec2(4.0 * GRID_CELL, 2.0 * GRID_CELL));+ let mins: Vec<_> = grid_cells(pic, Rect::EVERYTHING).iter().map(|r| ((r.min.x - 100.0) / GRID_CELL, (r.min.y - 50.0) / GRID_CELL)).collect();+ assert_eq!(mins, [(1.0, 0.0), (3.0, 0.0), (0.0, 1.0), (2.0, 1.0)]);+ // a magnified picture: only the squares in view, cut to it, keeping the picture's pattern+ let big = Rect::from_min_size(pos2(-1000.0, -1000.0), vec2(4000.0, 4000.0));+ let view = Rect::from_min_size(pos2(3.0, 0.0), vec2(20.0, 8.0));+ let cells = grid_cells(big, view);+ assert!(cells.iter().all(|c| view.contains_rect(*c)), "{cells:?}");+ assert_eq!(cells, [Rect::from_min_max(pos2(8.0, 0.0), pos2(16.0, 8.0))]);+ assert!(grid_cells(pic, Rect::from_min_size(pos2(0.0, 0.0), vec2(10.0, 10.0))).is_empty(), "nothing outside the picture");+ // a picture magnified far past the zoom menu (`ui.set` takes any zoom) does not overflow+ let huge = Rect::from_min_max(pos2(-1e20, -1e20), pos2(1e20, 1e20));+ assert!(grid_cells(huge, view).len() <= 6);+ assert!(grid_cells(Rect::from_min_max(pos2(f32::NEG_INFINITY, 0.0), pos2(f32::INFINITY, 1.0)), view).is_empty());+ }+#[test]fn channel_view_greyscales() {- let img = Rgba { w: 2, h: 1, px: vec![200, 100, 50, 255, 255, 255, 255, 0] };- assert_eq!(channel_view(&img, DisplayMode::Red).px, vec![200, 200, 200, 255, 0, 0, 0, 255]);+ // an opaque pixel, a transparent one and a half-transparent one (color premultiplied)+ let img = Rgba { w: 3, h: 1, px: vec![200, 100, 50, 255, 0, 0, 0, 0, 90, 40, 20, 128] };+ assert_eq!(channel_view(&img, DisplayMode::Red).px, vec![200, 200, 200, 255, 0, 0, 0, 255, 90, 90, 90, 255]);assert_eq!(channel_view(&img, DisplayMode::Green).px[..4], [100, 100, 100, 255]);- assert_eq!(channel_view(&img, DisplayMode::Alpha).px, vec![255, 255, 255, 255, 0, 0, 0, 255]);+ assert_eq!(channel_view(&img, DisplayMode::Alpha).px, vec![255, 255, 255, 255, 0, 0, 0, 255, 128, 128, 128, 255]);}#[test]diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rsindex e0710236c..d49fef92d 100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@ -316,6 +316,8 @@ pub struct MonitorView {/// length (start, end), set with the zoom bar under the ruler; None = all of it.pub time_zoom: Option<[f64; 2]>,pub safe_margins: bool,+ /// Transparency Grid: a checkerboard behind the picture shows its transparent areas.+ pub transparency_grid: bool,pub show_transport: bool,/// Transport buttons hidden through the monitor's Button Editor. Stored per monitor.pub transport_hidden: Vec<String>,@@ -342,6 +344,7 @@ impl Default for MonitorView {pan: [0.0, 0.0],time_zoom: None,safe_margins: false,+ transparency_grid: false,show_transport: true,// The optional Loop button is available from the editor without altering default layouts.transport_hidden: vec!["playback.loop".into()],diff --git a/crates/ui-egui/tests/it/view_ui.rs b/crates/ui-egui/tests/it/view_ui.rsindex 1bfeda836..1f3583ea0 100644--- a/crates/ui-egui/tests/it/view_ui.rs+++ b/crates/ui-egui/tests/it/view_ui.rs@@ -192,6 +192,132 @@ fn view_menu_resolutions_and_display_modes() {assert_eq!((s["display"].as_str(), s["show_rulers"].as_bool()), (Some("Composite"), Some(true)));}+/// The filled rectangles and the mesh vertex colors painted this frame inside `area`.+fn fills_in(d: &Driver, area: egui::Rect) -> (Vec<(egui::Rect, egui::Color32)>, Vec<egui::Color32>) {+ fn walk(s: &egui::Shape, area: egui::Rect, rects: &mut Vec<(egui::Rect, egui::Color32)>, verts: &mut Vec<egui::Color32>) {+ match s {+ egui::Shape::Rect(r) if area.expand(0.5).contains_rect(r.rect) => rects.push((r.rect, r.fill)),+ egui::Shape::Mesh(m) => verts.extend(m.vertices.iter().filter(|v| area.expand(0.5).contains(v.pos)).map(|v| v.color)),+ egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, area, rects, verts)),+ _ => {}+ }+ }+ let (mut rects, mut verts) = (Vec::new(), Vec::new());+ d.harness.output().shapes.iter().for_each(|c| walk(&c.shape, area, &mut rects, &mut verts));+ (rects, verts)+}++/// View ▸ Transparency Grid and the wrench menu item paint a gray and white checkerboard behind+/// the picture instead of the monitor background; each monitor keeps its own setting.+#[test]+fn transparency_grid_paints_a_checkerboard_behind_the_picture() {+ use filmcraft_ui_egui::frames::Target;+ use filmcraft_ui_egui::panels::monitor_view::{GRID_DARK, GRID_LIGHT};+ let mut d = Driver::demo();+ let checked = |d: &mut Driver| {+ let menu = d.ok("ui.menu.list", json!({}));+ menu.as_array().unwrap().iter().find(|m| m["id"] == "view.transparencyGrid").expect("View ▸ Transparency Grid")["checked"].clone()+ };+ assert_eq!(d.program()["transparency_grid"], false, "off by default");+ assert_eq!(checked(&mut d), false);+ let r = d.rect("program.picture");+ let pic = egui::Rect::from_min_size(egui::pos2(r[0] as f32, r[1] as f32), egui::vec2(r[2] as f32, r[3] as f32));+ let covers = |rects: &[(egui::Rect, egui::Color32)]| {+ rects.iter().any(|(r, c)| *c == GRID_LIGHT && (r.min - pic.min).length() < 1.0 && (r.max - pic.max).length() < 1.0)+ };+ let (rects, verts) = fills_in(&d, pic);+ assert!(!covers(&rects) && !verts.contains(&GRID_DARK), "no grid while it is off");++ d.click("program.settings");+ assert!(d.try_rect("program.settings.transparencyGrid").is_some(), "the wrench menu lists Transparency Grid");+ d.click("program.settings.transparencyGrid");+ d.frames(2);+ assert_eq!(d.program()["transparency_grid"], true);+ assert_eq!(checked(&mut d), true);+ let (rects, verts) = fills_in(&d, pic);+ assert!(covers(&rects), "the light squares fill the picture");+ let dark = verts.iter().filter(|c| **c == GRID_DARK).count();+ assert!(dark >= 4 * 100, "the dark squares are drawn: {dark} vertices");+ // the Program picture is rendered live (render previews are flattened over black)+ let live = |d: &Driver| matches!(d.harness.state().program_picture().map(|k| k.target), Some(Target::SequenceLive(_)));+ for _ in 0..600 {+ if live(&d) {+ break;+ }+ d.frames(1);+ std::thread::sleep(std::time::Duration::from_millis(5));+ }+ assert!(live(&d), "the Program monitor shows a live render: {:?}", d.harness.state().program_picture());+ assert_eq!(d.ok("ui.inspect", json!({}))["ui"]["source"]["transparency_grid"], false, "the Source monitor keeps its own setting");++ // Comparison View: the reference frame has the grid behind it too+ d.menu("view.display.comparison");+ d.frames(3);+ let r = d.rect("program.compare.reference");+ let reference = egui::Rect::from_min_size(egui::pos2(r[0] as f32, r[1] as f32), egui::vec2(r[2] as f32, r[3] as f32));+ let (rects, _) = fills_in(&d, reference);+ assert!(+ rects.iter().any(|(r, c)| *c == GRID_LIGHT && (r.min - reference.min).length() < 1.0 && (r.max - reference.max).length() < 1.0),+ "the light squares fill the reference frame"+ );+ d.menu("view.display.composite");+ d.frames(2);++ d.ok("ui.menu.invoke", json!({"id": "view.transparencyGrid", "params": {"monitor": "source", "enabled": true}}));+ assert_eq!(d.ok("ui.inspect", json!({}))["ui"]["source"]["transparency_grid"], true);+ assert_eq!(d.program()["transparency_grid"], true);++ // a Transparent Video in the Source monitor: the frame keeps its alpha and goes up as the+ // grid's texture, so the grid shows through it+ let item = d.exec("file.newTransparentVideo", json!({}))["item"].as_u64().expect("new item");+ d.exec("source.open", json!({"item": item}));+ let mut key = None;+ for _ in 0..600 {+ d.frames(1);+ key = d.harness.state().texture_key("monitor-source-grid");+ if key.is_some() {+ break;+ }+ std::thread::sleep(std::time::Duration::from_millis(5));+ }+ let key = key.expect("the Source monitor shows its frame through the grid");+ let frame = d.harness.state().frames.get(&key).expect("the shown frame is cached");+ assert!(!frame.px.is_empty() && frame.px.as_chunks::<4>().0.iter().all(|p| p[3] == 0), "the frame keeps its alpha");++ d.ok("ui.menu.invoke", json!({"id": "view.transparencyGrid", "params": {"monitor": "program"}}));+ d.frames(2);+ assert_eq!(d.program()["transparency_grid"], false);+ let (rects, verts) = fills_in(&d, pic);+ assert!(!covers(&rects) && !verts.contains(&GRID_DARK), "the grid goes when it is turned off");+}++/// Display Mode ▸ Alpha shows a live render of the sequence (render previews are opaque); Red+/// keeps the usual frames.+#[test]+fn alpha_display_mode_shows_a_live_render() {+ use filmcraft_ui_egui::frames::Target;+ let shown_live = |d: &mut Driver, live: bool| {+ let is = |d: &Driver| match d.harness.state().program_picture().map(|k| k.target) {+ Some(Target::SequenceLive(_)) => live,+ Some(Target::Sequence(_)) => !live,+ _ => false,+ };+ for _ in 0..600 {+ if is(d) {+ break;+ }+ d.frames(1);+ std::thread::sleep(std::time::Duration::from_millis(5));+ }+ assert!(is(d), "live render {live}: {:?}", d.harness.state().program_picture());+ };+ let mut d = Driver::demo();+ d.menu("view.display.alpha");+ shown_live(&mut d, true);+ d.menu("view.display.red");+ shown_live(&mut d, false);+}+fn num(v: &Value) -> f64 {v.as_f64().unwrap_or_else(|| panic!("not a number: {v}"))}diff --git a/docs/monitors.md b/docs/monitors.mdindex ae9408a26..a9db82af1 100644--- a/docs/monitors.md+++ b/docs/monitors.md@@ -19,6 +19,7 @@ focused monitor (Program by default). Code: `crates/ui-egui/src/panels/monitor_v| `view.showRulers`, `view.showGuides`, `view.lockGuides`, `view.clearGuides` | View | toggles take `{"enabled": bool}` || `view.addGuide` | View ▸ Add Guide… | dialog, or `{"orientation": "vertical\|horizontal", "position": px}` || `view.snapInProgramMonitor` | View ▸ Snap in Program Monitor | graphic moves snap to the frame edges / centre and the guides (6 pt) |+| `view.transparencyGrid` | View ▸ Transparency Grid | a gray and white checkerboard (8 pt squares) behind the picture shows its transparent areas; off by default, each monitor keeps its own; takes `{"enabled": bool}`. The Program monitor renders on the CPU while the grid is on || `view.safeMargins` | Guide Templates ▸ Safe Margins | action- and title-safe boxes || `view.guideTemplates.save`, `.manage`, `.apply`, `.delete` | Guide Templates ▸ Save Guides as Template… / Manage Guides… | templates are stored in the user preferences (`guides.templates`) |diff --git a/docs/ui-parity.md b/docs/ui-parity.mdindex 838a98ad0..19d0cb746 100644--- a/docs/ui-parity.md+++ b/docs/ui-parity.md@@ -19,7 +19,7 @@ open interaction reports (about 40 of the 188 open issues).| Menus | 366 in-scope menu items | ~338 present (label diff, 92%) | 92% | spelling, Render and Replace, 5 workspaces | 10–20 h || Keyboard | Premiere default keyboard + editor | Premiere-compatible preset (143 keyboard-only commands; 39 cloud / absent-panel keys skipped with reasons), FilmCraft / FCP / Avid presets, editor | 90% | Ctrl chords (#256 fixed), modifier hints on Windows (#270 fixed) | 5–10 h || Timeline editing tools | Selection, Track Select, Ripple / Rolling / Rate Stretch, Razor, Slip / Slide, Pen, Hand, Zoom, Type | all present, trim modes, Trim Monitor, dynamic trimming | 80% | deselect in empty space (#683), gap delete (#648, #668), clip stretch (#653), new tracks by dropping (#483), Escape cancels drag (#580 fixed), delete in timeline (#680, #404) | 30–50 h |-| Program monitor on-screen controls | Motion / Transform handles, mask handles, safe margins, guides | guides, rulers, safe margins, snapping, mask drawing; **no transform handles** (#639); Button Editor (+) does nothing (#431) | 55% | #639, #431 | 15–25 h |+| Program monitor on-screen controls | Motion / Transform handles, mask handles, safe margins, guides, transparency grid | guides, rulers, safe margins, transparency grid, snapping, mask drawing; **no transform handles** (#639); Button Editor (+) does nothing (#431) | 55% | #639, #431 | 15–25 h || Effect Controls | property rows, keyframe area with zoom, divider, graphs, eyedroppers | rows, keyframes, value / velocity graphs, eyedropper (#518); missing keyframe zoom (#641, #645), draggable divider (#643), row lines (#640), Position curves (#448) | 60% | #412, #640–#645, #448 | 15–25 h || Panels and docking | 17 workspaces, dock / undock / float, drop zones | 11 workspaces, docking; rearranging windows reported missing (#493); multi-monitor floating windows (#466) | 60% | #493, #466 | 20–35 h || Project panel | List / Icon / Freeform, hover scrub, marquee | all three views, hover scrub, view presets; no marquee (#578), Freeform bins and pan (#579), bins can't be left on Windows (#587), duplicate imports allowed (#356) | 75% | #578, #579, #587, #456 | 10–20 h |