diff --git a/crates/ui-egui/src/show.rs b/crates/ui-egui/src/show.rs index d90b01d39..13e5cd51e 100644 --- a/crates/ui-egui/src/show.rs +++ b/crates/ui-egui/src/show.rs @@ -2,6 +2,8 @@ //! keyboard/mouse navigation, pen, black/white screens, See All Slides, zoom, presenter view //! and rehearsed timings. +use craft::behavior::canvas::zoom as view_zoom; +use craft::behavior::kurbo::{Point, Size}; use deckcraft_anim::{Click, HitShape, Layer, LinkJump, ShowAction, ShowState, Source, StepStamp, Timeline, TriggerPlay}; use deckcraft_model::text::Hyperlink; use deckcraft_model::{Presentation, ShapeId}; @@ -12,7 +14,6 @@ use serde_json::json; use crate::SlideApp; use crate::theme; -mod keys; mod media; mod presenter; mod render; @@ -21,36 +22,33 @@ mod zoom; pub(crate) use zoom::GRID_CAP; #[cfg(test)] -use media::{on_screen, pointer_on_media_bar, shown_slide_rect, slide_media_bars}; -use presenter::{NOTES_DEFAULT, PresenterTimer}; -// P3(show-w4): ss.A11 +// PLAN: assumed fn transition_layers(kind: &str, option: &str, reverse: bool, p: f64, aspect: f64) -> Vec (show-w6) +use frames::transition_layers; +#[cfg(test)] +use media::slide_media_bars; pub(crate) use presenter::format_elapsed; +use presenter::{NOTES_DEFAULT, PresenterTimer}; #[cfg(test)] -use presenter::{NOTES_MAX, NOTES_MIN, NOTES_STEP, presenter_notes, presenter_window, wall_clock}; +use presenter::{NOTES_MAX, NOTES_MIN, NOTES_STEP, presenter_pass}; #[cfg(test)] -use render::{below_playing_video, next_rect, render_frame, start_prefetch}; -use render::{render_backdrop, render_threads}; -#[cfg(test)] -use ui::transition_layers; -// P3(show-w4): ss.A9 +use render::{below_playing_video, render_frame}; pub(crate) use ui::ui; -use zoom::Zoom; #[cfg(test)] -use zoom::{GOTO_DIGITS, norm_on_slide, see_all_cells, see_all_hit, toggle_blank, unit_uv, wheel_zoom_lines, zoom_uv}; +use zoom::{GOTO_DIGITS, toggle_blank}; +/// Playback state shared by the audience and presenter windows. pub struct Show { - #[allow(dead_code)] // P3(show-w4): ss.A4 view: craft::behavior::CanvasView, - #[allow(dead_code)] // P3(show-w4): ss.A4 zoomed: bool, - #[allow(dead_code)] // P3(show-w4): ss.A4 frames: frames::ShowFrames, - #[allow(dead_code)] // P3(show-w4): ss.A4 next_preview: Option<(std::sync::Arc, usize)>, - #[allow(dead_code)] // P3(show-w4): ss.A4 + /// Requested presenter mode, resolved by the show's first visible pass. pub(crate) presenter_start: PresenterStart, - #[allow(dead_code)] // P3(show-w4): ss.A4 + /// Native presenter identity for capture requests while its body is open. + pub(crate) presenter_viewport: Option, remote_images: crate::presenter::DeltaCache, + /// A control-requested logical time; wall-clock wakeups cannot advance it. + hold: Option, /// Monotonic identity of this show instance. Starting a show again (even at the same slide /// and step) is a new instance, so a queued click cannot cross an ABA transition. @@ -70,27 +68,11 @@ pub struct Show { slide_start: f64, step_end: f64, trans: Option, - tex: Option<(Key, TextureHandle)>, - /// The shapes stacked above the playing videos, drawn over the video frames (#1005). - overlay: Option<(Key, Vec, TextureHandle)>, - /// The Presenter View's next-slide preview: the presentation and slide it shows. - next_tex: Option<(std::sync::Arc, usize, TextureHandle)>, - /// The one next-slide preview being rendered on another thread (#964). - next_job: Option<(std::sync::Arc, usize, std::sync::mpsc::Receiver)>, - /// Preview renders started on another thread. - #[cfg(test)] - preview_spawns: usize, remote_preview: Option, - remote_next: Option<(usize, crate::presenter::Preview)>, /// All slides thumbnails sent to the web presenter window while its grid is open (#1866). remote_grid: Vec, remote_sent: f64, remote_opened: bool, - /// The next slide's first frame, rendered in the background while this one is shown so - /// advancing only uploads it (#240). - prefetch: Option, - /// The current slide's backdrop, under its animation frames. - backdrop: Option, blank: Option, /// See All Slides covers the show until a slide is chosen. pub grid: bool, @@ -98,12 +80,10 @@ pub struct Show { pub presenter_grid: bool, /// The next click on the slide zooms in there. pub zoom_arm: bool, - zoom: Option, - thumbs: Vec<(usize, TextureHandle)>, pen: bool, /// A dot that follows the pointer and leaves no ink (`Cmd/Ctrl+L`). laser: bool, - strokes: Vec>, + strokes: Vec>, /// Digits typed for Go to Slide, shown until Enter, Esc, or a short pause. goto: String, goto_at: f64, @@ -115,8 +95,6 @@ pub struct Show { notes_px: f32, timings: Vec<(usize, f64)>, last_move: f64, - /// The last trackpad flick or mouse-wheel notch, so one gesture turns one page. - last_swipe: f64, pub ended: bool, /// The slide whose media was last started (auto-play runs once per visit). media_slide: Option, @@ -149,12 +127,6 @@ struct Key { gif: u64, } -/// A slide frame being rendered on another thread: what it will be (`key`) and where it arrives. -struct Prefetch { - key: Key, - rx: std::sync::mpsc::Receiver, -} - /// What a slide's backdrop was rendered for. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub(crate) struct BackKey { @@ -163,28 +135,9 @@ pub(crate) struct BackKey { doc: usize, } -/// A slide's backdrop (background, master and layout graphics), kept while the slide is shown so -/// animation frames render only the slide's own shapes over it. The backdrop can cost far more -/// than the shapes: a full-slide picture with a glow in the layout made animations crawl at 2–3 -/// frames a second. `rx` brings it from another thread when it is rendered ahead of time. -struct Backdrop { - /// The presentation it was rendered from, held so its address (in `key`) can't be reused by - /// a later edit while the backdrop is kept. - doc: std::sync::Arc, - key: BackKey, - img: Option>, - rx: Option>, -} - struct Transition { - old: Option, - /// The slide left behind (Morph matches its shapes) and the Morph frame texture. + /// The slide left behind, whose shapes Morph matches. from: Option, - morph: Option, - /// Backgrounds and contents of the old and new slides, rendered once when the transition - /// moves contents over backgrounds (Pan, Ferris Wheel, Reveal…): old back, old content, new - /// back, new content. - parts: Option<[Option; 4]>, start: f64, kind: String, option: String, @@ -224,30 +177,19 @@ pub(crate) struct ShowInputState { pub zoom_arm: bool, } -/// True unless the root viewport explicitly reports itself minimized or fully occluded. -/// Integrations that do not report visibility stay visible rather than freezing the show. -pub(crate) fn viewport_visible(ctx: &egui::Context) -> bool { - ctx.input(|i| i.viewport().visible() != Some(false)) -} - impl Show { /// Initialise show state at the requested slide with reading/presenter modes; an out-of-range /// slide starts an ended show. pub fn new(doc: &Presentation, from: usize, reading: bool, presenter: bool) -> Self { Show { - // P3(show-w4): ss.A4 - view: craft::behavior::CanvasView::new(egui::Rect::NOTHING, craft::behavior::kurbo::Point::ZERO, 1.0), - // P3(show-w4): ss.A4 - zoomed: Default::default(), - // P3(show-w4): ss.A4 + view: craft::behavior::CanvasView::new(egui::Rect::NOTHING, Point::ORIGIN, 1.0), + zoomed: false, frames: Default::default(), - // P3(show-w4): ss.A4 - next_preview: Default::default(), - // P3(show-w4): ss.A4 + next_preview: None, presenter_start: if presenter { PresenterStart::Forced } else { PresenterStart::Off }, - // P3(show-w4): ss.A4 + presenter_viewport: None, remote_images: Default::default(), - + hold: None, instance: 0, state: ShowState::start_at(doc, from), reading, @@ -261,25 +203,14 @@ impl Show { slide_start: 0.0, step_end: 0.0, trans: None, - tex: None, - overlay: None, - next_tex: None, - next_job: None, - #[cfg(test)] - preview_spawns: 0, remote_preview: None, - remote_next: None, remote_grid: vec![], remote_sent: f64::NEG_INFINITY, remote_opened: false, - prefetch: None, - backdrop: None, blank: None, grid: false, presenter_grid: false, zoom_arm: false, - zoom: None, - thumbs: vec![], pen: false, laser: false, strokes: vec![], @@ -291,7 +222,6 @@ impl Show { notes_px: NOTES_DEFAULT, timings: vec![], last_move: 0.0, - last_swipe: f64::NEG_INFINITY, ended: false, media_slide: None, last_viewed: None, @@ -313,7 +243,7 @@ impl Show { .map(|t| (t.kind.clone(), t.option.clone(), t.duration_ms as f64 / 1000.0)) .unwrap_or(("none".into(), String::new(), 0.0)); self.trans = if kind != "none" && dur > 0.0 && !doc.show.without_animation { - Some(Transition { old: None, from, morph: None, parts: None, start: now, kind, option, dur, reverse: false }) + Some(Transition { from, start: now, kind, option, dur, reverse: false }) } else { None }; @@ -336,7 +266,6 @@ impl Show { grid: self.grid, pen: self.pen, laser: self.laser, - // P3(show-w4): ss.A4 blank: self .blank .map(|c| match c { @@ -344,7 +273,7 @@ impl Show { Blank::White => Color32::WHITE, }) .map(|c| [c.r(), c.g(), c.b(), c.a()]), - zoom: self.zoom.map(|z| [bits(z.nx), bits(z.ny), bits(z.scale)]), + zoom: self.zoomed.then(|| [bits(self.view.center.x as f32), bits(self.view.center.y as f32), bits(self.view.zoom as f32)]), zoom_arm: self.zoom_arm, } } @@ -371,13 +300,17 @@ impl Show { /// Whether hidden logic still has time-driven work, so it must keep requesting wake-ups. pub(crate) fn hidden_time_driven(&self, doc: &Presentation) -> bool { - self.started && !self.ended && (self.state.playing || self.trans.is_some() || self.autoplay || self.state.advance_after(doc).is_some()) + self.hold.is_none() + && self.started + && !self.ended + && (self.state.playing || self.state.trigger_playing() || self.trans.is_some() || self.autoplay || self.state.advance_after(doc).is_some()) } /// Advance the show's own clocks and automatic steps on a hidden logic pass. Drawing is a /// separate concern, so a minimized show keeps playing instead of inventing a pause policy. /// Returns false when the show should close (preview ended). pub(crate) fn advance_hidden(&mut self, doc: &Presentation, now: f64) -> bool { + let now = self.hold.unwrap_or(now); self.tick_triggers(doc, now); self.expire_goto(now); if self.trans.as_ref().is_some_and(|trans| now - trans.start >= trans.dur.max(0.01)) { @@ -400,6 +333,7 @@ impl Show { /// Queue the step/auto-advance actions for `now`. Shared by the visible UI pass and the /// hidden logic tick so both read the same clock. Returns false when a preview should close. fn queue_clock_actions(&mut self, doc: &Presentation, now: f64, actions: &mut Vec) -> bool { + let now = self.hold.unwrap_or(now); let (step, playing) = (self.state.step, self.state.playing); let t_step = if playing { now - self.step_start } else { 0.0 }; if playing { @@ -414,11 +348,11 @@ impl Show { let idle = now - self.step_end.max(self.slide_start); let cur_step = self.state.step; let n_steps = self.timeline(doc).steps(); - let step_due = self.autoplay && cur_step < n_steps && idle > 0.3; - let holding = self.grid || self.presenter_grid || self.zoom.is_some() || self.zoom_arm; + let step_due = self.autoplay && cur_step < n_steps && idle > AUTOPLAY_DELAY; + let holding = self.clock_navigation_held(); if !holding && (step_due || (!self.rehearse && self.state.auto_advance_due(doc, idle) && !self.ended)) { actions.push(self.state.next(doc)); - } else if self.preview_only && cur_step >= n_steps && idle > 0.8 { + } else if self.preview_only && cur_step >= n_steps && idle > PREVIEW_DELAY { return false; } } @@ -445,7 +379,7 @@ impl Show { /// True while the pointer moved in the last 2.5 s; the media controls and GIF button hide after that. fn pointer_awake(&self, now: f64) -> bool { - now - self.last_move < 2.5 + now - self.last_move < POINTER_IDLE } /// Whether a still pointer is hidden: after 2.5 s in a full-screen show, unless Keep mouse @@ -475,35 +409,14 @@ impl Show { self.laser = false; } - /// The backdrop for `key`: kept from earlier, waited for if it is being rendered ahead of - /// time, or rendered now. - fn backdrop(&mut self, doc: &std::sync::Arc, key: BackKey) -> std::sync::Arc { - if let Some(b) = self.backdrop.as_mut().filter(|b| b.key == key && std::sync::Arc::ptr_eq(&b.doc, doc)) { - if b.img.is_none() { - b.img = b.rx.take().and_then(|rx| rx.recv().ok()).map(std::sync::Arc::new); - } - if let Some(img) = &b.img { - return img.clone(); - } - } - let img = std::sync::Arc::new(render_backdrop(doc, key, render_threads())); - self.backdrop = Some(Backdrop { doc: doc.clone(), key, img: Some(img.clone()), rx: None }); - img + /// Obtain the backdrop through the frame store's retained source. + fn backdrop(&mut self, ctx: &egui::Context, doc: &std::sync::Arc, key: BackKey) -> std::sync::Arc { + self.frames.backdrop(ctx, doc, key) } - /// Start rendering the backdrop for `key` on another thread, unless it is already there or - /// on its way. Nothing on the web (no threads): the first animation frame renders it. - fn prefetch_backdrop(&mut self, doc: &std::sync::Arc, key: BackKey) { - if cfg!(target_arch = "wasm32") || self.backdrop.as_ref().is_some_and(|b| b.key == key && std::sync::Arc::ptr_eq(&b.doc, doc)) { - return; - } - let (tx, rx) = std::sync::mpsc::channel(); - let worker_doc = doc.clone(); - let threads = render_threads().saturating_sub(1).max(1); - let spawned = std::thread::Builder::new().name("show-backdrop".into()).spawn(move || { - let _ = tx.send(render_backdrop(&worker_doc, key, threads)); - }); - self.backdrop = spawned.ok().map(|_| Backdrop { doc: doc.clone(), key, img: None, rx: Some(rx) }); + /// Queue a backdrop through the frame resource owner. + fn prefetch_backdrop(&mut self, ctx: &egui::Context, doc: &std::sync::Arc, key: BackKey) { + self.frames.prefetch_backdrop(ctx, doc, key); } fn timeline(&mut self, doc: &Presentation) -> &Timeline { @@ -521,6 +434,7 @@ impl Show { } fn apply(&mut self, a: ShowAction, doc: &Presentation, now: f64) -> bool { + let now = self.hold.unwrap_or(now); match a { ShowAction::PlayStep(k) => { self.step_start = now; @@ -537,15 +451,13 @@ impl Show { } ShowAction::Slide(i) => { self.ended = false; - self.zoom = None; + // The next canvas pass has the current room and restores fit before painting. + self.zoomed = false; self.zoom_arm = false; if self.rehearse { self.timings.push((self.timeline.as_ref().map(|t| t.0).unwrap_or(i), now - self.slide_start)); } - // Take the old slide's texture rather than cloning its handle: the new slide is - // otherwise rendered into the same texture, and the transition blends the new - // slide with itself (#33). - let (from, old) = self.tex.take().map(|(k, t)| (k.slide, t)).unzip(); + let from = self.frames.shown_slide(); if from != Some(i) { self.last_viewed = from; } @@ -562,7 +474,7 @@ impl Show { // reversed Morph. let reverse = back && kind != "morph"; self.trans = if kind != "none" && dur > 0.0 && !doc.show.without_animation { - Some(Transition { old, from, morph: None, parts: None, start: now, kind, option, dur, reverse }) + Some(Transition { from, start: now, kind, option, dur, reverse }) } else { None }; @@ -659,11 +571,13 @@ fn show_fills_screen(reading: bool, show_type: &str) -> bool { mod tests; /// The requested presenter start mode. -#[allow(dead_code)] // P3(show-w4): ss.A4 #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum PresenterStart { + /// Do not open a presenter window. Off, + /// Use the saved setting and available displays. Setting, + /// Open the presenter regardless of the display count. Forced, } @@ -678,45 +592,125 @@ pub enum Blank { impl Show { /// The current zoom window in slide space. - #[allow(dead_code)] // P3(show-w4): ss.A5 pub(crate) fn zoom_window(&self) -> Option { - todo!("ss.A5") + self.zoomed.then(|| self.view.visible()) } } impl Show { /// Zooms the audience at a slide point. - #[allow(dead_code)] // P3(show-w4): ss.A5 pub(crate) fn zoom_at(&mut self, at: craft::behavior::kurbo::Point, inputs: &ShowZoomInputs<'_>) { - let _ = (at, inputs); - todo!("ss.A5") + if !at.x.is_finite() || !at.y.is_finite() { + return; + } + let current = view_zoom::device(&self.view, inputs.pixels_per_point); + let next = inputs.scheme.step(current, 1, inputs.size); + let target = inputs.scheme.clamp(next.min(current * zoom::ZOOM_SCALE), inputs.size); + let screen = self.view.to_screen(at); + view_zoom::about(&mut self.view, screen, target, true, inputs.pixels_per_point); + self.zoomed = true; + self.zoom_arm = false; + } + + fn update_zoomed(&mut self, pixels_per_point: f32, scheme: &craft::behavior::ZoomScheme) { + self.zoomed = view_zoom::device(&self.view, pixels_per_point) > scheme.hundred * 1.001; } } impl Show { /// The next show wake deadline. - #[allow(dead_code)] // P3(show-w4): ss.A5 pub(crate) fn next_wake(&self, doc: &Presentation, now: f64) -> Option { - let _ = (doc, now); - todo!("ss.A5") + if self.hold.is_some() || !now.is_finite() { + return None; + } + let mut wake: Option = None; + let mut consider = |deadline: f64| { + if deadline.is_finite() { + let deadline = deadline.max(now); + wake = Some(wake.map_or(deadline, |old| old.min(deadline))); + } + }; + if let Some(trans) = &self.trans { + consider((now + 1.0 / 60.0).min(trans.start + trans.dur.max(0.01))); + } + let fallback; + let timeline = match &self.timeline { + Some((slide, tl)) if *slide == self.state.slide => tl, + _ => { + fallback = ShowState::timeline(doc, self.state.slide); + &fallback + } + }; + if self.state.playing { + consider((now + 1.0 / 60.0).min(self.step_start + timeline.step_duration(self.state.step))); + } + if self.state.trigger_playing() { + consider(now + 1.0 / 60.0); + } + if !self.state.playing && self.trans.is_none() { + let idle_from = self.step_end.max(self.slide_start); + if !self.clock_navigation_held() { + if self.autoplay && self.state.step < timeline.steps() { + consider(idle_from + AUTOPLAY_DELAY); + } + if !self.rehearse + && !self.ended + && let Some(after) = self.state.advance_after(doc) + { + consider(idle_from + after); + } + } + if self.preview_only && self.state.step >= timeline.steps() { + consider(idle_from + PREVIEW_DELAY); + } + } + if !self.goto.is_empty() { + consider(self.goto_at + zoom::GOTO_HOLD); + } + if self.pointer_awake(now) { + consider(self.last_move + POINTER_IDLE); + } + if self.presenter { + if !self.timer.paused() { + let elapsed = self.timer.elapsed(now); + consider(now + 1.0 - elapsed.fract()); + } + if self.remote_opened { + consider(self.remote_sent + 0.2); + } + } + wake + } + + fn clock_navigation_held(&self) -> bool { + self.grid || self.presenter_grid || self.zoomed || self.zoom_arm } } +/// Idle delay between steps in an autoplay preview. +const AUTOPLAY_DELAY: f64 = 0.3; + +/// Idle delay before a completed preview closes. +const PREVIEW_DELAY: f64 = 0.8; + +/// Idle interval shared by the cursor and transient media controls. +const POINTER_IDLE: f64 = 2.5; + impl Show { /// Holds the show at the requested time. - #[allow(dead_code)] // P3(show-w4): ss.A5 pub(crate) fn set_hold(&mut self, t: Option) { - let _ = t; - todo!("ss.A5") + self.hold = t.filter(|t| t.is_finite()); } } impl Show { /// The shell page kind for this show. - #[allow(dead_code)] // P3(show-w4): ss.A5 pub(crate) fn page_kind(&self, doc: &Presentation, remote: bool) -> craft::ui::shell::PageKind { - let _ = (doc, remote); - todo!("ss.A5") + if show_fills_screen(self.reading, &doc.show.show_type) && !(self.presenter_start != PresenterStart::Off && remote) { + craft::ui::shell::PageKind::Presentation + } else { + craft::ui::shell::PageKind::Window + } } } @@ -732,9 +726,11 @@ pub(crate) mod tool; pub const SHOW_SCOPE: craft::ui::runtime::commands::CommandScope = ::SCOPE; /// Current canvas inputs used by show zoom operations. -#[allow(dead_code)] // P3(show-w4): ss.A5 pub(crate) struct ShowZoomInputs<'a> { - pub size: craft::behavior::kurbo::Size, + /// Slide extent in document units. + pub size: Size, + /// Device scale of the current window. pub pixels_per_point: f32, + /// The scope's edge-to-edge fitted zoom scheme. pub scheme: &'a craft::behavior::ZoomScheme, } diff --git a/crates/ui-egui/src/show/commands.rs b/crates/ui-egui/src/show/commands.rs index cb3fbfba9..f2a2a7f6c 100644 --- a/crates/ui-egui/src/show/commands.rs +++ b/crates/ui-egui/src/show/commands.rs @@ -1,96 +1,244 @@ +use super::presenter::NOTES_STEP; +use super::zoom::toggle_blank; +use super::{Blank, Show, ShowZoomInputs}; +use deckcraft_model::Presentation; +use std::sync::Arc; + /// The show window a command targets. -#[allow(dead_code)] // P3(show-w4): ss.A2 +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum ShowWindow { + /// The audience's canvas and grid. Audience, + /// The presenter's independent grid. Presenter, } -/// The commands shared by audience and presenter windows. -#[allow(dead_code)] // P3(show-w4): ss.A1 +/// Commands resolved by each live show scope, including the presenter popup. #[derive(Clone, Copy, Debug, PartialEq, Eq, craft::ui::contract::CommandSet)] #[command(prefix = "show", scope = "show")] pub(crate) enum ShowCommands { - #[command(label = "Next")] + /// Finish a step, start the next one, advance, or exit the end screen. + #[command(label = "Next", default = "Right", default = "Down", default = "Space", default = "PageDown", default = "N")] Next, - #[command(label = "Previous")] + /// Return to the previous step or slide. + #[command(label = "Previous", default = "Left", default = "Up", default = "PageUp", default = "P")] Previous, - #[command(label = "First")] + /// Visit the first slide in the show's range. + #[command(label = "First slide", default = "Home")] First, - #[command(label = "Last")] + /// Visit the last slide in the show's range. + #[command(label = "Last slide", default = "End")] Last, - #[command(label = "GoToTyped")] + /// Consume a slide number, or advance when none was typed. + #[command(label = "Go to typed slide", default = "Enter")] GoToTyped, - #[command(label = "EraseTyped")] + /// Erase a digit, or go back when none was typed. + #[command(label = "Erase typed digit", default = "Backspace")] EraseTyped, - #[command(label = "Cancel")] + /// Clear typed text, close this window's grid, leave zoom, or end the show. + #[command(label = "Cancel", default = "Escape")] Cancel, - #[command(label = "Back")] + /// Close this window's grid, leave zoom, or end the show. + #[command(label = "Back", default = "-")] Back, - #[command(label = "Pen")] + /// Toggle the ink pointer. + #[command(label = "Pen", default = "Cmd+P")] Pen, - #[command(label = "Laser")] + /// Toggle the laser pointer. + #[command(label = "Laser", default = "Cmd+L")] Laser, - #[command(label = "Arrow")] + /// Use the ordinary pointer. + #[command(label = "Arrow", default = "Cmd+A")] Arrow, - #[command(label = "Black")] + /// Toggle a black audience screen. + #[command(label = "Black screen", default = "B", default = ".")] Black, - #[command(label = "White")] + /// Toggle a white audience screen. + #[command(label = "White screen", default = "W", default = ",")] White, - #[command(label = "EraseInk")] + /// Erase this slide's ink. + #[command(label = "Erase ink", default = "E")] EraseInk, - #[command(label = "Grid")] + /// Open or close this window's slide grid. + #[command(label = "All slides", default = "G")] Grid, - #[command(label = "Zoom")] + /// Arm a zoom click or return to the whole slide. + #[command(label = "Zoom", default = "Z")] Zoom, - #[command(label = "Timer")] + /// Pause or resume the presenter timer. + #[command(label = "Pause or resume timer", default = "T")] Timer, - #[command(label = "TimerReset")] + /// Reset the presenter timer without changing its paused state. + #[command(label = "Reset timer", default = "R")] TimerReset, - #[command(label = "NotesSmaller")] + /// Decrease speaker-note text size. + #[command(label = "Smaller notes", default = "[")] NotesSmaller, - #[command(label = "NotesLarger")] + /// Increase speaker-note text size. + #[command(label = "Larger notes", default = "]")] NotesLarger, - #[command(label = "End")] + /// End the show from a control or automation request. + #[command(label = "End show")] End, - #[command(label = "Digit0")] + /// Type the digit zero. + #[command(label = "Type 0", default = "0")] Digit0, - #[command(label = "Digit1")] + /// Type the digit one. + #[command(label = "Type 1", default = "1")] Digit1, - #[command(label = "Digit2")] + /// Type the digit two. + #[command(label = "Type 2", default = "2")] Digit2, - #[command(label = "Digit3")] + /// Type the digit three. + #[command(label = "Type 3", default = "3")] Digit3, - #[command(label = "Digit4")] + /// Type the digit four. + #[command(label = "Type 4", default = "4")] Digit4, - #[command(label = "Digit5")] + /// Type the digit five. + #[command(label = "Type 5", default = "5")] Digit5, - #[command(label = "Digit6")] + /// Type the digit six. + #[command(label = "Type 6", default = "6")] Digit6, - #[command(label = "Digit7")] + /// Type the digit seven. + #[command(label = "Type 7", default = "7")] Digit7, - #[command(label = "Digit8")] + /// Type the digit eight. + #[command(label = "Type 8", default = "8")] Digit8, - #[command(label = "Digit9")] + /// Type the digit nine. + #[command(label = "Type 9", default = "9")] Digit9, } -/// Runs a show command for its window. -#[allow(dead_code)] // P3(show-w4): ss.A2 +/// Run one command in its target window and apply its navigation action before returning. pub(crate) fn run_command( - show: &mut super::Show, - doc: &std::sync::Arc, + show: &mut Show, + doc: &Arc, now: f64, command: ShowCommands, window: ShowWindow, - zoom: &super::ShowZoomInputs<'_>, + zoom: &ShowZoomInputs<'_>, ) -> bool { - let _ = (show, doc, now, command, window, zoom); - todo!("ss.A2") + use ShowCommands::*; + let presenter = window == ShowWindow::Presenter; + let grid = if presenter { show.presenter_grid } else { show.grid }; + if grid && !matches!(command, Grid | Cancel | Back) { + return true; + } + let digit = match command { + Digit0 => Some('0'), + Digit1 => Some('1'), + Digit2 => Some('2'), + Digit3 => Some('3'), + Digit4 => Some('4'), + Digit5 => Some('5'), + Digit6 => Some('6'), + Digit7 => Some('7'), + Digit8 => Some('8'), + Digit9 => Some('9'), + _ => None, + }; + if let Some(digit) = digit { + type_digit(show, digit, now); + return true; + } + let mut keep = true; + let action = match command { + Next => { + if show.ended { + keep = false; + None + } else { + Some(show.state.next(doc)) + } + } + GoToTyped => { + if !show.goto.is_empty() { + show.take_goto().filter(|i| *i < doc.slides.len()).map(|i| show.state.goto(doc, i)) + } else { + return run_command(show, doc, now, Next, window, zoom); + } + } + EraseTyped if !show.goto.is_empty() => { + show.goto.pop(); + None + } + Previous | EraseTyped => { + show.ended = false; + Some(show.state.prev(doc)) + } + Cancel | Back => { + let cleared = command == Cancel && show.clear_goto(); + if !cleared && !show.back_out(presenter, zoom) { + keep = false; + } + None + } + First => show.state.first_index(doc).map(|i| show.state.goto(doc, i)), + Last => show.state.last_index(doc).map(|i| show.state.goto(doc, i)), + Pen => { + show.set_pen(!show.pen); + None + } + Laser => { + show.set_laser(!show.laser); + None + } + Arrow => { + show.arrow(); + None + } + Black | White => { + toggle_blank(show, if command == Black { Blank::Black } else { Blank::White }); + None + } + EraseInk => { + show.strokes.clear(); + None + } + Grid => { + if grid { + if presenter { + show.presenter_grid = false; + } else { + show.grid = false; + } + } else { + show.open_grid(presenter); + } + None + } + Zoom => { + show.zoom_key(zoom); + None + } + Timer => { + show.timer.toggle(now); + None + } + TimerReset => { + show.timer.reset(now); + None + } + NotesSmaller | NotesLarger => { + show.nudge_notes(if command == NotesSmaller { -NOTES_STEP } else { NOTES_STEP }); + None + } + End => { + keep = false; + None + } + Digit0 | Digit1 | Digit2 | Digit3 | Digit4 | Digit5 | Digit6 | Digit7 | Digit8 | Digit9 => None, + }; + if let Some(action) = action { + keep &= show.apply(action, doc, now); + } + keep } -/// Adds a typed slide number digit. -#[allow(dead_code)] // P3(show-w4): ss.A2 -pub(crate) fn type_digit(show: &mut super::Show, digit: char, now: f64) { - let _ = (show, digit, now); - todo!("ss.A2") +/// Add one digit through the show's bounded slide-number buffer. +pub(crate) fn type_digit(show: &mut Show, digit: char, now: f64) { + show.push_slide_number(digit, now); } diff --git a/crates/ui-egui/src/show/keys.rs b/crates/ui-egui/src/show/keys.rs deleted file mode 100644 index cb5be19a6..000000000 --- a/crates/ui-egui/src/show/keys.rs +++ /dev/null @@ -1,167 +0,0 @@ -use super::presenter::NOTES_STEP; -use super::zoom::{plain, toggle_blank}; -// P3(show-w4): ss.A4 -use super::{Presentation, Show, ShowAction}; - -/// Read the current viewport's show keys before its widgets can consume them. Both the -/// audience window and Presenter View use this path, including animation steps and end-of-show. -/// `presenter` is true for Presenter View, where G opens that window's own grid (#1130). -pub(super) fn keyboard(ctx: &egui::Context, show: &mut Show, doc: &Presentation, now: f64, presenter: bool) -> bool { - let keys: Vec<(egui::Key, egui::Modifiers)> = ctx.input(|i| { - i.events - .iter() - .filter_map(|e| if let egui::Event::Key { key, pressed: true, modifiers, .. } = e { Some((*key, *modifiers)) } else { None }) - .collect() - }); - let (keep, consumed) = handle_keys(show, doc, now, keys, presenter); - for (key, modifiers) in consumed { - ctx.input_mut(|i| i.consume_key(modifiers, key)); - ctx.request_repaint_of(egui::ViewportId::ROOT); - } - keep -} - -pub(super) fn handle_keys( - show: &mut Show, - doc: &Presentation, - now: f64, - keys: Vec<(egui::Key, egui::Modifiers)>, - presenter: bool, -) -> (bool, Vec<(egui::Key, egui::Modifiers)>) { - let mut consumed = vec![]; - let mut keep = true; - let mut actions = vec![]; - for (k, m) in keys { - let handled = if grid_open(show, presenter) && !matches!(k, egui::Key::Escape | egui::Key::Minus) { - // See All Slides takes no other keys until a slide is chosen. - if k == egui::Key::G && plain(m) { - close_grid(show, presenter); - true - } else { - false - } - } else { - navigation_key(show, doc, k, m, presenter, &mut keep, &mut actions) || tool_key(show, k, m, now, presenter) - }; - if !handled { - continue; - } - // The same key must not also activate a focused presenter button or be handled again - // by an embedded presenter viewport. - consumed.push((k, m)); - } - for action in actions { - if !show.apply(action, doc, now) { - keep = false; - } - } - (keep, consumed) -} - -/// Whether the grid that the presenter key G opens is showing in this viewport. -fn grid_open(show: &Show, presenter: bool) -> bool { - if presenter { show.presenter_grid } else { show.grid } -} - -/// Closes the grid that G opens in this viewport. -fn close_grid(show: &mut Show, presenter: bool) { - if presenter && show.presenter_grid { - show.presenter_grid = false; - } else { - show.grid = false; - } -} - -/// Keys that move through the show or end it. False when `k` isn't one of them. -fn navigation_key( - show: &mut Show, - doc: &Presentation, - k: egui::Key, - m: egui::Modifiers, - presenter: bool, - keep: &mut bool, - actions: &mut Vec, -) -> bool { - use egui::Key::*; - match k { - Escape | Minus => { - let cancelled = k == Escape && show.clear_goto(); - // P3(show-w4): ss.A5 - if !cancelled && !show.back_out_base(presenter) { - *keep = false; - } - } - ArrowRight | ArrowDown | Space | PageDown | N => { - if show.ended { - *keep = false; - } else { - actions.push(show.state.next(doc)); - } - } - Enter => { - if !show.goto.is_empty() { - if let Some(i) = show.take_goto() - && i < doc.slides.len() - { - actions.push(show.state.goto(doc, i)); - } - } else if show.ended { - *keep = false; - } else { - actions.push(show.state.next(doc)); - } - } - Backspace if !show.goto.is_empty() => { - show.goto.pop(); - } - ArrowLeft | ArrowUp | Backspace | PageUp => { - show.ended = false; - actions.push(show.state.prev(doc)); - } - P if m.command => show.set_pen(!show.pen), - P => { - show.ended = false; - actions.push(show.state.prev(doc)); - } - Home => { - if let Some(i) = show.state.first_index(doc) { - actions.push(show.state.goto(doc, i)); - } - } - End => { - if let Some(i) = show.state.last_index(doc) { - actions.push(show.state.goto(doc, i)); - } - } - _ => return false, - } - true -} - -/// Pen, laser, blanking, zoom, the timer, note size and typed slide numbers. False when `k` -/// isn't one of them. -fn tool_key(show: &mut Show, k: egui::Key, m: egui::Modifiers, now: f64, presenter: bool) -> bool { - use egui::Key::*; - match k { - L if m.command => show.set_laser(!show.laser), - A if m.command => show.arrow(), - // P3(show-w4): ss.A4 - B | Period => toggle_blank(show, super::Blank::Black), - // P3(show-w4): ss.A4 - W | Comma => toggle_blank(show, super::Blank::White), - E => show.strokes.clear(), - G if plain(m) => show.open_grid(presenter), - Z if plain(m) => show.zoom_key(), - T if plain(m) => show.timer.toggle(now), - R if plain(m) => show.timer.reset(now), - OpenBracket if plain(m) => show.nudge_notes(-NOTES_STEP), - CloseBracket if plain(m) => show.nudge_notes(NOTES_STEP), - Num0 | Num1 | Num2 | Num3 | Num4 | Num5 | Num6 | Num7 | Num8 | Num9 => { - if let Some(d) = k.name().chars().next() { - show.push_slide_number(d, now); - } - } - _ => return false, - } - true -} diff --git a/crates/ui-egui/src/show/media.rs b/crates/ui-egui/src/show/media.rs index 259b09f05..b04625bc3 100644 --- a/crates/ui-egui/src/show/media.rs +++ b/crates/ui-egui/src/show/media.rs @@ -1,5 +1,6 @@ -use super::render::fit; -use super::{Click, HitShape, Hyperlink, PlacedShape, Presentation, Rect, ShapeId, Show, SlideApp, Ui, pos2, vec2}; +use super::{Click, HitShape, Hyperlink, PlacedShape, Presentation, Rect, ShapeId, Show, SlideApp, pos2, vec2}; +use craft::behavior::CanvasView; +use craft::behavior::kurbo::Point; use deckcraft_anim::AnimState; /// The media-host voice for slide transition sounds (no shape has this id). @@ -63,13 +64,6 @@ pub(super) fn run_media_cues(app: &mut SlideApp, show: &mut Show, doc_uid: u64, } } -/// Slide rectangle the show draws into (the reading bar keeps its strip). -pub(super) fn shown_slide_rect(ui: &Ui, show: &Show, doc: &Presentation) -> Rect { - let full = ui.max_rect(); - let avail = if show.reading { Rect::from_min_max(full.min, pos2(full.max.x, full.max.y - 34.0)) } else { full }; - fit(avail, doc) -} - /// Playback bar for one clip: along the bottom inside a large shape, just under a small icon. fn media_bar_rect(shape: Rect) -> Rect { let h = 26.0f32; @@ -81,12 +75,12 @@ fn media_bar_rect(shape: Rect) -> Rect { } } -pub(super) fn slide_media_bars(srect: Rect, doc: &Presentation, slide: usize) -> Vec<(ShapeId, deckcraft_model::MediaClip, Rect, Rect)> { - let k = srect.width() / doc.slide_size.width.max(1.0) as f32; +/// Map media shapes through the canvas view before placing their screen-space playback bars. +pub(super) fn slide_media_bars(view: CanvasView, doc: &Presentation, slide: usize) -> Vec<(ShapeId, deckcraft_model::MediaClip, Rect, Rect)> { crate::media::slide_media(doc, slide) .into_iter() .map(|(id, x, clip)| { - let r = Rect::from_min_size(pos2(srect.min.x + x.x as f32 * k, srect.min.y + x.y as f32 * k), vec2(x.w as f32 * k, x.h as f32 * k)); + let r = Rect::from_two_pos(view.to_screen(Point::new(x.x, x.y)), view.to_screen(Point::new(x.x + x.w, x.y + x.h))); let bar = media_bar_rect(r); (id, clip, r, bar) }) @@ -94,17 +88,12 @@ pub(super) fn slide_media_bars(srect: Rect, doc: &Presentation, slide: usize) -> } /// The clip whose bar or shape is under the pointer, when Show Media Controls is on. -pub(super) fn media_bar_target( - ctx: &egui::Context, - doc: &Presentation, - show: &Show, - srect: Rect, -) -> Option<(ShapeId, deckcraft_model::MediaClip, Rect)> { +pub(super) fn media_bar_target(doc: &Presentation, show: &Show, view: CanvasView, at: Point) -> Option<(ShapeId, deckcraft_model::MediaClip, Rect)> { if !doc.show.show_media_controls || show.pen || show.ended || show.blank.is_some() { return None; } - let p = ctx.input(|i| i.pointer.hover_pos())?; - let items = slide_media_bars(srect, doc, show.state.slide); + let p = view.to_screen(at); + let items = slide_media_bars(view, doc, show.state.slide); if let Some((id, clip, _, bar)) = items.iter().rev().find(|(_, _, _, bar)| bar.contains(p)) { return Some((*id, clip.clone(), *bar)); } @@ -112,26 +101,10 @@ pub(super) fn media_bar_target( Some((*id, clip.clone(), *bar)) } -/// True when the pointer is on a visible playback bar, so that click must not advance the show. -pub(super) fn pointer_on_media_bar(ctx: &egui::Context, ui: &Ui, doc: &Presentation, show: &Show, now: f64) -> bool { - if !doc.show.show_media_controls || !show.pointer_awake(now) || show.pen || show.ended || show.blank.is_some() { - return false; - } - let Some(p) = ctx.input(|i| i.pointer.interact_pos().or(i.pointer.hover_pos())) else { return false }; - let srect = shown_slide_rect(ui, show, doc); - slide_media_bars(srect, doc, show.state.slide).iter().any(|(_, _, _, bar)| bar.contains(p)) -} - /// The media shape under the pointer on the shown slide. -pub(super) fn media_hit(ctx: &egui::Context, ui: &Ui, show: &Show, doc: &Presentation) -> Option<(ShapeId, deckcraft_model::MediaClip)> { - let p = ctx.input(|i| i.pointer.interact_pos())?; - let full = ui.max_rect(); - let avail = if show.reading { Rect::from_min_max(full.min, pos2(full.max.x, full.max.y - 34.0)) } else { full }; - let srect = fit(avail, doc); - let k = srect.width() / doc.slide_size.width.max(1.0) as f32; - crate::media::slide_media(doc, show.state.slide).into_iter().rev().find_map(|(id, x, clip)| { - let r = Rect::from_min_size(pos2(srect.min.x + x.x as f32 * k, srect.min.y + x.y as f32 * k), vec2(x.w as f32 * k, x.h as f32 * k)); - r.contains(p).then_some((id, clip)) +pub(super) fn media_hit(doc: &Presentation, slide: usize, at: Point) -> Option<(ShapeId, deckcraft_model::MediaClip)> { + crate::media::slide_media(doc, slide).into_iter().rev().find_map(|(id, x, clip)| { + (at.x >= x.x && at.x <= x.x + x.w && at.y >= x.y && at.y <= x.y + x.h).then_some((id, clip)) }) } @@ -150,6 +123,7 @@ pub(crate) struct Under { shapes: Vec, /// Whether each of `shapes` is currently shown (an animation may have hidden it). visible: Vec, + /// The topmost text link or actionable shape at this pass's pointer. pub(super) pick: Option, } @@ -178,13 +152,8 @@ impl Under { /// What is under the pointer on the shown slide: the slide's shapes with their animation state, the /// topmost of them that does something when clicked, and a text hyperlink on it. Only shapes that /// are shown can be clicked, and a shape without an action hides the ones beneath it. -pub(super) fn shapes_under_pointer(ctx: &egui::Context, ui: &Ui, show: &mut Show, doc: &Presentation, now: f64) -> Option { - let p = ctx.input(|i| i.pointer.hover_pos())?; - let full = ui.max_rect(); - let avail = if show.reading { Rect::from_min_max(full.min, pos2(full.max.x, full.max.y - 34.0)) } else { full }; - let srect = fit(avail, doc); - let k = (srect.width() / doc.slide_size.width.max(1.0) as f32) as f64; - let (x, y) = ((p.x - srect.min.x) as f64 / k, (p.y - srect.min.y) as f64 / k); +pub(super) fn shapes_under_pointer(show: &mut Show, doc: &Presentation, at: Point, now: f64) -> Option { + let (x, y) = (at.x, at.y); let i = show.state.slide; if show.links.as_ref().is_none_or(|(s, ..)| *s != i) { let placed = deckcraft_render::place_slide(doc, i); @@ -252,22 +221,6 @@ impl Show { } } -/// A slide-space box on screen, the slide being drawn in `srect` at `k` pixels per point. -pub(super) fn on_screen(srect: Rect, k: f32, x: &deckcraft_geom::Xfrm) -> Rect { - Rect::from_min_size(pos2(srect.min.x + x.x as f32 * k, srect.min.y + x.y as f32 * k), vec2(x.w as f32 * k, x.h as f32 * k)) -} - -/// The animated GIF whose play/pause button is under the pointer on the shown slide. -pub(super) fn gif_hit(ctx: &egui::Context, ui: &Ui, show: &Show, doc_uid: u64, doc: &Presentation, app: &mut SlideApp) -> Option { - let p = ctx.input(|i| i.pointer.interact_pos())?; - let full = ui.max_rect(); - let avail = if show.reading { Rect::from_min_max(full.min, pos2(full.max.x, full.max.y - 34.0)) } else { full }; - let srect = fit(avail, doc); - let k = srect.width() / doc.slide_size.width.max(1.0) as f32; - let gifs = app.media.gifs(doc_uid, doc, show.state.slide, ctx.input(|i| i.time), &app.session.gif_paused); - gifs.iter().rev().find(|g| crate::media::gif_button_rect(on_screen(srect, k, &g.rect)).contains(p)).map(|g| g.id) -} - #[cfg(test)] mod hit_tests { use super::*; diff --git a/crates/ui-egui/src/show/tool.rs b/crates/ui-egui/src/show/tool.rs index c6b9a07ba..3e75afa0a 100644 --- a/crates/ui-egui/src/show/tool.rs +++ b/crates/ui-egui/src/show/tool.rs @@ -1,42 +1,363 @@ -/// The audience pointer tool and its output. -#[allow(dead_code)] // P3(show-w4): ss.A3 +use super::media::{Pick, Under, media_hit, shapes_under_pointer}; +use super::{Blank, Click, LinkJump, Show, ShowZoomInputs}; +use craft::behavior::kurbo::{Point, Size}; +use craft::behavior::{CancelReason, Cursor, CursorIcon, PointerButton}; +use craft::keymap::Mods; +use craft::ui::canvas::{CanvasTool, NavigationOptions, ToolAction, ToolContext, ToolKey, ToolPath, ToolPointer, TurnAxis, wheel_turn}; +use craft::ui::primitives::{DataStrokeWidth, DataWidth, Draw, HAlign, PaintShape, TextRun, Wrap}; +use craft::ui::style::{DataColor, Ink, TypeRole, UiTokens}; +use deckcraft_anim::ShowAction; +use deckcraft_model::Presentation; +use egui::{Color32, CornerRadius, Rect, pos2, vec2}; +use std::sync::Arc; + +craft::ui::words! { + /// Translated hints painted over the audience canvas. + struct ShowWords { + /// The audience's end-screen instruction. + end: plain = "End of slide show, click to exit."; + /// The pending magnifier's instruction. + zoom: plain = "Click the slide to zoom in. Esc cancels."; + /// The prefix of the pending slide-number hint. + goto: plain = "Go to slide"; + /// The pointer tool's accessible name. + tool: plain = "Slide show"; + } +} + +/// The audience pointer tool, rebuilt from the current pass's show and document. pub(crate) struct ShowTool<'a> { - pub show: &'a mut super::Show, - pub doc: &'a std::sync::Arc, - pub under: Option, + /// Playback state shared with show commands. + pub show: &'a mut Show, + /// Document whose slide the canvas displays. + pub doc: &'a Arc, + /// This pass's animated hit targets, also used by the pointer cursor. + pub under: Option, + /// Actions the page applies after pointer dispatch. pub out: &'a mut Out, } -/// The show tool actions and keep-show decision. -#[allow(dead_code)] // P3(show-w4): ss.A3 +/// Actions and the keep-show decision produced by one audience pass. pub(crate) struct Out { + /// Whether the show should remain open. pub keep: bool, - pub actions: Vec, + /// Navigation actions awaiting the page's clock and media handling. + pub actions: Vec, } -use craft::ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolPath, ToolPointer}; -impl CanvasTool for ShowTool<'_> { - fn press(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction { - let _ = (pointer, cx); - todo!("ss.A3") +impl ShowTool<'_> { + fn time(&self, cx: &ToolContext<'_>) -> f64 { + self.show.hold.unwrap_or(cx.time) } - fn drag(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { - let _ = (pointer, cx); - todo!("ss.A3") + + fn on_slide(&self) -> bool { + !self.show.grid + && !self.show.pen + && !self.show.laser + && !self.show.ended + && self.show.blank.is_none() + && !self.show.zoomed + && !self.show.zoom_arm } - fn release(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { - let _ = (pointer, cx); - todo!("ss.A3") + + fn slide_point(&self, at: Point) -> bool { + at.x >= 0.0 && at.y >= 0.0 && at.x <= self.doc.slide_size.width && at.y <= self.doc.slide_size.height } - fn cancel(&mut self, reason: craft::behavior::CancelReason, cx: &mut ToolContext<'_>) { - let _ = (reason, cx); - todo!("ss.A3") + + fn hit(&mut self, pointer: &ToolPointer, cx: &ToolContext<'_>) { + let at = self.show.view.to_doc(pointer.pos); + let now = self.time(cx); + self.under = if self.on_slide() { shapes_under_pointer(self.show, self.doc, at, now) } else { None }; } - fn paint(&self, draw: &craft::ui::primitives::Draw<'_>, cx: &ToolContext<'_>) { - let _ = (draw, cx); - todo!("ss.A3") + + fn next(&mut self) { + if self.show.ended { + self.out.keep = false; + } else { + self.out.actions.push(self.show.state.next(self.doc)); + } } - fn command_form(&self) -> ToolPath { - todo!("ss.A3") + + fn previous(&mut self) { + self.show.ended = false; + self.out.actions.push(self.show.state.prev(self.doc)); } } + +impl CanvasTool for ShowTool<'_> { + fn each_pass(&mut self, cx: &mut ToolContext<'_>) { + let now = self.time(cx); + // Only a move or entry event is movement: hover, a press-only rehover and key or modifier stir are not. + if cx.pointer_moved() { + self.show.last_move = now; + } + let Some(space) = cx.space() else { return }; + let scheme = space.zoom_scheme(); + self.show.view = space.view; + self.show.view.rect = cx.rect; + self.show.update_zoomed(space.pixels_per_point, &scheme); + if !self.show.zoomed { + let inputs = ShowZoomInputs { + size: Size::new(self.doc.slide_size.width, self.doc.slide_size.height), + pixels_per_point: space.pixels_per_point, + scheme: &scheme, + }; + // Restoring fit must not cancel a pending placement click. + let armed = self.show.zoom_arm; + self.show.dismiss_zoom(&inputs); + self.show.zoom_arm = armed; + cx.set_view(self.show.view); + } + if !self.show.zoomed + && !self.show.pen + && !self.show.grid + && let Some(wheel) = space.wheel() + && !wheel.zooms + { + let along = if wheel.gathered.x.abs() > wheel.gathered.y.abs() { wheel.scroll.x } else { wheel.scroll.y }; + let forward = along < 0.0; + let notch = f64::from(NavigationOptions::default().wheel_line); + if let Some(next) = wheel_turn(&wheel, Some(forward), notch, TurnAxis::Stronger) { + if next { + self.next(); + } else { + self.previous(); + } + } + } + if let Some(pointer) = cx.pointer { + self.hit(&pointer, cx); + } else { + self.under = None; + } + if self.show.hold.is_none() && (self.show.state.playing || self.show.state.trigger_playing() || self.show.trans.is_some()) { + cx.request_repaint(); + } + } + + fn takes(&self, button: PointerButton, _mods: Mods) -> bool { + matches!(button, PointerButton::Primary | PointerButton::Secondary) + } + + fn press(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction { + if self.show.grid { + return ToolAction::Ignored; + } + if self.show.pen && pointer.button == PointerButton::Primary { + let at = self.show.view.to_doc(pointer.pos); + if !self.slide_point(at) { + return ToolAction::Ignored; + } + self.show.strokes.push(vec![at]); + cx.request_repaint(); + } + ToolAction::Claimed + } + + fn drag(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { + if !self.show.pen || pointer.button != PointerButton::Primary { + return; + } + let at = self.show.view.to_doc(pointer.pos); + if self.slide_point(at) + && let Some(stroke) = self.show.strokes.last_mut() + && stroke.last() != Some(&at) + { + stroke.push(at); + cx.request_repaint(); + } + } + + fn release(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { + if self.show.grid { + return; + } + if pointer.button == PointerButton::Secondary { + if !self.show.ended && !self.show.zoomed && !self.show.zoom_arm { + self.previous(); + } + return; + } + if pointer.button != PointerButton::Primary { + return; + } + if self.show.pen { + // A press without movement leaves no ink geometry behind. + if self.show.strokes.last().is_some_and(|stroke| stroke.len() < 2) { + self.show.strokes.pop(); + } + return; + } + // PLAN: plan error: ToolContext needs the release-click verdict from ToolHost::phase's PressPhase::Release to suppress actions after a drag (canvas-w4). + let now = self.time(cx); + let at = self.show.view.to_doc(pointer.pos); + self.hit(pointer, cx); + // Canvas controls own their initiating presses before the background tool. Media shape + // clicks are independent of the visibility of their playback controls. + if self.on_slide() && let Some((id, _)) = media_hit(self.doc, self.show.state.slide, at) { + self.show.media_cues.push((id, "pause".into())); + } else if let Some(Pick::Text(link)) = self.under.as_ref().and_then(|under| under.pick.clone()) { + match self.show.state.follow_link(self.doc, &link, self.show.last_viewed) { + LinkJump::Show(action) => self.out.actions.push(action), + LinkJump::Open(url) => cx.open_url(url), + LinkJump::Exit => self.out.keep = false, + LinkJump::None => {} + } + } else if self.show.zoom_arm { + if self.slide_point(at) + && let Some(space) = cx.space() + { + let scheme = space.zoom_scheme(); + self.show.zoom_at( + at, + &ShowZoomInputs { + size: Size::new(self.doc.slide_size.width, self.doc.slide_size.height), + pixels_per_point: space.pixels_per_point, + scheme: &scheme, + }, + ); + cx.set_view(self.show.view); + } + } else if self.show.zoomed { + if let Some(space) = cx.space() { + let scheme = space.zoom_scheme(); + self.show.dismiss_zoom(&ShowZoomInputs { + size: Size::new(self.doc.slide_size.width, self.doc.slide_size.height), + pixels_per_point: space.pixels_per_point, + scheme: &scheme, + }); + cx.set_view(self.show.view); + } + } else if self.show.ended { + self.out.keep = false; + } else if self.show.blank.is_some() { + self.show.blank = None; + } else { + let none = Under::default(); + match self.show.click_slide(self.doc, self.under.as_ref().unwrap_or(&none), now) { + Click::Show(action) => self.out.actions.push(action), + Click::Open(url) => cx.open_url(url), + Click::Exit => self.out.keep = false, + Click::Animated | Click::None => {} + } + } + cx.request_repaint(); + } + + fn cancel(&mut self, _reason: CancelReason, cx: &mut ToolContext<'_>) { + if self.show.pen && cx.pointer.is_some_and(|pointer| pointer.button == PointerButton::Primary) { + self.show.strokes.pop(); + cx.request_repaint(); + } + } + + fn key(&mut self, _key: &ToolKey, _cx: &mut ToolContext<'_>) -> bool { + false + } + + fn takes_every_move(&self) -> bool { + self.show.pen + } + + fn autoscrolls(&self) -> bool { + false + } + + fn cursor(&self, cx: &ToolContext<'_>) -> Cursor { + let icon = if self.show.pen || self.show.zoom_arm || self.show.grid { + CursorIcon::Crosshair + } else if self.show.laser || self.show.hides_idle_cursor(self.time(cx)) { + CursorIcon::None + } else if self.under.as_ref().is_some_and(|under| under.pick.is_some()) { + CursorIcon::PointingHand + } else { + CursorIcon::Default + }; + icon.into() + } + + fn paint(&self, draw: &Draw<'_>, cx: &ToolContext<'_>) { + let words = cx.words::(); + if self.show.ended { + draw.data_fill(&PaintShape::Rect(cx.rect, CornerRadius::ZERO), DataColor::new(Color32::BLACK)); + hint(draw, cx, words.end.as_str(), true); + } + if let Some(blank) = self.show.blank { + let color = match blank { + Blank::Black => Color32::BLACK, + Blank::White => Color32::WHITE, + }; + draw.data_fill(&PaintShape::Rect(cx.rect, CornerRadius::ZERO), DataColor::new(color)); + } + let ink = DataColor::new(data_color(self.doc.show.pen_color)); + for stroke in &self.show.strokes { + if stroke.len() > 1 { + let points = stroke.iter().map(|at| self.show.view.to_screen(*at)).collect(); + draw.stroke(&PaintShape::Path(points), DataStrokeWidth::Data(DataWidth::points(INK_WIDTH)), ink); + } + } + if self.show.laser && !self.show.ended && let Some(pointer) = cx.pointer { + let color = data_color(self.doc.show.laser_color); + draw.data_fill( + &PaintShape::Circle(pointer.pos, LASER_HALO_RADIUS), + DataColor::new(Color32::from_rgba_unmultiplied(color.r(), color.g(), color.b(), LASER_HALO_ALPHA)), + ); + draw.data_fill(&PaintShape::Circle(pointer.pos, LASER_DOT_RADIUS), DataColor::new(color)); + } + if self.show.zoom_arm && !self.show.grid { + hint(draw, cx, words.zoom.as_str(), true); + } + if !self.show.goto.is_empty() { + hint(draw, cx, &format!("{} {}", words.goto.as_str(), self.show.goto), false); + } + } + + fn command_form(&self) -> ToolPath { + if self.show.pen { + ToolPath::Freehand("slide show ink has no keyboard equivalent; Erase ink clears it") + } else { + ToolPath::Command("show commands") + } + } + + fn access(&self, cx: &ToolContext<'_>) -> Option { + Some(craft::ui::canvas::ToolAccess::new(cx.words::().tool.as_str())) + } +} + +/// The pen's stroke width in points, as the production show draws it. +const INK_WIDTH: f32 = 3.0; + +/// The laser's translucent halo radius in points, as the production show draws it. +const LASER_HALO_RADIUS: f32 = 16.0; + +/// The laser's opaque core radius in points, as the production show draws it. +const LASER_DOT_RADIUS: f32 = 5.5; + +/// The laser halo's alpha, as the production show draws it. +const LASER_HALO_ALPHA: u8 = 70; + +/// The document's pen or laser colour as an egui colour. +fn data_color(c: deckcraft_color::Rgba) -> Color32 { + Color32::from_rgba_unmultiplied(c.r, c.g, c.b, c.a) +} + +fn hint(draw: &Draw<'_>, cx: &ToolContext<'_>, text: &str, top: bool) { + let Some(style) = cx.style() else { return }; + let pad = style.tokens.space.pad.control; + let gap = style.tokens.space.gap.section; + let run = TextRun::new(text).role(TypeRole::BodyLarge).align(HAlign::Center).wrap(Wrap::Wrap).color(style.ink(Ink::OnDark)); + let room = cx.rect.shrink(gap); + let layout = draw.layout(&run, (room.width() - 2.0 * pad).max(0.0)); + let size = (layout.size() + vec2(2.0 * pad, 2.0 * pad)).min(room.size().max(egui::Vec2::ZERO)); + let y = if top { room.top() } else { room.bottom() - size.y }; + let rect = Rect::from_min_size(pos2(room.center().x - size.x / 2.0, y), size); + // PLAN: plan error: Draw::surface_look over-picture resolver (show-w2) is not in this tree; the scrim pill stays hand-built until it lands. + draw.fill( + &PaintShape::Rect(rect, UiTokens::corner(style.tokens.shape.radius.pill)), + style.color(style.tokens.color.surface.scrim), + ); + draw.clipped(rect, |draw| { + draw.text(rect.shrink(pad), &run); + }); +} diff --git a/crates/ui-egui/src/show/zoom.rs b/crates/ui-egui/src/show/zoom.rs index dc6c09c77..5eb9fab7d 100644 --- a/crates/ui-egui/src/show/zoom.rs +++ b/crates/ui-egui/src/show/zoom.rs @@ -1,23 +1,13 @@ use super::presenter::{NOTES_MAX, NOTES_MIN}; -use super::render::render_thumb; -use super::{Align2, Color32, CornerRadius, Pos2, Presentation, Rect, Show, Stroke, json, pos2, theme, vec2}; +use super::{Blank, Presentation, Rect, Show, ShowZoomInputs, json, view_zoom}; impl Show { - pub(super) fn zoom_uv(&self) -> Rect { - self.zoom.map(Zoom::uv).unwrap_or_else(unit_uv) - } - + /// The label reflects whether a zoom is active or awaiting its placement click. pub(super) fn zoom_label(&self) -> &'static str { - if self.zoom.is_some() { - "Zoom on" - } else if self.zoom_arm { - "Zoom…" - } else { - "Zoom" - } + if self.zoomed { "Zoom on" } else if self.zoom_arm { "Zoom…" } else { "Zoom" } } - /// G opens See All Slides in the window it was pressed in: Presenter View's grid stays off the audience screen (#1130). + /// Open only the grid of the window that received the command. pub(super) fn open_grid(&mut self, presenter: bool) { if presenter { self.presenter_grid = true; @@ -26,83 +16,47 @@ impl Show { } } - /// Z, or the Zoom button: arm a click-to-zoom, or leave a zoom that is already on. - pub(super) fn zoom_key(&mut self) { - if self.zoom.is_some() || self.zoom_arm { - // P3(show-w4): ss.A5 - self.dismiss_zoom_base(); + /// Arm click placement, or restore the whole slide with this pass's fitted scheme. + pub(super) fn zoom_key(&mut self, inputs: &ShowZoomInputs<'_>) { + if self.zoomed || self.zoom_arm { + self.dismiss_zoom(inputs); } else { self.zoom_arm = true; self.pen = false; } } - /// Ctrl/Cmd+wheel: `lines` notches in (positive) or out around the slide point under `p`. - /// Back to the whole slide leaves the zoom. A pointer off the slide does nothing. - pub(super) fn wheel_zoom(&mut self, srect: Rect, p: Pos2, lines: f32) { - let uv = self.zoom_uv(); - let Some((nx, ny)) = norm_on_slide(srect, uv, p) else { return }; - let from = self.zoom.map_or(1.0, |z| z.scale); - let scale = (from * 2f32.powf(lines / WHEEL_NOTCHES_PER_DOUBLING)).min(WHEEL_ZOOM_MAX); - if !scale.is_finite() { - return; - } - self.zoom_arm = false; - if scale <= 1.0 + 1e-3 { - self.zoom = None; - return; - } - // The new window puts (nx, ny) at the same place on screen as before. - let w = 1.0 / scale; - let fx = (p.x - srect.min.x) / srect.width(); - let fy = (p.y - srect.min.y) / srect.height(); - let x = (nx - fx * w).clamp(0.0, 1.0 - w); - let y = (ny - fy * w).clamp(0.0, 1.0 - w); - self.zoom = Some(Zoom { nx: x + w * 0.5, ny: y + w * 0.5, scale }); - } - - /// Esc closes the See All Slides of the window it was pressed in, then a zoom, and only then leaves the show. - // P3(show-w4): ss.A5 - pub(super) fn back_out_base(&mut self, presenter: bool) -> bool { + /// Close this window's grid before backing out of an active or armed zoom. + pub(crate) fn back_out(&mut self, presenter: bool, inputs: &ShowZoomInputs<'_>) -> bool { if presenter && self.presenter_grid { self.presenter_grid = false; - true } else if !presenter && self.grid { self.grid = false; - true + } else if self.zoomed || self.zoom_arm { + self.dismiss_zoom(inputs); } else { - // P3(show-w4): ss.A5 - self.dismiss_zoom_base() + return false; } + true } - /// Esc backs out of a zoom before it leaves the show. True when it did. - // P3(show-w4): ss.A5 - pub(super) fn dismiss_zoom_base(&mut self) -> bool { - if self.zoom.is_some() || self.zoom_arm { - self.zoom = None; - self.zoom_arm = false; - true - } else { - false - } + /// Return to the slide's zero-margin fit using the current canvas inputs. + pub(crate) fn dismiss_zoom(&mut self, inputs: &ShowZoomInputs<'_>) { + view_zoom::fit_up_to(&mut self.view, inputs.size, inputs.pixels_per_point, inputs.scheme.max_device(), 0.0, inputs.scheme); + self.zoomed = false; + self.zoom_arm = false; } + /// The stable control-protocol name of the audience's blank colour. pub fn blank_name(&self) -> Option<&'static str> { match self.blank { - // P3(show-w4): ss.A4 - Some(c) if c == super::Blank::Black => Some("black"), - // P3(show-w4): ss.A4 - Some(c) if c == super::Blank::White => Some("white"), - Some(_) => Some("blank"), + Some(Blank::Black) => Some("black"), + Some(Blank::White) => Some("white"), None => None, } } - pub fn zoom_view(&self) -> Option<(f32, f32, f32)> { - self.zoom.map(|z| (z.nx, z.ny, z.scale)) - } - + /// Append a decimal digit without growing an unbounded number buffer. pub(super) fn push_slide_number(&mut self, digit: char, now: f64) { if !digit.is_ascii_digit() || self.goto.len() >= GOTO_DIGITS { return; @@ -111,31 +65,27 @@ impl Show { self.goto_at = if now.is_finite() { now } else { 0.0 }; } - /// 1-based slide number, or `None` for 0 or a non-number. The buffer is cleared either way. + /// Convert the consumed one-based number to an index; zero is not a slide. pub(super) fn take_goto(&mut self) -> Option { let raw = std::mem::take(&mut self.goto); raw.parse::().ok().and_then(|n| n.checked_sub(1)) } + /// Drop an unfinished number after its last digit has timed out. pub(super) fn expire_goto(&mut self, now: f64) { - if self.goto.is_empty() || !now.is_finite() || !self.goto_at.is_finite() { - return; - } - if now - self.goto_at > GOTO_HOLD { + if !self.goto.is_empty() && now.is_finite() && self.goto_at.is_finite() && now - self.goto_at > GOTO_HOLD { self.goto.clear(); } } - /// Esc drops a number in progress. True when it did. + /// Clear typed text before Escape backs out of a mode or ends the show. pub(super) fn clear_goto(&mut self) -> bool { - if self.goto.is_empty() { - false - } else { - self.goto.clear(); - true - } + let had_text = !self.goto.is_empty(); + self.goto.clear(); + had_text } + /// Keep speaker-note text within the presenter's supported range. pub(super) fn nudge_notes(&mut self, delta: f32) { let next = self.notes_px + delta; if next.is_finite() { @@ -143,15 +93,20 @@ impl Show { } } - pub fn showing_value(&self, n_slides: usize, aspect: f32, full: Rect, now: f64) -> serde_json::Value { - let mut v = json!({ + /// Snapshot the show for automation, laying out an open grid from this request's room. + pub fn showing_value(&self, ctx: &egui::Context, n_slides: usize, aspect: f32, full: Rect, now: f64) -> serde_json::Value { + let mut value = json!({ "slide": self.state.slide, "step": self.state.step, "ended": self.ended, "grid": self.grid, "zoomArm": self.zoom_arm, "blank": self.blank_name(), - "zoom": self.zoom_view().map(|(x, y, scale)| json!({"x": x, "y": y, "scale": scale})), + "zoom": self.zoom_window().map(|window| json!({ + "x": window.center().x, + "y": window.center().y, + "scale": self.view.zoom, + })), "presenterPaused": self.timer.paused(), "presenterSecs": self.timer.elapsed(now), "notesPx": self.notes_px, @@ -160,265 +115,39 @@ impl Show { }); if self.grid { let slides = grid_indices(n_slides); - let cells = see_all_cells(full, slides.len(), aspect); - v["cells"] = - serde_json::Value::Array(slides.iter().zip(cells).map(|(i, r)| json!({"slide": i, "x": r.center().x, "y": r.center().y})).collect()); + let cells = super::grid::cells(ctx, full, n_slides, aspect); + value["cells"] = serde_json::Value::Array( + slides.iter().zip(cells).map(|(i, rect)| json!({"slide": i, "x": rect.center().x, "y": rect.center().y})).collect(), + ); } - v - } - - pub(super) fn reading_bar_hit(&self, ctx: &egui::Context) -> bool { - // Clicks on the on-screen controls must not also advance. - ctx.input(|i| i.pointer.interact_pos()).is_some_and(|p| { - let r = ctx.content_rect(); - (self.reading && p.y > r.max.y - 34.0) || (!self.reading && tool_bar_rect(r).expand(8.0).contains(p)) - }) + value } } -const GOTO_HOLD: f64 = 3.0; +/// How long an unfinished slide number remains visible. +pub(super) const GOTO_HOLD: f64 = 3.0; +/// Maximum number of decimal digits in a typed slide number. pub(super) const GOTO_DIGITS: usize = 4; -const ZOOM_SCALE: f32 = 2.0; - -/// Four notches double the zoom, so the wheel passes through the click-zoom's 2× on its way to 4×. -const WHEEL_NOTCHES_PER_DOUBLING: f32 = 4.0; - -/// PowerPoint's slide show magnifier goes up to 400%. -const WHEEL_ZOOM_MAX: f32 = 4.0; +/// Click magnification relative to the current fitted zoom. +pub(super) const ZOOM_SCALE: f64 = 2.0; +/// Maximum number of slides offered by the overview grid. pub(crate) const GRID_CAP: usize = 48; -const TOOL_BAR_W: f32 = 520.0; - -#[derive(Clone, Copy)] -pub(super) struct Zoom { - pub(super) nx: f32, - pub(super) ny: f32, - pub(super) scale: f32, -} - -impl Zoom { - pub(super) fn at(nx: f32, ny: f32) -> Self { - Zoom { nx: finite_unit(nx), ny: finite_unit(ny), scale: ZOOM_SCALE } - } - - pub(super) fn uv(self) -> Rect { - zoom_uv(self.nx, self.ny, self.scale) - } -} - -fn finite_unit(n: f32) -> f32 { - if n.is_finite() { n.clamp(0.0, 1.0) } else { 0.5 } -} - -pub(super) fn plain(m: egui::Modifiers) -> bool { - !m.command && !m.ctrl && !m.alt && !m.shift -} - -pub(super) fn unit_uv() -> Rect { - Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)) -} - +/// The slide aspect used by previews and the overview grid. pub(super) fn slide_aspect(doc: &Presentation) -> f32 { - let a = doc.slide_size.width as f32 / doc.slide_size.height.max(1.0) as f32; - if a.is_finite() && a > 0.05 { a } else { 16.0 / 9.0 } + let aspect = doc.slide_size.width as f32 / doc.slide_size.height.max(1.0) as f32; + if aspect.is_finite() && aspect > 0.05 { aspect } else { 16.0 / 9.0 } } -/// The part of the slide a zoom shows, in 0–1 texture space. The window stays on the slide. -pub(super) fn zoom_uv(nx: f32, ny: f32, scale: f32) -> Rect { - let scale = if scale.is_finite() && scale > 1.0 { scale } else { ZOOM_SCALE }; - let w = 1.0 / scale; - if w >= 1.0 { - return unit_uv(); - } - let x = (nx - w * 0.5).clamp(0.0, 1.0 - w); - let y = (ny - w * 0.5).clamp(0.0, 1.0 - w); - Rect::from_min_size(pos2(x, y), vec2(w, w)) +/// Toggle the requested fixed audience colour. +pub(super) fn toggle_blank(show: &mut Show, blank: Blank) { + show.blank = if show.blank == Some(blank) { None } else { Some(blank) }; } -/// The Ctrl/Cmd+wheel movement this frame in wheel lines (up is positive), `None` when there was -/// none. Read from the raw events: egui's `zoom_delta` also carries the trackpad pinch, which is -/// not a show gesture. -pub(super) fn wheel_zoom_lines(events: &[egui::Event], line_points: f32) -> Option { - let mut lines = None; - for event in events { - if let egui::Event::MouseWheel { unit, delta, modifiers, .. } = event - && (modifiers.ctrl || modifiers.command) - { - let along = if delta.x.abs() > delta.y.abs() { delta.x } else { delta.y }; - let n = match unit { - egui::MouseWheelUnit::Point => along / line_points.max(1.0), - egui::MouseWheelUnit::Line | egui::MouseWheelUnit::Page => along, - }; - *lines.get_or_insert(0.0) += if n.is_finite() { n } else { 0.0 }; - } - } - lines -} - -pub(super) fn zoom_frame(slide: Rect, uv: Rect) -> Rect { - Rect::from_min_size( - pos2(slide.min.x + uv.min.x * slide.width(), slide.min.y + uv.min.y * slide.height()), - vec2(uv.width() * slide.width(), uv.height() * slide.height()), - ) -} - -pub(super) fn toggle_blank(show: &mut Show, color: super::Blank) { - show.blank = if show.blank == Some(color) { None } else { Some(color) }; -} - -pub(super) fn tool_bar_rect(full: Rect) -> Rect { - let w = TOOL_BAR_W.min((full.width() - 32.0).max(32.0)); - Rect::from_min_size(pos2(full.min.x + 16.0, full.max.y - 50.0), vec2(w, 34.0)) -} - -pub(super) fn grid_indices(n: usize) -> Vec { - (0..n.min(GRID_CAP)).collect() -} - -/// Thumbnail rectangles for `n` slides inside `full`, largest 16:9-style thumbs that fit. -pub(super) fn see_all_cells(full: Rect, n: usize, aspect: f32) -> Vec { - if n == 0 || full.width() < 16.0 || full.height() < 16.0 { - return vec![]; - } - let aspect = if aspect.is_finite() && aspect > 0.05 { aspect } else { 16.0 / 9.0 }; - let margin = 28.0; - let gap = 16.0; - let label_h = 22.0; - let inner = full.shrink(margin); - let inner = Rect::from_min_max(pos2(inner.min.x, inner.min.y + 36.0), inner.max); - if inner.width() < 8.0 || inner.height() < 8.0 { - return vec![]; - } - let mut best: Vec = vec![]; - let mut best_area = 0.0_f32; - for cols in 1..=n.min(8) { - let rows = n.div_ceil(cols); - let cell_w = (inner.width() - gap * (cols.saturating_sub(1) as f32)) / cols as f32; - let cell_h = (inner.height() - gap * (rows.saturating_sub(1) as f32)) / rows as f32; - if cell_w < 8.0 || cell_h < label_h + 8.0 { - continue; - } - let thumb_max_h = cell_h - label_h; - let mut tw = cell_w; - let mut th = tw / aspect; - if th > thumb_max_h { - th = thumb_max_h; - tw = th * aspect; - } - if tw < 8.0 || th < 8.0 { - continue; - } - let area = tw * th; - if area <= best_area { - continue; - } - best_area = area; - best = (0..n) - .map(|i| { - let c = i % cols; - let r = i / cols; - let ox = inner.min.x + c as f32 * (cell_w + gap) + (cell_w - tw) * 0.5; - let oy = inner.min.y + r as f32 * (cell_h + gap); - Rect::from_min_size(pos2(ox, oy), vec2(tw, th)) - }) - .collect(); - } - best -} - -pub(super) fn see_all_hit(full: Rect, n: usize, aspect: f32, p: Pos2) -> Option { - see_all_cells(full, n, aspect).into_iter().position(|r| r.expand2(vec2(4.0, 18.0)).contains(p)) -} - -pub(super) fn norm_on_slide(srect: Rect, uv: Rect, p: Pos2) -> Option<(f32, f32)> { - if srect.width() <= 1.0 || srect.height() <= 1.0 || !srect.contains(p) { - return None; - } - let u = (p.x - srect.min.x) / srect.width(); - let v = (p.y - srect.min.y) / srect.height(); - let nx = uv.min.x + u * uv.width(); - let ny = uv.min.y + v * uv.height(); - (nx.is_finite() && ny.is_finite()).then_some((nx.clamp(0.0, 1.0), ny.clamp(0.0, 1.0))) -} - -pub(super) fn slide_to_screen(srect: Rect, uv: Rect, nx: f32, ny: f32) -> Pos2 { - let u = (nx - uv.min.x) / uv.width().max(1e-4); - let v = (ny - uv.min.y) / uv.height().max(1e-4); - pos2(srect.min.x + u * srect.width(), srect.min.y + v * srect.height()) -} - -pub(super) fn slide_box(srect: Rect, uv: Rect, (slide_w, slide_h): (f32, f32), (x, y, w, h): (f32, f32, f32, f32)) -> Rect { - let a = slide_to_screen(srect, uv, x / slide_w.max(1.0), y / slide_h.max(1.0)); - let b = slide_to_screen(srect, uv, (x + w) / slide_w.max(1.0), (y + h) / slide_h.max(1.0)); - Rect::from_min_max(a, b) -} - -pub(super) fn paint_grid(painter: &egui::Painter, ctx: &egui::Context, show: &mut Show, doc: &Presentation, full: Rect) { - let slides = grid_indices(doc.slides.len()); - let aspect = slide_aspect(doc); - let cells = see_all_cells(full, slides.len(), aspect); - painter.rect_filled(full, CornerRadius::ZERO, Color32::from_gray(16)); - painter.text(pos2(full.center().x, full.min.y + 28.0), Align2::CENTER_CENTER, "All slides", theme::font(20.0), Color32::WHITE); - if doc.slides.len() > GRID_CAP { - painter.text( - pos2(full.center().x, full.min.y + 50.0), - Align2::CENTER_CENTER, - format!("First {GRID_CAP} slides"), - theme::font(13.0), - Color32::from_gray(180), - ); - } - let budget = if slides.len() <= 12 { 12 } else { 4 }; - let mut made = 0; - for (i, rect) in slides.iter().copied().zip(cells) { - painter.rect_filled(rect, CornerRadius::same(4), Color32::from_gray(32)); - let tex = match show.thumbs.iter().find(|(k, _)| *k == i).map(|(_, t)| t.clone()) { - Some(t) => Some(t), - None if made < budget => { - made += 1; - render_thumb(ctx, show, doc, i) - } - None => { - ctx.request_repaint(); - None - } - }; - if let Some(t) = tex { - painter.image(t.id(), rect, unit_uv(), Color32::WHITE); - } - let current = i == show.state.slide; - painter.rect_stroke( - rect, - CornerRadius::same(4), - Stroke::new(if current { 3.0 } else { 1.0 }, if current { Color32::WHITE } else { Color32::from_gray(70) }), - egui::StrokeKind::Inside, - ); - let hidden = doc.slides.get(i).is_some_and(|s| s.hidden); - let label = if hidden { format!("{} Hidden", i + 1) } else { format!("{}", i + 1) }; - painter.text( - pos2(rect.center().x, rect.max.y + 12.0), - Align2::CENTER_CENTER, - label, - theme::font(13.0), - if current { Color32::WHITE } else { Color32::from_gray(180) }, - ); - } -} - -impl Show { - /// Dismisses the zoom with the current pass inputs. - #[allow(dead_code)] // P3(show-w4): ss.A5 - pub(crate) fn dismiss_zoom(&mut self, inputs: &super::ShowZoomInputs<'_>) { - let _ = inputs; - todo!("ss.A5") - } - /// Closes the target window grid, then dismisses zoom before leaving the show. - #[allow(dead_code)] // P3(show-w4): ss.A5 - pub(crate) fn back_out(&mut self, presenter: bool, inputs: &super::ShowZoomInputs<'_>) -> bool { - let _ = (presenter, inputs); - todo!("ss.A5") - } +/// The row-major slide indices corresponding to the grid's capped layout. +pub(super) fn grid_indices(total: usize) -> Vec { + (0..total.min(GRID_CAP)).collect() }