1use 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
31pub const VIDEO_SURFACE: &str = "viewerVideo";
33pub const VIDEO_CONTEXT: &str = "viewerVideo";
35pub const VIDEO_ID: &str = "egui_pop.viewer";
38
39struct Page {
41 target: String,
42 path: PathBuf,
43 egui: egui::Context,
45 focus: bool,
47 stopped_told: bool,
49}
50
51pub(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 pub fn plays_video(&self) -> bool {
75 lock(&self.video).backend.is_some()
76 }
77
78 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 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 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 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 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 pub fn video_toggle(&self, app: &AppHandle) -> Result<Json, String> {
173 self.on_video(app, |v| v.toggle(Some(VIDEO_ID)))
174 }
175
176 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 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 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 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 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 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 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
253pub(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 lock(&v.video).volume = out.volume;
281 }
282 out.error.map(|e| (target, e))
283}