1mod embed;
75#[cfg(feature = "html")]
76mod html;
77mod page;
78mod video;
79mod view;
80#[cfg(all(feature = "webview", target_os = "linux"))]
81mod wry_view;
82
83use std::collections::{BTreeMap, BTreeSet};
84use std::sync::{Arc, Mutex};
85
86use egui_commonmark::CommonMarkCache;
87use egui_pop_api::links::{self, How, Inside, OpenCall, Policy, Request, Source, Target};
88use egui_pop_api::services::ServiceToken;
89use egui_pop_api::{AppHandle, Ctx, Plugin, PluginError};
90use egui_pop_core::debug::FnCollector;
91use egui_pop_core::lock;
92use egui_pop_model::commands::{CommandSpec, Origin};
93use egui_pop_model::ids::{CommandId, PanelId, PluginId, SettingId};
94use egui_pop_model::keymap::BindOptions;
95use egui_pop_model::links::VIDEOS;
96use egui_pop_model::panels::{Area, PanelSpec};
97use egui_pop_model::values::{Change, Descriptor, Set, Value};
98use serde_json::{Value as Json, json};
99
100#[allow(
101 deprecated,
102 reason = "DEFAULT_REFERRER stays re-exported, deprecated, until its removal"
103)]
104pub use embed::DEFAULT_REFERRER;
105pub use embed::{
106 EmbedBackend, EmbedRequest, Embedded, MIN_PLAYER, PUMP, Placement, WEB_VIEW_LISTENER,
107 WEB_VIEW_PREFIX, embed_url, fits_player, referrer_for,
108};
109pub use page::{Block, ImageRef, Markdown, has_scheme, resolve, slug};
110pub use video::{VIDEO_CONTEXT, VIDEO_ID, VIDEO_SURFACE};
111#[cfg(all(feature = "video", not(target_arch = "wasm32")))]
114pub use crate::video::{GStreamer, write_test_clip};
115pub use crate::video::{
116 SEEK_STEP, VOLUME_STEP, VideoBackend, VideoFrame, VideoPlayer, VideoRequest, VideoState,
117 VideoStatus, clock, rgba_image,
118};
119#[cfg(all(feature = "webview", target_os = "linux"))]
120pub use wry_view::Wry;
121
122pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.viewer");
124pub const PANEL: PanelId = PanelId::from_static("egui_pop.viewer");
126pub const VIEWER: ServiceToken<Viewer> = ServiceToken::new("app.viewer");
128pub const SURFACE: &str = "viewer";
130pub const SETTING_IMAGE_HOSTS: SettingId = SettingId::from_static("viewer.image_hosts");
132
133pub const CMD_BACK: CommandId = CommandId::from_static("viewer.back");
134pub const CMD_FORWARD: CommandId = CommandId::from_static("viewer.forward");
135pub const CMD_RELOAD: CommandId = CommandId::from_static("viewer.reload");
136pub const CMD_FIND: CommandId = CommandId::from_static("viewer.find");
137pub const CMD_FIND_NEXT: CommandId = CommandId::from_static("viewer.find_next");
138pub const CMD_FIND_PREVIOUS: CommandId = CommandId::from_static("viewer.find_previous");
139pub const CMD_ZOOM_IN: CommandId = CommandId::from_static("viewer.zoom_in");
140pub const CMD_ZOOM_OUT: CommandId = CommandId::from_static("viewer.zoom_out");
141pub const CMD_ZOOM_RESET: CommandId = CommandId::from_static("viewer.zoom_reset");
142pub const CMD_OPEN_OUTSIDE: CommandId = CommandId::from_static("viewer.open_outside");
143pub const CMD_COPY_LINK: CommandId = CommandId::from_static("viewer.copy_link");
144pub const CMD_LOAD_IMAGES: CommandId = CommandId::from_static("viewer.load_images");
145pub const CMD_STATE: CommandId = CommandId::from_static("viewer.state");
146pub const CMD_VIDEO_TOGGLE: CommandId = CommandId::from_static("viewer.video_toggle");
147pub const CMD_VIDEO_BACK: CommandId = CommandId::from_static("viewer.video_back");
148pub const CMD_VIDEO_AHEAD: CommandId = CommandId::from_static("viewer.video_ahead");
149pub const CMD_VIDEO_LOUDER: CommandId = CommandId::from_static("viewer.video_louder");
150pub const CMD_VIDEO_QUIETER: CommandId = CommandId::from_static("viewer.video_quieter");
151pub const CMD_VIDEO_SEEK: CommandId = CommandId::from_static("viewer.video_seek");
152pub const CMD_VIDEO_VOLUME: CommandId = CommandId::from_static("viewer.video_volume");
153
154pub const MAX_BYTES: usize = 16 * 1024 * 1024;
156pub const ZOOM_STEPS: &[f32] = &[
158 0.5, 0.67, 0.75, 0.8, 0.9, 1.0, 1.1, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0,
159];
160
161#[derive(Clone, Default)]
167pub struct Docs {
168 files: BTreeMap<String, Arc<[u8]>>,
169}
170
171impl std::fmt::Debug for Docs {
172 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173 f.debug_list().entries(self.files.keys()).finish()
174 }
175}
176
177impl Docs {
178 pub fn new() -> Self {
179 Self::default()
180 }
181
182 pub fn page(self, path: &str, markdown: &str) -> Self {
185 let path = path.trim_matches('/');
186 let path = if std::path::Path::new(path).extension().is_some() {
187 path.to_string()
188 } else {
189 format!("{path}.md")
190 };
191 self.file(&path, markdown.as_bytes().to_vec())
192 }
193
194 pub fn file(mut self, path: &str, bytes: impl Into<Arc<[u8]>>) -> Self {
196 self.files
197 .insert(path.trim_matches('/').to_string(), bytes.into());
198 self
199 }
200
201 pub fn get(&self, page: &str) -> Option<(String, Arc<[u8]>)> {
203 let p = page.trim_start_matches('/');
204 let folder = p.trim_end_matches('/');
205 let candidates = if folder.is_empty() {
206 vec!["index.md".to_string(), "index.html".to_string()]
207 } else if p.ends_with('/') {
208 vec![format!("{folder}/index.md"), format!("{folder}/index.html")]
209 } else {
210 vec![
211 p.to_string(),
212 format!("{p}.md"),
213 format!("{p}.html"),
214 format!("{p}/index.md"),
215 format!("{p}/index.html"),
216 ]
217 };
218 candidates
219 .into_iter()
220 .find_map(|c| self.files.get(&c).map(|b| (c.clone(), b.clone())))
221 }
222
223 pub fn pages(&self) -> Vec<String> {
226 let mut out = Vec::new();
227 for path in self.files.keys() {
228 out.push(path.clone());
229 if let Some(page) = path
230 .strip_suffix(".md")
231 .or_else(|| path.strip_suffix(".html"))
232 {
233 out.push(page.to_string());
234 if let Some(folder) = page.strip_suffix("index") {
235 out.push(folder.to_string());
236 out.push(folder.trim_end_matches('/').to_string());
237 }
238 }
239 }
240 out.sort();
241 out.dedup();
242 out
243 }
244}
245
246pub type Fetched = Result<Vec<u8>, String>;
248
249pub trait Fetch: Send + Sync {
253 fn fetch(&self, url: &str, done: Box<dyn FnOnce(Fetched) + Send>);
254}
255
256#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
258#[serde(rename_all = "snake_case")]
259pub enum Failure {
260 NotFound,
261 NoConnection,
262 TooLarge,
263 Unsupported,
264 Playback,
266}
267
268impl Failure {
269 fn title(self) -> &'static egui_pop_core::strings::StrKey {
270 use crate::strings as s;
271 match self {
272 Failure::NotFound => &s::VIEWER_NOT_FOUND,
273 Failure::NoConnection => &s::VIEWER_NO_CONNECTION,
274 Failure::TooLarge => &s::VIEWER_TOO_LARGE,
275 Failure::Unsupported => &s::VIEWER_UNSUPPORTED,
276 Failure::Playback => &s::VIEWER_VIDEO_FAILED,
277 }
278 }
279}
280
281#[derive(Debug)]
283pub enum Content {
284 Markdown(Markdown),
285 Image(String),
287 Video(std::path::PathBuf),
289 YouTube(String),
291}
292
293#[derive(Debug)]
295pub struct Page {
296 pub target: String,
298 pub content: Content,
299 pub html: bool,
301 pub dropped: Vec<String>,
304}
305
306impl Page {
307 fn kind(&self) -> &'static str {
308 match self.content {
309 Content::Markdown(_) if self.html => "html",
310 Content::Markdown(_) => "markdown",
311 Content::Image(_) => "image",
312 Content::Video(_) => "video",
313 Content::YouTube(_) => "youtube",
314 }
315 }
316}
317
318#[derive(Clone, Debug)]
320pub enum Status {
321 Empty,
322 Loading(String),
323 Shown(Arc<Page>),
324 Failed {
325 target: String,
326 failure: Failure,
327 detail: String,
328 },
329}
330
331#[derive(Clone, Debug, PartialEq, Eq)]
333enum Image {
334 Ready,
335 Loading,
336 Blocked(String),
338 Failed(String),
339}
340
341#[derive(Clone, Debug)]
342struct Entry {
343 target: String,
344 scroll: f32,
345}
346
347#[derive(Debug, Default)]
348struct Find {
349 open: bool,
350 focus: bool,
352 query: String,
353 matches: Vec<usize>,
355 at: usize,
356}
357
358#[derive(Debug)]
359struct Inner {
360 back: Vec<Entry>,
361 forward: Vec<Entry>,
362 current: Option<Entry>,
363 status: Status,
364 generation: u64,
366 find: Find,
367 zoom: f32,
368 scroll_to: Option<usize>,
370 restore: Option<f32>,
372 scroll: f32,
374 images: BTreeMap<String, Image>,
375 allowed: BTreeSet<String>,
376 address: String,
378}
379
380impl Default for Inner {
381 fn default() -> Self {
382 Self {
383 back: Vec::new(),
384 forward: Vec::new(),
385 current: None,
386 status: Status::Empty,
387 generation: 0,
388 find: Find::default(),
389 zoom: 1.0,
390 scroll_to: None,
391 restore: None,
392 scroll: 0.0,
393 images: BTreeMap::new(),
394 allowed: BTreeSet::new(),
395 address: String::new(),
396 }
397 }
398}
399
400enum Arrival {
401 Page { target: String, generation: u64 },
402 Image(String),
403}
404
405type Inbox = Arc<Mutex<Vec<(Arrival, Fetched)>>>;
406
407pub struct Viewer {
410 docs: Docs,
411 fetch: Option<Arc<dyn Fetch>>,
412 inner: Mutex<Inner>,
413 inbox: Inbox,
414 cache: Mutex<CommonMarkCache>,
415 video: Mutex<video::Video>,
416 embed: Mutex<embed::Embed>,
417}
418
419impl std::fmt::Debug for Viewer {
420 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
421 f.debug_struct("Viewer")
422 .field("docs", &self.docs)
423 .field("fetch", &self.fetch.is_some())
424 .field("inner", &lock(&self.inner))
425 .finish_non_exhaustive()
426 }
427}
428
429fn split_fragment(target: &str) -> (&str, Option<&str>) {
430 match target.split_once('#') {
431 Some((base, f)) => (base, Some(f)),
432 None => (target, None),
433 }
434}
435
436fn extension(path: &str) -> String {
437 let name = path.rsplit(['/', '\\']).next().unwrap_or_default();
438 let name = name.split(['?', '#']).next().unwrap_or_default();
439 match name.rsplit_once('.') {
440 Some((_, ext)) => ext.to_ascii_lowercase(),
441 None => String::new(),
442 }
443}
444
445fn host_of(url: &str) -> Option<String> {
446 Target::parse(url)
447 .ok()
448 .and_then(|t| t.host_ascii().map(str::to_ascii_lowercase))
449}
450
451pub fn parse_hosts(text: &str) -> BTreeSet<String> {
453 text.split([',', ' ', '\n'])
454 .map(|h| h.trim().to_ascii_lowercase())
455 .filter(|h| !h.is_empty())
456 .collect()
457}
458
459impl Viewer {
460 pub fn new(docs: Docs, fetch: Option<Arc<dyn Fetch>>) -> Self {
461 Self {
462 docs,
463 fetch,
464 inner: Mutex::new(Inner::default()),
465 inbox: Arc::default(),
466 cache: Mutex::new(CommonMarkCache::default()),
467 video: Mutex::new(video::Video::new(crate::video::default_backend())),
468 embed: Mutex::new(embed::Embed::new(embed::default_backend())),
469 }
470 }
471
472 pub fn set_video_backend(&self, backend: Option<Arc<dyn VideoBackend>>) {
474 lock(&self.video).set_backend(backend);
475 }
476
477 pub fn docs(&self) -> &Docs {
479 &self.docs
480 }
481
482 pub fn target(&self) -> Option<String> {
484 lock(&self.inner).current.as_ref().map(|e| e.target.clone())
485 }
486
487 pub fn status(&self) -> Status {
489 lock(&self.inner).status.clone()
490 }
491
492 pub fn zoom(&self) -> f32 {
494 lock(&self.inner).zoom
495 }
496
497 pub fn navigate(&self, app: &AppHandle, target: &str, push: bool) {
500 let (base, fragment) = split_fragment(target);
501 let same = {
502 let mut i = lock(&self.inner);
503 if push {
504 if let Some(mut cur) = i.current.take() {
505 cur.scroll = i.scroll;
506 i.back.push(cur);
507 }
508 i.forward.clear();
509 }
510 i.current = Some(Entry {
511 target: target.to_string(),
512 scroll: 0.0,
513 });
514 i.address = target.to_string();
515 match &i.status {
516 Status::Shown(p) if p.target == base && push => Some(p.clone()),
517 _ => None,
518 }
519 };
520 match same {
521 Some(page) => self.scroll_to_anchor(&page, fragment),
523 None => self.load(app, base, fragment),
524 }
525 app.set_panel_visible(&PANEL, true);
526 app.egui().request_repaint();
527 }
528
529 fn scroll_to_anchor(&self, page: &Page, fragment: Option<&str>) {
530 if let (Content::Markdown(md), Some(f)) = (&page.content, fragment) {
531 lock(&self.inner).scroll_to = md.anchor(f);
532 }
533 }
534
535 fn fail(&self, app: &AppHandle, target: &str, failure: Failure, detail: &str) {
536 lock(&self.inner).status = Status::Failed {
537 target: target.to_string(),
538 failure,
539 detail: detail.to_string(),
540 };
541 app.publish(
542 PLUGIN.as_str(),
543 None,
544 "viewer.failed",
545 json!({ "target": target, "failure": failure, "detail": detail }),
546 );
547 }
548
549 fn load(&self, app: &AppHandle, target: &str, fragment: Option<&str>) {
550 self.stop_video(app);
552 self.stop_embed(app, egui_pop_api::bus::Reason::Command);
553 let generation = {
554 let mut i = lock(&self.inner);
555 i.generation += 1;
556 i.status = Status::Loading(target.to_string());
557 i.scroll_to = None;
558 i.images.retain(|_, s| !matches!(s, Image::Blocked(_)));
560 i.generation
561 };
562 let parsed = Target::parse(target).ok();
563 let scheme = parsed.as_ref().map(|t| t.scheme().to_string());
564 match scheme.as_deref() {
565 Some("docs") => {
566 let page = parsed
567 .as_ref()
568 .and_then(Target::doc_page)
569 .unwrap_or_default();
570 match self.docs.get(&page) {
571 Some((path, bytes)) => {
572 self.finish(app, target, &path, bytes.to_vec(), fragment);
573 }
574 None => self.fail(
575 app,
576 target,
577 Failure::NotFound,
578 &format!("no page `{page}` among the application's pages"),
579 ),
580 }
581 }
582 Some("file") => {
583 let path = parsed
584 .as_ref()
585 .and_then(Target::local_path)
586 .unwrap_or_default();
587 if self.plays_video() && VIDEOS.contains(&extension(&path).as_str()) {
588 return self.open_video(app, target, &path);
589 }
590 match read_file(&path) {
591 Ok(bytes) => self.finish(app, target, &path, bytes, fragment),
592 Err((failure, e)) => self.fail(app, target, failure, &e),
593 }
594 }
595 Some("https")
596 if self.plays_web_video()
597 && parsed.as_ref().and_then(Target::youtube_id).is_some() =>
598 {
599 let id = parsed
600 .as_ref()
601 .and_then(Target::youtube_id)
602 .unwrap_or_default();
603 self.open_embed(app, target, id);
604 }
605 Some("http" | "https") => match &self.fetch {
606 Some(fetch) => {
607 let inbox = self.inbox.clone();
608 let ctx = app.egui();
609 let t = target.to_string();
612 fetch.fetch(
613 target,
614 Box::new(move |r| {
615 lock(&inbox).push((
616 Arrival::Page {
617 target: t,
618 generation,
619 },
620 r,
621 ));
622 ctx.request_repaint();
623 }),
624 );
625 }
626 None => self.fail(
627 app,
628 target,
629 Failure::NoConnection,
630 "this application does not load pages from the network",
631 ),
632 },
633 _ => self.fail(
634 app,
635 target,
636 Failure::Unsupported,
637 "the viewer shows `docs:` pages, web pages and local images",
638 ),
639 }
640 }
641
642 fn finish(
644 &self,
645 app: &AppHandle,
646 target: &str,
647 name: &str,
648 bytes: Vec<u8>,
649 fragment: Option<&str>,
650 ) {
651 if bytes.len() > MAX_BYTES {
652 let detail = format!("{} bytes, more than {MAX_BYTES}", bytes.len());
653 return self.fail(app, target, Failure::TooLarge, &detail);
654 }
655 let ext = extension(name);
656 let mut html = false;
657 let mut dropped = Vec::new();
658 let content = match ext.as_str() {
659 "" | "md" | "markdown" | "txt" => {
660 let text = String::from_utf8_lossy(&bytes);
661 let text = if ext == "txt" {
662 format!("```text\n{text}\n```")
663 } else {
664 text.into_owned()
665 };
666 match page::strip_links(&text, target, &page_schemes(app, target)) {
667 Ok(text) => Content::Markdown(Markdown::parse(&text)),
668 Err(why) => return self.fail(app, target, Failure::Unsupported, why),
669 }
670 }
671 "png" | "jpg" | "jpeg" | "gif" => {
672 app.egui().include_bytes(target.to_string(), bytes);
673 Content::Image(target.to_string())
674 }
675 "html" | "htm" | "xhtml" => match read_html(app, target, &bytes) {
676 Ok((md, elements)) => {
677 html = true;
678 dropped = elements;
679 Content::Markdown(md)
680 }
681 Err(why) => return self.fail(app, target, Failure::Unsupported, why),
682 },
683 other => {
684 let detail = format!("`.{other}` files are not shown inside");
685 return self.fail(app, target, Failure::Unsupported, &detail);
686 }
687 };
688 if let Content::Markdown(md) = &content {
689 for uri in self.prepare_images(app, target, md) {
690 if !dropped.contains(&uri) {
691 dropped.push(uri);
692 }
693 }
694 let mut cache = lock(&self.cache);
695 cache.link_hooks_clear();
696 for l in md.links() {
697 cache.add_link_hook(l);
698 }
699 }
700 let page = Arc::new(Page {
701 target: target.to_string(),
702 content,
703 html,
704 dropped,
705 });
706 {
707 let mut i = lock(&self.inner);
708 i.status = Status::Shown(page.clone());
709 i.restore = i.current.as_ref().map(|e| e.scroll);
710 i.scroll_to = None;
711 let query = i.find.query.clone();
712 if let Content::Markdown(md) = &page.content {
713 i.find.matches = md.find(&query);
714 i.find.at = 0;
715 }
716 }
717 self.scroll_to_anchor(&page, fragment);
718 app.publish(
719 PLUGIN.as_str(),
720 None,
721 "viewer.shown",
722 json!({ "target": target, "kind": page.kind() }),
723 );
724 }
725
726 fn prepare_images(&self, app: &AppHandle, base: &str, md: &Markdown) -> Vec<String> {
732 let page_host = host_of(base);
733 let readable = page_image_schemes(app, base);
734 let mut refused = Vec::new();
735 let ctx = app.egui();
736 for img in md.blocks.iter().flat_map(|b| &b.images) {
737 let uri = resolve(base, &img.dest);
738 let parsed = Target::parse(&uri).ok();
739 let scheme = parsed.as_ref().map(Target::scheme);
740 if scheme.is_some_and(|s| page::IMAGE_SCHEMES.contains(&s) && !readable.contains(s)) {
741 lock(&self.inner).images.remove(&uri);
742 if !refused.contains(&uri) {
743 refused.push(uri);
744 }
745 continue;
746 }
747 if lock(&self.inner).images.contains_key(&uri) {
748 continue;
749 }
750 let state = match scheme {
751 Some("docs") => {
752 let page = parsed
753 .as_ref()
754 .and_then(Target::doc_page)
755 .unwrap_or_default();
756 match self.docs.get(&page) {
757 Some((_, bytes)) => {
758 ctx.include_bytes(uri.clone(), bytes);
759 Image::Ready
760 }
761 None => Image::Failed(format!("no file `{page}`")),
762 }
763 }
764 Some("file") => {
765 let path = parsed
766 .as_ref()
767 .and_then(Target::local_path)
768 .unwrap_or_default();
769 match read_file(&path) {
770 Ok(bytes) => {
771 ctx.include_bytes(uri.clone(), bytes);
772 Image::Ready
773 }
774 Err((_, e)) => Image::Failed(e),
775 }
776 }
777 Some("http" | "https") => {
778 let host = host_of(&uri).unwrap_or_default();
779 let allowed =
780 page_host.as_deref() == Some(host.as_str()) || self.allows(app, &host);
781 if allowed {
782 self.fetch_image(app, &uri)
783 } else {
784 Image::Blocked(host)
785 }
786 }
787 _ => Image::Failed("not an image the viewer loads".into()),
788 };
789 lock(&self.inner).images.insert(uri, state);
790 }
791 refused
792 }
793
794 fn fetch_image(&self, app: &AppHandle, uri: &str) -> Image {
795 let Some(fetch) = &self.fetch else {
796 return Image::Failed("this application does not load images from the network".into());
797 };
798 let inbox = self.inbox.clone();
799 let ctx = app.egui();
800 let u = uri.to_string();
801 fetch.fetch(
802 uri,
803 Box::new(move |r| {
804 lock(&inbox).push((Arrival::Image(u), r));
805 ctx.request_repaint();
806 }),
807 );
808 Image::Loading
809 }
810
811 pub fn allowed_hosts(&self, app: &AppHandle) -> BTreeSet<String> {
813 let text = lock(&app.store())
814 .get(&format!("settings/{SETTING_IMAGE_HOSTS}"))
815 .and_then(|e| match &e.value {
816 Value::Text(t) => Some(t.clone()),
817 _ => None,
818 })
819 .unwrap_or_default();
820 let hosts = parse_hosts(&text);
821 lock(&self.inner).allowed = hosts.clone();
822 hosts
823 }
824
825 fn allows(&self, app: &AppHandle, host: &str) -> bool {
826 self.allowed_hosts(app).contains(host)
827 }
828
829 pub fn load_images(&self, app: &AppHandle, host: &str) -> Result<usize, String> {
832 let host = host.trim().to_ascii_lowercase();
833 if host.is_empty() {
834 return Err("`host` is missing".into());
835 }
836 let mut hosts = self.allowed_hosts(app);
837 if hosts.insert(host.clone()) {
838 let text = hosts.into_iter().collect::<Vec<_>>().join(", ");
839 lock(&app.store())
840 .set(Set::new(
841 &format!("settings/{SETTING_IMAGE_HOSTS}"),
842 Change::To(Value::Text(text)),
843 Origin::User,
844 ))
845 .map_err(|e| e.to_string())?;
846 self.allowed_hosts(app);
847 }
848 let waiting: Vec<String> = lock(&self.inner)
849 .images
850 .iter()
851 .filter(|(_, s)| **s == Image::Blocked(host.clone()))
852 .map(|(u, _)| u.clone())
853 .collect();
854 for uri in &waiting {
855 let state = self.fetch_image(app, uri);
856 lock(&self.inner).images.insert(uri.clone(), state);
857 }
858 app.egui().request_repaint();
859 Ok(waiting.len())
860 }
861
862 pub fn poll(&self, app: &AppHandle) {
864 let arrived: Vec<(Arrival, Fetched)> = std::mem::take(&mut *lock(&self.inbox));
865 for (what, result) in arrived {
866 match what {
867 Arrival::Page { target, generation } => {
868 if lock(&self.inner).generation != generation {
869 continue;
870 }
871 let fragment = self
872 .target()
873 .and_then(|t| split_fragment(&t).1.map(str::to_string));
874 match result {
875 Ok(bytes) => self.finish(app, &target, &target, bytes, fragment.as_deref()),
876 Err(e) => self.fail(app, &target, Failure::NoConnection, &e),
877 }
878 }
879 Arrival::Image(uri) => {
880 let state = match result {
881 Ok(bytes) if bytes.len() > MAX_BYTES => {
882 Image::Failed(format!("{} bytes, too large", bytes.len()))
883 }
884 Ok(bytes) => {
885 app.egui().include_bytes(uri.clone(), bytes);
886 Image::Ready
887 }
888 Err(e) => Image::Failed(e),
889 };
890 lock(&self.inner).images.insert(uri, state);
891 }
892 }
893 }
894 }
895
896 pub fn back(&self, app: &AppHandle) -> bool {
898 self.walk(app, true)
899 }
900
901 pub fn forward(&self, app: &AppHandle) -> bool {
903 self.walk(app, false)
904 }
905
906 fn walk(&self, app: &AppHandle, back: bool) -> bool {
907 let target = {
908 let mut i = lock(&self.inner);
909 let next = if back { i.back.pop() } else { i.forward.pop() };
910 let Some(next) = next else {
911 return false;
912 };
913 if let Some(mut cur) = i.current.take() {
914 cur.scroll = i.scroll;
915 if back {
916 i.forward.push(cur);
917 } else {
918 i.back.push(cur);
919 }
920 }
921 i.address = next.target.clone();
922 let t = next.target.clone();
923 i.current = Some(next);
924 t
925 };
926 let (base, fragment) = split_fragment(&target);
927 self.load(app, base, fragment);
928 true
929 }
930
931 pub fn reload(&self, app: &AppHandle) -> bool {
933 let Some(target) = self.target() else {
934 return false;
935 };
936 {
937 let mut i = lock(&self.inner);
938 i.images.retain(|_, s| !matches!(s, Image::Failed(_)));
939 let scroll = i.scroll;
940 if let Some(c) = i.current.as_mut() {
941 c.scroll = scroll;
942 }
943 }
944 let (base, fragment) = split_fragment(&target);
945 self.load(app, base, fragment);
946 true
947 }
948
949 pub fn find(&self, query: Option<&str>) -> usize {
952 let mut i = lock(&self.inner);
953 i.find.open = true;
954 i.find.focus = true;
955 if let Some(q) = query {
956 i.find.query = q.to_string();
957 }
958 self.refind(&mut i);
959 i.find.matches.len()
960 }
961
962 fn refind(&self, i: &mut Inner) {
963 let matches = match &i.status {
964 Status::Shown(p) => match &p.content {
965 Content::Markdown(md) => md.find(&i.find.query),
966 Content::Image(_) | Content::Video(_) | Content::YouTube(_) => Vec::new(),
967 },
968 _ => Vec::new(),
969 };
970 i.find.matches = matches;
971 i.find.at = 0;
972 i.scroll_to = i.find.matches.first().copied();
973 }
974
975 pub fn find_step(&self, next: bool) -> Option<usize> {
978 let mut i = lock(&self.inner);
979 let n = i.find.matches.len();
980 if n == 0 {
981 return None;
982 }
983 i.find.at = if next {
984 (i.find.at + 1) % n
985 } else {
986 (i.find.at + n - 1) % n
987 };
988 i.scroll_to = Some(i.find.matches[i.find.at]);
989 Some(i.find.at + 1)
990 }
991
992 pub fn close_find(&self) {
994 let mut i = lock(&self.inner);
995 i.find.open = false;
996 i.find.matches.clear();
997 }
998
999 pub fn zoom_step(&self, by: i32) -> f32 {
1001 let mut i = lock(&self.inner);
1002 i.zoom = if by == 0 {
1003 1.0
1004 } else {
1005 let at = ZOOM_STEPS
1006 .iter()
1007 .position(|z| (*z - i.zoom).abs() < 0.001)
1008 .unwrap_or(5) as i32;
1009 ZOOM_STEPS[(at + by).clamp(0, ZOOM_STEPS.len() as i32 - 1) as usize]
1010 };
1011 i.zoom
1012 }
1013
1014 fn source_of(target: &str) -> Source {
1017 if target.starts_with("docs:") {
1018 Source::Declared
1019 } else {
1020 Source::Content
1021 }
1022 }
1023
1024 pub fn open_outside(&self, app: &AppHandle, origin: &Origin) -> Result<Json, String> {
1026 let target = self.target().ok_or("nothing is open")?;
1027 let req = Request::new(&target)
1028 .how(How::Outside)
1029 .source(Self::source_of(&target))
1030 .origin(origin.clone());
1031 match links::open(app, req) {
1032 egui_pop_api::steps::Outcome::Done(r) => r,
1033 egui_pop_api::steps::Outcome::Vetoed { by, reason } => {
1034 Err(format!("vetoed by {by}: {reason}"))
1035 }
1036 }
1037 }
1038
1039 pub fn copy_link(&self, app: &AppHandle, origin: &Origin) -> Result<Json, String> {
1041 let target = self.target().ok_or("nothing is open")?;
1042 links::copy_link(app, &target, origin);
1043 Ok(json!({ "copied": target }))
1044 }
1045
1046 pub fn follow(&self, app: &AppHandle, dest: &str, outside: bool) {
1049 let Some(page) = (match self.status() {
1050 Status::Shown(p) => Some(p),
1051 _ => None,
1052 }) else {
1053 return;
1054 };
1055 let resolved = resolve(&page.target, dest);
1056 let (base, fragment) = split_fragment(&resolved);
1057 if base.is_empty() || (base == page.target && !outside) {
1058 self.scroll_to_anchor(&page, fragment);
1059 return;
1060 }
1061 let how = if outside { How::Outside } else { How::Auto };
1062 links::open(
1063 app,
1064 Request::new(&resolved)
1065 .how(how)
1066 .source(Self::source_of(&page.target)),
1067 );
1068 }
1069
1070 pub fn go(&self, app: &AppHandle, typed: &str) {
1073 let typed = typed.trim();
1074 if typed.is_empty() {
1075 return;
1076 }
1077 let target = if has_scheme(typed) || typed.starts_with('/') || typed.starts_with('\\') {
1078 typed.to_string()
1079 } else {
1080 format!("docs:{typed}")
1081 };
1082 if target.starts_with("command:") {
1083 self.fail(
1084 app,
1085 &target,
1086 Failure::Unsupported,
1087 "commands do not run from the address bar",
1088 );
1089 return;
1090 }
1091 links::open(app, Request::new(&target).source(Source::Declared));
1092 }
1093
1094 pub fn state(&self) -> Json {
1096 let video = self.video_state();
1097 let plays_video = self.plays_video();
1098 let embed = self.embed_state();
1099 let plays_web_video = self.plays_web_video();
1100 let i = lock(&self.inner);
1101 let mut links = Vec::new();
1102 let mut dropped = Vec::new();
1103 let (status, kind, title, error, text, headings) = match &i.status {
1104 Status::Empty => ("empty", None, None, None, None, Vec::new()),
1105 Status::Loading(_) => ("loading", None, None, None, None, Vec::new()),
1106 Status::Shown(p) => {
1107 dropped.clone_from(&p.dropped);
1108 if let Content::Markdown(md) = &p.content {
1109 links = md.links();
1110 }
1111 let (title, text, headings) = match &p.content {
1112 Content::Markdown(md) => (
1113 md.title.clone(),
1114 Some(md.text().chars().take(4000).collect::<String>()),
1115 md.blocks
1116 .iter()
1117 .filter_map(|b| {
1118 Some(json!({ "anchor": b.anchor.clone()?, "level": b.level }))
1119 })
1120 .collect(),
1121 ),
1122 Content::Image(_) | Content::Video(_) | Content::YouTube(_) => {
1123 (None, None, Vec::new())
1124 }
1125 };
1126 ("shown", Some(p.kind()), title, None, text, headings)
1127 }
1128 Status::Failed {
1129 failure, detail, ..
1130 } => (
1131 "failed",
1132 None,
1133 None,
1134 Some(json!({ "failure": failure, "detail": detail })),
1135 None,
1136 Vec::new(),
1137 ),
1138 };
1139 let blocked: BTreeSet<&String> = i
1140 .images
1141 .values()
1142 .filter_map(|s| match s {
1143 Image::Blocked(h) => Some(h),
1144 _ => None,
1145 })
1146 .collect();
1147 let images: Vec<Json> = i
1148 .images
1149 .iter()
1150 .map(|(u, s)| {
1151 let (state, why) = match s {
1152 Image::Ready => ("ready", None),
1153 Image::Loading => ("loading", None),
1154 Image::Blocked(_) => ("blocked", None),
1155 Image::Failed(e) => ("failed", Some(e)),
1156 };
1157 json!({ "uri": u, "state": state, "error": why })
1158 })
1159 .collect();
1160 json!({
1161 "target": i.current.as_ref().map(|e| e.target.clone()),
1162 "status": status,
1163 "kind": kind,
1164 "title": title,
1165 "error": error,
1166 "back": i.back.iter().map(|e| e.target.clone()).collect::<Vec<_>>(),
1167 "forward": i.forward.iter().rev().map(|e| e.target.clone()).collect::<Vec<_>>(),
1168 "find": {
1169 "open": i.find.open,
1170 "query": i.find.query,
1171 "matches": i.find.matches.len(),
1172 "at": (!i.find.matches.is_empty()).then_some(i.find.at + 1),
1173 },
1174 "zoom": i.zoom,
1175 "images": images,
1176 "blocked_hosts": blocked,
1177 "allowed_hosts": i.allowed,
1178 "headings": headings,
1179 "text": text,
1180 "links": links,
1181 "dropped": dropped,
1182 "fetch": self.fetch.is_some(),
1183 "video": video,
1184 "plays_video": plays_video,
1185 "embed": embed,
1186 "plays_web_video": plays_web_video,
1187 })
1188 }
1189}
1190
1191fn policy(app: &AppHandle) -> Policy {
1192 links::links(app).map(|l| l.policy()).unwrap_or_default()
1193}
1194
1195fn page_schemes(app: &AppHandle, page: &str) -> BTreeSet<String> {
1197 page::schemes(&policy(app), page)
1198}
1199
1200fn page_image_schemes(app: &AppHandle, page: &str) -> BTreeSet<String> {
1202 page::image_schemes(&policy(app), page)
1203}
1204
1205#[cfg(feature = "html")]
1208fn read_html(
1209 app: &AppHandle,
1210 target: &str,
1211 bytes: &[u8],
1212) -> Result<(Markdown, Vec<String>), &'static str> {
1213 let schemes = page_schemes(app, target);
1214 let page = html::read(&String::from_utf8_lossy(bytes), &schemes)?;
1215 let mut md = Markdown::parse(&page::strip_links(&page.markdown, target, &schemes)?);
1218 md.title = page.title.or(md.title);
1219 Ok((md, page.dropped))
1220}
1221
1222#[cfg(not(feature = "html"))]
1224fn read_html(_: &AppHandle, _: &str, _: &[u8]) -> Result<(Markdown, Vec<String>), &'static str> {
1225 Err("this application is built without the viewer's HTML subset")
1226}
1227
1228#[cfg(not(target_arch = "wasm32"))]
1229fn read_file(path: &str) -> Result<Vec<u8>, (Failure, String)> {
1230 let meta = std::fs::metadata(path).map_err(|e| (Failure::NotFound, e.to_string()))?;
1231 if meta.len() > MAX_BYTES as u64 {
1232 return Err((
1233 Failure::TooLarge,
1234 format!("{} bytes, more than {MAX_BYTES}", meta.len()),
1235 ));
1236 }
1237 std::fs::read(path).map_err(|e| (Failure::NotFound, e.to_string()))
1238}
1239
1240#[cfg(target_arch = "wasm32")]
1241fn read_file(_: &str) -> Result<Vec<u8>, (Failure, String)> {
1242 Err((
1243 Failure::Unsupported,
1244 "local files are not read on the web".into(),
1245 ))
1246}
1247
1248#[derive(Debug)]
1250struct Shows(Arc<Viewer>);
1251
1252impl Inside for Shows {
1253 fn name(&self) -> &str {
1254 "viewer"
1255 }
1256
1257 fn show(&self, app: &AppHandle, call: &OpenCall<'_>) -> Result<(), String> {
1258 self.0.navigate(app, call.target.as_str(), true);
1259 Ok(())
1260 }
1261
1262 fn docs_pages(&self) -> Option<Vec<String>> {
1263 Some(self.0.docs.pages())
1264 }
1265
1266 fn plays_video(&self) -> bool {
1267 self.0.plays_video()
1268 }
1269
1270 fn plays_web_video(&self) -> bool {
1271 self.0.plays_web_video()
1272 }
1273}
1274
1275#[derive(Default)]
1279pub struct ViewerPlugin {
1280 docs: Docs,
1281 fetch: Option<Arc<dyn Fetch>>,
1282 video: Option<Arc<dyn VideoBackend>>,
1283 embed: Option<Arc<dyn EmbedBackend>>,
1284 referrer: Option<String>,
1285}
1286
1287impl std::fmt::Debug for ViewerPlugin {
1288 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1289 f.debug_struct("ViewerPlugin")
1290 .field("docs", &self.docs)
1291 .field("fetch", &self.fetch.is_some())
1292 .field("video", &self.video.as_ref().map(|b| b.name().to_string()))
1293 .field("embed", &self.embed.as_ref().map(|b| b.name().to_string()))
1294 .field("referrer", &self.referrer)
1295 .finish()
1296 }
1297}
1298
1299impl ViewerPlugin {
1300 pub fn docs(mut self, docs: Docs) -> Self {
1302 self.docs = docs;
1303 self
1304 }
1305
1306 pub fn fetch(mut self, fetch: Arc<dyn Fetch>) -> Self {
1308 self.fetch = Some(fetch);
1309 self
1310 }
1311
1312 pub fn video(mut self, backend: Arc<dyn VideoBackend>) -> Self {
1315 self.video = Some(backend);
1316 self
1317 }
1318
1319 pub fn web_video(mut self, backend: Arc<dyn EmbedBackend>) -> Self {
1322 self.embed = Some(backend);
1323 self
1324 }
1325
1326 pub fn embed_referrer(mut self, referrer: impl Into<String>) -> Self {
1333 self.referrer = Some(referrer.into());
1334 self
1335 }
1336}
1337
1338fn surface() -> BindOptions {
1339 BindOptions::surface(SURFACE)
1340}
1341
1342fn viewer(app: &AppHandle) -> Result<Arc<Viewer>, String> {
1343 app.service(&VIEWER)
1344 .ok_or_else(|| "the viewer plugin is not connected".to_string())
1345}
1346
1347impl Plugin for ViewerPlugin {
1348 fn id(&self) -> PluginId {
1349 PLUGIN
1350 }
1351
1352 fn title(&self) -> String {
1353 "Viewer".into()
1354 }
1355
1356 fn requires(&self) -> Vec<PluginId> {
1357 vec![links::PLUGIN]
1358 }
1359
1360 fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
1361 let app = ctx.app();
1362 ctx.service(&VIEWER, Viewer::new(self.docs.clone(), self.fetch.clone()))?;
1363 let v = app
1364 .service(&VIEWER)
1365 .ok_or_else(|| PluginError::Failed("the viewer service is missing".into()))?;
1366 if let Some(backend) = &self.video {
1367 v.set_video_backend(Some(backend.clone()));
1368 }
1369 if let Some(backend) = &self.embed {
1370 v.set_embed_backend(Some(backend.clone()));
1371 }
1372 let referrer = self
1373 .referrer
1374 .clone()
1375 .or_else(|| embed::referrer_for(&app.app_id()));
1376 if referrer.is_none() && lock(&v.embed).has_backend() {
1377 log::warn!(
1378 target: "egui_pop",
1379 "viewer: no application id (`AppBuilder::app_id`) to name in YouTube's `Referer`: YouTube links open outside"
1380 );
1381 }
1382 lock(&v.embed).set_referrer(referrer);
1383 embed::listen(&app, &v);
1384 if let Some(l) = links::links(&app) {
1385 l.set_inside(Some(Arc::new(Shows(v.clone()))));
1386 }
1387 egui_extras::install_image_loaders(&app.egui());
1390 ctx.setting(
1391 SETTING_IMAGE_HOSTS,
1392 Descriptor::text("Images loaded from", "").description(
1393 "The hosts whose images the viewer loads, each allowed by you once; empty to be asked again.",
1394 ),
1395 )?;
1396 ctx.panel(
1397 PanelSpec::new(PANEL, "Viewer", Area::EndSide)
1398 .min_size(240.0)
1399 .default_size(420.0)
1400 .icon("help")
1401 .closed(),
1402 |ui, app| {
1403 if let Ok(v) = viewer(app) {
1404 view::show(ui, app, &v);
1405 }
1406 },
1407 )?;
1408 commands(ctx)?;
1409 let c = v.clone();
1410 ctx.collector(
1411 FnCollector::new(
1412 "viewer",
1413 "The viewer: the page (its address, status or error, title, headings, text, links and what its HTML did not show), the history back and forward, the search, the zoom, the images (ready, loading, blocked by host, failed) and the hosts allowed.",
1414 )
1415 .snapshot(move |_| c.state()),
1416 )?;
1417 ctx.on(egui_pop_api::hooks::On::Pass, |app, _| {
1418 if let Ok(v) = viewer(app) {
1419 v.video_pass(app);
1420 v.embed_pass(app);
1421 v.poll(app);
1422 }
1423 });
1424 Ok(())
1425 }
1426
1427 fn disconnect(&mut self, ctx: &mut Ctx<'_>) {
1428 let app = ctx.app();
1429 if let Ok(v) = viewer(&app) {
1430 v.stop_video(&app);
1431 v.stop_embed(&app, egui_pop_api::bus::Reason::OwnerGone);
1432 }
1433 embed::unlisten(&app);
1434 if let Some(l) = links::links(&app) {
1435 l.set_inside(None);
1436 }
1437 }
1438}
1439
1440const CAT: &str = "Viewer";
1441
1442fn video_key(id: CommandId, title: &str, key: &str) -> CommandSpec {
1445 CommandSpec::new(id, title, CAT)
1446 .when(VIDEO_CONTEXT)
1447 .key_with(key, BindOptions::surface(VIDEO_SURFACE))
1448}
1449
1450fn commands(ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
1451 ctx.command(
1452 CommandSpec::new(CMD_BACK, "Back", CAT)
1453 .description("Shows the viewer's previous page.")
1454 .key_with("Alt+Left", surface()),
1455 |call| Ok(json!({ "moved": viewer(call.app)?.back(call.app) })),
1456 )?
1457 .command(
1458 CommandSpec::new(CMD_FORWARD, "Forward", CAT)
1459 .description("Shows the viewer's next page, after going back.")
1460 .key_with("Alt+Right", surface()),
1461 |call| Ok(json!({ "moved": viewer(call.app)?.forward(call.app) })),
1462 )?
1463 .command(
1464 CommandSpec::new(CMD_RELOAD, "Reload the page", CAT)
1465 .description("Loads the viewer's page again.")
1466 .key_with("F5", surface()),
1467 |call| Ok(json!({ "reloaded": viewer(call.app)?.reload(call.app) })),
1468 )?
1469 .command(
1470 CommandSpec::new(CMD_FIND, "Find in page", CAT)
1471 .description("Opens the viewer's search; with `query`, searches the page and goes to the first match.")
1472 .key_with("Ctrl+F", surface())
1473 .args(json!({ "query": "install" })),
1474 |call| {
1475 let v = viewer(call.app)?;
1476 let n = v.find(call.args["query"].as_str());
1477 Ok(json!({ "matches": n }))
1478 },
1479 )?
1480 .command(
1481 CommandSpec::new(CMD_FIND_NEXT, "Find next in page", CAT)
1482 .description("Goes to the next match of the viewer's search.")
1483 .key_with("F3", surface()),
1484 |call| Ok(json!({ "at": viewer(call.app)?.find_step(true) })),
1485 )?
1486 .command(
1487 CommandSpec::new(CMD_FIND_PREVIOUS, "Find previous in page", CAT)
1488 .description("Goes to the previous match of the viewer's search.")
1489 .key_with("Shift+F3", surface()),
1490 |call| Ok(json!({ "at": viewer(call.app)?.find_step(false) })),
1491 )?
1492 .command(
1493 CommandSpec::new(CMD_ZOOM_IN, "Zoom in the page", CAT)
1494 .description("Makes the viewer's page larger, one step.")
1495 .key_with("Ctrl+Plus", surface())
1496 .key_with("Ctrl+Equals", surface()),
1497 |call| Ok(json!({ "zoom": viewer(call.app)?.zoom_step(1) })),
1498 )?
1499 .command(
1500 CommandSpec::new(CMD_ZOOM_OUT, "Zoom out the page", CAT)
1501 .description("Makes the viewer's page smaller, one step.")
1502 .key_with("Ctrl+Minus", surface()),
1503 |call| Ok(json!({ "zoom": viewer(call.app)?.zoom_step(-1) })),
1504 )?
1505 .command(
1506 CommandSpec::new(CMD_ZOOM_RESET, "Reset the page zoom", CAT)
1507 .description("Gives the viewer's page its normal size.")
1508 .key_with("Ctrl+0", surface()),
1509 |call| Ok(json!({ "zoom": viewer(call.app)?.zoom_step(0) })),
1510 )?
1511 .command(
1512 CommandSpec::new(CMD_OPEN_OUTSIDE, "Open the page outside", CAT)
1513 .description("Opens the viewer's page outside the application (a `docs:` page's online copy), through the links service; an agent's request is confirmed by the user."),
1514 |call| viewer(call.app)?.open_outside(call.app, call.origin),
1515 )?
1516 .command(
1517 CommandSpec::new(CMD_COPY_LINK, "Copy the page's link", CAT)
1518 .description("Copies the address of the viewer's page."),
1519 |call| viewer(call.app)?.copy_link(call.app, call.origin),
1520 )?
1521 .command(
1522 CommandSpec::new(CMD_LOAD_IMAGES, "Load images from a host", CAT)
1523 .description("Loads the images of a host (`host`) the viewer's page shows, and remembers the host; the user's choice alone.")
1524 .args(json!({ "host": "images.example.org" }))
1525 .hidden()
1526 .no_agent(),
1527 |call| {
1528 if *call.origin != Origin::User {
1529 return Err("only the user allows a host's images".into());
1530 }
1531 let host = call.args["host"].as_str().ok_or("`host` is missing")?;
1532 let n = viewer(call.app)?.load_images(call.app, host)?;
1533 Ok(json!({ "host": host, "loading": n }))
1534 },
1535 )?
1536 .command(
1537 CommandSpec::new(CMD_STATE, "Read the viewer", CAT)
1538 .description("The viewer's page (address, status or error, title, headings, text, links, what its HTML did not show), its history, search, zoom, images and the hosts allowed.")
1539 .hidden(),
1540 |call| {
1541 let v = viewer(call.app)?;
1542 v.allowed_hosts(call.app);
1543 Ok(v.state())
1544 },
1545 )?
1546 .command(
1547 video_key(CMD_VIDEO_TOGGLE, "Play or pause the video", "Space")
1548 .description("Plays or pauses the video the viewer shows; from its end, plays it from the start."),
1549 |call| viewer(call.app)?.video_toggle(call.app),
1550 )?
1551 .command(
1552 video_key(CMD_VIDEO_BACK, "Move the video back", "Left")
1553 .description("Moves the viewer's video back a few seconds."),
1554 |call| viewer(call.app)?.video_seek_by(call.app, -SEEK_STEP.as_secs_f64()),
1555 )?
1556 .command(
1557 video_key(CMD_VIDEO_AHEAD, "Move the video ahead", "Right")
1558 .description("Moves the viewer's video ahead a few seconds."),
1559 |call| viewer(call.app)?.video_seek_by(call.app, SEEK_STEP.as_secs_f64()),
1560 )?
1561 .command(
1562 video_key(CMD_VIDEO_LOUDER, "Make the video louder", "Up")
1563 .description("Raises the volume of the viewer's video one step."),
1564 |call| viewer(call.app)?.video_volume_by(call.app, VOLUME_STEP),
1565 )?
1566 .command(
1567 video_key(CMD_VIDEO_QUIETER, "Make the video quieter", "Down")
1568 .description("Lowers the volume of the viewer's video one step."),
1569 |call| viewer(call.app)?.video_volume_by(call.app, -VOLUME_STEP),
1570 )?
1571 .command(
1572 CommandSpec::new(CMD_VIDEO_SEEK, "Move the video to a time", CAT)
1573 .description("Moves the viewer's video to a position (`seconds`).")
1574 .when(VIDEO_CONTEXT)
1575 .args(json!({ "seconds": 12.5 }))
1576 .hidden(),
1577 |call| {
1578 let seconds = call.args["seconds"].as_f64().ok_or("`seconds` is missing")?;
1579 viewer(call.app)?.video_seek_to(call.app, seconds)
1580 },
1581 )?
1582 .command(
1583 CommandSpec::new(CMD_VIDEO_VOLUME, "Set the video's volume", CAT)
1584 .description("Sets the volume of the viewer's video (`volume`, from 0 to 1).")
1585 .when(VIDEO_CONTEXT)
1586 .args(json!({ "volume": 0.5 }))
1587 .hidden(),
1588 |call| {
1589 let volume = call.args["volume"].as_f64().ok_or("`volume` is missing")?;
1590 viewer(call.app)?.video_volume(call.app, volume as f32)
1591 },
1592 )?;
1593 Ok(())
1594}