Skip to main content

egui_pop_views/video/
mod.rs

1//! Video: the [`Video`] widget, a local video file played in place, and the
2//! [`VideoBackend`] it plays through.
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! ```no_run
8//! use egui_pop_views::video::{Controls, Fit, Video};
9//!
10//! fn ui(ui: &mut egui::Ui) {
11//!     // A tutorial, with every control.
12//!     Video::new("/usr/share/app/tour.webm").id("tour").show(ui);
13//!     // A preview: no controls, playing at once, again and again, silent.
14//!     Video::new("/usr/share/app/gesture.webm")
15//!         .controls(Controls::None)
16//!         .autoplay(true)
17//!         .looping(true)
18//!         .muted(true)
19//!         .fit(Fit::Cover)
20//!         .size(egui::vec2(240.0, 135.0))
21//!         .show(ui);
22//! }
23//! ```
24//!
25//! - **Players**: each widget has its own (one pipeline per video), opened
26//!   when it is first drawn and paused on its first picture, unless it plays
27//!   at once ([`Video::autoplay`]). The backend is GStreamer with the `video`
28//!   feature, none without it or on the web: the widget then draws a
29//!   placeholder saying so, with **Open outside**. [`Video::backend`] gives
30//!   another (a host's own player, a test's pretend one).
31//! - **Off the interface's thread**: the player decodes on its own threads and
32//!   keeps the last frame; each pass takes that one and uploads it, whatever
33//!   the player decoded in between.
34//! - **Repaints**: the player asks for one when a frame or an event arrives,
35//!   the widget for one a few times a second while playing, for the time.
36//!   Paused, ended or loading, nothing keeps the application awake.
37//! - **Out of view**: a widget no longer drawn (a page left, a panel closed, a
38//!   tab behind another) has its player stopped after a few passes; drawn
39//!   again, it opens the file at the same place, paused (playing, with
40//!   [`Video::autoplay`]).
41//! - **Controls** ([`Controls`]): `Full` (the position on a row of its own;
42//!   Play or Pause, the time and the volume under it), `Compact` (Play or
43//!   Pause, the position and the time on one row), `None` (the picture only).
44//!   A click on the picture plays or pauses, except without controls.
45//! - **Keys**, while the picture has the focus (it is a Tab stop with
46//!   controls): Space plays or pauses, Left and Right move by [`SEEK_STEP`],
47//!   Up and Down change the volume by [`VOLUME_STEP`]. A key an application
48//!   binds on the picture's surface ([`Video::surface`]) runs its command
49//!   instead, as the viewer's do.
50//! - **Loops** ([`Video::looping`]): the player loops by itself when it can
51//!   ([`VideoPlayer::set_looping`]; GStreamer's does, without a gap), else the
52//!   widget seeks back to the start at the end.
53//! - **Agents**: a widget given an [`id`](Video::id) is listed by the `videos`
54//!   collector and driven by the `video.*` commands ([`VideoPlugin`]); its
55//!   accessible node is a video named after the file (or [`Video::label`]).
56
57mod plugin;
58mod session;
59
60#[cfg(all(feature = "video", not(target_arch = "wasm32")))]
61mod gst;
62
63use std::path::{Path, PathBuf};
64use std::sync::Arc;
65use std::time::Duration;
66
67use crate::app_link::AppHandle;
68use egui::accesskit::Role;
69use egui::load::SizedTexture;
70use egui::{
71    Align2, Color32, ColorImage, Key, Modifiers, Rect, Response, Sense, Ui, Vec2, pos2, vec2,
72};
73#[cfg(feature = "api")]
74use egui_pop_api::links::{self, How, Request, Source};
75#[cfg(feature = "api")]
76use egui_pop_api::strings::LINKS_OPEN_OUTSIDE;
77use egui_pop_core::kit::{Kit, KitCx, Part, State};
78use egui_pop_core::lock;
79use egui_pop_core::slider::Slider;
80#[cfg(not(feature = "api"))]
81use egui_pop_core::strings::StrKey;
82use egui_pop_core::strings::{tr, tr_args};
83
84#[cfg(feature = "api")]
85pub use plugin::VideoPlugin;
86pub use plugin::{CMD_MUTE, CMD_PAUSE, CMD_PLAY, CMD_SEEK, CMD_TOGGLE, CMD_VOLUME, PLUGIN};
87pub use session::Videos;
88
89#[cfg(all(feature = "video", not(target_arch = "wasm32")))]
90pub use gst::{GStreamer, write_test_clip};
91
92use crate::strings as txt;
93use session::{Act, Session};
94
95/// The surface a video's picture opens by default, for key bindings
96/// (`videoFocus`).
97pub const SURFACE: &str = "video";
98/// What Left and Right move the position by.
99pub const SEEK_STEP: Duration = Duration::from_secs(5);
100/// What Up and Down change the volume by.
101pub const VOLUME_STEP: f32 = 0.05;
102/// How often the time is drawn again while playing.
103const TIME_REPAINT: Duration = Duration::from_millis(250);
104/// The shape of a video before its first picture.
105const DEFAULT_ASPECT: f32 = 16.0 / 9.0;
106
107/// What a backend is asked to open.
108#[derive(Clone, Debug)]
109pub struct VideoRequest {
110    /// The file, which exists and could be opened a moment ago.
111    pub path: PathBuf,
112    /// For the player's threads to ask for a repaint.
113    pub egui: egui::Context,
114    /// From 0 to 1.
115    pub volume: f32,
116}
117
118/// Where a player is.
119#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)]
120#[serde(rename_all = "snake_case")]
121pub enum VideoState {
122    /// Not ready to show anything yet.
123    #[default]
124    Loading,
125    Paused,
126    Playing,
127    /// At the end, not moving; Play starts again.
128    Ended,
129}
130
131/// What a player says of itself.
132#[derive(Clone, Debug, Default, PartialEq)]
133pub struct VideoStatus {
134    pub state: VideoState,
135    /// The position, when it can say.
136    pub position: Option<Duration>,
137    /// The length, when it can say.
138    pub duration: Option<Duration>,
139    /// Something the user should know while it plays on (no sound device, an
140    /// audio stream it cannot decode).
141    pub note: Option<String>,
142}
143
144/// A picture to show.
145#[derive(Clone, Debug)]
146pub struct VideoFrame {
147    pub image: Arc<ColorImage>,
148    /// The width over the height it is shown at, the file's pixel shape
149    /// included.
150    pub aspect: f32,
151}
152
153/// A video being played. A failure's text is shown in place of the picture
154/// (the viewer's error page, for the viewer's video).
155pub trait VideoPlayer: Send {
156    /// Takes what happened since the last call; an error ends the player.
157    fn poll(&mut self) -> Result<VideoStatus, String>;
158    /// The last frame not taken yet, the older ones forgotten.
159    fn frame(&mut self) -> Option<VideoFrame>;
160    fn play(&mut self) -> Result<(), String>;
161    fn pause(&mut self) -> Result<(), String>;
162    fn seek(&mut self, to: Duration) -> Result<(), String>;
163    /// From 0 to 1.
164    fn set_volume(&mut self, volume: f32);
165    /// Loops by itself from now on (or no longer), when it can: whether it
166    /// does. By default it cannot, and the widget seeks back to the start
167    /// when it ends.
168    fn set_looping(&mut self, on: bool) -> bool {
169        let _ = on;
170        false
171    }
172    /// How many times it went back to the start by itself.
173    fn loops(&self) -> u64 {
174        0
175    }
176}
177
178/// What opens videos ([`Video::backend`], and the viewer's).
179pub trait VideoBackend: Send + Sync {
180    /// Its name, in the widget's state.
181    fn name(&self) -> &str;
182    /// A player, paused at the start of the file, or why not. It stops when
183    /// dropped, without making the interface's thread wait.
184    fn open(&self, request: &VideoRequest) -> Result<Box<dyn VideoPlayer>, String>;
185}
186
187/// An RGBA picture from rows `stride` bytes apart, for a backend: `None` when
188/// the bytes do not hold it.
189pub fn rgba_image(data: &[u8], width: usize, height: usize, stride: usize) -> Option<ColorImage> {
190    let row = width.checked_mul(4)?;
191    if width == 0 || height == 0 || stride < row {
192        return None;
193    }
194    let mut rgba = Vec::with_capacity(row.checked_mul(height)?);
195    for y in 0..height {
196        let start = y.checked_mul(stride)?;
197        rgba.extend_from_slice(data.get(start..start.checked_add(row)?)?);
198    }
199    Some(ColorImage::from_rgba_unmultiplied([width, height], &rgba))
200}
201
202/// A time as a clock: `0:05`, `12:30`, `1:02:03`.
203pub fn clock(time: Duration) -> String {
204    let s = time.as_secs();
205    let (h, m, s) = (s / 3600, s / 60 % 60, s % 60);
206    if h > 0 {
207        format!("{h}:{m:02}:{s:02}")
208    } else {
209        format!("{m}:{s:02}")
210    }
211}
212
213/// The backend of this build: GStreamer with the `video` feature (not on the
214/// web), none otherwise.
215pub fn default_backend() -> Option<Arc<dyn VideoBackend>> {
216    #[cfg(all(feature = "video", not(target_arch = "wasm32")))]
217    {
218        Some(Arc::new(GStreamer::default()))
219    }
220    #[cfg(not(all(feature = "video", not(target_arch = "wasm32"))))]
221    {
222        None
223    }
224}
225
226/// Which controls a video draws under its picture.
227#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize)]
228#[serde(rename_all = "snake_case")]
229pub enum Controls {
230    /// The position on a row of its own; Play or Pause, the time and the
231    /// volume under it.
232    #[default]
233    Full,
234    /// Play or Pause, the position and the time on one row.
235    Compact,
236    /// The picture only: not a Tab stop, a click does nothing; commands and
237    /// [`Video::autoplay`] still play it.
238    None,
239}
240
241/// How the picture fills the widget.
242#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize)]
243#[serde(rename_all = "snake_case")]
244pub enum Fit {
245    /// All of it, with bars on the sides or above and below.
246    #[default]
247    Contain,
248    /// All the room, cropping what goes past it.
249    Cover,
250}
251
252/// Where the backend comes from.
253#[derive(Clone)]
254enum Backend {
255    Default,
256    Given(Option<Arc<dyn VideoBackend>>),
257}
258
259/// A local video file played in place. Its state (the player, the position,
260/// the volume) lives in the context, by [`id`](Self::id), from one pass to
261/// the next.
262#[must_use = "call `show` to draw it"]
263pub struct Video<'a> {
264    source: PathBuf,
265    id: Option<String>,
266    label: Option<String>,
267    controls: Controls,
268    autoplay: bool,
269    looping: bool,
270    muted: bool,
271    volume: f32,
272    fit: Fit,
273    poster: Option<SizedTexture>,
274    size: Option<Vec2>,
275    backend: Backend,
276    #[cfg_attr(
277        not(feature = "api"),
278        allow(
279            dead_code,
280            reason = "only the api feature's steps read the application"
281        )
282    )]
283    app: Option<&'a AppHandle>,
284    surface: &'a str,
285    take_focus: bool,
286}
287
288impl std::fmt::Debug for Video<'_> {
289    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
290        f.debug_struct("Video")
291            .field("source", &self.source)
292            .field("id", &self.id)
293            .field("controls", &self.controls)
294            .finish_non_exhaustive()
295    }
296}
297
298/// What a video did this pass.
299#[derive(Debug)]
300pub struct VideoOutput {
301    /// The picture (the placeholder without a player).
302    pub response: Response,
303    pub state: VideoState,
304    pub position: Duration,
305    pub duration: Option<Duration>,
306    /// From 0 to 1, whether muted or not.
307    pub volume: f32,
308    pub muted: bool,
309    /// Why it cannot play: the player failed to open or while it played.
310    pub error: Option<String>,
311    /// There is no player: the placeholder is drawn.
312    pub unavailable: bool,
313    /// **Open outside** was clicked on the placeholder (with an
314    /// [`app`](Video::app), the links service has been asked already).
315    pub open_outside: bool,
316}
317
318impl<'a> Video<'a> {
319    /// The file at `source`, with full controls, paused on its first picture.
320    pub fn new(source: impl AsRef<Path>) -> Self {
321        Self {
322            source: source.as_ref().to_path_buf(),
323            id: None,
324            label: None,
325            controls: Controls::Full,
326            autoplay: false,
327            looping: false,
328            muted: false,
329            volume: 1.0,
330            fit: Fit::Contain,
331            poster: None,
332            size: None,
333            backend: Backend::Default,
334            app: None,
335            surface: SURFACE,
336            take_focus: false,
337        }
338    }
339
340    /// Its name for agents (the `videos` collector, the `video.*` commands'
341    /// `video`) and its key in the context. Without one, the video is keyed by
342    /// its file and the `Ui` it is drawn in, and agents do not see it.
343    pub fn id(mut self, id: impl Into<String>) -> Self {
344        self.id = Some(id.into());
345        self
346    }
347
348    /// Its accessible name, instead of "Video: " and the file's name.
349    pub fn label(mut self, label: impl Into<String>) -> Self {
350        self.label = Some(label.into());
351        self
352    }
353
354    pub fn controls(mut self, controls: Controls) -> Self {
355        self.controls = controls;
356        self
357    }
358
359    /// Plays as soon as it opens, and again when drawn after being out of
360    /// view.
361    pub fn autoplay(mut self, on: bool) -> Self {
362        self.autoplay = on;
363        self
364    }
365
366    /// Starts again at the end; read every pass.
367    pub fn looping(mut self, on: bool) -> Self {
368        self.looping = on;
369        self
370    }
371
372    /// Starts without sound (read when it opens; the volume slider, or
373    /// `video.mute`, gives it back).
374    pub fn muted(mut self, on: bool) -> Self {
375        self.muted = on;
376        self
377    }
378
379    /// Its volume when it opens, from 0 to 1 (1 by default).
380    pub fn volume(mut self, volume: f32) -> Self {
381        self.volume = volume.clamp(0.0, 1.0);
382        self
383    }
384
385    pub fn fit(mut self, fit: Fit) -> Self {
386        self.fit = fit;
387        self
388    }
389
390    /// A picture shown until it first plays or moves, instead of its first
391    /// frame (a texture the application loaded: `&TextureHandle` converts).
392    pub fn poster(mut self, poster: impl Into<SizedTexture>) -> Self {
393        self.poster = Some(poster.into());
394        self
395    }
396
397    /// Its whole size, controls included. By default, the available width,
398    /// and the picture as high as its shape asks.
399    pub fn size(mut self, size: Vec2) -> Self {
400        self.size = Some(size);
401        self
402    }
403
404    /// What plays it (read when it opens), instead of this build's
405    /// ([`default_backend`]); `None` draws the placeholder.
406    pub fn backend(mut self, backend: Option<Arc<dyn VideoBackend>>) -> Self {
407        self.backend = Backend::Given(backend);
408        self
409    }
410
411    /// The application: **Open outside** goes through its links service.
412    #[cfg(feature = "api")]
413    pub fn app(mut self, app: &'a AppHandle) -> Self {
414        self.app = Some(app);
415        self
416    }
417
418    /// The focus surface around the picture, for key bindings ([`SURFACE`]
419    /// by default).
420    pub fn surface(mut self, surface: &'a str) -> Self {
421        self.surface = surface;
422        self
423    }
424
425    /// The picture takes the keyboard focus this pass.
426    pub fn take_focus(mut self, on: bool) -> Self {
427        self.take_focus = on;
428        self
429    }
430
431    /// Draws it.
432    pub fn show(self, ui: &mut Ui) -> VideoOutput {
433        let ctx = ui.ctx().clone();
434        let videos = Videos::of(&ctx);
435        videos.install_sweep();
436        let key = match &self.id {
437            Some(id) => egui::Id::unique(("egui_pop.video", id)),
438            None => ui.scope_id().with(("egui_pop.video", &self.source)),
439        };
440        let backend = match &self.backend {
441            Backend::Default => default_backend(),
442            Backend::Given(b) => b.clone(),
443        };
444        let fresh = || {
445            Session::new(
446                self.source.clone(),
447                backend.clone(),
448                self.volume,
449                self.muted,
450            )
451        };
452        let name = self.label.clone().unwrap_or_else(|| {
453            let file = self.source.file_name().map_or_else(
454                || self.source.display().to_string(),
455                |n| n.to_string_lossy().into_owned(),
456            );
457            tr_args(&ctx, &txt::VIEWER_VIDEO_PICTURE, &[("name", &file)])
458        });
459        let mut acts = Vec::new();
460        let registry = videos.registry();
461        let mut reg = lock(&registry);
462        let session = reg.session(key, fresh);
463        if session.source != self.source {
464            *session = fresh();
465        }
466        session.name.clone_from(&self.id);
467        session.controls = self.controls;
468        session.autoplay = self.autoplay;
469        session.seen(ctx.cumulative_pass_nr(), ctx.viewport_id());
470        session.update(&ctx, self.looping);
471        let (response, open_outside) = self.draw(ui, session, &name, &mut acts);
472        for act in acts {
473            session.act(&ctx, act);
474        }
475        if session.status.state == VideoState::Playing {
476            ctx.request_repaint_after(TIME_REPAINT);
477        }
478        let out = VideoOutput {
479            response,
480            state: session.status.state,
481            position: session.position,
482            duration: session.status.duration,
483            volume: session.volume,
484            muted: session.muted,
485            error: session.error.clone(),
486            unavailable: session.unavailable(),
487            open_outside,
488        };
489        if out.response.has_focus()
490            && let Some(name) = &self.id
491        {
492            reg.focused = Some(name.clone());
493        }
494        drop(reg);
495        #[cfg(feature = "api")]
496        if open_outside && let Some(app) = self.app {
497            let url = file_url(&self.source);
498            let _ = links::open(
499                app,
500                Request::new(&url)
501                    .how(How::Outside)
502                    .source(Source::Declared),
503            );
504        }
505        out
506    }
507
508    /// The picture and the controls; the user's asks into `acts`. Returns the
509    /// picture's response and whether Open outside was clicked.
510    fn draw(
511        &self,
512        ui: &mut Ui,
513        s: &mut Session,
514        name: &str,
515        acts: &mut Vec<Act>,
516    ) -> (Response, bool) {
517        let row = ui.spacing().interact_size.y + ui.spacing().item_spacing.y;
518        let playable = !s.unavailable() && s.error.is_none();
519        let controls = if playable {
520            match self.controls {
521                Controls::Full => 2.0 * row + if s.status.note.is_some() { row } else { 0.0 },
522                Controls::Compact => row,
523                Controls::None => 0.0,
524            }
525        } else {
526            0.0
527        };
528        let aspect = s.aspect_or(self.poster.map(|p| p.size.x / p.size.y.max(1.0)));
529        let width = self.size.map_or(ui.available_width(), |v| v.x).max(1.0);
530        let height = match self.size {
531            Some(v) => (v.y - controls).max(row),
532            None => width / aspect,
533        };
534        let size = vec2(width, height);
535        ui.vertical(|ui| {
536            ui.set_width(width);
537            if s.unavailable() {
538                return placeholder(ui, size, name);
539            }
540            let mut outside = false;
541            let picture = self.picture(ui, s, size, name, acts, &mut outside);
542            if !playable {
543                return (picture, outside);
544            }
545            if let Some(note) = &s.status.note
546                && self.controls == Controls::Full
547            {
548                ui.weak(note);
549            }
550            match self.controls {
551                Controls::Full => full_controls(ui, s, &picture, acts),
552                Controls::Compact => compact_controls(ui, s, &picture, acts),
553                Controls::None => {}
554            }
555            (picture, false)
556        })
557        .inner
558    }
559
560    /// The picture, its surface around it: its keys hold while it has the
561    /// focus.
562    fn picture(
563        &self,
564        ui: &mut Ui,
565        s: &mut Session,
566        size: Vec2,
567        name: &str,
568        acts: &mut Vec<Act>,
569        outside: &mut bool,
570    ) -> Response {
571        let ctx = ui.ctx().clone();
572        let interactive = self.controls != Controls::None && s.error.is_none();
573        egui_pop_core::focus::scope(ui, self.surface, &[], |ui| {
574            let sense = if interactive {
575                Sense::click()
576            } else {
577                Sense::hover()
578            };
579            let (rect, response) = ui.allocate_exact_size(size, sense);
580            egui_pop_core::a11y::name(&response, Role::Video, name);
581            let painter = ui.painter_at(rect);
582            painter.rect_filled(rect, 0.0, ui.visuals().extreme_bg_color);
583            if let Some(error) = s.error.clone() {
584                let title = tr(&ctx, &txt::VIEWER_VIDEO_FAILED);
585                *outside = notice(ui, rect, &title, Some(&error));
586                return response;
587            }
588            let poster = self.poster.filter(|_| !s.started);
589            let shown = match poster {
590                Some(p) => Some((p.id, p.size.x / p.size.y.max(1.0))),
591                None => s.texture.as_ref().map(|t| (t.id(), s.aspect)),
592            };
593            match shown {
594                Some((texture, aspect)) => {
595                    let (at, uv) = placed(rect, aspect, self.fit);
596                    painter.image(texture, at, uv, Color32::WHITE);
597                }
598                None if s.status.state == VideoState::Loading => {
599                    painter.text(
600                        rect.center(),
601                        Align2::CENTER_CENTER,
602                        tr(&ctx, &txt::VIEWER_VIDEO_LOADING),
603                        egui::TextStyle::Body.resolve(ui.style()),
604                        ui.visuals().weak_text_color(),
605                    );
606                }
607                None => {}
608            }
609            if !interactive {
610                return response;
611            }
612            if self.take_focus {
613                response.request_focus();
614            }
615            // egui clicks a focused widget on Space too: one toggle for it.
616            let clicked = response.clicked();
617            if clicked {
618                response.request_focus();
619                acts.push(Act::Toggle);
620            }
621            if response.has_focus() {
622                // The arrows are the picture's keys, not egui's way to move
623                // the focus to a neighbour.
624                ui.memory_mut(|m| {
625                    m.set_focus_lock_filter(
626                        response.id,
627                        egui::EventFilter {
628                            horizontal_arrows: true,
629                            vertical_arrows: true,
630                            ..Default::default()
631                        },
632                    );
633                });
634                egui_pop_core::focus::takes_keys(&ctx, response.id);
635                egui_pop_core::focus::own_ring(&ctx, response.id);
636                keys(ui, acts, clicked);
637                if egui_pop_core::focus::ring_shown(&ctx) {
638                    painter.rect_stroke(
639                        rect,
640                        0.0,
641                        ui.visuals().selection.stroke,
642                        egui::StrokeKind::Inside,
643                    );
644                }
645            }
646            response
647        })
648    }
649}
650
651/// The picture's keys, taken from the input (a binding of the application's
652/// on them has run and taken them first). Space is taken without a second
653/// toggle when egui made a click of it.
654fn keys(ui: &mut Ui, acts: &mut Vec<Act>, clicked: bool) {
655    ui.input_mut(|i| {
656        let none = Modifiers::NONE;
657        let mut toggled = clicked;
658        while i.consume_key(none, Key::Space) {
659            if !std::mem::replace(&mut toggled, false) {
660                acts.push(Act::Toggle);
661            }
662        }
663        while i.consume_key(none, Key::ArrowLeft) {
664            acts.push(Act::SeekBy(-SEEK_STEP.as_secs_f64()));
665        }
666        while i.consume_key(none, Key::ArrowRight) {
667            acts.push(Act::SeekBy(SEEK_STEP.as_secs_f64()));
668        }
669        while i.consume_key(none, Key::ArrowUp) {
670            acts.push(Act::VolumeBy(VOLUME_STEP));
671        }
672        while i.consume_key(none, Key::ArrowDown) {
673            acts.push(Act::VolumeBy(-VOLUME_STEP));
674        }
675    });
676}
677
678/// The rectangle a picture of that shape is painted in, and the part of it
679/// shown.
680fn placed(rect: Rect, aspect: f32, fit: Fit) -> (Rect, Rect) {
681    let whole = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0));
682    let aspect = if aspect > 0.0 { aspect } else { DEFAULT_ASPECT };
683    match fit {
684        Fit::Contain => (
685            Rect::from_center_size(rect.center(), fitted(rect.size(), aspect)),
686            whole,
687        ),
688        Fit::Cover => {
689            let room = rect.size();
690            if room.y <= 0.0 {
691                return (rect, whole);
692            }
693            let uv = if room.x / room.y > aspect {
694                // Wider than the picture: its top and bottom are cut.
695                let shown = (room.y / (room.x / aspect)).min(1.0);
696                Rect::from_min_max(pos2(0.0, 0.5 - shown / 2.0), pos2(1.0, 0.5 + shown / 2.0))
697            } else {
698                let shown = (room.x / (room.y * aspect)).min(1.0);
699                Rect::from_min_max(pos2(0.5 - shown / 2.0, 0.0), pos2(0.5 + shown / 2.0, 1.0))
700            };
701            (rect, uv)
702        }
703    }
704}
705
706/// The largest size of that shape within `room`.
707fn fitted(room: Vec2, aspect: f32) -> Vec2 {
708    let aspect = if aspect > 0.0 { aspect } else { DEFAULT_ASPECT };
709    if room.x / aspect <= room.y {
710        vec2(room.x, room.x / aspect)
711    } else {
712        vec2(room.y * aspect, room.y)
713    }
714}
715
716/// The picture's place without a player: why, and Open outside (whether it
717/// was clicked).
718fn placeholder(ui: &mut Ui, size: Vec2, name: &str) -> (Response, bool) {
719    let ctx = ui.ctx().clone();
720    let (rect, response) = ui.allocate_exact_size(size, Sense::hover());
721    egui_pop_core::a11y::name(&response, Role::Video, name);
722    ui.painter()
723        .rect_filled(rect, 0.0, ui.visuals().extreme_bg_color);
724    let clicked = notice(ui, rect, &tr(&ctx, &txt::VIDEO_NO_PLAYER), None);
725    (response, clicked)
726}
727
728/// A message centred in `rect`, already allocated, with Open outside: whether
729/// it was clicked.
730fn notice(ui: &mut Ui, rect: Rect, title: &str, detail: Option<&str>) -> bool {
731    let ctx = ui.ctx().clone();
732    let inner = rect.shrink(ui.spacing().item_spacing.x * 2.0);
733    let mut child = ui.new_child(
734        egui::UiBuilder::new()
735            .max_rect(inner)
736            .layout(egui::Layout::top_down(egui::Align::Center)),
737    );
738    child.set_clip_rect(inner.intersect(ui.clip_rect()));
739    // Centred as a block of two or three rows.
740    let rows = if detail.is_some() { 3.0 } else { 2.0 };
741    let block = rows * (child.spacing().interact_size.y + child.spacing().item_spacing.y);
742    child.add_space(((inner.height() - block) / 2.0).max(0.0));
743    child.label(title);
744    if let Some(detail) = detail {
745        child.weak(detail);
746    }
747    child.button(tr(&ctx, &LINKS_OPEN_OUTSIDE)).clicked()
748}
749
750/// Open outside, the links service's own words (the same catalogue key):
751/// without the application layer the output's `open_outside` says it was
752/// asked for, and the caller opens the file.
753#[cfg(not(feature = "api"))]
754const LINKS_OPEN_OUTSIDE: StrKey = StrKey::new("egui-pop-links-open-outside", "Open outside");
755
756/// Play or Pause, a toolbar button of the kit with its mark painted.
757fn play_button(ui: &mut Ui, playing: bool) -> Response {
758    let ctx = ui.ctx().clone();
759    let name = tr(
760        &ctx,
761        if playing {
762            &txt::VIEWER_VIDEO_PAUSE
763        } else {
764            &txt::VIEWER_VIDEO_PLAY
765        },
766    );
767    let side = ui.spacing().interact_size.y;
768    let (rect, response) = ui.allocate_exact_size(Vec2::splat(side), Sense::click());
769    if ui.is_rect_visible(rect) {
770        let kit = Kit::of(&ctx);
771        let look = &kit.toolbar_button;
772        let state = State::from_response(&response);
773        look.paint(
774            &KitCx {
775                painter: ui.painter(),
776                ppp: ctx.pixels_per_point(),
777            },
778            &Part {
779                rect,
780                room: rect,
781                state,
782                label: None,
783            },
784        );
785        let color = look.style(state).text;
786        let mark = Rect::from_center_size(rect.center(), Vec2::splat((side * 0.4).round()));
787        if playing {
788            let bar = mark.width() / 3.0;
789            for x in [mark.left(), mark.right() - bar] {
790                ui.painter().rect_filled(
791                    Rect::from_min_size(pos2(x, mark.top()), vec2(bar, mark.height())),
792                    0.0,
793                    color,
794                );
795            }
796        } else {
797            ui.painter().add(egui::Shape::convex_polygon(
798                vec![
799                    mark.left_top(),
800                    pos2(mark.right(), mark.center().y),
801                    mark.left_bottom(),
802                ],
803                color,
804                egui::Stroke::NONE,
805            ));
806        }
807    }
808    egui_pop_core::a11y::name(&response, Role::Button, &name);
809    response.on_hover_text(name)
810}
811
812/// The time, `0:12 / 1:00`.
813fn time(ui: &mut Ui, s: &Session) {
814    let ctx = ui.ctx().clone();
815    let total = s.status.duration.map_or_else(|| "-:--".to_string(), clock);
816    ui.monospace(tr_args(
817        &ctx,
818        &txt::VIEWER_VIDEO_TIME,
819        &[("elapsed", &clock(s.position)), ("total", &total)],
820    ));
821}
822
823/// The position's slider: it follows the video, except during a drag, whose
824/// end seeks. Without a length, there is nowhere to go yet.
825fn position(ui: &mut Ui, s: &mut Session, acts: &mut Vec<Act>) {
826    let ctx = ui.ctx().clone();
827    let name = tr(&ctx, &txt::VIEWER_VIDEO_POSITION);
828    let total = s.status.duration.map_or(0.0, |d| d.as_secs_f64());
829    let mut at = s.scrub.unwrap_or(s.position.as_secs_f64());
830    let out = ui
831        .add_enabled_ui(total > 0.0, |ui| {
832            Slider::new(&mut at, &name, 0.0..=total.max(1.0))
833                .hard(0.0..=total.max(1.0))
834                .step(1.0)
835                .coarse(10.0)
836                .precision(0)
837                .unit("s")
838                .show(ui)
839        })
840        .inner;
841    let mut scrub = None;
842    for change in &out.changes {
843        if change.done {
844            acts.push(Act::SeekTo(change.to));
845            scrub = None;
846        } else {
847            scrub = Some(change.to);
848        }
849    }
850    // Escape during a drag puts it back without a change.
851    s.scrub = scrub.or(if out.response.dragged() {
852        s.scrub
853    } else {
854        None
855    });
856}
857
858/// A click on Play or Pause: by the pointer the keys stay with the picture, by
859/// the keyboard with the button.
860fn toggled(button: &Response, picture: &Response, acts: &mut Vec<Act>) {
861    if button.clicked() {
862        acts.push(Act::Toggle);
863        if button.clicked_by(egui::PointerButton::Primary) && !button.has_focus() {
864            picture.request_focus();
865        }
866    }
867}
868
869fn full_controls(ui: &mut Ui, s: &mut Session, picture: &Response, acts: &mut Vec<Act>) {
870    let ctx = ui.ctx().clone();
871    position(ui, s, acts);
872    ui.horizontal(|ui| {
873        let button = play_button(ui, s.status.state == VideoState::Playing);
874        toggled(&button, picture, acts);
875        time(ui, s);
876        let mut percent = f64::from(s.audible_volume()) * 100.0;
877        let out = Slider::new(
878            &mut percent,
879            &tr(&ctx, &txt::VIEWER_VIDEO_VOLUME),
880            0.0..=100.0,
881        )
882        .hard(0.0..=100.0)
883        .step(5.0)
884        .precision(0)
885        .unit("%")
886        .show(ui);
887        if !out.changes.is_empty() {
888            acts.push(Act::Volume((percent / 100.0) as f32));
889        }
890    });
891}
892
893fn compact_controls(ui: &mut Ui, s: &mut Session, picture: &Response, acts: &mut Vec<Act>) {
894    ui.horizontal(|ui| {
895        let button = play_button(ui, s.status.state == VideoState::Playing);
896        toggled(&button, picture, acts);
897        // The time at the end, the position in what is left.
898        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
899            time(ui, s);
900            position(ui, s, acts);
901        });
902    });
903}
904
905/// A `file:` URL for a path.
906#[cfg(feature = "api")]
907fn file_url(path: &Path) -> String {
908    let path = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
909    format!("file://{}", path.display())
910}
911
912#[cfg(test)]
913mod tests {
914    use super::*;
915
916    #[test]
917    fn a_clock_grows_its_hours_only_when_it_has_them() {
918        assert_eq!(clock(Duration::ZERO), "0:00");
919        assert_eq!(clock(Duration::from_millis(5900)), "0:05");
920        assert_eq!(clock(Duration::from_secs(750)), "12:30");
921        assert_eq!(clock(Duration::from_secs(3723)), "1:02:03");
922    }
923
924    #[test]
925    fn a_picture_drops_the_padding_of_its_rows() {
926        let red = [255, 0, 0, 255];
927        let mut data = Vec::new();
928        for _ in 0..2 {
929            data.extend_from_slice(&red);
930            data.extend_from_slice(&red);
931            data.extend_from_slice(&[9, 9, 9, 9]);
932        }
933        let image = rgba_image(&data, 2, 2, 12).unwrap();
934        assert_eq!(image.size, [2, 2]);
935        assert!(image.pixels.iter().all(|p| *p == Color32::RED));
936    }
937
938    #[test]
939    fn bytes_that_do_not_hold_a_picture_give_none() {
940        assert!(rgba_image(&[0; 4], 2, 2, 8).is_none(), "too short");
941        assert!(rgba_image(&[0; 64], 2, 2, 4).is_none(), "rows overlap");
942        assert!(rgba_image(&[0; 64], 0, 2, 8).is_none(), "no width");
943        assert!(rgba_image(&[0; 64], usize::MAX, 2, 8).is_none(), "overflow");
944    }
945
946    #[test]
947    fn a_picture_fits_its_room_keeping_its_shape() {
948        assert_eq!(fitted(vec2(200.0, 200.0), 2.0), vec2(200.0, 100.0));
949        assert_eq!(fitted(vec2(400.0, 100.0), 2.0), vec2(200.0, 100.0));
950        assert_eq!(fitted(vec2(160.0, 900.0), 0.0), vec2(160.0, 90.0));
951    }
952
953    #[test]
954    fn a_covering_picture_fills_its_room_and_crops_the_rest() {
955        let room = Rect::from_min_size(pos2(0.0, 0.0), vec2(200.0, 100.0));
956        // A square picture in a wide room: its middle half, top to bottom.
957        let (at, uv) = placed(room, 1.0, Fit::Cover);
958        assert_eq!(at, room);
959        assert_eq!((uv.min.y, uv.max.y), (0.25, 0.75));
960        assert_eq!((uv.min.x, uv.max.x), (0.0, 1.0));
961        // A wide picture in a square room: its middle half, side to side.
962        let square = Rect::from_min_size(pos2(0.0, 0.0), vec2(100.0, 100.0));
963        let (_, uv) = placed(square, 2.0, Fit::Cover);
964        assert_eq!((uv.min.x, uv.max.x), (0.25, 0.75));
965        // Contained, all of it, in the middle.
966        let (at, uv) = placed(room, 1.0, Fit::Contain);
967        assert_eq!(
968            at,
969            Rect::from_center_size(room.center(), vec2(100.0, 100.0))
970        );
971        assert_eq!(uv, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)));
972    }
973}