1mod 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
95pub const SURFACE: &str = "video";
98pub const SEEK_STEP: Duration = Duration::from_secs(5);
100pub const VOLUME_STEP: f32 = 0.05;
102const TIME_REPAINT: Duration = Duration::from_millis(250);
104const DEFAULT_ASPECT: f32 = 16.0 / 9.0;
106
107#[derive(Clone, Debug)]
109pub struct VideoRequest {
110 pub path: PathBuf,
112 pub egui: egui::Context,
114 pub volume: f32,
116}
117
118#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)]
120#[serde(rename_all = "snake_case")]
121pub enum VideoState {
122 #[default]
124 Loading,
125 Paused,
126 Playing,
127 Ended,
129}
130
131#[derive(Clone, Debug, Default, PartialEq)]
133pub struct VideoStatus {
134 pub state: VideoState,
135 pub position: Option<Duration>,
137 pub duration: Option<Duration>,
139 pub note: Option<String>,
142}
143
144#[derive(Clone, Debug)]
146pub struct VideoFrame {
147 pub image: Arc<ColorImage>,
148 pub aspect: f32,
151}
152
153pub trait VideoPlayer: Send {
156 fn poll(&mut self) -> Result<VideoStatus, String>;
158 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 fn set_volume(&mut self, volume: f32);
165 fn set_looping(&mut self, on: bool) -> bool {
169 let _ = on;
170 false
171 }
172 fn loops(&self) -> u64 {
174 0
175 }
176}
177
178pub trait VideoBackend: Send + Sync {
180 fn name(&self) -> &str;
182 fn open(&self, request: &VideoRequest) -> Result<Box<dyn VideoPlayer>, String>;
185}
186
187pub 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
202pub 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
213pub 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize)]
228#[serde(rename_all = "snake_case")]
229pub enum Controls {
230 #[default]
233 Full,
234 Compact,
236 None,
239}
240
241#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize)]
243#[serde(rename_all = "snake_case")]
244pub enum Fit {
245 #[default]
247 Contain,
248 Cover,
250}
251
252#[derive(Clone)]
254enum Backend {
255 Default,
256 Given(Option<Arc<dyn VideoBackend>>),
257}
258
259#[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#[derive(Debug)]
300pub struct VideoOutput {
301 pub response: Response,
303 pub state: VideoState,
304 pub position: Duration,
305 pub duration: Option<Duration>,
306 pub volume: f32,
308 pub muted: bool,
309 pub error: Option<String>,
311 pub unavailable: bool,
313 pub open_outside: bool,
316}
317
318impl<'a> Video<'a> {
319 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 pub fn id(mut self, id: impl Into<String>) -> Self {
344 self.id = Some(id.into());
345 self
346 }
347
348 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 pub fn autoplay(mut self, on: bool) -> Self {
362 self.autoplay = on;
363 self
364 }
365
366 pub fn looping(mut self, on: bool) -> Self {
368 self.looping = on;
369 self
370 }
371
372 pub fn muted(mut self, on: bool) -> Self {
375 self.muted = on;
376 self
377 }
378
379 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 pub fn poster(mut self, poster: impl Into<SizedTexture>) -> Self {
393 self.poster = Some(poster.into());
394 self
395 }
396
397 pub fn size(mut self, size: Vec2) -> Self {
400 self.size = Some(size);
401 self
402 }
403
404 pub fn backend(mut self, backend: Option<Arc<dyn VideoBackend>>) -> Self {
407 self.backend = Backend::Given(backend);
408 self
409 }
410
411 #[cfg(feature = "api")]
413 pub fn app(mut self, app: &'a AppHandle) -> Self {
414 self.app = Some(app);
415 self
416 }
417
418 pub fn surface(mut self, surface: &'a str) -> Self {
421 self.surface = surface;
422 self
423 }
424
425 pub fn take_focus(mut self, on: bool) -> Self {
427 self.take_focus = on;
428 self
429 }
430
431 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(®istry);
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 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 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 let clicked = response.clicked();
617 if clicked {
618 response.request_focus();
619 acts.push(Act::Toggle);
620 }
621 if response.has_focus() {
622 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
651fn 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
678fn 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 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
706fn 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
716fn 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
728fn 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 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#[cfg(not(feature = "api"))]
754const LINKS_OPEN_OUTSIDE: StrKey = StrKey::new("egui-pop-links-open-outside", "Open outside");
755
756fn 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
812fn 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
823fn 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 s.scrub = scrub.or(if out.response.dragged() {
852 s.scrub
853 } else {
854 None
855 });
856}
857
858fn 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 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#[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 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 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 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}