From 5ccf8426a2eeda1d9d7fb1eff2e842260acb418b Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 06:59:09 -0700 Subject: [PATCH 01/23] ALI-2358: Proposed design tokens for the video and music player New tokens for the player design on the Alias View canvas, for Mike to review before any player code is written: - spacing: controls-gap, cover-gap; - sizes: controls-height, control-icon, seek-track, seek-played, seek-thumb, volume-width, cover-art; - motion: controls-hide, seek-step; - scale: volume-step. The colours stay the seven theme roles. New contrast pairs: an icon on a hovered button (foreground on border, 3:1), the music view's artist line (muted on base, 4.5:1) and the seek bar's unplayed part (muted on panel, 3:1). They pass in every shipped theme and the built-in two. --- design/tokens.json | 84 +++++++++++++++++++++++++++++++++++-- src/tokens.rs | 102 ++++++++++++++++++++++++++++++--------------- 2 files changed, 150 insertions(+), 36 deletions(-) diff --git a/design/tokens.json b/design/tokens.json index eec7c43..8a8708f 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." + "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." }, { "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." + "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." }, { "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." + "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." }, { "name": "danger", @@ -230,6 +230,16 @@ "name": "thumb-inset", "value": "8px", "usage": "Inside a grid tile, around its thumbnail on each side (src/app.rs grid_follow)." + }, + { + "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." + }, + { + "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." } ] }, @@ -283,6 +293,41 @@ "name": "min-window-height", "value": "420px", "usage": "The smallest window's height: room for the key list (src/main.rs MIN_SIZE)." + }, + { + "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." + }, + { + "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)." + }, + { + "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." + }, + { + "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." + }, + { + "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." + }, + { + "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." + }, + { + "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." } ] }, @@ -302,6 +347,16 @@ "name": "theme-settle", "value": "15ms", "usage": "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)." + }, + { + "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." + }, + { + "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." } ] }, @@ -316,6 +371,11 @@ "name": "line-height", "value": 1.3, "usage": "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)." + }, + { + "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." } ] }, @@ -475,6 +535,24 @@ "bg": "panel", "min": 3, "usage": "The grid's focus ring beside a tile, which is panel until its thumbnail loads." + }, + { + "fg": "foreground", + "bg": "border", + "min": 3, + "usage": "Proposed (ALI-2358): 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." + }, + { + "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." } ] } diff --git a/src/tokens.rs b/src/tokens.rs index ff32669..7b05002 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. + /// 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. 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. @@ -299,6 +299,12 @@ 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. + 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. + pub const COVER_GAP: f32 = 24.0; } /// Corner radii, in px. @@ -332,6 +338,27 @@ 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. + 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). + 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. + 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. + 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. + 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. + 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. + pub const COVER_ART: f32 = 320.0; } /// Durations, and easings as cubic Béziers `[x1, y1, x2, y2]`. @@ -346,6 +373,12 @@ 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. + 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. + pub const SEEK_STEP: Duration = Duration::from_millis(5000); } /// Unitless multiples. @@ -355,6 +388,9 @@ 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. + pub const VOLUME_STEP: f32 = 5.0; } /// The colours of every theme aliasOS ships, as its colors.toml gives them (aliasproject/aliasos, themes/*/colors.toml, at c3e9f60). The viewer derives its colour roles from these at run time; a test checks that what it derives matches each theme's tokens above, so the contrast list checks what's really drawn. A new aliasOS theme needs a row here and a theme above. From 2cfb1368f9a3589a07b1b7c960157ba2ba03ad07 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 10:53:29 -0700 Subject: [PATCH 02/23] ALI-2358: Videos and songs play, in the jailed GPU helper - A video or song in the list opens in alias-playback's GPU helper: libmpv in a bubblewrap jail, drawing on the card the compositor uses (from linux-dmabuf feedback) and handing its frames over as dmabufs. They show in a subsurface above the window, so they never pass through this process. Sound goes through the session's PulseAudio socket, bound into the jail read-only. - The folder list takes videos and songs, so n, p, Page Up and Page Down move between them and pictures. - Space plays and pauses (after the end, plays from the start), Left and Right seek 5 s (seek-step), f toggles full screen and Escape leaves it. - While a file opens, the window says so; a file that can't play says why. - alias-playback is a git dependency on the branch of its PR #3 until #2 and #3 merge. --- Cargo.lock | 10 ++ Cargo.toml | 4 + src/app.rs | 159 ++++++++++++++++++++++- src/args.rs | 2 +- src/main.rs | 36 ++++-- src/player/gpu.rs | 197 +++++++++++++++++++++++++++++ src/player/mod.rs | 312 ++++++++++++++++++++++++++++++++++++++++++++++ src/wl.rs | 222 ++++++++++++++++++++++++++++++++- 8 files changed, 928 insertions(+), 14 deletions(-) create mode 100644 src/player/gpu.rs create mode 100644 src/player/mod.rs diff --git a/Cargo.lock b/Cargo.lock index e7f52ad..48bb754 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -59,12 +59,22 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "alias-playback" +version = "0.1.0" +source = "git+https://github.com/aliasproject/alias-playback?branch=ali-2358-gpu-media#fd8ddc3d9bcf552af15047f37e5e46114e934f74" +dependencies = [ + "libc", + "rustix", +] + [[package]] name = "alias-view" version = "0.1.0" dependencies = [ "accesskit", "accesskit_unix", + "alias-playback", "blocking", "bytemuck", "flate2", diff --git a/Cargo.toml b/Cargo.toml index aa64ee0..0b7a8ae 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,10 @@ wayland-protocols = { version = "0.32.13", features = ["client", "staging", "uns 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" } [profile.release] opt-level = 3 diff --git a/src/app.rs b/src/app.rs index 0adda77..a785b92 100644 --- a/src/app.rs +++ b/src/app.rs @@ -15,6 +15,7 @@ use crate::decode::anim::{Next, Player}; use crate::decode::{Info, Want}; use crate::loader::{Done, Job, Kind, Loader}; use crate::pixels::Pixels; +use crate::player::{self, Media, Phase}; use crate::render::{self, Level}; use crate::text::{self, Text}; use crate::theme::Colors; @@ -86,6 +87,11 @@ pub struct App { pub title: String, pub focused: bool, pub cache_home: PathBuf, + /// The video or song open now, if the current file is one. + pub media: Option, + /// Carried from one video or song to the next. + pub volume: f64, + pub muted: bool, } impl App { @@ -127,6 +133,9 @@ impl App { title: String::new(), focused: false, cache_home, + media: None, + volume: 100.0, + muted: false, } } @@ -198,12 +207,94 @@ impl App { self.ask_current(); self.grid_follow(); } + let size = self.media.as_ref().map(|m| self.media_box(m.kind)); + 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); + 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) + } + } + } + + /// Opens the current file in the player if it's a video or song, closes the player if + /// 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)?))) }; + match want { + Some((path, _)) if self.media.as_ref().is_some_and(|m| m.path == path) => {} + Some((path, kind)) => { + self.close_media(wl); + let b = self.media_box(kind); + let size = (b.w.max(1) as u32, b.h.max(1) as u32); + 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) + } else { + Media::failed(path, kind, "this desktop can't show video from another process (it lacks linux-dmabuf)".into()) + }); + self.all(); + self.a11y_dirty = true; + } + None => { + if self.media.is_some() { + self.close_media(wl); + self.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.pump(wl, b, scale) + { + self.all(); + self.a11y_dirty = true; + } + } + + fn close_media(&mut self, wl: &mut Wl) { + if let Some(old) = self.media.take() { + if old.heard { + self.volume = old.state.volume; + self.muted = old.state.muted; + } + drop(old); + wl.video_end(); + if wl.state.fullscreen { + wl.set_fullscreen(false); + } + } + } + + /// The line drawn in the middle of the window for a video or song that isn't showing + /// a picture yet, or can't. + fn media_message(&self) -> Option { + let m = self.media.as_ref()?; + match m.phase() { + Phase::Opening => Some(format!("Opening {}", self.name())), + Phase::Failed(why) => Some(format!("Can't play {}: {why}", self.name())), + _ => None, + } } /// Asks for whatever the current picture still needs: its screen copy, a bigger one /// for zoom, and then its neighbours. pub fn ask_current(&mut self) { let Some(path) = self.path().map(|p| p.to_path_buf()) else { return }; + // Videos and songs play in the player, not the picture decoder. + if player::kind_of(&path).is_some() { + return; + } let bx = self.win; let entry = self.pictures.entry(path.clone()).or_default(); let stale = entry.screen.as_ref().is_some_and(|s| { @@ -242,7 +333,7 @@ impl App { } let bx = self.win; for i in self.neighbours() { - let Some(path) = self.files.get(i).cloned() else { continue }; + let Some(path) = self.files.get(i).cloned().filter(|p| player::kind_of(p).is_none()) else { continue }; let e = self.pictures.entry(path.clone()).or_default(); if e.screen.is_none() && e.error.is_none() && !e.asked { e.asked = true; @@ -576,6 +667,11 @@ impl App { self.drag = None; } Input::Close => self.quit = true, + Input::VideoReleased(slot) => { + if let Some(m) = &mut self.media { + m.released(slot); + } + } _ => {} } } @@ -628,6 +724,32 @@ 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). + k::KEY_Left | k::KEY_KP_Left | k::KEY_Right | k::KEY_KP_Right => { + 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; + } + _ => {} + } + } let img = self.img(); let zoomed = img.is_some_and(|img| self.view.zoomed(img, self.win)); let step = (64.0 * self.scale).max(self.win.0.min(self.win.1) as f64 / 10.0); @@ -823,6 +945,10 @@ impl App { } continue; } + // A video or song has no thumbnail yet: its tile stays empty. + if player::kind_of(path).is_some() { + continue; + } jobs.push(Job { path: path.clone(), kind: Kind::Thumb, want: Want::Fit(inner, inner) }); } self.thumbs_asked = jobs.iter().map(|j| j.path.clone()).collect(); @@ -954,13 +1080,17 @@ impl App { if damage.is_empty() || self.frame.len() < (w * h) as usize { return Rect::default(); } - let wants_text = self.show_info || self.show_help || self.toast.is_some() || self.grid.is_some() || self.current().is_some_and(|p| p.error.is_some()) || self.files.is_empty(); + let media_message = if self.grid.is_none() { self.media_message() } else { None }; + let wants_text = + self.show_info || self.show_help || self.toast.is_some() || self.grid.is_some() || self.current().is_some_and(|p| p.error.is_some()) || self.files.is_empty() || media_message.is_some(); if wants_text { self.ensure_text(); } let mut damage = damage; if self.grid.is_some() { self.paint_grid(damage); + } else if self.media.is_some() { + self.paint_media(damage, media_message.as_deref()); } else { damage = self.paint_picture(damage); } @@ -1034,6 +1164,20 @@ impl App { damage } + /// The window under a video or song: the background, and the line saying it's opening + /// or why it can't play. The frames are in the subsurface above. + fn paint_media(&mut self, damage: Rect, message: Option<&str>) { + let (w, h) = (self.win.0 as i32, self.win.1 as i32); + let mut c = Canvas::new(&mut self.frame, w, h); + c.set_clip(damage); + c.fill(damage, self.colors.base); + self.drawn = None; + let (Some(msg), Some(t)) = (message, self.text.as_mut()) else { return }; + let tw = t.measure(msg); + let x = ((w as f32 - tw) / 2.0).max(ui::px(ui::MARGIN, self.scale) as f32); + t.draw_fitted(&mut c, msg, x, h / 2, (w - ui::px(ui::MARGIN, self.scale) * 2) as f32, self.colors.foreground); + } + fn paint_grid(&mut self, damage: Rect) { let (w, h) = (self.win.0 as i32, self.win.1 as i32); let layout = self.grid_layout(); @@ -1109,6 +1253,17 @@ impl App { 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()) + } 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()), diff --git a/src/args.rs b/src/args.rs index 1585047..5e493a7 100644 --- a/src/args.rs +++ b/src/args.rs @@ -157,7 +157,7 @@ pub fn list_folder(dir: &Path, include: Option<&Path>) -> Vec { let name = e.file_name(); let s = name.to_string_lossy(); let wanted = include.is_some_and(|p| p.file_name() == Some(name.as_os_str())); - wanted || (!s.starts_with('.') && is_picture_name(&s) && e.path().is_file()) + wanted || (!s.starts_with('.') && (is_picture_name(&s) || crate::player::kind_of_name(&s).is_some()) && e.path().is_file()) }) .map(|e| e.file_name()) .collect(); diff --git a/src/main.rs b/src/main.rs index d14bd64..16fd5c2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,6 +16,7 @@ mod decode; mod exif; mod loader; mod pixels; +mod player; mod render; mod sort; mod text; @@ -74,6 +75,11 @@ fn restart_with_fixed_mmap_threshold() { fn main() { restart_with_fixed_mmap_threshold(); let argv: Vec<_> = std::env::args_os().skip(1).collect(); + // The video player's helper, inside its jail (src/player/gpu.rs). + if argv.first().is_some_and(|a| a == player::gpu::HELPER_ARG) { + let rest: Vec = argv[1..].iter().map(|a| a.to_string_lossy().into_owned()).collect(); + player::gpu::helper_main(&rest); + } if argv.len() == 2 && argv[0] == decode::heif::HELPER_ARG { std::process::exit(decode::heif::helper_main(std::path::Path::new(&argv[1]))); } @@ -178,7 +184,11 @@ fn run(o: Opening) -> i32 { let (info_tx, info_rx) = channel::(); let (box_tx, box_rx) = channel::(); let asked: Arc> = Arc::new(Mutex::new(Want::Fit(1920, 1080))); - { + // A video or song opens in the player once the window is up, not in the decoder. + let first_media = player::kind_of(&first).is_some(); + if first_media { + drop(info_tx); + } else { let (done, asked, first) = (loader.sender(), asked.clone(), first.clone()); let _ = std::thread::Builder::new().name("alias-view-open".into()).spawn(move || { let result = decode::decode_with(&first, threads, |info| { @@ -209,17 +219,22 @@ fn run(o: Opening) -> i32 { let (screen, scale) = wl.likely_output().map(|o| o.logical_and_scale()).unwrap_or(((1920, 1080), 1.0)); // A broken file says nothing here and closes the channel; the window still opens // to say what's wrong. - let info = info_rx.recv_timeout(Duration::from_secs(5)).ok(); - let img = info.as_ref().map(|i| (i.width, i.height)).filter(|&(w, h)| w > 0 && h > 0).unwrap_or((1, 1)); + let info = if first_media { None } else { info_rx.recv_timeout(Duration::from_secs(5)).ok() }; + // A video's size is known only once the player has looked: its window starts at 16:9, + // as big as the screen share allows, and keeps its size, as for pictures. + let fallback = if first_media { (7680, 4320) } else { (1, 1) }; + let img = info.as_ref().map(|i| (i.width, i.height)).filter(|&(w, h)| w > 0 && h > 0).unwrap_or(fallback); let (lw, lh) = window_for(img, screen, scale); let phys = ((lw as f64 * scale).round() as u32, (lh as f64 * scale).round() as u32); let _ = box_tx.send(Want::Fit(phys.0, phys.1)); mark(stamp, "headers read"); let mut app = App::new(o.files, o.start, colors, loader, threads); - let entry = app.pictures.entry(first.clone()).or_default(); - entry.asked = true; - entry.info = info; + if !first_media { + let entry = app.pictures.entry(first.clone()).or_default(); + entry.asked = true; + entry.info = info; + } app.title = app.window_title(); wl.open(&app.title, APP_ID, lw, lh, scale); let (pw, ph) = wl.physical_size(); @@ -268,6 +283,9 @@ fn run(o: Opening) -> i32 { app.set_files(files); folder = None; } + if wl.state.configured { + app.sync_media(&mut wl); + } if let Some(a) = &a11y { let reqs: Vec<_> = a.actions.try_iter().collect(); for r in reqs { @@ -297,7 +315,7 @@ fn run(o: Opening) -> i32 { if wl.state.configured && configured_at.is_none() { configured_at = Some(now); } - let waiting_for_first = first_frame && app.current().is_some_and(|p| p.screen.is_none() && p.error.is_none()) && configured_at.is_some_and(|t| now < t + FIRST_FRAME_WAIT); + let waiting_for_first = first_frame && !first_media && app.current().is_some_and(|p| p.screen.is_none() && p.error.is_none()) && configured_at.is_some_and(|t| now < t + FIRST_FRAME_WAIT); if wl.state.configured && !waiting_for_first && (wl.must_paint() || (wl.can_paint() && !app.damage.is_empty())) { if wl.must_paint() || first_frame { app.damage = canvas::Rect::new(0, 0, app.win.0 as i32, app.win.1 as i32); @@ -384,6 +402,10 @@ fn run(o: Opening) -> i32 { fds.push(PollFd::from_borrowed_fd(w.as_fd(), PollFlags::IN)); fds.len() - 1 }); + // The player's messages: read on the next turn, by sync_media. + if let Some(f) = app.media.as_ref().and_then(|m| m.session_fd()) { + fds.push(PollFd::from_borrowed_fd(f, PollFlags::IN)); + } let _ = poll(&mut fds, timeout.as_ref()); let ready = |i: usize| fds[i].revents().intersects(PollFlags::IN | PollFlags::ERR | PollFlags::HUP); let wl_ready = ready(0); diff --git a/src/player/gpu.rs b/src/player/gpu.rs new file mode 100644 index 0000000..2df9353 --- /dev/null +++ b/src/player/gpu.rs @@ -0,0 +1,197 @@ +//! The playback helper: libmpv in a bubblewrap jail, drawing on the graphics card and +//! handing its frames over as dmabufs (`alias_playback::gpu_helper`). Untrusted video never +//! decodes in this process. This is the only file that knows the helper's protocol; the +//! rest of the player sees [`Said`] and sends [`Command`]s. +//! +//! The helper is this program, started again inside the jail with [`HELPER_ARG`]. + +use std::fs::File; +use std::os::fd::{AsFd, BorrowedFd, OwnedFd}; +use std::path::Path; +use std::process::Child; + +use alias_playback::gpu_helper::{self, Started}; +pub use alias_playback::gpu_helper::{MetaField, Said}; +use alias_playback::helper::{EXIT_BAD_START, EXIT_CANT_PLAY, EXIT_NO_MPV}; +use alias_playback::{Audio, Hwdec, Options, RenderPath, Vendor, jail}; + +pub const HELPER_ARG: &str = "--gpu-helper"; +/// The helper's exit code when its own lock-down (Landlock, seccomp) couldn't be applied. +const EXIT_SANDBOX: i32 = 6; + +/// What the player asks of the helper. +#[derive(Clone, Copy, Debug, PartialEq)] +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. + Volume(f64), + Mute(bool), + /// The frame's box, in physical pixels: the helper draws the largest frame with the + /// video's shape inside it. + Size(u32, u32), + /// The compositor is done with this buffer. + Release(usize), +} + +impl Command { + fn line(self) -> String { + 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(), + Command::Mute(false) => "unmute".into(), + Command::Size(w, h) => format!("size {} {}", w.max(1), h.max(1)), + Command::Release(slot) => format!("release {slot}"), + } + } +} + +/// The render node at `path`, or the first there is when the compositor didn't say. +pub fn open_node(path: Option<&Path>) -> Result { + let opened = path.and_then(|p| std::fs::OpenOptions::new().read(true).write(true).open(p).ok()).map(OwnedFd::from); + match opened { + Some(fd) => Ok(fd), + None => alias_playback::gpu::first_render_node().map_err(|_| "no graphics card can be opened to draw it".to_string()), + } +} + +/// One file playing in one helper. +pub struct Session { + child: Child, + socket: OwnedFd, + /// The socket has closed: the helper is gone. + pub gone: bool, +} + +impl Session { + /// Starts a helper for `path` on the card at `node`, drawing into a box of `size` + /// physical pixels. `Err` says why, in words for the screen. + pub fn start(path: &Path, node: OwnedFd, size: (u32, u32)) -> Result { + let file = File::open(path).map_err(|e| match e.kind() { + std::io::ErrorKind::NotFound => "it isn't there any more".to_string(), + std::io::ErrorKind::PermissionDenied => "you don't have permission to read it".to_string(), + _ => format!("it can't be read ({e})"), + })?; + let vendor = alias_playback::gpu::vendor(&node); + let exe = jail::own_exe().map_err(|_| "Alias View's own program file is gone; was it updated? Open it again".to_string())?; + let sound = jail::sound_socket(); + let mut command = std::process::Command::new("bwrap"); + command.args(jail::gpu_arguments(&exe, vendor, sound.as_deref())).arg(HELPER_ARG).arg(vendor_word(vendor)).arg(if sound.is_some() { "sound" } else { "silent" }); + let Started { child, socket } = gpu_helper::start(command, file, node, size, false).map_err(|e| { + if e.kind() == std::io::ErrorKind::NotFound { "bubblewrap (bwrap), which keeps video in a sandbox, isn't installed".to_string() } else { format!("the player didn't start ({e})") } + })?; + rustix::io::ioctl_fionbio(&socket, true).map_err(|_| "the player didn't start".to_string())?; + Ok(Session { child, socket, gone: false }) + } + + /// For the loop's poll. + pub fn fd(&self) -> BorrowedFd<'_> { + self.socket.as_fd() + } + + /// Every message waiting, with the descriptors that came with it. A message that isn't + /// sensible is dropped, with its descriptors. Sets `gone` when the helper has gone. + pub fn read(&mut self) -> Vec<(Said, Vec)> { + let mut out = Vec::new(); + loop { + match gpu_helper::receive(&self.socket) { + Ok(Some((text, fds))) => { + if let Some(said) = gpu_helper::parse_said(&text) { + out.push((said, fds)); + } + } + Ok(None) => { + self.gone = true; + break; + } + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, + Err(_) => { + self.gone = true; + break; + } + } + } + out + } + + pub fn send(&self, c: Command) { + let _ = gpu_helper::send(&self.socket, &c.line(), &[]); + } + + /// After `gone`: why, if it wasn't a clean exit. Waits for the helper, which has + /// closed its socket and so is ending. + pub fn failure(&mut self) -> Option { + let status = self.child.wait().ok()?; + match status.code() { + Some(0) => None, + Some(EXIT_NO_MPV) => Some("libmpv isn't installed".into()), + Some(EXIT_SANDBOX) => Some("the sandbox video plays in couldn't be set up".into()), + Some(EXIT_BAD_START) => Some("the player didn't start".into()), + Some(EXIT_CANT_PLAY) | None => Some("the player stopped".into()), + Some(_) => Some("the player stopped".into()), + } + } +} + +impl Drop for Session { + fn drop(&mut self) { + // Closing the socket ends the helper; bubblewrap takes the jail with it. + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +fn vendor_word(v: Vendor) -> &'static str { + match v { + Vendor::Nvidia => "nvidia", + Vendor::Amd => "amd", + Vendor::Intel => "intel", + Vendor::Apple => "apple", + Vendor::Other => "other", + } +} + +/// The helper's `main`, inside the jail: `HELPER_ARG VENDOR sound|silent WIDTH HEIGHT`. +/// Never returns. +pub fn helper_main(args: &[String]) -> ! { + let vendor = match args.first().map(String::as_str) { + Some("nvidia") => Vendor::Nvidia, + Some("amd") => Vendor::Amd, + Some("intel") => Vendor::Intel, + Some("apple") => Vendor::Apple, + Some("other") => Vendor::Other, + _ => std::process::exit(EXIT_BAD_START), + }; + let audio = match args.get(1).map(String::as_str) { + Some("sound") => Audio::Pulse, + Some("silent") => Audio::Off, + _ => std::process::exit(EXIT_BAD_START), + }; + // A song's cover art is drawn as its picture. + let options = Options { render: RenderPath::Gpu, hwdec: Hwdec::For(vendor), audio, cover_art: true, start_paused: true }; + gpu_helper::run(&args[2..], &options, EXIT_SANDBOX, jail::lock_down_gpu_helper) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[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"); + assert_eq!(Command::Size(0, 720).line(), "size 1 720"); + assert_eq!(Command::Release(2).line(), "release 2"); + } +} diff --git a/src/player/mod.rs b/src/player/mod.rs new file mode 100644 index 0000000..3261085 --- /dev/null +++ b/src/player/mod.rs @@ -0,0 +1,312 @@ +//! Video and music (ALI-2358). A file the viewer recognises as video or sound plays in the +//! 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 gpu; + +use std::os::fd::OwnedFd; +use std::path::{Path, PathBuf}; + +use alias_playback::helper::PlayState; + +use crate::canvas::Rect; +use crate::wl::{VIDEO_SLOTS, VideoBuffer, Wl}; +use gpu::{Command, MetaField, Said, Session}; + +/// The containers aliasOS sends to a video player (`install/user/mimetypes.sh`), and their +/// usual other names. +const VIDEO: &[&str] = &["mp4", "m4v", "mkv", "webm", "mov", "avi", "flv", "wmv", "mpeg", "mpg", "ogv", "ogm", "3gp", "3g2", "asf"]; +/// Sound files. Plain `.ogg` is here: it's nearly always sound, and a video in one still +/// plays, shown as its picture. +const MUSIC: &[&str] = &["mp3", "flac", "ogg", "oga", "opus", "m4a", "aac", "wav", "wma", "aif", "aiff", "mka", "wv", "ape"]; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Video, + Music, +} + +pub fn kind_of_name(name: &str) -> Option { + let (stem, ext) = name.rsplit_once('.')?; + if stem.is_empty() { + return None; + } + let is = |list: &[&str]| list.iter().any(|e| ext.eq_ignore_ascii_case(e)); + if is(VIDEO) { + Some(Kind::Video) + } else if is(MUSIC) { + Some(Kind::Music) + } else { + None + } +} + +pub fn kind_of(path: &Path) -> Option { + kind_of_name(&path.file_name()?.to_string_lossy()) +} + +/// Where the player is, in the words the screen and the screen reader use. +#[derive(Clone, Debug, PartialEq)] +pub enum Phase { + Opening, + Playing, + Paused, + /// Stopped on its last frame. + Ended, + Failed(String), +} + +/// The song's tags, as the helper said them (already cleaned). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Meta { + pub title: Option, + pub artist: Option, + pub album: Option, +} + +/// One video or song, open. +pub struct Media { + pub path: PathBuf, + pub kind: Kind, + session: Option, + pub state: PlayState, + /// The helper has said where it is at least once. + pub heard: bool, + buffers: [Option; VIDEO_SLOTS], + /// The buffer on screen. + pub shown: Option, + /// It has a picture: a video's frames or a song's cover art. `None` until known. + pub has_picture: Option, + pub meta: Meta, + pub error: Option, + /// The size asked of the helper, so it's only told of changes. + asked: (u32, u32), +} + +impl Media { + /// Opens `path` in a new helper on the card at `node`, playing from the start, with the + /// volume and mute the last file had. + pub fn open(path: PathBuf, kind: Kind, node: Result, size: (u32, u32), volume: f64, muted: bool) -> Media { + let mut m = Media { + path, + kind, + session: None, + state: PlayState { volume, muted, ..PlayState::default() }, + heard: false, + buffers: Default::default(), + shown: None, + has_picture: None, + meta: Meta::default(), + error: None, + asked: size, + }; + match node.and_then(|node| Session::start(&m.path, node, size)) { + Ok(s) => { + s.send(Command::Volume(volume)); + s.send(Command::Mute(muted)); + s.send(Command::Play); + m.session = Some(s); + } + Err(e) => m.error = Some(e), + } + m + } + + /// 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 + } + + pub fn phase(&self) -> Phase { + if let Some(e) = &self.error { + Phase::Failed(e.clone()) + } else if !self.heard { + Phase::Opening + } else if self.state.ended { + Phase::Ended + } else if self.state.paused { + Phase::Paused + } else { + Phase::Playing + } + } + + pub fn session_fd(&self) -> Option> { + self.session.as_ref().filter(|s| !s.gone).map(|s| s.fd()) + } + + pub fn send(&self, c: Command) { + if let Some(s) = &self.session { + s.send(c); + } + } + + /// Play or pause. At the end, plays again from the start. + pub fn toggle(&mut self) { + match self.phase() { + Phase::Ended => { + self.send(Command::SeekTo(0.0)); + self.send(Command::Play); + } + Phase::Paused => self.send(Command::Play), + Phase::Playing | Phase::Opening => self.send(Command::Pause), + Phase::Failed(_) => {} + } + } + + /// The frame's box changed size (physical px). + pub fn resize(&mut self, size: (u32, u32)) { + if size != self.asked { + self.asked = size; + self.send(Command::Size(size.0, size.1)); + } + } + + /// The compositor let a buffer go. + pub fn released(&mut self, slot: usize) { + if self.shown != Some(slot) { + self.send(Command::Release(slot)); + } + } + + /// Reads the helper's messages and acts on them: buffers become `wl_buffer`s, frames + /// are shown centred in `frame_box` (physical px; `scale` turns them logical). Returns + /// true if what's drawn or said about it changed. + pub fn pump(&mut self, wl: &mut Wl, frame_box: Rect, scale: f64) -> bool { + let Some(session) = &mut self.session else { return false }; + let messages = session.read(); + let gone = session.gone; + let mut changed = false; + for (said, mut fds) in messages { + match said { + Said::Hello | Said::Dropped { .. } | Said::Decoder(_) => {} + Said::Buffer { slot, width, height, fourcc, modifier, stride, offset } => { + let Some(fd) = fds.pop().filter(|_| fds.is_empty()) else { continue }; + let b = VideoBuffer { width, height, fourcc, modifier, stride, offset }; + wl.video_begin(); + wl.video_buffer(slot, fd, b); + self.buffers[slot] = Some(b); + if self.shown == Some(slot) { + self.shown = None; + } + } + Said::Frame { slot } => { + let Some(b) = self.buffers[slot] else { + self.send(Command::Release(slot)); + continue; + }; + let place = centre(b.width, b.height, frame_box, scale); + // The one shown until now is given back when the compositor releases it. + if wl.video_frame(slot, place) { + self.shown = Some(slot); + if self.has_picture != Some(true) { + self.has_picture = Some(true); + changed = true; + } + } else { + self.send(Command::Release(slot)); + } + } + Said::State(s) => { + changed |= !self.heard + || s.paused != self.state.paused + || s.ended != self.state.ended + || s.muted != self.state.muted + || (s.volume - self.state.volume).abs() >= 0.5 + || (s.duration - self.state.duration).abs() >= 0.5 + || s.position.floor() != self.state.position.floor(); + self.state = s; + self.heard = true; + } + Said::Meta(field, text) => { + let slot = match field { + MetaField::Title => &mut self.meta.title, + MetaField::Artist => &mut self.meta.artist, + MetaField::Album => &mut self.meta.album, + }; + *slot = Some(text); + changed = true; + } + Said::NoVideo => { + self.has_picture = Some(false); + changed = true; + } + Said::CantPlay => { + self.error = Some(self.cant_play_reason()); + changed = true; + } + } + } + if gone { + let why = self.session.as_mut().and_then(Session::failure); + if self.error.is_none() { + self.error = Some(why.unwrap_or_else(|| "the player stopped".into())); + } + self.session = None; + changed = true; + } + changed + } + + /// Why it can't play, in the canvas's words. + fn cant_play_reason(&self) -> String { + if self.heard && self.state.position >= 1.0 { format!("it's damaged after {}", clock(self.state.position)) } else { "it's damaged or in a format that can't be played".into() } + } +} + +/// `w`×`h` physical px centred in `b`, as logical x, y, width and height. +fn centre(w: u32, h: u32, b: Rect, scale: f64) -> (i32, i32, i32, i32) { + let s = scale.max(1e-6); + let x = b.x as f64 + (b.w as f64 - w as f64) / 2.0; + let y = b.y as f64 + (b.h as f64 - h as f64) / 2.0; + ((x / s).round() as i32, (y / s).round() as i32, (w as f64 / s).round() as i32, (h as f64 / s).round() as i32) +} + +/// A time as the player writes it: 0:05, 4:56, 1:02:03. +pub fn clock(seconds: f64) -> String { + let t = if seconds.is_finite() { seconds.max(0.0) as u64 } else { 0 }; + let (h, m, s) = (t / 3600, t / 60 % 60, t % 60); + if h > 0 { format!("{h}:{m:02}:{s:02}") } else { format!("{m}:{s:02}") } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn files_are_told_apart_by_name() { + assert_eq!(kind_of_name("clip.MP4"), Some(Kind::Video)); + assert_eq!(kind_of_name("a.mkv"), Some(Kind::Video)); + assert_eq!(kind_of_name("song.flac"), Some(Kind::Music)); + assert_eq!(kind_of_name("song.ogg"), Some(Kind::Music)); + assert_eq!(kind_of_name("film.ogv"), Some(Kind::Video)); + assert_eq!(kind_of_name("photo.jpg"), None); + assert_eq!(kind_of_name(".mp4"), None, "a hidden name with no stem"); + assert_eq!(kind_of_name("mp4"), None); + } + + #[test] + fn no_name_is_both_a_picture_and_media() { + for ext in VIDEO.iter().chain(MUSIC) { + assert!(!crate::decode::is_picture_name(&format!("x.{ext}")), "{ext}"); + } + } + + #[test] + fn times_read_as_a_clock() { + assert_eq!(clock(0.0), "0:00"); + assert_eq!(clock(83.9), "1:23"); + assert_eq!(clock(296.0), "4:56"); + assert_eq!(clock(3723.0), "1:02:03"); + assert_eq!(clock(f64::NAN), "0:00"); + assert_eq!(clock(-4.0), "0:00"); + } + + #[test] + fn a_frame_sits_in_the_middle_of_its_box() { + assert_eq!(centre(1920, 800, Rect::new(0, 0, 1920, 1080), 1.0), (0, 140, 1920, 800)); + assert_eq!(centre(1000, 1000, Rect::new(0, 0, 2000, 1000), 2.0), (250, 0, 500, 500)); + } +} diff --git a/src/wl.rs b/src/wl.rs index 0f4a07b..01321bb 100644 --- a/src/wl.rs +++ b/src/wl.rs @@ -5,22 +5,28 @@ //! //! Buffers are memfds written with `pwrite` rather than mapped, so this file needs no //! unsafe code: the copy costs about a millisecond for a full window. +//! +//! A video or a song's cover art is a subsurface above the window, showing the playback +//! helper's dmabufs through `linux-dmabuf` (src/player/gpu.rs): the frames never pass +//! through this process. use std::collections::VecDeque; use std::fs::File; use std::os::fd::{AsFd, BorrowedFd, OwnedFd}; use std::os::unix::fs::FileExt; +use std::path::PathBuf; use std::sync::Arc; use rustix::fs::{MemfdFlags, ftruncate, memfd_create}; use rustix::time::{Itimerspec, TimerfdClockId, TimerfdFlags, TimerfdTimerFlags, Timespec, timerfd_create, timerfd_settime}; use wayland_client::protocol::{ - wl_buffer, wl_callback, wl_compositor, wl_data_device, wl_data_device_manager, wl_data_offer, wl_data_source, wl_keyboard, wl_output, wl_pointer, wl_registry, wl_seat, wl_shm, wl_shm_pool, - wl_surface, + wl_buffer, wl_callback, wl_compositor, wl_data_device, wl_data_device_manager, wl_data_offer, wl_data_source, wl_keyboard, wl_output, wl_pointer, wl_region, wl_registry, wl_seat, wl_shm, + wl_shm_pool, wl_subcompositor, wl_subsurface, wl_surface, }; use wayland_client::{Connection, Dispatch, EventQueue, Proxy, QueueHandle, WEnum, event_created_child}; use wayland_protocols::wp::cursor_shape::v1::client::{wp_cursor_shape_device_v1 as cursor_dev, wp_cursor_shape_manager_v1 as cursor_mgr}; use wayland_protocols::wp::fractional_scale::v1::client::{wp_fractional_scale_manager_v1 as frac_mgr, wp_fractional_scale_v1 as frac}; +use wayland_protocols::wp::linux_dmabuf::zv1::client::{zwp_linux_buffer_params_v1 as dmabuf_params, zwp_linux_dmabuf_feedback_v1 as dmabuf_feedback, zwp_linux_dmabuf_v1 as dmabuf}; use wayland_protocols::wp::pointer_gestures::zv1::client::{zwp_pointer_gesture_pinch_v1 as pinch, zwp_pointer_gestures_v1 as gestures}; use wayland_protocols::wp::viewporter::client::{wp_viewport, wp_viewporter}; use wayland_protocols::xdg::decoration::zv1::client::{zxdg_decoration_manager_v1 as deco_mgr, zxdg_toplevel_decoration_v1 as deco}; @@ -78,8 +84,38 @@ pub enum Input { Resized, Close, Focus(bool), + /// The compositor is done with a video buffer: the helper may draw into it again. + VideoReleased(usize), +} + +/// How many video buffers the helper keeps in turn (`gpu_helper::SLOTS`). +pub const VIDEO_SLOTS: usize = alias_playback::gpu_helper::SLOTS; + +/// A video buffer's layout, as the helper describes it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct VideoBuffer { + pub width: u32, + pub height: u32, + pub fourcc: u32, + pub modifier: u64, + pub stride: u32, + pub offset: u32, +} + +/// The subsurface a video or cover art is shown in, above the window's own surface. +struct VideoLayer { + surface: wl_surface::WlSurface, + sub: wl_subsurface::WlSubsurface, + viewport: Option, + buffers: [Option<(wl_buffer::WlBuffer, VideoBuffer)>; VIDEO_SLOTS], + /// Where it sits, in logical px, and the buffer on it. + place: Option<(i32, i32, i32, i32)>, + shown: Option, } +/// A video buffer's slot, as its `wl_buffer`'s data. +pub struct VideoSlot(usize); + /// Makes the clipboard's data when another program asks for it, on a thread of its /// own: a picture is only encoded as PNG if something pastes it. pub type Producer = Arc Option>> + Send + Sync>; @@ -142,6 +178,14 @@ pub struct State { deco_manager: Option, xout_manager: Option, gestures: Option, + subcompositor: Option, + dmabuf: Option, + /// The compositor's main graphics device (`dev_t`), from dmabuf feedback. + main_device: Option, + video: Option, + /// In full screen, as the compositor last said. + pub fullscreen: bool, + pending_fullscreen: bool, pub outputs: Vec, /// The output the window is on, once the compositor says. pub entered: Option, @@ -222,6 +266,12 @@ impl Wl { deco_manager: None, xout_manager: None, gestures: None, + subcompositor: None, + dmabuf: None, + main_device: None, + video: None, + fullscreen: false, + pending_fullscreen: false, outputs: Vec::new(), entered: None, surface: None, @@ -327,6 +377,109 @@ impl Wl { } } + /// Asks for full screen, or back to a window. The compositor's configure says what it did. + pub fn set_fullscreen(&self, on: bool) { + if let Some(t) = &self.state.toplevel { + if on { + t.set_fullscreen(None); + } else { + t.unset_fullscreen(); + } + } + } + + /// Whether video can be shown: the compositor takes dmabufs and subsurfaces. + pub fn can_show_video(&self) -> bool { + self.state.dmabuf.is_some() && self.state.subcompositor.is_some() + } + + /// The render node of the card the compositor draws with, when it said which. The + /// playback helper draws there, so its buffers need no copy to be shown. + pub fn render_node_path(&self) -> Option { + render_node_for(self.state.main_device?) + } + + /// Makes the video subsurface, above the window and below nothing yet, if there isn't + /// one. It shows nothing until a frame arrives. + pub fn video_begin(&mut self) { + let s = &mut self.state; + if s.video.is_some() { + return; + } + let (Some(compositor), Some(subs), Some(parent)) = (&s.compositor, &s.subcompositor, &s.surface) else { return }; + let surface = compositor.create_surface(&self.qh, ()); + let sub = subs.get_subsurface(&surface, parent, &self.qh, ()); + // Frames arrive at the video's own pace, not the window's. + sub.set_desync(); + // 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)); + empty.destroy(); + let viewport = s.viewporter.as_ref().map(|v| v.get_viewport(&surface, &self.qh, ())); + s.video = Some(VideoLayer { surface, sub, viewport, buffers: Default::default(), place: None, shown: None }); + } + + /// The helper described a buffer and sent its dmabuf: makes the `wl_buffer` for it. + pub fn video_buffer(&mut self, slot: usize, fd: OwnedFd, b: VideoBuffer) { + let (Some(d), Some(v)) = (&self.state.dmabuf, &mut self.state.video) else { return }; + if slot >= VIDEO_SLOTS { + return; + } + let params = d.create_params(&self.qh, ()); + params.add(fd.as_fd(), 0, b.offset, b.stride, (b.modifier >> 32) as u32, b.modifier as u32); + let wl = params.create_immed(b.width as i32, b.height as i32, b.fourcc, dmabuf_params::Flags::empty(), &self.qh, VideoSlot(slot)); + params.destroy(); + if let Some((old, _)) = v.buffers[slot].replace((wl, b)) { + // Still on screen: destroyed when the compositor lets it go (see the release). + if v.shown != Some(slot) { + old.destroy(); + } + } + if v.shown == Some(slot) { + v.shown = None; + } + } + + /// Shows the frame in `slot` at `place`: x, y, width and height in logical px. Returns + /// false if the slot has no buffer, so the caller gives it straight back. + pub fn video_frame(&mut self, slot: usize, place: (i32, i32, i32, i32)) -> bool { + let Some(v) = &mut self.state.video else { return false }; + let Some((wl, b)) = v.buffers.get(slot).and_then(|b| b.as_ref()) else { return false }; + let moved = v.place != Some(place); + if moved { + v.sub.set_position(place.0, place.1); + if let Some(vp) = &v.viewport { + vp.set_destination(place.2.max(1), place.3.max(1)); + } + v.place = Some(place); + } + v.surface.attach(Some(wl), 0, 0); + v.surface.damage_buffer(0, 0, b.width as i32, b.height as i32); + v.surface.commit(); + v.shown = Some(slot); + // A subsurface's position takes effect with its parent's next commit. + if moved && let Some(p) = &self.state.surface { + p.commit(); + } + true + } + + /// Ends the video: the subsurface and its buffers go. + pub fn video_end(&mut self) { + let Some(v) = self.state.video.take() else { return }; + for (wl, _) in v.buffers.into_iter().flatten() { + wl.destroy(); + } + if let Some(vp) = v.viewport { + vp.destroy(); + } + v.sub.destroy(); + v.surface.destroy(); + if let Some(p) = &self.state.surface { + p.commit(); + } + } + pub fn set_title(&self, title: &str) { if let Some(t) = &self.state.toplevel { t.set_title(title.to_string()); @@ -455,6 +608,16 @@ impl Wl { } } +/// The render node (`/dev/dri/renderD*`) of the graphics device `dev`, which may be its +/// primary node: both list the render node in /sys. +fn render_node_for(dev: u64) -> Option { + let (major, minor) = (rustix::fs::major(dev), rustix::fs::minor(dev)); + let drm = PathBuf::from(format!("/sys/dev/char/{major}:{minor}/device/drm")); + let mut names: Vec = std::fs::read_dir(drm).ok()?.filter_map(|e| e.ok()?.file_name().into_string().ok()).filter(|n| n.starts_with("renderD")).collect(); + names.sort(); + names.into_iter().next().map(|n| PathBuf::from("/dev/dri").join(n)) +} + fn shape_of(c: Cursor) -> cursor_dev::Shape { match c { Cursor::Default => cursor_dev::Shape::Default, @@ -526,6 +689,10 @@ impl State { } fn apply_size(&mut self) { + if self.pending_fullscreen != self.fullscreen { + self.fullscreen = self.pending_fullscreen; + self.inputs.push_back(Input::Resized); + } if let Some((w, h)) = self.pending_size.take() && w > 0 && h > 0 @@ -554,6 +721,15 @@ impl Dispatch for State { "zxdg_decoration_manager_v1" => s.deco_manager = Some(r.bind(name, 1, qh, ())), "zxdg_output_manager_v1" => s.xout_manager = Some(r.bind(name, version.min(3), qh, ())), "zwp_pointer_gestures_v1" => s.gestures = Some(r.bind(name, version.min(3), qh, ())), + "wl_subcompositor" => s.subcompositor = Some(r.bind(name, 1, qh, ())), + "zwp_linux_dmabuf_v1" if version >= 3 => { + let d: dmabuf::ZwpLinuxDmabufV1 = r.bind(name, version.min(4), qh, ()); + // Which card the compositor draws with: the helper draws on the same. + if version >= 4 { + d.get_default_feedback(qh, ()); + } + s.dmabuf = Some(d); + } "wl_output" => { let o: wl_output::WlOutput = r.bind(name, version.min(4), qh, name); let xdg = s.xout_manager.as_ref().map(|m| m.get_xdg_output(&o, qh, name)).is_some(); @@ -593,8 +769,40 @@ ignore_events!( wl_data_device_manager::WlDataDeviceManager, xout_mgr::ZxdgOutputManagerV1, gestures::ZwpPointerGesturesV1, + wl_subcompositor::WlSubcompositor, + wl_subsurface::WlSubsurface, + wl_region::WlRegion, + dmabuf::ZwpLinuxDmabufV1, + dmabuf_params::ZwpLinuxBufferParamsV1, ); +impl Dispatch for State { + fn event(s: &mut State, _: &dmabuf_feedback::ZwpLinuxDmabufFeedbackV1, e: dmabuf_feedback::Event, _: &(), _: &Connection, _: &QueueHandle) { + // The format table's descriptor is dropped with the event: formats are the + // helper's choice, and every compositor takes XRGB8888. + if let dmabuf_feedback::Event::MainDevice { device } = e + && let Ok(bytes) = <[u8; 8]>::try_from(device.as_slice()) + { + s.main_device = Some(u64::from_ne_bytes(bytes)); + } + } +} + +impl Dispatch for State { + fn event(s: &mut State, b: &wl_buffer::WlBuffer, e: wl_buffer::Event, slot: &VideoSlot, _: &Connection, _: &QueueHandle) { + if let wl_buffer::Event::Release = e { + // A buffer replaced since it was attached is destroyed once let go; the helper + // isn't told, as it holds a new one in that slot. + let current = s.video.as_ref().and_then(|v| v.buffers.get(slot.0)?.as_ref()).is_some_and(|(wl, _)| wl == b); + if current { + s.inputs.push_back(Input::VideoReleased(slot.0)); + } else { + b.destroy(); + } + } + } +} + impl Dispatch for State { fn event(s: &mut State, _: &wl_output::WlOutput, e: wl_output::Event, name: &u32, _: &Connection, _: &QueueHandle) { let Some(o) = s.outputs.iter_mut().find(|o| o.name == *name) else { return }; @@ -621,7 +829,11 @@ impl Dispatch for State { } impl Dispatch for State { - fn event(s: &mut State, _: &wl_surface::WlSurface, e: wl_surface::Event, _: &(), _: &Connection, _: &QueueHandle) { + fn event(s: &mut State, surface: &wl_surface::WlSurface, e: wl_surface::Event, _: &(), _: &Connection, _: &QueueHandle) { + // The window's own surface speaks for the window; the video's follows it. + if s.surface.as_ref() != Some(surface) { + return; + } match e { wl_surface::Event::PreferredBufferScale { factor } if s.viewport.is_none() => { s.scale_known = true; @@ -674,10 +886,12 @@ impl Dispatch for State { impl Dispatch for State { fn event(s: &mut State, _: &xdg_toplevel::XdgToplevel, e: xdg_toplevel::Event, _: &(), _: &Connection, _: &QueueHandle) { match e { - xdg_toplevel::Event::Configure { width, height, .. } => { + xdg_toplevel::Event::Configure { width, height, states } => { if width > 0 && height > 0 { s.pending_size = Some((width, height)); } + let fullscreen = xdg_toplevel::State::Fullscreen as u32; + s.pending_fullscreen = states.as_chunks::<4>().0.iter().any(|c| u32::from_ne_bytes(*c) == fullscreen); } xdg_toplevel::Event::Close => s.inputs.push_back(Input::Close), _ => {} From 94b32daf4cd5d32601057ed79f262b8fabe54570 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:12:12 -0700 Subject: [PATCH 03/23] ALI-2358: The player's controls, music view and screen-reader support MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The control bar from the design canvas, on an overlay subsurface above the video: Previous, Play (pause and replay icons), Next, the time, Position, Mute, Volume and Full screen, every target 44 px, with the focus ring and a border-coloured hover fill. The played part of a slider is thicker than the rest. - It hides 2 s after the last pointer move or key while a video plays, and stays while paused, ended, opening, for music, and while the keyboard focus is in it. - Keys from the canvas: Space and k, Left and Right seek, Up and Down volume, m, f and double-click, Home, t, Tab through the bar, and the media keys. - The music view: cover art at up to 320 px with rounded corners, or a panel with a note, and the title with "artist · album" under it. A song plays on to the next song in the folder and stops after the last. - AccessKit: named buttons, toggle buttons and sliders with values, and polite announcements for opening, play and pause, the end, failures, volume and seeks. - Tokens: time-pad, controls-group-gap, cover-icon, seek-announce and double-click, proposed with #6's. Lucide's ISC notice for the icons is in LICENSE. --- LICENSE | 22 ++ README.md | 58 ++++- design/tokens.json | 49 +++- src/a11y.rs | 147 ++++++++++- src/app.rs | 154 +++++++---- src/app/player_ui.rs | 598 +++++++++++++++++++++++++++++++++++++++++++ src/canvas.rs | 29 ++- src/main.rs | 8 + src/player/bar.rs | 336 ++++++++++++++++++++++++ src/player/gpu.rs | 4 - src/player/icons.rs | 95 +++++++ src/player/mod.rs | 88 ++++++- src/theme.rs | 18 ++ src/tokens.rs | 39 ++- src/ui.rs | 15 ++ src/wl.rs | 131 +++++++++- 16 files changed, 1685 insertions(+), 106 deletions(-) create mode 100644 src/app/player_ui.rs create mode 100644 src/player/bar.rs create mode 100644 src/player/icons.rs 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..ed75451 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,33 @@ 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. 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 +67,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 +175,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 +193,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 +236,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 +246,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..2c4a131 100644 --- a/design/tokens.json +++ b/design/tokens.json @@ -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": "Proposed (ALI-2358): 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": "Proposed (ALI-2358): in the music view, between the cover art and the title under it." + }, + { + "name": "time-pad", + "value": "12px", + "usage": "Proposed (ALI-2358): 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": "Proposed (ALI-2358): 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": "Proposed (ALI-2358): 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": "Proposed (ALI-2358): 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": "Proposed (ALI-2358): 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": "Proposed (ALI-2358): 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": "Proposed (ALI-2358): 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": "Proposed (ALI-2358): 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": "Proposed (ALI-2358): 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": "Proposed (ALI-2358): 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": "Proposed (ALI-2358): 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." }, { "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": "Proposed (ALI-2358): 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": "Proposed (ALI-2358): 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": "Proposed (ALI-2358): 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": "Proposed (ALI-2358): how many points of 100 Up and Down (and the volume bar's arrow keys) move the volume." } ] }, diff --git a/src/a11y.rs b/src/a11y.rs index d886e03..041459e 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -17,6 +17,10 @@ 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 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 +33,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 +82,10 @@ 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, } pub fn tree(s: &Snapshot) -> TreeUpdate { @@ -46,7 +93,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 +146,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 { @@ -175,8 +276,50 @@ 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); + } + 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, + } } #[test] diff --git a/src/app.rs b/src/app.rs index a785b92..ae120ca 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,21 @@ 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 was last told. + announcement: Option, + /// 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, + /// In full screen, as the compositor last said. + fullscreen: bool, } impl App { @@ -136,6 +154,15 @@ impl App { media: None, volume: 100.0, muted: false, + controls: Controls::default(), + icons: Default::default(), + overlay: Vec::new(), + overlay_damage: Rect::default(), + announcement: None, + seek_said_at: None, + last_click: None, + toggle_fullscreen: false, + fullscreen: false, } } @@ -207,21 +234,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, } } @@ -240,6 +266,12 @@ impl App { } else { Media::failed(path, kind, "this desktop can't show video from another process (it lacks linux-dmabuf)".into()) }); + self.controls = Controls { focus: self.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; } @@ -251,14 +283,28 @@ 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.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 changes only with these; the bar with any news. + if after != before { + self.all(); + } + self.overlay_all(); self.a11y_dirty = true; + self.after_media_news(Some(before.0)); } } @@ -270,6 +316,9 @@ impl App { } drop(old); wl.video_end(); + wl.overlay_end(); + self.controls = Controls::default(); + self.seek_said_at = None; if wl.state.fullscreen { wl.set_fullscreen(false); } @@ -542,9 +591,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(); @@ -556,7 +607,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> { @@ -610,6 +661,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 } => { @@ -724,31 +783,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). - k::KEY_Left | k::KEY_KP_Left | k::KEY_Right | k::KEY_KP_Right => { - 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)); @@ -811,11 +847,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; } @@ -823,9 +862,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); } @@ -1090,7 +1129,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); } @@ -1249,21 +1292,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()), @@ -1276,19 +1309,28 @@ 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()), + // A toast is on screen and said; otherwise the player's last announcement. + status: self.toast.as_ref().map(|(m, _)| m.as_str()).or(self.announcement.as_deref()), + 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..3bfc4b3 --- /dev/null +++ b/src/app/player_ui.rs @@ -0,0 +1,598 @@ +//! 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() +} + +impl App { + /// 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.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. + 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); + let line = self.ensure_text().map_or(ui::px(25.0 / 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) { + 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 + } + 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 => { + if let Some(text) = self.media.as_ref().map(|m| m.position_text()) { + // Said again even if unchanged: the screen reader is asked each time. + self.announcement = None; + 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))); + } +} 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..67be871 100644 --- a/src/main.rs +++ b/src/main.rs @@ -367,6 +367,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..fea50af --- /dev/null +++ b/src/player/bar.rs @@ -0,0 +1,336 @@ +//! 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, colors.border); + } + 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 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 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 2df9353..2ac9407 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(), @@ -187,7 +184,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 3261085..e3fa61b 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,8 @@ 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, } impl Media { @@ -99,6 +103,7 @@ impl Media { meta: Meta::default(), error: None, asked: size, + advanced: false, }; match node.and_then(|node| Session::start(&m.path, node, size)) { Ok(s) => { @@ -114,9 +119,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 { @@ -156,6 +159,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 { @@ -304,6 +363,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_frame_sits_in_the_middle_of_its_box() { assert_eq!(centre(1920, 800, Rect::new(0, 0, 1920, 1080), 1.0), (0, 140, 1920, 800)); 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..1e049bb 100644 --- a/src/tokens.rs +++ b/src/tokens.rs @@ -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. + /// Proposed (ALI-2358): 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. + /// Proposed (ALI-2358): in the music view, between the cover art and the title under it. pub const COVER_GAP: f32 = 24.0; + + /// Proposed (ALI-2358): 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; + + /// Proposed (ALI-2358): 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. + /// Proposed (ALI-2358): 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). + /// Proposed (ALI-2358): 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. + /// Proposed (ALI-2358): 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. + /// Proposed (ALI-2358): 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. + /// Proposed (ALI-2358): 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. + /// Proposed (ALI-2358): 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. + /// Proposed (ALI-2358): 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; + + /// Proposed (ALI-2358): 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. + /// Proposed (ALI-2358): 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. 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. + /// Proposed (ALI-2358): 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); + + /// Proposed (ALI-2358): 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); + + /// Proposed (ALI-2358): 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. + /// Proposed (ALI-2358): 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..f2896a5 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; diff --git a/src/wl.rs b/src/wl.rs index 01321bb..311b29e 100644 --- a/src/wl.rs +++ b/src/wl.rs @@ -113,6 +113,18 @@ struct VideoLayer { shown: Option, } +/// 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); @@ -183,6 +195,7 @@ pub struct State { /// The compositor's main graphics device (`dev_t`), from dmabuf feedback. main_device: Option, video: Option, + overlay: Option, /// In full screen, as the compositor last said. pub fullscreen: bool, pending_fullscreen: bool, @@ -270,6 +283,7 @@ impl Wl { dmabuf: None, main_device: None, video: None, + overlay: None, fullscreen: false, pending_fullscreen: false, outputs: Vec::new(), @@ -411,6 +425,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)); @@ -464,6 +482,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,6 +734,10 @@ fn shape_of(c: Cursor) -> cursor_dev::Shape { impl State { /// 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 { @@ -646,12 +754,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; @@ -661,7 +769,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 }) } @@ -909,13 +1017,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; + } } } } From 43d016976a305b5d3d48e9110df8b22eefcdf601 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:16:12 -0700 Subject: [PATCH 04/23] ALI-2358: MPRIS, so media controllers and playerctl work (work in progress) --- Cargo.toml | 3 + src/app.rs | 4 + src/app/player_ui.rs | 71 ++++++++ src/main.rs | 15 ++ src/mpris.rs | 397 +++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 490 insertions(+) create mode 100644 src/mpris.rs diff --git a/Cargo.toml b/Cargo.toml index 0b7a8ae..0c2a33d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,9 @@ rustix = { version = "1.1.6", features = ["fs", "event", "time", "pipe", "proces # 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. +# MPRIS on the session bus (src/mpris.rs). Already built for accesskit_unix, with the +# same async-io executor; blocking-api adds only the blocking wrappers. +zbus = { version = "5.19.0", default-features = false, features = ["async-io", "blocking-api"] } alias-playback = { git = "https://github.com/aliasproject/alias-playback", branch = "ali-2358-gpu-media" } [profile.release] diff --git a/src/app.rs b/src/app.rs index ae120ca..d065b51 100644 --- a/src/app.rs +++ b/src/app.rs @@ -110,6 +110,8 @@ pub struct App { toggle_fullscreen: bool, /// In full screen, as the compositor last said. fullscreen: bool, + /// Counts the videos and songs opened, so MPRIS sees each as a new track. + track: u64, } impl App { @@ -163,6 +165,7 @@ impl App { last_click: None, toggle_fullscreen: false, fullscreen: false, + track: 0, } } @@ -267,6 +270,7 @@ impl App { Media::failed(path, kind, "this desktop can't show video from another process (it lacks linux-dmabuf)".into()) }); self.controls = Controls { focus: self.controls.focus, ..Controls::default() }; + self.track += 1; self.seek_said_at = None; let opening = format!("Opening {}", self.name()); self.say(opening); diff --git a/src/app/player_ui.rs b/src/app/player_ui.rs index 3bfc4b3..df04052 100644 --- a/src/app/player_ui.rs +++ b/src/app/player_ui.rs @@ -580,6 +580,77 @@ impl App { } } +impl App { + /// What's playing, for MPRIS. + pub fn mpris_now(&self) -> crate::mpris::Now { + let many = self.files.len() > 1; + let Some(m) = &self.media else { return crate::mpris::Now { status: "Stopped", ..Default::default() } }; + let status = match m.phase() { + Phase::Playing => "Playing", + Phase::Failed(_) => "Stopped", + _ => "Paused", + }; + crate::mpris::Now { + status, + track: self.track, + path: Some(m.path.to_string_lossy().into_owned()), + title: Some(m.title()), + artist: m.meta.artist.clone(), + album: m.meta.album.clone(), + length: m.state.duration.max(0.0), + position: if m.state.ended { m.state.duration } else { m.state.position }, + volume: m.state.volume, + can_go_next: many, + can_go_previous: many, + } + } + + /// A media controller (the bar, playerctl, the screensaver) asked for something. + pub fn mpris_request(&mut self, r: crate::mpris::Request) { + use crate::mpris::Request; + if r == Request::Quit { + self.quit = true; + return; + } + if self.media.is_none() { + return; + } + match r { + Request::PlayPause => self.toggle_media(), + Request::Play => { + if self.media.as_ref().is_some_and(|m| m.phase() != Phase::Playing) { + self.toggle_media(); + } + } + Request::Pause => { + if self.media.as_ref().is_some_and(|m| m.phase() == Phase::Playing) { + self.toggle_media(); + } + } + Request::Next => self.step(1, false), + Request::Previous => self.step(-1, false), + Request::SeekBy(s) => { + if let Some(m) = &mut self.media { + m.seek_by(s); + } + } + Request::SeekTo(s) => { + if let Some(m) = &mut self.media { + m.seek_to(s); + } + } + Request::Volume(v) => { + if let Some(m) = &mut self.media { + m.set_volume(v); + } + } + Request::Quit => {} + } + self.overlay_bar(); + self.a11y_dirty = true; + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/main.rs b/src/main.rs index 67be871..4311f28 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,6 +15,7 @@ mod clip; mod decode; mod exif; mod loader; +mod mpris; mod pixels; mod player; mod render; @@ -243,6 +244,8 @@ fn run(o: Opening) -> i32 { let mut folder: Option>> = None; let mut folder_of = o.folder_of; let mut a11y: Option = None; + let mut mpris: Option = None; + let mut mpris_tried = false; let mut first_frame = true; let mut configured_at: Option = None; // Recolours when aliasOS's theme changes. Started after the first frame, as nothing @@ -286,6 +289,18 @@ fn run(o: Opening) -> i32 { if wl.state.configured { app.sync_media(&mut wl); } + // MPRIS, from the first video or song on, when there's a session bus. + if mpris.is_none() && !mpris_tried && app.media.is_some() { + mpris_tried = true; + mpris = if a11y::session_bus_exists() { mpris::Mpris::start() } else { None }; + } + if let Some(m) = &mpris { + let reqs: Vec<_> = m.requests.try_iter().collect(); + for r in reqs { + app.mpris_request(r); + } + m.update(app.mpris_now()); + } if let Some(a) = &a11y { let reqs: Vec<_> = a.actions.try_iter().collect(); for r in reqs { diff --git a/src/mpris.rs b/src/mpris.rs new file mode 100644 index 0000000..b198347 --- /dev/null +++ b/src/mpris.rs @@ -0,0 +1,397 @@ +//! MPRIS (ALI-2358), so the bar's media controls, `playerctl` and the screensaver's pause +//! work: org.mpris.MediaPlayer2 and its Player interface on the session bus, as +//! `org.mpris.MediaPlayer2.alias_view.instance`. +//! +//! It starts when the first video or song opens, never for pictures alone, and only when +//! there's a session bus. zbus's own thread answers the bus; a request becomes a +//! [`Request`] the loop reads after a wake, as the screen reader's actions do. The loop +//! tells it what's playing with [`Mpris::update`], which signals only what changed. + +use std::collections::HashMap; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::{Arc, Mutex}; + +use zbus::object_server::SignalEmitter; +use zbus::zvariant::{ObjectPath, OwnedValue, Value}; + +const PATH: &str = "/org/mpris/MediaPlayer2"; +/// MPRIS times are in microseconds. +const US: f64 = 1_000_000.0; + +/// What a media controller asked for. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Request { + PlayPause, + Play, + Pause, + Next, + Previous, + /// By this many seconds. + SeekBy(f64), + /// To this many seconds from the start. + SeekTo(f64), + /// 0 to 100. + Volume(f64), + Quit, +} + +/// What's playing, as MPRIS says it. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Now { + /// "Playing", "Paused" or "Stopped" (no video or song open). + pub status: &'static str, + /// Changes with each file, so controllers see a new track. + pub track: u64, + pub path: Option, + pub title: Option, + pub artist: Option, + pub album: Option, + pub length: f64, + pub position: f64, + /// 0 to 100. + pub volume: f64, + pub can_go_next: bool, + pub can_go_previous: bool, +} + +impl Now { + fn metadata(&self) -> HashMap { + let mut m = HashMap::new(); + if self.status == "Stopped" { + let none = ObjectPath::from_static_str_unchecked("/org/mpris/MediaPlayer2/TrackList/NoTrack"); + m.insert("mpris:trackid".into(), owned(Value::from(none))); + return m; + } + let id = format!("/com/aliasproject/view/track/{}", self.track); + if let Ok(p) = ObjectPath::try_from(id) { + m.insert("mpris:trackid".into(), owned(Value::from(p))); + } + if self.length > 0.0 { + m.insert("mpris:length".into(), owned(Value::from((self.length * US) as i64))); + } + if let Some(t) = &self.title { + m.insert("xesam:title".into(), owned(Value::from(t.as_str()))); + } + if let Some(a) = &self.artist { + m.insert("xesam:artist".into(), owned(Value::from(vec![a.as_str()]))); + } + if let Some(a) = &self.album { + m.insert("xesam:album".into(), owned(Value::from(a.as_str()))); + } + if let Some(p) = &self.path { + let url = format!("file://{}", percent_encode(p)); + m.insert("xesam:url".into(), owned(Value::from(url))); + } + m + } +} + +fn owned(v: Value<'_>) -> OwnedValue { + v.try_to_owned().unwrap_or_else(|_| OwnedValue::from(0u8)) +} + +/// A path as a `file://` URL's path: everything but unreserved characters and `/` escaped. +fn percent_encode(p: &str) -> String { + let mut out = String::new(); + for b in p.bytes() { + if b.is_ascii_alphanumeric() || b"-._~/".contains(&b) { + out.push(b as char); + } else { + out.push_str(&format!("%{b:02X}")); + } + } + out +} + +struct Shared { + now: Mutex, + tx: Mutex>, +} + +impl Shared { + fn ask(&self, r: Request) { + if let Ok(tx) = self.tx.lock() { + let _ = tx.send(r); + } + crate::wake::wake(); + } + + fn now(&self) -> Now { + self.now.lock().map(|n| n.clone()).unwrap_or_default() + } +} + +struct Root(Arc); + +#[zbus::interface(name = "org.mpris.MediaPlayer2")] +impl Root { + fn raise(&self) {} + + fn quit(&self) { + self.0.ask(Request::Quit); + } + + #[zbus(property)] + fn can_quit(&self) -> bool { + true + } + + #[zbus(property)] + fn can_raise(&self) -> bool { + false + } + + #[zbus(property)] + fn has_track_list(&self) -> bool { + false + } + + #[zbus(property)] + fn identity(&self) -> &str { + "Alias View" + } + + #[zbus(property)] + fn desktop_entry(&self) -> &str { + crate::APP_ID + } + + #[zbus(property)] + fn supported_uri_schemes(&self) -> Vec { + Vec::new() + } + + #[zbus(property)] + fn supported_mime_types(&self) -> Vec { + Vec::new() + } +} + +struct Player(Arc); + +#[zbus::interface(name = "org.mpris.MediaPlayer2.Player")] +impl Player { + fn next(&self) { + self.0.ask(Request::Next); + } + + fn previous(&self) { + self.0.ask(Request::Previous); + } + + fn pause(&self) { + self.0.ask(Request::Pause); + } + + fn play_pause(&self) { + self.0.ask(Request::PlayPause); + } + + /// There's no stopped state with a file open: Stop pauses, as the screensaver wants. + fn stop(&self) { + self.0.ask(Request::Pause); + } + + fn play(&self) { + self.0.ask(Request::Play); + } + + fn seek(&self, offset: i64) { + self.0.ask(Request::SeekBy(offset as f64 / US)); + } + + fn set_position(&self, track_id: ObjectPath<'_>, position: i64) { + // Only for the track playing now, as the spec says. + let now = self.0.now(); + if track_id.as_str() == format!("/com/aliasproject/view/track/{}", now.track) && position >= 0 { + self.0.ask(Request::SeekTo(position as f64 / US)); + } + } + + /// Opening another file isn't offered (no URI schemes are listed). + fn open_uri(&self, _uri: &str) {} + + #[zbus(signal)] + async fn seeked(emitter: &SignalEmitter<'_>, position: i64) -> zbus::Result<()>; + + #[zbus(property)] + fn playback_status(&self) -> String { + let s = self.0.now().status; + if s.is_empty() { "Stopped".into() } else { s.into() } + } + + #[zbus(property)] + fn rate(&self) -> f64 { + 1.0 + } + + #[zbus(property)] + fn set_rate(&self, _rate: f64) {} + + #[zbus(property)] + fn minimum_rate(&self) -> f64 { + 1.0 + } + + #[zbus(property)] + fn maximum_rate(&self) -> f64 { + 1.0 + } + + #[zbus(property)] + fn metadata(&self) -> HashMap { + self.0.now().metadata() + } + + #[zbus(property)] + fn volume(&self) -> f64 { + self.0.now().volume / 100.0 + } + + #[zbus(property)] + fn set_volume(&self, v: f64) { + if v.is_finite() { + self.0.ask(Request::Volume((v * 100.0).clamp(0.0, 100.0))); + } + } + + /// Read when asked; MPRIS sends no signal for it. + #[zbus(property(emits_changed_signal = "false"))] + fn position(&self) -> i64 { + (self.0.now().position * US) as i64 + } + + #[zbus(property)] + fn can_go_next(&self) -> bool { + self.0.now().can_go_next + } + + #[zbus(property)] + fn can_go_previous(&self) -> bool { + self.0.now().can_go_previous + } + + #[zbus(property)] + fn can_play(&self) -> bool { + self.0.now().status != "Stopped" + } + + #[zbus(property)] + fn can_pause(&self) -> bool { + self.0.now().status != "Stopped" + } + + #[zbus(property)] + fn can_seek(&self) -> bool { + self.0.now().status != "Stopped" && self.0.now().length > 0.0 + } + + #[zbus(property(emits_changed_signal = "const"))] + fn can_control(&self) -> bool { + true + } +} + +pub struct Mpris { + conn: zbus::blocking::Connection, + shared: Arc, + pub requests: Receiver, +} + +impl Mpris { + /// Joins the session bus. `None` if there isn't one or the name can't be had. + pub fn start() -> Option { + let (tx, requests) = channel(); + let shared = Arc::new(Shared { now: Mutex::new(Now { status: "Stopped", ..Now::default() }), tx: Mutex::new(tx) }); + let name = format!("org.mpris.MediaPlayer2.alias_view.instance{}", std::process::id()); + let conn = zbus::blocking::connection::Builder::session() + .ok()? + .name(name) + .ok()? + .serve_at(PATH, Root(shared.clone())) + .ok()? + .serve_at(PATH, Player(shared.clone())) + .ok()? + .build() + .ok()?; + Some(Mpris { conn, shared, requests }) + } + + /// What's playing now. Signals what changed; a jump in position other than by playing + /// is signalled as `Seeked`. + pub fn update(&self, now: Now) { + let before = { + let Ok(mut n) = self.shared.now.lock() else { return }; + std::mem::replace(&mut *n, now.clone()) + }; + if before == now { + return; + } + let Ok(iface) = self.conn.object_server().interface::<_, Player>(PATH) else { return }; + let player = iface.get(); + let e = iface.signal_emitter(); + zbus::block_on(async { + if before.status != now.status { + let _ = player.playback_status_changed(e).await; + let _ = player.can_play_changed(e).await; + let _ = player.can_pause_changed(e).await; + let _ = player.can_seek_changed(e).await; + } + if before.track != now.track || before.title != now.title || before.artist != now.artist || before.album != now.album || before.length != now.length || before.status != now.status { + let _ = player.metadata_changed(e).await; + let _ = player.can_seek_changed(e).await; + } + if before.volume != now.volume { + let _ = player.volume_changed(e).await; + } + if before.can_go_next != now.can_go_next { + let _ = player.can_go_next_changed(e).await; + } + if before.can_go_previous != now.can_go_previous { + let _ = player.can_go_previous_changed(e).await; + } + if jumped(&before, &now) { + let _ = Player::seeked(e, (now.position * US) as i64).await; + } + }); + } +} + +/// A move in position that playing doesn't explain: back at all, or forward by more than a +/// second beyond what the time since the last report (at most a few tenths) would give. +fn jumped(before: &Now, now: &Now) -> bool { + before.track == now.track && now.status != "Stopped" && (now.position < before.position - 0.5 || now.position > before.position + 1.5) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn playing() -> Now { + Now { status: "Playing", track: 1, path: Some("/m/Night Drive.flac".into()), title: Some("Night Drive".into()), artist: Some("The Test Signals".into()), album: Some("Calibration".into()), length: 221.0, position: 52.0, volume: 80.0, can_go_next: true, can_go_previous: true } + } + + #[test] + fn metadata_has_the_track_its_length_and_tags() { + let m = playing().metadata(); + assert_eq!(m.get("mpris:length").and_then(|v| i64::try_from(v.clone()).ok()), Some(221_000_000)); + assert_eq!(m.get("xesam:title").and_then(|v| String::try_from(v.clone()).ok()).as_deref(), Some("Night Drive")); + assert_eq!(m.get("xesam:url").and_then(|v| String::try_from(v.clone()).ok()).as_deref(), Some("file:///m/Night%20Drive.flac")); + assert!(m.contains_key("mpris:trackid") && m.contains_key("xesam:artist") && m.contains_key("xesam:album")); + } + + #[test] + fn stopped_has_the_no_track_id_only() { + let m = Now { status: "Stopped", ..Now::default() }.metadata(); + assert_eq!(m.len(), 1); + } + + #[test] + fn a_seek_is_told_from_playing_on() { + let a = playing(); + assert!(!jumped(&a, &Now { position: 52.3, ..playing() }), "playing on"); + assert!(jumped(&a, &Now { position: 57.0, ..playing() }), "forward 5 s"); + assert!(jumped(&a, &Now { position: 47.0, ..playing() }), "back 5 s"); + assert!(!jumped(&a, &Now { position: 0.0, track: 2, ..playing() }), "a new track isn't a seek"); + } +} From 713294acccb4ee694ab1230932d05681884e4f8a Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:16:56 -0700 Subject: [PATCH 05/23] alias-playback: follow #3 to 6afd318 (#2's warm start, Intel and review fixes) --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 48bb754..f994443 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#fd8ddc3d9bcf552af15047f37e5e46114e934f74" +source = "git+https://github.com/aliasproject/alias-playback?branch=ali-2358-gpu-media#6afd318e86af0b294dce49af3c34b2430cab32c6" dependencies = [ "libc", "rustix", From 8add44524da22e3851cde49df2040d9cc429f9d3 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:27:55 -0700 Subject: [PATCH 06/23] Review fixes: buffers the helper sends, frames on resize, failures, FIFOs, full screen - A buffer the helper sends is checked before it reaches the compositor: its format and modifier must be one the compositor listed (dmabuf feedback's table, or v3's events) and its planes must fit in the dmabuf. A bad one was a protocol error that closed the window; now the file can't play and says why. - A buffer replaced while on screen is destroyed with the video layer if it's never let go. - A buffer the compositor lets go while still on screen goes back to the helper once the next frame replaces it; before, the slot was lost, and after three the video froze. - The frame on screen moves to the middle of the window when it changes size, even with no new frame coming (paused, ended, a song's cover). - A helper that dies mid-play takes its last frame with it, so the reason shows. - Session::failure ends the helper before waiting for it: the socket can fail with the helper still running, and the wait froze the window. - A path that isn't a regular file (a FIFO) is refused before it's opened, which waited for a writer. - Full screen carries from one video to the next, and ends for a song or a picture. - Left and Right change file when the file can't play, as for pictures. --- src/app.rs | 16 ++++++--- src/player/gpu.rs | 20 +++++++++++ src/player/mod.rs | 57 ++++++++++++++++++++++++++++--- src/wl.rs | 87 +++++++++++++++++++++++++++++++++++++++++------ 4 files changed, 162 insertions(+), 18 deletions(-) diff --git a/src/app.rs b/src/app.rs index a785b92..65ffb39 100644 --- a/src/app.rs +++ b/src/app.rs @@ -233,6 +233,10 @@ impl App { Some((path, _)) if self.media.as_ref().is_some_and(|m| m.path == path) => {} Some((path, kind)) => { 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 { + wl.set_fullscreen(false); + } let b = self.media_box(kind); let size = (b.w.max(1) as u32, b.h.max(1) as u32); self.media = Some(if wl.can_show_video() { @@ -246,6 +250,9 @@ impl App { None => { if self.media.is_some() { self.close_media(wl); + if wl.state.fullscreen { + wl.set_fullscreen(false); + } self.all(); self.a11y_dirty = true; } @@ -254,6 +261,9 @@ impl App { 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) { @@ -270,9 +280,6 @@ impl App { } drop(old); wl.video_end(); - if wl.state.fullscreen { - wl.set_fullscreen(false); - } } } @@ -734,7 +741,8 @@ impl App { } // In a video or song, Left and Right seek; n, p, Page Up and Page Down still // change file (Mike, 2026-12-02). - k::KEY_Left | k::KEY_KP_Left | k::KEY_Right | k::KEY_KP_Right => { + // 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; diff --git a/src/player/gpu.rs b/src/player/gpu.rs index 2df9353..dd7b98a 100644 --- a/src/player/gpu.rs +++ b/src/player/gpu.rs @@ -75,6 +75,10 @@ impl Session { /// Starts a helper for `path` on the card at `node`, drawing into a box of `size` /// physical pixels. `Err` says why, in words for the screen. pub fn start(path: &Path, node: OwnedFd, size: (u32, u32)) -> Result { + // Only a regular file: opening a FIFO would wait for a writer, with the window stuck. + if std::fs::metadata(path).is_ok_and(|m| !m.is_file()) { + return Err("it isn't a regular file".into()); + } let file = File::open(path).map_err(|e| match e.kind() { std::io::ErrorKind::NotFound => "it isn't there any more".to_string(), std::io::ErrorKind::PermissionDenied => "you don't have permission to read it".to_string(), @@ -130,6 +134,10 @@ impl Session { /// After `gone`: why, if it wasn't a clean exit. Waits for the helper, which has /// closed its socket and so is ending. pub fn failure(&mut self) -> Option { + // Its socket can also fail with the helper still running: ended first, so this never + // waits on it. On one that has already exited, the kill does nothing and its own + // exit code is read. + let _ = self.child.kill(); let status = self.child.wait().ok()?; match status.code() { Some(0) => None, @@ -185,6 +193,18 @@ pub fn helper_main(args: &[String]) -> ! { mod tests { use super::*; + #[test] + fn a_fifo_is_refused_without_waiting_for_a_writer() { + let dir = std::env::temp_dir().join(format!("alias-view-fifo-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let fifo = dir.join("x.mp4"); + rustix::fs::mknodat(rustix::fs::CWD, &fifo, rustix::fs::FileType::Fifo, rustix::fs::Mode::from_raw_mode(0o600), 0).unwrap(); + let node = OwnedFd::from(File::open("/dev/null").unwrap()); + let started = Session::start(&fifo, node, (64, 64)); + assert_eq!(started.err().as_deref(), Some("it isn't a regular file")); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn commands_are_the_lines_the_helper_reads() { assert_eq!(Command::SeekBy(-5.0).line(), "seek -5.000"); diff --git a/src/player/mod.rs b/src/player/mod.rs index 3261085..6d96c30 100644 --- a/src/player/mod.rs +++ b/src/player/mod.rs @@ -81,6 +81,10 @@ pub struct Media { pub error: Option, /// The size asked of the helper, so it's only told of changes. asked: (u32, u32), + /// 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. + placed: Option, } impl Media { @@ -99,6 +103,8 @@ impl Media { meta: Meta::default(), error: None, asked: size, + released_early: [false; VIDEO_SLOTS], + placed: None, }; match node.and_then(|node| Session::start(&m.path, node, size)) { Ok(s) => { @@ -166,11 +172,27 @@ impl Media { /// The compositor let a buffer go. pub fn released(&mut self, slot: usize) { - if self.shown != Some(slot) { + if self.shown == Some(slot) { + // Some compositors let go of a buffer they've copied while it's still attached: + // it goes back once the next frame replaces it, or the slot would be lost. + self.released_early[slot] = true; + } else if slot < VIDEO_SLOTS { self.send(Command::Release(slot)); } } + /// The window or the frame's box changed: the frame on screen moves to the middle of + /// the new box, even with no new frame coming (paused, ended, a song's cover). + pub fn replace(&mut self, wl: &mut Wl, frame_box: Rect, scale: f64) { + if self.placed == Some(frame_box) { + return; + } + if let Some(b) = self.shown.and_then(|s| self.buffers[s]) { + wl.video_place(centre(b.width, b.height, frame_box, scale)); + self.placed = Some(frame_box); + } + } + /// Reads the helper's messages and acts on them: buffers become `wl_buffer`s, frames /// are shown centred in `frame_box` (physical px; `scale` turns them logical). Returns /// true if what's drawn or said about it changed. @@ -186,8 +208,13 @@ impl Media { let Some(fd) = fds.pop().filter(|_| fds.is_empty()) else { continue }; let b = VideoBuffer { width, height, fourcc, modifier, stride, offset }; wl.video_begin(); - wl.video_buffer(slot, fd, b); + if let Err(why) = wl.video_buffer(slot, fd, b) { + self.error = Some(why); + changed = true; + continue; + } self.buffers[slot] = Some(b); + self.released_early[slot] = false; if self.shown == Some(slot) { self.shown = None; } @@ -198,9 +225,15 @@ impl Media { continue; }; let place = centre(b.width, b.height, frame_box, scale); - // The one shown until now is given back when the compositor releases it. + // The one shown until now is given back when the compositor releases it, + // or now if it already has. if wl.video_frame(slot, place) { - self.shown = Some(slot); + if let Some(old) = self.shown.replace(slot).filter(|o| *o != slot) + && std::mem::take(&mut self.released_early[old]) + { + self.send(Command::Release(old)); + } + self.placed = Some(frame_box); if self.has_picture != Some(true) { self.has_picture = Some(true); changed = true; @@ -247,6 +280,12 @@ impl Media { self.session = None; changed = true; } + // A file that can't play shows its reason, not a frozen frame over it. + if self.error.is_some() && self.shown.is_some() { + self.shown = None; + self.placed = None; + wl.video_end(); + } changed } @@ -304,6 +343,16 @@ mod tests { assert_eq!(clock(-4.0), "0:00"); } + #[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()); + m.shown = Some(1); + m.released(1); + assert!(m.released_early[1], "remembered, to give back once the next frame is up"); + m.released(2); + assert!(!m.released_early[2], "one not on screen goes straight back"); + } + #[test] fn a_frame_sits_in_the_middle_of_its_box() { assert_eq!(centre(1920, 800, Rect::new(0, 0, 1920, 1080), 1.0), (0, 140, 1920, 800)); diff --git a/src/wl.rs b/src/wl.rs index 01321bb..18f2c1b 100644 --- a/src/wl.rs +++ b/src/wl.rs @@ -111,6 +111,8 @@ struct VideoLayer { /// Where it sits, in logical px, and the buffer on it. place: Option<(i32, i32, i32, i32)>, shown: Option, + /// Buffers replaced while on screen, destroyed when let go, or with the layer. + retired: Vec, } /// A video buffer's slot, as its `wl_buffer`'s data. @@ -182,6 +184,9 @@ pub struct State { dmabuf: Option, /// The compositor's main graphics device (`dev_t`), from dmabuf feedback. main_device: Option, + /// The dmabuf formats and modifiers the compositor takes, so a buffer it would refuse + /// (a protocol error that would close the window) is refused here first. + dmabuf_formats: std::collections::HashSet<(u32, u64)>, video: Option, /// In full screen, as the compositor last said. pub fullscreen: bool, @@ -269,6 +274,7 @@ impl Wl { subcompositor: None, dmabuf: None, main_device: None, + dmabuf_formats: Default::default(), video: None, fullscreen: false, pending_fullscreen: false, @@ -416,14 +422,26 @@ impl Wl { surface.set_input_region(Some(&empty)); empty.destroy(); let viewport = s.viewporter.as_ref().map(|v| v.get_viewport(&surface, &self.qh, ())); - s.video = Some(VideoLayer { surface, sub, viewport, buffers: Default::default(), place: None, shown: None }); + s.video = Some(VideoLayer { surface, sub, viewport, buffers: Default::default(), place: None, shown: None, retired: Vec::new() }); } /// The helper described a buffer and sent its dmabuf: makes the `wl_buffer` for it. - pub fn video_buffer(&mut self, slot: usize, fd: OwnedFd, b: VideoBuffer) { - let (Some(d), Some(v)) = (&self.state.dmabuf, &mut self.state.video) else { return }; + /// `Err` says why it can't be shown. The helper isn't trusted, and a buffer the + /// compositor refuses would be a protocol error, closing the window: the format must be + /// one the compositor listed, and the planes must fit in the dmabuf. + pub fn video_buffer(&mut self, slot: usize, fd: OwnedFd, b: VideoBuffer) -> Result<(), String> { + let formats = &self.state.dmabuf_formats; + let (Some(d), Some(v)) = (&self.state.dmabuf, &mut self.state.video) else { return Err("there's no video surface".into()) }; if slot >= VIDEO_SLOTS { - return; + return Err("the player sent a buffer it shouldn't have".into()); + } + if !formats.is_empty() && !formats.contains(&(b.fourcc, b.modifier)) { + return Err("the desktop can't show frames in the form the player made them".into()); + } + let len = rustix::fs::seek(&fd, rustix::fs::SeekFrom::End(0)).unwrap_or(0); + let needs = u64::from(b.offset) + u64::from(b.stride) * u64::from(b.height); + if needs > len { + return Err("the player sent a frame smaller than it said".into()); } let params = d.create_params(&self.qh, ()); params.add(fd.as_fd(), 0, b.offset, b.stride, (b.modifier >> 32) as u32, b.modifier as u32); @@ -431,13 +449,33 @@ impl Wl { params.destroy(); if let Some((old, _)) = v.buffers[slot].replace((wl, b)) { // Still on screen: destroyed when the compositor lets it go (see the release). - if v.shown != Some(slot) { + if v.shown == Some(slot) { + v.retired.push(old); + } else { old.destroy(); } } if v.shown == Some(slot) { v.shown = None; } + Ok(()) + } + + /// Moves the frame on screen to `place`, as when the window changes size while paused. + pub fn video_place(&mut self, place: (i32, i32, i32, i32)) { + let Some(v) = &mut self.state.video else { return }; + if v.shown.is_none() || v.place == Some(place) { + return; + } + v.sub.set_position(place.0, place.1); + if let Some(vp) = &v.viewport { + vp.set_destination(place.2.max(1), place.3.max(1)); + } + v.place = Some(place); + v.surface.commit(); + if let Some(p) = &self.state.surface { + p.commit(); + } } /// Shows the frame in `slot` at `place`: x, y, width and height in logical px. Returns @@ -470,6 +508,9 @@ impl Wl { for (wl, _) in v.buffers.into_iter().flatten() { wl.destroy(); } + for wl in v.retired { + wl.destroy(); + } if let Some(vp) = v.viewport { vp.destroy(); } @@ -772,18 +813,41 @@ ignore_events!( wl_subcompositor::WlSubcompositor, wl_subsurface::WlSubsurface, wl_region::WlRegion, - dmabuf::ZwpLinuxDmabufV1, dmabuf_params::ZwpLinuxBufferParamsV1, ); +impl Dispatch for State { + fn event(s: &mut State, _: &dmabuf::ZwpLinuxDmabufV1, e: dmabuf::Event, _: &(), _: &Connection, _: &QueueHandle) { + // Version 3 lists formats as events; version 4 sends the table instead. + if let dmabuf::Event::Modifier { format, modifier_hi, modifier_lo } = e { + s.dmabuf_formats.insert((format, (u64::from(modifier_hi) << 32) | u64::from(modifier_lo))); + } + } +} + impl Dispatch for State { fn event(s: &mut State, _: &dmabuf_feedback::ZwpLinuxDmabufFeedbackV1, e: dmabuf_feedback::Event, _: &(), _: &Connection, _: &QueueHandle) { // The format table's descriptor is dropped with the event: formats are the // helper's choice, and every compositor takes XRGB8888. - if let dmabuf_feedback::Event::MainDevice { device } = e - && let Ok(bytes) = <[u8; 8]>::try_from(device.as_slice()) - { - s.main_device = Some(u64::from_ne_bytes(bytes)); + match e { + dmabuf_feedback::Event::MainDevice { device } => { + if let Ok(bytes) = <[u8; 8]>::try_from(device.as_slice()) { + s.main_device = Some(u64::from_ne_bytes(bytes)); + } + } + // Read rather than mapped, as this file has no unsafe code: 16 bytes an entry, + // the format (u32), padding, then the modifier (u64). + dmabuf_feedback::Event::FormatTable { fd, size } => { + let mut table = vec![0u8; (size as usize).min(1 << 20)]; + if File::from(fd).read_exact_at(&mut table, 0).is_ok() { + for e in table.as_chunks::<16>().0 { + let format = u32::from_ne_bytes([e[0], e[1], e[2], e[3]]); + let modifier = u64::from_ne_bytes([e[8], e[9], e[10], e[11], e[12], e[13], e[14], e[15]]); + s.dmabuf_formats.insert((format, modifier)); + } + } + } + _ => {} } } } @@ -797,6 +861,9 @@ impl Dispatch for State { if current { s.inputs.push_back(Input::VideoReleased(slot.0)); } else { + if let Some(v) = &mut s.video { + v.retired.retain(|r| r != b); + } b.destroy(); } } From d13d9cf32593efeb39b7b5f0aefa6c7629105aba Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:32:28 -0700 Subject: [PATCH 07/23] alias-playback: follow #3 to 74c8c87 (cover art always drawn, warm-load fixes) --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index f994443..430fb97 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#6afd318e86af0b294dce49af3c34b2430cab32c6" +source = "git+https://github.com/aliasproject/alias-playback?branch=ali-2358-gpu-media#74c8c8715ed6a1ced9d691db3caf3cf86ec7ea26" dependencies = [ "libc", "rustix", From 5648de2866ccc3d9fdf5d446d30d4485c0928c4f Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:40:38 -0700 Subject: [PATCH 08/23] Review round 2: a failed file's helper ends; a helper's exit code is kept - A file that can't play (a refused buffer, or the helper saying it can't) ends its helper, so no sound plays on under the reason, and frames that still arrive are given back, not shown. - A helper that closed its socket cleanly is waited for, not killed, so its exit code says why (libmpv missing, the sandbox not set up). Only after a read error is it ended first. - The format table comment says what the table is now used for. --- src/player/gpu.rs | 16 +++++++++++----- src/player/mod.rs | 7 +++++++ src/wl.rs | 4 ++-- 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/src/player/gpu.rs b/src/player/gpu.rs index dd7b98a..3156264 100644 --- a/src/player/gpu.rs +++ b/src/player/gpu.rs @@ -69,6 +69,9 @@ pub struct Session { socket: OwnedFd, /// The socket has closed: the helper is gone. pub gone: bool, + /// It closed cleanly (end of stream), as a helper exiting does; not a read error with + /// the helper perhaps still running. + closed_cleanly: bool, } impl Session { @@ -93,7 +96,7 @@ impl Session { if e.kind() == std::io::ErrorKind::NotFound { "bubblewrap (bwrap), which keeps video in a sandbox, isn't installed".to_string() } else { format!("the player didn't start ({e})") } })?; rustix::io::ioctl_fionbio(&socket, true).map_err(|_| "the player didn't start".to_string())?; - Ok(Session { child, socket, gone: false }) + Ok(Session { child, socket, gone: false, closed_cleanly: false }) } /// For the loop's poll. @@ -114,6 +117,7 @@ impl Session { } Ok(None) => { self.gone = true; + self.closed_cleanly = true; break; } Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, @@ -134,10 +138,12 @@ impl Session { /// After `gone`: why, if it wasn't a clean exit. Waits for the helper, which has /// closed its socket and so is ending. pub fn failure(&mut self) -> Option { - // Its socket can also fail with the helper still running: ended first, so this never - // waits on it. On one that has already exited, the kill does nothing and its own - // exit code is read. - let _ = self.child.kill(); + // A clean end of the socket is the helper exiting: bubblewrap follows once it has + // reaped it, with its exit code, which says why. After a read error the helper may + // still be running, so it's ended first and never waited on. + if !self.closed_cleanly { + let _ = self.child.kill(); + } let status = self.child.wait().ok()?; match status.code() { Some(0) => None, diff --git a/src/player/mod.rs b/src/player/mod.rs index 6d96c30..1f5cb54 100644 --- a/src/player/mod.rs +++ b/src/player/mod.rs @@ -219,6 +219,8 @@ impl Media { self.shown = None; } } + // A file that can't play shows its reason; no more frames go up. + Said::Frame { slot } if self.error.is_some() => self.send(Command::Release(slot)), Said::Frame { slot } => { let Some(b) = self.buffers[slot] else { self.send(Command::Release(slot)); @@ -280,6 +282,11 @@ impl Media { self.session = None; changed = true; } + // A file that can't play stops: its helper ends (with the session), so no sound + // plays on under the reason. + if self.error.is_some() && self.session.is_some() { + self.session = None; + } // A file that can't play shows its reason, not a frozen frame over it. if self.error.is_some() && self.shown.is_some() { self.shown = None; diff --git a/src/wl.rs b/src/wl.rs index 18f2c1b..f17ead4 100644 --- a/src/wl.rs +++ b/src/wl.rs @@ -827,8 +827,8 @@ impl Dispatch for State { impl Dispatch for State { fn event(s: &mut State, _: &dmabuf_feedback::ZwpLinuxDmabufFeedbackV1, e: dmabuf_feedback::Event, _: &(), _: &Connection, _: &QueueHandle) { - // The format table's descriptor is dropped with the event: formats are the - // helper's choice, and every compositor takes XRGB8888. + // The main device says which card to draw on; the format table which buffers the + // compositor takes, so a bad one from the helper is refused before it's sent. match e { dmabuf_feedback::Event::MainDevice { device } => { if let Ok(bytes) = <[u8; 8]>::try_from(device.as_slice()) { From 683afab0bfacc31de051450b0a60c1b65fec588e Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:43:19 -0700 Subject: [PATCH 09/23] MPRIS review fixes: play and pause while opening, Seeked, signals, the bus off the loop - Play and Pause do what they say while a file opens (Play no longer toggled it to paused; Pause no longer did nothing), and Opening reads as Playing. - Seeked is sent for each real seek (keys, the slider, Seek, SetPosition, the screen reader) with where it went, not guessed from jumps in position. - Each property is signalled once and only when it changed: Metadata not on a pause, and CanSeek once. - Volume reads 0 while muted, and a Volume set is known at once, so its change signal carries the new value. - Seek past the end goes to the next track; SetPosition is ignored when stopped or past the end, as the spec says. - Next and Previous (and CanGoNext and CanGoPrevious) go to the next video or song, past pictures, going round. - A volume set or seek from a controller is announced as a key's would be. - The session bus is joined on a thread, so a slow bus never holds up the window; what MPRIS says is rebuilt only when it changed, with Position stored on each wake. - The zbus comment is back above its own line. --- Cargo.toml | 6 +-- src/app/player_ui.rs | 87 +++++++++++++++++++++++++------- src/main.rs | 27 ++++++++-- src/mpris.rs | 117 +++++++++++++++++++++++++++---------------- src/player/mod.rs | 26 ++++++++++ 5 files changed, 194 insertions(+), 69 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 0c2a33d..07eb751 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,12 +28,12 @@ wayland-protocols = { version = "0.32.13", features = ["client", "staging", "uns 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. # MPRIS on the session bus (src/mpris.rs). Already built for accesskit_unix, with the # same async-io executor; blocking-api adds only the blocking wrappers. zbus = { version = "5.19.0", default-features = false, features = ["async-io", "blocking-api"] } +# 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" } [profile.release] diff --git a/src/app/player_ui.rs b/src/app/player_ui.rs index fe87f70..e4f6c12 100644 --- a/src/app/player_ui.rs +++ b/src/app/player_ui.rs @@ -585,14 +585,50 @@ impl App { } impl App { + /// What MPRIS would be told, cheaply: when this is unchanged, so is what it says. + pub fn mpris_key(&self) -> Option<(u64, u8, i64, i64, bool, bool, bool)> { + let m = self.media.as_ref()?; + let phase = match m.phase() { + Phase::Opening => 0, + Phase::Playing => 1, + Phase::Paused => 2, + Phase::Ended => 3, + Phase::Failed(_) => 4, + }; + let (next, previous) = self.media_neighbours(); + let tags = m.meta.title.is_some() || m.meta.artist.is_some() || m.meta.album.is_some(); + Some((self.track, phase, (m.state.duration * 10.0) as i64, if m.state.muted { -1 } else { m.state.volume as i64 }, next.is_some(), previous.is_some(), tags)) + } + + /// The next and previous video or song in the list, going round, if any other. + fn media_neighbours(&self) -> (Option, Option) { + let n = self.files.len(); + let is_media = |i: usize| crate::player::kind_of(&self.files[i]).is_some(); + let next = (1..n).map(|d| (self.cur + d) % n).find(|i| is_media(*i)); + let previous = (1..n).map(|d| (self.cur + n - d) % n).find(|i| is_media(*i)); + (next, previous) + } + + /// Where playback is, for MPRIS's Position. + pub fn mpris_position(&self) -> Option { + let m = self.media.as_ref()?; + Some(if m.state.ended { m.state.duration } else { m.state.position }) + } + + /// Where the last seek went, for MPRIS's Seeked signal. + pub fn take_seeked(&mut self) -> Option { + self.media.as_mut()?.take_seeked() + } + /// What's playing, for MPRIS. pub fn mpris_now(&self) -> crate::mpris::Now { - let many = self.files.len() > 1; let Some(m) = &self.media else { return crate::mpris::Now { status: "Stopped", ..Default::default() } }; + let (next, previous) = self.media_neighbours(); let status = match m.phase() { - Phase::Playing => "Playing", + // Opening plays once loaded, unless paused meanwhile. + Phase::Playing | Phase::Opening => "Playing", Phase::Failed(_) => "Stopped", - _ => "Paused", + Phase::Paused | Phase::Ended => "Paused", }; crate::mpris::Now { status, @@ -603,13 +639,14 @@ impl App { album: m.meta.album.clone(), length: m.state.duration.max(0.0), position: if m.state.ended { m.state.duration } else { m.state.position }, - volume: m.state.volume, - can_go_next: many, - can_go_previous: many, + volume: if m.state.muted { 0.0 } else { m.state.volume }, + can_go_next: next.is_some(), + can_go_previous: previous.is_some(), } } - /// A media controller (the bar, playerctl, the screensaver) asked for something. + /// A media controller (the bar, playerctl, the screensaver) asked for something. Next + /// and Previous go to the next video or song, past any pictures between. pub fn mpris_request(&mut self, r: crate::mpris::Request) { use crate::mpris::Request; if r == Request::Quit { @@ -622,31 +659,32 @@ impl App { match r { Request::PlayPause => self.toggle_media(), Request::Play => { - if self.media.as_ref().is_some_and(|m| m.phase() != Phase::Playing) { - self.toggle_media(); + if let Some(m) = &mut self.media { + m.play(); } } Request::Pause => { - if self.media.as_ref().is_some_and(|m| m.phase() == Phase::Playing) { - self.toggle_media(); + if let Some(m) = &mut self.media { + m.pause(); } } - Request::Next => self.step(1, false), - Request::Previous => self.step(-1, false), - Request::SeekBy(s) => { - if let Some(m) = &mut self.media { - m.seek_by(s); + Request::Next | Request::Previous => { + let (next, previous) = self.media_neighbours(); + if let Some(i) = if r == Request::Next { next } else { previous } { + self.go(i); } } Request::SeekTo(s) => { if let Some(m) = &mut self.media { m.seek_to(s); } + self.seek_said_at = Some(Instant::now() + motion::SEEK_ANNOUNCE); } Request::Volume(v) => { - if let Some(m) = &mut self.media { - m.set_volume(v); - } + let Some(m) = &mut self.media else { return }; + m.set_volume(v); + let said = format!("Volume {:.0}%", m.state.volume); + self.say(said); } Request::Quit => {} } @@ -670,4 +708,15 @@ mod tests { assert!(!may_hide(Kind::Video, &Phase::Playing, Some(Control::Play), None)); assert!(!may_hide(Kind::Video, &Phase::Playing, None, Some(Control::Position))); } + + #[test] + fn media_controllers_skip_pictures_and_go_round() { + let files: Vec = ["a.mp4", "b.jpg", "c.flac", "d.png"].iter().map(|f| std::path::PathBuf::from(format!("/m/{f}"))).collect(); + let mut app = App::new(files, 2, crate::theme::builtin(true), crate::loader::Loader::new(1), 1); + assert_eq!(app.media_neighbours(), (Some(0), Some(0)), "from the song, the video either way"); + app.cur = 0; + assert_eq!(app.media_neighbours(), (Some(2), Some(2))); + app.files = vec!["/m/only.mp4".into(), "/m/x.jpg".into()]; + assert_eq!(app.media_neighbours(), (None, None), "no other video or song"); + } } diff --git a/src/main.rs b/src/main.rs index 4311f28..b6b537e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -245,6 +245,8 @@ fn run(o: Opening) -> i32 { let mut folder_of = o.folder_of; let mut a11y: Option = None; let mut mpris: Option = None; + let mut mpris_joining: Option>> = None; + let mut mpris_said = None; let mut mpris_tried = false; let mut first_frame = true; let mut configured_at: Option = None; @@ -289,17 +291,34 @@ fn run(o: Opening) -> i32 { if wl.state.configured { app.sync_media(&mut wl); } - // MPRIS, from the first video or song on, when there's a session bus. - if mpris.is_none() && !mpris_tried && app.media.is_some() { + // MPRIS, from the first video or song on, when there's a session bus; joined on a + // thread, so a slow bus never holds up the window. + if !mpris_tried && app.media.is_some() { mpris_tried = true; - mpris = if a11y::session_bus_exists() { mpris::Mpris::start() } else { None }; + mpris_joining = a11y::session_bus_exists().then(mpris::Mpris::spawn); + } + if let Some(rx) = &mpris_joining + && let Ok(joined) = rx.try_recv() + { + mpris = joined; + mpris_joining = None; } if let Some(m) = &mpris { let reqs: Vec<_> = m.requests.try_iter().collect(); for r in reqs { app.mpris_request(r); } - m.update(app.mpris_now()); + if let Some(at) = app.take_seeked() { + m.seeked(at); + } + // Built only when something it says changed, not on every wake. + let key = app.mpris_key(); + if key != mpris_said { + m.update(app.mpris_now()); + mpris_said = key; + } else if let Some(at) = app.mpris_position() { + m.set_position(at); + } } if let Some(a) = &a11y { let reqs: Vec<_> = a.actions.try_iter().collect(); diff --git a/src/mpris.rs b/src/mpris.rs index b198347..492e30e 100644 --- a/src/mpris.rs +++ b/src/mpris.rs @@ -26,8 +26,6 @@ pub enum Request { Pause, Next, Previous, - /// By this many seconds. - SeekBy(f64), /// To this many seconds from the start. SeekTo(f64), /// 0 to 100. @@ -48,7 +46,7 @@ pub struct Now { pub album: Option, pub length: f64, pub position: f64, - /// 0 to 100. + /// 0 to 100; 0 while muted. pub volume: f64, pub can_go_next: bool, pub can_go_previous: bool, @@ -196,15 +194,26 @@ impl Player { self.0.ask(Request::Play); } + /// Past the end is the next track, and before the start the start, as the spec says. fn seek(&self, offset: i64) { - self.0.ask(Request::SeekBy(offset as f64 / US)); + let now = self.0.now(); + if now.status == "Stopped" { + return; + } + let to = now.position + offset as f64 / US; + if now.length > 0.0 && to > now.length { + self.0.ask(Request::Next); + } else { + self.0.ask(Request::SeekTo(to.max(0.0))); + } } + /// Only for the track playing now, and only within it, as the spec says. fn set_position(&self, track_id: ObjectPath<'_>, position: i64) { - // Only for the track playing now, as the spec says. let now = self.0.now(); - if track_id.as_str() == format!("/com/aliasproject/view/track/{}", now.track) && position >= 0 { - self.0.ask(Request::SeekTo(position as f64 / US)); + let at = position as f64 / US; + if now.status != "Stopped" && track_id.as_str() == format!("/com/aliasproject/view/track/{}", now.track) && position >= 0 && at <= now.length { + self.0.ask(Request::SeekTo(at)); } } @@ -251,7 +260,12 @@ impl Player { #[zbus(property)] fn set_volume(&self, v: f64) { if v.is_finite() { - self.0.ask(Request::Volume((v * 100.0).clamp(0.0, 100.0))); + let v = (v * 100.0).clamp(0.0, 100.0); + // Known at once, so the change signal sent after this setter has the new value. + if let Ok(mut n) = self.0.now.lock() { + n.volume = v; + } + self.0.ask(Request::Volume(v)); } } @@ -299,26 +313,41 @@ pub struct Mpris { } impl Mpris { + /// Joins the session bus on a thread of its own, so a slow bus never holds up the + /// window: the result arrives on the receiver, with a wake. + pub fn spawn() -> Receiver> { + let (tx, rx) = channel(); + let _ = std::thread::Builder::new().name("alias-view-mpris".into()).spawn(move || { + let _ = tx.send(Mpris::start()); + crate::wake::wake(); + }); + rx + } + + /// Where playback is, for controllers that read Position: stored, never signalled. + pub fn set_position(&self, at: f64) { + if let Ok(mut n) = self.shared.now.lock() { + n.position = at; + } + } + + /// A seek went to `at` seconds: tells controllers, which otherwise only read Position. + pub fn seeked(&self, at: f64) { + let Ok(iface) = self.conn.object_server().interface::<_, Player>(PATH) else { return }; + let _ = zbus::block_on(Player::seeked(iface.signal_emitter(), (at * US) as i64)); + } + /// Joins the session bus. `None` if there isn't one or the name can't be had. - pub fn start() -> Option { + fn start() -> Option { let (tx, requests) = channel(); let shared = Arc::new(Shared { now: Mutex::new(Now { status: "Stopped", ..Now::default() }), tx: Mutex::new(tx) }); let name = format!("org.mpris.MediaPlayer2.alias_view.instance{}", std::process::id()); - let conn = zbus::blocking::connection::Builder::session() - .ok()? - .name(name) - .ok()? - .serve_at(PATH, Root(shared.clone())) - .ok()? - .serve_at(PATH, Player(shared.clone())) - .ok()? - .build() - .ok()?; + let conn = zbus::blocking::connection::Builder::session().ok()?.name(name).ok()?.serve_at(PATH, Root(shared.clone())).ok()?.serve_at(PATH, Player(shared.clone())).ok()?.build().ok()?; Some(Mpris { conn, shared, requests }) } - /// What's playing now. Signals what changed; a jump in position other than by playing - /// is signalled as `Seeked`. + /// What's playing now. Signals each property that changed, once. Position isn't + /// signalled (MPRIS has controllers read it); a seek is, with [`Mpris::seeked`]. pub fn update(&self, now: Now) { let before = { let Ok(mut n) = self.shared.now.lock() else { return }; @@ -330,16 +359,24 @@ impl Mpris { let Ok(iface) = self.conn.object_server().interface::<_, Player>(PATH) else { return }; let player = iface.get(); let e = iface.signal_emitter(); + let status = before.status != now.status; + let stopped = (before.status == "Stopped") != (now.status == "Stopped"); + let metadata = + stopped || before.track != now.track || before.title != now.title || before.artist != now.artist || before.album != now.album || before.length != now.length || before.path != now.path; + let can_seek = stopped || (before.length > 0.0) != (now.length > 0.0); zbus::block_on(async { - if before.status != now.status { + if status { let _ = player.playback_status_changed(e).await; + } + if stopped { let _ = player.can_play_changed(e).await; let _ = player.can_pause_changed(e).await; + } + if can_seek { let _ = player.can_seek_changed(e).await; } - if before.track != now.track || before.title != now.title || before.artist != now.artist || before.album != now.album || before.length != now.length || before.status != now.status { + if metadata { let _ = player.metadata_changed(e).await; - let _ = player.can_seek_changed(e).await; } if before.volume != now.volume { let _ = player.volume_changed(e).await; @@ -350,25 +387,28 @@ impl Mpris { if before.can_go_previous != now.can_go_previous { let _ = player.can_go_previous_changed(e).await; } - if jumped(&before, &now) { - let _ = Player::seeked(e, (now.position * US) as i64).await; - } }); } } -/// A move in position that playing doesn't explain: back at all, or forward by more than a -/// second beyond what the time since the last report (at most a few tenths) would give. -fn jumped(before: &Now, now: &Now) -> bool { - before.track == now.track && now.status != "Stopped" && (now.position < before.position - 0.5 || now.position > before.position + 1.5) -} - #[cfg(test)] mod tests { use super::*; fn playing() -> Now { - Now { status: "Playing", track: 1, path: Some("/m/Night Drive.flac".into()), title: Some("Night Drive".into()), artist: Some("The Test Signals".into()), album: Some("Calibration".into()), length: 221.0, position: 52.0, volume: 80.0, can_go_next: true, can_go_previous: true } + Now { + status: "Playing", + track: 1, + path: Some("/m/Night Drive.flac".into()), + title: Some("Night Drive".into()), + artist: Some("The Test Signals".into()), + album: Some("Calibration".into()), + length: 221.0, + position: 52.0, + volume: 80.0, + can_go_next: true, + can_go_previous: true, + } } #[test] @@ -385,13 +425,4 @@ mod tests { let m = Now { status: "Stopped", ..Now::default() }.metadata(); assert_eq!(m.len(), 1); } - - #[test] - fn a_seek_is_told_from_playing_on() { - let a = playing(); - assert!(!jumped(&a, &Now { position: 52.3, ..playing() }), "playing on"); - assert!(jumped(&a, &Now { position: 57.0, ..playing() }), "forward 5 s"); - assert!(jumped(&a, &Now { position: 47.0, ..playing() }), "back 5 s"); - assert!(!jumped(&a, &Now { position: 0.0, track: 2, ..playing() }), "a new track isn't a seek"); - } } diff --git a/src/player/mod.rs b/src/player/mod.rs index 1318891..a8eb4c7 100644 --- a/src/player/mod.rs +++ b/src/player/mod.rs @@ -85,6 +85,8 @@ pub struct Media { asked: (u32, u32), /// A song that ended has gone on to the next one (or found none), once. pub advanced: bool, + /// Where a seek just went, for MPRIS's Seeked signal. + seeked: Option, /// 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. @@ -108,6 +110,7 @@ impl Media { error: None, asked: size, advanced: false, + seeked: None, released_early: [false; VIDEO_SLOTS], placed: None, }; @@ -165,6 +168,28 @@ impl Media { } } + /// Plays, whatever the state: from the start after the end. Opening, it plays once + /// loaded, as it would anyway. + pub fn play(&mut self) { + match self.phase() { + Phase::Ended => self.toggle(), + Phase::Paused | Phase::Opening => self.send(Command::Play), + Phase::Playing | Phase::Failed(_) => {} + } + } + + /// Pauses, opening too, so it stays paused once loaded. + pub fn pause(&mut self) { + if matches!(self.phase(), Phase::Playing | Phase::Opening) { + self.send(Command::Pause); + } + } + + /// Where the last seek went, once. + pub fn take_seeked(&mut self) -> Option { + self.seeked.take() + } + /// Seeks by `by` seconds, and shows the new position at once. pub fn seek_by(&mut self, by: f64) { if !self.heard { @@ -182,6 +207,7 @@ impl Media { let at = at.clamp(0.0, self.state.duration.max(0.0)); self.send(Command::SeekTo(at)); self.state.position = at; + self.seeked = Some(at); self.state.ended = self.state.ended && at >= self.state.duration; } From 756fbf49325d8749e3a15357e097b5cdc24091c5 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:44:11 -0700 Subject: [PATCH 10/23] Commands to the helper wait out a full socket; video needs viewporter - Session::send waited for nothing: the socket is non-blocking (for reading), so a full one dropped the command, and a lost release left the helper a buffer short for good. A full socket is now waited on briefly. - Video is shown only where the compositor has viewporter, which places a frame at any window scale; without it the frame would be drawn at the wrong size. --- src/app.rs | 2 +- src/player/gpu.rs | 15 ++++++++++++++- src/wl.rs | 5 +++-- 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/app.rs b/src/app.rs index 65ffb39..2d58339 100644 --- a/src/app.rs +++ b/src/app.rs @@ -242,7 +242,7 @@ impl App { 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) } else { - Media::failed(path, kind, "this desktop can't show video from another process (it lacks linux-dmabuf)".into()) + Media::failed(path, kind, "this desktop can't show video from another process (it lacks linux-dmabuf or viewporter)".into()) }); self.all(); self.a11y_dirty = true; diff --git a/src/player/gpu.rs b/src/player/gpu.rs index 3156264..37017fb 100644 --- a/src/player/gpu.rs +++ b/src/player/gpu.rs @@ -131,8 +131,21 @@ impl Session { out } + /// Sends a command. The socket doesn't block (for reading), so a full one is waited on + /// briefly rather than the command dropped: a lost `release` would leave the helper a + /// buffer short for good. pub fn send(&self, c: Command) { - let _ = gpu_helper::send(&self.socket, &c.line(), &[]); + let line = c.line(); + for _ in 0..10 { + match gpu_helper::send(&self.socket, &line, &[]) { + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { + let mut fds = [rustix::event::PollFd::new(&self.socket, rustix::event::PollFlags::OUT)]; + let wait = rustix::time::Timespec { tv_sec: 0, tv_nsec: 20_000_000 }; + let _ = rustix::event::poll(&mut fds, Some(&wait)); + } + _ => return, + } + } } /// After `gone`: why, if it wasn't a clean exit. Waits for the helper, which has diff --git a/src/wl.rs b/src/wl.rs index f17ead4..a9c9d2a 100644 --- a/src/wl.rs +++ b/src/wl.rs @@ -394,9 +394,10 @@ impl Wl { } } - /// Whether video can be shown: the compositor takes dmabufs and subsurfaces. + /// Whether video can be shown: the compositor takes dmabufs and subsurfaces, and can + /// scale a surface (viewporter), which places a frame at any window scale. pub fn can_show_video(&self) -> bool { - self.state.dmabuf.is_some() && self.state.subcompositor.is_some() + self.state.dmabuf.is_some() && self.state.subcompositor.is_some() && self.state.viewporter.is_some() } /// The render node of the card the compositor draws with, when it said which. The From b2f1106f5a4e61fa8b28442157801ec798f5bbc8 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:45:49 -0700 Subject: [PATCH 11/23] Review round 2: back from the grid where it was; hover contrast held; player keys in --help - Opening the grid closes the player; back from it, the same video or song picks up at the position it had, playing or paused as it was, instead of from the start. - The hover fill keeps the icon at 3:1 in any theme: a theme whose border is too close to its text gets a fill moved toward the panel until it passes (with a test). - The key-list fit test covers the player's list too, at 100%, 125% and 200%. - --help lists the player's keys, and the usage and folder messages say videos and songs. --- src/app.rs | 11 ++++++++++- src/app/player_ui.rs | 10 ++++++++++ src/args.rs | 8 ++++---- src/main.rs | 4 ++++ src/player/bar.rs | 24 +++++++++++++++++++++++- src/player/mod.rs | 4 ++++ src/ui.rs | 11 +++++++---- 7 files changed, 62 insertions(+), 10 deletions(-) diff --git a/src/app.rs b/src/app.rs index 2ac934c..5e51849 100644 --- a/src/app.rs +++ b/src/app.rs @@ -111,6 +111,9 @@ pub struct App { 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, } @@ -166,6 +169,7 @@ impl App { seek_said_at: None, last_click: None, toggle_fullscreen: false, + resume: None, fullscreen: false, } } @@ -272,8 +276,11 @@ 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); + 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()) }); @@ -334,6 +341,8 @@ 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(); diff --git a/src/app/player_ui.rs b/src/app/player_ui.rs index a5ad39c..a0523f6 100644 --- a/src/app/player_ui.rs +++ b/src/app/player_ui.rs @@ -114,6 +114,16 @@ impl App { /// 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 { + 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); 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/main.rs b/src/main.rs index 67be871..eba9c92 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) => { diff --git a/src/player/bar.rs b/src/player/bar.rs index fea50af..d903b2e 100644 --- a/src/player/bar.rs +++ b/src/player/bar.rs @@ -147,7 +147,7 @@ pub fn paint(c: &mut Canvas, t: &mut Text, icons: &mut Icons, colors: &Colors, s Control::Volume => slider(c, r, if v.muted { 0.0 } else { v.volume }, colors, scale), _ => { if v.hover == Some(control) { - c.rrect(r, corner, colors.border); + c.rrect(r, corner, hover_fill(colors)); } let icon = match control { Control::Previous => Icon::Previous, @@ -171,6 +171,16 @@ pub fn paint(c: &mut Canvas, t: &mut Text, icons: &mut Icons, colors: &Colors, s 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); @@ -323,6 +333,18 @@ mod tests { 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 }; diff --git a/src/player/mod.rs b/src/player/mod.rs index 1318891..942e7c5 100644 --- a/src/player/mod.rs +++ b/src/player/mod.rs @@ -85,6 +85,9 @@ pub struct Media { 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. @@ -108,6 +111,7 @@ impl Media { error: None, asked: size, advanced: false, + resume: None, released_early: [false; VIDEO_SLOTS], placed: None, }; diff --git a/src/ui.rs b/src/ui.rs index f2896a5..b24aa32 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -320,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"); + } } } } From d4c5ab0ac87c950b51c5b6f40d91ac838e1526cf Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:55:51 -0700 Subject: [PATCH 12/23] Follow alias-playback #3 to e11d5f4; a helper's exit code survives a reset - alias-playback e11d5f4: #2's requests and reads that never wait, and #3's tags read with them (a song's cover played 12 of 12 times in the private weston, tags each time). - A helper whose socket ends in a reset rather than a clean close (it exited with commands unread) gets 100 ms to finish before it's ended, so its exit code still says why it stopped. --- Cargo.lock | 2 +- src/player/gpu.rs | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 430fb97..df9cc95 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#74c8c8715ed6a1ced9d691db3caf3cf86ec7ea26" +source = "git+https://github.com/aliasproject/alias-playback?branch=ali-2358-gpu-media#e11d5f479b3bd01258f356909d4d3a88e513d5e3" dependencies = [ "libc", "rustix", diff --git a/src/player/gpu.rs b/src/player/gpu.rs index 37017fb..822710a 100644 --- a/src/player/gpu.rs +++ b/src/player/gpu.rs @@ -154,7 +154,15 @@ impl Session { // A clean end of the socket is the helper exiting: bubblewrap follows once it has // reaped it, with its exit code, which says why. After a read error the helper may // still be running, so it's ended first and never waited on. + // A close can also show up as a reset (the helper left with commands unread): a + // moment's grace lets a helper that's exiting anyway finish, with its code. if !self.closed_cleanly { + for _ in 0..10 { + if matches!(self.child.try_wait(), Ok(Some(_))) { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } let _ = self.child.kill(); } let status = self.child.wait().ok()?; From b5c527bdd41138b96b33e09b751c3bd1a4b7283c Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:56:36 -0700 Subject: [PATCH 13/23] Review round 3: the grid's kept place can't outlive it; a paused resume stays paused - The place kept for the file the grid closed was dropped only when another video or song opened, so after closing the grid onto a picture, the file could open much later at the old place. It now lasts only until the grid closes: onto that file it's used, onto any other it's dropped. - A file paused before the grid is asked to pause as it opens, so it no longer plays briefly from the start before the seek. --- src/app.rs | 9 +++++++++ src/app/player_ui.rs | 1 + 2 files changed, 10 insertions(+) diff --git a/src/app.rs b/src/app.rs index 5e51849..ec0c471 100644 --- a/src/app.rs +++ b/src/app.rs @@ -263,6 +263,11 @@ 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)) => { @@ -279,6 +284,10 @@ impl App { let resume = self.resume.take().filter(|(p, ..)| *p == path).map(|(_, at, play)| (at, play)); self.media = Some(if wl.can_show_video() { 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 { diff --git a/src/app/player_ui.rs b/src/app/player_ui.rs index a0523f6..0f55271 100644 --- a/src/app/player_ui.rs +++ b/src/app/player_ui.rs @@ -121,6 +121,7 @@ impl App { { 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); } } From 5e3750746219fb317aad3ea4a2ae54f2261d2a49 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:58:11 -0700 Subject: [PATCH 14/23] MPRIS review round 2: tags as they arrive, Seeked after Position, pause while opening - What MPRIS says is rebuilt when any tag changes, not only the first: tags arrive one by one, and the artist or album could go unsignalled. - On a seek, Position is stored before Seeked is sent, so a controller reading it then gets the new place. - A pause while a file opens is kept (it stays paused once loaded, and reads Paused), and Play or Play/Pause undoes it. - Seek past the end with no next track goes to the end. - A Volume set with nothing playing isn't stored. - Replay from the end sends Seeked to 0. - The file's URL is made from its bytes, so a name that isn't UTF-8 still names it. - The next and previous video or song are kept while the list and the place are the same, not looked for on every wake. --- src/app.rs | 6 ++++++ src/app/player_ui.rs | 30 ++++++++++++++++++++++++++---- src/main.rs | 2 ++ src/mpris.rs | 25 ++++++++++++++++--------- src/player/mod.rs | 20 +++++++++++++++++--- 5 files changed, 67 insertions(+), 16 deletions(-) diff --git a/src/app.rs b/src/app.rs index 7405900..c1255fb 100644 --- a/src/app.rs +++ b/src/app.rs @@ -51,6 +51,9 @@ pub struct Grid { pub scroll: i32, } +/// The next and previous video or song, and the (place, list length, list) they're for. +type NeighboursCache = ((usize, usize, usize), (Option, Option)); + pub struct App { pub files: Vec, pub cur: usize, @@ -118,6 +121,8 @@ pub struct App { fullscreen: bool, /// Counts the videos and songs opened, so MPRIS sees each as a new track. track: u64, + /// The next and previous video or song for MPRIS, by (place, list length, list). + neighbours_cache: std::cell::Cell>, } impl App { @@ -174,6 +179,7 @@ impl App { resume: None, fullscreen: false, track: 0, + neighbours_cache: std::cell::Cell::new(None), } } diff --git a/src/app/player_ui.rs b/src/app/player_ui.rs index 49fe95b..e126b15 100644 --- a/src/app/player_ui.rs +++ b/src/app/player_ui.rs @@ -597,9 +597,10 @@ impl App { impl App { /// What MPRIS would be told, cheaply: when this is unchanged, so is what it says. - pub fn mpris_key(&self) -> Option<(u64, u8, i64, i64, bool, bool, bool)> { + pub fn mpris_key(&self) -> Option<(u64, u8, i64, i64, bool, bool, u64)> { let m = self.media.as_ref()?; let phase = match m.phase() { + Phase::Opening if m.opening_paused() => 5, Phase::Opening => 0, Phase::Playing => 1, Phase::Paused => 2, @@ -607,12 +608,32 @@ impl App { Phase::Failed(_) => 4, }; let (next, previous) = self.media_neighbours(); - let tags = m.meta.title.is_some() || m.meta.artist.is_some() || m.meta.album.is_some(); + // The tags themselves, as they arrive one by one: each one is news. + let tags = { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + m.meta.hash(&mut h); + h.finish() + }; Some((self.track, phase, (m.state.duration * 10.0) as i64, if m.state.muted { -1 } else { m.state.volume as i64 }, next.is_some(), previous.is_some(), tags)) } - /// The next and previous video or song in the list, going round, if any other. + /// The next and previous video or song in the list, going round, if any other. Kept + /// while the list and the place in it are the same, so a long folder isn't walked on + /// every wake. fn media_neighbours(&self) -> (Option, Option) { + let key = (self.cur, self.files.len(), self.files.as_ptr() as usize); + if let Some((k, v)) = self.neighbours_cache.get() + && k == key + { + return v; + } + let v = self.find_media_neighbours(); + self.neighbours_cache.set(Some((key, v))); + v + } + + fn find_media_neighbours(&self) -> (Option, Option) { let n = self.files.len(); let is_media = |i: usize| crate::player::kind_of(&self.files[i]).is_some(); let next = (1..n).map(|d| (self.cur + d) % n).find(|i| is_media(*i)); @@ -637,6 +658,7 @@ impl App { let (next, previous) = self.media_neighbours(); let status = match m.phase() { // Opening plays once loaded, unless paused meanwhile. + Phase::Opening if m.opening_paused() => "Paused", Phase::Playing | Phase::Opening => "Playing", Phase::Failed(_) => "Stopped", Phase::Paused | Phase::Ended => "Paused", @@ -644,7 +666,7 @@ impl App { crate::mpris::Now { status, track: self.track, - path: Some(m.path.to_string_lossy().into_owned()), + path: Some(m.path.clone()), title: Some(m.title()), artist: m.meta.artist.clone(), album: m.meta.album.clone(), diff --git a/src/main.rs b/src/main.rs index 89d7a9f..073b466 100644 --- a/src/main.rs +++ b/src/main.rs @@ -313,6 +313,8 @@ fn run(o: Opening) -> i32 { app.mpris_request(r); } if let Some(at) = app.take_seeked() { + // Stored first, so a controller that reads Position on Seeked gets the new one. + m.set_position(at); m.seeked(at); } // Built only when something it says changed, not on every wake. diff --git a/src/mpris.rs b/src/mpris.rs index 492e30e..61efc58 100644 --- a/src/mpris.rs +++ b/src/mpris.rs @@ -40,7 +40,7 @@ pub struct Now { pub status: &'static str, /// Changes with each file, so controllers see a new track. pub track: u64, - pub path: Option, + pub path: Option, pub title: Option, pub artist: Option, pub album: Option, @@ -77,7 +77,8 @@ impl Now { m.insert("xesam:album".into(), owned(Value::from(a.as_str()))); } if let Some(p) = &self.path { - let url = format!("file://{}", percent_encode(p)); + use std::os::unix::ffi::OsStrExt; + let url = format!("file://{}", percent_encode(p.as_os_str().as_bytes())); m.insert("xesam:url".into(), owned(Value::from(url))); } m @@ -88,10 +89,11 @@ fn owned(v: Value<'_>) -> OwnedValue { v.try_to_owned().unwrap_or_else(|_| OwnedValue::from(0u8)) } -/// A path as a `file://` URL's path: everything but unreserved characters and `/` escaped. -fn percent_encode(p: &str) -> String { +/// A path's bytes as a `file://` URL's path: everything but unreserved characters and `/` +/// escaped, so a name that isn't UTF-8 still names the file. +fn percent_encode(p: &[u8]) -> String { let mut out = String::new(); - for b in p.bytes() { + for &b in p { if b.is_ascii_alphanumeric() || b"-._~/".contains(&b) { out.push(b as char); } else { @@ -202,7 +204,8 @@ impl Player { } let to = now.position + offset as f64 / US; if now.length > 0.0 && to > now.length { - self.0.ask(Request::Next); + // The next track, or the end when there's none. + self.0.ask(if now.can_go_next { Request::Next } else { Request::SeekTo(now.length) }); } else { self.0.ask(Request::SeekTo(to.max(0.0))); } @@ -261,8 +264,11 @@ impl Player { fn set_volume(&self, v: f64) { if v.is_finite() { let v = (v * 100.0).clamp(0.0, 100.0); - // Known at once, so the change signal sent after this setter has the new value. - if let Ok(mut n) = self.0.now.lock() { + // Known at once, so the change signal sent after this setter has the new value; + // with nothing playing there's nothing to set. + if let Ok(mut n) = self.0.now.lock() + && n.status != "Stopped" + { n.volume = v; } self.0.ask(Request::Volume(v)); @@ -399,7 +405,7 @@ mod tests { Now { status: "Playing", track: 1, - path: Some("/m/Night Drive.flac".into()), + path: Some(std::path::PathBuf::from("/m/Night Drive.flac")), title: Some("Night Drive".into()), artist: Some("The Test Signals".into()), album: Some("Calibration".into()), @@ -417,6 +423,7 @@ mod tests { assert_eq!(m.get("mpris:length").and_then(|v| i64::try_from(v.clone()).ok()), Some(221_000_000)); assert_eq!(m.get("xesam:title").and_then(|v| String::try_from(v.clone()).ok()).as_deref(), Some("Night Drive")); assert_eq!(m.get("xesam:url").and_then(|v| String::try_from(v.clone()).ok()).as_deref(), Some("file:///m/Night%20Drive.flac")); + assert_eq!(percent_encode(b"/m/caf\xe9.mp3"), "/m/caf%E9.mp3", "a name that isn't UTF-8 keeps its byte"); assert!(m.contains_key("mpris:trackid") && m.contains_key("xesam:artist") && m.contains_key("xesam:album")); } diff --git a/src/player/mod.rs b/src/player/mod.rs index 46d86bf..de7189d 100644 --- a/src/player/mod.rs +++ b/src/player/mod.rs @@ -59,7 +59,7 @@ pub enum Phase { } /// The song's tags, as the helper said them (already cleaned). -#[derive(Clone, Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq, Hash)] pub struct Meta { pub title: Option, pub artist: Option, @@ -87,6 +87,8 @@ pub struct Media { pub advanced: bool, /// Where a seek just went, for MPRIS's Seeked signal. seeked: Option, + /// Asked to pause while still opening. + opening_paused: 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)>, @@ -114,6 +116,7 @@ impl Media { asked: size, advanced: false, seeked: None, + opening_paused: false, resume: None, released_early: [false; VIDEO_SLOTS], placed: None, @@ -165,9 +168,11 @@ impl Media { Phase::Ended => { self.send(Command::SeekTo(0.0)); self.send(Command::Play); + self.seeked = Some(0.0); } Phase::Paused => self.send(Command::Play), - Phase::Playing | Phase::Opening => self.send(Command::Pause), + Phase::Opening if self.opening_paused => self.play(), + Phase::Playing | Phase::Opening => self.pause(), Phase::Failed(_) => {} } } @@ -177,14 +182,23 @@ impl Media { pub fn play(&mut self) { match self.phase() { Phase::Ended => self.toggle(), - Phase::Paused | Phase::Opening => self.send(Command::Play), + Phase::Paused | Phase::Opening => { + self.opening_paused = false; + self.send(Command::Play); + } Phase::Playing | Phase::Failed(_) => {} } } + /// Paused while still opening: it'll stay paused once loaded. + pub fn opening_paused(&self) -> bool { + self.opening_paused && !self.heard + } + /// Pauses, opening too, so it stays paused once loaded. pub fn pause(&mut self) { if matches!(self.phase(), Phase::Playing | Phase::Opening) { + self.opening_paused = !self.heard; self.send(Command::Pause); } } From 55eb9d352e048b587b0a5f2468e519016abf3e3a Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 12:04:31 -0700 Subject: [PATCH 15/23] MPRIS review round 3: Next opens at once, replay's Seeked, paused resume - A controller's requests are handled before the player syncs, so Next and Previous open the next file on the same turn, not on the next input. - Replay from the end shows the start at once, so the Position read on its Seeked is 0. - A file reopened paused after the grid is paused the way a controller's pause is, so it reads Paused while it opens and Play/Pause plays it. - A seek made before the bus joined isn't sent late; a SeekTo while a file opens isn't announced, as it can't happen. --- src/app.rs | 2 +- src/app/player_ui.rs | 5 +++-- src/main.rs | 15 ++++++++++----- src/player/mod.rs | 3 ++- 4 files changed, 16 insertions(+), 9 deletions(-) diff --git a/src/app.rs b/src/app.rs index c1255fb..13b7af5 100644 --- a/src/app.rs +++ b/src/app.rs @@ -295,7 +295,7 @@ impl App { 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.pause(); } m.resume = resume; m diff --git a/src/app/player_ui.rs b/src/app/player_ui.rs index e126b15..e7aee4c 100644 --- a/src/app/player_ui.rs +++ b/src/app/player_ui.rs @@ -708,10 +708,11 @@ impl App { } } Request::SeekTo(s) => { - if let Some(m) = &mut self.media { + // Nothing to seek while it opens, so nothing to say either. + if let Some(m) = self.media.as_mut().filter(|m| m.heard) { m.seek_to(s); + self.seek_said_at = Some(Instant::now() + motion::SEEK_ANNOUNCE); } - self.seek_said_at = Some(Instant::now() + motion::SEEK_ANNOUNCE); } Request::Volume(v) => { let Some(m) = &mut self.media else { return }; diff --git a/src/main.rs b/src/main.rs index 073b466..095b641 100644 --- a/src/main.rs +++ b/src/main.rs @@ -292,11 +292,9 @@ fn run(o: Opening) -> i32 { app.set_files(files); folder = None; } - if wl.state.configured { - app.sync_media(&mut wl); - } // MPRIS, from the first video or song on, when there's a session bus; joined on a - // thread, so a slow bus never holds up the window. + // thread, so a slow bus never holds up the window. Its requests go first, so a Next + // opens the next file on this turn. if !mpris_tried && app.media.is_some() { mpris_tried = true; mpris_joining = a11y::session_bus_exists().then(mpris::Mpris::spawn); @@ -312,7 +310,14 @@ fn run(o: Opening) -> i32 { for r in reqs { app.mpris_request(r); } - if let Some(at) = app.take_seeked() { + } + if wl.state.configured { + app.sync_media(&mut wl); + } + // Taken every turn, so a seek made before the bus joined isn't sent late. + let seeked = app.take_seeked(); + if let Some(m) = &mpris { + if let Some(at) = seeked { // Stored first, so a controller that reads Position on Seeked gets the new one. m.set_position(at); m.seeked(at); diff --git a/src/player/mod.rs b/src/player/mod.rs index de7189d..b71cb62 100644 --- a/src/player/mod.rs +++ b/src/player/mod.rs @@ -168,7 +168,8 @@ impl Media { Phase::Ended => { self.send(Command::SeekTo(0.0)); self.send(Command::Play); - self.seeked = Some(0.0); + // At the start now, as a seek shows it at once. + (self.state.ended, self.state.position, self.seeked) = (false, 0.0, Some(0.0)); } Phase::Paused => self.send(Command::Play), Phase::Opening if self.opening_paused => self.play(), From 42d4ab2469f688053e93923d50ff9bb8c5fb37d6 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 12:04:34 -0700 Subject: [PATCH 16/23] Follow alias-playback #3 to a314208 (#2's late-Loaded fixes; no picture confirmed by the loading file) --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index df9cc95..594e772 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#e11d5f479b3bd01258f356909d4d3a88e513d5e3" +source = "git+https://github.com/aliasproject/alias-playback?branch=ali-2358-gpu-media#a3142084e4c63be43f140c0f32a9d4294faf43c2" dependencies = [ "libc", "rustix", From b6cbe18d528f81b4bad6ce067e2dc5d284070a48 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 12:08:35 -0700 Subject: [PATCH 17/23] A buffer's modifier must be one the compositor listed for its format With no list (the table couldn't be read), any modifier was taken; now nothing is, so a buffer from the helper is never one the compositor hasn't said it takes. --- src/wl.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/wl.rs b/src/wl.rs index a9c9d2a..a0eac1b 100644 --- a/src/wl.rs +++ b/src/wl.rs @@ -436,7 +436,9 @@ impl Wl { if slot >= VIDEO_SLOTS { return Err("the player sent a buffer it shouldn't have".into()); } - if !formats.is_empty() && !formats.contains(&(b.fourcc, b.modifier)) { + // Only a format and modifier the compositor listed for each other; with no list + // (it couldn't be read), nothing is taken on trust. + if !formats.contains(&(b.fourcc, b.modifier)) { return Err("the desktop can't show frames in the form the player made them".into()); } let len = rustix::fs::seek(&fd, rustix::fs::SeekFrom::End(0)).unwrap_or(0); From 69efc81624240555bcadf1076aa110390422355c Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 12:13:03 -0700 Subject: [PATCH 18/23] MPRIS: the player syncs before and after a controller's requests So requests act on the file that's open (not one a key just left), a Next opens the next file on this turn, and MPRIS starts on the turn the first video or song opens. --- src/main.rs | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/main.rs b/src/main.rs index 095b641..88267f5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -292,9 +292,14 @@ fn run(o: Opening) -> i32 { app.set_files(files); folder = None; } + // The player follows the current file: once after input, and again after any media + // controller's requests, so both act on the file that's open and a Next opens the + // next file on this turn. + if wl.state.configured { + app.sync_media(&mut wl); + } // MPRIS, from the first video or song on, when there's a session bus; joined on a - // thread, so a slow bus never holds up the window. Its requests go first, so a Next - // opens the next file on this turn. + // thread, so a slow bus never holds up the window. if !mpris_tried && app.media.is_some() { mpris_tried = true; mpris_joining = a11y::session_bus_exists().then(mpris::Mpris::spawn); @@ -307,13 +312,15 @@ fn run(o: Opening) -> i32 { } if let Some(m) = &mpris { let reqs: Vec<_> = m.requests.try_iter().collect(); - for r in reqs { - app.mpris_request(r); + if !reqs.is_empty() { + for r in reqs { + app.mpris_request(r); + } + if wl.state.configured { + app.sync_media(&mut wl); + } } } - if wl.state.configured { - app.sync_media(&mut wl); - } // Taken every turn, so a seek made before the bus joined isn't sent late. let seeked = app.take_seeked(); if let Some(m) = &mpris { From c4eeb7d6cbe71285a85dcf05024312c155ecf5b6 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 12:13:05 -0700 Subject: [PATCH 19/23] Follow alias-playback #3 to its merge of 6c0187c (GPU setup freed on failure) --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 594e772..2f25624 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#a3142084e4c63be43f140c0f32a9d4294faf43c2" +source = "git+https://github.com/aliasproject/alias-playback?branch=ali-2358-gpu-media#4a05f2ce2e59e38f901f7fdcb198557f3b48f16b" dependencies = [ "libc", "rustix", From 6d2f67e77320b4b714dbaa438893c774176d6275 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 15:45:43 -0700 Subject: [PATCH 20/23] Player tokens approved: their usage notes drop "Proposed" Mike approved the player's tokens on 2026-12-02 (the ones from #6, and time-pad, controls-group-gap, cover-icon, seek-announce and double-click added after it). Their usage notes, the player's contrast pairs, and the player clauses on border, muted and accent now read as plain fact. src/tokens.rs regenerated with design/build. --- design/tokens.json | 46 ++++++++++----------- src/tokens.rs | 100 ++++++++++++++++++++++----------------------- 2 files changed, 73 insertions(+), 73 deletions(-) diff --git a/design/tokens.json b/design/tokens.json index 2c4a131..cc7beea 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,22 +234,22 @@ { "name": "controls-gap", "value": "4px", - "usage": "Proposed (ALI-2358): 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 (ALI-2358): 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": "Proposed (ALI-2358): either side of the time (1:23 / 4:56) in the player's control bar (src/player/bar.rs)." + "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": "Proposed (ALI-2358): 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)." + "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)." } ] }, @@ -307,42 +307,42 @@ { "name": "controls-height", "value": "64px", - "usage": "Proposed (ALI-2358): 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 (ALI-2358): 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 (ALI-2358): 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 (ALI-2358): 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 (ALI-2358): 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 (ALI-2358): 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 (ALI-2358): 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": "Proposed (ALI-2358): the note icon in the panel square a song with no cover art shows, in muted (src/player/bar.rs)." + "usage": "The note icon in the panel square a song with no cover art shows, in muted (src/player/bar.rs)." } ] }, @@ -366,22 +366,22 @@ { "name": "controls-hide", "value": "2s", - "usage": "Proposed (ALI-2358): 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." }, { "name": "seek-step", "value": "5s", - "usage": "Proposed (ALI-2358): 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": "Proposed (ALI-2358): 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)." + "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": "Proposed (ALI-2358): two clicks on a video this close together are a double-click, which toggles full screen (src/app.rs)." + "usage": "Two clicks on a video this close together are a double-click, which toggles full screen (src/app.rs)." } ] }, @@ -400,7 +400,7 @@ { "name": "volume-step", "value": 5, - "usage": "Proposed (ALI-2358): 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." } ] }, @@ -565,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/tokens.rs b/src/tokens.rs index 1e049bb..33d241c 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,16 +300,16 @@ 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 (ALI-2358): 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 (ALI-2358): 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; - /// Proposed (ALI-2358): either side of the time (1:23 / 4:56) in the player's control bar (src/player/bar.rs). + /// 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; - /// Proposed (ALI-2358): 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). + /// 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; } @@ -345,28 +345,28 @@ 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 (ALI-2358): 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 (ALI-2358): 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 (ALI-2358): 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 (ALI-2358): 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 (ALI-2358): 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 (ALI-2358): 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 (ALI-2358): 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; - /// Proposed (ALI-2358): the note icon in the panel square a song with no cover art shows, in muted (src/player/bar.rs). + /// 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; } @@ -383,16 +383,16 @@ 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 (ALI-2358): 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. pub const CONTROLS_HIDE: Duration = Duration::from_millis(2000); - /// Proposed (ALI-2358): 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); - /// Proposed (ALI-2358): 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). + /// 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); - /// Proposed (ALI-2358): two clicks on a video this close together are a double-click, which toggles full screen (src/app.rs). + /// 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); } @@ -404,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 (ALI-2358): 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; } From bf75c8eb544bff318f980a268999600dc4b973b0 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 15:43:16 -0700 Subject: [PATCH 21/23] Hide the pointer with the control bar while a video plays Mike's decision of 2026-12-02: once the bar hides by itself over a playing video, the pointer hides with it, and whatever brings the bar back (any pointer motion, a key, a pause) brings the pointer back with the shape it would have. Music, a paused or ended video, and keyboard focus in the bar never hide it, as they never hide the bar. The pointer is hidden with wl_pointer.set_cursor and no surface, at the serial of the last enter, and kept hidden when it enters the window again. Only where cursor-shape-v1 is offered: without it the shape can't be set again, so the pointer is never hidden there. --- README.md | 3 +- design/tokens.json | 2 +- src/app/player_ui.rs | 70 ++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 1 + src/tokens.rs | 2 +- src/wl.rs | 38 +++++++++++++++++++++--- 6 files changed, 109 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index ed75451..f4833fb 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,8 @@ 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. A video stops on its last frame with a +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. 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. diff --git a/design/tokens.json b/design/tokens.json index cc7beea..812a2eb 100644 --- a/design/tokens.json +++ b/design/tokens.json @@ -366,7 +366,7 @@ { "name": "controls-hide", "value": "2s", - "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." + "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", diff --git a/src/app/player_ui.rs b/src/app/player_ui.rs index 0f55271..cc527d4 100644 --- a/src/app/player_ui.rs +++ b/src/app/player_ui.rs @@ -37,7 +37,18 @@ pub fn may_hide(kind: Kind, phase: &Phase, focus: Option, drag: Option< 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 }; @@ -610,4 +621,63 @@ mod tests { 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/main.rs b/src/main.rs index eba9c92..d756d3d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -304,6 +304,7 @@ fn run(o: Opening) -> i32 { } } app.expire(now); + wl.hide_cursor(app.pointer_hidden()); if wl.can_paint() { app.animate(now); } diff --git a/src/tokens.rs b/src/tokens.rs index 33d241c..1a00e6a 100644 --- a/src/tokens.rs +++ b/src/tokens.rs @@ -383,7 +383,7 @@ 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); - /// 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); /// How far Left and Right (or a click on the seek bar's keyboard focus) move in a video. diff --git a/src/wl.rs b/src/wl.rs index e02b23f..115cfec 100644 --- a/src/wl.rs +++ b/src/wl.rs @@ -255,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 { @@ -331,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}"))?; @@ -734,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(); } } @@ -776,6 +797,13 @@ 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) @@ -1215,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 }); } From 2fec5ede7ae820fee2046fe9253d6116a7baeba9 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 15:55:47 -0700 Subject: [PATCH 22/23] README: what brings the pointer back, and where it hides The pointer comes back with the bar on a key, a click or a pause as well as on pointer motion, and hides only where cursor-shape-v1 is offered. Review round 5 on #8. --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index f4833fb..2f19427 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,9 @@ 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. A video stops on its last frame with a +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. From caa95f44ac53604a725e07abb306b55fb319d28c Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 17:22:34 -0700 Subject: [PATCH 23/23] Use alias-playback from main, now that #2 and #3 are merged The jailed GPU helper's branch (ali-2358-gpu-media) merged as fef4a47, with the same code as the 4a05f2c this was pinned to. --- Cargo.lock | 2 +- Cargo.toml | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) 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