diff --git a/crates/ui-egui/src/canvas/media.rs b/crates/ui-egui/src/canvas/media.rs index 077fdc36a..9bcab1467 100644 --- a/crates/ui-egui/src/canvas/media.rs +++ b/crates/ui-egui/src/canvas/media.rs @@ -1,8 +1,92 @@ -use super::{Rect, Sense, SlideApp, Target, Ui, Xf, json, pos2, screen_rect, vec2}; +use craft::behavior::{IconId, Proposal, kurbo::Point}; +use craft::theme::ControlSize; +// PLAN: plan error: crates/ui-egui/Cargo.toml lacks the craft timeline feature required by cv.F22 (shell-w11). +use craft::timeline::ui::MediaControls; +use craft::ui::bars::BarBackgroundPress; +use craft::ui::buttons::IconButton; +use craft::ui::canvas::CanvasSpace; +use craft::ui::contract::{Props as _, Show as _, clicked}; +use deckcraft_engine::Target; +use deckcraft_geom::Xfrm; +use deckcraft_media::PlayState; +use egui::{Rect, Ui, UiBuilder, pos2, vec2}; +use serde_json::json; -/// Play/pause on an animated GIF under the pointer or selected on its own. -// P3(canvas-w14): cv.A3 -pub(super) fn gif_buttons_base(app: &mut SlideApp, ui: &mut Ui, xf: Xf, gifs: &[crate::media::Gif]) { +use crate::SlideApp; + +fn screen_rect(space: &CanvasSpace, x: &Xfrm) -> Rect { + Rect::from_min_max(space.view.to_screen(Point::new(x.x, x.y)), space.view.to_screen(Point::new(x.x + x.w, x.y + x.h))) +} + +/// Appends live video frames to the slide picture's paint slot. +pub(crate) fn show_frames(app: &mut SlideApp, ui: &mut Ui, space: &CanvasSpace) { + let Some(d) = app.session.active() else { return }; + if d.selection.target != Target::Slides || !app.media.any_active() { + return; + } + let mut shapes = Vec::new(); + for (id, x, clip) in crate::media::slide_media(&d.doc, d.selection.slide) { + if clip.video { + crate::media::paint_frame(&mut shapes, &app.media, id, screen_rect(space, &x), clip.crop); + } + } + space.paint_picture(ui.ctx(), shapes); +} + +/// Hosts the selected or hovered clip's controls within the canvas clip. +pub(crate) fn show_controls(app: &mut SlideApp, ui: &mut Ui, space: &CanvasSpace) { + let Some(d) = app.session.active() else { return }; + if d.selection.target != Target::Slides || d.selection.text.is_some() || app.session.tool.dragging() { + return; + } + let pointer = ui.input(|i| i.pointer.hover_pos()); + let media = crate::media::slide_media(&d.doc, d.selection.slide); + let pick = media.iter().find(|(id, _, _)| d.selection.shapes.len() == 1 && d.selection.shapes[0] == *id).or_else(|| { + media.iter().find(|(id, x, _)| { + let r = screen_rect(space, x); + app.media.status(*id).is_some() || pointer.is_some_and(|p| r.expand2(vec2(0.0, 40.0)).contains(p)) + }) + }); + let Some((id, x, clip)) = pick.cloned() else { return }; + let Some(shape) = d.doc.slides[d.selection.slide].shape(id) else { return }; + let name = shape.name.clone(); + let (uid, doc) = (d.uid, d.doc.clone()); + let r = screen_rect(space, &x); + let width = r.width().max(230.0); + let top = r.max.y + 6.0; + let room = Rect::from_min_size(pos2(r.center().x - width / 2.0, top), vec2(width, (space.view.rect.max.y - top).max(0.0))); + let status = app.media.status(id); + let position = status.as_ref().map_or(clip.trim_start_ms as f64 / 1000.0, |s| s.position); + let duration = status.as_ref().map(|s| s.duration).filter(|d| *d > 0.0).unwrap_or(clip.duration_ms as f64 / 1000.0); + let playing = status.as_ref().is_some_and(|s| matches!(s.state, PlayState::Playing | PlayState::Loading)); + let error = status.as_ref().and_then(|s| s.error.as_ref()).map(|err| format!("No sound: {err}")); + let (toggle, nudge, seek): (bool, Option, Option) = ui + .scope_builder(UiBuilder::new().id_salt(("media_controls", id.0)).max_rect(room), |ui| { + ui.set_clip_rect(ui.clip_rect().intersect(space.view.rect)); + let controls = MediaControls::new(name, position, duration) + .playing(playing) + .trim((clip.trim_start_ms as f64 / 1000.0, duration - clip.trim_end_ms as f64 / 1000.0)) + .background_press(BarBackgroundPress::Absorb); + let controls = if let Some(error) = error { controls.error(error) } else { controls }; + let output = controls.show(ui); + (output.toggle, output.nudge, output.seek.value().copied()) + }) + .inner; + // Hover is a held fact used only for visibility. Actions come from this pass's control output, + // so a second pass with no input cannot replay a toggle, nudge or seek. + if toggle { + app.media.toggle(uid, &doc, id, &clip, crate::media::Owner::Editor); + } + if let Some(dt) = nudge { + app.media.seek(uid, &doc, id, &clip, (position + dt).max(0.0), crate::media::Owner::Editor); + } + if let Some(t) = seek { + app.media.seek(uid, &doc, id, &clip, t, crate::media::Owner::Editor); + } +} + +/// Hosts play/pause buttons on the selected GIF or GIFs under the pointer. +pub(crate) fn gif_buttons(app: &mut SlideApp, ui: &mut Ui, space: &CanvasSpace, gifs: &[crate::media::Gif]) { let Some(d) = app.session.active() else { return }; if d.selection.text.is_some() || app.session.tool.dragging() { return; @@ -11,88 +95,25 @@ pub(super) fn gif_buttons_base(app: &mut SlideApp, ui: &mut Ui, xf: Xf, gifs: &[ let pointer = ui.input(|i| i.pointer.hover_pos()); let mut toggle = None; for g in gifs { - let r = screen_rect(xf, &g.rect); + let r = screen_rect(space, &g.rect); if only != Some(g.id) && !pointer.is_some_and(|p| r.contains(p)) { continue; } - let b = crate::media::gif_button_rect(r); - // Sensing drags too keeps the press from reaching the canvas (selecting or moving the GIF). - let resp = ui.interact(b, ui.scope_id().with(("gif_button", g.id.0)), Sense::click_and_drag()); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, if g.paused { "Play animated GIF" } else { "Pause animated GIF" })); - crate::media::paint_gif_button(ui.painter(), b, g.paused, resp.hovered()); - if resp.clicked() { + let rect = crate::media::gif_button_rect(r); + let mut button = IconButton::new(IconId::new(if g.paused { "play" } else { "pause" })) + .id_salt(("gif_button", g.id.0)) + .variant(IconButton::OVER_PICTURE) + .label(if g.paused { "Play animated GIF" } else { "Pause animated GIF" }); + if rect.width() < button.measure_in(ui, Proposal::Ideal).x { + button = button.size(ControlSize::Sm); + } + let size = button.measure_in(ui, Proposal::Ideal); + if clicked(&button.show_at(ui, Rect::from_center_size(rect.center(), size))) { toggle = Some(g.id); } } + // Only the pass receiving the activation emits a command; hover never becomes an event. if let Some(id) = toggle { let _ = app.run("media.gifPlay", json!({"id": id})); } } - -/// Video playing in the editor: its current frame over the poster. -pub(super) fn media_frames(app: &SlideApp, painter: &egui::Painter, xf: Xf) { - let Some(d) = app.session.active() else { return }; - if d.selection.target != Target::Slides || !app.media.any_active() { - return; - } - for (id, x, clip) in crate::media::slide_media(&d.doc, d.selection.slide) { - if clip.video { - // P3(canvas-w14): cv.A9 - crate::media::paint_frame_base(painter, &app.media, id, screen_rect(xf, &x), clip.crop); - } - } -} - -/// The play/pause and timeline bar under a selected audio or video (PowerPoint shows it on -/// selection or hover). -pub(super) fn media_bar(app: &mut SlideApp, ui: &mut Ui, xf: Xf) { - let Some(d) = app.session.active() else { return }; - let uid = d.uid; - if d.selection.target != Target::Slides || d.selection.text.is_some() || app.session.tool.dragging() { - return; - } - let pointer = ui.input(|i| i.pointer.hover_pos()); - let media = crate::media::slide_media(&d.doc, d.selection.slide); - let pick = media.iter().find(|(id, _, _)| d.selection.shapes.len() == 1 && d.selection.shapes[0] == *id).or_else(|| { - media.iter().find(|(id, x, _)| { - let r = screen_rect(xf, x); - app.media.status(*id).is_some() || pointer.is_some_and(|p| r.expand2(vec2(0.0, 40.0)).contains(p)) - }) - }); - let Some((id, x, clip)) = pick.cloned() else { return }; - let doc = d.doc.clone(); - let r = screen_rect(xf, &x); - let w = r.width().max(230.0); - let bar = Rect::from_min_size(pos2(r.center().x - w / 2.0, r.max.y + 6.0), vec2(w, 26.0)); - let status = app.media.status(id); - match crate::media::control_bar(ui, bar, status.as_ref(), &clip) { - Some(crate::media::BarAction::Toggle) => app.media.toggle(uid, &doc, id, &clip, crate::media::Owner::Editor), - Some(crate::media::BarAction::Seek(t)) => app.media.seek(uid, &doc, id, &clip, t, crate::media::Owner::Editor), - Some(crate::media::BarAction::Nudge(dt)) => { - let pos = status.map(|s| s.position).unwrap_or(0.0); - app.media.seek(uid, &doc, id, &clip, (pos + dt).max(0.0), crate::media::Owner::Editor); - } - None => {} - } -} - -/// Paints or hosts this canvas part over the slide picture. -#[allow(dead_code)] // P3(canvas-w14): cv.A3 -pub(crate) fn show_frames(app: &mut crate::SlideApp, ui: &mut egui::Ui, space: &craft::ui::canvas::CanvasSpace) { - let _ = (app, ui, space); - todo!("cv.A3") -} - -/// Paints or hosts this canvas part over the slide picture. -#[allow(dead_code)] // P3(canvas-w14): cv.A3 -pub(crate) fn show_controls(app: &mut crate::SlideApp, ui: &mut egui::Ui, space: &craft::ui::canvas::CanvasSpace) { - let _ = (app, ui, space); - todo!("cv.A3") -} - -/// Shows the GIF pause buttons over the slide picture. -#[allow(dead_code)] // P3(canvas-w14): cv.A3 -pub(crate) fn gif_buttons(app: &mut SlideApp, ui: &mut Ui, space: &craft::ui::canvas::CanvasSpace, gifs: &[crate::media::Gif]) { - let _ = (app, ui, space, gifs); - todo!("cv.A3") -} diff --git a/crates/ui-egui/src/media.rs b/crates/ui-egui/src/media.rs index f5f64e93a..cea69c6ed 100644 --- a/crates/ui-egui/src/media.rs +++ b/crates/ui-egui/src/media.rs @@ -4,13 +4,12 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; +use craft::ui::primitives::{CachedTexture, Revision, Serials, TextureStore, TextureStoreOptions}; use deckcraft_engine::{MediaStatus, Session}; use deckcraft_geom::Xfrm; use deckcraft_media::{AudioOut, ClipParams, Frame, PlayState, Player, VideoFeed, VoiceSpec, VoiceStatus}; use deckcraft_model::{MediaClip, Presentation, Shape, ShapeId, ShapeKind}; -use egui::{Align2, Color32, CornerRadius, Pos2, Rect, Sense, Stroke, TextureHandle, Ui, pos2, vec2}; - -use crate::icons::{self, Icon}; +use egui::{Color32, CornerRadius, Rect, pos2, vec2}; /// Video shapes that get a decoder at once; more play their sound without a picture. const MAX_VIDEO_FEEDS: usize = 16; @@ -26,7 +25,7 @@ pub enum Owner { struct Video { feed: Option, frame: Option>, - tex: Option, + tex: Option, } /// A voice started for one shape in one presentation. @@ -45,8 +44,7 @@ struct Probed { } pub struct MediaHost { - #[allow(dead_code)] // P3(canvas-w14): cv.A9 - serials: craft::ui::primitives::Serials, + serials: Serials, player: Player, /// Presentation the voices and GIF clocks belong to. `None` before the first document is /// bound, and after the last one closes. @@ -102,7 +100,6 @@ fn key(id: ShapeId) -> u64 { impl MediaHost { pub fn new(out: Option>) -> MediaHost { MediaHost { - // P3(canvas-w14): cv.A9 serials: Default::default(), player: Player::new(out), doc: None, @@ -325,9 +322,8 @@ impl MediaHost { } /// The current video frame of shape `id`, once one has decoded. - // P3(canvas-w14): cv.A9 - fn texture_base(&self, id: ShapeId) -> Option<&TextureHandle> { - self.videos.get(&id).and_then(|v| v.tex.as_ref()) + pub fn texture(&self, id: ShapeId) -> Option { + self.videos.get(&id).and_then(|v| v.tex) } /// Run the media clocks, apply loop/rewind and report state to the engine. Called from @@ -371,6 +367,7 @@ impl MediaHost { /// Upload due video frames for the pass that is about to draw them. Called only from the real /// UI phase: a hidden window accumulates no texture uploads and catches up when it appears. pub fn sync_video_textures(&mut self, ctx: &egui::Context) { + let store = TextureStore::::in_context(ctx, "deckcraft.media-frames", TextureStoreOptions::frames()); for (id, v) in &mut self.videos { let Some(st) = self.player.status(key(*id)) else { continue }; let Some(feed) = v.feed.as_mut() else { continue }; @@ -379,13 +376,11 @@ impl MediaHost { && v.frame.as_ref().is_none_or(|old| !Arc::ptr_eq(old, &f)) { let img = egui::ColorImage::from_rgba_unmultiplied([f.width as usize, f.height as usize], &f.rgba); - match v.tex.as_mut() { - Some(t) => crate::textures::replace(ctx, t, img), - None => v.tex = Some(crate::textures::upload(ctx, format!("media-{id}"), img)), - } + v.tex = Some(store.put(ctx, key(*id), Revision::new(self.serials.mint()), img)); v.frame = Some(f); } } + store.retain(ctx, |id| self.videos.contains_key(&ShapeId(*id as u32))); } /// Carry out a `media.*` request from the engine for presentation `doc_uid`. @@ -442,12 +437,6 @@ pub fn slide_media(doc: &Presentation, index: usize) -> Vec<(ShapeId, deckcraft_ .collect() } -/// "1:05.25" style time. -pub fn clock(secs: f64) -> String { - let s = secs.max(0.0); - format!("{:02}:{:05.2}", (s / 60.0) as u32, s % 60.0) -} - /// The part of a video frame a picture crop (left, top, right, bottom fractions) leaves visible. fn crop_uv(crop: [f64; 4]) -> Rect { let [l, t, r, b] = crop.map(|v| if v.is_finite() { v.clamp(0.0, 0.99) as f32 } else { 0.0 }); @@ -456,21 +445,21 @@ fn crop_uv(crop: [f64; 4]) -> Rect { /// Draw the playing video frame of `id` into `rect`: letterboxed to the frame's aspect, or, when /// the video is cropped, the cropped part stretched over the whole box as PowerPoint shows it. -// P3(canvas-w14): cv.A9 -pub(crate) fn paint_frame_base(painter: &egui::Painter, host: &MediaHost, id: ShapeId, rect: Rect, crop: [f64; 4]) -> bool { - // P3(canvas-w14): cv.A9 - let Some(tex) = host.texture_base(id) else { return false }; +pub fn paint_frame(shapes: &mut Vec, host: &MediaHost, id: ShapeId, rect: Rect, crop: [f64; 4]) -> bool { + let Some(tex) = host.texture(id) else { return false }; + shapes.push(egui::Shape::rect_filled(rect, CornerRadius::ZERO, Color32::BLACK)); if crop.iter().any(|v| *v > 0.0) { - painter.rect_filled(rect, CornerRadius::ZERO, Color32::BLACK); - painter.image(tex.id(), rect, crop_uv(crop), Color32::WHITE); + let uv = tex.uv(); + let crop = crop_uv(crop); + let uv = Rect::from_min_max(uv.min + crop.min.to_vec2() * uv.size(), uv.min + crop.max.to_vec2() * uv.size()); + shapes.push(egui::Shape::image(tex.id, rect, uv, Color32::WHITE)); return true; } - let [w, h] = tex.size(); + let (w, h) = (tex.size.width, tex.size.height); let (w, h) = (w.max(1) as f32, h.max(1) as f32); let k = (rect.width() / w).min(rect.height() / h); let r = Rect::from_center_size(rect.center(), vec2(w * k, h * k)); - painter.rect_filled(rect, CornerRadius::ZERO, Color32::BLACK); - painter.image(tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + shapes.push(egui::Shape::image(tex.id, r, tex.uv(), Color32::WHITE)); true } @@ -482,7 +471,7 @@ pub fn gif_key(gifs: &[Gif]) -> u64 { /// Come back when the next frame of a playing GIF is due. pub fn gif_repaint(ctx: &egui::Context, gifs: &[Gif]) { if let Some(next) = gifs.iter().filter(|g| !g.paused).map(|g| g.next).reduce(f64::min) { - ctx.request_repaint_after(std::time::Duration::from_millis((next * 1000.0).clamp(5.0, 1000.0) as u64)); + craft::ui::runtime::frame::request_repaint_after(ctx, next.clamp(0.005, 1.0)); } } @@ -492,125 +481,6 @@ pub fn gif_button_rect(r: Rect) -> Rect { Rect::from_min_size(pos2(r.min.x + 6.0, r.max.y - 6.0 - s), vec2(s, s)) } -pub fn paint_gif_button(painter: &egui::Painter, b: Rect, paused: bool, hot: bool) { - painter.circle_filled(b.center(), b.width() / 2.0, Color32::from_black_alpha(if hot { 210 } else { 150 })); - let r = b.shrink(b.width() * 0.3); - let white = Color32::from_gray(235); - if paused { - icons::paint(painter, r, Icon::Play, white, false); - } else { - let w = r.width() * 0.3; - painter.rect_filled(Rect::from_min_size(r.min, vec2(w, r.height())), CornerRadius::ZERO, white); - painter.rect_filled(Rect::from_min_size(pos2(r.max.x - w, r.min.y), vec2(w, r.height())), CornerRadius::ZERO, white); - } -} - -/// What the control bar asks for. -pub enum BarAction { - Toggle, - Seek(f64), - Nudge(f64), -} - -/// PowerPoint-style media controls: play/pause, ΒΌ-second nudges, a seekable timeline and the time. -pub fn control_bar(ui: &mut Ui, rect: Rect, status: Option<&VoiceStatus>, clip: &MediaClip) -> Option { - let painter = ui.painter_at(rect.expand(2.0)); - painter.rect_filled(rect, CornerRadius::same(4), Color32::from_rgba_unmultiplied(28, 28, 32, 230)); - // Sensing drags too keeps a press on the bar from reaching the editor canvas: there it would - // start a selection marquee, which hides the bar before the click lands. - ui.interact(rect, ui.scope_id().with("media_bar_back"), Sense::click_and_drag()); - let playing = status.is_some_and(|s| matches!(s.state, PlayState::Playing | PlayState::Loading)); - let duration = status.map(|s| s.duration).filter(|d| *d > 0.0).unwrap_or(clip.duration_ms as f64 / 1000.0); - let pos = status.map(|s| s.position).unwrap_or(clip.trim_start_ms as f64 / 1000.0); - let mut action = None; - let h = rect.height(); - let mut x = rect.min.x + 4.0; - let button = |ui: &mut Ui, x: &mut f32, id: &str, paint: &dyn Fn(&egui::Painter, Rect)| -> bool { - let r = Rect::from_min_size(pos2(*x, rect.min.y + 2.0), vec2(h - 4.0, h - 4.0)); - *x += h - 2.0; - let resp = ui.interact(r, ui.scope_id().with(("media_bar", id)), Sense::click_and_drag()); - let name = match id { - "play" => "Play or pause media", - "back" => "Back 0.25 seconds", - "fwd" => "Forward 0.25 seconds", - _ => "Media control", - }; - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, name)); - if resp.hovered() { - painter.rect_filled(r, CornerRadius::same(3), Color32::from_white_alpha(28)); - } - paint(&painter, r.shrink(4.0)); - resp.clicked() - }; - let white = Color32::from_gray(235); - if button(ui, &mut x, "play", &|p, r| { - if playing { - let w = r.width() * 0.3; - p.rect_filled(Rect::from_min_size(r.min, vec2(w, r.height())), CornerRadius::ZERO, white); - p.rect_filled(Rect::from_min_size(pos2(r.max.x - w, r.min.y), vec2(w, r.height())), CornerRadius::ZERO, white); - } else { - icons::paint(p, r, Icon::Play, white, false); - } - }) { - action = Some(BarAction::Toggle); - } - let tri = |p: &egui::Painter, r: Rect, left: bool| { - let (a, b) = if left { (r.max.x, r.min.x) } else { (r.min.x, r.max.x) }; - let pts: Vec = vec![pos2(a, r.min.y + 2.0), pos2(b, r.center().y), pos2(a, r.max.y - 2.0)]; - p.add(egui::Shape::convex_polygon(pts, white, Stroke::NONE)); - }; - if button(ui, &mut x, "back", &|p, r| tri(p, r.shrink(2.0), true)) { - action = Some(BarAction::Nudge(-0.25)); - } - if button(ui, &mut x, "fwd", &|p, r| tri(p, r.shrink(2.0), false)) { - action = Some(BarAction::Nudge(0.25)); - } - // Time label on the right, timeline between. - let label = clock(pos); - let label_w = 64.0; - painter.text(pos2(rect.max.x - 6.0, rect.center().y), Align2::RIGHT_CENTER, label, egui::FontId::monospace(11.0), white); - let track = Rect::from_min_max(pos2(x + 6.0, rect.center().y - 3.0), pos2(rect.max.x - label_w - 6.0, rect.center().y + 3.0)); - if track.width() > 10.0 { - painter.rect_filled(track, CornerRadius::same(3), Color32::from_gray(90)); - let frac = if duration > 0.0 { (pos / duration).clamp(0.0, 1.0) as f32 } else { 0.0 }; - let done = Rect::from_min_max(track.min, pos2(track.min.x + track.width() * frac, track.max.y)); - painter.rect_filled(done, CornerRadius::same(3), Color32::from_rgb(0x4C, 0x9A, 0xFF)); - // Trim marks. - if duration > 0.0 { - for t in [clip.trim_start_ms as f64 / 1000.0, duration - clip.trim_end_ms as f64 / 1000.0] { - if t > 0.0 && t < duration { - let tx = track.min.x + track.width() * (t / duration) as f32; - painter.line_segment( - [pos2(tx, track.min.y - 3.0), pos2(tx, track.max.y + 3.0)], - Stroke::new(1.5, Color32::from_rgb(0xF2, 0xB1, 0x34)), - ); - } - } - } - painter.circle_filled(pos2(done.max.x, track.center().y), 5.0, white); - let hit = track.expand2(vec2(4.0, 8.0)); - let resp = ui.interact(hit, ui.scope_id().with("media_bar_track"), Sense::click_and_drag()); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Unknown, true, "Media position")); - if (resp.clicked() || resp.dragged()) - && duration > 0.0 - && let Some(p) = resp.interact_pointer_pos() - { - let f = ((p.x - track.min.x) / track.width()).clamp(0.0, 1.0) as f64; - action = Some(BarAction::Seek(f * duration)); - } - } - if let Some(err) = status.and_then(|s| s.error.as_ref()) { - painter.text( - pos2(rect.min.x, rect.max.y + 3.0), - Align2::LEFT_TOP, - format!("No sound: {err}"), - egui::FontId::proportional(10.0), - Color32::from_rgb(0xC0, 0x40, 0x40), - ); - } - action -} - #[cfg(test)] mod tests { use std::collections::HashSet; @@ -622,12 +492,6 @@ mod tests { use super::*; - #[test] - fn a_video_crop_shows_only_the_cropped_part_of_the_frame() { - assert_eq!(crop_uv([0.0; 4]), Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0))); - assert_eq!(crop_uv([0.25, 0.5, 0.25, 0.0]), Rect::from_min_max(pos2(0.25, 0.5), pos2(0.75, 1.0))); - } - /// 16-bit mono WAV of a constant level, `secs` long at 8 kHz. fn wav_level(secs: f64, amp: f32) -> Vec { let rate = 8_000u32; @@ -812,8 +676,7 @@ mod tests { assert!(host.videos.get(&id).is_some_and(|v| v.feed.is_none()), "VP8 opens no video feed"); host.tick_clock(0.1, &mut s); host.sync_video_textures(&egui::Context::default()); - // P3(canvas-w14): cv.A9 - assert!(host.texture_base(id).is_none(), "no VP8 frame exists to show"); + assert!(host.texture(id).is_none(), "no VP8 frame exists to show"); } #[test] @@ -893,18 +756,3 @@ mod tests { assert_eq!(host.videos.values().filter(|v| v.feed.is_some()).count(), MAX_VIDEO_FEEDS); } } - -impl MediaHost { - /// Returns the cached current video frame of the shape, once one has decoded. - pub fn texture(&self, id: ShapeId) -> Option { - let _ = (id,); - todo!("cv.A9") - } -} - -/// Appends the playing video frame as shapes and reports whether a frame was available. -#[allow(dead_code)] // P3(canvas-w14): cv.A9 -pub fn paint_frame(shapes: &mut Vec, host: &MediaHost, id: ShapeId, rect: Rect, crop: [f64; 4]) -> bool { - let _ = (shapes, host, id, rect, crop); - todo!("cv.A9") -} diff --git a/crates/ui-egui/src/media_bar_tests.rs b/crates/ui-egui/src/media_bar_tests.rs index f2de25209..f5301fd4e 100644 --- a/crates/ui-egui/src/media_bar_tests.rs +++ b/crates/ui-egui/src/media_bar_tests.rs @@ -1,14 +1,19 @@ -//! The play/pause and timeline bar under a selected audio or video in the editor, clicked with the -//! mouse: a press on it used to reach the canvas, start a selection marquee there and hide the bar -//! before the click landed, so Play only worked in the slide show. +//! Media-bar presses belong to the editor controls through release, and canvas clipping keeps +//! those controls from painting or taking input in the speaker notes. +use std::sync::Arc; + +// PLAN: plan error: crates/ui-egui/Cargo.toml lacks the craft timeline feature required by TransportWords (shell-w11). +use craft::timeline::ui::TransportWords; +use craft::ui::runtime::env::Env; use deckcraft_engine::Session; use deckcraft_model::ShapeId; use egui::{Modifiers, PointerButton, Pos2, pos2, vec2}; use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; use serde_json::json; -use crate::{Services, SlideApp}; +use crate::{Services, SlideApp, test_harness}; /// 16-bit mono WAV of silence, `secs` long at 8 kHz. fn wav(secs: f64) -> Vec { @@ -41,44 +46,59 @@ fn play_on_the_editor_media_bar_plays_the_selected_clip() { s.execute("slide.new", &json!({"layout": "blank"})).unwrap(); let r = s.execute("insert.audio", &json!({"name": "tone.wav", "data": deckcraft_engine::cmd::base64_encode(&wav(2.0))})).unwrap(); let id = ShapeId(r["id"].as_u64().unwrap() as u32); - // P3(canvas-w14): sh.A2 - let app = SlideApp::new_base(s, Services::default()); - let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state( - |ui, app: &mut SlideApp| { - app.logic(ui.ctx()); - app.ui(ui); - }, - app, + let mut h = test_harness::harness_with( + s, + Services::default(), + Harness::builder().with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0), + |_| {}, ); h.run_steps(3); let d = h.state().session.active().unwrap(); assert_eq!(d.selection.shapes, vec![id], "the inserted clip is selected"); - let x = d.doc.slides[d.selection.slide].shape(id).unwrap().xfrm.unwrap(); - let (slide, k) = (h.state().slide_rect.unwrap(), h.state().canvas_scale); - // The bar sits 6 points under the clip, centred, at least 230 wide; Play is its first button. - let (left, right, bottom) = (slide.min.x + x.x as f32 * k, slide.min.x + (x.x + x.w) as f32 * k, slide.min.y + (x.y + x.h) as f32 * k); - let w = (right - left).max(230.0); - let bar = pos2((left + right) / 2.0 - w / 2.0, bottom + 6.0); + let name = d.doc.slides[d.selection.slide].shape(id).unwrap().name.clone(); + let words = h.ctx.root_ui(|ui| Env::of(ui).words::()); + let play = h.get_by_role_and_label(egui::accesskit::Role::Button, words.play_pause_media.as_str()).rect().center(); assert!(h.state().media.status(id).is_none()); - click(&mut h, bar + vec2(15.0, 13.0)); + // Replaying layout in the release frame must not replay Play as Pause. + h.ctx.on_end_pass( + "media bar second pass", + Arc::new(|ui| { + if ui.ctx().current_pass_index() == 0 && ui.input(|i| i.pointer.any_released()) { + ui.ctx().request_discard("media bar activation with a second layout pass"); + } + }), + ); + h.hover_at(play); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: play, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + assert_eq!(h.state().session.active().unwrap().selection.shapes, vec![id], "the Play press belongs to the controls"); + assert!(!h.state().session.tool.dragging(), "the Play press must not begin a canvas gesture"); + h.event(egui::Event::PointerButton { pos: play, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); assert!(h.state().media.status(id).is_some(), "Play starts the clip"); + assert!(h.state().media.is_playing(id), "a second pass did not toggle playback back off"); + assert_eq!(h.state().media.owner(id), Some(crate::media::Owner::Editor)); let d = h.state().session.active().unwrap(); assert_eq!(d.selection.shapes, vec![id], "the click did not reach the slide behind the bar"); assert!(!h.state().session.tool.dragging()); - // Between the buttons and the timeline the bar still keeps the press from the slide. - click(&mut h, bar + vec2(w - 30.0, 13.0)); + let bar = h.get_by_role_and_label(egui::accesskit::Role::Toolbar, name.as_str()).rect(); + let forward = h.get_by_role_and_label(egui::accesskit::Role::Button, words.forward_quarter.as_str()).rect(); + let track = h.get_by_role_and_label(egui::accesskit::Role::Slider, words.seek.as_str()).rect(); + let gap = pos2((forward.max.x + track.min.x) / 2.0, bar.center().y); + assert!(forward.max.x < gap.x && gap.x < track.min.x && bar.contains(gap), "the click is on empty bar space"); + click(&mut h, gap); assert_eq!(h.state().session.active().unwrap().selection.shapes, vec![id]); + assert!(!h.state().session.tool.dragging(), "the bar background owns its press through release"); } -/// #1922: the bar hangs 6 pt under the clip, so a clip at the bottom edge of the slide put it -/// inside the speaker-notes pane, painted over the notes text. The canvas is clipped to its own -/// rect: nothing it paints reaches the notes pane, and a click there goes to the notes field. +/// #1922: a bar below a clip at the slide's bottom edge must respect the canvas clip so that +/// speaker notes retain their paint and input area. #[test] fn the_media_bar_never_paints_or_clicks_into_the_notes_pane() { use egui::accesskit::Role; - use egui_kittest::kittest::Queryable; let mut s = Session::with_new(); s.execute("slide.new", &json!({"layout": "blank"})).unwrap(); let r = s.execute("insert.audio", &json!({"name": "tone.wav", "data": deckcraft_engine::cmd::base64_encode(&wav(2.0))})).unwrap(); @@ -86,45 +106,34 @@ fn the_media_bar_never_paints_or_clicks_into_the_notes_pane() { // Dragged across the bottom edge of the slide, onto the pasteboard. let h_slide = s.doc().unwrap().doc.slide_size.height; s.execute("shape.setBounds", &json!({"ids": [id.0], "x": 300.0, "y": h_slide - 10.0, "w": 120.0, "h": 60.0})).unwrap(); - // P3(canvas-w14): sh.A2 - let mut app = SlideApp::new_base(s, Services::default()); - app.ui.notes = true; - app.ui.notes_height = 140.0; - let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state( - |ui, app: &mut SlideApp| { - app.logic(ui.ctx()); - app.ui(ui); - }, - app, + let mut h = test_harness::harness_with( + s, + Services::default(), + Harness::builder().with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0), + |_| {}, ); + h.state_mut().ui.notes = true; + h.state_mut().ui.notes_height = 140.0; h.run_steps(3); let notes = h.query_all_by_role(Role::MultilineTextInput).next().map(|n| n.rect()).expect("the notes field"); - let canvas = h.state().canvas_rect.unwrap(); + let canvas = h.state().canvas_rect().unwrap(); assert!(canvas.max.y <= notes.min.y + 1.0, "the notes pane sits under the canvas: {canvas:?} / {notes:?}"); let d = h.state().session.active().unwrap(); let x = d.doc.slides[d.selection.slide].shape(id).unwrap().xfrm.unwrap(); - let (slide, k) = (h.state().slide_rect.unwrap(), h.state().canvas_scale); + let name = d.doc.slides[d.selection.slide].shape(id).unwrap().name.clone(); + let (slide, k) = (h.state().slide_rect().unwrap(), h.state().canvas_scale()); let bottom = slide.min.y + (x.y + x.h) as f32 * k; let bar_y = bottom + 6.0 + 13.0; assert!(bar_y > notes.min.y, "the bar's row ({bar_y}) would fall inside the notes pane (top {})", notes.min.y); - // The bar's own background (the only dark rounded rect the canvas paints there) has no - // visible area below the canvas edge: whatever the canvas paints is clipped to the canvas. - let bar_fill = egui::Color32::from_rgba_unmultiplied(28, 28, 32, 230); - let bars: Vec = h - .output() - .shapes - .iter() - .filter_map(|cs| match &cs.shape { - egui::Shape::Rect(r) if r.fill == bar_fill => Some(r.rect.intersect(cs.clip_rect)), - _ => None, - }) - .collect(); - assert!(!bars.is_empty(), "the bar is still laid out for the selected clip"); - assert!(bars.iter().all(|v| !v.is_positive() || v.max.y <= canvas.max.y + 0.5), "the bar is painted into the notes pane: {bars:?}"); + let bar = h.get_by_role_and_label(Role::Toolbar, name.as_str()).rect(); + // PLAN: plan error: the sheet's intersection filter also selects notes and window paint; FullOutput.shapes lacks component ownership for selecting the media bar's shapes (canvas-w5). + let shapes: Vec<_> = h.output().shapes.iter().filter(|cs| cs.shape.visual_bounding_rect().intersects(bar)).collect(); + assert!(!shapes.is_empty(), "the bar is still laid out for the selected clip"); + assert!(shapes.iter().all(|cs| cs.clip_rect.max.y <= canvas.max.y + 0.5), "the bar is painted into the notes pane: {shapes:?}"); // A click where the bar would be lands in the notes field, not on the bar. click(&mut h, pos2(slide.min.x + (x.x + x.w / 2.0) as f32 * k, bar_y)); assert!(h.state().media.status(id).is_none(), "Play was not hit through the notes pane"); - assert!(h.ctx.memory(|m| m.focused()).is_some(), "the notes field took the click"); + assert!(h.query_all_by_role(Role::MultilineTextInput).any(|n| n.is_focused()), "the notes field took the click"); }