Skip to main content

egui_pop_views/viewer/
video.rs

1//! The viewer's video page (ADR 0017): a local video file played in the panel
2//! by the [`Video`](crate::video::Video) widget, with its full controls,
3//! under the id [`VIDEO_ID`].
4//!
5//! The backend is the build's (GStreamer with the `video` feature), none
6//! without it: a local video then opens outside, as any local file (the policy
7//! asks [`Viewer::plays_video`]).
8//!
9//! - **Stopping**: leaving the page forgets the widget, whose player stops. A
10//!   panel no longer drawn (closed, or a tab behind another) stops the player
11//!   too and keeps the position: showing it again opens the file there,
12//!   paused.
13//! - **Keys**: the picture is a Tab stop, its keys are the viewer's commands,
14//!   bound on its own surface ([`VIDEO_SURFACE`]): Space plays or pauses, Left
15//!   and Right move by [`SEEK_STEP`](crate::video::SEEK_STEP), Up and Down
16//!   change the volume by [`VOLUME_STEP`](crate::video::VOLUME_STEP).
17//! - **Failures**: the player's failure, opening or playing, ends on the
18//!   viewer's error page.
19
20use std::path::PathBuf;
21use std::sync::Arc;
22
23use egui::Ui;
24use egui_pop_api::AppHandle;
25use egui_pop_core::lock;
26use serde_json::{Value as Json, json};
27
28use super::{Failure, PLUGIN, Status, Viewer};
29use crate::video::{Controls, VideoBackend, Videos};
30
31/// The surface the picture's keys are bound on (`viewerVideoFocus`).
32pub const VIDEO_SURFACE: &str = "viewerVideo";
33/// The context key saying a video page is shown.
34pub const VIDEO_CONTEXT: &str = "viewerVideo";
35/// The id of the viewer's video, for the `video.*` commands and the `videos`
36/// collector.
37pub const VIDEO_ID: &str = "egui_pop.viewer";
38
39/// The page shown.
40struct Page {
41    target: String,
42    path: PathBuf,
43    /// The context its widget lives in.
44    egui: egui::Context,
45    /// The picture takes the focus when next drawn.
46    focus: bool,
47    /// The journal was told its player stopped out of view.
48    stopped_told: bool,
49}
50
51/// The viewer's video state: the backend, the volume for the session, the page.
52pub(super) struct Video {
53    backend: Option<Arc<dyn VideoBackend>>,
54    volume: f32,
55    page: Option<Page>,
56}
57
58impl Video {
59    pub(super) fn new(backend: Option<Arc<dyn VideoBackend>>) -> Self {
60        Self {
61            backend,
62            volume: 1.0,
63            page: None,
64        }
65    }
66
67    pub(super) fn set_backend(&mut self, backend: Option<Arc<dyn VideoBackend>>) {
68        self.backend = backend;
69    }
70}
71
72impl Viewer {
73    /// Whether local video files open here: a backend is there.
74    pub fn plays_video(&self) -> bool {
75        lock(&self.video).backend.is_some()
76    }
77
78    /// Opens the video page, or the error page saying why not.
79    pub(super) fn open_video(&self, app: &AppHandle, target: &str, path: &str) {
80        let path = PathBuf::from(path);
81        if let Err(e) = std::fs::File::open(&path) {
82            let failure = if e.kind() == std::io::ErrorKind::NotFound {
83                Failure::NotFound
84            } else {
85                Failure::Playback
86            };
87            return self.fail(app, target, failure, &e.to_string());
88        }
89        if !self.plays_video() {
90            return self.fail(
91                app,
92                target,
93                Failure::Playback,
94                "this application has no video player",
95            );
96        }
97        // A new page: a new player, from the start.
98        Videos::of(&app.egui()).forget(VIDEO_ID);
99        lock(&self.video).page = Some(Page {
100            target: target.to_string(),
101            path: path.clone(),
102            egui: app.egui(),
103            focus: true,
104            stopped_told: false,
105        });
106        app.set_context(VIDEO_CONTEXT, "true");
107        self.show_video_page(app, target, path);
108    }
109
110    /// Leaves the video page: the player stops, what it showed goes.
111    pub(super) fn stop_video(&self, app: &AppHandle) {
112        let page = lock(&self.video).page.take();
113        if page.is_some() {
114            Videos::of(&app.egui()).forget(VIDEO_ID);
115            app.set_context(VIDEO_CONTEXT, "false");
116        }
117    }
118
119    pub(super) fn video_failed(&self, app: &AppHandle, target: &str, detail: &str) {
120        self.stop_video(app);
121        self.fail(app, target, Failure::Playback, detail);
122    }
123
124    /// Once per pass of the application: tells the journal when the page's
125    /// player stopped out of view (`viewer.video_stopped`).
126    pub(super) fn video_pass(&self, app: &AppHandle) {
127        let stopped = {
128            let mut v = lock(&self.video);
129            let Some(page) = v.page.as_mut() else {
130                return;
131            };
132            let now = Videos::of(&page.egui)
133                .state(VIDEO_ID)
134                .is_some_and(|s| s["stopped"] == true);
135            let tell = now && !page.stopped_told;
136            page.stopped_told = now;
137            tell
138        };
139        if stopped {
140            app.publish(PLUGIN.as_str(), None, "viewer.video_stopped", json!({}));
141        }
142    }
143
144    /// Runs `act` on the page's video; a player that fails there ends on the
145    /// error page.
146    fn on_video(
147        &self,
148        app: &AppHandle,
149        act: impl FnOnce(&Videos) -> Result<Json, String>,
150    ) -> Result<Json, String> {
151        let target = lock(&self.video)
152            .page
153            .as_ref()
154            .map(|p| p.target.clone())
155            .ok_or("no video is open")?;
156        let videos = Videos::of(&app.egui());
157        match act(&videos) {
158            Ok(_) => Ok(self.video_state()),
159            Err(e) => {
160                let failed = videos
161                    .state(VIDEO_ID)
162                    .and_then(|s| s["error"].as_str().map(str::to_string));
163                if let Some(detail) = failed {
164                    self.video_failed(app, &target, &detail);
165                }
166                Err(e)
167            }
168        }
169    }
170
171    /// Plays or pauses; from the end, plays from the start.
172    pub fn video_toggle(&self, app: &AppHandle) -> Result<Json, String> {
173        self.on_video(app, |v| v.toggle(Some(VIDEO_ID)))
174    }
175
176    /// Moves to a position, kept within the video.
177    pub fn video_seek_to(&self, app: &AppHandle, seconds: f64) -> Result<Json, String> {
178        self.on_video(app, |v| v.seek_to(Some(VIDEO_ID), seconds))
179    }
180
181    /// Moves the position forward, or back with a negative number.
182    pub fn video_seek_by(&self, app: &AppHandle, seconds: f64) -> Result<Json, String> {
183        self.on_video(app, |v| v.seek_by(Some(VIDEO_ID), seconds))
184    }
185
186    /// Sets the volume, from 0 to 1, kept for the session's next videos.
187    pub fn video_volume(&self, app: &AppHandle, volume: f32) -> Result<Json, String> {
188        let volume = volume.clamp(0.0, 1.0);
189        lock(&self.video).volume = volume;
190        self.on_video(app, |v| v.set_volume(Some(VIDEO_ID), volume))
191    }
192
193    /// Changes the volume by an amount.
194    pub fn video_volume_by(&self, app: &AppHandle, by: f32) -> Result<Json, String> {
195        let volume = lock(&self.video).volume;
196        self.video_volume(app, volume + by)
197    }
198
199    /// What the page holds, for `viewer.state`: null without a video page.
200    pub(super) fn video_state(&self) -> Json {
201        let v = lock(&self.video);
202        let Some(page) = v.page.as_ref() else {
203            return Json::Null;
204        };
205        let backend = v.backend.as_ref().map(|b| b.name().to_string());
206        // In hundredths, not the float's long tail.
207        let volume = f64::from((v.volume * 100.0).round()) / 100.0;
208        match Videos::of(&page.egui).state(VIDEO_ID) {
209            Some(mut s) => {
210                s["volume"] = json!(volume);
211                s
212            }
213            // Not drawn yet.
214            None => json!({
215                "video": VIDEO_ID,
216                "source": page.path.display().to_string(),
217                "backend": backend,
218                "state": "loading",
219                "stopped": false,
220                "position_ms": 0,
221                "duration_ms": null,
222                "volume": volume,
223                "size": null,
224                "note": null,
225            }),
226        }
227    }
228
229    fn show_video_page(&self, app: &AppHandle, target: &str, path: PathBuf) {
230        let page = Arc::new(super::Page {
231            target: target.to_string(),
232            content: super::Content::Video(path),
233            html: false,
234            dropped: Vec::new(),
235        });
236        {
237            let mut i = lock(&self.inner);
238            i.status = Status::Shown(page);
239            i.restore = None;
240            i.scroll_to = None;
241            i.find.matches.clear();
242            i.find.at = 0;
243        }
244        app.publish(
245            PLUGIN.as_str(),
246            None,
247            "viewer.shown",
248            json!({ "target": target, "kind": "video" }),
249        );
250    }
251}
252
253/// Draws the page: the widget with its full controls. Its failure, with the
254/// page's target, for the error page.
255pub(super) fn draw(ui: &mut Ui, app: &AppHandle, v: &Viewer) -> Option<(String, String)> {
256    let (target, path, backend, volume, focus) = {
257        let mut video = lock(&v.video);
258        let (backend, volume) = (video.backend.clone(), video.volume);
259        let page = video.page.as_mut()?;
260        (
261            page.target.clone(),
262            page.path.clone(),
263            backend,
264            volume,
265            std::mem::take(&mut page.focus),
266        )
267    };
268    let out = crate::video::Video::new(&path)
269        .id(VIDEO_ID)
270        .surface(VIDEO_SURFACE)
271        .controls(Controls::Full)
272        .backend(backend)
273        .volume(volume)
274        .size(ui.available_size())
275        .take_focus(focus)
276        .app(app)
277        .show(ui);
278    if !out.muted {
279        // The slider's volume is the session's.
280        lock(&v.video).volume = out.volume;
281    }
282    out.error.map(|e| (target, e))
283}