diff --git a/Cargo.lock b/Cargo.lock index 2f25624..d703536 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -62,7 +62,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "alias-playback" version = "0.1.0" -source = "git+https://github.com/aliasproject/alias-playback?branch=ali-2358-gpu-media#4a05f2ce2e59e38f901f7fdcb198557f3b48f16b" +source = "git+https://github.com/aliasproject/alias-playback?branch=main#fef4a47593f34a24c7c0d7702a2581764cb3020c" dependencies = [ "libc", "rustix", diff --git a/Cargo.toml b/Cargo.toml index 0b7a8ae..60d1a68 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,9 +29,8 @@ xkbcommon = { version = "0.9.0", default-features = false } swash = "0.2.10" rustix = { version = "1.1.6", features = ["fs", "event", "time", "pipe", "process"] } # Video and music: libmpv in a jailed helper that draws on the graphics card and hands its -# frames over as dmabufs (ALI-2358). On the branch of alias-playback PR #3 (stacked on #2) -# until those merge; then this moves to main. -alias-playback = { git = "https://github.com/aliasproject/alias-playback", branch = "ali-2358-gpu-media" } +# frames over as dmabufs (ALI-2358). +alias-playback = { git = "https://github.com/aliasproject/alias-playback", branch = "main" } [profile.release] opt-level = 3 diff --git a/LICENSE b/LICENSE index 79569e9..00a7e53 100644 --- a/LICENSE +++ b/LICENSE @@ -19,3 +19,25 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--- + +The player's icons in src/player/icons.rs (previous, play, pause, replay, next, sound, +muted, full screen and the music note) are from Lucide (https://lucide.dev), under the ISC +licence: + +ISC License + +Copyright (c) for portions of Lucide are held by Cole Bemis 2013-2022 as part of Feather (MIT). +All other copyright (c) for Lucide are held by Lucide Contributors 2022. + +Permission to use, copy, modify, and/or distribute this software for any purpose with or +without fee is hereby granted, provided that the above copyright notice and this permission +notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS +SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL +THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY +DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF +CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. diff --git a/README.md b/README.md index c00224e..2f19427 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ # Alias View -aliasOS's picture viewer. It replaces `imv` as the default for pictures; video and -audio stay with `mpv`. Rust, drawn on the CPU straight onto Wayland with no toolkit, in +aliasOS's picture viewer, which also plays video and music (ALI-2358, to replace `mpv`). It +replaces `imv` as the default for pictures. Rust, drawn on the CPU straight onto Wayland with no toolkit, in the style of [Gannet](../gannet), aliasOS's file manager. - alias-view FILE... # those pictures, in that order + alias-view FILE... # those pictures (or videos and songs), in that order alias-view FILE # that picture, then the rest of its folder alias-view FOLDER # the folder, from its first picture @@ -29,6 +29,36 @@ already has the picture in it. | `?` | The key list | | Escape, `q` | Escape closes a panel, leaves zoom or the grid, then quits; `q` quits | +### In a video or song + +From the design canvas's player boards, with Mike's decisions of 2026-12-02. + +| Keys | What they do | +| --- | --- | +| Space, `k` | Play or pause; after the end, play again from the start | +| Left, Right | Back or forward 5 s. Pictures keep Left and Right for the previous and next file | +| Up, Down | Volume down or up by 5 | +| `m` | Mute or unmute | +| `f`, double-click | Full screen, or back (videos) | +| `n`, Page Down / `p`, Page Up | Next or previous file in the folder | +| Home | Back to the start | +| `t` | Says the position to a screen reader: "1:23 of 4:56" | +| Tab, Shift+Tab | Through the control bar: Previous, Play, Next, Position, Mute, Volume, Full screen. Enter or Space presses a button; arrows move a slider | +| `?` | The key list | +| Escape, `q` | Escape leaves full screen, then quits | + +The media keys (play, pause, next, previous, volume, mute) work while the window has the +keyboard. + +The control bar hides 2 s after the pointer last moved or a key was pressed while a video +plays, in a window and in full screen. It stays while the video is paused or has ended, +for music, and while the keyboard focus is in it. The mouse pointer hides with the bar and +comes back with it: on any pointer motion, and on a key, a click or a pause. It hides only +where the desktop offers cursor-shape-v1, without which its shape couldn't be set again. +A video stops on its last frame with a +replay icon and never goes on by itself; a song plays on to the next song in the folder +and stops after the last. + ## Formats JPEG, PNG, WebP (still and animated), GIF (animated), BMP, TIFF, ICO, AVIF, HEIC/HEIF, @@ -40,6 +70,16 @@ file that claims more is shown at screen size where its format allows that witho holding the whole picture (baseline JPEG, PNG that isn't interlaced); zooming in then enlarges the screen copy and says why, and copying offers only the file itself. +Video: mp4, m4v, mkv, webm, mov, avi, flv, wmv, mpeg, ogv, 3gp and asf. Music: mp3, flac, +ogg, opus, m4a, aac, wav, wma, aiff, mka, wv and ape, with the cover art the file holds. +They play in [alias-playback](https://github.com/aliasproject/alias-playback)'s GPU +helper: libmpv in a bubblewrap jail (with Landlock and a seccomp filter), decoding on the +graphics card where it can (NVDEC, VA-API or V4L2, else the CPU) and drawing into +buffers it hands over as dmabufs. They show in a subsurface above the window, so video +never decodes in this process and its frames never pass through it. Sound goes through +the session's PulseAudio socket (PipeWire serves it), bound into the jail read-only. Needs +`bwrap`, libmpv, and a compositor with linux-dmabuf. + ## How it's fast Measured with `make startup` in a headless sway (1920x1080, pixman), three runs each, on @@ -138,6 +178,7 @@ Each is here for one job, and the crate itself has no unsafe code | `resvg` | SVG, drawn at the window's size | | `libheif-rs` | HEIC and AVIF through libheif. No pure Rust HEVC decoder exists, and libheif with its codec threads decodes the 24 MP HEIC in about 100 ms. | | `accesskit`, `accesskit_unix` | Screen readers, over AT-SPI | +| `alias-playback` | Video and music: libmpv in a jailed helper, its frames as dmabufs (Alias Project's own crate; its `unsafe` FFI lives there) | | `blocking` | Not used directly; pinned to 1.6.2 for zbus under accesskit_unix, because 1.7.0's last pool thread never exits and wakes twice a second | Test-only: `jpeg-encoder` and `zune-jpegxl` make test pictures; `zune-core` is the @@ -155,6 +196,15 @@ latter's options. background and the tiles; all text is held to 4.5:1 on what it sits on. A theme whose colours fall short is pulled up to those ratios, and a unit test checks the built-in palettes with the WCAG formula. +- The player's controls are AccessKit buttons, toggle buttons (Play, Mute, Full screen, + pressed or not) and sliders (Position "1:23 of 4:56", Volume "80%" or "Muted, 80% when + unmuted") in Tab order, with the focus ring on the focused one. Opening, pausing, + playing, the end, a failure, a change of volume and a seek by key (once the keys stop) + are announced politely; nothing is announced by itself while a video plays. +- Nothing in the player is told by colour alone: play, pause and replay are different + icons, the played part of a slider is 4 px against the rest's 2 px, and hover fills a + button behind its icon. The bar is opaque, so its text and icons keep their contrast + over any video. - Grid tiles are 168 px; nothing clickable is smaller than 44x44. Overlays rearrange themselves to fit (two columns, or label above value), and a test checks the key list fits the smallest window at 100%, 125% and 200%. @@ -189,6 +239,8 @@ that the list matches what the viewer derives (`cargo test`). src/view.rs fit and zoom maths src/ui.rs overlays and the grid's layout src/a11y.rs the AccessKit tree + src/player/ video and music: the helper (gpu.rs), the bar (bar.rs), icons + src/app/player_ui.rs the player's keys, pointer, bar hiding and announcements src/exif.rs orientation, date and camera src/trash.rs the freedesktop Trash, and putting things back src/theme.rs, text.rs, canvas.rs, sort.rs Gannet's, trimmed @@ -197,4 +249,5 @@ that the list matches what the viewer derives (`cargo test`). ## Licence -MIT. Copyright (c) 2026 Alias Project, Inc. +MIT. Copyright (c) 2026 Alias Project, Inc. The player's icons are Lucide's, under the +ISC licence (see `LICENSE`). diff --git a/design/tokens.json b/design/tokens.json index 8a8708f..812a2eb 100644 --- a/design/tokens.json +++ b/design/tokens.json @@ -103,7 +103,7 @@ "light": "#c3c4c6", "dark": "#4a4d51" }, - "usage": "A panel's and toast's 1 px edge: the background blended 25% toward the theme's text. Decorative: panels aren't controls, so it isn't in the contrast list. Proposed (ALI-2358): also a player button's fill under the pointer, behind its icon in foreground." + "usage": "A panel's and toast's 1 px edge: the background blended 25% toward the theme's text. Decorative: panels aren't controls, so it isn't in the contrast list. Also the fill of a player button under the pointer, behind its icon in foreground." }, { "name": "foreground", @@ -137,7 +137,7 @@ "light": "#65686c", "dark": "#9b9ea2" }, - "usage": "Labels in a panel of rows (Name, Size; a key in the key list): foreground blended 35% toward panel, then held to 4.5:1 on panel. Proposed (ALI-2358): also the unplayed part of the seek and volume bars, the time's total, and the artist and album under a song's title." + "usage": "Labels in a panel of rows (Name, Size; a key in the key list): foreground blended 35% toward panel, then held to 4.5:1 on panel. Also the unplayed part of the player's seek and volume bars, the time's total, and the artist and album under a song's title." }, { "name": "accent", @@ -154,7 +154,7 @@ "light": "#2f6feb", "dark": "#5b9bf5" }, - "usage": "The grid's focus ring. The theme's accent (or color4, or blue), moved until it has 3:1 against base and panel, the two things it sits beside. Proposed (ALI-2358): also the played part of the player's seek and volume bars, and the focus ring around its buttons." + "usage": "The grid's focus ring. The theme's accent (or color4, or blue), moved until it has 3:1 against base and panel, the two things it sits beside. Also the played part of the player's seek and volume bars, and the focus ring around its buttons." }, { "name": "danger", @@ -234,12 +234,22 @@ { "name": "controls-gap", "value": "4px", - "usage": "Proposed for the video and music player (ALI-2358), not drawn yet: between the buttons in the player's control bar, so each keeps its 44 px target." + "usage": "Between the buttons in the player's control bar, so each keeps its 44 px target." }, { "name": "cover-gap", "value": "24px", - "usage": "Proposed for the video and music player (ALI-2358), not drawn yet: in the music view, between the cover art and the title under it." + "usage": "In the music view, between the cover art and the title under it." + }, + { + "name": "time-pad", + "value": "12px", + "usage": "Either side of the time (1:23 / 4:56) in the player's control bar (src/player/bar.rs)." + }, + { + "name": "controls-group-gap", + "value": "8px", + "usage": "In the player's control bar, the extra space before the Mute and Full screen buttons, which sets the sound and window controls apart from the position (src/player/bar.rs)." } ] }, @@ -297,37 +307,42 @@ { "name": "controls-height", "value": "64px", - "usage": "Proposed for the video and music player (ALI-2358), not drawn yet: the player's control bar along the window's foot: a 44 px button with 10 px above and below. Opaque panel, so its text and icons keep their contrast over any video." + "usage": "The player's control bar along the window's foot: a 44 px button with 10 px above and below. Opaque panel, so its text and icons keep their contrast over any video." }, { "name": "control-icon", "value": "20px", - "usage": "Proposed for the video and music player (ALI-2358), not drawn yet: an icon inside a 44 px control button, drawn in foreground (border behind it under the pointer)." + "usage": "An icon inside a 44 px control button, drawn in foreground (border behind it under the pointer)." }, { "name": "seek-track", "value": "2px", - "usage": "Proposed for the video and music player (ALI-2358), not drawn yet: the part of the seek and volume bars still to come, in muted. Thinner than the played part, so the two differ in shape, not colour alone." + "usage": "The part of the seek and volume bars still to come, in muted. Thinner than the played part, so the two differ in shape, not colour alone." }, { "name": "seek-played", "value": "4px", - "usage": "Proposed for the video and music player (ALI-2358), not drawn yet: the part of the seek and volume bars already played or set, in accent." + "usage": "The part of the seek and volume bars already played or set, in accent." }, { "name": "seek-thumb", "value": "14px", - "usage": "Proposed for the video and music player (ALI-2358), not drawn yet: the round handle on the seek and volume bars, in foreground; its 44 px target is the bar's whole height." + "usage": "The round handle on the seek and volume bars, in foreground; its 44 px target is the bar's whole height." }, { "name": "volume-width", "value": "96px", - "usage": "Proposed for the video and music player (ALI-2358), not drawn yet: the volume bar's length in the control bar." + "usage": "The volume bar's length in the control bar." }, { "name": "cover-art", "value": "320px", - "usage": "Proposed for the video and music player (ALI-2358), not drawn yet: the music view's cover art, square, at most; smaller in a smaller window. No cover art: a panel square with a note icon in muted." + "usage": "The music view's cover art, square, at most; smaller in a smaller window. No cover art: a panel square with a note icon in muted." + }, + { + "name": "cover-icon", + "value": "96px", + "usage": "The note icon in the panel square a song with no cover art shows, in muted (src/player/bar.rs)." } ] }, @@ -351,12 +366,22 @@ { "name": "controls-hide", "value": "2s", - "usage": "Proposed for the video and music player (ALI-2358), not drawn yet: while a video plays, how long the control bar stays after the pointer last moved or a key was pressed. Paused, ended, loading, failed, music, or a keyboard focus inside the bar: it stays." + "usage": "While a video plays, how long the control bar stays after the pointer last moved or a key was pressed. Paused, ended, loading, failed, music, or a keyboard focus inside the bar: it stays. The mouse pointer hides and comes back with it." }, { "name": "seek-step", "value": "5s", - "usage": "Proposed for the video and music player (ALI-2358), not drawn yet: how far Left and Right (or a click on the seek bar's keyboard focus) move in a video." + "usage": "How far Left and Right (or a click on the seek bar's keyboard focus) move in a video." + }, + { + "name": "seek-announce", + "value": "500ms", + "usage": "After the last seek by key, how long the player waits before telling the screen reader the new position, so a held key is announced once, where it stops (src/app.rs)." + }, + { + "name": "double-click", + "value": "400ms", + "usage": "Two clicks on a video this close together are a double-click, which toggles full screen (src/app.rs)." } ] }, @@ -375,7 +400,7 @@ { "name": "volume-step", "value": 5, - "usage": "Proposed for the video and music player (ALI-2358), not drawn yet: how many points of 100 Up and Down (and the volume bar's arrow keys) move the volume." + "usage": "How many points of 100 Up and Down (and the volume bar's arrow keys) move the volume." } ] }, @@ -540,19 +565,19 @@ "fg": "foreground", "bg": "border", "min": 3, - "usage": "Proposed (ALI-2358): a player button's icon under the pointer, on its border-coloured fill." + "usage": "A player button's icon under the pointer, on its border-coloured fill." }, { "fg": "muted", "bg": "base", "min": 4.5, - "usage": "Proposed (ALI-2358): the artist and album under a song's title in the music view, straight on the background." + "usage": "The artist and album under a song's title in the music view, straight on the background." }, { "fg": "muted", "bg": "panel", "min": 3, - "usage": "Proposed (ALI-2358): the unplayed part of the seek and volume bars, a 2 px line on the control bar." + "usage": "The unplayed part of the seek and volume bars, a 2 px line on the control bar." } ] } diff --git a/src/a11y.rs b/src/a11y.rs index d886e03..1ffbb3e 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -17,6 +17,11 @@ pub const INFO: NodeId = NodeId(3); pub const HELP: NodeId = NodeId(4); pub const GRID: NodeId = NodeId(5); pub const STATUS: NodeId = NodeId(6); +pub const CONTROLS: NodeId = NodeId(7); +const SONG: NodeId = NodeId(8); +const ANNOUNCE: [NodeId; 2] = [NodeId(10), NodeId(11)]; +const BYLINE: NodeId = NodeId(9); +const CONTROL: u64 = 300; const INFO_LINE: u64 = 100; const HELP_LINE: u64 = 200; const TILE: u64 = 10_000; @@ -29,6 +34,45 @@ pub fn tile_index(id: NodeId) -> Option { id.0.checked_sub(TILE).map(|i| i as usize) } +/// The player's control at `i` in its list. +pub fn control_id(i: usize) -> NodeId { + NodeId(CONTROL + i as u64) +} + +pub fn control_index(id: NodeId) -> Option { + id.0.checked_sub(CONTROL).filter(|i| *i < 100).map(|i| i as usize) +} + +/// What a player control is to a screen reader. +#[derive(Clone, Debug, PartialEq)] +pub enum ControlKind { + Button, + /// A toggle button, pressed or not. + Toggle(bool), + Slider { + min: f64, + max: f64, + value: f64, + step: f64, + text: String, + }, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct ControlSnap { + pub name: String, + pub kind: ControlKind, + pub bounds: Rect, +} + +/// The player: its controls, which has the keyboard focus, and a song's words. +pub struct PlayerSnap { + pub controls: Vec, + pub focus: Option, + /// A song's title and "artist, album". + pub song: Option<(String, Option)>, +} + /// What the tree is built from, so it can be built off the main thread's state. pub struct Snapshot<'a> { pub title: &'a str, @@ -39,6 +83,13 @@ pub struct Snapshot<'a> { /// Tile names and the focused one. pub grid: Option<(Vec, usize)>, pub status: Option<&'a str>, + /// Set for a video or song; the picture node is then the video or cover art. + pub player: Option, + /// The picture node's role: an image, or a video. + pub video: bool, + /// Something to say once, politely, and which of two nodes to say it in: alternating, + /// the same words twice still change a node, so they're said again. + pub announce: Option<(String, bool)>, } pub fn tree(s: &Snapshot) -> TreeUpdate { @@ -46,7 +97,7 @@ pub fn tree(s: &Snapshot) -> TreeUpdate { let mut root = Node::new(Role::Window); root.set_label(s.title.to_string()); let mut children = vec![PICTURE]; - let mut picture = Node::new(Role::Image); + let mut picture = Node::new(if s.video { Role::Video } else { Role::Image }); picture.set_label(s.picture.clone()); picture.set_bounds(s.bounds); nodes.push((PICTURE, picture)); @@ -99,6 +150,60 @@ pub fn tree(s: &Snapshot) -> TreeUpdate { focus = tile_id(*focused); } } + if let Some(p) = &s.player { + if let Some((title, byline)) = &p.song { + let mut n = Node::new(Role::Label); + n.set_value(title.clone()); + nodes.push((SONG, n)); + children.push(SONG); + if let Some(b) = byline { + let mut n = Node::new(Role::Label); + n.set_value(b.clone()); + nodes.push((BYLINE, n)); + children.push(BYLINE); + } + } + let mut group = Node::new(Role::Group); + group.set_label("Player controls"); + let ids: Vec = (0..p.controls.len()).map(control_id).collect(); + for (id, c) in ids.iter().zip(&p.controls) { + let mut n = match &c.kind { + ControlKind::Button => Node::new(Role::Button), + ControlKind::Toggle(on) => { + let mut n = Node::new(Role::Button); + n.set_toggled(accesskit::Toggled::from(*on)); + n + } + ControlKind::Slider { min, max, value, step, text } => { + let mut n = Node::new(Role::Slider); + n.set_min_numeric_value(*min); + n.set_max_numeric_value(*max); + n.set_numeric_value(*value); + n.set_numeric_value_step(*step); + n.set_value(text.clone()); + n.add_action(Action::Increment); + n.add_action(Action::Decrement); + n.add_action(Action::SetValue); + n + } + }; + n.set_label(c.name.clone()); + n.set_bounds(c.bounds); + if !matches!(c.kind, ControlKind::Slider { .. }) { + n.add_action(Action::Click); + } + n.add_action(Action::Focus); + nodes.push((*id, n)); + } + group.set_children(ids); + nodes.push((CONTROLS, group)); + children.push(CONTROLS); + if let Some(i) = p.focus + && s.help.is_none() + { + focus = control_id(i); + } + } let mut status = Node::new(Role::Status); status.set_live(Live::Polite); if let Some(text) = s.status { @@ -107,6 +212,17 @@ pub fn tree(s: &Snapshot) -> TreeUpdate { } nodes.push((STATUS, status)); children.push(STATUS); + for (i, id) in ANNOUNCE.into_iter().enumerate() { + let mut n = Node::new(Role::Status); + n.set_live(Live::Polite); + if let Some((text, flip)) = &s.announce + && usize::from(*flip) == i + { + n.set_value(text.clone()); + } + nodes.push((id, n)); + children.push(id); + } root.set_children(children); nodes.push((ROOT, root)); TreeUpdate { nodes, tree: Some(TreeInfo::new(ROOT)), tree_id: TreeId::ROOT, focus } @@ -175,8 +291,66 @@ impl A11y { mod tests { use super::*; + #[test] + fn the_player_has_named_buttons_toggles_and_sliders() { + let mut s = snap(); + s.video = true; + s.player = Some(PlayerSnap { + controls: vec![ + ControlSnap { name: "Previous: beach.mkv".into(), kind: ControlKind::Button, bounds: Rect::new(16.0, 810.0, 60.0, 854.0) }, + ControlSnap { name: "Play".into(), kind: ControlKind::Toggle(true), bounds: Rect::new(64.0, 810.0, 108.0, 854.0) }, + ControlSnap { + name: "Position".into(), + kind: ControlKind::Slider { min: 0.0, max: 296.0, value: 83.0, step: 5.0, text: "1:23 of 4:56".into() }, + bounds: Rect::new(300.0, 810.0, 900.0, 854.0), + }, + ], + focus: Some(2), + song: None, + }); + let t = tree(&s); + let node = |id: NodeId| &t.nodes.iter().find(|(i, _)| *i == id).unwrap().1; + assert_eq!(node(PICTURE).role(), Role::Video); + assert_eq!(node(control_id(0)).label(), Some("Previous: beach.mkv")); + assert_eq!(node(control_id(1)).toggled(), Some(accesskit::Toggled::True)); + let slider = node(control_id(2)); + assert_eq!(slider.role(), Role::Slider); + assert_eq!(slider.value(), Some("1:23 of 4:56")); + assert_eq!(slider.numeric_value(), Some(83.0)); + assert!(slider.supports_action(Action::Increment) && slider.supports_action(Action::SetValue)); + assert_eq!(t.focus, control_id(2), "the focused control has the focus"); + assert_eq!(control_index(control_id(2)), Some(2)); + assert_eq!(control_index(tile_id(0)), None); + } + + #[test] + fn the_same_words_twice_land_in_different_nodes() { + let mut s = snap(); + let value = |t: &TreeUpdate, id: NodeId| t.nodes.iter().find(|(i, _)| *i == id).and_then(|(_, n)| n.value().map(str::to_string)); + s.announce = Some(("1:23 of 4:56".into(), false)); + let a = tree(&s); + s.announce = Some(("1:23 of 4:56".into(), true)); + let b = tree(&s); + assert_eq!((value(&a, ANNOUNCE[0]).as_deref(), value(&a, ANNOUNCE[1])), (Some("1:23 of 4:56"), None)); + assert_eq!((value(&b, ANNOUNCE[0]), value(&b, ANNOUNCE[1]).as_deref()), (None, Some("1:23 of 4:56"))); + s.announce = None; + let c = tree(&s); + assert_eq!((value(&c, ANNOUNCE[0]), value(&c, ANNOUNCE[1])), (None, None), "said once, then gone"); + } + fn snap() -> Snapshot<'static> { - Snapshot { title: "photo.jpg (3 of 12)", picture: "photo.jpg, 3 of 12".into(), bounds: Rect::new(0.0, 0.0, 10.0, 10.0), info: None, help: None, grid: None, status: None } + Snapshot { + title: "photo.jpg (3 of 12)", + picture: "photo.jpg, 3 of 12".into(), + bounds: Rect::new(0.0, 0.0, 10.0, 10.0), + info: None, + help: None, + grid: None, + status: None, + player: None, + video: false, + announce: None, + } } #[test] diff --git a/src/app.rs b/src/app.rs index 2d58339..ec0c471 100644 --- a/src/app.rs +++ b/src/app.rs @@ -24,6 +24,9 @@ use crate::ui::{self, Anchor, GridLayout}; use crate::view::{self, View}; use crate::wl::{Cursor, Input, Mods, Offer, Producer, Wl}; +mod player_ui; +use player_ui::Controls; + const BTN_LEFT: u32 = 0x110; const TOAST_FOR: Duration = crate::tokens::motion::TOAST; @@ -92,6 +95,27 @@ pub struct App { /// Carried from one video or song to the next. pub volume: f64, pub muted: bool, + /// The player's control bar. + controls: Controls, + icons: crate::player::icons::Icons, + /// The player's overlay, premultiplied ARGB at the window's size, and what changed. + pub overlay: Vec, + overlay_damage: Rect, + /// What the screen reader is to be told, until the next tree carries it. + announcement: Option, + /// Which of the two announcement nodes it goes in, so the same words twice are still + /// a change, and said again. + announce_flip: bool, + /// When to say the position after seeking by key. + seek_said_at: Option, + last_click: Option, + /// Full screen was asked for where the Wayland connection isn't at hand. + toggle_fullscreen: bool, + /// The video or song the grid closed, where it was, and whether it was playing, to + /// pick up from there when it opens again. + resume: Option<(PathBuf, f64, bool)>, + /// In full screen, as the compositor last said. + fullscreen: bool, } impl App { @@ -136,6 +160,17 @@ impl App { media: None, volume: 100.0, muted: false, + controls: Controls::default(), + icons: Default::default(), + overlay: Vec::new(), + overlay_damage: Rect::default(), + announcement: None, + announce_flip: false, + seek_said_at: None, + last_click: None, + toggle_fullscreen: false, + resume: None, + fullscreen: false, } } @@ -207,21 +242,20 @@ impl App { self.ask_current(); self.grid_follow(); } - let size = self.media.as_ref().map(|m| self.media_box(m.kind)); + if changed { + self.overlay_all(); + } + let size = self.media.as_ref().map(|m| m.kind).map(|k| self.media_box(k)); if let (Some(m), Some(b)) = (&mut self.media, size) { m.resize((b.w.max(1) as u32, b.h.max(1) as u32)); } } /// Where a video's frames or a song's cover art go, in physical px. - fn media_box(&self, kind: player::Kind) -> Rect { - let (w, h) = (self.win.0 as i32, self.win.1 as i32); + fn media_box(&mut self, kind: player::Kind) -> Rect { match kind { - player::Kind::Video => Rect::new(0, 0, w, h), - player::Kind::Music => { - let side = ui::px(crate::tokens::size::COVER_ART as f64, self.scale).min(w.min(h) / 2).max(1); - Rect::new((w - side) / 2, (h - side) / 2, side, side) - } + player::Kind::Video => Rect::new(0, 0, self.win.0 as i32, self.win.1 as i32), + player::Kind::Music => self.music_layout().cover, } } @@ -229,9 +263,17 @@ impl App { /// it isn't, and acts on what the player has said. Called on every turn of the loop. pub fn sync_media(&mut self, wl: &mut Wl) { let want = if self.grid.is_some() { None } else { self.path().and_then(|p| Some((p.to_path_buf(), player::kind_of(p)?))) }; + // The place kept for the file the grid closed lasts only until the grid closes: + // onto that file it's used just below; onto any other, it's dropped. + if self.grid.is_none() && self.resume.as_ref().is_some_and(|(p, ..)| self.path() != Some(p.as_path())) { + self.resume = None; + } match want { Some((path, _)) if self.media.as_ref().is_some_and(|m| m.path == path) => {} Some((path, kind)) => { + // The keyboard focus stays on the same control from one file to the next + // (Next pressed again goes on), except Full screen, which a song hasn't. + let focus = self.controls.focus.filter(|f| kind == player::Kind::Video || *f != crate::player::bar::Control::FullScreen); self.close_media(wl); // Full screen carries from one video to the next; a song has no full screen. if kind != player::Kind::Video && wl.state.fullscreen { @@ -239,11 +281,24 @@ impl App { } let b = self.media_box(kind); let size = (b.w.max(1) as u32, b.h.max(1) as u32); + let resume = self.resume.take().filter(|(p, ..)| *p == path).map(|(_, at, play)| (at, play)); self.media = Some(if wl.can_show_video() { - Media::open(path, kind, player::gpu::open_node(wl.render_node_path().as_deref()), size, self.volume, self.muted) + let mut m = Media::open(path, kind, player::gpu::open_node(wl.render_node_path().as_deref()), size, self.volume, self.muted); + // Paused before: paused from the start, so nothing plays before the seek. + if resume.is_some_and(|(_, play)| !play) { + m.send(player::gpu::Command::Pause); + } + m.resume = resume; + m } else { Media::failed(path, kind, "this desktop can't show video from another process (it lacks linux-dmabuf or viewporter)".into()) }); + self.controls = Controls { focus, ..Controls::default() }; + self.seek_said_at = None; + let opening = format!("Opening {}", self.name()); + self.say(opening); + self.poke_controls(Instant::now()); + self.after_media_news(None); self.all(); self.a11y_dirty = true; } @@ -258,17 +313,34 @@ impl App { } } } + if std::mem::take(&mut self.toggle_fullscreen) { + wl.set_fullscreen(!wl.state.fullscreen); + } + if wl.state.fullscreen != self.fullscreen { + self.fullscreen = wl.state.fullscreen; + self.overlay_all(); + self.a11y_dirty = true; + } let Some(kind) = self.media.as_ref().map(|m| m.kind) else { return }; let b = self.media_box(kind); let scale = self.scale; if let Some(m) = &mut self.media { m.replace(wl, b, scale); } - if let Some(m) = &mut self.media - && m.pump(wl, b, scale) - { - self.all(); + let Some(m) = &mut self.media else { return }; + let before = (m.phase(), m.has_picture, m.meta.clone()); + if m.pump(wl, b, scale) { + let after = (m.phase(), m.has_picture, m.meta.clone()); + // The window under the video, and the overlay's cover corners, change only with + // these; otherwise only the bar has news. + if after != before { + self.all(); + self.overlay_all(); + } else { + self.overlay_bar(); + } self.a11y_dirty = true; + self.after_media_news(Some(before.0)); } } @@ -278,8 +350,13 @@ impl App { self.volume = old.state.volume; self.muted = old.state.muted; } + // Opening the grid closes the player; back from it, the file picks up here. + self.resume = (self.grid.is_some() && old.heard && old.error.is_none() && !old.state.ended).then(|| (old.path.clone(), old.state.position, old.phase() == Phase::Playing)); drop(old); wl.video_end(); + wl.overlay_end(); + self.controls = Controls::default(); + self.seek_said_at = None; } } @@ -549,9 +626,11 @@ impl App { // and an overlay that's gone mustn't be moved along by a pan. self.damage = Rect::new(0, 0, self.win.0 as i32, self.win.1 as i32); self.drawn = None; + self.overlay_all(); } pub fn expire(&mut self, now: Instant) { + self.expire_controls(now); if self.toast.as_ref().is_some_and(|(_, until)| now >= *until) { self.toast = None; self.redraw_overlays(); @@ -563,7 +642,7 @@ impl App { /// hasn't shown the last frame, as when the window is hidden: an animation waits for /// that instead of decoding frames nobody sees. pub fn next_deadline(&self, shown: bool) -> Option { - [self.toast.as_ref().map(|(_, t)| *t), self.anim_due.filter(|_| self.playing && shown && !self.anim_waiting)].into_iter().flatten().min() + [self.toast.as_ref().map(|(_, t)| *t), self.anim_due.filter(|_| self.playing && shown && !self.anim_waiting), self.controls_deadline()].into_iter().flatten().min() } fn ensure_text(&mut self) -> Option<&mut Text> { @@ -617,6 +696,14 @@ impl App { // Input. pub fn input(&mut self, wl: &mut Wl, ev: Input) { + if self.media.is_some() && self.grid.is_none() { + if let Input::Move { x, y } = ev { + self.pointer = (x * self.scale, y * self.scale); + } + if self.media_pointer(wl, &ev) { + return; + } + } match ev { Input::Key { keysym, utf8, mods, repeat } => self.key(wl, keysym, &utf8, mods, repeat), Input::Move { x, y } => { @@ -731,32 +818,8 @@ impl App { if self.grid.is_some() && self.grid_key(sym) { return; } - if self.grid.is_none() - && let Some(m) = &mut self.media - { - match sym { - k::KEY_space => { - m.toggle(); - return; - } - // In a video or song, Left and Right seek; n, p, Page Up and Page Down still - // change file (Mike, 2026-12-02). - // Seeking needs a file that's playing; otherwise they change file, as for pictures. - k::KEY_Left | k::KEY_KP_Left | k::KEY_Right | k::KEY_KP_Right if m.heard && m.error.is_none() => { - let step = crate::tokens::motion::SEEK_STEP.as_secs_f64(); - m.send(player::gpu::Command::SeekBy(if matches!(sym, k::KEY_Left | k::KEY_KP_Left) { -step } else { step })); - return; - } - k::KEY_f if m.kind == player::Kind::Video => { - wl.set_fullscreen(!wl.state.fullscreen); - return; - } - k::KEY_Escape if wl.state.fullscreen && !(self.show_help || self.show_info) => { - wl.set_fullscreen(false); - return; - } - _ => {} - } + if self.media_key(wl, sym, mods.shift) { + return; } let img = self.img(); let zoomed = img.is_some_and(|img| self.view.zoomed(img, self.win)); @@ -819,11 +882,14 @@ impl App { if n == 0 { return; } + // "picture" while the list is all pictures, as before; "file" once it has videos or songs. + let any_media = self.files.iter().any(|f| player::kind_of(f).is_some()); + let word = |picture: &'static str, file: &'static str| if any_media { file } else { picture }; if n == 1 { if repeat { - self.toast_held("This is the only picture"); + self.toast_held(word("This is the only picture", "This is the only file")); } else { - self.toast("This is the only picture"); + self.toast(word("This is the only picture", "This is the only file")); } return; } @@ -831,9 +897,9 @@ impl App { if (0..n as isize).contains(&next) { self.go(next as usize); } else if repeat { - self.toast_held(if next < 0 { "This is the first picture" } else { "This is the last picture" }); + self.toast_held(if next < 0 { word("This is the first picture", "This is the first file") } else { word("This is the last picture", "This is the last file") }); } else { - let (to, msg) = if next < 0 { (n - 1, "Back to the last picture") } else { (0, "Back to the first picture") }; + let (to, msg) = if next < 0 { (n - 1, word("Back to the last picture", "Back to the last file")) } else { (0, word("Back to the first picture", "Back to the first file")) }; self.go(to); self.toast(msg); } @@ -999,7 +1065,10 @@ impl App { // Past the size limit there's no full-size copy to make a PNG of: only the file goes. let whole = self.img().map_or(Ok(()), |(w, h)| crate::pixels::check_size(w, h)); let mut mimes: Vec<(String, Producer)> = Vec::new(); - if whole.is_ok() { + // A video or song goes as the file only: no picture to make, and the picture + // decoders never see it. + let media = player::kind_of(&path).is_some(); + if whole.is_ok() && !media { mimes.push(("image/png".into(), make_png)); } // The file as it is, too, when it's a type other programs commonly take. @@ -1098,7 +1167,11 @@ impl App { if self.grid.is_some() { self.paint_grid(damage); } else if self.media.is_some() { + // The bar, toasts and the key list go on the overlay above the video. self.paint_media(damage, media_message.as_deref()); + self.paint_music(damage); + self.find_fallbacks(); + return damage; } else { damage = self.paint_picture(damage); } @@ -1257,21 +1330,11 @@ impl App { // Accessibility. - pub fn snapshot_tree(&self) -> accesskit::TreeUpdate { + pub fn snapshot_tree(&mut self) -> accesskit::TreeUpdate { let title = self.window_title(); let picture = match self.current() { _ if self.files.is_empty() => "No pictures left".to_string(), - _ if self.media.is_some() => { - let state = match self.media.as_ref().map(Media::phase) { - Some(Phase::Opening) => "opening".to_string(), - Some(Phase::Playing) => "playing".to_string(), - Some(Phase::Paused) => "paused".to_string(), - Some(Phase::Ended) => "ended".to_string(), - Some(Phase::Failed(why)) => format!("can't be played: {why}"), - None => String::new(), - }; - format!("{}, {} of {}, {state}", self.name(), self.cur + 1, self.files.len()) - } + _ if self.media.is_some() => self.media_label().unwrap_or_default(), Some(p) if p.error.is_some() => format!("{}, {} of {}, can't be shown: {}", self.name(), self.cur + 1, self.files.len(), p.error.as_deref().unwrap_or("")), Some(p) if p.screen.is_none() => format!("{}, {} of {}, loading", self.name(), self.cur + 1, self.files.len()), _ => format!("{}, {} of {}", self.name(), self.cur + 1, self.files.len()), @@ -1284,19 +1347,29 @@ impl App { } None => accesskit::Rect::new(0.0, 0.0, self.win.0 as f64 / s, self.win.1 as f64 / s), }; + let player = if self.grid.is_none() { self.player_snap() } else { None }; + let video = self.media.as_ref().is_some_and(|m| m.kind == player::Kind::Video); + let keys = if self.media.is_some() { ui::PLAYER_KEYS } else { ui::KEYS }; let snap = Snapshot { title: &title, picture, bounds, info: self.show_info.then(|| self.info_rows()), - help: self.show_help.then(|| ui::KEYS.to_vec()), + help: self.show_help.then(|| keys.to_vec()), grid: self.grid.as_ref().map(|g| (self.files.iter().map(|p| Self::name_of(p)).collect(), g.focus)), status: self.toast.as_ref().map(|(m, _)| m.as_str()), + // Said once: published in this tree, then gone from the next. + announce: self.announcement.take().map(|a| (a, self.announce_flip)), + player, + video, }; a11y::tree(&snap) } pub fn a11y_action(&mut self, req: accesskit::ActionRequest) { + if self.player_action(&req) { + return; + } let Some(i) = a11y::tile_index(req.target_node) else { return }; if i >= self.files.len() { return; diff --git a/src/app/player_ui.rs b/src/app/player_ui.rs new file mode 100644 index 0000000..cc527d4 --- /dev/null +++ b/src/app/player_ui.rs @@ -0,0 +1,683 @@ +//! The player's controls in the viewer: keys, the pointer, the control bar's showing and +//! hiding, what the screen reader is told, and the overlay the bar is drawn on. The design +//! is the canvas's Player rows and its "Player · Keys, screen reader, questions" board, with +//! Mike's decisions of 2026-12-02. + +use std::time::Instant; + +use xkbcommon::xkb::keysyms as k; + +use super::App; +use crate::a11y::{ControlKind, ControlSnap, PlayerSnap}; +use crate::canvas::{Canvas, Rect}; +use crate::player::bar::{self, Control, Layout, MusicLayout}; +use crate::player::icons::Icon; +use crate::player::{Kind, Phase, clock}; +use crate::tokens::{motion, scale}; +use crate::ui; +use crate::wl::{Input, Wl}; + +const BTN_LEFT: u32 = 0x110; + +/// The control bar's state. +#[derive(Default)] +pub struct Controls { + /// Keyboard focus, in the bar. While it's there the bar stays. + pub focus: Option, + pub hover: Option, + /// A slider held down with the pointer. + pub drag: Option, + pub shown: bool, + pub hide_at: Option, +} + +/// Whether the bar may hide by itself: only while a video plays, with no keyboard focus or +/// drag in it (Mike, 2026-12-02: paused, ended, music and a focus in the bar keep it). +pub fn may_hide(kind: Kind, phase: &Phase, focus: Option, drag: Option) -> bool { + kind == Kind::Video && *phase == Phase::Playing && focus.is_none() && drag.is_none() +} + +/// Whether the pointer is hidden: with the bar, once the bar hid by itself over a playing +/// video (Mike, 2026-12-02). What brings the bar back, as any pointer motion, brings it back. +pub fn hides_pointer(kind: Kind, phase: &Phase, shown: bool) -> bool { + kind == Kind::Video && *phase == Phase::Playing && !shown +} + +impl App { + /// Whether the pointer is hidden over the window now. + pub fn pointer_hidden(&self) -> bool { + self.grid.is_none() && self.media.as_ref().is_some_and(|m| hides_pointer(m.kind, &m.phase(), self.controls.shown)) + } + + /// Something happened: show the bar, and hide it `controls-hide` later if it may. + pub(super) fn poke_controls(&mut self, now: Instant) { + let Some(m) = &self.media else { return }; + let may = may_hide(m.kind, &m.phase(), self.controls.focus, self.controls.drag); + if !self.controls.shown { + self.controls.shown = true; + self.overlay_all(); + } + self.controls.hide_at = may.then(|| now + motion::CONTROLS_HIDE); + } + + /// The bar's time to hide came: hides it if it still may. + pub(super) fn expire_controls(&mut self, now: Instant) { + if self.controls.hide_at.is_some_and(|t| now >= t) { + self.controls.hide_at = None; + let may = self.media.as_ref().is_some_and(|m| may_hide(m.kind, &m.phase(), self.controls.focus, self.controls.drag)); + if may && self.controls.shown { + self.controls.shown = false; + self.controls.hover = None; + self.overlay_all(); + } + } + if self.seek_said_at.is_some_and(|t| now >= t) { + self.seek_said_at = None; + if let Some(text) = self.media.as_ref().map(|m| m.position_text()) { + self.say(text); + } + } + } + + /// The next time the player needs the loop to wake. + pub(super) fn controls_deadline(&self) -> Option { + [self.controls.hide_at, self.seek_said_at].into_iter().flatten().min() + } + + /// Tells the screen reader, politely. + pub(super) fn say(&mut self, text: String) { + self.announcement = Some(text); + self.announce_flip = !self.announce_flip; + self.a11y_dirty = true; + } + + /// The whole overlay needs drawing again. + pub(super) fn overlay_all(&mut self) { + self.overlay_damage = Rect::new(0, 0, self.win.0 as i32, self.win.1 as i32); + } + + /// Only the bar changed. + pub(super) fn overlay_bar(&mut self) { + if let Some(l) = self.bar_layout() { + self.overlay_damage = self.overlay_damage.union(l.bar); + } + } + + /// The bar's layout for this window, for the media open now. + pub(super) fn bar_layout(&mut self) -> Option { + let m = self.media.as_ref()?; + let full = m.kind == Kind::Video; + let template: String = format!("{} / {}", clock(m.state.duration), clock(m.state.duration)).chars().map(|c| if c.is_ascii_digit() { '0' } else { c }).collect(); + let (w, h, scale) = (self.win.0 as i32, self.win.1 as i32, self.scale); + let tw = self.ensure_text().map_or(0, |t| t.measure(&template).ceil() as i32); + Some(Layout::new(w, h, scale, tw, full)) + } + + /// The music view's layout. + pub(super) fn music_layout(&mut self) -> MusicLayout { + let (w, h, scale) = (self.win.0 as i32, self.win.1 as i32, self.scale); + // Without a font, the line the type tokens give. + let line = self.ensure_text().map_or(ui::px(crate::text::UI_PX as f64 * scale::LINE_HEIGHT as f64, scale), |t| ui::line_height(t)); + MusicLayout::new(w, h, scale, line) + } + + /// After the player said something: what changed is announced, the bar redrawn, a song + /// that ended goes on to the next song in the folder, and the bar's hiding follows the + /// new state. + pub(super) fn after_media_news(&mut self, before: Option) { + // Back from the grid: once loaded, the file picks up where it was. + if let Some(m) = &mut self.media + && m.heard + && let Some((at, play)) = m.resume.take() + { + m.seek_to(at); + if !play { + // Already asked at open; this covers a helper that took the play first. + m.send(crate::player::gpu::Command::Pause); + } + } + let Some(m) = &self.media else { return }; + let now = m.phase(); + let (kind, duration, position) = (m.kind, m.state.duration, m.state.position); + if before.as_ref() != Some(&now) { + let name = self.name(); + let said = match (&before, &now) { + (_, Phase::Failed(why)) => Some(format!("Can't play {name}: {why}")), + (Some(Phase::Opening) | None, Phase::Playing) => Some(format!("Playing {name}, {}", clock(duration))), + (Some(Phase::Opening) | None, Phase::Paused) => Some(format!("{name}, {}, paused", clock(duration))), + (_, Phase::Paused) => Some(format!("Paused at {}", clock(position))), + (_, Phase::Playing) => Some("Playing".to_string()), + (_, Phase::Ended) if kind == Kind::Video => Some(format!("Ended at {}, on the last frame. Space plays it again.", clock(duration))), + (_, Phase::Ended) => Some(format!("Ended at {}", clock(duration))), + (_, Phase::Opening) => None, + }; + if let Some(s) = said { + self.say(s); + } + self.poke_controls(Instant::now()); + self.overlay_bar(); + } + if now == Phase::Ended && kind == Kind::Music { + self.next_song(); + } + } + + /// A song ended: the next song in the folder plays, once; after the last, it stops. + fn next_song(&mut self) { + let Some(m) = &mut self.media else { return }; + if m.advanced { + return; + } + m.advanced = true; + let next = (self.cur + 1..self.files.len()).find(|i| crate::player::kind_of(&self.files[*i]) == Some(Kind::Music)); + if let Some(i) = next { + self.go(i); + } + } + + /// Keys for a video or song. True if the key was the player's. + pub(super) fn media_key(&mut self, wl: &mut Wl, sym: u32, shift: bool) -> bool { + if self.media.is_none() || self.grid.is_some() { + return false; + } + self.poke_controls(Instant::now()); + let focus = self.controls.focus; + let step = motion::SEEK_STEP.as_secs_f64(); + let vol = scale::VOLUME_STEP as f64; + match sym { + k::KEY_Tab | k::KEY_ISO_Left_Tab => { + self.move_focus(if shift || sym == k::KEY_ISO_Left_Tab { -1 } else { 1 }); + true + } + k::KEY_Return | k::KEY_KP_Enter if focus.is_some_and(|f| !f.is_slider()) => { + self.activate(focus.expect("checked")); + true + } + k::KEY_space if focus.is_some_and(|f| !f.is_slider()) => { + self.activate(focus.expect("checked")); + true + } + k::KEY_space | k::KEY_k | k::KEY_XF86AudioPlay => { + self.toggle_media(); + true + } + k::KEY_XF86AudioPause | k::KEY_XF86AudioStop => { + if self.media.as_ref().is_some_and(|m| m.phase() == Phase::Playing) { + self.toggle_media(); + } + true + } + // A file that can't play has nothing to seek: Left and Right change file, as for + // pictures. + k::KEY_Left | k::KEY_KP_Left | k::KEY_Right | k::KEY_KP_Right if focus.is_none() && self.media.as_ref().is_some_and(|m| !m.heard || m.error.is_some()) => false, + k::KEY_Left | k::KEY_KP_Left | k::KEY_Right | k::KEY_KP_Right | k::KEY_Up | k::KEY_KP_Up | k::KEY_Down | k::KEY_KP_Down => { + let up = matches!(sym, k::KEY_Right | k::KEY_KP_Right | k::KEY_Up | k::KEY_KP_Up); + let sideways = matches!(sym, k::KEY_Left | k::KEY_KP_Left | k::KEY_Right | k::KEY_KP_Right); + // Arrows move a focused slider; otherwise Left and Right seek and Up and + // Down set the volume. + let volume = match focus { + Some(Control::Volume) => true, + Some(Control::Position) => false, + _ => !sideways, + }; + if volume { + self.nudge_volume(if up { vol } else { -vol }); + } else { + self.seek_by_key(if up { step } else { -step }); + } + true + } + k::KEY_XF86AudioRaiseVolume => { + self.nudge_volume(vol); + true + } + k::KEY_XF86AudioLowerVolume => { + self.nudge_volume(-vol); + true + } + k::KEY_Home | k::KEY_KP_Home => { + self.seek_by_key(f64::NEG_INFINITY); + true + } + k::KEY_m | k::KEY_XF86AudioMute => { + self.toggle_mute(); + true + } + k::KEY_f if self.media.as_ref().is_some_and(|m| m.kind == Kind::Video) => { + wl.set_fullscreen(!wl.state.fullscreen); + true + } + k::KEY_Escape if wl.state.fullscreen && !(self.show_help || self.show_info) => { + wl.set_fullscreen(false); + true + } + k::KEY_XF86AudioNext => { + self.step(1, false); + true + } + k::KEY_XF86AudioPrev => { + self.step(-1, false); + true + } + k::KEY_t => { + // Said each time, even unchanged: each announcement goes in the other node. + if let Some(text) = self.media.as_ref().map(|m| m.position_text()) { + self.say(text); + } + true + } + // Picture info and zoom don't apply to a video or song. + k::KEY_i | k::KEY_plus | k::KEY_equal | k::KEY_KP_Add | k::KEY_minus | k::KEY_KP_Subtract | k::KEY_0 | k::KEY_1 => true, + _ => false, + } + } + + fn move_focus(&mut self, by: i32) { + let Some(l) = self.bar_layout() else { return }; + let order: Vec = l.controls().collect(); + if order.is_empty() { + return; + } + // Past either end, focus leaves the bar, so it can hide again. + let next = match self.controls.focus.and_then(|f| order.iter().position(|c| *c == f)) { + None if by > 0 => Some(order[0]), + None => order.last().copied(), + Some(i) => { + let j = i as i32 + by; + (0..order.len() as i32).contains(&j).then(|| order[j as usize]) + } + }; + self.controls.focus = next; + self.poke_controls(Instant::now()); + self.overlay_bar(); + self.a11y_dirty = true; + } + + /// Presses a button. + pub(super) fn activate(&mut self, c: Control) { + match c { + Control::Previous => self.step(-1, false), + Control::Play => self.toggle_media(), + Control::Next => self.step(1, false), + Control::Mute => self.toggle_mute(), + // Done in sync_media, which has the Wayland connection. + Control::FullScreen => self.toggle_fullscreen = true, + Control::Position | Control::Volume => {} + } + } + + fn toggle_media(&mut self) { + if let Some(m) = &mut self.media { + m.toggle(); + } + } + + fn toggle_mute(&mut self) { + let Some(m) = &mut self.media else { return }; + let on = !m.state.muted; + m.set_muted(on); + let text = if on { "Muted".to_string() } else { format!("Volume {:.0}%", m.state.volume) }; + self.say(text); + self.overlay_bar(); + self.a11y_dirty = true; + } + + fn nudge_volume(&mut self, by: f64) { + let Some(m) = &mut self.media else { return }; + let v = (m.state.volume + by).clamp(0.0, 100.0); + m.set_volume(v); + self.say(format!("Volume {v:.0}%")); + self.overlay_bar(); + } + + /// Seeks by a key: the position is said once the keys stop (`seek-announce`). + fn seek_by_key(&mut self, by: f64) { + let Some(m) = &mut self.media else { return }; + if by == f64::NEG_INFINITY { + m.seek_to(0.0); + } else { + m.seek_by(by); + } + self.seek_said_at = Some(Instant::now() + motion::SEEK_ANNOUNCE); + self.overlay_bar(); + self.a11y_dirty = true; + } + + /// The pointer, over a video or song. True if it was the player's. + pub(super) fn media_pointer(&mut self, wl: &mut Wl, ev: &Input) -> bool { + if self.media.is_none() || self.grid.is_some() { + return false; + } + let now = Instant::now(); + let (x, y) = (self.pointer.0 as i32, self.pointer.1 as i32); + match *ev { + Input::Move { .. } => { + let was_shown = self.controls.shown; + self.poke_controls(now); + let l = self.bar_layout(); + if let (Some(c), Some(l)) = (self.controls.drag, l) { + self.slide(c, l, x); + } + let hover = if was_shown { l.and_then(|l| l.hit(x, y)) } else { None }; + if hover != self.controls.hover { + self.controls.hover = hover; + self.overlay_bar(); + } + true + } + Input::Leave => { + if self.controls.hover.take().is_some() { + self.overlay_bar(); + } + false + } + Input::Button { button: BTN_LEFT, pressed } => { + if !pressed { + if self.controls.drag.take().is_some() { + self.poke_controls(now); + } + return true; + } + // A click on a hidden bar only shows it. + let hit = if self.controls.shown { self.bar_layout().and_then(|l| l.hit(x, y)) } else { None }; + self.poke_controls(now); + match hit { + Some(c) if c.is_slider() => { + self.controls.drag = Some(c); + if let Some(l) = self.bar_layout() { + self.slide(c, l, x); + } + } + Some(c) => self.activate(c), + None => { + let inside_bar = self.bar_layout().is_some_and(|l| l.bar.contains(x, y)); + let double = self.last_click.is_some_and(|t| now.duration_since(t) <= motion::DOUBLE_CLICK); + if double && !inside_bar && self.media.as_ref().is_some_and(|m| m.kind == Kind::Video) { + wl.set_fullscreen(!wl.state.fullscreen); + self.last_click = None; + } else { + self.last_click = Some(now); + } + } + } + true + } + _ => false, + } + } + + /// The pointer at `x` on a slider sets its value. + fn slide(&mut self, c: Control, l: Layout, x: i32) { + let Some(r) = l.rect(c) else { return }; + let f = bar::fraction_at(r, self.scale, x); + let Some(m) = &mut self.media else { return }; + match c { + Control::Position => m.seek_to(f * m.state.duration), + Control::Volume => m.set_volume(f * 100.0), + _ => {} + } + self.overlay_bar(); + self.a11y_dirty = true; + } + + /// Draws the overlay where it changed: the bar if it's shown, a toast, the key list. + /// Returns what changed, or `None` if nothing is to be shown at all. + pub fn paint_overlay(&mut self) -> Option { + let (w, h) = (self.win.0 as i32, self.win.1 as i32); + let damage = std::mem::take(&mut self.overlay_damage).intersect(Rect::new(0, 0, w, h)); + let failed = self.media.as_ref().is_some_and(|m| matches!(m.phase(), Phase::Failed(_))); + let anything = (self.controls.shown && !failed) || self.toast.is_some() || self.show_help; + if !anything { + return None; + } + if damage.is_empty() { + return Some(damage); + } + self.overlay.resize((w * h) as usize, 0); + let layout = self.bar_layout(); + let colors = self.colors.opaque(); + let scale = self.scale; + let toast = self.toast.as_ref().map(|(m, _)| m.clone()); + let help = self.show_help; + let m = self.media.as_ref()?; + // Different shapes for each state, not colour: replay at the end, pause while playing. + let play_icon = match m.phase() { + Phase::Ended => Icon::Replay, + Phase::Playing => Icon::Pause, + _ => Icon::Play, + }; + let d = m.state.duration.max(0.0); + let position = if m.state.ended { + 1.0 + } else if d > 0.0 { + m.state.position / d + } else { + 0.0 + }; + let (time, total) = (clock(if m.state.ended { d } else { m.state.position }), if m.heard { format!(" / {}", clock(d)) } else { " / -:--".to_string() }); + let (muted, volume) = (m.state.muted, m.state.volume / 100.0); + // A file that can't play shows its reason alone, as the canvas has it. + let failed = matches!(m.phase(), Phase::Failed(_)); + let cover = (m.kind == Kind::Music && m.has_picture == Some(true)).then_some(()); + let (focus, hover, shown) = (self.controls.focus, self.controls.hover, self.controls.shown && !failed); + let cover = cover.map(|()| self.music_layout().cover); + let t = self.text.as_mut()?; + let mut c = Canvas::new(&mut self.overlay, w, h); + c.set_clip(damage); + c.fill(damage, 0); + if let Some(r) = cover { + bar::round_corners(&mut c, r, ui::px(ui::RADIUS, scale), colors.base); + } + if shown && let Some(l) = layout { + let v = bar::View { play_icon, muted, position, volume, time: &time, total: &total, focus, hover }; + bar::paint(&mut c, t, &mut self.icons, &colors, scale, &l, &v); + } + if help { + let rows: Vec<(String, String)> = ui::PLAYER_KEYS.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(); + ui::draw_rows(&mut c, t, &colors, scale, "Keys", &rows, ui::Anchor::Centre); + } + if let Some(msg) = toast { + let above = if shown { layout.map_or(h, |l| l.bar.y) } else { h }; + ui::draw_toast(&mut c, t, &colors, scale, &msg, above); + } + Some(damage) + } + + /// The window under a song: the panel for no cover art, the title and the byline. + pub(super) fn paint_music(&mut self, c_damage: Rect) { + let Some(m) = &self.media else { return }; + if m.kind != Kind::Music || m.has_picture.is_none() && m.error.is_none() && !m.heard { + return; + } + let (title, byline, no_art) = (m.title(), m.byline(" · "), m.has_picture == Some(false)); + let l = self.music_layout(); + let (w, h) = (self.win.0 as i32, self.win.1 as i32); + let colors = self.colors; + let scale = self.scale; + let Some(t) = self.text.as_mut() else { return }; + let mut c = Canvas::new(&mut self.frame, w, h); + c.set_clip(c_damage); + if no_art { + bar::paint_no_art(&mut c, &mut self.icons, &colors, scale, l.cover); + } + let margin = ui::px(ui::MARGIN, scale); + let max = (w - margin * 2) as f32; + let tw = t.measure(&title).min(max); + t.draw_fitted(&mut c, &title, (w as f32 - tw) / 2.0, l.title_y, max, colors.foreground); + if let Some(b) = byline { + let bw = t.measure(&b).min(max); + t.draw_fitted(&mut c, &b, (w as f32 - bw) / 2.0, l.byline_y, max, colors.muted); + } + } +} + +impl App { + /// The player as the screen reader finds it, with the controls in Tab order. + pub(super) fn player_snap(&mut self) -> Option { + let l = self.bar_layout()?; + let fullscreen = self.fullscreen; + let s = self.scale.max(1e-6); + let n = self.files.len().max(1); + let name_at = |i: usize| self.files.get(i % n).and_then(|p| p.file_name()).map(|f| f.to_string_lossy().into_owned()).unwrap_or_default(); + let (prev, next) = (name_at(self.cur + n - 1), name_at(self.cur + 1)); + let m = self.media.as_ref()?; + let phase = m.phase(); + let step = motion::SEEK_STEP.as_secs_f64(); + let mut controls = Vec::new(); + for c in l.controls() { + let r = l.rect(c).expect("listed"); + let bounds = accesskit::Rect::new(r.x as f64 / s, r.y as f64 / s, r.right() as f64 / s, r.bottom() as f64 / s); + let (name, kind) = match c { + Control::Previous => (format!("Previous: {prev}"), ControlKind::Button), + Control::Next => (format!("Next: {next}"), ControlKind::Button), + Control::Play if phase == Phase::Ended => ("Play again from the start".into(), ControlKind::Button), + Control::Play => ("Play".into(), ControlKind::Toggle(phase == Phase::Playing)), + Control::Position => { + let d = m.state.duration.max(0.0); + let value = if m.state.ended { d } else { m.state.position.clamp(0.0, d) }; + ("Position".into(), ControlKind::Slider { min: 0.0, max: d, value, step, text: m.position_text() }) + } + Control::Mute => ("Mute".into(), ControlKind::Toggle(m.state.muted)), + Control::Volume => { + let value = if m.state.muted { 0.0 } else { m.state.volume }; + ("Volume".into(), ControlKind::Slider { min: 0.0, max: 100.0, value, step: scale::VOLUME_STEP as f64, text: m.volume_text() }) + } + Control::FullScreen => ("Full screen".into(), ControlKind::Toggle(fullscreen)), + }; + controls.push(ControlSnap { name, kind, bounds }); + } + let focus = self.controls.focus.and_then(|f| l.controls().position(|c| c == f)); + let song = (m.kind == Kind::Music).then(|| (m.title(), m.byline(", "))); + Some(PlayerSnap { controls, focus, song }) + } + + /// What the picture node says for a video or song. + pub(super) fn media_label(&self) -> Option { + let m = self.media.as_ref()?; + let place = format!("{}, {} of {}", self.name(), self.cur + 1, self.files.len()); + Some(match (m.kind, m.phase(), m.has_picture) { + (_, Phase::Failed(why), _) => format!("{place}, can't be played: {why}"), + (_, Phase::Opening, _) => format!("{place}, opening"), + (Kind::Music, _, Some(true)) => format!("Cover art of {}", m.title()), + (Kind::Music, _, _) => "No cover art".into(), + (Kind::Video, Phase::Playing, _) => format!("{place}, playing"), + (Kind::Video, Phase::Paused, _) => format!("{place}, paused"), + (Kind::Video, Phase::Ended, _) => format!("{place}, ended"), + }) + } + + /// A screen reader acted on a player control. True if it was one. + pub(super) fn player_action(&mut self, req: &accesskit::ActionRequest) -> bool { + let Some(i) = crate::a11y::control_index(req.target_node) else { return false }; + let Some(l) = self.bar_layout() else { return false }; + let Some(c) = l.controls().nth(i) else { return true }; + self.poke_controls(Instant::now()); + match req.action { + accesskit::Action::Click => self.activate(c), + accesskit::Action::Focus => { + self.controls.focus = Some(c); + self.overlay_bar(); + } + accesskit::Action::Increment | accesskit::Action::Decrement => { + let up = req.action == accesskit::Action::Increment; + match c { + Control::Position => self.seek_by_key(if up { motion::SEEK_STEP.as_secs_f64() } else { -motion::SEEK_STEP.as_secs_f64() }), + Control::Volume => self.nudge_volume(if up { scale::VOLUME_STEP as f64 } else { -(scale::VOLUME_STEP as f64) }), + _ => {} + } + } + accesskit::Action::SetValue => { + if let Some(accesskit::ActionData::NumericValue(v)) = req.data + && v.is_finite() + && let Some(m) = &mut self.media + { + match c { + Control::Position => m.seek_to(v), + Control::Volume => m.set_volume(v), + _ => {} + } + self.overlay_bar(); + } + } + _ => {} + } + self.a11y_dirty = true; + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_bar_hides_only_while_a_video_plays_with_no_focus_in_it() { + assert!(may_hide(Kind::Video, &Phase::Playing, None, None)); + assert!(!may_hide(Kind::Video, &Phase::Paused, None, None)); + assert!(!may_hide(Kind::Video, &Phase::Ended, None, None)); + assert!(!may_hide(Kind::Video, &Phase::Opening, None, None)); + assert!(!may_hide(Kind::Video, &Phase::Failed("x".into()), None, None)); + assert!(!may_hide(Kind::Music, &Phase::Playing, None, None)); + assert!(!may_hide(Kind::Video, &Phase::Playing, Some(Control::Play), None)); + assert!(!may_hide(Kind::Video, &Phase::Playing, None, Some(Control::Position))); + } + + /// A viewer with `name` open in the player, as the helper said it: playing, paused or + /// ended. No helper runs: the file can't be opened, and then is told it was. + fn playing(name: &str, paused: bool, ended: bool) -> App { + let path = std::path::PathBuf::from(format!("/nowhere/{name}")); + let kind = crate::player::kind_of(&path).expect("a video or song"); + let mut a = App::new(vec![path.clone()], 0, crate::theme::builtin(true), crate::loader::Loader::new(1), 1); + a.resize(400, 300, 1.0); + let mut m = crate::player::Media::failed(path, kind, String::new()); + (m.error, m.heard) = (None, true); + (m.state.paused, m.state.ended, m.state.duration) = (paused, ended, 60.0); + a.media = Some(m); + a + } + + #[test] + fn the_pointer_hides_with_the_bar_while_a_video_plays_and_motion_brings_it_back() { + let t = Instant::now(); + let mut a = playing("clip.mp4", false, false); + a.poke_controls(t); + assert!(!a.pointer_hidden(), "shown with the bar"); + a.expire_controls(t + motion::CONTROLS_HIDE - std::time::Duration::from_millis(1)); + assert!(a.controls.shown && !a.pointer_hidden(), "not before the bar hides"); + a.expire_controls(t + motion::CONTROLS_HIDE); + assert!(!a.controls.shown && a.pointer_hidden(), "hidden with the bar"); + // Motion over the window pokes the bar, as media_pointer does. + a.poke_controls(t + motion::CONTROLS_HIDE * 2); + assert!(a.controls.shown && !a.pointer_hidden(), "back on motion"); + // A pause while hidden brings it back too. + a.expire_controls(t + motion::CONTROLS_HIDE * 3); + assert!(a.pointer_hidden()); + a.media.as_mut().expect("open").state.paused = true; + assert!(!a.pointer_hidden(), "shown once paused"); + // The grid over it shows it. + a.media.as_mut().expect("open").state.paused = false; + a.grid = Some(super::super::Grid { focus: 0, scroll: 0 }); + assert!(!a.pointer_hidden(), "shown in the grid"); + } + + #[test] + fn the_pointer_never_hides_for_music_or_a_paused_or_ended_video_or_with_focus_in_the_bar() { + let t = Instant::now(); + let later = t + motion::CONTROLS_HIDE * 2; + for (name, paused, ended) in [("song.mp3", false, false), ("clip.mp4", true, false), ("clip.mp4", false, true)] { + let mut a = playing(name, paused, ended); + a.poke_controls(t); + a.expire_controls(later); + assert!(a.controls.shown && !a.pointer_hidden(), "{name} paused {paused} ended {ended}"); + } + let mut a = playing("clip.mp4", false, false); + a.controls.focus = Some(Control::Play); + a.poke_controls(t); + a.expire_controls(later); + assert!(a.controls.shown && !a.pointer_hidden(), "keyboard focus keeps the bar and the pointer"); + assert!(!hides_pointer(Kind::Video, &Phase::Opening, false)); + assert!(!hides_pointer(Kind::Video, &Phase::Failed("x".into()), false)); + assert!(!hides_pointer(Kind::Music, &Phase::Playing, false)); + assert!(hides_pointer(Kind::Video, &Phase::Playing, false)); + } +} diff --git a/src/args.rs b/src/args.rs index 5e493a7..7054c9c 100644 --- a/src/args.rs +++ b/src/args.rs @@ -7,7 +7,7 @@ use std::path::{Path, PathBuf}; use crate::decode::is_picture_name; use crate::sort::natural_cmp; -pub const USAGE: &str = "Usage: alias-view FILE...\n alias-view FOLDER\n\nShows pictures. One file opens with the rest of its folder; several files are\nshown in the order given; a folder opens at its first picture.\n"; +pub const USAGE: &str = "Usage: alias-view FILE...\n alias-view FOLDER\n\nShows pictures and plays videos and songs. One file opens with the rest of its\nfolder; several files are shown in the order given; a folder opens at its first file.\n"; #[derive(Debug, PartialEq)] pub enum Command { @@ -78,7 +78,7 @@ pub fn parse(args: Vec, cwd: &Path) -> Result { if p.is_dir() { let files = list_folder(&p, None); if files.is_empty() { - return Err(format!("no pictures in {}", p.display())); + return Err(format!("no pictures, videos or songs in {}", p.display())); } return Ok(Command::View(Opening { files, start: 0, folder_of: None })); } @@ -146,8 +146,8 @@ fn file_uri_path(uri: &[u8]) -> Option { Some(PathBuf::from(OsString::from_vec(out))) } -/// The pictures in a folder, in Gannet's natural order. Hidden files stay hidden, as in -/// Gannet, and only picture extensions count, except `include`: it's what was asked for, +/// The pictures, videos and songs in a folder, in Gannet's natural order. Hidden files stay +/// hidden, as in Gannet, and only those extensions count, except `include`: it's what was asked for, /// and opened by its bytes, so it stays in the list whatever its name. pub fn list_folder(dir: &Path, include: Option<&Path>) -> Vec { let Ok(rd) = std::fs::read_dir(dir) else { return include.map(|p| vec![p.to_path_buf()]).unwrap_or_default() }; diff --git a/src/canvas.rs b/src/canvas.rs index 65fd428..36e5421 100644 --- a/src/canvas.rs +++ b/src/canvas.rs @@ -109,6 +109,11 @@ impl<'a> Canvas<'a> { } } + /// One pixel blended toward `color` by `a` (0 to 255), inside the clip. + pub fn blend_at(&mut self, x: i32, y: i32, color: u32, a: u32) { + self.blend_px(x, y, color, a); + } + fn blend_px(&mut self, x: i32, y: i32, color: u32, a: u32) { if self.clip.contains(x, y) { let p = &mut self.px[(y * self.w + x) as usize]; @@ -152,7 +157,7 @@ impl<'a> Canvas<'a> { for row in area.y..area.bottom() { for col in area.x..area.right() { let m = ((row - y) * mw + (col - x)) as usize * 4; - let c = (data[m] as u32) << 16 | (data[m + 1] as u32) << 8 | data[m + 2] as u32; + let c = 0xff00_0000 | (data[m] as u32) << 16 | (data[m + 1] as u32) << 8 | data[m + 2] as u32; let p = &mut self.px[(row * self.w + col) as usize]; *p = blend(*p, c, data[m + 3] as u32); } @@ -160,7 +165,9 @@ impl<'a> Canvas<'a> { } } -/// Blends two XRGB colors. `a` is 0 to 255. +/// Blends two colors. `a` is 0 to 255. The top byte is blended too, so on the player's +/// overlay, whose pixels are premultiplied ARGB, an opaque colour (top byte 0xff) drawn +/// with coverage `a` over a clear pixel comes out right; in an XRGB frame it's ignored. #[inline] pub fn blend(dst: u32, src: u32, a: u32) -> u32 { // Widened so weights run 0 to 256 and the shift is exact at both ends. @@ -168,7 +175,13 @@ pub fn blend(dst: u32, src: u32, a: u32) -> u32 { let ia = 256 - a; let rb = (((src & 0xff00ff) * a + (dst & 0xff00ff) * ia) >> 8) & 0xff00ff; let g = (((src & 0x00ff00) * a + (dst & 0x00ff00) * ia) >> 8) & 0x00ff00; - rb | g + let alpha = ((((src >> 24) * a + (dst >> 24) * ia) >> 8) & 0xff) << 24; + rb | g | alpha +} + +/// `color` as an opaque premultiplied ARGB pixel, for the player's overlay. +pub const fn opaque(color: u32) -> u32 { + color | 0xff00_0000 } #[cfg(test)] @@ -208,4 +221,14 @@ mod tests { assert_eq!(blend(0x123456, 0xabcdef, 255), 0xabcdef); assert_eq!(blend(0x000000, 0xffffff, 128) & 0xff, 128); } + + #[test] + fn an_opaque_colour_over_clear_comes_out_premultiplied() { + assert_eq!(blend(0, opaque(0x204060), 255), 0xff20_4060); + assert_eq!(blend(0, opaque(0x204060), 0), 0); + let half = blend(0, opaque(0xffffff), 128); + assert!((half >> 24).abs_diff(128) <= 1 && (half & 0xff).abs_diff(128) <= 1, "{half:08x}"); + assert!((half & 0xff) <= half >> 24, "never brighter than its alpha"); + assert_eq!(blend(opaque(0x102030), 0x405060, 0) >> 24, 0xff, "an opaque pixel stays opaque"); + } } diff --git a/src/main.rs b/src/main.rs index 16fd5c2..d756d3d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -90,6 +90,10 @@ fn main() { for (k, v) in ui::KEYS { println!(" {k:<22} {v}"); } + println!("\nIn a video or song:"); + for (k, v) in ui::PLAYER_KEYS { + println!(" {k:<22} {v}"); + } 0 } Ok(Command::Version) => { @@ -300,6 +304,7 @@ fn run(o: Opening) -> i32 { } } app.expire(now); + wl.hide_cursor(app.pointer_hidden()); if wl.can_paint() { app.animate(now); } @@ -367,6 +372,14 @@ fn run(o: Opening) -> i32 { mark(stamp, "accessibility started"); } } + // The player's bar, toasts and key list, above the video. + if wl.state.configured && app.media.is_some() { + match app.paint_overlay() { + Some(d) if !d.is_empty() => wl.overlay_present(&app.overlay, d), + Some(_) => {} + None => wl.overlay_hide(), + } + } if app.a11y_dirty && let Some(a) = &mut a11y { diff --git a/src/player/bar.rs b/src/player/bar.rs new file mode 100644 index 0000000..d903b2e --- /dev/null +++ b/src/player/bar.rs @@ -0,0 +1,358 @@ +//! The player's control bar and music view, as the design canvas draws them (the Player +//! artboards): an opaque bar of `controls-height` along the window's foot with Previous, +//! Play, Next, the time, the position, Mute, the volume and Full screen, each target 44 px. +//! Every size is a token; colours are the theme's roles. +//! +//! Nothing is told by colour alone: play, pause and replay are different icons, the played +//! part of a slider is thicker than the rest, and hover fills the button behind its icon. + +use crate::canvas::{Canvas, Rect}; +use crate::player::icons::{Icon, Icons}; +use crate::text::Text; +use crate::theme::Colors; +use crate::tokens::{radius, size, spacing}; +use crate::ui::{self, px}; + +/// The bar's controls, in Tab order. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Control { + Previous, + Play, + Next, + Position, + Mute, + Volume, + FullScreen, +} + +impl Control { + pub const ORDER: [Control; 7] = [Control::Previous, Control::Play, Control::Next, Control::Position, Control::Mute, Control::Volume, Control::FullScreen]; + + pub fn is_slider(self) -> bool { + matches!(self, Control::Position | Control::Volume) + } +} + +/// Where everything in the bar is, in physical px. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Layout { + pub bar: Rect, + pub previous: Rect, + pub play: Rect, + pub next: Rect, + /// The time's text box, `time-pad` inside either side. + pub time: Rect, + pub position: Rect, + pub mute: Rect, + pub volume: Rect, + /// Not in the music view. + pub full_screen: Option, +} + +impl Layout { + /// The bar across a `w`×`h` window. `time_w` is the time text's width; `full_screen` + /// whether the Full screen button is there (videos only). + pub fn new(w: i32, h: i32, scale: f64, time_w: i32, full_screen: bool) -> Layout { + let bar_h = px(size::CONTROLS_HEIGHT as f64, scale); + let target = px(size::TOUCH_TARGET as f64, scale); + let gap = px(spacing::CONTROLS_GAP as f64, scale); + let group = px(spacing::CONTROLS_GROUP_GAP as f64, scale); + let margin = px(ui::MARGIN, scale); + let time_pad = px(spacing::TIME_PAD as f64, scale); + let bar = Rect::new(0, h - bar_h, w, bar_h); + let y = bar.y + (bar_h - target) / 2; + let at = |x: i32| Rect::new(x, y, target, target); + let previous = at(margin); + let play = at(previous.right() + gap); + let next = at(play.right() + gap); + let time = Rect::new(next.right() + gap + time_pad, y, time_w.max(0), target); + // From the right: Full screen, Volume, Mute. + let mut right = w - margin; + let full_screen = full_screen.then(|| { + let r = at(right - target); + right = r.x - group; + r + }); + let volume = Rect::new(right - px(size::VOLUME_WIDTH as f64, scale), y, px(size::VOLUME_WIDTH as f64, scale), target); + let mute = at(volume.x - gap - target); + let start = time.right() + time_pad + gap; + let end = mute.x - group; + let position = Rect::new(start, y, (end - start).max(0), target); + Layout { bar, previous, play, next, time, position, mute, volume, full_screen } + } + + pub fn rect(&self, c: Control) -> Option { + match c { + Control::Previous => Some(self.previous), + Control::Play => Some(self.play), + Control::Next => Some(self.next), + Control::Position => Some(self.position), + Control::Mute => Some(self.mute), + Control::Volume => Some(self.volume), + Control::FullScreen => self.full_screen, + } + } + + /// The controls there are, in Tab order. + pub fn controls(&self) -> impl Iterator + '_ { + Control::ORDER.into_iter().filter(|c| self.rect(*c).is_some_and(|r| r.w > 0)) + } + + /// The control under a point, if any. + pub fn hit(&self, x: i32, y: i32) -> Option { + self.controls().find(|c| self.rect(*c).is_some_and(|r| r.contains(x, y))) + } +} + +/// Inside a slider's box, the track runs between the thumb's centres at either end. +fn track(r: Rect, scale: f64) -> (i32, i32) { + let half = px(size::SEEK_THUMB as f64, scale) / 2; + (r.x + half, (r.w - half * 2).max(1)) +} + +/// The fraction, 0 to 1, a point `x` sets on a slider in `r`. +pub fn fraction_at(r: Rect, scale: f64, x: i32) -> f64 { + let (x0, len) = track(r, scale); + ((x - x0) as f64 / len as f64).clamp(0.0, 1.0) +} + +/// What the bar shows now. +pub struct View<'a> { + pub play_icon: Icon, + pub muted: bool, + /// 0 to 1. + pub position: f64, + pub volume: f64, + pub time: &'a str, + /// " / 4:56", in muted. + pub total: &'a str, + pub focus: Option, + pub hover: Option, +} + +/// Draws the bar. `colors` are opaque (the overlay's). +pub fn paint(c: &mut Canvas, t: &mut Text, icons: &mut Icons, colors: &Colors, scale: f64, l: &Layout, v: &View) { + c.fill(l.bar, colors.panel); + let corner = px(radius::CORNER as f64, scale); + // The focused control last, so its ring isn't covered by a neighbour's hover. + let mut order: Vec = l.controls().filter(|c| Some(*c) != v.focus).collect(); + order.extend(v.focus.filter(|f| l.rect(*f).is_some())); + for control in order { + let r = l.rect(control).expect("listed"); + if v.focus == Some(control) { + ring(c, r, corner, colors, scale); + } + match control { + Control::Position => slider(c, r, v.position, colors, scale), + Control::Volume => slider(c, r, if v.muted { 0.0 } else { v.volume }, colors, scale), + _ => { + if v.hover == Some(control) { + c.rrect(r, corner, hover_fill(colors)); + } + let icon = match control { + Control::Previous => Icon::Previous, + Control::Play => v.play_icon, + Control::Next => Icon::Next, + Control::Mute if v.muted => Icon::Muted, + Control::Mute => Icon::Sound, + _ => Icon::FullScreen, + }; + let ipx = px(size::CONTROL_ICON as f64, scale); + let m = icons.mask(icon, ipx); + c.mask(m, ipx, ipx, r.x + (r.w - ipx) / 2, r.y + (r.h - ipx) / 2, colors.foreground); + } + } + } + // The time: now in foreground, the total in muted. + let y = l.time.y + ((l.time.h as f32 + t.ascent - t.descent) / 2.0) as i32; + let now = t.shape(v.time); + t.draw(c, &now, l.time.x as f32, y, colors.foreground); + let total = t.shape(v.total); + t.draw(c, &total, l.time.x as f32 + now.width, y, colors.muted); +} + +/// The fill behind a button under the pointer: `border`, unless a theme's border leaves +/// the icon below 3:1 on it; then moved toward `panel` until it passes. A theme can come +/// from anywhere, so this is held here, not only in the token check. +fn hover_fill(colors: &Colors) -> u32 { + use crate::theme::{blend, contrast}; + let (fg, border, panel) = (colors.foreground & 0xff_ffff, colors.border & 0xff_ffff, colors.panel & 0xff_ffff); + let alpha = colors.border & 0xff00_0000; + (0..=20).map(|i| blend(border, panel, i as f32 / 20.0)).find(|c| contrast(fg, *c) >= 3.0).map_or(colors.panel, |c| c | alpha) +} + +/// The focus ring: `focus-ring` thick, `ring-gap` outside the control, rounded like it. +fn ring(c: &mut Canvas, r: Rect, corner: i32, colors: &Colors, scale: f64) { + let ring = px(ui::RING, scale).max(2); + let gap = px(ui::RING_GAP, scale).max(1); + let grow = |r: Rect, by: i32| Rect::new(r.x - by, r.y - by, r.w + by * 2, r.h + by * 2); + c.rrect(grow(r, gap + ring), corner + gap + ring, colors.accent); + c.rrect(grow(r, gap), corner + gap, colors.panel); +} + +/// A slider: the track still to come thin in muted, the part played or set thicker in +/// accent, and a round thumb in foreground. +fn slider(c: &mut Canvas, r: Rect, value: f64, colors: &Colors, scale: f64) { + let (x0, len) = track(r, scale); + let cy = r.y + r.h / 2; + let thin = px(size::SEEK_TRACK as f64, scale).max(1); + let thick = px(size::SEEK_PLAYED as f64, scale).max(thin + 1); + let thumb = px(size::SEEK_THUMB as f64, scale); + let at = x0 + (value.clamp(0.0, 1.0) * len as f64).round() as i32; + c.fill(Rect::new(x0, cy - thin / 2, len, thin), colors.muted); + c.fill(Rect::new(x0, cy - thick / 2, at - x0, thick), colors.accent); + c.rrect(Rect::new(at - thumb / 2, cy - thumb / 2, thumb, thumb), thumb / 2, colors.foreground); +} + +/// Where the music view's cover and its two lines go, above the bar: a square of at most +/// `cover-art`, `cover-gap` above the title, all centred. +pub struct MusicLayout { + pub cover: Rect, + /// Baselines of the title and the "artist · album" line. + pub title_y: i32, + pub byline_y: i32, +} + +impl MusicLayout { + pub fn new(w: i32, h: i32, scale: f64, line_h: i32) -> MusicLayout { + let bar_h = px(size::CONTROLS_HEIGHT as f64, scale); + let gap = px(spacing::COVER_GAP as f64, scale); + let margin = px(ui::MARGIN, scale); + let area = (h - bar_h).max(1); + let text_h = line_h * 2; + let side = px(size::COVER_ART as f64, scale).min(w - margin * 2).min(area - text_h - gap - margin * 2).max(0); + let top = (area - (side + gap + text_h)) / 2; + let cover = Rect::new((w - side) / 2, top.max(0), side, side); + let title_y = cover.bottom() + gap + line_h * 3 / 4; + MusicLayout { cover, title_y, byline_y: title_y + line_h } + } +} + +/// Rounds the cover art's corners, which sit in a subsurface below: paints `color` (the +/// background) outside a quarter circle of `radius` in each corner of `r`, antialiased. +pub fn round_corners(c: &mut Canvas, r: Rect, radius: i32, color: u32) { + let radius = radius.min(r.w / 2).min(r.h / 2); + if radius <= 0 { + return; + } + let rf = radius as f32; + for i in 0..radius { + for j in 0..radius { + // Distance of the pixel's centre from the corner circle's centre. + let (dx, dy) = (rf - i as f32 - 0.5, rf - j as f32 - 0.5); + let outside = ((dx * dx + dy * dy).sqrt() - rf + 0.5).clamp(0.0, 1.0); + if outside <= 0.0 { + continue; + } + let a = (outside * 255.0).round() as u32; + for (x, y) in [(r.x + i, r.y + j), (r.right() - 1 - i, r.y + j), (r.x + i, r.bottom() - 1 - j), (r.right() - 1 - i, r.bottom() - 1 - j)] { + c.blend_at(x, y, color, a); + } + } + } +} + +/// The panel square a song with no cover art shows, with a note in muted. +pub fn paint_no_art(c: &mut Canvas, icons: &mut Icons, colors: &Colors, scale: f64, r: Rect) { + c.rrect(r, px(radius::CORNER as f64, scale), colors.panel); + let ipx = px(size::COVER_ICON as f64, scale).min(r.w); + let m = icons.mask(Icon::Note, ipx); + c.mask(m, ipx, ipx, r.x + (r.w - ipx) / 2, r.y + (r.h - ipx) / 2, colors.muted); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_bar_matches_the_canvas_at_1296_by_864() { + let l = Layout::new(1296, 864, 1.0, 92, true); + assert_eq!(l.bar, Rect::new(0, 800, 1296, 64)); + assert_eq!(l.previous, Rect::new(16, 810, 44, 44)); + assert_eq!(l.play.x, 64); + assert_eq!(l.next.x, 112); + assert_eq!(l.time.x, 112 + 44 + 4 + 12); + assert_eq!(l.full_screen, Some(Rect::new(1296 - 16 - 44, 810, 44, 44))); + assert_eq!(l.volume, Rect::new(1296 - 16 - 44 - 8 - 96, 810, 96, 44)); + assert_eq!(l.mute.right() + 4, l.volume.x); + assert_eq!(l.position.right() + 8, l.mute.x); + assert!(l.position.w > 600); + } + + #[test] + fn every_target_is_at_least_44_px_and_none_overlap() { + for (w, scale) in [(560, 1.0), (1296, 1.0), (560, 2.0), (1120, 2.0)] { + let l = Layout::new(w * scale as i32, 420 * scale as i32, scale, (92.0 * scale) as i32, true); + let rects: Vec = l.controls().map(|c| l.rect(c).unwrap()).collect(); + assert_eq!(rects.len(), 7, "every control fits at {w} px, x{scale}"); + for (i, a) in rects.iter().enumerate() { + assert!(a.h >= (44.0 * scale) as i32 && (a.w >= (44.0 * scale) as i32), "{a:?} at {w}, x{scale}"); + for b in &rects[i + 1..] { + assert!(!a.intersects(*b), "{a:?} and {b:?}"); + } + } + } + } + + #[test] + fn the_music_view_has_no_full_screen_and_tab_order_follows_the_bar() { + let l = Layout::new(1296, 864, 1.0, 92, false); + let order: Vec = l.controls().collect(); + assert_eq!(order, [Control::Previous, Control::Play, Control::Next, Control::Position, Control::Mute, Control::Volume]); + assert_eq!(l.hit(20, 820), Some(Control::Previous)); + assert_eq!(l.hit(20, 700), None); + } + + #[test] + fn a_slider_reads_from_thumb_centre_to_thumb_centre() { + let r = Rect::new(100, 0, 214, 44); + assert_eq!(fraction_at(r, 1.0, 107), 0.0); + assert_eq!(fraction_at(r, 1.0, 307), 1.0); + assert_eq!(fraction_at(r, 1.0, 207), 0.5); + assert_eq!(fraction_at(r, 1.0, 0), 0.0); + } + + #[test] + fn the_cover_is_at_most_320_and_shrinks_in_a_small_window() { + let big = MusicLayout::new(1296, 864, 1.0, 25); + assert_eq!((big.cover.w, big.cover.h), (320, 320)); + assert_eq!(big.cover.x, (1296 - 320) / 2); + let small = MusicLayout::new(560, 420, 1.0, 25); + assert!(small.cover.w < 320 && small.cover.w > 100, "{:?}", small.cover); + assert!(small.byline_y < 420 - 64, "the lines stay above the bar"); + } + + #[test] + fn cover_corners_are_rounded_and_the_middle_left_alone() { + let mut px = vec![0u32; 40 * 40]; + let mut c = Canvas::new(&mut px, 40, 40); + round_corners(&mut c, Rect::new(0, 0, 40, 40), 8, 0xff00_0009); + assert_eq!(px[0], 0xff00_0009, "the very corner is background"); + assert_eq!(px[39 * 40 + 39], 0xff00_0009); + assert_eq!(px[20 * 40 + 20], 0, "the middle is clear, so the art shows"); + assert_eq!(px[7 * 40 + 7], 0, "inside the curve is clear"); + } + + #[test] + fn hover_keeps_the_icon_at_3_to_1_in_any_theme() { + use crate::theme::contrast; + let shipped = crate::theme::builtin(true).opaque(); + assert_eq!(hover_fill(&shipped), shipped.border, "a theme that passes keeps its border"); + // A theme whose border is nearly its text colour. + let poor = Colors { dark: true, base: 0x101010, panel: 0x202020, border: 0xb8b8b8, foreground: 0xd0d0d0, muted: 0x909090, accent: 0x6080ff, danger: 0xff6060 }; + assert!(contrast(poor.foreground, poor.border) < 3.0); + let fill = hover_fill(&poor); + assert!(contrast(poor.foreground, fill & 0xff_ffff) >= 3.0, "{fill:06x}"); + } + + #[test] + fn played_is_thicker_than_the_rest() { + let colors = Colors { dark: true, base: 1, panel: 2, border: 3, foreground: 4, muted: 5, accent: 6, danger: 7 }; + let mut px = vec![0u32; 200 * 44]; + let mut c = Canvas::new(&mut px, 200, 44); + slider(&mut c, Rect::new(0, 0, 200, 44), 0.25, &colors, 1.0); + let column = |x: usize, colour: u32| (0..44).filter(|y| px[y * 200 + x] == colour).count(); + assert_eq!(column(30, 6), 4, "played: 4 px of accent"); + assert_eq!(column(150, 5), 2, "to come: 2 px of muted"); + } +} diff --git a/src/player/gpu.rs b/src/player/gpu.rs index 822710a..96dbff4 100644 --- a/src/player/gpu.rs +++ b/src/player/gpu.rs @@ -24,8 +24,6 @@ const EXIT_SANDBOX: i32 = 6; pub enum Command { Play, Pause, - /// By this many seconds, back if negative. - SeekBy(f64), /// To this many seconds from the start. SeekTo(f64), /// 0 to 100. @@ -43,7 +41,6 @@ impl Command { match self { Command::Play => "play".into(), Command::Pause => "pause".into(), - Command::SeekBy(s) => format!("seek {s:.3}"), Command::SeekTo(s) => format!("seekat {:.3}", s.max(0.0)), Command::Volume(v) => format!("volume {:.0}", v.clamp(0.0, 100.0)), Command::Mute(true) => "mute".into(), @@ -234,7 +231,6 @@ mod tests { #[test] fn commands_are_the_lines_the_helper_reads() { - assert_eq!(Command::SeekBy(-5.0).line(), "seek -5.000"); assert_eq!(Command::SeekTo(-1.0).line(), "seekat 0.000", "never before the start"); assert_eq!(Command::Volume(130.0).line(), "volume 100"); assert_eq!(Command::Mute(true).line(), "mute"); diff --git a/src/player/icons.rs b/src/player/icons.rs new file mode 100644 index 0000000..7ad16b3 --- /dev/null +++ b/src/player/icons.rs @@ -0,0 +1,95 @@ +//! The player's icons, from the design canvas: Lucide's (ISC licence, see LICENSE), drawn +//! with resvg into coverage masks the size of the control-icon token, and kept per size. + +use std::collections::HashMap; + +use resvg::{tiny_skia, usvg}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Icon { + Previous, + Play, + Pause, + Replay, + Next, + Sound, + Muted, + FullScreen, + /// In the panel a song with no cover art shows. + Note, +} + +impl Icon { + /// The SVG body: Lucide's paths, on a 24 px grid. + fn body(self) -> &'static str { + match self { + Icon::Previous => r#""#, + Icon::Play => r#""#, + Icon::Pause => r#""#, + Icon::Replay => r#""#, + Icon::Next => r#""#, + Icon::Sound => r#""#, + Icon::Muted => r#""#, + Icon::FullScreen => r#""#, + Icon::Note => r#""#, + } + } + + /// The canvas draws the big note thinner, as Lucide does at that size. + fn stroke(self) -> &'static str { + if self == Icon::Note { "1.5" } else { "2" } + } +} + +/// Masks already drawn, by icon and size in px. +#[derive(Default)] +pub struct Icons { + masks: HashMap<(Icon, i32), Vec>, +} + +impl Icons { + /// `icon` as a `px`×`px` coverage mask. + pub fn mask(&mut self, icon: Icon, px: i32) -> &[u8] { + let px = px.max(1); + self.masks.entry((icon, px)).or_insert_with(|| draw(icon, px)) + } +} + +fn draw(icon: Icon, px: i32) -> Vec { + let svg = format!( + r#"{}"#, + icon.stroke(), + icon.body() + ); + let size = px as usize * px as usize; + let Ok(tree) = usvg::Tree::from_str(&svg, &usvg::Options::default()) else { return vec![0; size] }; + let Some(mut pixmap) = tiny_skia::Pixmap::new(px as u32, px as u32) else { return vec![0; size] }; + let s = px as f32 / 24.0; + resvg::render(&tree, tiny_skia::Transform::from_scale(s, s), &mut pixmap.as_mut()); + pixmap.data().as_chunks::<4>().0.iter().map(|p| p[3]).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_icon_draws_something_inside_its_square() { + let mut icons = Icons::default(); + for icon in [Icon::Previous, Icon::Play, Icon::Pause, Icon::Replay, Icon::Next, Icon::Sound, Icon::Muted, Icon::FullScreen, Icon::Note] { + for px in [20, 40, 96] { + let m = icons.mask(icon, px); + assert_eq!(m.len(), (px * px) as usize); + let inked = m.iter().filter(|a| **a > 128).count(); + assert!(inked > (px * px) as usize / 50 && inked < (px * px) as usize / 2, "{icon:?} at {px}: {inked}"); + } + } + } + + #[test] + fn play_pause_and_replay_differ_in_shape() { + let mut icons = Icons::default(); + let (a, b, c) = (icons.mask(Icon::Play, 20).to_vec(), icons.mask(Icon::Pause, 20).to_vec(), icons.mask(Icon::Replay, 20).to_vec()); + assert!(a != b && b != c && a != c); + } +} diff --git a/src/player/mod.rs b/src/player/mod.rs index 1f5cb54..942e7c5 100644 --- a/src/player/mod.rs +++ b/src/player/mod.rs @@ -2,7 +2,9 @@ //! jailed GPU helper (`gpu`); its frames, or a song's cover art, show in a subsurface above //! the window. The window's own surface keeps the background and whatever is drawn over it. +pub mod bar; pub mod gpu; +pub mod icons; use std::os::fd::OwnedFd; use std::path::{Path, PathBuf}; @@ -81,6 +83,11 @@ pub struct Media { pub error: Option, /// The size asked of the helper, so it's only told of changes. asked: (u32, u32), + /// A song that ended has gone on to the next one (or found none), once. + pub advanced: bool, + /// Where to pick up once loaded, and whether to play: set when the same file opens + /// again after the grid closed it. + pub resume: Option<(f64, bool)>, /// Released by the compositor while still on screen: given back once replaced. released_early: [bool; VIDEO_SLOTS], /// The box the frame on screen was placed in. @@ -103,6 +110,8 @@ impl Media { meta: Meta::default(), error: None, asked: size, + advanced: false, + resume: None, released_early: [false; VIDEO_SLOTS], placed: None, }; @@ -120,9 +129,7 @@ impl Media { /// A media file that can't be opened at all, with why. pub fn failed(path: PathBuf, kind: Kind, why: String) -> Media { - let mut m = Media::open(path, kind, Err(why), (1, 1), 100.0, false); - m.session = None; - m + Media::open(path, kind, Err(why), (1, 1), 100.0, false) } pub fn phase(&self) -> Phase { @@ -162,6 +169,62 @@ impl Media { } } + /// Seeks by `by` seconds, and shows the new position at once. + pub fn seek_by(&mut self, by: f64) { + if !self.heard { + return; + } + let to = (self.state.position + by).clamp(0.0, self.state.duration.max(0.0)); + self.seek_to(to); + } + + /// Seeks to `at` seconds from the start, and shows it at once. + pub fn seek_to(&mut self, at: f64) { + if !self.heard { + return; + } + let at = at.clamp(0.0, self.state.duration.max(0.0)); + self.send(Command::SeekTo(at)); + self.state.position = at; + self.state.ended = self.state.ended && at >= self.state.duration; + } + + /// Sets the volume, 0 to 100; a change unmutes, as a volume control does. + pub fn set_volume(&mut self, v: f64) { + let v = v.clamp(0.0, 100.0).round(); + self.send(Command::Volume(v)); + self.state.volume = v; + if self.state.muted { + self.set_muted(false); + } + } + + pub fn set_muted(&mut self, on: bool) { + self.send(Command::Mute(on)); + self.state.muted = on; + } + + /// The position as the screen reader says it: "1:23 of 4:56". + pub fn position_text(&self) -> String { + if self.state.ended { format!("Ended at {}, on the last frame", clock(self.state.duration)) } else { format!("{} of {}", clock(self.state.position), clock(self.state.duration)) } + } + + /// The volume as the screen reader says it. + pub fn volume_text(&self) -> String { + if self.state.muted { format!("Muted, {:.0}% when unmuted", self.state.volume) } else { format!("{:.0}%", self.state.volume) } + } + + /// A song's title, or its file name without the extension. + pub fn title(&self) -> String { + self.meta.title.clone().unwrap_or_else(|| self.path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default()) + } + + /// "artist · album", or whichever there is, with `sep` between. + pub fn byline(&self, sep: &str) -> Option { + let parts: Vec<&str> = [self.meta.artist.as_deref(), self.meta.album.as_deref()].into_iter().flatten().collect(); + (!parts.is_empty()).then(|| parts.join(sep)) + } + /// The frame's box changed size (physical px). pub fn resize(&mut self, size: (u32, u32)) { if size != self.asked { @@ -350,6 +413,29 @@ mod tests { assert_eq!(clock(-4.0), "0:00"); } + #[test] + fn a_song_reads_its_tags_or_its_name() { + let mut m = Media::failed("/m/Night Drive.flac".into(), Kind::Music, "x".into()); + assert_eq!(m.title(), "Night Drive"); + assert_eq!(m.byline(" · "), None); + m.meta = Meta { title: Some("Night Drive".into()), artist: Some("The Test Signals".into()), album: Some("Calibration".into()) }; + assert_eq!(m.byline(" · ").as_deref(), Some("The Test Signals · Calibration")); + m.meta.artist = None; + assert_eq!(m.byline(", ").as_deref(), Some("Calibration")); + } + + #[test] + fn positions_and_volume_read_as_the_canvas_has_them() { + let mut m = Media::failed("/m/clip.mp4".into(), Kind::Video, "x".into()); + m.state = PlayState { position: 83.0, duration: 296.0, volume: 80.0, ..PlayState::default() }; + assert_eq!(m.position_text(), "1:23 of 4:56"); + assert_eq!(m.volume_text(), "80%"); + m.state.muted = true; + assert_eq!(m.volume_text(), "Muted, 80% when unmuted"); + m.state.ended = true; + assert_eq!(m.position_text(), "Ended at 4:56, on the last frame"); + } + #[test] fn a_buffer_let_go_while_on_screen_is_kept_until_replaced() { let mut m = Media::failed("/m/clip.mp4".into(), Kind::Video, "x".into()); diff --git a/src/theme.rs b/src/theme.rs index c32f4b8..fd29ebb 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -73,6 +73,24 @@ pub struct Colors { pub danger: Rgb, } +impl Colors { + /// The same colours as opaque premultiplied ARGB, for drawing on the player's overlay, + /// which is clear where nothing is drawn. + pub fn opaque(self) -> Colors { + use crate::canvas::opaque; + Colors { + dark: self.dark, + base: opaque(self.base), + panel: opaque(self.panel), + border: opaque(self.border), + foreground: opaque(self.foreground), + muted: opaque(self.muted), + accent: opaque(self.accent), + danger: opaque(self.danger), + } + } +} + /// Parses `colors.toml` by hand: only `key = "#rrggbb"` lines matter, and this is read /// before the first frame, so it's not worth a TOML dependency. Anything malformed is /// ignored. diff --git a/src/tokens.rs b/src/tokens.rs index 7b05002..1a00e6a 100644 --- a/src/tokens.rs +++ b/src/tokens.rs @@ -12,16 +12,16 @@ pub mod aliasos { /// Panels (Picture info, Keys), toasts, grid tiles before their thumbnail and the grid's caption bar: the background blended 8% toward the theme's text (src/theme.rs derive). pub const PANEL: u32 = 0x232A2E; - /// A panel's and toast's 1 px edge: the background blended 25% toward the theme's text. Decorative: panels aren't controls, so it isn't in the contrast list. Proposed (ALI-2358): also a player button's fill under the pointer, behind its icon in foreground. + /// A panel's and toast's 1 px edge: the background blended 25% toward the theme's text. Decorative: panels aren't controls, so it isn't in the contrast list. Also the fill of a player button under the pointer, behind its icon in foreground. pub const BORDER: u32 = 0x444B4F; /// Text: panel titles, values, toasts, the grid's caption, and the error and empty messages on the background. The theme's text, moved until it has 4.5:1 on panel and on base. pub const FOREGROUND: u32 = 0xD8DDE0; - /// Labels in a panel of rows (Name, Size; a key in the key list): foreground blended 35% toward panel, then held to 4.5:1 on panel. Proposed (ALI-2358): also the unplayed part of the seek and volume bars, the time's total, and the artist and album under a song's title. + /// Labels in a panel of rows (Name, Size; a key in the key list): foreground blended 35% toward panel, then held to 4.5:1 on panel. Also the unplayed part of the player's seek and volume bars, the time's total, and the artist and album under a song's title. pub const MUTED: u32 = 0x999EA2; - /// The grid's focus ring. The theme's accent (or color4, or blue), moved until it has 3:1 against base and panel, the two things it sits beside. Proposed (ALI-2358): also the played part of the player's seek and volume bars, and the focus ring around its buttons. + /// The grid's focus ring. The theme's accent (or color4, or blue), moved until it has 3:1 against base and panel, the two things it sits beside. Also the played part of the player's seek and volume bars, and the focus ring around its buttons. pub const ACCENT: u32 = 0x7F96A1; /// Errors. The theme's color1 (or red), held to 4.5:1 on panel. Derived but not drawn yet: error messages use foreground. @@ -36,16 +36,16 @@ pub mod aliasos_amber { /// Panels (Picture info, Keys), toasts, grid tiles before their thumbnail and the grid's caption bar: the background blended 8% toward the theme's text (src/theme.rs derive). pub const PANEL: u32 = 0x25211C; - /// A panel's and toast's 1 px edge: the background blended 25% toward the theme's text. Decorative: panels aren't controls, so it isn't in the contrast list. Proposed (ALI-2358): also a player button's fill under the pointer, behind its icon in foreground. + /// A panel's and toast's 1 px edge: the background blended 25% toward the theme's text. Decorative: panels aren't controls, so it isn't in the contrast list. Also the fill of a player button under the pointer, behind its icon in foreground. pub const BORDER: u32 = 0x49443E; /// Text: panel titles, values, toasts, the grid's caption, and the error and empty messages on the background. The theme's text, moved until it has 4.5:1 on panel and on base. pub const FOREGROUND: u32 = 0xE6DFD3; - /// Labels in a panel of rows (Name, Size; a key in the key list): foreground blended 35% toward panel, then held to 4.5:1 on panel. Proposed (ALI-2358): also the unplayed part of the seek and volume bars, the time's total, and the artist and album under a song's title. + /// Labels in a panel of rows (Name, Size; a key in the key list): foreground blended 35% toward panel, then held to 4.5:1 on panel. Also the unplayed part of the player's seek and volume bars, the time's total, and the artist and album under a song's title. pub const MUTED: u32 = 0xA29D93; - /// The grid's focus ring. The theme's accent (or color4, or blue), moved until it has 3:1 against base and panel, the two things it sits beside. Proposed (ALI-2358): also the played part of the player's seek and volume bars, and the focus ring around its buttons. + /// The grid's focus ring. The theme's accent (or color4, or blue), moved until it has 3:1 against base and panel, the two things it sits beside. Also the played part of the player's seek and volume bars, and the focus ring around its buttons. pub const ACCENT: u32 = 0xE0B36A; /// Errors. The theme's color1 (or red), held to 4.5:1 on panel. Derived but not drawn yet: error messages use foreground. @@ -60,16 +60,16 @@ pub mod aliasos_azure { /// Panels (Picture info, Keys), toasts, grid tiles before their thumbnail and the grid's caption bar: the background blended 8% toward the theme's text (src/theme.rs derive). pub const PANEL: u32 = 0x17232A; - /// A panel's and toast's 1 px edge: the background blended 25% toward the theme's text. Decorative: panels aren't controls, so it isn't in the contrast list. Proposed (ALI-2358): also a player button's fill under the pointer, behind its icon in foreground. + /// A panel's and toast's 1 px edge: the background blended 25% toward the theme's text. Decorative: panels aren't controls, so it isn't in the contrast list. Also the fill of a player button under the pointer, behind its icon in foreground. pub const BORDER: u32 = 0x3C464D; /// Text: panel titles, values, toasts, the grid's caption, and the error and empty messages on the background. The theme's text, moved until it has 4.5:1 on panel and on base. pub const FOREGROUND: u32 = 0xDCE2E6; - /// Labels in a panel of rows (Name, Size; a key in the key list): foreground blended 35% toward panel, then held to 4.5:1 on panel. Proposed (ALI-2358): also the unplayed part of the seek and volume bars, the time's total, and the artist and album under a song's title. + /// Labels in a panel of rows (Name, Size; a key in the key list): foreground blended 35% toward panel, then held to 4.5:1 on panel. Also the unplayed part of the player's seek and volume bars, the time's total, and the artist and album under a song's title. pub const MUTED: u32 = 0x979FA4; - /// The grid's focus ring. The theme's accent (or color4, or blue), moved until it has 3:1 against base and panel, the two things it sits beside. Proposed (ALI-2358): also the played part of the player's seek and volume bars, and the focus ring around its buttons. + /// The grid's focus ring. The theme's accent (or color4, or blue), moved until it has 3:1 against base and panel, the two things it sits beside. Also the played part of the player's seek and volume bars, and the focus ring around its buttons. pub const ACCENT: u32 = 0x5E9AC4; /// Errors. The theme's color1 (or red), held to 4.5:1 on panel. Derived but not drawn yet: error messages use foreground. @@ -84,16 +84,16 @@ pub mod aliasos_teal { /// Panels (Picture info, Keys), toasts, grid tiles before their thumbnail and the grid's caption bar: the background blended 8% toward the theme's text (src/theme.rs derive). pub const PANEL: u32 = 0x17262A; - /// A panel's and toast's 1 px edge: the background blended 25% toward the theme's text. Decorative: panels aren't controls, so it isn't in the contrast list. Proposed (ALI-2358): also a player button's fill under the pointer, behind its icon in foreground. + /// A panel's and toast's 1 px edge: the background blended 25% toward the theme's text. Decorative: panels aren't controls, so it isn't in the contrast list. Also the fill of a player button under the pointer, behind its icon in foreground. pub const BORDER: u32 = 0x3C494D; /// Text: panel titles, values, toasts, the grid's caption, and the error and empty messages on the background. The theme's text, moved until it has 4.5:1 on panel and on base. pub const FOREGROUND: u32 = 0xDCE2E6; - /// Labels in a panel of rows (Name, Size; a key in the key list): foreground blended 35% toward panel, then held to 4.5:1 on panel. Proposed (ALI-2358): also the unplayed part of the seek and volume bars, the time's total, and the artist and album under a song's title. + /// Labels in a panel of rows (Name, Size; a key in the key list): foreground blended 35% toward panel, then held to 4.5:1 on panel. Also the unplayed part of the player's seek and volume bars, the time's total, and the artist and album under a song's title. pub const MUTED: u32 = 0x97A0A4; - /// The grid's focus ring. The theme's accent (or color4, or blue), moved until it has 3:1 against base and panel, the two things it sits beside. Proposed (ALI-2358): also the played part of the player's seek and volume bars, and the focus ring around its buttons. + /// The grid's focus ring. The theme's accent (or color4, or blue), moved until it has 3:1 against base and panel, the two things it sits beside. Also the played part of the player's seek and volume bars, and the focus ring around its buttons. pub const ACCENT: u32 = 0x5EC4B6; /// Errors. The theme's color1 (or red), held to 4.5:1 on panel. Derived but not drawn yet: error messages use foreground. @@ -108,16 +108,16 @@ pub mod ayu_dark { /// Panels (Picture info, Keys), toasts, grid tiles before their thumbnail and the grid's caption bar: the background blended 8% toward the theme's text (src/theme.rs derive). pub const PANEL: u32 = 0x191C21; - /// A panel's and toast's 1 px edge: the background blended 25% toward the theme's text. Decorative: panels aren't controls, so it isn't in the contrast list. Proposed (ALI-2358): also a player button's fill under the pointer, behind its icon in foreground. + /// A panel's and toast's 1 px edge: the background blended 25% toward the theme's text. Decorative: panels aren't controls, so it isn't in the contrast list. Also the fill of a player button under the pointer, behind its icon in foreground. pub const BORDER: u32 = 0x383A3D; /// Text: panel titles, values, toasts, the grid's caption, and the error and empty messages on the background. The theme's text, moved until it has 4.5:1 on panel and on base. pub const FOREGROUND: u32 = 0xBFBDB6; - /// Labels in a panel of rows (Name, Size; a key in the key list): foreground blended 35% toward panel, then held to 4.5:1 on panel. Proposed (ALI-2358): also the unplayed part of the seek and volume bars, the time's total, and the artist and album under a song's title. + /// Labels in a panel of rows (Name, Size; a key in the key list): foreground blended 35% toward panel, then held to 4.5:1 on panel. Also the unplayed part of the player's seek and volume bars, the time's total, and the artist and album under a song's title. pub const MUTED: u32 = 0x858582; - /// The grid's focus ring. The theme's accent (or color4, or blue), moved until it has 3:1 against base and panel, the two things it sits beside. Proposed (ALI-2358): also the played part of the player's seek and volume bars, and the focus ring around its buttons. + /// The grid's focus ring. The theme's accent (or color4, or blue), moved until it has 3:1 against base and panel, the two things it sits beside. Also the played part of the player's seek and volume bars, and the focus ring around its buttons. pub const ACCENT: u32 = 0x53BDFA; /// Errors. The theme's color1 (or red), held to 4.5:1 on panel. Derived but not drawn yet: error messages use foreground. @@ -132,16 +132,16 @@ pub mod last_horizon { /// Panels (Picture info, Keys), toasts, grid tiles before their thumbnail and the grid's caption bar: the background blended 8% toward the theme's text (src/theme.rs derive). pub const PANEL: u32 = 0x1F1E1F; - /// A panel's and toast's 1 px edge: the background blended 25% toward the theme's text. Decorative: panels aren't controls, so it isn't in the contrast list. Proposed (ALI-2358): also a player button's fill under the pointer, behind its icon in foreground. + /// A panel's and toast's 1 px edge: the background blended 25% toward the theme's text. Decorative: panels aren't controls, so it isn't in the contrast list. Also the fill of a player button under the pointer, behind its icon in foreground. pub const BORDER: u32 = 0x484748; /// Text: panel titles, values, toasts, the grid's caption, and the error and empty messages on the background. The theme's text, moved until it has 4.5:1 on panel and on base. pub const FOREGROUND: u32 = 0xFAFCFB; - /// Labels in a panel of rows (Name, Size; a key in the key list): foreground blended 35% toward panel, then held to 4.5:1 on panel. Proposed (ALI-2358): also the unplayed part of the seek and volume bars, the time's total, and the artist and album under a song's title. + /// Labels in a panel of rows (Name, Size; a key in the key list): foreground blended 35% toward panel, then held to 4.5:1 on panel. Also the unplayed part of the player's seek and volume bars, the time's total, and the artist and album under a song's title. pub const MUTED: u32 = 0xADAEAE; - /// The grid's focus ring. The theme's accent (or color4, or blue), moved until it has 3:1 against base and panel, the two things it sits beside. Proposed (ALI-2358): also the played part of the player's seek and volume bars, and the focus ring around its buttons. + /// The grid's focus ring. The theme's accent (or color4, or blue), moved until it has 3:1 against base and panel, the two things it sits beside. Also the played part of the player's seek and volume bars, and the focus ring around its buttons. pub const ACCENT: u32 = 0xB59790; /// Errors. The theme's color1 (or red), held to 4.5:1 on panel. Derived but not drawn yet: error messages use foreground. @@ -156,16 +156,16 @@ pub mod matte_black { /// Panels (Picture info, Keys), toasts, grid tiles before their thumbnail and the grid's caption bar: the background blended 8% toward the theme's text (src/theme.rs derive). pub const PANEL: u32 = 0x202020; - /// A panel's and toast's 1 px edge: the background blended 25% toward the theme's text. Decorative: panels aren't controls, so it isn't in the contrast list. Proposed (ALI-2358): also a player button's fill under the pointer, behind its icon in foreground. + /// A panel's and toast's 1 px edge: the background blended 25% toward the theme's text. Decorative: panels aren't controls, so it isn't in the contrast list. Also the fill of a player button under the pointer, behind its icon in foreground. pub const BORDER: u32 = 0x3D3D3D; /// Text: panel titles, values, toasts, the grid's caption, and the error and empty messages on the background. The theme's text, moved until it has 4.5:1 on panel and on base. pub const FOREGROUND: u32 = 0xBEBEBE; - /// Labels in a panel of rows (Name, Size; a key in the key list): foreground blended 35% toward panel, then held to 4.5:1 on panel. Proposed (ALI-2358): also the unplayed part of the seek and volume bars, the time's total, and the artist and album under a song's title. + /// Labels in a panel of rows (Name, Size; a key in the key list): foreground blended 35% toward panel, then held to 4.5:1 on panel. Also the unplayed part of the player's seek and volume bars, the time's total, and the artist and album under a song's title. pub const MUTED: u32 = 0x878787; - /// The grid's focus ring. The theme's accent (or color4, or blue), moved until it has 3:1 against base and panel, the two things it sits beside. Proposed (ALI-2358): also the played part of the player's seek and volume bars, and the focus ring around its buttons. + /// The grid's focus ring. The theme's accent (or color4, or blue), moved until it has 3:1 against base and panel, the two things it sits beside. Also the played part of the player's seek and volume bars, and the focus ring around its buttons. pub const ACCENT: u32 = 0xE68E0D; /// Errors. The theme's color1 (or red), held to 4.5:1 on panel. Derived but not drawn yet: error messages use foreground. @@ -180,16 +180,16 @@ pub mod osaka_jade { /// Panels (Picture info, Keys), toasts, grid tiles before their thumbnail and the grid's caption bar: the background blended 8% toward the theme's text (src/theme.rs derive). pub const PANEL: u32 = 0x1F2922; - /// A panel's and toast's 1 px edge: the background blended 25% toward the theme's text. Decorative: panels aren't controls, so it isn't in the contrast list. Proposed (ALI-2358): also a player button's fill under the pointer, behind its icon in foreground. + /// A panel's and toast's 1 px edge: the background blended 25% toward the theme's text. Decorative: panels aren't controls, so it isn't in the contrast list. Also the fill of a player button under the pointer, behind its icon in foreground. pub const BORDER: u32 = 0x3D4638; /// Text: panel titles, values, toasts, the grid's caption, and the error and empty messages on the background. The theme's text, moved until it has 4.5:1 on panel and on base. pub const FOREGROUND: u32 = 0xC1C497; - /// Labels in a panel of rows (Name, Size; a key in the key list): foreground blended 35% toward panel, then held to 4.5:1 on panel. Proposed (ALI-2358): also the unplayed part of the seek and volume bars, the time's total, and the artist and album under a song's title. + /// Labels in a panel of rows (Name, Size; a key in the key list): foreground blended 35% toward panel, then held to 4.5:1 on panel. Also the unplayed part of the player's seek and volume bars, the time's total, and the artist and album under a song's title. pub const MUTED: u32 = 0x8E9475; - /// The grid's focus ring. The theme's accent (or color4, or blue), moved until it has 3:1 against base and panel, the two things it sits beside. Proposed (ALI-2358): also the played part of the player's seek and volume bars, and the focus ring around its buttons. + /// The grid's focus ring. The theme's accent (or color4, or blue), moved until it has 3:1 against base and panel, the two things it sits beside. Also the played part of the player's seek and volume bars, and the focus ring around its buttons. pub const ACCENT: u32 = 0x509475; /// Errors. The theme's color1 (or red), held to 4.5:1 on panel. Derived but not drawn yet: error messages use foreground. @@ -204,16 +204,16 @@ pub mod retro_82 { /// Panels (Picture info, Keys), toasts, grid tiles before their thumbnail and the grid's caption bar: the background blended 8% toward the theme's text (src/theme.rs derive). pub const PANEL: u32 = 0x182838; - /// A panel's and toast's 1 px edge: the background blended 25% toward the theme's text. Decorative: panels aren't controls, so it isn't in the contrast list. Proposed (ALI-2358): also a player button's fill under the pointer, behind its icon in foreground. + /// A panel's and toast's 1 px edge: the background blended 25% toward the theme's text. Decorative: panels aren't controls, so it isn't in the contrast list. Also the fill of a player button under the pointer, behind its icon in foreground. pub const BORDER: u32 = 0x41494E; /// Text: panel titles, values, toasts, the grid's caption, and the error and empty messages on the background. The theme's text, moved until it has 4.5:1 on panel and on base. pub const FOREGROUND: u32 = 0xF6DCAC; - /// Labels in a panel of rows (Name, Size; a key in the key list): foreground blended 35% toward panel, then held to 4.5:1 on panel. Proposed (ALI-2358): also the unplayed part of the seek and volume bars, the time's total, and the artist and album under a song's title. + /// Labels in a panel of rows (Name, Size; a key in the key list): foreground blended 35% toward panel, then held to 4.5:1 on panel. Also the unplayed part of the player's seek and volume bars, the time's total, and the artist and album under a song's title. pub const MUTED: u32 = 0xA89D83; - /// The grid's focus ring. The theme's accent (or color4, or blue), moved until it has 3:1 against base and panel, the two things it sits beside. Proposed (ALI-2358): also the played part of the player's seek and volume bars, and the focus ring around its buttons. + /// The grid's focus ring. The theme's accent (or color4, or blue), moved until it has 3:1 against base and panel, the two things it sits beside. Also the played part of the player's seek and volume bars, and the focus ring around its buttons. pub const ACCENT: u32 = 0xFAA968; /// Errors. The theme's color1 (or red), held to 4.5:1 on panel. Derived but not drawn yet: error messages use foreground. @@ -228,16 +228,16 @@ pub mod light { /// Panels (Picture info, Keys), toasts, grid tiles before their thumbnail and the grid's caption bar: the background blended 8% toward the theme's text (src/theme.rs derive). pub const PANEL: u32 = 0xE8E9E9; - /// A panel's and toast's 1 px edge: the background blended 25% toward the theme's text. Decorative: panels aren't controls, so it isn't in the contrast list. Proposed (ALI-2358): also a player button's fill under the pointer, behind its icon in foreground. + /// A panel's and toast's 1 px edge: the background blended 25% toward the theme's text. Decorative: panels aren't controls, so it isn't in the contrast list. Also the fill of a player button under the pointer, behind its icon in foreground. pub const BORDER: u32 = 0xC3C4C6; /// Text: panel titles, values, toasts, the grid's caption, and the error and empty messages on the background. The theme's text, moved until it has 4.5:1 on panel and on base. pub const FOREGROUND: u32 = 0x1F2328; - /// Labels in a panel of rows (Name, Size; a key in the key list): foreground blended 35% toward panel, then held to 4.5:1 on panel. Proposed (ALI-2358): also the unplayed part of the seek and volume bars, the time's total, and the artist and album under a song's title. + /// Labels in a panel of rows (Name, Size; a key in the key list): foreground blended 35% toward panel, then held to 4.5:1 on panel. Also the unplayed part of the player's seek and volume bars, the time's total, and the artist and album under a song's title. pub const MUTED: u32 = 0x65686C; - /// The grid's focus ring. The theme's accent (or color4, or blue), moved until it has 3:1 against base and panel, the two things it sits beside. Proposed (ALI-2358): also the played part of the player's seek and volume bars, and the focus ring around its buttons. + /// The grid's focus ring. The theme's accent (or color4, or blue), moved until it has 3:1 against base and panel, the two things it sits beside. Also the played part of the player's seek and volume bars, and the focus ring around its buttons. pub const ACCENT: u32 = 0x2F6FEB; /// Errors. The theme's color1 (or red), held to 4.5:1 on panel. Derived but not drawn yet: error messages use foreground. @@ -252,16 +252,16 @@ pub mod dark { /// Panels (Picture info, Keys), toasts, grid tiles before their thumbnail and the grid's caption bar: the background blended 8% toward the theme's text (src/theme.rs derive). pub const PANEL: u32 = 0x2A2C30; - /// A panel's and toast's 1 px edge: the background blended 25% toward the theme's text. Decorative: panels aren't controls, so it isn't in the contrast list. Proposed (ALI-2358): also a player button's fill under the pointer, behind its icon in foreground. + /// A panel's and toast's 1 px edge: the background blended 25% toward the theme's text. Decorative: panels aren't controls, so it isn't in the contrast list. Also the fill of a player button under the pointer, behind its icon in foreground. pub const BORDER: u32 = 0x4A4D51; /// Text: panel titles, values, toasts, the grid's caption, and the error and empty messages on the background. The theme's text, moved until it has 4.5:1 on panel and on base. pub const FOREGROUND: u32 = 0xD8DBE0; - /// Labels in a panel of rows (Name, Size; a key in the key list): foreground blended 35% toward panel, then held to 4.5:1 on panel. Proposed (ALI-2358): also the unplayed part of the seek and volume bars, the time's total, and the artist and album under a song's title. + /// Labels in a panel of rows (Name, Size; a key in the key list): foreground blended 35% toward panel, then held to 4.5:1 on panel. Also the unplayed part of the player's seek and volume bars, the time's total, and the artist and album under a song's title. pub const MUTED: u32 = 0x9B9EA2; - /// The grid's focus ring. The theme's accent (or color4, or blue), moved until it has 3:1 against base and panel, the two things it sits beside. Proposed (ALI-2358): also the played part of the player's seek and volume bars, and the focus ring around its buttons. + /// The grid's focus ring. The theme's accent (or color4, or blue), moved until it has 3:1 against base and panel, the two things it sits beside. Also the played part of the player's seek and volume bars, and the focus ring around its buttons. pub const ACCENT: u32 = 0x5B9BF5; /// Errors. The theme's color1 (or red), held to 4.5:1 on panel. Derived but not drawn yet: error messages use foreground. @@ -300,11 +300,17 @@ pub mod spacing { /// Inside a grid tile, around its thumbnail on each side (src/app.rs grid_follow). pub const THUMB_INSET: f32 = 8.0; - /// Proposed for the video and music player (ALI-2358), not drawn yet: between the buttons in the player's control bar, so each keeps its 44 px target. + /// Between the buttons in the player's control bar, so each keeps its 44 px target. pub const CONTROLS_GAP: f32 = 4.0; - /// Proposed for the video and music player (ALI-2358), not drawn yet: in the music view, between the cover art and the title under it. + /// In the music view, between the cover art and the title under it. pub const COVER_GAP: f32 = 24.0; + + /// Either side of the time (1:23 / 4:56) in the player's control bar (src/player/bar.rs). + pub const TIME_PAD: f32 = 12.0; + + /// In the player's control bar, the extra space before the Mute and Full screen buttons, which sets the sound and window controls apart from the position (src/player/bar.rs). + pub const CONTROLS_GROUP_GAP: f32 = 8.0; } /// Corner radii, in px. @@ -339,26 +345,29 @@ pub mod size { /// The smallest window's height: room for the key list (src/main.rs MIN_SIZE). pub const MIN_WINDOW_HEIGHT: f32 = 420.0; - /// Proposed for the video and music player (ALI-2358), not drawn yet: the player's control bar along the window's foot: a 44 px button with 10 px above and below. Opaque panel, so its text and icons keep their contrast over any video. + /// The player's control bar along the window's foot: a 44 px button with 10 px above and below. Opaque panel, so its text and icons keep their contrast over any video. pub const CONTROLS_HEIGHT: f32 = 64.0; - /// Proposed for the video and music player (ALI-2358), not drawn yet: an icon inside a 44 px control button, drawn in foreground (border behind it under the pointer). + /// An icon inside a 44 px control button, drawn in foreground (border behind it under the pointer). pub const CONTROL_ICON: f32 = 20.0; - /// Proposed for the video and music player (ALI-2358), not drawn yet: the part of the seek and volume bars still to come, in muted. Thinner than the played part, so the two differ in shape, not colour alone. + /// The part of the seek and volume bars still to come, in muted. Thinner than the played part, so the two differ in shape, not colour alone. pub const SEEK_TRACK: f32 = 2.0; - /// Proposed for the video and music player (ALI-2358), not drawn yet: the part of the seek and volume bars already played or set, in accent. + /// The part of the seek and volume bars already played or set, in accent. pub const SEEK_PLAYED: f32 = 4.0; - /// Proposed for the video and music player (ALI-2358), not drawn yet: the round handle on the seek and volume bars, in foreground; its 44 px target is the bar's whole height. + /// The round handle on the seek and volume bars, in foreground; its 44 px target is the bar's whole height. pub const SEEK_THUMB: f32 = 14.0; - /// Proposed for the video and music player (ALI-2358), not drawn yet: the volume bar's length in the control bar. + /// The volume bar's length in the control bar. pub const VOLUME_WIDTH: f32 = 96.0; - /// Proposed for the video and music player (ALI-2358), not drawn yet: the music view's cover art, square, at most; smaller in a smaller window. No cover art: a panel square with a note icon in muted. + /// The music view's cover art, square, at most; smaller in a smaller window. No cover art: a panel square with a note icon in muted. pub const COVER_ART: f32 = 320.0; + + /// The note icon in the panel square a song with no cover art shows, in muted (src/player/bar.rs). + pub const COVER_ICON: f32 = 96.0; } /// Durations, and easings as cubic Béziers `[x1, y1, x2, y2]`. @@ -374,11 +383,17 @@ pub mod motion { /// After the theme folder changes, how long the viewer waits before reading it, so a theme swap is read once it's whole (src/main.rs). pub const THEME_SETTLE: Duration = Duration::from_millis(15); - /// Proposed for the video and music player (ALI-2358), not drawn yet: while a video plays, how long the control bar stays after the pointer last moved or a key was pressed. Paused, ended, loading, failed, music, or a keyboard focus inside the bar: it stays. + /// While a video plays, how long the control bar stays after the pointer last moved or a key was pressed. Paused, ended, loading, failed, music, or a keyboard focus inside the bar: it stays. The mouse pointer hides and comes back with it. pub const CONTROLS_HIDE: Duration = Duration::from_millis(2000); - /// Proposed for the video and music player (ALI-2358), not drawn yet: how far Left and Right (or a click on the seek bar's keyboard focus) move in a video. + /// How far Left and Right (or a click on the seek bar's keyboard focus) move in a video. pub const SEEK_STEP: Duration = Duration::from_millis(5000); + + /// After the last seek by key, how long the player waits before telling the screen reader the new position, so a held key is announced once, where it stops (src/app.rs). + pub const SEEK_ANNOUNCE: Duration = Duration::from_millis(500); + + /// Two clicks on a video this close together are a double-click, which toggles full screen (src/app.rs). + pub const DOUBLE_CLICK: Duration = Duration::from_millis(400); } /// Unitless multiples. @@ -389,7 +404,7 @@ pub mod scale { /// A line of text's height, as a multiple of the font's own line height, rounded up to a whole pixel (src/ui.rs line_height). pub const LINE_HEIGHT: f32 = 1.3; - /// Proposed for the video and music player (ALI-2358), not drawn yet: how many points of 100 Up and Down (and the volume bar's arrow keys) move the volume. + /// How many points of 100 Up and Down (and the volume bar's arrow keys) move the volume. pub const VOLUME_STEP: f32 = 5.0; } diff --git a/src/ui.rs b/src/ui.rs index 9e4120b..b24aa32 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -24,6 +24,21 @@ pub const KEYS: &[(&str, &str)] = &[ ("Esc, q", "Back out, quit"), ]; +/// The key list in a video or song (the canvas's "Player · Keys" board). +pub const PLAYER_KEYS: &[(&str, &str)] = &[ + ("Space, k", "Play, pause"), + ("Left, Right", "Back, forward 5 s"), + ("Up, Down", "Volume"), + ("m", "Mute"), + ("f, double-click", "Full screen"), + ("n, PgDn / p, PgUp", "Next, previous file"), + ("Home", "Back to the start"), + ("t", "Say the position"), + ("Tab", "The controls"), + ("?", "These keys"), + ("Esc, q", "Leave full screen, quit"), +]; + /// Sizes in logical pixels, from design/tokens.json (src/tokens.rs). pub const MARGIN: f64 = spacing::MARGIN as f64; pub const PAD: f64 = spacing::PAD as f64; @@ -305,10 +320,13 @@ mod tests { let mut text = Text::new(crate::text::UI_PX * scale as f32, false); assert!(text.add_font(&path, index)); let colors = crate::theme::builtin(true); - let rows: Vec<(String, String)> = KEYS.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(); - let (r, all) = draw_rows(&mut c, &mut text, &colors, scale, "Keys", &rows, Anchor::Centre); - assert!(r.x >= 0 && r.y >= 0 && r.right() <= w && r.bottom() <= h, "{r:?}"); - assert!(all, "at {scale}x some keys were cut off"); + // The pictures' list and the player's. + for list in [KEYS, PLAYER_KEYS] { + let rows: Vec<(String, String)> = list.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(); + let (r, all) = draw_rows(&mut c, &mut text, &colors, scale, "Keys", &rows, Anchor::Centre); + assert!(r.x >= 0 && r.y >= 0 && r.right() <= w && r.bottom() <= h, "{r:?}"); + assert!(all, "at {scale}x some keys were cut off"); + } } } } diff --git a/src/wl.rs b/src/wl.rs index a0eac1b..115cfec 100644 --- a/src/wl.rs +++ b/src/wl.rs @@ -115,6 +115,18 @@ struct VideoLayer { retired: Vec, } +/// The player's controls, toasts and panels: a subsurface above the video, in premultiplied +/// ARGB, clear where nothing is drawn, and unmapped when there's nothing to show, so a +/// playing video with the bar hidden is the only thing over the window. +struct Overlay { + surface: wl_surface::WlSurface, + sub: wl_subsurface::WlSubsurface, + viewport: Option, + buffers: Vec, + pending_damage: Rect, + mapped: bool, +} + /// A video buffer's slot, as its `wl_buffer`'s data. pub struct VideoSlot(usize); @@ -188,6 +200,7 @@ pub struct State { /// (a protocol error that would close the window) is refused here first. dmabuf_formats: std::collections::HashSet<(u32, u64)>, video: Option, + overlay: Option, /// In full screen, as the compositor last said. pub fullscreen: bool, pending_fullscreen: bool, @@ -242,6 +255,8 @@ pub struct State { source: Option, offer: Option>, cursor_now: Cursor, + /// The pointer is hidden over the window (a video playing with its bar hidden). + cursor_hidden: bool, } pub struct Wl { @@ -276,6 +291,7 @@ impl Wl { main_device: None, dmabuf_formats: Default::default(), video: None, + overlay: None, fullscreen: false, pending_fullscreen: false, outputs: Vec::new(), @@ -317,6 +333,7 @@ impl Wl { source: None, offer: None, cursor_now: Cursor::Default, + cursor_hidden: false, }; // One round trip binds the globals, the second brings the outputs' modes. queue.roundtrip(&mut state).map_err(|e| format!("Wayland: {e}"))?; @@ -418,6 +435,10 @@ impl Wl { let sub = subs.get_subsurface(&surface, parent, &self.qh, ()); // Frames arrive at the video's own pace, not the window's. sub.set_desync(); + // Always under the player's controls. + if let Some(o) = &s.overlay { + sub.place_below(&o.surface); + } // No input: the window beneath takes the pointer, as it does for a picture. let empty = compositor.create_region(&self.qh, ()); surface.set_input_region(Some(&empty)); @@ -505,6 +526,92 @@ impl Wl { true } + /// Shows the overlay: `frame` is premultiplied ARGB at the window's physical size, and + /// `damage` what changed since the last call. Maps it if it wasn't. + pub fn overlay_present(&mut self, frame: &[u32], damage: Rect) { + let (w, h) = self.physical_size(); + if w <= 0 || h <= 0 || frame.len() < (w * h) as usize { + return; + } + let qh = self.qh.clone(); + if self.state.overlay.is_none() { + let s = &mut self.state; + let (Some(compositor), Some(subs), Some(parent)) = (&s.compositor, &s.subcompositor, &s.surface) else { return }; + let surface = compositor.create_surface(&qh, ()); + let sub = subs.get_subsurface(&surface, parent, &qh, ()); + sub.set_desync(); + // Above the video, which was made, or will be, as the parent's other child. + if let Some(v) = &s.video { + sub.place_above(&v.surface); + } + // The order takes effect with the parent's next commit. + parent.commit(); + let empty = compositor.create_region(&qh, ()); + surface.set_input_region(Some(&empty)); + empty.destroy(); + let viewport = s.viewporter.as_ref().map(|v| v.get_viewport(&surface, &qh, ())); + s.overlay = Some(Overlay { surface, sub, viewport, buffers: Vec::new(), pending_damage: Rect::default(), mapped: false }); + } + let full = Rect::new(0, 0, w, h); + // A buffer from the overlay's own list: taken out and put back, so the shared + // buffer code can run with the state borrowed. + let mut o = self.state.overlay.take().expect("made above"); + std::mem::swap(&mut o.buffers, &mut self.state.buffers); + let got = self.state.acquire_buffer_as(w, h, wl_shm::Format::Argb8888, &qh); + std::mem::swap(&mut o.buffers, &mut self.state.buffers); + let Some(i) = got else { + self.state.overlay = Some(o); + return; + }; + let damage = if o.mapped { std::mem::take(&mut o.pending_damage).union(damage).intersect(full) } else { full }; + o.pending_damage = Rect::default(); + for b in o.buffers.iter_mut() { + b.stale = b.stale.union(damage); + } + let b = &mut o.buffers[i]; + let clip = b.stale.intersect(full); + let wz = w as usize; + for y in clip.y..clip.bottom() { + let start = y as usize * wz + clip.x as usize; + let _ = b.file.write_all_at(bytemuck::cast_slice(&frame[start..start + clip.w as usize]), (start * 4) as u64); + } + b.stale = Rect::default(); + b.busy = true; + o.surface.attach(Some(&b.wl), 0, 0); + o.surface.damage_buffer(damage.x, damage.y, damage.w, damage.h); + if let Some(v) = &o.viewport { + v.set_destination(self.state.width, self.state.height); + } else { + o.surface.set_buffer_scale(self.state.integer_scale); + } + o.surface.commit(); + o.mapped = true; + self.state.overlay = Some(o); + } + + /// Takes the overlay off the screen, keeping its buffers for next time. + pub fn overlay_hide(&mut self) { + let Some(o) = &mut self.state.overlay else { return }; + if o.mapped { + o.surface.attach(None, 0, 0); + o.surface.commit(); + o.mapped = false; + } + } + + /// Ends the overlay, as when the window shows a picture again. + pub fn overlay_end(&mut self) { + let Some(o) = self.state.overlay.take() else { return }; + for b in o.buffers { + b.wl.destroy(); + } + if let Some(v) = o.viewport { + v.destroy(); + } + o.sub.destroy(); + o.surface.destroy(); + } + /// Ends the video: the subsurface and its buffers go. pub fn video_end(&mut self) { let Some(v) = self.state.video.take() else { return }; @@ -630,8 +737,26 @@ impl Wl { return; } self.state.cursor_now = c; - if let Some(d) = &self.state.cursor_device { - d.set_shape(self.state.pointer_serial, shape_of(c)); + if !self.state.cursor_hidden { + self.state.show_cursor(); + } + } + + /// Hides the pointer over the window, or shows it again with the shape it would have. + /// Only where the shape can be set again (cursor-shape-v1): without it, a pointer once + /// hidden couldn't be brought back, so it stays. + pub fn hide_cursor(&mut self, hide: bool) { + let hide = hide && self.state.cursor_device.is_some(); + if self.state.cursor_hidden == hide { + return; + } + self.state.cursor_hidden = hide; + if hide { + if let Some(p) = &self.state.pointer { + p.set_cursor(self.state.pointer_serial, None, 0, 0); + } + } else { + self.state.show_cursor(); } } @@ -672,8 +797,19 @@ fn shape_of(c: Cursor) -> cursor_dev::Shape { } impl State { + /// Sets the pointer's shape, as of the last time it entered the window. + fn show_cursor(&self) { + if let Some(d) = &self.cursor_device { + d.set_shape(self.pointer_serial, shape_of(self.cursor_now)); + } + } + /// The first free buffer of the right size, making one if none is free. fn acquire_buffer(&mut self, w: i32, h: i32, qh: &QueueHandle) -> Option { + self.acquire_buffer_as(w, h, wl_shm::Format::Xrgb8888, qh) + } + + fn acquire_buffer_as(&mut self, w: i32, h: i32, format: wl_shm::Format, qh: &QueueHandle) -> Option { let mut i = 0; while i < self.buffers.len() { if self.buffers[i].w != w || self.buffers[i].h != h { @@ -690,12 +826,12 @@ impl State { if let Some(i) = self.buffers.iter().position(|b| !b.busy && !b.retired) { return Some(i); } - let b = self.new_buffer(w, h, qh)?; + let b = self.new_buffer(w, h, format, qh)?; self.buffers.push(b); Some(self.buffers.len() - 1) } - fn new_buffer(&mut self, w: i32, h: i32, qh: &QueueHandle) -> Option { + fn new_buffer(&mut self, w: i32, h: i32, format: wl_shm::Format, qh: &QueueHandle) -> Option { let size = (w as usize) * (h as usize) * 4; if size > i32::MAX as usize { return None; @@ -705,7 +841,7 @@ impl State { let pool = self.shm.as_ref()?.create_pool(fd.as_fd(), size as i32, qh, ()); let id = self.next_buffer_id; self.next_buffer_id = id.wrapping_add(1); - let wl = pool.create_buffer(0, w, h, w * 4, wl_shm::Format::Xrgb8888, qh, id); + let wl = pool.create_buffer(0, w, h, w * 4, format, qh, id); pool.destroy(); Some(Buffer { wl, file: File::from(fd), w, h, busy: false, stale: Rect::new(0, 0, w, h), retired: false, id }) } @@ -979,13 +1115,16 @@ impl Dispatch for State { impl Dispatch for State { fn event(s: &mut State, _: &wl_buffer::WlBuffer, e: wl_buffer::Event, id: &u32, _: &Connection, _: &QueueHandle) { - if let wl_buffer::Event::Release = e - && let Some(i) = s.buffers.iter().position(|b| b.id == *id) - { - if s.buffers[i].retired { - s.buffers.swap_remove(i).wl.destroy(); - } else { - s.buffers[i].busy = false; + if let wl_buffer::Event::Release = e { + let list = if s.buffers.iter().any(|b| b.id == *id) { Some(&mut s.buffers) } else { s.overlay.as_mut().map(|o| &mut o.buffers) }; + if let Some(list) = list + && let Some(i) = list.iter().position(|b| b.id == *id) + { + if list[i].retired { + list.swap_remove(i).wl.destroy(); + } else { + list[i].busy = false; + } } } } @@ -1104,8 +1243,10 @@ impl Dispatch for State { match e { wl_pointer::Event::Enter { serial, surface_x, surface_y, .. } => { s.pointer_serial = serial; - if let Some(d) = &s.cursor_device { - d.set_shape(serial, shape_of(s.cursor_now)); + // Back over the window while hidden, it stays hidden until the viewer shows it. + match &s.pointer { + Some(p) if s.cursor_hidden => p.set_cursor(serial, None, 0, 0), + _ => s.show_cursor(), } s.inputs.push_back(Input::Move { x: surface_x, y: surface_y }); }