Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
54ac94c168 | ||
|
|
5dbdc04cd4 | ||
|
|
391a554736 | ||
|
|
fa5f25e69b | ||
|
|
6dc8f0d9f2 | ||
|
|
d9594a5de5 | ||
|
|
c1defa565b | ||
|
|
e2ac2de9f4 | ||
|
|
899ab223b9 | ||
|
|
4ea9250e16 | ||
|
|
9c8ba2a4dc | ||
|
|
555d0ca749 | ||
|
|
9cbda56abc | ||
|
|
ac5c8c4c8c | ||
|
|
e5c43fbb77 | ||
|
|
766ed22726 | ||
|
|
44f4a1f06e | ||
|
|
5b465e2859 |
No files matched your search
@@ -1,7 +1,10 @@
|
|||||||
/target
|
/target
|
||||||
.DS_Store
|
.DS_Store
|
||||||
/design/shots
|
/design/shots
|
||||||
|
.env
|
||||||
/packaging/arch/src
|
/packaging/arch/src
|
||||||
/packaging/arch/pkg
|
/packaging/arch/pkg
|
||||||
/packaging/arch/musyx
|
/packaging/arch/musyx
|
||||||
/packaging/arch/*.pkg.tar.*
|
/packaging/arch/*.pkg.tar.*
|
||||||
|
/.impeccable
|
||||||
|
/.env
|
||||||
Generated
+18
-2
@@ -2992,12 +2992,13 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "musyx"
|
name = "musyx"
|
||||||
version = "0.2.1"
|
version = "0.4.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"block2 0.6.2",
|
"block2 0.6.2",
|
||||||
"directories",
|
"directories",
|
||||||
"iced",
|
"iced",
|
||||||
"iced_test",
|
"iced_test",
|
||||||
|
"image",
|
||||||
"keyring",
|
"keyring",
|
||||||
"objc2 0.6.5",
|
"objc2 0.6.5",
|
||||||
"objc2-app-kit 0.3.2",
|
"objc2-app-kit 0.3.2",
|
||||||
@@ -3009,6 +3010,7 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"souvlaki",
|
"souvlaki",
|
||||||
|
"subsonic-api",
|
||||||
"sys-locale",
|
"sys-locale",
|
||||||
"tokio",
|
"tokio",
|
||||||
"winresource",
|
"winresource",
|
||||||
@@ -5008,6 +5010,19 @@ dependencies = [
|
|||||||
"float-cmp",
|
"float-cmp",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "subsonic-api"
|
||||||
|
version = "0.4.0"
|
||||||
|
dependencies = [
|
||||||
|
"md-5",
|
||||||
|
"rand 0.9.5",
|
||||||
|
"reqwest",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"thiserror 2.0.21",
|
||||||
|
"tokio",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "subtle"
|
name = "subtle"
|
||||||
version = "2.6.1"
|
version = "2.6.1"
|
||||||
@@ -6670,8 +6685,9 @@ checksum = "e01738255b5a16e78bbb83e7fbba0a1e7dd506905cfc53f4622d89015a03fbb5"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ym-api"
|
name = "ym-api"
|
||||||
version = "0.2.1"
|
version = "0.4.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"reqwest",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"thiserror 2.0.21",
|
"thiserror 2.0.21",
|
||||||
|
|||||||
+2
-2
@@ -1,9 +1,9 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
resolver = "3"
|
resolver = "3"
|
||||||
members = ["crates/ym-api", "crates/musyx"]
|
members = ["crates/ym-api", "crates/subsonic-api", "crates/musyx"]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.2.1"
|
version = "0.4.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
publish = false
|
publish = false
|
||||||
|
|||||||
@@ -1,63 +1,497 @@
|
|||||||
# Musyx design system
|
---
|
||||||
|
name: Musyx
|
||||||
|
description: A dark-first desktop player for Yandex Music, built with iced.
|
||||||
|
colors:
|
||||||
|
bg: "#1C1A22"
|
||||||
|
panel: "#23202B"
|
||||||
|
raised: "#2D2937"
|
||||||
|
line: "#3A3546"
|
||||||
|
fg: "#EEEAF3"
|
||||||
|
muted: "#A39CB0"
|
||||||
|
accent: "#F0B23E"
|
||||||
|
accent-ink: "#2A1D04"
|
||||||
|
like: "#F27286"
|
||||||
|
ok: "#7FCB9B"
|
||||||
|
bg-light: "#F3F1F6"
|
||||||
|
panel-light: "#FFFFFF"
|
||||||
|
raised-light: "#EAE6F0"
|
||||||
|
line-light: "#DCD6E4"
|
||||||
|
fg-light: "#1F1B27"
|
||||||
|
muted-light: "#686178"
|
||||||
|
accent-light: "#A86C05"
|
||||||
|
accent-ink-light: "#FFF7E6"
|
||||||
|
like-light: "#D2405A"
|
||||||
|
ok-light: "#2E8A55"
|
||||||
|
typography:
|
||||||
|
display:
|
||||||
|
fontFamily: "Unbounded"
|
||||||
|
fontSize: "46px"
|
||||||
|
fontWeight: 600
|
||||||
|
display-l:
|
||||||
|
fontFamily: "Unbounded"
|
||||||
|
fontSize: "40px"
|
||||||
|
fontWeight: 600
|
||||||
|
display-m:
|
||||||
|
fontFamily: "Unbounded"
|
||||||
|
fontSize: "34px"
|
||||||
|
fontWeight: 600
|
||||||
|
display-s:
|
||||||
|
fontFamily: "Unbounded"
|
||||||
|
fontSize: "30px"
|
||||||
|
fontWeight: 600
|
||||||
|
wordmark:
|
||||||
|
fontFamily: "Unbounded"
|
||||||
|
fontSize: "20px"
|
||||||
|
fontWeight: 600
|
||||||
|
section:
|
||||||
|
fontFamily: "Onest"
|
||||||
|
fontSize: "19px"
|
||||||
|
fontWeight: 600
|
||||||
|
body:
|
||||||
|
fontFamily: "Onest"
|
||||||
|
fontSize: "14px"
|
||||||
|
fontWeight: 400
|
||||||
|
lineHeight: 1.45
|
||||||
|
body-medium:
|
||||||
|
fontFamily: "Onest"
|
||||||
|
fontSize: "14px"
|
||||||
|
fontWeight: 500
|
||||||
|
meta:
|
||||||
|
fontFamily: "Onest"
|
||||||
|
fontSize: "13px"
|
||||||
|
fontWeight: 400
|
||||||
|
small:
|
||||||
|
fontFamily: "Onest"
|
||||||
|
fontSize: "12.5px"
|
||||||
|
fontWeight: 400
|
||||||
|
rounded:
|
||||||
|
small-cover: "6px"
|
||||||
|
control: "8px"
|
||||||
|
cover: "10px"
|
||||||
|
card: "14px"
|
||||||
|
hero: "16px"
|
||||||
|
pill: "999px"
|
||||||
|
spacing:
|
||||||
|
xs: "4px"
|
||||||
|
s: "8px"
|
||||||
|
m: "12px"
|
||||||
|
l: "18px"
|
||||||
|
xl: "22px"
|
||||||
|
gutter: "28px"
|
||||||
|
section: "34px"
|
||||||
|
components:
|
||||||
|
button-primary:
|
||||||
|
backgroundColor: "{colors.accent}"
|
||||||
|
textColor: "{colors.accent-ink}"
|
||||||
|
typography: "{typography.body-medium}"
|
||||||
|
rounded: "{rounded.pill}"
|
||||||
|
padding: "10px 18px"
|
||||||
|
button-ghost:
|
||||||
|
backgroundColor: "transparent"
|
||||||
|
textColor: "{colors.fg}"
|
||||||
|
rounded: "{rounded.pill}"
|
||||||
|
padding: "10px 18px"
|
||||||
|
button-ghost-hover:
|
||||||
|
backgroundColor: "{colors.raised}"
|
||||||
|
chip:
|
||||||
|
textColor: "{colors.fg}"
|
||||||
|
rounded: "{rounded.pill}"
|
||||||
|
padding: "7px 13px"
|
||||||
|
chip-selected:
|
||||||
|
backgroundColor: "{colors.accent}"
|
||||||
|
textColor: "{colors.accent-ink}"
|
||||||
|
icon-button:
|
||||||
|
textColor: "{colors.muted}"
|
||||||
|
rounded: "{rounded.control}"
|
||||||
|
size: "34px"
|
||||||
|
icon-button-hover:
|
||||||
|
backgroundColor: "{colors.raised}"
|
||||||
|
textColor: "{colors.fg}"
|
||||||
|
nav-item-active:
|
||||||
|
backgroundColor: "{colors.raised}"
|
||||||
|
textColor: "{colors.fg}"
|
||||||
|
rounded: "{rounded.control}"
|
||||||
|
search-field:
|
||||||
|
backgroundColor: "{colors.panel}"
|
||||||
|
textColor: "{colors.fg}"
|
||||||
|
rounded: "{rounded.pill}"
|
||||||
|
padding: "10px 16px"
|
||||||
|
width: "420px"
|
||||||
|
track-row:
|
||||||
|
textColor: "{colors.fg}"
|
||||||
|
rounded: "{rounded.control}"
|
||||||
|
height: "52px"
|
||||||
|
track-row-lit:
|
||||||
|
backgroundColor: "{colors.raised}"
|
||||||
|
context-menu:
|
||||||
|
backgroundColor: "{colors.panel}"
|
||||||
|
rounded: "{rounded.cover}"
|
||||||
|
padding: "6px"
|
||||||
|
width: "280px"
|
||||||
|
context-menu-item:
|
||||||
|
textColor: "{colors.fg}"
|
||||||
|
typography: "{typography.body}"
|
||||||
|
rounded: "{rounded.control}"
|
||||||
|
height: "32px"
|
||||||
|
card:
|
||||||
|
textColor: "{colors.fg}"
|
||||||
|
rounded: "{rounded.cover}"
|
||||||
|
width: "168px"
|
||||||
|
dialog:
|
||||||
|
backgroundColor: "{colors.panel}"
|
||||||
|
rounded: "{rounded.card}"
|
||||||
|
padding: "18px"
|
||||||
|
width: "380px"
|
||||||
|
toast:
|
||||||
|
backgroundColor: "{colors.fg}"
|
||||||
|
textColor: "{colors.bg}"
|
||||||
|
rounded: "{rounded.pill}"
|
||||||
|
padding: "10px 18px"
|
||||||
|
key-cap:
|
||||||
|
backgroundColor: "{colors.raised}"
|
||||||
|
textColor: "{colors.fg}"
|
||||||
|
typography: "{typography.meta}"
|
||||||
|
rounded: "{rounded.small-cover}"
|
||||||
|
padding: "2px 8px"
|
||||||
|
---
|
||||||
|
|
||||||
The approved mockup is [`design/mockup.html`](design/mockup.html) (published at
|
# Design System: Musyx
|
||||||
https://claude.ai/artifact/2gmswtceJM61fcE2F5uYYM). This file records its tokens. They map
|
|
||||||
1:1 to [`crates/musyx/src/ui/theme.rs`](crates/musyx/src/ui/theme.rs), so change both together.
|
|
||||||
|
|
||||||
## Direction
|
The source of truth is the build. The tokens above map 1:1 to
|
||||||
|
[`crates/musyx/src/ui/theme.rs`](crates/musyx/src/ui/theme.rs), so change both together. Keys
|
||||||
|
without a suffix are the dark theme. The `-light` keys are the same roles in the light theme.
|
||||||
|
[`design/mockup.html`](design/mockup.html) is the original exploration (see [History](#history)).
|
||||||
|
It is no longer the authority.
|
||||||
|
|
||||||
The ground is aubergine graphite, with one amber accent taken from a tape deck's VU needle.
|
## Overview
|
||||||
The app is dark-first, and the light theme follows the system setting. Everything stays quiet
|
|
||||||
except the My Wave hero, which is the one animated, accent-heavy surface.
|
|
||||||
|
|
||||||
## Colour
|
**Creative North Star: "The Late-Night Tape Deck"**
|
||||||
|
|
||||||
| Token | Dark | Light | Used for |
|
Musyx looks like a piece of dark hardware playing in a dim room late at night. The casing is
|
||||||
|--------------|-----------|-----------|----------|
|
aubergine graphite. The controls are quiet and almost the same colour as the casing. Exactly
|
||||||
| `bg` | `#1C1A22` | `#F3F1F6` | Window and content background |
|
one thing glows: an amber lamp that marks what is playing, what you chose and what you can
|
||||||
| `panel` | `#23202B` | `#FFFFFF` | Sidebar, player bar, drawer, cards that need separation |
|
press next. People leave the window open for hours, so nothing moves or competes for attention
|
||||||
| `raised` | `#2D2937` | `#EAE6F0` | Hover and selected rows, chip fills, progress track |
|
unless the music asks for it.
|
||||||
| `line` | `#3A3546` | `#DCD6E4` | 1px dividers and outlines |
|
|
||||||
| `fg` | `#EEEAF3` | `#1F1B27` | Primary text, the play/pause disc |
|
|
||||||
| `muted` | `#A39CB0` | `#686178` | Secondary text, idle icons |
|
|
||||||
| `accent` | `#F0B23E` | `#A86C05` | Current track, progress fill, primary buttons, active nav icon |
|
|
||||||
| `accent_ink` | `#2A1D04` | `#FFF7E6` | Text and icons on `accent` |
|
|
||||||
| `like` | `#F27286` | `#D2405A` | Filled heart, falling chart position |
|
|
||||||
| `ok` | `#7FCB9B` | `#2E8A55` | Subscription status, rising chart position |
|
|
||||||
|
|
||||||
Covers that have no artwork yet get a placeholder made of two hues (`h1`, `h2`) derived from
|
The layout is the familiar desktop player shell: sidebar, content, player bar, and an optional
|
||||||
the item id, painted as a diagonal gradient between them.
|
drawer. Its brand shows in the details, not the structure. There is one display face for titles
|
||||||
|
and one plain face for everything else. Depth comes from three close tonal steps, not from
|
||||||
|
shadows. Interactions follow desktop rules: right-click menus at the pointer, keyboard shortcuts,
|
||||||
|
and drag to reorder. The My Wave hero is the one place that animates. Its amber lines drift only
|
||||||
|
while My Wave is actually playing.
|
||||||
|
|
||||||
## Type
|
The theme is dark first. The light theme follows the system setting, or the choice in Settings,
|
||||||
|
and keeps every role.
|
||||||
|
|
||||||
| Role | Face | Size / weight | Where |
|
**Key Characteristics:**
|
||||||
|---------|----------------------|--------------------|-------|
|
- One amber accent on an aubergine ground. Amber means "this one, now".
|
||||||
| Display | Unbounded SemiBold | 46 / 40 / 34 / 30 | My Wave hero, detail page titles, sign-in headline, screen titles |
|
- Three tonal surfaces (bg, panel, raised) do the layering. Shadows appear only on things that float.
|
||||||
| Wordmark| Unbounded SemiBold | 20 | `musyx` + amber dot |
|
- Unbounded for titles, Onest for everything else. Icons are Lucide at 18pt.
|
||||||
| Section | Onest SemiBold | 19 | Section headings ("Made for you") |
|
- Dense, scannable lists with 52pt track rows.
|
||||||
| Body | Onest Regular/Medium | 14 (rows 14, meta 13, small 12.5) | Everything else |
|
- Desktop-native interaction: context menus, shortcuts, drag reorder, media keys, and a macOS
|
||||||
|
menu-bar mini player.
|
||||||
|
|
||||||
The fonts are bundled from `crates/musyx/assets/fonts` and licensed under OFL. Durations and
|
## Colors
|
||||||
counts use tabular figures.
|
|
||||||
|
|
||||||
## Space and shape
|
A near-monochrome violet-grey palette with a single warm amber and two quiet status colours.
|
||||||
|
|
||||||
- Spacing steps: 2 · 4 · 6 · 8 · 10 · 12 · 14 · 18 · 22 · 28 · 34. Content gutter is 28,
|
### Primary
|
||||||
and the gap between sections is 34.
|
- **Indicator Amber** (`accent`): the playing track's title, the progress fill, primary buttons,
|
||||||
- Radii: cover 10 · control 8 · small cover 6 · pill/round 999 · hero 16 · window cards 14.
|
selected chips, the active nav icon, the active tab underline, the focused search border, the
|
||||||
- Shell: sidebar 232 · player bar 80 · drawer 320 · track row 52 tall.
|
wordmark dot, the My Wave hero lines, and on Now Playing the play disc and the line being sung.
|
||||||
- Icons: Lucide 0.460 (ISC), 18px and tinted via `currentColor`. The `-fill` variants are for
|
The Lossless quality badge also turns amber when Yandex
|
||||||
liked, play and pause.
|
serves FLAC.
|
||||||
|
- **Amber Ink** (`accent-ink`): text and icons placed on amber.
|
||||||
|
|
||||||
|
### Secondary
|
||||||
|
- **Heart Rose** (`like`): a filled heart, a falling chart position, destructive menu entries
|
||||||
|
("Remove from this playlist", "Delete…") and the player's error notice line.
|
||||||
|
- **Signal Green** (`ok`): subscription status and a rising chart position.
|
||||||
|
|
||||||
|
### Neutral
|
||||||
|
- **Aubergine Graphite** (`bg`): the window, the content area and the sidebar.
|
||||||
|
- **Casing Panel** (`panel`): the player bar, the drawer, cards that need separation, the search
|
||||||
|
field, dialogs and the context menu.
|
||||||
|
- **Raised Plate** (`raised`): hover and selected rows, lit track rows, chip hover, the slider
|
||||||
|
rail and key caps.
|
||||||
|
- **Seam** (`line`): 1px dividers, outlines on ghost buttons and chips, the menu border and the
|
||||||
|
scrollbar thumb.
|
||||||
|
- **Label White** (`fg`): primary text, the play/pause disc, the volume fill and the toast fill.
|
||||||
|
- **Faded Label** (`muted`): secondary text, idle icons, column headers and placeholders.
|
||||||
|
|
||||||
|
Covers with no artwork yet get a placeholder: a diagonal gradient between two hues derived from
|
||||||
|
the item's id.
|
||||||
|
|
||||||
|
### Named Rules
|
||||||
|
**The One Lit Lamp Rule.** Amber marks state (playing, selected, primary, focused) and nothing
|
||||||
|
else. Never use it to decorate. If a screen has two amber things, they must be the same "now".
|
||||||
|
|
||||||
|
**The Light-Theme Contrast Rule.** In the light theme, amber text on `bg` measures 3.9:1 and
|
||||||
|
`ok` text measures 3.8:1. Both are below AA for body text. Until the light accent is darkened,
|
||||||
|
keep amber text in light mode to titles of 14pt medium or larger, and never use it for small
|
||||||
|
meta text.
|
||||||
|
|
||||||
|
## Typography
|
||||||
|
|
||||||
|
**Display Font:** Unbounded SemiBold (bundled, OFL)
|
||||||
|
**Body Font:** Onest Regular / Medium / SemiBold (bundled, OFL)
|
||||||
|
|
||||||
|
**Character:** Unbounded's wide geometric letters give titles the look of a label on hardware.
|
||||||
|
Onest is a neutral grotesque that holds dense lists and covers Cyrillic well.
|
||||||
|
|
||||||
|
### Hierarchy
|
||||||
|
- **Display** (600, 46 / 40 / 34 / 30): the My Wave hero, detail page titles, the sign-in
|
||||||
|
headline and screen titles ("Collection", "Settings").
|
||||||
|
- **Wordmark** (600, 20): `musyx` followed by the amber dot.
|
||||||
|
- **Section** (Onest 600, 19): section headings ("Made for you"), sheet titles, and settings card
|
||||||
|
titles.
|
||||||
|
- **Body** (400–500, 14; 1.45 for running text): row titles (medium), menu entries (regular),
|
||||||
|
buttons (medium/semibold) and paragraphs.
|
||||||
|
- **Meta** (400, 13): artist lines, album columns, durations and help text.
|
||||||
|
- **Small** (400, 12.5): column headers, sidebar section labels and the player's times.
|
||||||
|
|
||||||
|
### Named Rules
|
||||||
|
**The Two Faces Rule.** Unbounded appears only at display sizes and in the wordmark. Everything
|
||||||
|
interactive is Onest.
|
||||||
|
|
||||||
|
## Layout
|
||||||
|
|
||||||
|
The window is a fixed desktop shell. The minimum size is 960×620 and the default is 1280×800.
|
||||||
|
|
||||||
|
- **Shell:** a 232pt sidebar, a 1px seam, then the content column, which holds the top bar and
|
||||||
|
the scrolling page. An optional 320pt drawer sits at the right edge and narrows the content
|
||||||
|
while it is open. An 80pt player bar spans the full width at the bottom.
|
||||||
|
- **Content gutter:** 28pt. Sections are 34pt apart.
|
||||||
|
- **Spacing steps:** 4 · 8 · 12 · 18 · 22 · 28 · 34 are the named tokens. Tight in-component gaps
|
||||||
|
use 2, 6, 10 and 14. About 50 one-off values (16, 9, 24 and others) predate the scale and should
|
||||||
|
move onto it when touched.
|
||||||
|
- **Lists:** track rows are 52pt tall with 2pt between rows. Cards are 168pt wide and wrap, with
|
||||||
|
12pt between cards and 14pt between rows.
|
||||||
|
- **Overlays:** the toast floats 96pt above the bottom edge. Menus are pinned to the pointer or to
|
||||||
|
their button. Dialogs are centred in the window.
|
||||||
|
|
||||||
|
## Elevation & Depth
|
||||||
|
|
||||||
|
The resting UI is flat. Depth comes from tonal steps: `bg` → `panel` → `raised`, about one
|
||||||
|
lightness step apart, with `line` seams where two surfaces meet. Shadows are kept for elements
|
||||||
|
that float above the content.
|
||||||
|
|
||||||
|
### Shadow Vocabulary
|
||||||
|
- **Primary lift** (0 4px 12px, black 18%): primary pill buttons only, so the amber action sits
|
||||||
|
slightly proud of the page.
|
||||||
|
- **Menu float** (0 10px 28px, black 30%): the context menu and its submenu.
|
||||||
|
- **Toast float** (0 6px 18px, black 30%): the status pill above the player bar.
|
||||||
|
- **Dialog float** (0 18px 50px, black 35%), over a 45% black backdrop: dialogs only.
|
||||||
|
- **Stage float** (0 18px 50px, black 35%), no backdrop: the large cover on Now Playing, which
|
||||||
|
floats over its own blurred copy.
|
||||||
|
|
||||||
|
### Named Rules
|
||||||
|
**The Float-Only Shadow Rule.** If it isn't floating above the content (menu, toast, dialog, the
|
||||||
|
Now Playing cover) and it isn't a primary button, it has no shadow.
|
||||||
|
|
||||||
|
**The No-Dim Rule.** Only dialogs dim the window. Menus, the drawer and toasts never do.
|
||||||
|
|
||||||
|
## Shapes
|
||||||
|
|
||||||
|
Shapes are soft and functional. Controls are pills or gently rounded squares, and covers have
|
||||||
|
rounded corners.
|
||||||
|
|
||||||
|
- **Pills** (999): primary, ghost and chip buttons, the search field, the toast and the
|
||||||
|
play/pause disc.
|
||||||
|
- **Controls** (8): icon buttons, nav items, track rows and menu entries.
|
||||||
|
- **Covers** (10) and **small covers** (6): album and playlist art at card and row size. Artist
|
||||||
|
covers are round. The context menu also uses the cover radius.
|
||||||
|
- **Cards** (14): settings cards, the empty-state card and dialogs. **Hero** (16): the My Wave hero.
|
||||||
|
- **Key caps** (6): the shortcut list in Settings.
|
||||||
|
|
||||||
## Components
|
## Components
|
||||||
|
|
||||||
- **Sidebar**: wordmark, five nav items (Home, My Wave, Search, Collection, Podcasts), a
|
### Buttons
|
||||||
playlist list, and an account chip with sign-out. The active item sits on a `raised` fill
|
- **Primary:** an amber pill with amber-ink label, medium or semibold, padded 10×18, with the
|
||||||
and has an amber icon.
|
primary lift. On hover it mixes 12% toward `fg`. When pressed it mixes 12% toward `bg`. When
|
||||||
- **Player bar**: shows cover, title/artist, like and dislike on the left. The centre has
|
disabled it is `raised` with a `muted` label.
|
||||||
transport (shuffle, previous, play disc, next, repeat) over a progress bar with times. On
|
- **Ghost:** a transparent pill with a 1px `line` outline and an `fg` label. It fills `raised` on
|
||||||
the right are a quality badge, lyrics, queue and a volume bar.
|
hover. It pairs with Primary, as in Play + Shuffle.
|
||||||
- **Track row**: index (or an equaliser when playing), cover, title/artist, album, like,
|
- **Icon button:** a 34pt square holding an 18pt icon. Idle it is `muted`. On hover the icon turns
|
||||||
duration and a "more" button that appears on hover. The playing row is amber.
|
`fg` on a `raised` fill. A toggle that is on is tinted `accent`, and a liked heart is `like`.
|
||||||
- **Cards**: a cover with a hover play button, the title, and one muted subtitle line.
|
- **Play disc:** a 40pt `fg` circle with a `bg` glyph. When nothing is queued it becomes a
|
||||||
- **Drawer**: Queue | Lyrics tabs, sliding in from the right over the content edge.
|
`raised` circle with a `muted` glyph.
|
||||||
|
|
||||||
|
### Chips
|
||||||
|
- **Style:** pills padded 7×13, with a `line` outline and an `fg` label.
|
||||||
|
- **State:** a selected chip fills `accent` with an `accent-ink` label, and can't be clicked
|
||||||
|
again. Chips are used for quality, appearance, language and the My Wave mood, character and
|
||||||
|
language settings.
|
||||||
|
|
||||||
|
### Tabs
|
||||||
|
- Text only: `muted` labels that turn `fg` on hover or when selected, with a 2pt amber underline
|
||||||
|
under the selected tab. Collection tabs are Liked tracks, Albums, Artists, Playlists and Clips.
|
||||||
|
A count appears next to a tab once its list has loaded.
|
||||||
|
|
||||||
|
### Cards / Containers
|
||||||
|
- **Cover cards:** a 168pt cover with a medium title and a muted subtitle. A raised fill shows on
|
||||||
|
hover. Clicking opens the page. Right-click opens a menu for albums, playlists and artists:
|
||||||
|
Play, Shuffle, and add to or remove from the collection. Your own playlists get Rename… and
|
||||||
|
Delete… instead of the collection item. Clips have a heart instead of a menu.
|
||||||
|
- **Settings cards:** a `panel` fill, 1px `line`, card radius, 24pt padding, and a section title.
|
||||||
|
|
||||||
|
### Inputs / Fields
|
||||||
|
- **Search:** a 420pt pill with a `panel` fill and a 1px `line` border that turns `accent` on
|
||||||
|
focus. Selected text is highlighted in amber at 35%. Suggestions float in a list under it.
|
||||||
|
Opening Search, ⌘F or `/` puts the cursor in it with the text selected.
|
||||||
|
- **Dialog inputs:** use the same style.
|
||||||
|
|
||||||
|
### Navigation
|
||||||
|
- **Sidebar:** sits on `bg`, not `panel`, and is separated from the content by a seam. From top
|
||||||
|
to bottom: the wordmark, five nav items (Home, My Wave, Search, Collection, Podcasts), Playlists
|
||||||
|
with a + button, the playlist list, and an account chip with a settings gear. The active item
|
||||||
|
has a `raised` fill, an `fg` label and an amber icon. Idle items are `muted`.
|
||||||
|
- **Top bar:** a back chevron, disabled when there is no history, and the search field.
|
||||||
|
|
||||||
|
### Player bar
|
||||||
|
- `panel` fill, 80pt tall, in three zones.
|
||||||
|
- **Left:** a 52pt cover with the title and artist, then like and dislike buttons. Clicking the
|
||||||
|
cover or title opens Now Playing; right-clicking it opens the track's menu.
|
||||||
|
- **Centre:** shuffle, previous, the play disc, next and repeat, above a 4pt seek rail with an
|
||||||
|
amber fill. The rail's handle appears only on hover or drag. Times sit on either side.
|
||||||
|
- **Right:** the quality badge, Now Playing (expand), lyrics, queue, and a volume rail with an
|
||||||
|
`fg` fill.
|
||||||
|
|
||||||
|
### Track row
|
||||||
|
- 52pt tall, built as a button. Columns in order:
|
||||||
|
- a grip (your own playlists only)
|
||||||
|
- the index, or an amber `audio-lines` glyph for the playing track (static; it doesn't show
|
||||||
|
pause)
|
||||||
|
- a 40pt cover
|
||||||
|
- title and artist
|
||||||
|
- album
|
||||||
|
- the heart
|
||||||
|
- the duration
|
||||||
|
- "…"
|
||||||
|
- **Playing:** the title turns amber.
|
||||||
|
- **Unavailable:** the title is `muted` and clicking does nothing.
|
||||||
|
- Clicking plays the row and replaces the queue.
|
||||||
|
- Right-click, or "…", opens the context menu.
|
||||||
|
- A row stays lit (`raised`) while its menu is open, and while it is being dragged.
|
||||||
|
- The heart and "…" are always visible.
|
||||||
|
- **Dragging (your own playlists):** press the grip and move. The list reorders live to show
|
||||||
|
where the row will land. Drop to save, or press Esc to cancel. The wheel scrolls during a drag.
|
||||||
|
The list doesn't auto-scroll near its edges yet.
|
||||||
|
|
||||||
|
### Context menu (signature)
|
||||||
|
- A 280pt `panel` card with a 1px `line` border, cover radius, 6pt padding and the menu float.
|
||||||
|
There is no backdrop.
|
||||||
|
- **Placement:** it opens at the pointer on right-click, or hangs under "…" with the right edges
|
||||||
|
lined up. Near a window edge it flips left or up, and it always stays 8pt inside the window.
|
||||||
|
- **Entries:** 32pt tall, with an 18pt `muted` icon and a 14pt `fg` label. The entry under the
|
||||||
|
pointer, or chosen with the arrow keys, gets a `raised` fill. Destructive entries are `like`.
|
||||||
|
Disabled entries are `muted` and skipped by the arrow keys.
|
||||||
|
- **Groups:** separated by hairlines.
|
||||||
|
- **Track menus:** play actions (Play next or Next track, Add to queue, Play similar tracks);
|
||||||
|
library actions (Liked tracks, Add to playlist ▸, Don't recommend); go-to (album, then up to
|
||||||
|
three artists by name). Your own playlists add Move to top, Move to bottom, and Remove from
|
||||||
|
this playlist. In the queue the first group is Play now, Play next and Remove from queue.
|
||||||
|
- **Card menus:** Play and Shuffle; then the collection item, or Rename… and Delete… for your
|
||||||
|
own playlists; then go-to artist for albums.
|
||||||
|
- **Add to playlist ▸:** opens a submenu beside the menu on hover, click or →. The submenu holds
|
||||||
|
New playlist… and your own playlists, and scrolls after 10 rows.
|
||||||
|
- **Closing:** every action closes the menu, and a toast confirms what happened. Clicking outside,
|
||||||
|
scrolling or Esc also closes it. ↑/↓ move, Enter picks, → and ← open and close the submenu.
|
||||||
|
|
||||||
|
### Drawer
|
||||||
|
- 320pt on `panel`, with Queue | Lyrics tabs and a close button.
|
||||||
|
- **Queue:** shows Now playing, then Next up with a count. It lists up to 100 rows, then
|
||||||
|
"and N more". Clicking a row jumps to it. Right-click opens the queue version of the track menu.
|
||||||
|
- **Lyrics:** synced lyrics follow playback.
|
||||||
|
|
||||||
|
### Now Playing
|
||||||
|
- Follows the Apple TV app's Now Playing. It covers the whole window, player bar included, until
|
||||||
|
closed with the chevron at its top left, Esc, ⌘P or Back. Going to an album or artist from its
|
||||||
|
menu closes it too.
|
||||||
|
- **Backdrop:** the cover shrunk to 32px, blurred and stretched over the window, washed with
|
||||||
|
`bg` from 55% at the top to 92% at the bottom. Until the cover loads, its placeholder gradient
|
||||||
|
stands in.
|
||||||
|
- **Stage:** the cover at hero radius with the stage float, as large as the window allows between
|
||||||
|
160 and 520pt, and beside it the quality badge, the title in display-m (wrapping), the artists in
|
||||||
|
section `fg`, and the album in `muted`. A playback notice shows in `like`. With synced lyrics, the
|
||||||
|
line being sung shows under them in section amber.
|
||||||
|
- **Seek:** a 6pt rail with an amber fill across the stage, the times under its ends.
|
||||||
|
- **Controls:** shuffle, previous, a 56pt amber play disc (the primary style), next and repeat at
|
||||||
|
20pt; then the heart, "…", Queue and Lyrics pills (chip style, filled while their panel is open)
|
||||||
|
and the volume. Below 820pt of stage width the pills lose their labels.
|
||||||
|
- **Drawer:** opens at the right edge as in the main window, and Esc closes it before Now Playing.
|
||||||
|
|
||||||
|
### Dialogs
|
||||||
|
- 380pt `panel` card with card radius and the dialog float over a dimmed window.
|
||||||
|
- Used only when you type or confirm: New playlist, Rename playlist, and Delete playlist.
|
||||||
|
- Cancel is a ghost button. Confirm is primary, or `like` for Delete. Delete's white label on
|
||||||
|
`like` measures 2.8:1 in the dark theme, which is below AA, and is a known issue.
|
||||||
|
|
||||||
|
### Toast
|
||||||
|
- An `fg` pill with `bg` text, 96pt above the bottom edge. It reports every action from menus,
|
||||||
|
likes and edits, and clears itself after a few seconds.
|
||||||
|
|
||||||
|
### My Wave hero
|
||||||
|
- A 16pt-radius panel holding a canvas of 14 amber sine lines, the title, a line describing how
|
||||||
|
the wave is tuned, and Play / Pause / Resume.
|
||||||
|
- It is the same hero on Home and on My Wave, larger on My Wave.
|
||||||
|
- The lines drift only while My Wave plays. Otherwise they hold still at reduced energy.
|
||||||
|
|
||||||
|
### Keyboard shortcuts
|
||||||
|
- Listed in Settings → Keyboard shortcuts as label + key caps. The list is capped at 560pt wide so
|
||||||
|
the caps sit near their labels.
|
||||||
|
- The shortcuts:
|
||||||
|
- Space: play/pause
|
||||||
|
- ⌘←/→: previous/next
|
||||||
|
- ⇧←/→: seek 10s
|
||||||
|
- ⌘↑/↓: volume
|
||||||
|
- ⌘L: like
|
||||||
|
- ⌘F or `/`: search
|
||||||
|
- ⌘[ or ⌥←: back
|
||||||
|
- ⌘P: Now Playing
|
||||||
|
- Esc: closes a drag, menu, dialog, suggestions, the drawer or Now Playing, in that order
|
||||||
|
- ⌘1–5: nav sections
|
||||||
|
- ⌘,: Settings
|
||||||
|
- ⌘ is Ctrl on Windows and Linux.
|
||||||
|
- Letter shortcuts follow the key's position on non-Latin layouts.
|
||||||
|
|
||||||
|
## Do's and Don'ts
|
||||||
|
|
||||||
|
### Do:
|
||||||
|
- **Do** take every colour from `Tokens` in `theme.rs`, and change DESIGN.md in the same commit.
|
||||||
|
- **Do** use Lucide 0.460 icons at 18pt, tinted with the colour of the text they sit beside. New
|
||||||
|
icons go in `assets/icons` with the Lucide license header.
|
||||||
|
- **Do** put routine actions on an item in its context menu, and confirm them with a toast.
|
||||||
|
- **Do** give every new action a keyboard path, and add it to the Settings shortcut list.
|
||||||
|
- **Do** translate every string through `tr`/`trf` with a Russian entry in `i18n/ru.rs`. The test
|
||||||
|
suite fails otherwise.
|
||||||
|
- **Do** test new screens in both themes and both languages with the snapshot tool
|
||||||
|
(`MUSYX_SNAPSHOT_*`, see `snapshot.rs`). Russian labels run about 30% longer.
|
||||||
|
|
||||||
|
### Don't:
|
||||||
|
- **Don't** use amber for decoration, borders or illustrations other than the My Wave hero.
|
||||||
|
- **Don't** open a dialog for anything that doesn't need typing or a destructive confirmation.
|
||||||
|
- **Don't** dim the window for menus, the drawer or toasts.
|
||||||
|
- **Don't** fade icons with `scale_alpha`. iced's SVG tint drops alpha, so a faded icon renders at
|
||||||
|
full strength. Disabled previous/next already do this. Pre-mix the colour with the surface.
|
||||||
|
- **Don't** add hardcoded colours outside `theme.rs`. About 19 still exist (sign-in, genre tiles,
|
||||||
|
dialogs) and should move into tokens when touched.
|
||||||
|
- **Don't** add shadows to resting surfaces. Depth comes from `bg` → `panel` → `raised`.
|
||||||
|
|
||||||
|
## History
|
||||||
|
|
||||||
|
`design/mockup.html` (published at https://claude.ai/artifact/2gmswtceJM61fcE2F5uYYM) was the
|
||||||
|
first approved exploration, and it set the palette, type and shell. The build kept those and
|
||||||
|
deliberately dropped or replaced these parts of it:
|
||||||
|
- the hero's Tune button and the separate My Wave copy
|
||||||
|
- the hover play button on cards
|
||||||
|
- the display-face, two-column chart ranks
|
||||||
|
- the Podcasts and Disliked collection tabs (Clips was added)
|
||||||
|
- the Continue listening shelf for podcasts
|
||||||
|
- the drag grip with an edit bar (replaced by a grip column and live drag)
|
||||||
|
- Artist wave
|
||||||
|
- the hover-only "…"
|
||||||
|
- the animated equaliser on the playing row
|
||||||
|
- the live sign-in canvas
|
||||||
|
|
||||||
|
Treat the mockup as history. Where it and this file disagree, this file and the build win.
|
||||||
@@ -9,7 +9,9 @@ and it isn't affiliated with or endorsed by Yandex.
|
|||||||
|
|
||||||
- `crates/ym-api`: the Yandex Music API client, with no UI dependencies.
|
- `crates/ym-api`: the Yandex Music API client, with no UI dependencies.
|
||||||
- `crates/musyx`: the iced app (screens, widgets, player, theme).
|
- `crates/musyx`: the iced app (screens, widgets, player, theme).
|
||||||
- `design/mockup.html`: the approved design. `DESIGN.md` records its tokens.
|
- `DESIGN.md`: the design system as built; its tokens map 1:1 to `crates/musyx/src/ui/theme.rs`.
|
||||||
|
- `design/mockup.html`: the first design exploration, kept for history. Where it differs from
|
||||||
|
`DESIGN.md`, the build wins.
|
||||||
|
|
||||||
## Run
|
## Run
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ publish.workspace = true
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
ym-api = { path = "../ym-api" }
|
ym-api = { path = "../ym-api" }
|
||||||
|
subsonic-api = { path = "../subsonic-api" }
|
||||||
iced = { version = "0.14.0", features = ["svg", "image", "tokio", "advanced", "qr_code", "lazy", "canvas"] }
|
iced = { version = "0.14.0", features = ["svg", "image", "tokio", "advanced", "qr_code", "lazy", "canvas"] }
|
||||||
keyring = "4.2.0"
|
keyring = "4.2.0"
|
||||||
rodio = { version = "0.23.0", default-features = false, features = ["playback", "mp3", "mp4", "flac"] }
|
rodio = { version = "0.23.0", default-features = false, features = ["playback", "mp3", "mp4", "flac"] }
|
||||||
@@ -20,6 +21,8 @@ tokio = { version = "1", features = ["time", "rt", "fs", "sync"] }
|
|||||||
directories = "6.0.0"
|
directories = "6.0.0"
|
||||||
sys-locale = "0.3.2"
|
sys-locale = "0.3.2"
|
||||||
png = { version = "0.18.1", optional = true }
|
png = { version = "0.18.1", optional = true }
|
||||||
|
# Already built for iced's image widget; used directly to blur the Now Playing backdrop.
|
||||||
|
image = { version = "0.25", default-features = false }
|
||||||
|
|
||||||
[target.'cfg(target_os = "macos")'.dependencies]
|
[target.'cfg(target_os = "macos")'.dependencies]
|
||||||
objc2 = "0.6.3"
|
objc2 = "0.6.3"
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<!-- @license lucide-static v0.460.0 - ISC -->
|
||||||
|
<svg
|
||||||
|
class="lucide lucide-arrow-down-to-line"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
width="24"
|
||||||
|
height="24"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
stroke-width="2"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
>
|
||||||
|
<path d="M12 17V3" />
|
||||||
|
<path d="m6 11 6 6 6-6" />
|
||||||
|
<path d="M19 21H5" />
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 375 B |
@@ -0,0 +1,17 @@
|
|||||||
|
<!-- @license lucide-static v0.460.0 - ISC -->
|
||||||
|
<svg
|
||||||
|
class="lucide lucide-arrow-up-to-line"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
width="24"
|
||||||
|
height="24"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
stroke-width="2"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
>
|
||||||
|
<path d="M5 3h14" />
|
||||||
|
<path d="m18 13-6-6-6 6" />
|
||||||
|
<path d="M12 7v14" />
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 373 B |
@@ -0,0 +1,15 @@
|
|||||||
|
<!-- @license lucide-static v0.460.0 - ISC -->
|
||||||
|
<svg
|
||||||
|
class="lucide lucide-chevron-down"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
width="24"
|
||||||
|
height="24"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
stroke-width="2"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
>
|
||||||
|
<path d="m6 9 6 6 6-6" />
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 320 B |
@@ -0,0 +1,18 @@
|
|||||||
|
<!-- @license lucide-static v0.460.0 - ISC -->
|
||||||
|
<svg
|
||||||
|
class="lucide lucide-maximize-2"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
width="24"
|
||||||
|
height="24"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
stroke-width="2"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
>
|
||||||
|
<polyline points="15 3 21 3 21 9" />
|
||||||
|
<polyline points="9 21 3 21 3 15" />
|
||||||
|
<line x1="21" x2="14" y1="3" y2="10" />
|
||||||
|
<line x1="3" x2="10" y1="21" y2="14" />
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 452 B |
@@ -0,0 +1,18 @@
|
|||||||
|
<!-- @license lucide-static v0.460.0 - ISC -->
|
||||||
|
<svg
|
||||||
|
class="lucide lucide-server"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
width="24"
|
||||||
|
height="24"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
stroke-width="2"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
>
|
||||||
|
<rect width="20" height="8" x="2" y="2" rx="2" ry="2" />
|
||||||
|
<rect width="20" height="8" x="2" y="14" rx="2" ry="2" />
|
||||||
|
<line x1="6" x2="6.01" y1="6" y2="6" />
|
||||||
|
<line x1="6" x2="6.01" y1="18" y2="18" />
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 491 B |
@@ -0,0 +1,16 @@
|
|||||||
|
<!-- @license lucide-static v0.460.0 - ISC -->
|
||||||
|
<svg
|
||||||
|
class="lucide lucide-user"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
width="24"
|
||||||
|
height="24"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
stroke-width="2"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
>
|
||||||
|
<path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" />
|
||||||
|
<circle cx="12" cy="7" r="4" />
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 375 B |
@@ -74,10 +74,10 @@ async fn main() {
|
|||||||
if let Ok(found) = client.search("eminem without me", SearchKind::Tracks, 0).await {
|
if let Ok(found) = client.search("eminem without me", SearchKind::Tracks, 0).await {
|
||||||
for track in found.tracks.iter().take(2) {
|
for track in found.tracks.iter().take(2) {
|
||||||
println!("track {} {} lyrics_available={}", track.id, track.title, track.lyrics_available);
|
println!("track {} {} lyrics_available={}", track.id, track.title, track.lyrics_available);
|
||||||
match client.lyrics(&track.id).await {
|
match client.lyrics(track).await {
|
||||||
Ok(Some(l)) => println!(
|
Ok(Some(l)) => println!(
|
||||||
"lyrics {}: synced={} lines={} first_stamp={:?}",
|
"lyrics {}: {:?} synced={} lines={} first_stamp={:?}",
|
||||||
track.id, l.synced, l.lines.len(), l.lines.first().and_then(|x| x.at)
|
track.id, l.source, l.synced, l.lines.len(), l.lines.first().and_then(|x| x.at)
|
||||||
),
|
),
|
||||||
Ok(None) => println!("lyrics {}: none", track.id),
|
Ok(None) => println!("lyrics {}: none", track.id),
|
||||||
Err(e) => println!("lyrics {}: ERROR {e}", track.id),
|
Err(e) => println!("lyrics {}: ERROR {e}", track.id),
|
||||||
@@ -87,10 +87,10 @@ async fn main() {
|
|||||||
if let Ok(chart) = client.chart().await {
|
if let Ok(chart) = client.chart().await {
|
||||||
for entry in chart.iter().take(3) {
|
for entry in chart.iter().take(3) {
|
||||||
println!("chart {} lyrics_available={}", entry.track.id, entry.track.lyrics_available);
|
println!("chart {} lyrics_available={}", entry.track.id, entry.track.lyrics_available);
|
||||||
match client.lyrics(&entry.track.id).await {
|
match client.lyrics(&entry.track).await {
|
||||||
Ok(Some(l)) => println!(
|
Ok(Some(l)) => println!(
|
||||||
"lyrics {}: synced={} lines={} first_stamp={:?}",
|
"lyrics {}: {:?} synced={} lines={} first_stamp={:?}",
|
||||||
entry.track.id, l.synced, l.lines.len(), l.lines.first().and_then(|x| x.at)
|
entry.track.id, l.source, l.synced, l.lines.len(), l.lines.first().and_then(|x| x.at)
|
||||||
),
|
),
|
||||||
Ok(None) => println!("lyrics {}: none", entry.track.id),
|
Ok(None) => println!("lyrics {}: none", entry.track.id),
|
||||||
Err(e) => println!("lyrics {}: ERROR {e}", entry.track.id),
|
Err(e) => println!("lyrics {}: ERROR {e}", entry.track.id),
|
||||||
|
|||||||
+704
-72
File diff suppressed because it is too large.
Load diff
@@ -269,17 +269,18 @@ impl App {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Lyrics for the playing track, fetched once per track while the panel is open.
|
/// Lyrics for the playing track, fetched once per track while the panel or Now Playing is open.
|
||||||
pub(super) fn want_lyrics(&mut self) -> Task<Message> {
|
pub(super) fn want_lyrics(&mut self) -> Task<Message> {
|
||||||
let (Some(client), Some(track)) = (self.client().cloned(), self.player.track()) else { return Task::none() };
|
let (Some(client), Some(track)) = (self.client().cloned(), self.player.track()) else { return Task::none() };
|
||||||
if self.drawer != Some(crate::widgets::drawer::Panel::Lyrics) || self.lyrics.contains_key(&track.id) {
|
let shown = self.now_playing || self.drawer == Some(crate::widgets::drawer::Panel::Lyrics);
|
||||||
|
if !shown || self.lyrics.contains_key(&track.id) {
|
||||||
return Task::none();
|
return Task::none();
|
||||||
}
|
}
|
||||||
let id = track.id.clone();
|
let track = track.clone();
|
||||||
self.lyrics.insert(id.clone(), Loadable::Loading);
|
self.lyrics.insert(track.id.clone(), Loadable::Loading);
|
||||||
Task::future(async move {
|
Task::future(async move {
|
||||||
let result = client.lyrics(&id).await.map(|l| l.map(Arc::new));
|
let result = client.lyrics(&track).await.map(|l| l.map(Arc::new));
|
||||||
Message::LyricsLoaded(id, result)
|
Message::LyricsLoaded(track.id, result)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -24,10 +24,45 @@ pub const LARGE: u32 = 400;
|
|||||||
/// Downloads in flight at once.
|
/// Downloads in flight at once.
|
||||||
const PARALLEL: usize = 8;
|
const PARALLEL: usize = 8;
|
||||||
|
|
||||||
|
/// Side of the Now Playing backdrop in pixels; it is stretched over the window.
|
||||||
|
const BACKDROP: u32 = 32;
|
||||||
|
|
||||||
|
/// Who downloads a cover: Yandex for its own URLs, the music server for
|
||||||
|
/// `subsonic://cover/…` ones. Yandex's client sends its token with every
|
||||||
|
/// request, so it must never fetch a server URL.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub enum Fetcher {
|
||||||
|
Yandex(YmClient),
|
||||||
|
Server(subsonic_api::Client),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Fetcher {
|
||||||
|
/// The cache file name. Server covers include the host, since another
|
||||||
|
/// server can reuse the same cover id for a different picture.
|
||||||
|
fn file_name(&self, url: &str) -> String {
|
||||||
|
match self {
|
||||||
|
Fetcher::Yandex(_) => file_name(url),
|
||||||
|
Fetcher::Server(client) => file_name(&format!("{}|{url}", client.host())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch(&self, url: &str) -> Result<Vec<u8>, String> {
|
||||||
|
match self {
|
||||||
|
Fetcher::Yandex(client) => client.image(url).await.map_err(|e| e.to_string()),
|
||||||
|
Fetcher::Server(client) => {
|
||||||
|
let (id, size) = ym_api::parse_subsonic_cover(url).ok_or("not a server cover")?;
|
||||||
|
client.cover_art(id, size).await.map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub struct Covers {
|
pub struct Covers {
|
||||||
images: HashMap<String, image::Handle>,
|
images: HashMap<String, image::Handle>,
|
||||||
pending: HashSet<String>,
|
pending: HashSet<String>,
|
||||||
failed: HashSet<String>,
|
failed: HashSet<String>,
|
||||||
|
/// Blurred copies for the Now Playing backdrop, by cover url; `None` if it couldn't be decoded.
|
||||||
|
backdrops: HashMap<String, Option<image::Handle>>,
|
||||||
/// Bumped (debounced) when images arrive, so cached lists rebuild.
|
/// Bumped (debounced) when images arrive, so cached lists rebuild.
|
||||||
version: u64,
|
version: u64,
|
||||||
dirty: bool,
|
dirty: bool,
|
||||||
@@ -42,6 +77,7 @@ impl Default for Covers {
|
|||||||
images: HashMap::new(),
|
images: HashMap::new(),
|
||||||
pending: HashSet::new(),
|
pending: HashSet::new(),
|
||||||
failed: HashSet::new(),
|
failed: HashSet::new(),
|
||||||
|
backdrops: HashMap::new(),
|
||||||
version: 0,
|
version: 0,
|
||||||
dirty: false,
|
dirty: false,
|
||||||
dir,
|
dir,
|
||||||
@@ -55,6 +91,20 @@ impl Covers {
|
|||||||
self.images.get(url).cloned()
|
self.images.get(url).cloned()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn backdrop(&self, url: &str) -> Option<image::Handle> {
|
||||||
|
self.backdrops.get(url).cloned().flatten()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Blurs a loaded cover for the Now Playing backdrop, once per url.
|
||||||
|
pub fn make_backdrop(&mut self, url: &str) {
|
||||||
|
if self.backdrops.contains_key(url) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let Some(image::Handle::Bytes(_, bytes)) = self.images.get(url) else { return };
|
||||||
|
let blurred = blur(bytes);
|
||||||
|
self.backdrops.insert(url.to_owned(), blurred);
|
||||||
|
}
|
||||||
|
|
||||||
pub fn version(&self) -> u64 {
|
pub fn version(&self) -> u64 {
|
||||||
self.version
|
self.version
|
||||||
}
|
}
|
||||||
@@ -72,14 +122,14 @@ impl Covers {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Starts fetching `url` unless it is known, in flight, or failed before.
|
/// Starts fetching `url` unless it is known, in flight, or failed before.
|
||||||
pub fn want(&mut self, url: String, client: &YmClient) -> Task<Message> {
|
pub fn want(&mut self, url: String, fetcher: Fetcher) -> Task<Message> {
|
||||||
if self.images.contains_key(&url) || self.pending.contains(&url) || self.failed.contains(&url) {
|
if self.images.contains_key(&url) || self.pending.contains(&url) || self.failed.contains(&url) {
|
||||||
return Task::none();
|
return Task::none();
|
||||||
}
|
}
|
||||||
self.pending.insert(url.clone());
|
self.pending.insert(url.clone());
|
||||||
let (client, dir, gate) = (client.clone(), self.dir.clone(), self.gate.clone());
|
let (dir, gate) = (self.dir.clone(), self.gate.clone());
|
||||||
Task::future(async move {
|
Task::future(async move {
|
||||||
let bytes = load(&client, &url, dir, &gate).await;
|
let bytes = load(&fetcher, &url, dir, &gate).await;
|
||||||
Message::CoverLoaded(url, bytes)
|
Message::CoverLoaded(url, bytes)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -97,6 +147,15 @@ impl Covers {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Drops server covers held in memory, after switching servers.
|
||||||
|
pub fn forget_server(&mut self) {
|
||||||
|
let theirs = |url: &String| url.starts_with(ym_api::SUBSONIC_COVER_PREFIX);
|
||||||
|
self.images.retain(|url, _| !theirs(url));
|
||||||
|
self.failed.retain(|url| !theirs(url));
|
||||||
|
self.backdrops.retain(|url, _| !theirs(url));
|
||||||
|
self.version += 1;
|
||||||
|
}
|
||||||
|
|
||||||
pub fn loaded(&mut self, url: String, bytes: Option<Arc<[u8]>>) {
|
pub fn loaded(&mut self, url: String, bytes: Option<Arc<[u8]>>) {
|
||||||
self.pending.remove(&url);
|
self.pending.remove(&url);
|
||||||
match bytes {
|
match bytes {
|
||||||
@@ -111,8 +170,8 @@ impl Covers {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn load(client: &YmClient, url: &str, dir: Option<PathBuf>, gate: &Semaphore) -> Option<Arc<[u8]>> {
|
async fn load(fetcher: &Fetcher, url: &str, dir: Option<PathBuf>, gate: &Semaphore) -> Option<Arc<[u8]>> {
|
||||||
let path = dir.as_ref().map(|d| d.join(file_name(url)));
|
let path = dir.as_ref().map(|d| d.join(fetcher.file_name(url)));
|
||||||
if let Some(path) = &path
|
if let Some(path) = &path
|
||||||
&& let Ok(bytes) = tokio::fs::read(path).await
|
&& let Ok(bytes) = tokio::fs::read(path).await
|
||||||
{
|
{
|
||||||
@@ -120,7 +179,7 @@ async fn load(client: &YmClient, url: &str, dir: Option<PathBuf>, gate: &Semapho
|
|||||||
}
|
}
|
||||||
|
|
||||||
let _permit = gate.acquire().await.ok()?;
|
let _permit = gate.acquire().await.ok()?;
|
||||||
let bytes = match client.image(url).await {
|
let bytes = match fetcher.fetch(url).await {
|
||||||
Ok(bytes) if !bytes.is_empty() => bytes,
|
Ok(bytes) if !bytes.is_empty() => bytes,
|
||||||
Ok(_) => return None,
|
Ok(_) => return None,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
@@ -136,6 +195,14 @@ async fn load(client: &YmClient, url: &str, dir: Option<PathBuf>, gate: &Semapho
|
|||||||
Some(bytes.into())
|
Some(bytes.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Shrunk and blurred, so stretched over the window it reads as the cover's colours out of focus.
|
||||||
|
fn blur(bytes: &[u8]) -> Option<image::Handle> {
|
||||||
|
let cover = ::image::load_from_memory(bytes).ok()?;
|
||||||
|
let small = cover.thumbnail_exact(BACKDROP, BACKDROP).to_rgba8();
|
||||||
|
let soft = ::image::imageops::blur(&small, 3.0);
|
||||||
|
Some(image::Handle::from_rgba(BACKDROP, BACKDROP, soft.into_raw()))
|
||||||
|
}
|
||||||
|
|
||||||
/// A stable, filesystem-safe name for a URL (64-bit FNV-1a).
|
/// A stable, filesystem-safe name for a URL (64-bit FNV-1a).
|
||||||
fn file_name(url: &str) -> String {
|
fn file_name(url: &str) -> String {
|
||||||
let hash = url.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3));
|
let hash = url.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3));
|
||||||
@@ -176,6 +243,27 @@ mod tests {
|
|||||||
assert!(a.ends_with(".img") && a.len() == 20);
|
assert!(a.ends_with(".img") && a.len() == 20);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn backdrops_are_blurred_once_from_loaded_covers() {
|
||||||
|
let mut png = Vec::new();
|
||||||
|
::image::RgbaImage::from_fn(100, 100, |x, _| ::image::Rgba([if x < 50 { 255 } else { 0 }, 0, 0, 255]))
|
||||||
|
.write_to(&mut std::io::Cursor::new(&mut png), ::image::ImageFormat::Png)
|
||||||
|
.expect("encode");
|
||||||
|
let mut covers = Covers { dir: None, ..Covers::default() };
|
||||||
|
covers.make_backdrop("u");
|
||||||
|
assert!(covers.backdrop("u").is_none(), "nothing to blur before the cover loads");
|
||||||
|
covers.loaded("u".into(), Some(Arc::from(png)));
|
||||||
|
covers.make_backdrop("u");
|
||||||
|
let Some(image::Handle::Rgba { width, pixels, .. }) = covers.backdrop("u") else { panic!("no backdrop") };
|
||||||
|
assert_eq!(width, BACKDROP);
|
||||||
|
// The hard edge in the middle is softened into intermediate reds.
|
||||||
|
let red = |x: usize| pixels[(BACKDROP as usize * 16 + x) * 4];
|
||||||
|
assert!(red(0) > 200 && red(31) < 50 && (60..200).contains(&red(16)));
|
||||||
|
covers.loaded("bad".into(), Some(Arc::from(vec![1u8, 2, 3])));
|
||||||
|
covers.make_backdrop("bad");
|
||||||
|
assert!(covers.backdrop("bad").is_none());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn arrivals_bump_version_only_on_flush() {
|
fn arrivals_bump_version_only_on_flush() {
|
||||||
let mut covers = Covers { dir: None, ..Covers::default() };
|
let mut covers = Covers { dir: None, ..Covers::default() };
|
||||||
|
|||||||
@@ -10,6 +10,17 @@ pub fn get(english: &str) -> Option<&'static str> {
|
|||||||
"Collection" => "Коллекция",
|
"Collection" => "Коллекция",
|
||||||
"Podcasts" => "Подкасты",
|
"Podcasts" => "Подкасты",
|
||||||
"Settings" => "Настройки",
|
"Settings" => "Настройки",
|
||||||
|
"Keyboard shortcuts" => "Сочетания клавиш",
|
||||||
|
"Play or pause" => "Играть или пауза",
|
||||||
|
"Space" => "Пробел",
|
||||||
|
"Next or previous track" => "Следующий или предыдущий трек",
|
||||||
|
"Skip 10 seconds forward or back" => "Перемотать на 10 секунд вперёд или назад",
|
||||||
|
"Volume up or down" => "Громче или тише",
|
||||||
|
"Like or unlike the track playing" => "«Мне нравится» для играющего трека",
|
||||||
|
"Open or close Now Playing" => "Открыть или закрыть «Сейчас играет»",
|
||||||
|
"Go back" => "Назад",
|
||||||
|
"Close a menu or panel" => "Закрыть меню или панель",
|
||||||
|
"Home, My Wave, Search, Collection, My server, Podcasts" => "Главная, Моя волна, Поиск, Коллекция, Мой сервер, Подкасты",
|
||||||
"Album" => "Альбом",
|
"Album" => "Альбом",
|
||||||
"Artist" => "Исполнитель",
|
"Artist" => "Исполнитель",
|
||||||
"Playlist" => "Плейлист",
|
"Playlist" => "Плейлист",
|
||||||
@@ -264,12 +275,13 @@ pub fn get(english: &str) -> Option<&'static str> {
|
|||||||
"Очередь пока пуста. Здесь появятся треки, которые вы включите, и те, что за ними."
|
"Очередь пока пуста. Здесь появятся треки, которые вы включите, и те, что за ними."
|
||||||
}
|
}
|
||||||
"Play a track to see its lyrics." => "Включите трек, чтобы увидеть его текст.",
|
"Play a track to see its lyrics." => "Включите трек, чтобы увидеть его текст.",
|
||||||
"Yandex Music has no lyrics for this track." => "У Яндекс Музыки нет текста этого трека.",
|
"No lyrics for this track." => "У этого трека нет текста.",
|
||||||
"Couldn't load the lyrics. Check your connection and try again." => {
|
"Couldn't load the lyrics. Check your connection and try again." => {
|
||||||
"Не удалось загрузить текст. Проверьте подключение и попробуйте ещё раз."
|
"Не удалось загрузить текст. Проверьте подключение и попробуйте ещё раз."
|
||||||
}
|
}
|
||||||
"Loading lyrics…" => "Загружаем текст…",
|
"Loading lyrics…" => "Загружаем текст…",
|
||||||
"Written by {}" => "Авторы: {}",
|
"Written by {}" => "Авторы: {}",
|
||||||
|
"Lyrics from LRCLIB" => "Текст из LRCLIB",
|
||||||
"No sound output found. Connect speakers or headphones and playback picks up." => {
|
"No sound output found. Connect speakers or headphones and playback picks up." => {
|
||||||
"Не найдено устройство вывода звука. Подключите колонки или наушники, и воспроизведение продолжится."
|
"Не найдено устройство вывода звука. Подключите колонки или наушники, и воспроизведение продолжится."
|
||||||
}
|
}
|
||||||
@@ -299,6 +311,17 @@ pub fn get(english: &str) -> Option<&'static str> {
|
|||||||
"Move up" => "Переместить выше",
|
"Move up" => "Переместить выше",
|
||||||
"Move down" => "Переместить ниже",
|
"Move down" => "Переместить ниже",
|
||||||
"Remove from this playlist" => "Удалить из этого плейлиста",
|
"Remove from this playlist" => "Удалить из этого плейлиста",
|
||||||
|
"Rename…" => "Переименовать…",
|
||||||
|
"Delete…" => "Удалить…",
|
||||||
|
"Play now" => "Играть сейчас",
|
||||||
|
"Remove from queue" => "Убрать из очереди",
|
||||||
|
"Move to top" => "Переместить в начало",
|
||||||
|
"Move to bottom" => "Переместить в конец",
|
||||||
|
"Add to collection" => "Добавить в коллекцию",
|
||||||
|
"Remove from collection" => "Убрать из коллекции",
|
||||||
|
"Go to {}" => "Исполнитель: {}",
|
||||||
|
"Couldn't load the tracks. Try again." => "Не удалось загрузить треки. Попробуйте ещё раз.",
|
||||||
|
"There's nothing to play here." => "Здесь нечего слушать.",
|
||||||
"New playlist…" => "Новый плейлист…",
|
"New playlist…" => "Новый плейлист…",
|
||||||
"New playlist" => "Новый плейлист",
|
"New playlist" => "Новый плейлист",
|
||||||
"Rename playlist" => "Переименовать плейлист",
|
"Rename playlist" => "Переименовать плейлист",
|
||||||
@@ -352,6 +375,41 @@ pub fn get(english: &str) -> Option<&'static str> {
|
|||||||
"Moved" => "Перемещено",
|
"Moved" => "Перемещено",
|
||||||
"Couldn't move the track. Try again." => "Не удалось переместить трек. Попробуйте ещё раз.",
|
"Couldn't move the track. Try again." => "Не удалось переместить трек. Попробуйте ещё раз.",
|
||||||
|
|
||||||
|
// My server (Navidrome and other Subsonic servers)
|
||||||
|
"My server" => "Мой сервер",
|
||||||
|
"Checking your server…" => "Проверяем сервер…",
|
||||||
|
"Connect your Navidrome or another Subsonic-compatible server to browse and play your own music here." => "Подключите Navidrome или другой Subsonic-совместимый сервер, чтобы слушать здесь свою музыку.",
|
||||||
|
"Browse and play a Navidrome or other Subsonic-compatible server under My server. The password is kept in the system keychain." => "Слушайте музыку с Navidrome или другого Subsonic-совместимого сервера в разделе «Мой сервер». Пароль хранится в системной связке ключей.",
|
||||||
|
"Server address" => "Адрес сервера",
|
||||||
|
"Username" => "Имя пользователя",
|
||||||
|
"Password" => "Пароль",
|
||||||
|
"Connect" => "Подключить",
|
||||||
|
"Connecting…" => "Подключаемся…",
|
||||||
|
"Disconnect" => "Отключить",
|
||||||
|
"Connected to {} as {}." => "Подключено к {} как {}.",
|
||||||
|
"{} on {}" => "{} на {}",
|
||||||
|
"Enter the server address and your username." => "Введите адрес сервера и имя пользователя.",
|
||||||
|
"That doesn't look like a server address. Try something like music.example.com." => "Это не похоже на адрес сервера. Попробуйте, например, music.example.com.",
|
||||||
|
"Couldn't reach the server. Check the address and your connection." => "Не удалось связаться с сервером. Проверьте адрес и подключение к интернету.",
|
||||||
|
"That address didn't answer like a music server. Check it and try again." => "По этому адресу не отвечает музыкальный сервер. Проверьте адрес и попробуйте ещё раз.",
|
||||||
|
"The server didn't accept that username and password." => "Сервер не принял имя пользователя и пароль.",
|
||||||
|
"The server no longer accepts your sign-in. Disconnect it in Settings and connect again." => "Сервер больше не принимает ваш вход. Отключите его в настройках и подключите снова.",
|
||||||
|
"Search your server" => "Поиск на сервере",
|
||||||
|
"Clear" => "Очистить",
|
||||||
|
"Recently added" => "Недавно добавленные",
|
||||||
|
"A–Z" => "А–Я",
|
||||||
|
"Starred" => "Избранное",
|
||||||
|
"your starred songs" => "избранные треки",
|
||||||
|
"The server has no albums yet." => "На сервере пока нет альбомов.",
|
||||||
|
"The server has no artists yet." => "На сервере пока нет исполнителей.",
|
||||||
|
"No playlists yet. Playlists you make on the server show up here." => "Плейлистов пока нет. Плейлисты, созданные на сервере, появятся здесь.",
|
||||||
|
"No starred songs yet. Star songs on the server and they show up here." => "Избранных треков пока нет. Отметьте треки звёздочкой на сервере, и они появятся здесь.",
|
||||||
|
"Nothing on your server matches that." => "На сервере ничего не нашлось.",
|
||||||
|
"This album isn't on your server any more." => "Этого альбома больше нет на сервере.",
|
||||||
|
"This artist isn't on your server any more." => "Этого исполнителя больше нет на сервере.",
|
||||||
|
"This playlist isn't on your server any more." => "Этого плейлиста больше нет на сервере.",
|
||||||
|
"Connect your server under My server to see this page." => "Подключите сервер в разделе «Мой сервер», чтобы открыть эту страницу.",
|
||||||
|
|
||||||
// Units
|
// Units
|
||||||
"{} h {} min" => "{} ч {} мин",
|
"{} h {} min" => "{} ч {} мин",
|
||||||
"{} min" => "{} мин",
|
"{} min" => "{} мин",
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ mod player;
|
|||||||
mod route;
|
mod route;
|
||||||
mod screens;
|
mod screens;
|
||||||
mod session;
|
mod session;
|
||||||
|
mod shortcuts;
|
||||||
mod store;
|
mod store;
|
||||||
#[cfg(feature = "snapshot")]
|
#[cfg(feature = "snapshot")]
|
||||||
mod snapshot;
|
mod snapshot;
|
||||||
|
|||||||
@@ -101,12 +101,13 @@ impl Media {
|
|||||||
if new_track {
|
if new_track {
|
||||||
let title = track.full_title();
|
let title = track.full_title();
|
||||||
let artist = track.artist_line();
|
let artist = track.artist_line();
|
||||||
let album = track.album.as_ref().map(|a| a.title.clone());
|
let album = track.album_title();
|
||||||
let cover = track.cover_url(covers::LARGE);
|
// Server covers are app-internal URLs the system can't open.
|
||||||
|
let cover = track.cover_url(covers::LARGE).filter(|url| url.starts_with("http"));
|
||||||
let _ = controls.set_metadata(MediaMetadata {
|
let _ = controls.set_metadata(MediaMetadata {
|
||||||
title: Some(&title),
|
title: Some(&title),
|
||||||
artist: Some(&artist),
|
artist: Some(&artist),
|
||||||
album: album.as_deref(),
|
album,
|
||||||
cover_url: cover.as_deref(),
|
cover_url: cover.as_deref(),
|
||||||
duration: Some(track.duration),
|
duration: Some(track.duration),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -55,6 +55,9 @@ pub enum Msg {
|
|||||||
SetVolume(f32),
|
SetVolume(f32),
|
||||||
ToggleMute,
|
ToggleMute,
|
||||||
JumpTo(usize),
|
JumpTo(usize),
|
||||||
|
/// Take an upcoming track out of the queue: a position from `Queue::upcoming`
|
||||||
|
/// and the track's id, so a queue that changed meanwhile loses nothing else.
|
||||||
|
Remove { pos: usize, id: String },
|
||||||
Fetched { generation: u64, result: Result<Audio, Error> },
|
Fetched { generation: u64, result: Result<Audio, Error> },
|
||||||
Prefetched { track_id: String, result: Result<Audio, Error> },
|
Prefetched { track_id: String, result: Result<Audio, Error> },
|
||||||
/// Start a station (`type:tag`).
|
/// Start a station (`type:tag`).
|
||||||
@@ -72,14 +75,25 @@ pub enum Msg {
|
|||||||
/// Work the app has to do on the player's behalf.
|
/// Work the app has to do on the player's behalf.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum Effect {
|
pub enum Effect {
|
||||||
Fetch { generation: u64, track_id: String },
|
/// Download `track`'s audio from wherever it lives.
|
||||||
Prefetch { track_id: String },
|
Fetch { generation: u64, track: Track },
|
||||||
|
Prefetch { track: Track },
|
||||||
/// The token stopped working mid-session.
|
/// The token stopped working mid-session.
|
||||||
SignedOut,
|
SignedOut,
|
||||||
/// Start a session (`session_id: None`) or continue one; `queue` is recent `full_id`s.
|
/// Start a session (`session_id: None`) or continue one; `queue` is recent `full_id`s.
|
||||||
WaveFetch { station: String, session_id: Option<String>, queue: Vec<String> },
|
WaveFetch { station: String, session_id: Option<String>, queue: Vec<String> },
|
||||||
WaveFeedback { session_id: String, event: WaveEvent, batch_id: Option<String> },
|
WaveFeedback { session_id: String, event: WaveEvent, batch_id: Option<String> },
|
||||||
|
/// A finished or abandoned listen of a Yandex track.
|
||||||
Report(PlayReport),
|
Report(PlayReport),
|
||||||
|
/// A track from a music server started: set it as "now playing" there.
|
||||||
|
NowPlaying(Track),
|
||||||
|
/// A music-server track was played long enough to count as a play.
|
||||||
|
Scrobble(Track),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The usual scrobbling rule: half the track, or four minutes of a long one.
|
||||||
|
pub fn counts_as_play(played: Duration, length: Duration) -> bool {
|
||||||
|
!length.is_zero() && played >= (length / 2).min(Duration::from_secs(240))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A station being played, endlessly topped up.
|
/// A station being played, endlessly topped up.
|
||||||
@@ -321,6 +335,14 @@ impl Player {
|
|||||||
}
|
}
|
||||||
self.send(Command::Volume(self.effective_volume()));
|
self.send(Command::Volume(self.effective_volume()));
|
||||||
}
|
}
|
||||||
|
Msg::Remove { pos, id } => {
|
||||||
|
if let Some(queue) = &mut self.queue
|
||||||
|
&& queue.upcoming().any(|(p, t)| p == pos && t.id == id)
|
||||||
|
&& queue.remove(pos)
|
||||||
|
{
|
||||||
|
return self.prefetch_next();
|
||||||
|
}
|
||||||
|
}
|
||||||
Msg::JumpTo(pos) => {
|
Msg::JumpTo(pos) => {
|
||||||
let mut effects = self.leave(false);
|
let mut effects = self.leave(false);
|
||||||
if let Some(queue) = &mut self.queue {
|
if let Some(queue) = &mut self.queue {
|
||||||
@@ -370,8 +392,11 @@ impl Player {
|
|||||||
self.status = Status::Playing;
|
self.status = Status::Playing;
|
||||||
self.skips = 0;
|
self.skips = 0;
|
||||||
let mut effects = Vec::new();
|
let mut effects = Vec::new();
|
||||||
if let Some((id, full_id)) = self.track().map(|t| (t.id.clone(), t.full_id())) {
|
if let Some(track) = self.track().cloned() {
|
||||||
if let Some(wave) = &self.wave
|
let (id, full_id) = (track.id.clone(), track.full_id());
|
||||||
|
if !track.is_yandex() {
|
||||||
|
effects.push(Effect::NowPlaying(track));
|
||||||
|
} else if let Some(wave) = &self.wave
|
||||||
&& let Some(session_id) = wave.session_id.clone()
|
&& let Some(session_id) = wave.session_id.clone()
|
||||||
{
|
{
|
||||||
effects.push(Effect::WaveFeedback {
|
effects.push(Effect::WaveFeedback {
|
||||||
@@ -444,6 +469,10 @@ impl Player {
|
|||||||
let Some(id) = self.started.take() else { return vec![] };
|
let Some(id) = self.started.take() else { return vec![] };
|
||||||
let Some(track) = self.track().filter(|t| t.id == id) else { return vec![] };
|
let Some(track) = self.track().filter(|t| t.id == id) else { return vec![] };
|
||||||
let played = if finished { self.duration } else { self.position.min(self.duration) };
|
let played = if finished { self.duration } else { self.position.min(self.duration) };
|
||||||
|
// Server tracks are reported to their server, never to Yandex or its stations.
|
||||||
|
if !track.is_yandex() {
|
||||||
|
return if counts_as_play(played, self.duration) { vec![Effect::Scrobble(track.clone())] } else { vec![] };
|
||||||
|
}
|
||||||
let mut effects = vec![Effect::Report(PlayReport {
|
let mut effects = vec![Effect::Report(PlayReport {
|
||||||
track_id: id.clone(),
|
track_id: id.clone(),
|
||||||
album_id: track.album.as_ref().map(|a| a.id),
|
album_id: track.album.as_ref().map(|a| a.id),
|
||||||
@@ -564,7 +593,7 @@ impl Player {
|
|||||||
None => {
|
None => {
|
||||||
self.status = Status::Loading;
|
self.status = Status::Loading;
|
||||||
self.current = None;
|
self.current = None;
|
||||||
vec![Effect::Fetch { generation: self.generation, track_id: track.id }]
|
vec![Effect::Fetch { generation: self.generation, track }]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -599,7 +628,7 @@ impl Player {
|
|||||||
return vec![];
|
return vec![];
|
||||||
}
|
}
|
||||||
self.prefetched = None;
|
self.prefetched = None;
|
||||||
vec![Effect::Prefetch { track_id: next.id.clone() }]
|
vec![Effect::Prefetch { track: next.clone() }]
|
||||||
}
|
}
|
||||||
|
|
||||||
fn skip_unplayable(&mut self) -> Vec<Effect> {
|
fn skip_unplayable(&mut self) -> Vec<Effect> {
|
||||||
@@ -656,14 +685,14 @@ mod tests {
|
|||||||
let mut p = Player::default();
|
let mut p = Player::default();
|
||||||
let tracks: Arc<[Track]> = vec![track("a", 10), track("b", 20)].into();
|
let tracks: Arc<[Track]> = vec![track("a", 10), track("b", 20)].into();
|
||||||
let effects = p.update(Msg::Play { tracks, start: 0, shuffle: None });
|
let effects = p.update(Msg::Play { tracks, start: 0, shuffle: None });
|
||||||
assert!(effects.contains(&Effect::Fetch { generation: 1, track_id: "a".into() }), "{effects:?}");
|
assert!(effects.contains(&Effect::Fetch { generation: 1, track: track("a", 10) }), "{effects:?}");
|
||||||
assert_eq!(effects.iter().filter(|e| matches!(e, Effect::Fetch { .. })).count(), 1);
|
assert_eq!(effects.iter().filter(|e| matches!(e, Effect::Fetch { .. })).count(), 1);
|
||||||
assert_eq!(p.status(), Status::Loading);
|
assert_eq!(p.status(), Status::Loading);
|
||||||
assert!(p.update(Msg::Fetched { generation: 1, result: Ok(audio()) }).is_empty());
|
assert!(p.update(Msg::Fetched { generation: 1, result: Ok(audio()) }).is_empty());
|
||||||
let effects = p.update(Msg::Engine(Event::Loaded { generation: 1, duration: None }));
|
let effects = p.update(Msg::Engine(Event::Loaded { generation: 1, duration: None }));
|
||||||
assert_eq!(p.status(), Status::Playing);
|
assert_eq!(p.status(), Status::Playing);
|
||||||
assert_eq!(p.duration(), Duration::from_secs(10));
|
assert_eq!(p.duration(), Duration::from_secs(10));
|
||||||
assert_eq!(effects, vec![Effect::Prefetch { track_id: "b".into() }]);
|
assert_eq!(effects, vec![Effect::Prefetch { track: track("b", 20) }]);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -850,7 +879,7 @@ mod tests {
|
|||||||
assert_eq!(p.status(), Status::Loading, "a wave doesn't end");
|
assert_eq!(p.status(), Status::Loading, "a wave doesn't end");
|
||||||
let batch = WaveBatch { session_id: Some("s1".into()), tracks: vec![track("w9", 50)], batch_id: Some("b2".into()) };
|
let batch = WaveBatch { session_id: Some("s1".into()), tracks: vec![track("w9", 50)], batch_id: Some("b2".into()) };
|
||||||
let effects = p.update(Msg::WaveBatch { station: "user:onyourwave".into(), result: Ok(batch) });
|
let effects = p.update(Msg::WaveBatch { station: "user:onyourwave".into(), result: Ok(batch) });
|
||||||
assert!(matches!(effects.first(), Some(Effect::Fetch { track_id, .. }) if track_id == "w9"));
|
assert!(matches!(effects.first(), Some(Effect::Fetch { track, .. }) if track.id == "w9"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -890,7 +919,7 @@ mod tests {
|
|||||||
|
|
||||||
let mut empty = Player::default();
|
let mut empty = Player::default();
|
||||||
let effects = empty.update(Msg::Append(track("solo", 5)));
|
let effects = empty.update(Msg::Append(track("solo", 5)));
|
||||||
assert!(effects.iter().any(|e| matches!(e, Effect::Fetch { track_id, .. } if track_id == "solo")));
|
assert!(effects.iter().any(|e| matches!(e, Effect::Fetch { track, .. } if track.id == "solo")));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -898,7 +927,7 @@ mod tests {
|
|||||||
let mut p = playing(3, 0);
|
let mut p = playing(3, 0);
|
||||||
p.update(Msg::Prefetched { track_id: "1".into(), result: Ok(audio()) });
|
p.update(Msg::Prefetched { track_id: "1".into(), result: Ok(audio()) });
|
||||||
let effects = p.update(Msg::PlayNext(track("n", 5)));
|
let effects = p.update(Msg::PlayNext(track("n", 5)));
|
||||||
assert!(effects.contains(&Effect::Prefetch { track_id: "n".into() }), "{effects:?}");
|
assert!(effects.iter().any(|e| matches!(e, Effect::Prefetch { track } if track.id == "n")), "{effects:?}");
|
||||||
let generation = p.generation;
|
let generation = p.generation;
|
||||||
let effects = p.update(Msg::Engine(Event::Ended { generation }));
|
let effects = p.update(Msg::Engine(Event::Ended { generation }));
|
||||||
assert_eq!(p.track().unwrap().id, "n", "{effects:?}");
|
assert_eq!(p.track().unwrap().id, "n", "{effects:?}");
|
||||||
@@ -941,4 +970,57 @@ mod tests {
|
|||||||
assert!(!p.muted);
|
assert!(!p.muted);
|
||||||
assert_eq!(p.volume, 0.5);
|
assert_eq!(p.volume, 0.5);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn server_track(id: &str, secs: u64) -> Track {
|
||||||
|
let song = ym_api::SubsonicSong {
|
||||||
|
song_id: id.into(),
|
||||||
|
album_id: None,
|
||||||
|
album_title: None,
|
||||||
|
artist_id: None,
|
||||||
|
cover_art: None,
|
||||||
|
suffix: "mp3".into(),
|
||||||
|
bit_rate: 320,
|
||||||
|
};
|
||||||
|
Track::from_subsonic(format!("S{id}"), None, Duration::from_secs(secs), song)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn server_tracks_in_a_wave_report_to_their_server_only() {
|
||||||
|
let mut p = wave_with(3);
|
||||||
|
loaded(&mut p);
|
||||||
|
p.update(Msg::PlayNext(server_track("s1", 100)));
|
||||||
|
let effects = p.update(Msg::Next);
|
||||||
|
assert!(effects.iter().any(|e| matches!(e, Effect::Fetch { track, .. } if track.id == "sub-s1")), "{effects:?}");
|
||||||
|
let generation = p.generation;
|
||||||
|
p.update(Msg::Fetched { generation, result: Ok(audio()) });
|
||||||
|
let effects = loaded(&mut p);
|
||||||
|
assert!(effects.iter().any(|e| matches!(e, Effect::NowPlaying(t) if t.id == "sub-s1")), "{effects:?}");
|
||||||
|
assert!(!effects.iter().any(|e| matches!(e, Effect::WaveFeedback { .. })), "{effects:?}");
|
||||||
|
|
||||||
|
let generation = p.generation;
|
||||||
|
p.update(Msg::Engine(Event::Position { generation, position: Duration::from_secs(30) }));
|
||||||
|
let effects = p.update(Msg::Next);
|
||||||
|
assert!(
|
||||||
|
!effects.iter().any(|e| matches!(e, Effect::Report(_) | Effect::WaveFeedback { .. } | Effect::Scrobble(_))),
|
||||||
|
"30 of 100 seconds: nothing to report anywhere: {effects:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn server_tracks_scrobble_after_half_or_four_minutes() {
|
||||||
|
let mut p = Player::default();
|
||||||
|
let tracks: Arc<[Track]> = vec![server_track("a", 100), server_track("b", 100)].into();
|
||||||
|
let effects = p.update(Msg::Play { tracks, start: 0, shuffle: None });
|
||||||
|
let generation = fetch_generation(&effects).unwrap();
|
||||||
|
p.update(Msg::Fetched { generation, result: Ok(audio()) });
|
||||||
|
loaded(&mut p);
|
||||||
|
p.update(Msg::Engine(Event::Position { generation, position: Duration::from_secs(60) }));
|
||||||
|
let effects = p.update(Msg::Next);
|
||||||
|
assert!(effects.iter().any(|e| matches!(e, Effect::Scrobble(t) if t.id == "sub-a")), "{effects:?}");
|
||||||
|
assert!(!effects.iter().any(|e| matches!(e, Effect::Report(_))));
|
||||||
|
|
||||||
|
assert!(counts_as_play(Duration::from_secs(240), Duration::from_secs(3600)));
|
||||||
|
assert!(!counts_as_play(Duration::from_secs(239), Duration::from_secs(3600)));
|
||||||
|
assert!(!counts_as_play(Duration::ZERO, Duration::ZERO));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -161,6 +161,23 @@ impl<T> Queue<T> {
|
|||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Takes an upcoming item out of the play order. Positions are the ones
|
||||||
|
/// [`Queue::upcoming`] reports; the current item and anything before it stay.
|
||||||
|
/// Returns whether something was removed.
|
||||||
|
pub fn remove(&mut self, order_pos: usize) -> bool {
|
||||||
|
if order_pos <= self.pos || order_pos >= self.order.len() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let index = self.order.remove(order_pos);
|
||||||
|
self.items.remove(index);
|
||||||
|
for i in &mut self.order {
|
||||||
|
if *i > index {
|
||||||
|
*i -= 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
/// Drops everything after the current item, e.g. when a station's settings change.
|
/// Drops everything after the current item, e.g. when a station's settings change.
|
||||||
pub fn clear_upcoming(&mut self) {
|
pub fn clear_upcoming(&mut self) {
|
||||||
let keep: Vec<usize> = self.order[..=self.pos].to_vec();
|
let keep: Vec<usize> = self.order[..=self.pos].to_vec();
|
||||||
@@ -184,6 +201,21 @@ mod tests {
|
|||||||
assert!(Queue::<u8>::new(vec![], 0, false).is_none());
|
assert!(Queue::<u8>::new(vec![], 0, false).is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn remove_takes_out_an_upcoming_item_only() {
|
||||||
|
let mut q = q(5, 1);
|
||||||
|
assert!(q.remove(3));
|
||||||
|
assert_eq!(q.upcoming().map(|(_, &i)| i).collect::<Vec<_>>(), [2, 4]);
|
||||||
|
assert!(!q.remove(1), "the current item stays");
|
||||||
|
assert!(!q.remove(0), "played items stay");
|
||||||
|
assert!(!q.remove(9));
|
||||||
|
// Shuffling off again must not bring the removed item back.
|
||||||
|
q.set_shuffle(true);
|
||||||
|
q.set_shuffle(false);
|
||||||
|
assert_eq!(q.len(), 4);
|
||||||
|
assert!(!q.upcoming().any(|(_, &i)| i == 3));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn start_is_clamped() {
|
fn start_is_clamped() {
|
||||||
assert_eq!(*q(3, 99).current(), 2);
|
assert_eq!(*q(3, 99).current(), 2);
|
||||||
|
|||||||
@@ -6,12 +6,26 @@ use ym_api::PlaylistId;
|
|||||||
|
|
||||||
use crate::ui::icons::Icon;
|
use crate::ui::icons::Icon;
|
||||||
|
|
||||||
|
/// A music-server id (album, artist, playlist) as a `Copy` handle, so routes
|
||||||
|
/// to server pages stay `Copy`. The server screen maps it back to the id.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
pub struct Sid(pub u64);
|
||||||
|
|
||||||
|
impl Sid {
|
||||||
|
/// 64-bit FNV-1a of the id; equal ids give equal handles.
|
||||||
|
pub fn of(id: &str) -> Sid {
|
||||||
|
Sid(id.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
pub enum Route {
|
pub enum Route {
|
||||||
Home,
|
Home,
|
||||||
Wave,
|
Wave,
|
||||||
Search,
|
Search,
|
||||||
Collection,
|
Collection,
|
||||||
|
/// The user's own music server (Navidrome or another Subsonic server).
|
||||||
|
Server,
|
||||||
Podcasts,
|
Podcasts,
|
||||||
Settings,
|
Settings,
|
||||||
Album(i64),
|
Album(i64),
|
||||||
@@ -20,12 +34,15 @@ pub enum Route {
|
|||||||
Chart,
|
Chart,
|
||||||
/// Index into the app's flattened genre list.
|
/// Index into the app's flattened genre list.
|
||||||
Genre(usize),
|
Genre(usize),
|
||||||
|
ServerAlbum(Sid),
|
||||||
|
ServerArtist(Sid),
|
||||||
|
ServerPlaylist(Sid),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Route {
|
impl Route {
|
||||||
/// Sidebar order.
|
/// Sidebar order.
|
||||||
pub const NAV: [Route; 5] =
|
pub const NAV: [Route; 6] =
|
||||||
[Route::Home, Route::Wave, Route::Search, Route::Collection, Route::Podcasts];
|
[Route::Home, Route::Wave, Route::Search, Route::Collection, Route::Server, Route::Podcasts];
|
||||||
|
|
||||||
pub fn label(self) -> &'static str {
|
pub fn label(self) -> &'static str {
|
||||||
match self {
|
match self {
|
||||||
@@ -33,27 +50,34 @@ impl Route {
|
|||||||
Route::Wave => tr("My Wave"),
|
Route::Wave => tr("My Wave"),
|
||||||
Route::Search => tr("Search"),
|
Route::Search => tr("Search"),
|
||||||
Route::Collection => tr("Collection"),
|
Route::Collection => tr("Collection"),
|
||||||
|
Route::Server => tr("My server"),
|
||||||
Route::Podcasts => tr("Podcasts"),
|
Route::Podcasts => tr("Podcasts"),
|
||||||
Route::Settings => tr("Settings"),
|
Route::Settings => tr("Settings"),
|
||||||
Route::Album(_) => tr("Album"),
|
Route::Album(_) | Route::ServerAlbum(_) => tr("Album"),
|
||||||
Route::Artist(_) => tr("Artist"),
|
Route::Artist(_) | Route::ServerArtist(_) => tr("Artist"),
|
||||||
Route::Playlist(_) => tr("Playlist"),
|
Route::Playlist(_) | Route::ServerPlaylist(_) => tr("Playlist"),
|
||||||
Route::Chart => tr("Chart"),
|
Route::Chart => tr("Chart"),
|
||||||
Route::Genre(_) => tr("Genre"),
|
Route::Genre(_) => tr("Genre"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// My server and its album, artist and playlist pages.
|
||||||
|
pub fn is_server(self) -> bool {
|
||||||
|
matches!(self, Route::Server | Route::ServerAlbum(_) | Route::ServerArtist(_) | Route::ServerPlaylist(_))
|
||||||
|
}
|
||||||
|
|
||||||
pub fn icon(self) -> Icon {
|
pub fn icon(self) -> Icon {
|
||||||
match self {
|
match self {
|
||||||
Route::Home => Icon::Home,
|
Route::Home => Icon::Home,
|
||||||
Route::Wave => Icon::Wave,
|
Route::Wave => Icon::Wave,
|
||||||
Route::Search => Icon::Search,
|
Route::Search => Icon::Search,
|
||||||
Route::Collection => Icon::Library,
|
Route::Collection => Icon::Library,
|
||||||
|
Route::Server => Icon::Server,
|
||||||
Route::Podcasts => Icon::Podcast,
|
Route::Podcasts => Icon::Podcast,
|
||||||
Route::Settings => Icon::Settings,
|
Route::Settings => Icon::Settings,
|
||||||
Route::Album(_) => Icon::Disc,
|
Route::Album(_) | Route::ServerAlbum(_) => Icon::Disc,
|
||||||
Route::Artist(_) => Icon::Wave,
|
Route::Artist(_) | Route::ServerArtist(_) => Icon::Wave,
|
||||||
Route::Playlist(_) => Icon::Queue,
|
Route::Playlist(_) | Route::ServerPlaylist(_) => Icon::Queue,
|
||||||
Route::Chart => Icon::Chart,
|
Route::Chart => Icon::Chart,
|
||||||
Route::Genre(_) => Icon::Library,
|
Route::Genre(_) => Icon::Library,
|
||||||
}
|
}
|
||||||
@@ -125,6 +149,14 @@ mod tests {
|
|||||||
assert!(!nav.can_go_back());
|
assert!(!nav.can_go_back());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn server_ids_become_stable_route_handles() {
|
||||||
|
assert_eq!(Sid::of("al-1"), Sid::of("al-1"));
|
||||||
|
assert_ne!(Sid::of("al-1"), Sid::of("al-2"));
|
||||||
|
assert_ne!(Route::ServerAlbum(Sid::of("x")), Route::ServerArtist(Sid::of("x")));
|
||||||
|
assert_eq!(Route::NAV[4], Route::Server, "My server sits after Collection");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn history_is_bounded() {
|
fn history_is_bounded() {
|
||||||
let mut nav = Navigator::new(Route::Home);
|
let mut nav = Navigator::new(Route::Home);
|
||||||
|
|||||||
@@ -105,6 +105,7 @@ pub fn home<'a>(env: Env<'a>, discover: &'a Discover, hero: Element<'a, Message>
|
|||||||
hues: p.playlist.hues(),
|
hues: p.playlist.hues(),
|
||||||
round: false,
|
round: false,
|
||||||
on_press: Message::Navigate(Route::Playlist(p.playlist.id)),
|
on_press: Message::Navigate(Route::Playlist(p.playlist.id)),
|
||||||
|
menu: Some(crate::widgets::menu::Target::Playlist(p.playlist.clone())),
|
||||||
})
|
})
|
||||||
}),
|
}),
|
||||||
));
|
));
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ use crate::ui::icons::{Icon, icon};
|
|||||||
use crate::ui::theme::{self, Tokens, size};
|
use crate::ui::theme::{self, Tokens, size};
|
||||||
use crate::ui::{duration_words, line, para, tracks_word};
|
use crate::ui::{duration_words, line, para, tracks_word};
|
||||||
use crate::widgets::card::{self, Card};
|
use crate::widgets::card::{self, Card};
|
||||||
|
use crate::widgets::menu::Target;
|
||||||
use crate::widgets::track_list::{self, Env};
|
use crate::widgets::track_list::{self, Env};
|
||||||
use crate::widgets::track_row::Columns;
|
use crate::widgets::track_row::Columns;
|
||||||
use crate::i18n::{tr, trf};
|
use crate::i18n::{tr, trf};
|
||||||
@@ -277,6 +278,7 @@ pub fn album_card<'a>(t: &'static Tokens, covers: &Covers, a: &AlbumSummary) ->
|
|||||||
hues: a.hues(),
|
hues: a.hues(),
|
||||||
round: false,
|
round: false,
|
||||||
on_press: Message::Navigate(Route::Album(a.id)),
|
on_press: Message::Navigate(Route::Album(a.id)),
|
||||||
|
menu: Some(Target::Album(a.clone())),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -292,6 +294,7 @@ pub fn artist_card<'a>(t: &'static Tokens, covers: &Covers, a: &ArtistSummary) -
|
|||||||
hues: a.hues(),
|
hues: a.hues(),
|
||||||
round: true,
|
round: true,
|
||||||
on_press: Message::Navigate(Route::Artist(a.id)),
|
on_press: Message::Navigate(Route::Artist(a.id)),
|
||||||
|
menu: Some(Target::Artist(a.clone())),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -307,6 +310,7 @@ pub fn playlist_card<'a>(t: &'static Tokens, covers: &Covers, p: &PlaylistSummar
|
|||||||
hues: p.hues(),
|
hues: p.hues(),
|
||||||
round: false,
|
round: false,
|
||||||
on_press: Message::Navigate(Route::Playlist(p.id)),
|
on_press: Message::Navigate(Route::Playlist(p.id)),
|
||||||
|
menu: Some(Target::Playlist(p.clone())),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -325,6 +329,7 @@ pub fn clip_card<'a>(env: Env<'_>, c: &Clip) -> Element<'a, Message> {
|
|||||||
hues: c.hues(),
|
hues: c.hues(),
|
||||||
round: false,
|
round: false,
|
||||||
on_press: Message::OpenClip(c.clone()),
|
on_press: Message::OpenClip(c.clone()),
|
||||||
|
menu: None,
|
||||||
},
|
},
|
||||||
liked,
|
liked,
|
||||||
Message::LikeClip(c.clone(), !liked),
|
Message::LikeClip(c.clone(), !liked),
|
||||||
|
|||||||
@@ -88,18 +88,18 @@ fn not_found_or_retry<'a>(env: Env<'a>, e: &'a Error, what: What, route: Route)
|
|||||||
status(env.t, LoadState::Failed(e), what.retry, Message::Navigate(route))
|
status(env.t, LoadState::Failed(e), what.retry, Message::Navigate(route))
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Head<'a> {
|
pub(crate) struct Head<'a> {
|
||||||
cover: Option<String>,
|
pub cover: Option<String>,
|
||||||
hues: (f32, f32),
|
pub hues: (f32, f32),
|
||||||
round: bool,
|
pub round: bool,
|
||||||
kind: String,
|
pub kind: String,
|
||||||
title: String,
|
pub title: String,
|
||||||
by: Option<Element<'a, Message>>,
|
pub by: Option<Element<'a, Message>>,
|
||||||
meta: String,
|
pub meta: String,
|
||||||
actions: Vec<Element<'a, Message>>,
|
pub actions: Vec<Element<'a, Message>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn head<'a>(env: Env<'a>, h: Head<'a>) -> Element<'a, Message> {
|
pub(crate) fn head<'a>(env: Env<'a>, h: Head<'a>) -> Element<'a, Message> {
|
||||||
let t = env.t;
|
let t = env.t;
|
||||||
let size_px = 200.0;
|
let size_px = 200.0;
|
||||||
let corner = if h.round { size_px / 2.0 } else { theme::radius::COVER };
|
let corner = if h.round { size_px / 2.0 } else { theme::radius::COVER };
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ pub mod browse;
|
|||||||
pub mod collection;
|
pub mod collection;
|
||||||
pub mod detail;
|
pub mod detail;
|
||||||
pub mod search;
|
pub mod search;
|
||||||
|
pub mod server;
|
||||||
pub mod settings;
|
pub mod settings;
|
||||||
pub mod sign_in;
|
pub mod sign_in;
|
||||||
pub mod wave;
|
pub mod wave;
|
||||||
@@ -24,16 +25,17 @@ use crate::widgets::track_list::Env;
|
|||||||
use crate::i18n::{tr, trf};
|
use crate::i18n::{tr, trf};
|
||||||
|
|
||||||
/// Something fetched from the API: not asked for yet, on its way, here, or failed.
|
/// Something fetched from the API: not asked for yet, on its way, here, or failed.
|
||||||
|
/// `E` is the API's error type: Yandex's, or the music server's.
|
||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
pub enum Loadable<T> {
|
pub enum Loadable<T, E = Error> {
|
||||||
#[default]
|
#[default]
|
||||||
NotLoaded,
|
NotLoaded,
|
||||||
Loading,
|
Loading,
|
||||||
Loaded(T),
|
Loaded(T),
|
||||||
Failed(Error),
|
Failed(E),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Loadable<T> {
|
impl<T, E> Loadable<T, E> {
|
||||||
pub fn get(&self) -> Option<&T> {
|
pub fn get(&self) -> Option<&T> {
|
||||||
match self {
|
match self {
|
||||||
Loadable::Loaded(v) => Some(v),
|
Loadable::Loaded(v) => Some(v),
|
||||||
@@ -46,19 +48,21 @@ impl<T> Loadable<T> {
|
|||||||
matches!(self, Loadable::NotLoaded | Loadable::Failed(_))
|
matches!(self, Loadable::NotLoaded | Loadable::Failed(_))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn from_result(result: Result<T, E>) -> Self {
|
||||||
|
match result {
|
||||||
|
Ok(v) => Loadable::Loaded(v),
|
||||||
|
Err(e) => Loadable::Failed(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Loadable<T> {
|
||||||
pub fn state(&self) -> collection::LoadState<'_> {
|
pub fn state(&self) -> collection::LoadState<'_> {
|
||||||
match self {
|
match self {
|
||||||
Loadable::Failed(e) => collection::LoadState::Failed(e),
|
Loadable::Failed(e) => collection::LoadState::Failed(e),
|
||||||
_ => collection::LoadState::Loading,
|
_ => collection::LoadState::Loading,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn from_result(result: Result<T, Error>) -> Self {
|
|
||||||
match result {
|
|
||||||
Ok(v) => Loadable::Loaded(v),
|
|
||||||
Err(e) => Loadable::Failed(e),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Everything a routed screen may need from app state.
|
/// Everything a routed screen may need from app state.
|
||||||
@@ -75,10 +79,12 @@ pub struct Ctx<'a> {
|
|||||||
pub wave: &'a wave::WaveScreen,
|
pub wave: &'a wave::WaveScreen,
|
||||||
pub wave_phase: f32,
|
pub wave_phase: f32,
|
||||||
pub settings: &'a crate::store::Settings,
|
pub settings: &'a crate::store::Settings,
|
||||||
|
pub server: &'a server::ServerScreen,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn view<'a>(ctx: Ctx<'a>) -> Element<'a, Message> {
|
pub fn view<'a>(ctx: Ctx<'a>) -> Element<'a, Message> {
|
||||||
let Ctx { env, route, search, me, library, pages, discover, genre_playlists, player, wave, wave_phase, settings } = ctx;
|
let Ctx { env, route, search, me, library, pages, discover, genre_playlists, player, wave, wave_phase, settings, server } =
|
||||||
|
ctx;
|
||||||
let t = env.t;
|
let t = env.t;
|
||||||
let content: Column<'a, Message> = match route {
|
let content: Column<'a, Message> = match route {
|
||||||
Route::Home => {
|
Route::Home => {
|
||||||
@@ -102,8 +108,12 @@ pub fn view<'a>(ctx: Ctx<'a>) -> Element<'a, Message> {
|
|||||||
Route::Album(_) | Route::Artist(_) | Route::Playlist(_) => {
|
Route::Album(_) | Route::Artist(_) | Route::Playlist(_) => {
|
||||||
column![detail::view(env, route, pages.get(&route).unwrap_or(&Loadable::Loading))]
|
column![detail::view(env, route, pages.get(&route).unwrap_or(&Loadable::Loading))]
|
||||||
}
|
}
|
||||||
|
Route::Server => column![server::view(env, server)],
|
||||||
|
Route::ServerAlbum(_) | Route::ServerArtist(_) | Route::ServerPlaylist(_) => {
|
||||||
|
column![server::page(env, server, route)]
|
||||||
|
}
|
||||||
Route::Podcasts => column![browse::podcasts(env, discover, &library.albums)],
|
Route::Podcasts => column![browse::podcasts(env, discover, &library.albums)],
|
||||||
Route::Settings => column![settings::view(t, settings, account_card(t, me))],
|
Route::Settings => column![settings::view(t, settings, account_card(t, me), server::settings_section(t, server))],
|
||||||
};
|
};
|
||||||
|
|
||||||
content
|
content
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
|||||||
//! Settings: account, streaming quality, appearance, storage.
|
//! Settings: account, streaming quality, appearance, storage.
|
||||||
|
|
||||||
use iced::widget::{Row, button, column, container, row};
|
use iced::widget::{Column, Row, button, column, container, row, space};
|
||||||
use iced::{Alignment, Element, Fill};
|
use iced::{Alignment, Element, Fill};
|
||||||
use crate::app::Message;
|
use crate::app::Message;
|
||||||
use crate::store::{Appearance, Locale, Quality, Settings};
|
use crate::store::{Appearance, Locale, Quality, Settings};
|
||||||
@@ -9,7 +9,12 @@ use crate::ui::theme::{self, Tokens, size};
|
|||||||
use crate::ui::{line, para};
|
use crate::ui::{line, para};
|
||||||
use crate::i18n::{tr, trf};
|
use crate::i18n::{tr, trf};
|
||||||
|
|
||||||
pub fn view<'a>(t: &'static Tokens, settings: &Settings, account: Element<'a, Message>) -> Element<'a, Message> {
|
pub fn view<'a>(
|
||||||
|
t: &'static Tokens,
|
||||||
|
settings: &Settings,
|
||||||
|
account: Element<'a, Message>,
|
||||||
|
server: Element<'a, Message>,
|
||||||
|
) -> Element<'a, Message> {
|
||||||
let quality = Row::with_children(Quality::ALL.map(|q| chip(t, q.label(), q == settings.quality, Message::SetQuality(q))))
|
let quality = Row::with_children(Quality::ALL.map(|q| chip(t, q.label(), q == settings.quality, Message::SetQuality(q))))
|
||||||
.spacing(6);
|
.spacing(6);
|
||||||
let appearance =
|
let appearance =
|
||||||
@@ -23,6 +28,7 @@ pub fn view<'a>(t: &'static Tokens, settings: &Settings, account: Element<'a, Me
|
|||||||
line(tr("Settings"), theme::DISPLAY, size::DISPLAY_S, t.fg),
|
line(tr("Settings"), theme::DISPLAY, size::DISPLAY_S, t.fg),
|
||||||
account,
|
account,
|
||||||
section(t, tr("Streaming quality"), column![quality, para(settings.quality.detail(), size::META, t.muted)].spacing(10).into()),
|
section(t, tr("Streaming quality"), column![quality, para(settings.quality.detail(), size::META, t.muted)].spacing(10).into()),
|
||||||
|
section(t, tr("My server"), server),
|
||||||
section(t, tr("Appearance"), appearance.into()),
|
section(t, tr("Appearance"), appearance.into()),
|
||||||
section(t, tr("Language"), language.into()),
|
section(t, tr("Language"), language.into()),
|
||||||
section(
|
section(
|
||||||
@@ -42,6 +48,7 @@ pub fn view<'a>(t: &'static Tokens, settings: &Settings, account: Element<'a, Me
|
|||||||
.spacing(12)
|
.spacing(12)
|
||||||
.into(),
|
.into(),
|
||||||
),
|
),
|
||||||
|
section(t, tr("Keyboard shortcuts"), shortcuts(t)),
|
||||||
line(trf("Musyx {} · unofficial Yandex Music client", &[&env!("CARGO_PKG_VERSION")]), theme::BODY, size::SMALL, t.muted),
|
line(trf("Musyx {} · unofficial Yandex Music client", &[&env!("CARGO_PKG_VERSION")]), theme::BODY, size::SMALL, t.muted),
|
||||||
]
|
]
|
||||||
.spacing(28)
|
.spacing(28)
|
||||||
@@ -64,3 +71,17 @@ fn chip<'a>(t: &'static Tokens, label: &'static str, on: bool, msg: Message) ->
|
|||||||
.on_press_maybe((!on).then_some(msg))
|
.on_press_maybe((!on).then_some(msg))
|
||||||
.into()
|
.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn shortcuts<'a>(t: &'static Tokens) -> Element<'a, Message> {
|
||||||
|
let rows = crate::shortcuts::help().into_iter().map(|(action, keys)| {
|
||||||
|
let caps = Row::with_children(keys.into_iter().map(|k| {
|
||||||
|
container(line(k, theme::MEDIUM, size::META, t.fg)).padding([2, 8]).style(theme::kbd).into()
|
||||||
|
}))
|
||||||
|
.spacing(6);
|
||||||
|
row![line(action, theme::BODY, size::BODY, t.fg), space::horizontal(), caps]
|
||||||
|
.spacing(12)
|
||||||
|
.align_y(Alignment::Center)
|
||||||
|
.into()
|
||||||
|
});
|
||||||
|
Column::with_children(rows).spacing(10).max_width(560).into()
|
||||||
|
}
|
||||||
@@ -273,8 +273,9 @@ impl SignIn {
|
|||||||
|
|
||||||
let copied = w.copied_at.is_some_and(|at| w.now.duration_since(at) < Duration::from_secs(2));
|
let copied = w.copied_at.is_some_and(|at| w.now.duration_since(at) < Duration::from_secs(2));
|
||||||
let code_box = row![
|
let code_box = row![
|
||||||
container(line(spaced(&w.code.user_code), theme::DISPLAY, 30.0, t.fg))
|
// Taller line so descenders (j, g, y) aren't clipped; padding shrinks to keep the card size.
|
||||||
.padding([14, 18])
|
container(line(spaced(&w.code.user_code), theme::DISPLAY, size::DISPLAY_S, t.fg).line_height(1.5))
|
||||||
|
.padding([11, 18])
|
||||||
.style(theme::card),
|
.style(theme::card),
|
||||||
ghost(t, Icon::Copy, if copied { tr("Copied") } else { tr("Copy code") }, Msg::CopyCode),
|
ghost(t, Icon::Copy, if copied { tr("Copied") } else { tr("Copy code") }, Msg::CopyCode),
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -109,3 +109,45 @@ async fn forget(reason: Error) -> Restored {
|
|||||||
}
|
}
|
||||||
Restored::SignedOut
|
Restored::SignedOut
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The music server's address and sign-in, kept in the keychain next to the
|
||||||
|
/// Yandex credentials (the password is a secret like the token).
|
||||||
|
pub mod server {
|
||||||
|
use subsonic_api::Config;
|
||||||
|
|
||||||
|
use super::blocking;
|
||||||
|
|
||||||
|
const ACCOUNT: &str = "subsonic";
|
||||||
|
|
||||||
|
fn entry() -> Result<keyring::Entry, String> {
|
||||||
|
keyring::Entry::new(super::SERVICE, ACCOUNT).map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn load() -> Result<Option<Config>, String> {
|
||||||
|
blocking(|| {
|
||||||
|
let raw = match entry()?.get_password() {
|
||||||
|
Ok(raw) => raw,
|
||||||
|
Err(keyring::Error::NoEntry) => return Ok(None),
|
||||||
|
Err(e) => return Err(e.to_string()),
|
||||||
|
};
|
||||||
|
Ok(serde_json::from_str(&raw).ok())
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn save(config: Config) -> Result<(), String> {
|
||||||
|
blocking(move || {
|
||||||
|
let json = serde_json::to_string(&config).map_err(|e| e.to_string())?;
|
||||||
|
entry()?.set_password(&json).map_err(|e| e.to_string())
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn clear() -> Result<(), String> {
|
||||||
|
blocking(|| match entry()?.delete_credential() {
|
||||||
|
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
|
||||||
|
Err(e) => Err(e.to_string()),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
//! Keyboard shortcuts. Only keys a focused text field didn't use arrive here, so
|
||||||
|
//! Space typed into search stays a space. Letters and punctuation are read by
|
||||||
|
//! their position as a fallback, so ⌘F still works on a Russian layout.
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use iced::Subscription;
|
||||||
|
use iced::keyboard::key::{Code, Named, Physical};
|
||||||
|
use iced::keyboard::{self, Key, Modifiers};
|
||||||
|
|
||||||
|
use crate::i18n::tr;
|
||||||
|
use crate::route::Route;
|
||||||
|
|
||||||
|
/// One step of the volume keys.
|
||||||
|
pub const VOLUME_STEP: f32 = 0.05;
|
||||||
|
/// How far the seek keys jump.
|
||||||
|
pub const SEEK_STEP: Duration = Duration::from_secs(10);
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum Shortcut {
|
||||||
|
TogglePlay,
|
||||||
|
Next,
|
||||||
|
Previous,
|
||||||
|
SeekForward,
|
||||||
|
SeekBack,
|
||||||
|
VolumeUp,
|
||||||
|
VolumeDown,
|
||||||
|
ToggleLike,
|
||||||
|
FocusSearch,
|
||||||
|
Back,
|
||||||
|
/// Esc: closes the menu, then the search suggestions, then the drawer, then Now Playing.
|
||||||
|
Dismiss,
|
||||||
|
Go(Route),
|
||||||
|
/// Opens or closes Now Playing.
|
||||||
|
NowPlaying,
|
||||||
|
/// Plain arrows and Enter move through an open menu; without one they do nothing.
|
||||||
|
MenuUp,
|
||||||
|
MenuDown,
|
||||||
|
MenuIn,
|
||||||
|
MenuOut,
|
||||||
|
MenuEnter,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn subscription() -> Subscription<Shortcut> {
|
||||||
|
keyboard::listen().filter_map(|event| match event {
|
||||||
|
keyboard::Event::KeyPressed { key, physical_key, modifiers, repeat, .. } => {
|
||||||
|
from_key(&key, physical_key, modifiers, repeat)
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn from_key(key: &Key, physical: Physical, mods: Modifiers, repeat: bool) -> Option<Shortcut> {
|
||||||
|
use Shortcut as S;
|
||||||
|
let cmd = mods.command();
|
||||||
|
// Shortcuts that Alt or the other platform's Ctrl would change into something else.
|
||||||
|
let plain = !mods.alt() && !(mods.control() && mods.logo());
|
||||||
|
|
||||||
|
if let Key::Named(named) = key {
|
||||||
|
let shortcut = match (named, cmd, mods.shift(), mods.alt()) {
|
||||||
|
(Named::Space, false, false, false) if !mods.control() && !mods.logo() => S::TogglePlay,
|
||||||
|
(Named::Escape, false, false, false) => S::Dismiss,
|
||||||
|
(Named::ArrowRight, true, false, false) => S::Next,
|
||||||
|
(Named::ArrowLeft, true, false, false) => S::Previous,
|
||||||
|
(Named::ArrowUp, true, false, false) => S::VolumeUp,
|
||||||
|
(Named::ArrowDown, true, false, false) => S::VolumeDown,
|
||||||
|
(Named::ArrowRight, false, true, false) => S::SeekForward,
|
||||||
|
(Named::ArrowLeft, false, true, false) => S::SeekBack,
|
||||||
|
(Named::ArrowLeft, false, false, true) => S::Back,
|
||||||
|
_ if mods.is_empty() => match named {
|
||||||
|
Named::ArrowUp => S::MenuUp,
|
||||||
|
Named::ArrowDown => S::MenuDown,
|
||||||
|
Named::ArrowRight => S::MenuIn,
|
||||||
|
Named::ArrowLeft => S::MenuOut,
|
||||||
|
Named::Enter => S::MenuEnter,
|
||||||
|
_ => return None,
|
||||||
|
},
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
// Holding a key repeats volume and seek steps; a held Space must not flicker play and pause.
|
||||||
|
let repeats = matches!(shortcut, S::VolumeUp | S::VolumeDown | S::SeekForward | S::SeekBack | S::MenuUp | S::MenuDown);
|
||||||
|
return (!repeat || repeats).then_some(shortcut);
|
||||||
|
}
|
||||||
|
|
||||||
|
if repeat || !plain || mods.shift() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let c = latin(key, physical)?;
|
||||||
|
if !cmd {
|
||||||
|
// "/" by character, or by position where the layout puts something else there.
|
||||||
|
let slash = c == '/' || physical == Physical::Code(Code::Slash);
|
||||||
|
return (slash && !mods.control() && !mods.logo()).then_some(S::FocusSearch);
|
||||||
|
}
|
||||||
|
Some(match c {
|
||||||
|
'f' => S::FocusSearch,
|
||||||
|
'l' => S::ToggleLike,
|
||||||
|
'p' => S::NowPlaying,
|
||||||
|
'[' => S::Back,
|
||||||
|
',' => S::Go(Route::Settings),
|
||||||
|
'1'..='6' => S::Go(Route::NAV[c as usize - '1' as usize]),
|
||||||
|
_ => return None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The character a key stands for on a Latin layout.
|
||||||
|
fn latin(key: &Key, physical: Physical) -> Option<char> {
|
||||||
|
if let Key::Character(s) = key {
|
||||||
|
let mut chars = s.chars();
|
||||||
|
if let (Some(c), None) = (chars.next(), chars.next())
|
||||||
|
&& c.is_ascii()
|
||||||
|
{
|
||||||
|
return Some(c.to_ascii_lowercase());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match physical {
|
||||||
|
Physical::Code(Code::Slash) => Some('/'),
|
||||||
|
Physical::Code(Code::BracketLeft) => Some('['),
|
||||||
|
Physical::Code(Code::Comma) => Some(','),
|
||||||
|
_ => key.to_latin(physical),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The list Settings shows: what each shortcut does and the keys for it.
|
||||||
|
pub fn help() -> Vec<(&'static str, Vec<String>)> {
|
||||||
|
let (cmd, shift, alt) = if cfg!(target_os = "macos") { ("⌘", "⇧", "⌥") } else { ("Ctrl+", "Shift+", "Alt+") };
|
||||||
|
let with = |m: &str, k: &str| format!("{m}{k}");
|
||||||
|
vec![
|
||||||
|
(tr("Play or pause"), vec![tr("Space").to_owned()]),
|
||||||
|
(tr("Next or previous track"), vec![with(cmd, "→"), with(cmd, "←")]),
|
||||||
|
(tr("Skip 10 seconds forward or back"), vec![with(shift, "→"), with(shift, "←")]),
|
||||||
|
(tr("Volume up or down"), vec![with(cmd, "↑"), with(cmd, "↓")]),
|
||||||
|
(tr("Like or unlike the track playing"), vec![with(cmd, "L")]),
|
||||||
|
(tr("Open or close Now Playing"), vec![with(cmd, "P")]),
|
||||||
|
(tr("Search"), vec![with(cmd, "F"), "/".to_owned()]),
|
||||||
|
(tr("Go back"), vec![with(cmd, "["), with(alt, "←")]),
|
||||||
|
(tr("Close a menu or panel"), vec!["Esc".to_owned()]),
|
||||||
|
(tr("Home, My Wave, Search, Collection, My server, Podcasts"), vec![format!("{cmd}1 … {cmd}6")]),
|
||||||
|
(tr("Settings"), vec![with(cmd, ",")]),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use iced::keyboard::key::NativeCode;
|
||||||
|
|
||||||
|
fn press(key: Key, code: Code, mods: Modifiers) -> Option<Shortcut> {
|
||||||
|
from_key(&key, Physical::Code(code), mods, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ch(s: &str) -> Key {
|
||||||
|
Key::Character(s.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn space_toggles_only_without_modifiers() {
|
||||||
|
assert_eq!(press(Key::Named(Named::Space), Code::Space, Modifiers::empty()), Some(Shortcut::TogglePlay));
|
||||||
|
assert_eq!(press(Key::Named(Named::Space), Code::Space, Modifiers::COMMAND), None);
|
||||||
|
assert_eq!(press(Key::Named(Named::Space), Code::Space, Modifiers::SHIFT), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn held_space_does_not_repeat_but_volume_does() {
|
||||||
|
let space = from_key(&Key::Named(Named::Space), Physical::Code(Code::Space), Modifiers::empty(), true);
|
||||||
|
assert_eq!(space, None);
|
||||||
|
let up = from_key(&Key::Named(Named::ArrowUp), Physical::Code(Code::ArrowUp), Modifiers::COMMAND, true);
|
||||||
|
assert_eq!(up, Some(Shortcut::VolumeUp));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn transport_and_seek_arrows() {
|
||||||
|
let arrow = |n, code, m| press(Key::Named(n), code, m);
|
||||||
|
assert_eq!(arrow(Named::ArrowRight, Code::ArrowRight, Modifiers::COMMAND), Some(Shortcut::Next));
|
||||||
|
assert_eq!(arrow(Named::ArrowLeft, Code::ArrowLeft, Modifiers::COMMAND), Some(Shortcut::Previous));
|
||||||
|
assert_eq!(arrow(Named::ArrowRight, Code::ArrowRight, Modifiers::SHIFT), Some(Shortcut::SeekForward));
|
||||||
|
assert_eq!(arrow(Named::ArrowLeft, Code::ArrowLeft, Modifiers::ALT), Some(Shortcut::Back));
|
||||||
|
assert_eq!(arrow(Named::ArrowRight, Code::ArrowRight, Modifiers::empty()), Some(Shortcut::MenuIn));
|
||||||
|
assert_eq!(arrow(Named::ArrowDown, Code::ArrowDown, Modifiers::CTRL), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn letters_follow_the_key_position_on_a_russian_layout() {
|
||||||
|
// ⌘ plus the key that types "а" in the Russian layout is ⌘F.
|
||||||
|
assert_eq!(press(ch("а"), Code::KeyF, Modifiers::COMMAND), Some(Shortcut::FocusSearch));
|
||||||
|
assert_eq!(press(ch("д"), Code::KeyL, Modifiers::COMMAND), Some(Shortcut::ToggleLike));
|
||||||
|
assert_eq!(press(ch("з"), Code::KeyP, Modifiers::COMMAND), Some(Shortcut::NowPlaying));
|
||||||
|
assert_eq!(press(ch("х"), Code::BracketLeft, Modifiers::COMMAND), Some(Shortcut::Back));
|
||||||
|
assert_eq!(press(ch("."), Code::Slash, Modifiers::empty()), Some(Shortcut::FocusSearch));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn letters_follow_the_character_on_latin_layouts() {
|
||||||
|
// On AZERTY the key in QWERTY's F position still types "f".
|
||||||
|
assert_eq!(press(ch("f"), Code::KeyF, Modifiers::COMMAND), Some(Shortcut::FocusSearch));
|
||||||
|
assert_eq!(press(ch("l"), Code::KeyO, Modifiers::COMMAND), Some(Shortcut::ToggleLike));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn number_keys_open_the_sidebar_sections() {
|
||||||
|
assert_eq!(press(ch("1"), Code::Digit1, Modifiers::COMMAND), Some(Shortcut::Go(Route::Home)));
|
||||||
|
assert_eq!(press(ch("5"), Code::Digit5, Modifiers::COMMAND), Some(Shortcut::Go(Route::Server)));
|
||||||
|
assert_eq!(press(ch("6"), Code::Digit6, Modifiers::COMMAND), Some(Shortcut::Go(Route::Podcasts)));
|
||||||
|
assert_eq!(press(ch("7"), Code::Digit7, Modifiers::COMMAND), None);
|
||||||
|
assert_eq!(press(ch(","), Code::Comma, Modifiers::COMMAND), Some(Shortcut::Go(Route::Settings)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bare_letters_and_shifted_combinations_do_nothing() {
|
||||||
|
assert_eq!(press(ch("f"), Code::KeyF, Modifiers::empty()), None);
|
||||||
|
assert_eq!(press(ch("l"), Code::KeyL, Modifiers::COMMAND | Modifiers::SHIFT), None);
|
||||||
|
assert_eq!(press(ch("l"), Code::KeyL, Modifiers::COMMAND | Modifiers::ALT), None);
|
||||||
|
let unknown = from_key(&ch("ж"), Physical::Unidentified(NativeCode::Unidentified), Modifiers::COMMAND, false);
|
||||||
|
assert_eq!(unknown, None);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,12 @@
|
|||||||
//! MUSYX_SNAPSHOT=home.png MUSYX_SNAPSHOT_ROUTE=wave MUSYX_SNAPSHOT_DRAWER=queue \
|
//! MUSYX_SNAPSHOT=home.png MUSYX_SNAPSHOT_ROUTE=wave MUSYX_SNAPSHOT_DRAWER=queue \
|
||||||
//! MUSYX_SNAPSHOT_THEME=light MUSYX_SNAPSHOT_LANG=ru cargo run -p musyx --features snapshot
|
//! MUSYX_SNAPSHOT_THEME=light MUSYX_SNAPSHOT_LANG=ru cargo run -p musyx --features snapshot
|
||||||
//! ```
|
//! ```
|
||||||
|
//!
|
||||||
|
//! `MUSYX_SNAPSHOT_MENU` opens a track menu: `row` (right-click on a row), `sub`
|
||||||
|
//! (with the playlist list), `edge` (near the bottom-right corner) or `more`
|
||||||
|
//! (under a row's "…"). `MUSYX_SNAPSHOT_DRAG=1` with `ROUTE=playlist` shows a
|
||||||
|
//! row of the sample own playlist mid-drag. `MUSYX_SNAPSHOT_ROUTE=nowplaying` opens Now Playing
|
||||||
|
//! on the first sample track.
|
||||||
//! iced's own `window::screenshot` is used, so it needs no screen-recording permission.
|
//! iced's own `window::screenshot` is used, so it needs no screen-recording permission.
|
||||||
|
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
@@ -34,22 +40,31 @@ pub struct Config {
|
|||||||
pub lang: Option<Lang>,
|
pub lang: Option<Lang>,
|
||||||
/// `MUSYX_SNAPSHOT_DELAY` in ms before capturing (default 1500; live runs need longer).
|
/// `MUSYX_SNAPSHOT_DELAY` in ms before capturing (default 1500; live runs need longer).
|
||||||
pub delay: Duration,
|
pub delay: Duration,
|
||||||
|
pub menu: Option<String>,
|
||||||
|
pub drag: bool,
|
||||||
|
pub now_playing: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The sample own playlist for `MUSYX_SNAPSHOT_ROUTE=playlist`.
|
||||||
|
pub const OWN_PLAYLIST: ym_api::PlaylistId = ym_api::PlaylistId { owner: 1, kind: 3 };
|
||||||
|
|
||||||
impl Config {
|
impl Config {
|
||||||
pub fn from_env() -> Option<Self> {
|
pub fn from_env() -> Option<Self> {
|
||||||
let out = PathBuf::from(std::env::var_os("MUSYX_SNAPSHOT")?);
|
let out = PathBuf::from(std::env::var_os("MUSYX_SNAPSHOT")?);
|
||||||
let var = |k: &str| std::env::var(k).ok().map(|v| v.to_ascii_lowercase());
|
let var = |k: &str| std::env::var(k).ok().map(|v| v.to_ascii_lowercase());
|
||||||
let signed_out = var("MUSYX_SNAPSHOT_ROUTE").as_deref() == Some("signin");
|
let signed_out = var("MUSYX_SNAPSHOT_ROUTE").as_deref() == Some("signin");
|
||||||
|
let now_playing = var("MUSYX_SNAPSHOT_ROUTE").as_deref() == Some("nowplaying");
|
||||||
let route = var("MUSYX_SNAPSHOT_ROUTE").and_then(|r| {
|
let route = var("MUSYX_SNAPSHOT_ROUTE").and_then(|r| {
|
||||||
Some(match r.as_str() {
|
Some(match r.as_str() {
|
||||||
"home" => Route::Home,
|
"home" => Route::Home,
|
||||||
"wave" => Route::Wave,
|
"wave" => Route::Wave,
|
||||||
"search" => Route::Search,
|
"search" => Route::Search,
|
||||||
"collection" => Route::Collection,
|
"collection" => Route::Collection,
|
||||||
|
"server" => Route::Server,
|
||||||
"podcasts" => Route::Podcasts,
|
"podcasts" => Route::Podcasts,
|
||||||
"settings" => Route::Settings,
|
"settings" => Route::Settings,
|
||||||
"album" => Route::Album(1),
|
"album" => Route::Album(1),
|
||||||
|
"playlist" => Route::Playlist(OWN_PLAYLIST),
|
||||||
"chart" => Route::Chart,
|
"chart" => Route::Chart,
|
||||||
// `artist:41075`, for live runs.
|
// `artist:41075`, for live runs.
|
||||||
other => Route::Artist(other.strip_prefix("artist:")?.parse().ok()?),
|
other => Route::Artist(other.strip_prefix("artist:")?.parse().ok()?),
|
||||||
@@ -70,7 +85,9 @@ impl Config {
|
|||||||
let delay = var("MUSYX_SNAPSHOT_DELAY")
|
let delay = var("MUSYX_SNAPSHOT_DELAY")
|
||||||
.and_then(|d| d.parse().ok())
|
.and_then(|d| d.parse().ok())
|
||||||
.map_or(Duration::from_millis(if live { 8000 } else { 1500 }), Duration::from_millis);
|
.map_or(Duration::from_millis(if live { 8000 } else { 1500 }), Duration::from_millis);
|
||||||
Some(Self { out, signed_out, route, drawer, mode, lang, live, delay })
|
let menu = var("MUSYX_SNAPSHOT_MENU");
|
||||||
|
let drag = var("MUSYX_SNAPSHOT_DRAG").is_some_and(|v| v == "1");
|
||||||
|
Some(Self { out, signed_out, route, drawer, mode, lang, live, delay, menu, drag, now_playing })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A made-up account so the shell renders without a network or keychain.
|
/// A made-up account so the shell renders without a network or keychain.
|
||||||
@@ -134,6 +151,43 @@ impl Config {
|
|||||||
crate::screens::detail::Page::Album { info, tracks }
|
crate::screens::detail::Page::Album { info, tracks }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The sample liked tracks as one of the user's own playlists.
|
||||||
|
pub fn sample_playlist(&self) -> crate::screens::detail::Page {
|
||||||
|
let info = ym_api::PlaylistPage {
|
||||||
|
playlist: ym_api::PlaylistSummary::for_tests(OWN_PLAYLIST, "Дорога"),
|
||||||
|
description: None,
|
||||||
|
tracks: Vec::new(),
|
||||||
|
};
|
||||||
|
crate::screens::detail::Page::Playlist { info, tracks: self.sample_liked().into() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The menu `MUSYX_SNAPSHOT_MENU` asks for, on the second sample track.
|
||||||
|
pub fn menu(&self) -> Option<crate::widgets::menu::Menu> {
|
||||||
|
use crate::widgets::menu::{Anchor, Menu, Source, Target};
|
||||||
|
use iced::{Point, Rectangle, Size};
|
||||||
|
let track = self.sample_liked().swap_remove(1);
|
||||||
|
let playlist = (self.route == Some(Route::Playlist(OWN_PLAYLIST))).then_some((OWN_PLAYLIST, 1, 6));
|
||||||
|
let target = Target::Track { track, from: Source::List { playlist } };
|
||||||
|
let anchor = match self.menu.as_deref()? {
|
||||||
|
"edge" => Anchor::Point(Point::new(1180.0, 640.0)),
|
||||||
|
"more" => Anchor::Below(Rectangle::new(Point::new(1212.0, 289.0), Size::new(34.0, 34.0))),
|
||||||
|
_ => Anchor::Point(Point::new(560.0, 300.0)),
|
||||||
|
};
|
||||||
|
let mut menu = Menu::new(target, anchor);
|
||||||
|
menu.highlight = Some(1);
|
||||||
|
if self.menu.as_deref() == Some("sub") {
|
||||||
|
menu.highlight = Some(4);
|
||||||
|
menu.sub = Some(Some(0));
|
||||||
|
}
|
||||||
|
Some(menu)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The second sample track dragged two rows down.
|
||||||
|
pub fn drag(&self) -> Option<crate::widgets::track_list::Drag> {
|
||||||
|
let track = self.sample_liked().swap_remove(1);
|
||||||
|
self.drag.then_some(crate::widgets::track_list::Drag { playlist: OWN_PLAYLIST, track, from: 1, to: 3 })
|
||||||
|
}
|
||||||
|
|
||||||
/// Waits for fonts and the first frames, captures the window, writes the PNG, exits.
|
/// Waits for fonts and the first frames, captures the window, writes the PNG, exits.
|
||||||
pub fn capture<M: Send + 'static>(self) -> Task<M> {
|
pub fn capture<M: Send + 'static>(self) -> Task<M> {
|
||||||
Task::future(tokio::time::sleep(self.delay))
|
Task::future(tokio::time::sleep(self.delay))
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ icons! {
|
|||||||
Wave => "audio-lines",
|
Wave => "audio-lines",
|
||||||
Search => "search",
|
Search => "search",
|
||||||
Library => "library",
|
Library => "library",
|
||||||
|
Server => "server",
|
||||||
Podcast => "podcast",
|
Podcast => "podcast",
|
||||||
Plus => "plus",
|
Plus => "plus",
|
||||||
LogOut => "log-out",
|
LogOut => "log-out",
|
||||||
@@ -65,6 +66,11 @@ icons! {
|
|||||||
Clock => "clock-3",
|
Clock => "clock-3",
|
||||||
Tune => "sliders-horizontal",
|
Tune => "sliders-horizontal",
|
||||||
Settings => "settings",
|
Settings => "settings",
|
||||||
|
MoveTop => "arrow-up-to-line",
|
||||||
|
MoveBottom => "arrow-down-to-line",
|
||||||
|
Artist => "user",
|
||||||
|
Expand => "maximize-2",
|
||||||
|
Collapse => "chevron-down",
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Icon {
|
impl Icon {
|
||||||
|
|||||||
@@ -188,6 +188,17 @@ pub fn badge(theme: &Theme) -> container::Style {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A key cap in the shortcut list.
|
||||||
|
pub fn kbd(theme: &Theme) -> container::Style {
|
||||||
|
let t = tokens(theme);
|
||||||
|
container::Style {
|
||||||
|
background: Some(t.raised.into()),
|
||||||
|
text_color: Some(t.fg),
|
||||||
|
border: Border { radius: radius::SMALL_COVER.into(), ..Border::default() },
|
||||||
|
..container::Style::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn accent_dot(theme: &Theme) -> container::Style {
|
pub fn accent_dot(theme: &Theme) -> container::Style {
|
||||||
container::Style {
|
container::Style {
|
||||||
background: Some(tokens(theme).accent.into()),
|
background: Some(tokens(theme).accent.into()),
|
||||||
@@ -211,6 +222,29 @@ pub fn avatar(theme: &Theme) -> container::Style {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Washes the Now Playing backdrop with the ground, more towards the transport.
|
||||||
|
pub fn backdrop_wash(theme: &Theme) -> container::Style {
|
||||||
|
let t = tokens(theme);
|
||||||
|
container::Style {
|
||||||
|
background: Some(Background::Gradient(
|
||||||
|
iced::gradient::Linear::new(std::f32::consts::PI)
|
||||||
|
.add_stop(0.0, t.bg.scale_alpha(0.55))
|
||||||
|
.add_stop(1.0, t.bg.scale_alpha(0.92))
|
||||||
|
.into(),
|
||||||
|
)),
|
||||||
|
..container::Style::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The large cover on Now Playing, which floats over its own blurred copy.
|
||||||
|
pub fn stage_cover(_: &Theme) -> container::Style {
|
||||||
|
container::Style {
|
||||||
|
border: Border { radius: radius::HERO.into(), ..Border::default() },
|
||||||
|
shadow: Shadow { color: Color::BLACK.scale_alpha(0.35), offset: Vector::new(0.0, 18.0), blur_radius: 50.0 },
|
||||||
|
..container::Style::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Placeholder art for an item without a cover yet: two hues on a diagonal.
|
/// Placeholder art for an item without a cover yet: two hues on a diagonal.
|
||||||
pub fn cover(h1: f32, h2: f32, corner: f32) -> impl Fn(&Theme) -> container::Style {
|
pub fn cover(h1: f32, h2: f32, corner: f32) -> impl Fn(&Theme) -> container::Style {
|
||||||
move |_| container::Style {
|
move |_| container::Style {
|
||||||
@@ -391,24 +425,29 @@ pub fn search_field(theme: &Theme, status: text_input::Status) -> text_input::St
|
|||||||
|
|
||||||
/// Thin seek bar: amber fill, knob only while hovered or dragged.
|
/// Thin seek bar: amber fill, knob only while hovered or dragged.
|
||||||
pub fn seek_bar(theme: &Theme, status: slider::Status) -> slider::Style {
|
pub fn seek_bar(theme: &Theme, status: slider::Status) -> slider::Style {
|
||||||
thin_slider(theme, status, tokens(theme).accent)
|
thin_slider(theme, status, tokens(theme).accent, 4.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The wider seek bar on Now Playing.
|
||||||
|
pub fn stage_seek_bar(theme: &Theme, status: slider::Status) -> slider::Style {
|
||||||
|
thin_slider(theme, status, tokens(theme).accent, 6.0)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn volume_bar(theme: &Theme, status: slider::Status) -> slider::Style {
|
pub fn volume_bar(theme: &Theme, status: slider::Status) -> slider::Style {
|
||||||
thin_slider(theme, status, tokens(theme).fg)
|
thin_slider(theme, status, tokens(theme).fg, 4.0)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn thin_slider(theme: &Theme, status: slider::Status, fill: Color) -> slider::Style {
|
fn thin_slider(theme: &Theme, status: slider::Status, fill: Color, width: f32) -> slider::Style {
|
||||||
let t = tokens(theme);
|
let t = tokens(theme);
|
||||||
let engaged = matches!(status, slider::Status::Hovered | slider::Status::Dragged);
|
let engaged = matches!(status, slider::Status::Hovered | slider::Status::Dragged);
|
||||||
slider::Style {
|
slider::Style {
|
||||||
rail: slider::Rail {
|
rail: slider::Rail {
|
||||||
backgrounds: (fill.into(), t.raised.into()),
|
backgrounds: (fill.into(), t.raised.into()),
|
||||||
width: 4.0,
|
width,
|
||||||
border: Border { radius: 2.0.into(), ..Border::default() },
|
border: Border { radius: (width / 2.0).into(), ..Border::default() },
|
||||||
},
|
},
|
||||||
handle: slider::Handle {
|
handle: slider::Handle {
|
||||||
shape: slider::HandleShape::Circle { radius: if engaged { 6.0 } else { 0.0 } },
|
shape: slider::HandleShape::Circle { radius: if engaged { width + 2.0 } else { 0.0 } },
|
||||||
background: t.fg.into(),
|
background: t.fg.into(),
|
||||||
border_width: 0.0,
|
border_width: 0.0,
|
||||||
border_color: Color::TRANSPARENT,
|
border_color: Color::TRANSPARENT,
|
||||||
|
|||||||
@@ -0,0 +1,171 @@
|
|||||||
|
//! Reports where a menu should open: the pointer on a right-click, or the bounds
|
||||||
|
//! of the wrapped control on a left-click, both in window coordinates.
|
||||||
|
//!
|
||||||
|
//! Inside a scrollable a widget only sees content coordinates. iced hands every
|
||||||
|
//! widget its offset from the window when it asks for overlays, which it does
|
||||||
|
//! before each event, so the offset is kept here and added back.
|
||||||
|
|
||||||
|
use iced::advanced::widget::{Operation, Tree, tree};
|
||||||
|
use iced::advanced::{Clipboard, Layout, Shell, Widget, layout, mouse, overlay, renderer};
|
||||||
|
use iced::{Element, Event, Length, Point, Rectangle, Renderer, Size, Theme, Vector};
|
||||||
|
|
||||||
|
pub struct Anchor<'a, Message> {
|
||||||
|
content: Element<'a, Message>,
|
||||||
|
on_right_press: Option<Box<dyn Fn(Point) -> Message + 'a>>,
|
||||||
|
on_press: Option<Box<dyn Fn(Rectangle) -> Message + 'a>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn anchor<'a, Message>(content: impl Into<Element<'a, Message>>) -> Anchor<'a, Message> {
|
||||||
|
Anchor { content: content.into(), on_right_press: None, on_press: None }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, Message> Anchor<'a, Message> {
|
||||||
|
/// A right-click anywhere on the content, with the pointer's position.
|
||||||
|
pub fn on_right_press(mut self, f: impl Fn(Point) -> Message + 'a) -> Self {
|
||||||
|
self.on_right_press = Some(Box::new(f));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A left-click on the content, with its bounds. The content doesn't see the click.
|
||||||
|
pub fn on_press(mut self, f: impl Fn(Rectangle) -> Message + 'a) -> Self {
|
||||||
|
self.on_press = Some(Box::new(f));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct State {
|
||||||
|
/// Content coordinates plus this give window coordinates.
|
||||||
|
offset: Vector,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<Message> Widget<Message, Theme, Renderer> for Anchor<'_, Message> {
|
||||||
|
fn tag(&self) -> tree::Tag {
|
||||||
|
tree::Tag::of::<State>()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn state(&self) -> tree::State {
|
||||||
|
tree::State::new(State::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn children(&self) -> Vec<Tree> {
|
||||||
|
vec![Tree::new(&self.content)]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn diff(&self, tree: &mut Tree) {
|
||||||
|
tree.diff_children(std::slice::from_ref(&self.content));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn size(&self) -> Size<Length> {
|
||||||
|
self.content.as_widget().size()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn layout(&mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits) -> layout::Node {
|
||||||
|
self.content.as_widget_mut().layout(&mut tree.children[0], renderer, limits)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn operate(&mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn Operation) {
|
||||||
|
self.content.as_widget_mut().operate(&mut tree.children[0], layout, renderer, operation);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update(
|
||||||
|
&mut self,
|
||||||
|
tree: &mut Tree,
|
||||||
|
event: &Event,
|
||||||
|
layout: Layout<'_>,
|
||||||
|
cursor: mouse::Cursor,
|
||||||
|
renderer: &Renderer,
|
||||||
|
clipboard: &mut dyn Clipboard,
|
||||||
|
shell: &mut Shell<'_, Message>,
|
||||||
|
viewport: &Rectangle,
|
||||||
|
) {
|
||||||
|
let offset = tree.state.downcast_ref::<State>().offset;
|
||||||
|
let bounds = layout.bounds();
|
||||||
|
if let (Some(f), Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))) = (&self.on_press, event)
|
||||||
|
&& cursor.is_over(bounds)
|
||||||
|
{
|
||||||
|
shell.publish(f(bounds + offset));
|
||||||
|
shell.capture_event();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.content
|
||||||
|
.as_widget_mut()
|
||||||
|
.update(&mut tree.children[0], event, layout, cursor, renderer, clipboard, shell, viewport);
|
||||||
|
if shell.is_event_captured() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let (Some(f), Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Right))) = (&self.on_right_press, event)
|
||||||
|
&& let Some(at) = cursor.position_over(bounds)
|
||||||
|
{
|
||||||
|
shell.publish(f(at + offset));
|
||||||
|
shell.capture_event();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mouse_interaction(
|
||||||
|
&self,
|
||||||
|
tree: &Tree,
|
||||||
|
layout: Layout<'_>,
|
||||||
|
cursor: mouse::Cursor,
|
||||||
|
viewport: &Rectangle,
|
||||||
|
renderer: &Renderer,
|
||||||
|
) -> mouse::Interaction {
|
||||||
|
self.content.as_widget().mouse_interaction(&tree.children[0], layout, cursor, viewport, renderer)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw(
|
||||||
|
&self,
|
||||||
|
tree: &Tree,
|
||||||
|
renderer: &mut Renderer,
|
||||||
|
theme: &Theme,
|
||||||
|
style: &renderer::Style,
|
||||||
|
layout: Layout<'_>,
|
||||||
|
cursor: mouse::Cursor,
|
||||||
|
viewport: &Rectangle,
|
||||||
|
) {
|
||||||
|
self.content.as_widget().draw(&tree.children[0], renderer, theme, style, layout, cursor, viewport);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn overlay<'b>(
|
||||||
|
&'b mut self,
|
||||||
|
tree: &'b mut Tree,
|
||||||
|
layout: Layout<'b>,
|
||||||
|
renderer: &Renderer,
|
||||||
|
viewport: &Rectangle,
|
||||||
|
translation: Vector,
|
||||||
|
) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
|
||||||
|
tree.state.downcast_mut::<State>().offset = translation;
|
||||||
|
self.content.as_widget_mut().overlay(&mut tree.children[0], layout, renderer, viewport, translation)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, Message: 'a> From<Anchor<'a, Message>> for Element<'a, Message> {
|
||||||
|
fn from(anchor: Anchor<'a, Message>) -> Self {
|
||||||
|
Element::new(anchor)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::anchor;
|
||||||
|
use iced::mouse::{Button, Event as Mouse, ScrollDelta};
|
||||||
|
use iced::widget::{column, container, scrollable, space, text};
|
||||||
|
use iced::{Element, Event, Fill, Point, Size};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_right_click_inside_a_scrolled_list_reports_window_coordinates() {
|
||||||
|
let target = anchor(container(text("target")).width(Fill).height(60)).on_right_press(|at| at);
|
||||||
|
let page: Element<'_, Point> = scrollable(column![space().height(500), target, space().height(500)]).into();
|
||||||
|
let mut ui = iced_test::Simulator::with_size(Default::default(), Size::new(400.0, 300.0), page);
|
||||||
|
|
||||||
|
ui.point_at(Point::new(100.0, 150.0));
|
||||||
|
let _ = ui.simulate([Event::Mouse(Mouse::WheelScrolled { delta: ScrollDelta::Pixels { x: 0.0, y: -400.0 } })]);
|
||||||
|
// "target" sits at 500..560 in the content; scrolled by 400 it shows at 100..160.
|
||||||
|
ui.point_at(Point::new(100.0, 130.0));
|
||||||
|
let _ = ui.simulate([Event::Mouse(Mouse::ButtonPressed(Button::Right))]);
|
||||||
|
let messages: Vec<Point> = ui.into_messages().collect();
|
||||||
|
assert_eq!(messages, [Point::new(100.0, 130.0)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,6 +8,8 @@ use crate::covers::{self, Covers};
|
|||||||
use crate::ui::icons::{Icon, icon};
|
use crate::ui::icons::{Icon, icon};
|
||||||
use crate::ui::line;
|
use crate::ui::line;
|
||||||
use crate::ui::theme::{self, Tokens, radius, size};
|
use crate::ui::theme::{self, Tokens, radius, size};
|
||||||
|
use crate::widgets::anchor::anchor;
|
||||||
|
use crate::widgets::menu::{Anchor, Menu, Target};
|
||||||
|
|
||||||
/// Card width; covers are square at this size.
|
/// Card width; covers are square at this size.
|
||||||
pub const WIDTH: f32 = 168.0;
|
pub const WIDTH: f32 = 168.0;
|
||||||
@@ -20,6 +22,8 @@ pub struct Card {
|
|||||||
/// Artists get a round cover.
|
/// Artists get a round cover.
|
||||||
pub round: bool,
|
pub round: bool,
|
||||||
pub on_press: Message,
|
pub on_press: Message,
|
||||||
|
/// What a right-click's menu is for; clips have none.
|
||||||
|
pub menu: Option<Target>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn view<'a>(t: &'static Tokens, covers: &Covers, card: Card) -> Element<'a, Message> {
|
pub fn view<'a>(t: &'static Tokens, covers: &Covers, card: Card) -> Element<'a, Message> {
|
||||||
@@ -47,7 +51,7 @@ fn build<'a>(t: &'static Tokens, covers: &Covers, card: Card, action: Option<Ele
|
|||||||
.spacing(2)
|
.spacing(2)
|
||||||
.width(Fill)
|
.width(Fill)
|
||||||
.clip(true);
|
.clip(true);
|
||||||
button(
|
let button = button(
|
||||||
column![
|
column![
|
||||||
covers::view(covers, card.cover, card.hues, WIDTH, corner),
|
covers::view(covers, card.cover, card.hues, WIDTH, corner),
|
||||||
row![text].push(action).spacing(4).align_y(Alignment::Center).width(WIDTH),
|
row![text].push(action).spacing(4).align_y(Alignment::Center).width(WIDTH),
|
||||||
@@ -56,8 +60,13 @@ fn build<'a>(t: &'static Tokens, covers: &Covers, card: Card, action: Option<Ele
|
|||||||
)
|
)
|
||||||
.padding(Padding::from(6))
|
.padding(Padding::from(6))
|
||||||
.style(theme::nav_item(false))
|
.style(theme::nav_item(false))
|
||||||
.on_press(card.on_press)
|
.on_press(card.on_press);
|
||||||
.into()
|
match card.menu {
|
||||||
|
Some(target) => anchor(button)
|
||||||
|
.on_right_press(move |at| Message::OpenMenu(Box::new(Menu::new(target.clone(), Anchor::Point(at)))))
|
||||||
|
.into(),
|
||||||
|
None => button.into(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Cards in rows that wrap to the available width.
|
/// Cards in rows that wrap to the available width.
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use std::sync::Arc;
|
|||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use iced::widget::{Column, button, column, container, row, scrollable, space};
|
use iced::widget::{Column, button, column, container, row, scrollable, space};
|
||||||
use ym_api::{Lyrics, Track};
|
use ym_api::{Lyrics, LyricsSource, Track};
|
||||||
use iced::{Alignment, Element, Fill, Padding};
|
use iced::{Alignment, Element, Fill, Padding};
|
||||||
|
|
||||||
use crate::app::Message;
|
use crate::app::Message;
|
||||||
@@ -13,6 +13,8 @@ use crate::player::{Msg, Player, Queue};
|
|||||||
use crate::screens::Loadable;
|
use crate::screens::Loadable;
|
||||||
use crate::ui::icons::{Icon, icon};
|
use crate::ui::icons::{Icon, icon};
|
||||||
use crate::ui::theme::{self, Tokens, radius, shell, size};
|
use crate::ui::theme::{self, Tokens, radius, shell, size};
|
||||||
|
use crate::widgets::anchor::anchor;
|
||||||
|
use crate::widgets::menu::{Anchor, Menu, Source, Target};
|
||||||
use crate::widgets::player_bar::clock;
|
use crate::widgets::player_bar::clock;
|
||||||
use crate::ui::{line, para};
|
use crate::ui::{line, para};
|
||||||
use crate::i18n::{tr, trf};
|
use crate::i18n::{tr, trf};
|
||||||
@@ -67,7 +69,7 @@ pub fn view<'a>(
|
|||||||
(Panel::Lyrics, None) => note(t, tr("Play a track to see its lyrics.")),
|
(Panel::Lyrics, None) => note(t, tr("Play a track to see its lyrics.")),
|
||||||
(Panel::Lyrics, Some(_)) => match lyrics {
|
(Panel::Lyrics, Some(_)) => match lyrics {
|
||||||
Some(Loadable::Loaded(Some(l))) => lyrics_view(t, l, player.position()),
|
Some(Loadable::Loaded(Some(l))) => lyrics_view(t, l, player.position()),
|
||||||
Some(Loadable::Loaded(None)) => note(t, tr("Yandex Music has no lyrics for this track.")),
|
Some(Loadable::Loaded(None)) => note(t, tr("No lyrics for this track.")),
|
||||||
Some(Loadable::Failed(_)) => column![
|
Some(Loadable::Failed(_)) => column![
|
||||||
note(t, tr("Couldn't load the lyrics. Check your connection and try again.")),
|
note(t, tr("Couldn't load the lyrics. Check your connection and try again.")),
|
||||||
container(
|
container(
|
||||||
@@ -121,10 +123,14 @@ fn lyrics_view<'a>(t: &'static Tokens, l: &'a Lyrics, position: Duration) -> Ele
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
let mut list = Column::with_children(lines).spacing(2);
|
let mut list = Column::with_children(lines).spacing(2);
|
||||||
if !l.writers.is_empty() {
|
let credit = match l.source {
|
||||||
|
LyricsSource::Lrclib => Some(tr("Lyrics from LRCLIB").to_owned()),
|
||||||
|
LyricsSource::Yandex if !l.writers.is_empty() => Some(trf("Written by {}", &[&l.writers.join(", ")])),
|
||||||
|
LyricsSource::Yandex => None,
|
||||||
|
};
|
||||||
|
if let Some(credit) = credit {
|
||||||
list = list.push(
|
list = list.push(
|
||||||
container(para(trf("Written by {}", &[&l.writers.join(", ")]), size::SMALL, t.muted))
|
container(para(credit, size::SMALL, t.muted)).padding(iced::Padding::default().top(18).left(8).right(8)),
|
||||||
.padding(iced::Padding::default().top(18).left(8).right(8)),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
scrollable(list.padding(Padding::default().left(10).right(10).bottom(18)))
|
scrollable(list.padding(Padding::default().left(10).right(10).bottom(18)))
|
||||||
@@ -141,8 +147,9 @@ fn queue_list<'a>(t: &'static Tokens, queue: &'a Queue<Track>, covers: &Covers)
|
|||||||
let heading = |s: String| {
|
let heading = |s: String| {
|
||||||
container(line(s, theme::MEDIUM, size::SMALL, t.muted)).padding(Padding::default().top(14).bottom(8).left(8))
|
container(line(s, theme::MEDIUM, size::SMALL, t.muted)).padding(Padding::default().top(14).bottom(8).left(8))
|
||||||
};
|
};
|
||||||
let item = |track: &Track, now: bool, msg: Option<Message>| {
|
let item = |track: &Track, now: bool, msg: Option<Message>, from: Source| {
|
||||||
button(
|
let target = Target::Track { track: track.clone(), from };
|
||||||
|
let row = button(
|
||||||
row![
|
row![
|
||||||
covers::view(covers, track.cover_url(covers::SMALL), track.hues(), 40.0, radius::SMALL_COVER),
|
covers::view(covers, track.cover_url(covers::SMALL), track.hues(), 40.0, radius::SMALL_COVER),
|
||||||
column![
|
column![
|
||||||
@@ -160,18 +167,19 @@ fn queue_list<'a>(t: &'static Tokens, queue: &'a Queue<Track>, covers: &Covers)
|
|||||||
.width(Fill)
|
.width(Fill)
|
||||||
.padding([6, 8])
|
.padding([6, 8])
|
||||||
.style(theme::nav_item(false))
|
.style(theme::nav_item(false))
|
||||||
.on_press_maybe(msg)
|
.on_press_maybe(msg);
|
||||||
|
anchor(row).on_right_press(move |at| Message::OpenMenu(Box::new(Menu::new(target.clone(), Anchor::Point(at)))))
|
||||||
};
|
};
|
||||||
|
|
||||||
let remaining = queue.upcoming().count();
|
let remaining = queue.upcoming().count();
|
||||||
let mut list = column![heading(tr("Now playing").into()), item(queue.current(), true, None)];
|
let mut list = column![heading(tr("Now playing").into()), item(queue.current(), true, None, Source::PlayerBar)];
|
||||||
list = list.push(heading(if remaining == 0 {
|
list = list.push(heading(if remaining == 0 {
|
||||||
tr("Nothing after this").into()
|
tr("Nothing after this").into()
|
||||||
} else {
|
} else {
|
||||||
trf("Next up · {}", &[&remaining])
|
trf("Next up · {}", &[&remaining])
|
||||||
}));
|
}));
|
||||||
for (pos, track) in queue.upcoming().take(SHOWN) {
|
for (pos, track) in queue.upcoming().take(SHOWN) {
|
||||||
list = list.push(item(track, false, Some(Message::Player(Msg::JumpTo(pos)))));
|
list = list.push(item(track, false, Some(Message::Player(Msg::JumpTo(pos))), Source::Queue { pos }));
|
||||||
}
|
}
|
||||||
if remaining > SHOWN {
|
if remaining > SHOWN {
|
||||||
list = list.push(
|
list = list.push(
|
||||||
|
|||||||
@@ -0,0 +1,571 @@
|
|||||||
|
//! The context menu for tracks, albums, playlists and artists. It opens at the
|
||||||
|
//! pointer on a right-click, or under the "…" button, without dimming anything.
|
||||||
|
//! Every action closes it; a toast says what happened.
|
||||||
|
|
||||||
|
use iced::widget::{Column, button, container, mouse_area, opaque, pin, responsive, row, scrollable, space, stack};
|
||||||
|
use iced::{Alignment, Element, Fill, Point, Rectangle, Size};
|
||||||
|
use ym_api::{AlbumSummary, ArtistSummary, PlaylistId, PlaylistSummary, Track};
|
||||||
|
|
||||||
|
use crate::app::Message;
|
||||||
|
use crate::i18n::{tr, trf};
|
||||||
|
use crate::route::{Route, Sid};
|
||||||
|
use crate::ui::icons::{Icon, icon};
|
||||||
|
use crate::ui::line;
|
||||||
|
use crate::ui::theme::{self, Tokens, radius, size};
|
||||||
|
use crate::widgets::sheet::Sheet;
|
||||||
|
|
||||||
|
pub const WIDTH: f32 = 280.0;
|
||||||
|
const ITEM: f32 = 32.0;
|
||||||
|
const SEPARATOR: f32 = 9.0;
|
||||||
|
const PAD: f32 = 6.0;
|
||||||
|
/// Keeps the menu off the window edge.
|
||||||
|
const MARGIN: f32 = 8.0;
|
||||||
|
/// The playlist submenu scrolls past this many rows.
|
||||||
|
const SUB_ROWS: usize = 10;
|
||||||
|
/// Artist names longer than this are cut so the menu keeps its width.
|
||||||
|
const NAME_CHARS: usize = 24;
|
||||||
|
|
||||||
|
/// What the menu is for.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub enum Target {
|
||||||
|
Track { track: Track, from: Source },
|
||||||
|
Album(AlbumSummary),
|
||||||
|
Playlist(PlaylistSummary),
|
||||||
|
Artist(ArtistSummary),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a track's menu was opened; each place adds its own actions.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum Source {
|
||||||
|
/// A track list. In one of the user's own playlists: its id, the row, its length.
|
||||||
|
List { playlist: Option<(PlaylistId, usize, usize)> },
|
||||||
|
PlayerBar,
|
||||||
|
/// The queue drawer, at a position from `Queue::upcoming`.
|
||||||
|
Queue { pos: usize },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||||
|
pub enum Anchor {
|
||||||
|
/// Right-click: the pointer.
|
||||||
|
Point(Point),
|
||||||
|
/// The "…" button: the menu hangs under it, right edges lined up.
|
||||||
|
Below(Rectangle),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Menu {
|
||||||
|
pub target: Target,
|
||||||
|
pub anchor: Anchor,
|
||||||
|
/// The entry under the pointer or picked with the arrow keys, counted across groups.
|
||||||
|
pub highlight: Option<usize>,
|
||||||
|
/// The "Add to playlist" list is showing; the index is its highlighted row.
|
||||||
|
pub sub: Option<Option<usize>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Menu {
|
||||||
|
pub fn new(target: Target, anchor: Anchor) -> Self {
|
||||||
|
Self { target, anchor, highlight: None, sub: None }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn track(&self) -> Option<&Track> {
|
||||||
|
match &self.target {
|
||||||
|
Target::Track { track, .. } => Some(track),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the menu needs to know about the library for its target.
|
||||||
|
pub struct Ctx<'a> {
|
||||||
|
/// The target is the track playing now: "next" means skipping ahead.
|
||||||
|
pub playing: bool,
|
||||||
|
/// Liked track, or album/artist/playlist in the collection.
|
||||||
|
pub liked: bool,
|
||||||
|
pub disliked: bool,
|
||||||
|
pub own_playlists: &'a [PlaylistSummary],
|
||||||
|
pub me: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub enum Action {
|
||||||
|
Send(Box<Message>),
|
||||||
|
Submenu,
|
||||||
|
Disabled,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Entry {
|
||||||
|
pub icon: Icon,
|
||||||
|
pub label: String,
|
||||||
|
pub action: Action,
|
||||||
|
pub danger: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn entry(icon: Icon, label: impl Into<String>, msg: Message) -> Entry {
|
||||||
|
Entry { icon, label: label.into(), action: Action::Send(Box::new(msg)), danger: false }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The menu's entries in groups; a thin line separates the groups.
|
||||||
|
pub fn groups(target: &Target, ctx: &Ctx<'_>) -> Vec<Vec<Entry>> {
|
||||||
|
let mut groups = match target {
|
||||||
|
Target::Track { track, from } => track_groups(track, *from, ctx),
|
||||||
|
Target::Album(a) => vec![
|
||||||
|
play_group(Route::Album(a.id)),
|
||||||
|
vec![collection_entry(ctx.liked, Message::LikeAlbum(a.id, !ctx.liked))],
|
||||||
|
artist_entries(a.artists.iter().filter_map(|r| Some((r.id?, r.name.as_str())))),
|
||||||
|
],
|
||||||
|
Target::Playlist(p) if p.id.owner == ctx.me => vec![
|
||||||
|
play_group(Route::Playlist(p.id)),
|
||||||
|
vec![
|
||||||
|
entry(Icon::Pencil, tr("Rename…"), Message::OpenSheet(Sheet::Rename { id: p.id, name: p.title.clone() })),
|
||||||
|
Entry {
|
||||||
|
danger: true,
|
||||||
|
..entry(Icon::Trash, tr("Delete…"), Message::OpenSheet(Sheet::ConfirmDelete { id: p.id, title: p.title.clone() }))
|
||||||
|
},
|
||||||
|
],
|
||||||
|
],
|
||||||
|
Target::Playlist(p) => vec![
|
||||||
|
play_group(Route::Playlist(p.id)),
|
||||||
|
vec![collection_entry(ctx.liked, Message::LikePlaylist(p.id, !ctx.liked))],
|
||||||
|
],
|
||||||
|
Target::Artist(a) => vec![
|
||||||
|
vec![entry(Icon::Play, tr("Play"), Message::PlayRoute { route: Route::Artist(a.id), shuffle: false })],
|
||||||
|
vec![collection_entry(ctx.liked, Message::LikeArtist(a.id, !ctx.liked))],
|
||||||
|
],
|
||||||
|
};
|
||||||
|
groups.retain(|g| !g.is_empty());
|
||||||
|
groups
|
||||||
|
}
|
||||||
|
|
||||||
|
fn track_groups(track: &Track, from: Source, ctx: &Ctx<'_>) -> Vec<Vec<Entry>> {
|
||||||
|
if let Some(song) = track.subsonic() {
|
||||||
|
return server_track_groups(track, song, from, ctx);
|
||||||
|
}
|
||||||
|
let playable = |e: Entry| if track.available { e } else { Entry { action: Action::Disabled, ..e } };
|
||||||
|
let queue_group = match from {
|
||||||
|
Source::Queue { pos } => vec![
|
||||||
|
playable(entry(Icon::Play, tr("Play now"), Message::Player(crate::player::Msg::JumpTo(pos)))),
|
||||||
|
playable(entry(Icon::Next, tr("Play next"), Message::PlayNext(track.clone()))),
|
||||||
|
entry(Icon::Close, tr("Remove from queue"), Message::Player(crate::player::Msg::Remove { pos, id: track.id.clone() })),
|
||||||
|
],
|
||||||
|
_ => vec![
|
||||||
|
if ctx.playing {
|
||||||
|
entry(Icon::Next, tr("Next track"), Message::SkipFromMenu)
|
||||||
|
} else {
|
||||||
|
playable(entry(Icon::Next, tr("Play next"), Message::PlayNext(track.clone())))
|
||||||
|
},
|
||||||
|
playable(entry(Icon::Queue, tr("Add to queue"), Message::AddToQueue(track.clone()))),
|
||||||
|
entry(Icon::Wave, tr("Play similar tracks"), Message::PlaySimilar(track.clone())),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
let library = vec![
|
||||||
|
entry(
|
||||||
|
if ctx.liked { Icon::HeartFilled } else { Icon::Heart },
|
||||||
|
if ctx.liked { tr("Remove from Liked tracks") } else { tr("Add to Liked tracks") },
|
||||||
|
Message::LikeTrack(track.clone(), !ctx.liked),
|
||||||
|
),
|
||||||
|
Entry { icon: Icon::Plus, label: tr("Add to playlist").into(), action: Action::Submenu, danger: false },
|
||||||
|
entry(
|
||||||
|
Icon::Dislike,
|
||||||
|
if ctx.disliked { tr("Recommend this track again") } else { tr("Don't recommend this track") },
|
||||||
|
Message::DislikeTrack(track.clone(), !ctx.disliked),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
let mut go = Vec::new();
|
||||||
|
if let Some(album) = &track.album {
|
||||||
|
go.push(entry(Icon::Disc, tr("Go to album"), Message::Navigate(Route::Album(album.id))));
|
||||||
|
}
|
||||||
|
go.extend(artist_entries(track.artists.iter().filter_map(|a| Some((a.id?, a.name.as_str())))));
|
||||||
|
|
||||||
|
let mut groups = vec![queue_group, library, go];
|
||||||
|
if let Source::List { playlist: Some((id, index, len)) } = from {
|
||||||
|
let mut own = Vec::new();
|
||||||
|
if index > 0 {
|
||||||
|
own.push(entry(Icon::MoveTop, tr("Move to top"), Message::MovePlaylistTrack { id, track: track.clone(), from: index, to: 0 }));
|
||||||
|
}
|
||||||
|
if index + 1 < len {
|
||||||
|
own.push(entry(
|
||||||
|
Icon::MoveBottom,
|
||||||
|
tr("Move to bottom"),
|
||||||
|
Message::MovePlaylistTrack { id, track: track.clone(), from: index, to: len - 1 },
|
||||||
|
));
|
||||||
|
}
|
||||||
|
own.push(Entry { danger: true, ..entry(Icon::Trash, tr("Remove from this playlist"), Message::RemoveFromPlaylist(id, index)) });
|
||||||
|
groups.push(own);
|
||||||
|
}
|
||||||
|
groups
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A song from the music server: queueing and its album and artist there.
|
||||||
|
/// Likes, playlists and recommendations are Yandex's and don't apply.
|
||||||
|
fn server_track_groups(track: &Track, song: &ym_api::SubsonicSong, from: Source, ctx: &Ctx<'_>) -> Vec<Vec<Entry>> {
|
||||||
|
let queue_group = match from {
|
||||||
|
Source::Queue { pos } => vec![
|
||||||
|
entry(Icon::Play, tr("Play now"), Message::Player(crate::player::Msg::JumpTo(pos))),
|
||||||
|
entry(Icon::Next, tr("Play next"), Message::PlayNext(track.clone())),
|
||||||
|
entry(Icon::Close, tr("Remove from queue"), Message::Player(crate::player::Msg::Remove { pos, id: track.id.clone() })),
|
||||||
|
],
|
||||||
|
_ => vec![
|
||||||
|
if ctx.playing {
|
||||||
|
entry(Icon::Next, tr("Next track"), Message::SkipFromMenu)
|
||||||
|
} else {
|
||||||
|
entry(Icon::Next, tr("Play next"), Message::PlayNext(track.clone()))
|
||||||
|
},
|
||||||
|
entry(Icon::Queue, tr("Add to queue"), Message::AddToQueue(track.clone())),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
let mut go = Vec::new();
|
||||||
|
if let Some(album) = &song.album_id {
|
||||||
|
go.push(entry(Icon::Disc, tr("Go to album"), Message::Navigate(Route::ServerAlbum(Sid::of(album)))));
|
||||||
|
}
|
||||||
|
if let (Some(artist), Some(name)) = (&song.artist_id, track.artists.first()) {
|
||||||
|
let label = trf("Go to {}", &[&shorten(&name.name)]);
|
||||||
|
go.push(entry(Icon::Artist, label, Message::Navigate(Route::ServerArtist(Sid::of(artist)))));
|
||||||
|
}
|
||||||
|
let mut groups = vec![queue_group, go];
|
||||||
|
groups.retain(|g| !g.is_empty());
|
||||||
|
groups
|
||||||
|
}
|
||||||
|
|
||||||
|
fn play_group(route: Route) -> Vec<Entry> {
|
||||||
|
vec![
|
||||||
|
entry(Icon::Play, tr("Play"), Message::PlayRoute { route, shuffle: false }),
|
||||||
|
entry(Icon::Shuffle, tr("Shuffle"), Message::PlayRoute { route, shuffle: true }),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn collection_entry(liked: bool, msg: Message) -> Entry {
|
||||||
|
entry(
|
||||||
|
if liked { Icon::HeartFilled } else { Icon::Heart },
|
||||||
|
if liked { tr("Remove from collection") } else { tr("Add to collection") },
|
||||||
|
msg,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One named entry per artist, up to three.
|
||||||
|
fn artist_entries<'n>(artists: impl Iterator<Item = (i64, &'n str)>) -> Vec<Entry> {
|
||||||
|
artists
|
||||||
|
.take(3)
|
||||||
|
.map(|(id, name)| entry(Icon::Artist, trf("Go to {}", &[&shorten(name)]), Message::Navigate(Route::Artist(id))))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn shorten(name: &str) -> String {
|
||||||
|
if name.chars().count() <= NAME_CHARS {
|
||||||
|
return name.to_owned();
|
||||||
|
}
|
||||||
|
let cut: String = name.chars().take(NAME_CHARS - 1).collect();
|
||||||
|
format!("{}…", cut.trim_end())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The "Add to playlist" list: a new playlist, then the user's own.
|
||||||
|
pub fn sub_entries(track: &Track, own: &[PlaylistSummary]) -> Vec<Entry> {
|
||||||
|
std::iter::once(entry(Icon::Plus, tr("New playlist…"), Message::OpenSheet(Sheet::NewPlaylist { name: String::new(), add: Some(track.clone()) })))
|
||||||
|
.chain(own.iter().map(|p| entry(Icon::Queue, p.title.clone(), Message::AddToPlaylist(p.id, track.clone()))))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Entries in order, without the groups.
|
||||||
|
pub fn flat(groups: &[Vec<Entry>]) -> impl Iterator<Item = &Entry> {
|
||||||
|
groups.iter().flatten()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The next entry in `step` direction that can be picked, wrapping around.
|
||||||
|
pub fn step(entries: &[&Entry], from: Option<usize>, down: bool) -> Option<usize> {
|
||||||
|
let n = entries.len();
|
||||||
|
if n == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut i = from.unwrap_or(if down { n - 1 } else { 0 });
|
||||||
|
for _ in 0..n {
|
||||||
|
i = if down { (i + 1) % n } else { (i + n - 1) % n };
|
||||||
|
if !matches!(entries[i].action, Action::Disabled) {
|
||||||
|
return Some(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Placement ----
|
||||||
|
|
||||||
|
pub fn height(groups: &[Vec<Entry>]) -> f32 {
|
||||||
|
let items: usize = groups.iter().map(Vec::len).sum();
|
||||||
|
2.0 * PAD + items as f32 * ITEM + groups.len().saturating_sub(1) as f32 * SEPARATOR
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sub_height(rows: usize) -> f32 {
|
||||||
|
2.0 * PAD + rows.min(SUB_ROWS) as f32 * ITEM
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the menu's top-left corner goes: at the anchor, flipped left or up
|
||||||
|
/// where it would leave the window, and never past the edges.
|
||||||
|
pub fn place(anchor: Anchor, menu: Size, window: Size) -> Point {
|
||||||
|
let (x, y, flip_x, flip_y) = match anchor {
|
||||||
|
Anchor::Point(p) => (p.x, p.y, p.x - menu.width, p.y - menu.height),
|
||||||
|
Anchor::Below(r) => (r.x + r.width - menu.width, r.y + r.height + 4.0, r.x + r.width - menu.width, r.y - 4.0 - menu.height),
|
||||||
|
};
|
||||||
|
let x = if x + menu.width > window.width - MARGIN { flip_x } else { x };
|
||||||
|
let y = if y + menu.height > window.height - MARGIN { flip_y } else { y };
|
||||||
|
Point::new(clamp(x, menu.width, window.width), clamp(y, menu.height, window.height))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The submenu beside the menu at `menu`, its first row level with the entry at `row_y`.
|
||||||
|
pub fn place_sub(menu: Point, row_y: f32, sub: Size, window: Size) -> Point {
|
||||||
|
let right = menu.x + WIDTH + 2.0;
|
||||||
|
let x = if right + sub.width > window.width - MARGIN { menu.x - 2.0 - sub.width } else { right };
|
||||||
|
Point::new(clamp(x, sub.width, window.width), clamp(row_y - PAD, sub.height, window.height))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clamp(v: f32, len: f32, room: f32) -> f32 {
|
||||||
|
v.min(room - MARGIN - len).max(MARGIN)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Top of the entry at flat index `at`, measured from the menu's top.
|
||||||
|
fn row_top(groups: &[Vec<Entry>], at: usize) -> f32 {
|
||||||
|
let mut y = PAD;
|
||||||
|
let mut i = 0;
|
||||||
|
for (g, group) in groups.iter().enumerate() {
|
||||||
|
if g > 0 {
|
||||||
|
y += SEPARATOR;
|
||||||
|
}
|
||||||
|
for _ in group {
|
||||||
|
if i == at {
|
||||||
|
return y;
|
||||||
|
}
|
||||||
|
y += ITEM;
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
y
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- View ----
|
||||||
|
|
||||||
|
/// The whole-window layer: a catcher that closes the menu on any click or scroll
|
||||||
|
/// outside it, and the menu (plus its submenu) pinned where it belongs.
|
||||||
|
pub fn layer<'a>(t: &'static Tokens, menu: &'a Menu, ctx: Ctx<'a>) -> Element<'a, Message> {
|
||||||
|
let groups = groups(&menu.target, &ctx);
|
||||||
|
let sub = match (menu.sub, menu.track()) {
|
||||||
|
(Some(highlight), Some(track)) => Some((sub_entries(track, ctx.own_playlists), highlight)),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
let sub_at = flat(&groups).position(|e| matches!(e.action, Action::Submenu));
|
||||||
|
|
||||||
|
responsive(move |window| {
|
||||||
|
let size = Size::new(WIDTH, height(&groups));
|
||||||
|
let at = place(menu.anchor, size, window);
|
||||||
|
let catcher = mouse_area(container(space()).width(Fill).height(Fill))
|
||||||
|
.on_press(Message::CloseMenu)
|
||||||
|
.on_right_press(Message::CloseMenu)
|
||||||
|
.on_scroll(|_| Message::CloseMenu);
|
||||||
|
|
||||||
|
let mut items: Vec<Element<'a, Message>> = Vec::new();
|
||||||
|
let mut i = 0;
|
||||||
|
for (g, group) in groups.iter().enumerate() {
|
||||||
|
if g > 0 {
|
||||||
|
items.push(separator());
|
||||||
|
}
|
||||||
|
for e in group {
|
||||||
|
let open = matches!(e.action, Action::Submenu) && sub.is_some();
|
||||||
|
items.push(item(t, e, menu.highlight == Some(i) || open, Message::MenuHover(i)));
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut layers = stack![catcher, pin(panel(t, Column::with_children(items).into())).position(at)];
|
||||||
|
|
||||||
|
if let (Some((entries, highlight)), Some(row)) = (&sub, sub_at) {
|
||||||
|
let size = Size::new(WIDTH, sub_height(entries.len()));
|
||||||
|
let sub_pos = place_sub(at, at.y + row_top(&groups, row), size, window);
|
||||||
|
let rows = Column::with_children(
|
||||||
|
entries.iter().enumerate().map(|(j, e)| item(t, e, *highlight == Some(j), Message::MenuSubHover(j))),
|
||||||
|
);
|
||||||
|
let list: Element<'a, Message> = if entries.len() > SUB_ROWS {
|
||||||
|
scrollable(rows).height(SUB_ROWS as f32 * ITEM).style(theme::scroll).into()
|
||||||
|
} else {
|
||||||
|
rows.into()
|
||||||
|
};
|
||||||
|
layers = layers.push(pin(panel(t, list)).position(sub_pos));
|
||||||
|
}
|
||||||
|
layers.into()
|
||||||
|
})
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn panel<'a>(t: &'static Tokens, content: Element<'a, Message>) -> Element<'a, Message> {
|
||||||
|
opaque(container(content).width(WIDTH).padding(PAD).style(move |_| container::Style {
|
||||||
|
background: Some(t.panel.into()),
|
||||||
|
border: iced::Border { color: t.line, width: 1.0, radius: radius::COVER.into() },
|
||||||
|
shadow: iced::Shadow {
|
||||||
|
color: iced::Color::BLACK.scale_alpha(0.3),
|
||||||
|
offset: iced::Vector::new(0.0, 10.0),
|
||||||
|
blur_radius: 28.0,
|
||||||
|
},
|
||||||
|
..Default::default()
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn item<'a>(t: &'static Tokens, e: &Entry, lit: bool, hover: Message) -> Element<'a, Message> {
|
||||||
|
let disabled = matches!(e.action, Action::Disabled);
|
||||||
|
let (glyph, label) = match (disabled, e.danger) {
|
||||||
|
(true, _) => (t.muted, t.muted),
|
||||||
|
(false, true) => (t.like, t.like),
|
||||||
|
(false, false) => (t.muted, t.fg),
|
||||||
|
};
|
||||||
|
let mut content = row![icon(e.icon, glyph), line(e.label.clone(), theme::BODY, size::BODY, label).width(Fill)]
|
||||||
|
.spacing(12)
|
||||||
|
.align_y(Alignment::Center)
|
||||||
|
.height(ITEM);
|
||||||
|
if matches!(e.action, Action::Submenu) {
|
||||||
|
content = content.push(icon(crate::ui::icons::Icon::Forward, t.muted));
|
||||||
|
}
|
||||||
|
let press = match &e.action {
|
||||||
|
Action::Send(msg) => Some(Message::MenuPick(msg.clone())),
|
||||||
|
Action::Submenu => Some(Message::MenuSub(true)),
|
||||||
|
Action::Disabled => None,
|
||||||
|
};
|
||||||
|
let button = button(container(content).clip(true))
|
||||||
|
.width(Fill)
|
||||||
|
.padding([0, 10])
|
||||||
|
.style(theme::nav_item(lit && !disabled))
|
||||||
|
.on_press_maybe(press);
|
||||||
|
mouse_area(button).on_enter(hover).into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn separator<'a>() -> Element<'a, Message> {
|
||||||
|
container(container(space()).width(Fill).height(1).style(theme::divider)).padding([4, 4]).into()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn track(json_extra: &str) -> Track {
|
||||||
|
Track::from_json(&format!(
|
||||||
|
r#"{{"id":"7","title":"Хочешь?","artists":[{{"id":3,"name":"Земфира"}}],"albums":[{{"id":5,"title":"A"}}]{json_extra}}}"#
|
||||||
|
))
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ctx() -> Ctx<'static> {
|
||||||
|
Ctx { playing: false, liked: false, disliked: false, own_playlists: &[], me: 1 }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn labels(groups: &[Vec<Entry>]) -> Vec<Vec<String>> {
|
||||||
|
groups.iter().map(|g| g.iter().map(|e| e.label.clone()).collect()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_track_in_a_list_has_three_groups_with_named_artists() {
|
||||||
|
let groups = groups(&Target::Track { track: track(""), from: Source::List { playlist: None } }, &ctx());
|
||||||
|
assert_eq!(
|
||||||
|
labels(&groups),
|
||||||
|
[
|
||||||
|
vec!["Play next", "Add to queue", "Play similar tracks"],
|
||||||
|
vec!["Add to Liked tracks", "Add to playlist", "Don't recommend this track"],
|
||||||
|
vec!["Go to album", "Go to Земфира"],
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn own_playlist_rows_get_moves_that_fit_their_position() {
|
||||||
|
let id = PlaylistId { owner: 1, kind: 3 };
|
||||||
|
let first = groups(&Target::Track { track: track(""), from: Source::List { playlist: Some((id, 0, 5)) } }, &ctx());
|
||||||
|
assert_eq!(labels(&first)[3], ["Move to bottom", "Remove from this playlist"]);
|
||||||
|
let last = groups(&Target::Track { track: track(""), from: Source::List { playlist: Some((id, 4, 5)) } }, &ctx());
|
||||||
|
assert_eq!(labels(&last)[3], ["Move to top", "Remove from this playlist"]);
|
||||||
|
assert!(last[3][1].danger);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn queue_rows_can_be_played_now_or_removed() {
|
||||||
|
let groups = groups(&Target::Track { track: track(""), from: Source::Queue { pos: 4 } }, &ctx());
|
||||||
|
assert_eq!(labels(&groups)[0], ["Play now", "Play next", "Remove from queue"]);
|
||||||
|
assert!(matches!(&groups[0][2].action, Action::Send(m) if matches!(&**m, Message::Player(crate::player::Msg::Remove { pos: 4, .. }))));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_playing_track_offers_next_track_and_unavailable_ones_cant_be_queued() {
|
||||||
|
let playing = Ctx { playing: true, ..ctx() };
|
||||||
|
let groups = groups(&Target::Track { track: track(""), from: Source::PlayerBar }, &playing);
|
||||||
|
assert_eq!(groups[0][0].label, "Next track");
|
||||||
|
|
||||||
|
let gone = groups_for_unavailable();
|
||||||
|
assert!(matches!(gone[0][0].action, Action::Disabled));
|
||||||
|
assert!(matches!(gone[0][1].action, Action::Disabled));
|
||||||
|
assert!(matches!(gone[1][0].action, Action::Send(_)), "liking still works");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn groups_for_unavailable() -> Vec<Vec<Entry>> {
|
||||||
|
groups(&Target::Track { track: track(r#","available":false"#), from: Source::List { playlist: None } }, &ctx())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn server_tracks_only_queue_and_link_to_their_server_pages() {
|
||||||
|
let song = ym_api::SubsonicSong {
|
||||||
|
song_id: "s1".into(),
|
||||||
|
album_id: Some("al1".into()),
|
||||||
|
album_title: Some("A".into()),
|
||||||
|
artist_id: Some("ar1".into()),
|
||||||
|
cover_art: None,
|
||||||
|
suffix: "mp3".into(),
|
||||||
|
bit_rate: 320,
|
||||||
|
};
|
||||||
|
let t = Track::from_subsonic("T".into(), Some("Kino".into()), std::time::Duration::from_secs(60), song);
|
||||||
|
let groups = groups(&Target::Track { track: t, from: Source::List { playlist: None } }, &ctx());
|
||||||
|
assert_eq!(labels(&groups), [vec!["Play next", "Add to queue"], vec!["Go to album", "Go to Kino"]]);
|
||||||
|
assert!(matches!(&groups[1][0].action,
|
||||||
|
Action::Send(m) if matches!(&**m, Message::Navigate(Route::ServerAlbum(sid)) if *sid == Sid::of("al1"))));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn long_artist_names_are_shortened_and_at_most_three_listed() {
|
||||||
|
let names: Vec<String> = (0..5).map(|i| format!(r#"{{"id":{i},"name":"Очень длинное имя исполнителя номер {i}"}}"#)).collect();
|
||||||
|
let t = Track::from_json(&format!(r#"{{"id":"1","title":"T","artists":[{}]}}"#, names.join(","))).unwrap();
|
||||||
|
let groups = groups(&Target::Track { track: t, from: Source::List { playlist: None } }, &ctx());
|
||||||
|
let go = &groups[2];
|
||||||
|
assert_eq!(go.len(), 3);
|
||||||
|
assert!(go[0].label.ends_with('…'), "{}", go[0].label);
|
||||||
|
assert!(go[0].label.chars().count() <= "Go to ".len() + NAME_CHARS);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn own_playlist_cards_rename_and_delete_instead_of_liking() {
|
||||||
|
let own = PlaylistSummary::for_tests(PlaylistId { owner: 1, kind: 9 }, "Дорога");
|
||||||
|
assert_eq!(labels(&groups(&Target::Playlist(own), &ctx()))[1], ["Rename…", "Delete…"]);
|
||||||
|
let theirs = PlaylistSummary::for_tests(PlaylistId { owner: 2, kind: 9 }, "Чужой");
|
||||||
|
assert_eq!(labels(&groups(&Target::Playlist(theirs), &ctx()))[1], ["Add to collection"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn arrow_keys_skip_disabled_entries_and_wrap() {
|
||||||
|
let gone = groups_for_unavailable();
|
||||||
|
let entries: Vec<&Entry> = flat(&gone).collect();
|
||||||
|
assert_eq!(step(&entries, None, true), Some(2), "the first two can't be picked");
|
||||||
|
assert_eq!(step(&entries, Some(2), false), Some(entries.len() - 1), "up from the first wraps to the last");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_menu_flips_and_stays_inside_the_window() {
|
||||||
|
let window = Size::new(960.0, 620.0);
|
||||||
|
let menu = Size::new(WIDTH, 300.0);
|
||||||
|
assert_eq!(place(Anchor::Point(Point::new(100.0, 100.0)), menu, window), Point::new(100.0, 100.0));
|
||||||
|
// Near the right and bottom edges it opens to the left of and above the pointer.
|
||||||
|
assert_eq!(place(Anchor::Point(Point::new(900.0, 600.0)), menu, window), Point::new(620.0, 300.0));
|
||||||
|
// Under the "…" button, right edges line up.
|
||||||
|
let button = Rectangle::new(Point::new(800.0, 100.0), Size::new(34.0, 34.0));
|
||||||
|
assert_eq!(place(Anchor::Below(button), menu, window), Point::new(834.0 - WIDTH, 138.0));
|
||||||
|
// A menu taller than the room left above and below is held inside.
|
||||||
|
let tall = Size::new(WIDTH, 500.0);
|
||||||
|
let at = place(Anchor::Point(Point::new(100.0, 300.0)), tall, window);
|
||||||
|
assert!(at.y >= MARGIN && at.y + tall.height <= window.height - MARGIN + 0.5, "{at:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_submenu_opens_left_when_there_is_no_room_on_the_right() {
|
||||||
|
let window = Size::new(960.0, 620.0);
|
||||||
|
let sub = Size::new(WIDTH, 200.0);
|
||||||
|
assert_eq!(place_sub(Point::new(100.0, 50.0), 90.0, sub, window).x, 100.0 + WIDTH + 2.0);
|
||||||
|
assert_eq!(place_sub(Point::new(600.0, 50.0), 90.0, sub, window).x, 600.0 - 2.0 - WIDTH);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
|
pub mod anchor;
|
||||||
pub mod card;
|
pub mod card;
|
||||||
pub mod drawer;
|
pub mod drawer;
|
||||||
|
pub mod menu;
|
||||||
|
pub mod now_playing;
|
||||||
pub mod player_bar;
|
pub mod player_bar;
|
||||||
pub mod sheet;
|
pub mod sheet;
|
||||||
pub mod sidebar;
|
pub mod sidebar;
|
||||||
|
|||||||
@@ -0,0 +1,299 @@
|
|||||||
|
//! Now Playing: the cover large over a blurred copy of itself, what's playing beside it and
|
||||||
|
//! the transport along the bottom. It takes the whole window, player bar included; the queue
|
||||||
|
//! and lyrics drawer opens at its right edge.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use iced::widget::image::FilterMethod;
|
||||||
|
use iced::widget::{button, column, container, image, responsive, row, slider, space, stack, text};
|
||||||
|
use iced::{Alignment, ContentFit, Element, Fill, Padding, Size};
|
||||||
|
use ym_api::{Lyrics, Track};
|
||||||
|
|
||||||
|
use crate::app::Message;
|
||||||
|
use crate::covers::{self, Covers};
|
||||||
|
use crate::i18n::tr;
|
||||||
|
use crate::player::{Msg, Player, Repeat, Status};
|
||||||
|
use crate::screens::Loadable;
|
||||||
|
use crate::ui::icons::{Icon, icon, sized};
|
||||||
|
use crate::ui::theme::{self, Tokens, radius, size};
|
||||||
|
use crate::ui::theme::space as gap;
|
||||||
|
use crate::ui::{line, para};
|
||||||
|
use crate::widgets::anchor::anchor;
|
||||||
|
use crate::widgets::drawer::{self, Panel};
|
||||||
|
use crate::widgets::menu::{Anchor, Menu, Source, Target};
|
||||||
|
use crate::widgets::player_bar::clock;
|
||||||
|
|
||||||
|
/// The cover never grows past this, nor shrinks below the second.
|
||||||
|
const COVER_MAX: f32 = 520.0;
|
||||||
|
const COVER_MIN: f32 = 160.0;
|
||||||
|
/// Height the header, the seek bar and the controls take around the stage, with their gaps.
|
||||||
|
const CHROME: f32 = 236.0;
|
||||||
|
/// Below this stage width the Queue and Lyrics pills lose their labels.
|
||||||
|
const NARROW: f32 = 820.0;
|
||||||
|
|
||||||
|
pub struct Ctx<'a> {
|
||||||
|
pub t: &'static Tokens,
|
||||||
|
pub player: &'a Player,
|
||||||
|
pub liked: bool,
|
||||||
|
pub drawer: Option<Panel>,
|
||||||
|
pub covers: &'a Covers,
|
||||||
|
pub lyrics: Option<&'a Loadable<Option<Arc<Lyrics>>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn view(cx: Ctx<'_>) -> Element<'_, Message> {
|
||||||
|
let Ctx { t, player, liked, drawer, covers, lyrics } = cx;
|
||||||
|
let Some(track) = player.track() else { return empty(t, player) };
|
||||||
|
|
||||||
|
let stage = responsive(move |area| stage(t, player, track, liked, drawer, covers, lyrics, area));
|
||||||
|
let mut body = row![stage].height(Fill);
|
||||||
|
if let Some(panel) = drawer {
|
||||||
|
body = body
|
||||||
|
.push(container(space()).width(1).height(Fill).style(theme::divider))
|
||||||
|
.push(drawer::view(t, panel, player, covers, lyrics));
|
||||||
|
}
|
||||||
|
stack![backdrop(track, covers), body].into()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
fn stage<'a>(
|
||||||
|
t: &'static Tokens,
|
||||||
|
p: &'a Player,
|
||||||
|
track: &'a Track,
|
||||||
|
liked: bool,
|
||||||
|
drawer: Option<Panel>,
|
||||||
|
covers: &Covers,
|
||||||
|
lyrics: Option<&'a Loadable<Option<Arc<Lyrics>>>>,
|
||||||
|
area: Size,
|
||||||
|
) -> Element<'a, Message> {
|
||||||
|
let side = (area.height - CHROME)
|
||||||
|
.min((area.width - 2.0 * gap::SECTION) * 0.45)
|
||||||
|
.clamp(COVER_MIN, COVER_MAX);
|
||||||
|
let cover = container(covers::view(covers, track.cover_url(covers::LARGE), track.hues(), side, radius::HERO))
|
||||||
|
.style(theme::stage_cover);
|
||||||
|
|
||||||
|
let middle = row![cover, info(t, p, track, lyrics)]
|
||||||
|
.spacing(48)
|
||||||
|
.align_y(Alignment::Center)
|
||||||
|
.height(Fill);
|
||||||
|
|
||||||
|
column![header(t), middle, seek(t, p), controls(t, p, track, liked, drawer, area.width < NARROW)]
|
||||||
|
.spacing(gap::L)
|
||||||
|
.padding(Padding::from([gap::XL, gap::SECTION]))
|
||||||
|
.width(Fill)
|
||||||
|
.height(Fill)
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn header<'a>(t: &'static Tokens) -> Element<'a, Message> {
|
||||||
|
row![
|
||||||
|
button(icon(Icon::Collapse, t.muted))
|
||||||
|
.padding(8)
|
||||||
|
.style(theme::icon_button(None))
|
||||||
|
.on_press(Message::ShowNowPlaying(false)),
|
||||||
|
line(tr("Now playing"), theme::MEDIUM, size::SMALL, t.muted),
|
||||||
|
]
|
||||||
|
.spacing(6)
|
||||||
|
.align_y(Alignment::Center)
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Quality, title, artists, album, the notice when there is one, and the line being sung.
|
||||||
|
fn info<'a>(
|
||||||
|
t: &'static Tokens,
|
||||||
|
p: &'a Player,
|
||||||
|
track: &'a Track,
|
||||||
|
lyrics: Option<&'a Loadable<Option<Arc<Lyrics>>>>,
|
||||||
|
) -> Element<'a, Message> {
|
||||||
|
let mut info = column![].spacing(gap::M).width(Fill);
|
||||||
|
if let Some(stream) = p.stream() {
|
||||||
|
let label = if stream.preview { tr("Preview").to_owned() } else { stream.label() };
|
||||||
|
let ink = if stream.lossless() { t.accent } else { t.muted };
|
||||||
|
info = info.push(container(line(label, theme::MEDIUM, 11.5, ink)).padding([2, 6]).style(theme::badge));
|
||||||
|
}
|
||||||
|
info = info
|
||||||
|
.push(text(track.full_title()).font(theme::DISPLAY).size(size::DISPLAY_M).color(t.fg).line_height(1.2))
|
||||||
|
.push(line(track.artist_line(), theme::SEMIBOLD, size::SECTION, t.fg));
|
||||||
|
if let Some(album) = track.album_title() {
|
||||||
|
info = info.push(line(album, theme::BODY, size::BODY, t.muted));
|
||||||
|
}
|
||||||
|
if let Some(notice) = &p.notice
|
||||||
|
&& matches!(p.status(), Status::Loading | Status::Paused)
|
||||||
|
{
|
||||||
|
info = info.push(para(notice.as_str(), size::META, t.like));
|
||||||
|
}
|
||||||
|
// Synced lyrics show the line being sung; the drawer has the rest.
|
||||||
|
if let Some(Loadable::Loaded(Some(l))) = lyrics
|
||||||
|
&& l.synced
|
||||||
|
&& let Some(i) = l.current(p.position())
|
||||||
|
{
|
||||||
|
let sung = if l.lines[i].text.is_empty() { "♪" } else { l.lines[i].text.as_str() };
|
||||||
|
let glance = text(sung).font(theme::SEMIBOLD).size(size::SECTION).color(t.accent).line_height(1.35);
|
||||||
|
info = info.push(container(glance).padding(Padding::default().top(gap::L)));
|
||||||
|
}
|
||||||
|
info.clip(true).into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The bar and the times under its ends.
|
||||||
|
fn seek<'a>(t: &'static Tokens, p: &'a Player) -> Element<'a, Message> {
|
||||||
|
let duration = p.duration().as_secs_f32();
|
||||||
|
let position = p.position().as_secs_f32().min(duration);
|
||||||
|
let bar: Element<'a, Message> = if duration > 0.0 {
|
||||||
|
slider(0.0..=duration, position, |v| Message::Player(Msg::SeekPreview(v)))
|
||||||
|
.on_release(Message::Player(Msg::SeekCommit))
|
||||||
|
.step(0.5_f32)
|
||||||
|
.width(Fill)
|
||||||
|
.style(theme::stage_seek_bar)
|
||||||
|
.into()
|
||||||
|
} else {
|
||||||
|
container(space())
|
||||||
|
.width(Fill)
|
||||||
|
.height(6)
|
||||||
|
.style(move |_| container::Style {
|
||||||
|
background: Some(t.raised.into()),
|
||||||
|
border: iced::Border { radius: 3.0.into(), ..Default::default() },
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
.into()
|
||||||
|
};
|
||||||
|
let times = row![
|
||||||
|
line(clock(position), theme::BODY, size::SMALL, t.muted),
|
||||||
|
space().width(Fill),
|
||||||
|
line(clock(duration), theme::BODY, size::SMALL, t.muted),
|
||||||
|
];
|
||||||
|
column![bar, times].spacing(6).into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shuffle, previous, the play disc, next and repeat; then like, the track's menu, the
|
||||||
|
/// drawer's two panels and the volume.
|
||||||
|
fn controls<'a>(
|
||||||
|
t: &'static Tokens,
|
||||||
|
p: &'a Player,
|
||||||
|
track: &'a Track,
|
||||||
|
liked: bool,
|
||||||
|
drawer: Option<Panel>,
|
||||||
|
narrow: bool,
|
||||||
|
) -> Element<'a, Message> {
|
||||||
|
let send = Message::Player;
|
||||||
|
let round = |glyph: Icon, tint, on: Option<iced::Color>, msg: Message| {
|
||||||
|
button(sized(glyph, 20.0, tint)).padding(10).style(theme::icon_button(on)).on_press(msg)
|
||||||
|
};
|
||||||
|
let toggle = |glyph: Icon, on: bool, msg: Msg| {
|
||||||
|
round(glyph, if on { t.accent } else { t.fg }, on.then_some(t.accent), send(msg))
|
||||||
|
};
|
||||||
|
|
||||||
|
let glyph = match p.status() {
|
||||||
|
Status::Playing | Status::Loading => Icon::Pause,
|
||||||
|
Status::Paused | Status::Ended => Icon::Play,
|
||||||
|
};
|
||||||
|
let ink = if p.status() == Status::Loading { theme::mix(t.accent_ink, t.accent, 0.5) } else { t.accent_ink };
|
||||||
|
let disc = button(container(sized(glyph, 24.0, ink)).center(56))
|
||||||
|
.width(56)
|
||||||
|
.height(56)
|
||||||
|
.padding(0)
|
||||||
|
.style(theme::primary)
|
||||||
|
.on_press(send(Msg::Toggle));
|
||||||
|
|
||||||
|
let transport = row![
|
||||||
|
toggle(Icon::Shuffle, p.shuffle(), Msg::ToggleShuffle),
|
||||||
|
round(Icon::Previous, t.fg, None, send(Msg::Previous)),
|
||||||
|
disc,
|
||||||
|
round(Icon::Next, t.fg, None, send(Msg::Next)),
|
||||||
|
toggle(
|
||||||
|
if p.repeat == Repeat::One { Icon::RepeatOne } else { Icon::Repeat },
|
||||||
|
p.repeat != Repeat::Off,
|
||||||
|
Msg::CycleRepeat,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
.spacing(10)
|
||||||
|
.align_y(Alignment::Center);
|
||||||
|
|
||||||
|
// Only Yandex tracks can be liked.
|
||||||
|
let heart = track.is_yandex().then(|| {
|
||||||
|
button(icon(if liked { Icon::HeartFilled } else { Icon::Heart }, if liked { t.like } else { t.muted }))
|
||||||
|
.padding(8)
|
||||||
|
.style(theme::icon_button(None))
|
||||||
|
.on_press(Message::LikeTrack(track.clone(), !liked))
|
||||||
|
});
|
||||||
|
|
||||||
|
// The anchor takes the click and reports where the button is, so the menu hangs under it.
|
||||||
|
let target = Target::Track { track: track.clone(), from: Source::PlayerBar };
|
||||||
|
let more = anchor(button(icon(Icon::More, t.muted)).padding(8).style(theme::icon_button(None)).on_press(Message::CloseMenu))
|
||||||
|
.on_press(move |bounds| Message::OpenMenu(Box::new(Menu::new(target.clone(), Anchor::Below(bounds)))));
|
||||||
|
|
||||||
|
let pill = |glyph: Icon, panel: Panel, label: &'static str| -> Element<'a, Message> {
|
||||||
|
let on = drawer == Some(panel);
|
||||||
|
if narrow {
|
||||||
|
return button(icon(glyph, if on { t.accent } else { t.muted }))
|
||||||
|
.padding(8)
|
||||||
|
.style(theme::icon_button(on.then_some(t.accent)))
|
||||||
|
.on_press(Message::ToggleDrawer(panel))
|
||||||
|
.into();
|
||||||
|
}
|
||||||
|
let ink = if on { t.accent_ink } else { t.fg };
|
||||||
|
button(row![icon(glyph, ink), line(label, theme::MEDIUM, size::BODY, ink)].spacing(8).align_y(Alignment::Center))
|
||||||
|
.padding([7, 14])
|
||||||
|
.style(theme::chip(on))
|
||||||
|
.on_press(Message::ToggleDrawer(panel))
|
||||||
|
.into()
|
||||||
|
};
|
||||||
|
|
||||||
|
let volume = if p.muted { 0.0 } else { p.volume };
|
||||||
|
row![transport, space().width(Fill)]
|
||||||
|
.push(heart)
|
||||||
|
.push(more)
|
||||||
|
.push(pill(Icon::Queue, Panel::Queue, tr("Queue")))
|
||||||
|
.push(pill(Icon::Lyrics, Panel::Lyrics, tr("Lyrics")))
|
||||||
|
.push(
|
||||||
|
button(icon(if p.muted { Icon::Muted } else { Icon::Volume }, t.muted))
|
||||||
|
.padding(8)
|
||||||
|
.style(theme::icon_button(None))
|
||||||
|
.on_press(send(Msg::ToggleMute)),
|
||||||
|
)
|
||||||
|
.push(
|
||||||
|
slider(0.0..=1.0, volume, |v| Message::Player(Msg::SetVolume(v)))
|
||||||
|
.step(0.01_f32)
|
||||||
|
.width(if narrow { 72 } else { 110 })
|
||||||
|
.style(theme::volume_bar),
|
||||||
|
)
|
||||||
|
.spacing(8)
|
||||||
|
.align_y(Alignment::Center)
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The cover's blurred copy stretched over the window, washed with the ground. Until the
|
||||||
|
/// cover has loaded, its placeholder gradient stands in.
|
||||||
|
fn backdrop<'a>(track: &Track, covers: &Covers) -> Element<'a, Message> {
|
||||||
|
let art: Element<'a, Message> = match track.cover_url(covers::LARGE).and_then(|url| covers.backdrop(&url)) {
|
||||||
|
Some(handle) => image(handle)
|
||||||
|
.width(Fill)
|
||||||
|
.height(Fill)
|
||||||
|
.content_fit(ContentFit::Cover)
|
||||||
|
.filter_method(FilterMethod::Linear)
|
||||||
|
.into(),
|
||||||
|
None => {
|
||||||
|
let (h1, h2) = track.hues();
|
||||||
|
container(space()).width(Fill).height(Fill).style(theme::cover(h1, h2, 0.0)).into()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
stack![art, container(space()).width(Fill).height(Fill).style(theme::backdrop_wash)].into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Nothing to show: a station's first track on its way, or nothing queued at all.
|
||||||
|
fn empty<'a>(t: &'static Tokens, p: &'a Player) -> Element<'a, Message> {
|
||||||
|
let (title, sub) = match (&p.notice, p.wave_station()) {
|
||||||
|
(None, Some(_)) => (tr("Loading…"), ""),
|
||||||
|
(Some(notice), _) => (tr("Can't play"), notice.as_str()),
|
||||||
|
(None, None) => (tr("Nothing playing"), tr("Pick a track to start")),
|
||||||
|
};
|
||||||
|
let message = column![
|
||||||
|
line(title, theme::DISPLAY, size::DISPLAY_S, t.fg),
|
||||||
|
para(sub, size::BODY, t.muted),
|
||||||
|
]
|
||||||
|
.spacing(gap::M);
|
||||||
|
container(column![header(t), container(message).center(Fill)].height(Fill))
|
||||||
|
.padding(Padding::from([gap::XL, gap::SECTION]))
|
||||||
|
.width(Fill)
|
||||||
|
.height(Fill)
|
||||||
|
.style(theme::app)
|
||||||
|
.into()
|
||||||
|
}
|
||||||
@@ -9,7 +9,9 @@ use crate::player::{Msg, Player, Repeat, Status};
|
|||||||
use crate::ui::icons::{Icon, icon, sized};
|
use crate::ui::icons::{Icon, icon, sized};
|
||||||
use crate::ui::line;
|
use crate::ui::line;
|
||||||
use crate::ui::theme::{self, Tokens, radius, size};
|
use crate::ui::theme::{self, Tokens, radius, size};
|
||||||
|
use crate::widgets::anchor::anchor;
|
||||||
use crate::widgets::drawer::Panel;
|
use crate::widgets::drawer::Panel;
|
||||||
|
use crate::widgets::menu::{Anchor, Menu, Source, Target};
|
||||||
use crate::i18n::tr;
|
use crate::i18n::tr;
|
||||||
|
|
||||||
fn send(msg: Msg) -> Message {
|
fn send(msg: Msg) -> Message {
|
||||||
@@ -68,6 +70,9 @@ fn now_playing<'a>(t: &'static Tokens, p: &'a Player, liked: bool, covers: &Cove
|
|||||||
_ => (track.artist_line(), t.muted),
|
_ => (track.artist_line(), t.muted),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// A click on the cover or the title opens Now Playing; a right-click, the track's menu.
|
||||||
|
let target = Target::Track { track: track.clone(), from: Source::PlayerBar };
|
||||||
|
let about = anchor(
|
||||||
row![
|
row![
|
||||||
cover,
|
cover,
|
||||||
column![
|
column![
|
||||||
@@ -76,18 +81,28 @@ fn now_playing<'a>(t: &'static Tokens, p: &'a Player, liked: bool, covers: &Cove
|
|||||||
]
|
]
|
||||||
.spacing(2)
|
.spacing(2)
|
||||||
.width(Length::Shrink),
|
.width(Length::Shrink),
|
||||||
button(icon(
|
]
|
||||||
if liked { Icon::HeartFilled } else { Icon::Heart },
|
.spacing(12)
|
||||||
if liked { t.like } else { t.muted },
|
.align_y(Alignment::Center),
|
||||||
))
|
)
|
||||||
|
.on_press(|_| Message::ShowNowPlaying(true))
|
||||||
|
.on_right_press(move |at| Message::OpenMenu(Box::new(Menu::new(target.clone(), Anchor::Point(at)))));
|
||||||
|
|
||||||
|
// Likes and dislikes are Yandex's; tracks from the music server have neither.
|
||||||
|
let yandex = track.is_yandex();
|
||||||
|
row![about]
|
||||||
|
.push(yandex.then(|| {
|
||||||
|
button(icon(if liked { Icon::HeartFilled } else { Icon::Heart }, if liked { t.like } else { t.muted }))
|
||||||
.padding(8)
|
.padding(8)
|
||||||
.style(theme::icon_button(None))
|
.style(theme::icon_button(None))
|
||||||
.on_press(Message::LikeTrack(track.clone(), !liked)),
|
.on_press(Message::LikeTrack(track.clone(), !liked))
|
||||||
|
}))
|
||||||
|
.push(yandex.then(|| {
|
||||||
button(icon(Icon::Dislike, t.muted))
|
button(icon(Icon::Dislike, t.muted))
|
||||||
.padding(8)
|
.padding(8)
|
||||||
.style(theme::icon_button(None))
|
.style(theme::icon_button(None))
|
||||||
.on_press(Message::DislikeTrack(track.clone(), true)),
|
.on_press(Message::DislikeTrack(track.clone(), true))
|
||||||
]
|
}))
|
||||||
.spacing(12)
|
.spacing(12)
|
||||||
.align_y(Alignment::Center)
|
.align_y(Alignment::Center)
|
||||||
.clip(true)
|
.clip(true)
|
||||||
@@ -188,6 +203,12 @@ fn extras<'a>(t: &'static Tokens, p: &'a Player, drawer: Option<Panel>) -> Eleme
|
|||||||
|
|
||||||
let volume = if p.muted { 0.0 } else { p.volume };
|
let volume = if p.muted { 0.0 } else { p.volume };
|
||||||
items
|
items
|
||||||
|
.push(
|
||||||
|
button(icon(Icon::Expand, t.muted))
|
||||||
|
.padding(8)
|
||||||
|
.style(theme::icon_button(None))
|
||||||
|
.on_press_maybe(p.track().is_some().then_some(Message::ShowNowPlaying(true))),
|
||||||
|
)
|
||||||
.push(panel_button(Icon::Lyrics, Panel::Lyrics))
|
.push(panel_button(Icon::Lyrics, Panel::Lyrics))
|
||||||
.push(panel_button(Icon::Queue, Panel::Queue))
|
.push(panel_button(Icon::Queue, Panel::Queue))
|
||||||
.push(
|
.push(
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
//! Small dialogs over the window: track actions, new/rename playlist, delete confirmation.
|
//! Small dialogs over the window: new/rename playlist, delete confirmation.
|
||||||
|
//! Track actions live in the context menu (`widgets::menu`).
|
||||||
|
|
||||||
use iced::widget::{Column, button, column, container, mouse_area, opaque, row, space, text_input};
|
use iced::widget::{button, column, container, mouse_area, opaque, row, space, text_input};
|
||||||
use iced::{Alignment, Element, Fill, Length};
|
use iced::{Alignment, Element, Fill};
|
||||||
use ym_api::{PlaylistId, PlaylistSummary, Track};
|
use ym_api::{PlaylistId, Track};
|
||||||
|
|
||||||
use crate::app::Message;
|
use crate::app::Message;
|
||||||
use crate::route::Route;
|
|
||||||
use crate::ui::icons::{Icon, icon};
|
use crate::ui::icons::{Icon, icon};
|
||||||
use crate::ui::theme::{self, Tokens, radius, size};
|
use crate::ui::theme::{self, Tokens, radius, size};
|
||||||
use crate::ui::{line, para};
|
use crate::ui::{line, para};
|
||||||
@@ -13,13 +13,6 @@ use crate::i18n::{tr, trf};
|
|||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub enum Sheet {
|
pub enum Sheet {
|
||||||
Track {
|
|
||||||
track: Track,
|
|
||||||
/// Set when opened from one of the user's own playlists: its id, the row, its length.
|
|
||||||
playlist: Option<(PlaylistId, usize, usize)>,
|
|
||||||
/// Showing the "Add to playlist" list instead of the actions.
|
|
||||||
choosing: bool,
|
|
||||||
},
|
|
||||||
NewPlaylist { name: String, add: Option<Track> },
|
NewPlaylist { name: String, add: Option<Track> },
|
||||||
Rename { id: PlaylistId, name: String },
|
Rename { id: PlaylistId, name: String },
|
||||||
ConfirmDelete { id: PlaylistId, title: String },
|
ConfirmDelete { id: PlaylistId, title: String },
|
||||||
@@ -27,17 +20,8 @@ pub enum Sheet {
|
|||||||
|
|
||||||
pub const INPUT_ID: &str = "sheet-input";
|
pub const INPUT_ID: &str = "sheet-input";
|
||||||
|
|
||||||
/// What the sheet needs to know about the library.
|
|
||||||
pub struct Ctx<'a> {
|
|
||||||
/// The menu is for the track playing now: "next" means skipping ahead.
|
|
||||||
pub playing: bool,
|
|
||||||
pub liked: bool,
|
|
||||||
pub disliked: bool,
|
|
||||||
pub own_playlists: &'a [PlaylistSummary],
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The dimmed backdrop plus the dialog; clicking the backdrop closes it.
|
/// The dimmed backdrop plus the dialog; clicking the backdrop closes it.
|
||||||
pub fn overlay<'a>(t: &'static Tokens, sheet: &'a Sheet, ctx: Ctx<'a>) -> Element<'a, Message> {
|
pub fn overlay<'a>(t: &'static Tokens, sheet: &'a Sheet) -> Element<'a, Message> {
|
||||||
let backdrop = mouse_area(
|
let backdrop = mouse_area(
|
||||||
container(space()).width(Fill).height(Fill).style(|_| container::Style {
|
container(space()).width(Fill).height(Fill).style(|_| container::Style {
|
||||||
background: Some(iced::Color::BLACK.scale_alpha(0.45).into()),
|
background: Some(iced::Color::BLACK.scale_alpha(0.45).into()),
|
||||||
@@ -46,7 +30,7 @@ pub fn overlay<'a>(t: &'static Tokens, sheet: &'a Sheet, ctx: Ctx<'a>) -> Elemen
|
|||||||
)
|
)
|
||||||
.on_press(Message::CloseSheet);
|
.on_press(Message::CloseSheet);
|
||||||
|
|
||||||
let card = container(body(t, sheet, ctx))
|
let card = container(body(t, sheet))
|
||||||
.width(380)
|
.width(380)
|
||||||
.padding(18)
|
.padding(18)
|
||||||
.style(move |_| container::Style {
|
.style(move |_| container::Style {
|
||||||
@@ -63,80 +47,8 @@ pub fn overlay<'a>(t: &'static Tokens, sheet: &'a Sheet, ctx: Ctx<'a>) -> Elemen
|
|||||||
iced::widget::stack![backdrop, container(opaque(card)).center(Fill)].into()
|
iced::widget::stack![backdrop, container(opaque(card)).center(Fill)].into()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn body<'a>(t: &'static Tokens, sheet: &'a Sheet, ctx: Ctx<'a>) -> Element<'a, Message> {
|
fn body<'a>(t: &'static Tokens, sheet: &'a Sheet) -> Element<'a, Message> {
|
||||||
match sheet {
|
match sheet {
|
||||||
Sheet::Track { track, playlist, choosing: false } => {
|
|
||||||
let mut items: Vec<Element<'a, Message>> = vec![
|
|
||||||
if ctx.playing {
|
|
||||||
item(t, Icon::Next, tr("Next track"), Some(Message::SkipFromMenu))
|
|
||||||
} else {
|
|
||||||
item(t, Icon::Next, tr("Play next"), Some(Message::PlayNext(track.clone())))
|
|
||||||
},
|
|
||||||
item(t, Icon::Queue, tr("Add to queue"), Some(Message::AddToQueue(track.clone()))),
|
|
||||||
item(
|
|
||||||
t,
|
|
||||||
if ctx.liked { Icon::HeartFilled } else { Icon::Heart },
|
|
||||||
if ctx.liked { tr("Remove from Liked tracks") } else { tr("Add to Liked tracks") },
|
|
||||||
Some(Message::LikeTrack(track.clone(), !ctx.liked)),
|
|
||||||
),
|
|
||||||
item(
|
|
||||||
t,
|
|
||||||
Icon::Plus,
|
|
||||||
tr("Add to playlist…"),
|
|
||||||
Some(Message::OpenSheet(Sheet::Track { track: track.clone(), playlist: *playlist, choosing: true })),
|
|
||||||
),
|
|
||||||
item(t, Icon::Wave, tr("Play similar tracks"), Some(Message::PlaySimilar(track.clone()))),
|
|
||||||
];
|
|
||||||
if let Some(album) = &track.album {
|
|
||||||
items.push(item(t, Icon::Disc, tr("Go to album"), Some(Message::Navigate(Route::Album(album.id)))));
|
|
||||||
}
|
|
||||||
for artist in track.artists.iter().filter(|a| a.id.is_some()).take(3) {
|
|
||||||
items.push(item(
|
|
||||||
t,
|
|
||||||
Icon::Forward,
|
|
||||||
tr("Go to artist"),
|
|
||||||
artist.id.map(|id| Message::Navigate(Route::Artist(id))),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
items.push(item(
|
|
||||||
t,
|
|
||||||
Icon::Dislike,
|
|
||||||
if ctx.disliked { tr("Recommend this track again") } else { tr("Don't recommend this track") },
|
|
||||||
Some(Message::DislikeTrack(track.clone(), !ctx.disliked)),
|
|
||||||
));
|
|
||||||
if let Some((id, index, len)) = *playlist {
|
|
||||||
items.push(divider());
|
|
||||||
if index > 0 {
|
|
||||||
items.push(item(t, Icon::Back, tr("Move up"), Some(Message::MovePlaylistTrack {
|
|
||||||
id, track: track.clone(), from: index, to: index - 1,
|
|
||||||
})));
|
|
||||||
}
|
|
||||||
if index + 1 < len {
|
|
||||||
items.push(item(t, Icon::Forward, tr("Move down"), Some(Message::MovePlaylistTrack {
|
|
||||||
id, track: track.clone(), from: index, to: index + 1,
|
|
||||||
})));
|
|
||||||
}
|
|
||||||
items.push(item(t, Icon::Trash, tr("Remove from this playlist"), Some(Message::RemoveFromPlaylist(id, index))));
|
|
||||||
}
|
|
||||||
frame(t, track.full_title(), Some(track.artist_line()), Column::with_children(items).spacing(2).into())
|
|
||||||
}
|
|
||||||
Sheet::Track { track, choosing: true, .. } => {
|
|
||||||
let mut items: Vec<Element<'a, Message>> = vec![item(
|
|
||||||
t,
|
|
||||||
Icon::Plus,
|
|
||||||
tr("New playlist…"),
|
|
||||||
Some(Message::OpenSheet(Sheet::NewPlaylist { name: String::new(), add: Some(track.clone()) })),
|
|
||||||
)];
|
|
||||||
items.extend(ctx.own_playlists.iter().map(|p| {
|
|
||||||
item(t, Icon::Queue, &p.title, Some(Message::AddToPlaylist(p.id, track.clone())))
|
|
||||||
}));
|
|
||||||
frame(
|
|
||||||
t,
|
|
||||||
tr("Add to playlist").into(),
|
|
||||||
Some(track.full_title()),
|
|
||||||
iced::widget::scrollable(Column::with_children(items).spacing(2)).height(Length::Shrink).into(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Sheet::NewPlaylist { name, add } => {
|
Sheet::NewPlaylist { name, add } => {
|
||||||
let can = !name.trim().is_empty();
|
let can = !name.trim().is_empty();
|
||||||
let hint = if add.is_some() { tr("The track goes in once it's created.") } else { tr("Only you can see it until you make it public.") };
|
let hint = if add.is_some() { tr("The track goes in once it's created.") } else { tr("Only you can see it until you make it public.") };
|
||||||
@@ -198,19 +110,6 @@ fn frame<'a>(t: &'static Tokens, title: String, subtitle: Option<String>, conten
|
|||||||
.into()
|
.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn item<'a>(t: &'static Tokens, glyph: Icon, label: &str, msg: Option<Message>) -> Element<'a, Message> {
|
|
||||||
button(row![icon(glyph, t.muted), line(label.to_owned(), theme::MEDIUM, size::BODY, t.fg)].spacing(12).align_y(Alignment::Center))
|
|
||||||
.width(Fill)
|
|
||||||
.padding([9, 10])
|
|
||||||
.style(theme::nav_item(false))
|
|
||||||
.on_press_maybe(msg)
|
|
||||||
.into()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn divider<'a>() -> Element<'a, Message> {
|
|
||||||
container(space()).width(Fill).height(1).style(theme::divider).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn input<'a>(placeholder: &'a str, value: &'a str, submit: Option<Message>) -> Element<'a, Message> {
|
fn input<'a>(placeholder: &'a str, value: &'a str, submit: Option<Message>) -> Element<'a, Message> {
|
||||||
text_input(placeholder, value)
|
text_input(placeholder, value)
|
||||||
.id(INPUT_ID)
|
.id(INPUT_ID)
|
||||||
@@ -271,40 +170,3 @@ pub fn toast<'a>(t: &'static Tokens, text: &'a str) -> Element<'a, Message> {
|
|||||||
.padding(iced::Padding::default().bottom(96))
|
.padding(iced::Padding::default().bottom(96))
|
||||||
.into()
|
.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use crate::ui::theme::DARK;
|
|
||||||
|
|
||||||
fn track_sheet() -> Sheet {
|
|
||||||
let track = Track::from_json(r#"{"id":"7","title":"Хочешь?","artists":[{"id":3,"name":"Земфира"}],"albums":[{"id":5,"title":"A"}]}"#).unwrap();
|
|
||||||
Sheet::Track { track, playlist: None, choosing: false }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn click(label: &str) -> Vec<String> {
|
|
||||||
let sheet = track_sheet();
|
|
||||||
let mut ui = iced_test::simulator(overlay(&DARK, &sheet, Ctx { playing: false, liked: false, disliked: false, own_playlists: &[] }));
|
|
||||||
ui.click(label).unwrap_or_else(|e| panic!("can't click {label}: {e:?}"));
|
|
||||||
ui.into_messages().map(|m| format!("{m:?}").chars().take(40).collect()).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn menu_for_the_playing_track_offers_next_track() {
|
|
||||||
let sheet = track_sheet();
|
|
||||||
let mut ui = iced_test::simulator(overlay(&DARK, &sheet, Ctx { playing: true, liked: false, disliked: false, own_playlists: &[] }));
|
|
||||||
assert!(ui.find("Play next").is_err());
|
|
||||||
ui.click("Next track").expect("next track item");
|
|
||||||
let messages: Vec<String> = ui.into_messages().map(|m| format!("{m:?}")).collect();
|
|
||||||
assert_eq!(messages, ["SkipFromMenu"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn menu_items_send_their_action_and_not_close() {
|
|
||||||
for (label, expected) in [("Play next", "PlayNext("), ("Add to queue", "AddToQueue("), ("Go to album", "Navigate(Album(5))"), ("Play similar tracks", "PlaySimilar(")] {
|
|
||||||
let messages = click(label);
|
|
||||||
assert!(messages.first().is_some_and(|m| m.starts_with(expected)), "{label}: {messages:?}");
|
|
||||||
assert!(!messages.iter().any(|m| m.starts_with("CloseSheet")), "{label} also closed the sheet: {messages:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -10,7 +10,7 @@ use ym_api::{LikedIds, PlaylistId, Track};
|
|||||||
use crate::app::Message;
|
use crate::app::Message;
|
||||||
use crate::covers::{self, Covers};
|
use crate::covers::{self, Covers};
|
||||||
use crate::screens::collection::Liked;
|
use crate::screens::collection::Liked;
|
||||||
use crate::widgets::sheet::Sheet;
|
use crate::widgets::menu::{Source, Target};
|
||||||
use crate::ui::theme::{self, Tokens, radius};
|
use crate::ui::theme::{self, Tokens, radius};
|
||||||
use crate::widgets::track_row::{self, Columns};
|
use crate::widgets::track_row::{self, Columns};
|
||||||
|
|
||||||
@@ -24,6 +24,29 @@ pub struct Env<'a> {
|
|||||||
pub playing: Option<&'a str>,
|
pub playing: Option<&'a str>,
|
||||||
/// The signed-in user's uid, to tell their own playlists apart.
|
/// The signed-in user's uid, to tell their own playlists apart.
|
||||||
pub me: i64,
|
pub me: i64,
|
||||||
|
/// The track whose menu is open; its rows stay lit.
|
||||||
|
pub menu_track: Option<&'a str>,
|
||||||
|
pub drag: Option<&'a Drag>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A row of an own playlist on its way to a new place.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Drag {
|
||||||
|
pub playlist: PlaylistId,
|
||||||
|
pub track: Track,
|
||||||
|
/// Where it was when picked up, and where it would land now.
|
||||||
|
pub from: usize,
|
||||||
|
pub to: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `items` with the one at `from` moved to `to`.
|
||||||
|
pub fn moved<T: Clone>(items: &[T], from: usize, to: usize) -> Arc<[T]> {
|
||||||
|
let mut v = items.to_vec();
|
||||||
|
if from < v.len() {
|
||||||
|
let item = v.remove(from);
|
||||||
|
v.insert(to.min(v.len()), item);
|
||||||
|
}
|
||||||
|
v.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Hash)]
|
#[derive(Hash)]
|
||||||
@@ -37,6 +60,9 @@ struct Key {
|
|||||||
dark: bool,
|
dark: bool,
|
||||||
playlist: Option<PlaylistId>,
|
playlist: Option<PlaylistId>,
|
||||||
lang: crate::i18n::Lang,
|
lang: crate::i18n::Lang,
|
||||||
|
menu: Option<String>,
|
||||||
|
/// `(from, to)` while a row of this list is dragged.
|
||||||
|
drag: Option<(usize, usize)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn view<'a>(env: Env<'a>, tracks: &Arc<[Track]>, columns: Columns) -> Element<'a, Message> {
|
pub fn view<'a>(env: Env<'a>, tracks: &Arc<[Track]>, columns: Columns) -> Element<'a, Message> {
|
||||||
@@ -55,7 +81,7 @@ pub fn view_with<'a>(
|
|||||||
|
|
||||||
/// One of the user's own playlists: rows get move and remove actions.
|
/// One of the user's own playlists: rows get move and remove actions.
|
||||||
pub fn view_own_playlist<'a>(env: Env<'a>, tracks: &Arc<[Track]>, id: PlaylistId) -> Element<'a, Message> {
|
pub fn view_own_playlist<'a>(env: Env<'a>, tracks: &Arc<[Track]>, id: PlaylistId) -> Element<'a, Message> {
|
||||||
build(env, tracks, Columns::FULL, None, Some(id))
|
build(env, tracks, Columns::OWN_PLAYLIST, None, Some(id))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn build<'a>(
|
fn build<'a>(
|
||||||
@@ -65,7 +91,8 @@ fn build<'a>(
|
|||||||
shifts: Option<Arc<[i32]>>,
|
shifts: Option<Arc<[i32]>>,
|
||||||
playlist: Option<PlaylistId>,
|
playlist: Option<PlaylistId>,
|
||||||
) -> Element<'a, Message> {
|
) -> Element<'a, Message> {
|
||||||
let Env { t, covers, liked, playing, .. } = env;
|
let Env { t, covers, liked, playing, menu_track, drag, .. } = env;
|
||||||
|
let drag = drag.filter(|d| playlist == Some(d.playlist)).map(|d| (d.from, d.to));
|
||||||
let key = Key {
|
let key = Key {
|
||||||
list: (tracks.as_ptr() as usize, tracks.len()),
|
list: (tracks.as_ptr() as usize, tracks.len()),
|
||||||
columns,
|
columns,
|
||||||
@@ -76,11 +103,19 @@ fn build<'a>(
|
|||||||
dark: t == &theme::DARK,
|
dark: t == &theme::DARK,
|
||||||
playlist,
|
playlist,
|
||||||
lang: crate::i18n::lang(),
|
lang: crate::i18n::lang(),
|
||||||
|
menu: menu_track.filter(|id| tracks.iter().any(|tr| tr.id == *id)).map(str::to_owned),
|
||||||
|
drag,
|
||||||
|
};
|
||||||
|
// While dragging, the list shows the order it would have if dropped now.
|
||||||
|
let shown = match drag {
|
||||||
|
Some((from, to)) => moved(tracks, from, to),
|
||||||
|
None => tracks.clone(),
|
||||||
};
|
};
|
||||||
let tracks = tracks.clone();
|
let tracks = tracks.clone();
|
||||||
|
|
||||||
lazy(key, move |key: &Key| {
|
lazy(key, move |key: &Key| {
|
||||||
let rows = tracks.iter().enumerate().map(|(index, track)| {
|
let rows = shown.iter().enumerate().map(|(index, track)| {
|
||||||
|
let dragged = key.drag.is_some_and(|(_, to)| to == index);
|
||||||
let cover = columns.cover.then(|| {
|
let cover = columns.cover.then(|| {
|
||||||
covers::view(covers, track.cover_url(covers::SMALL), track.hues(), 40.0, radius::SMALL_COVER)
|
covers::view(covers, track.cover_url(covers::SMALL), track.hues(), 40.0, radius::SMALL_COVER)
|
||||||
});
|
});
|
||||||
@@ -92,11 +127,16 @@ fn build<'a>(
|
|||||||
playing: key.playing.as_deref() == Some(track.id.as_str()),
|
playing: key.playing.as_deref() == Some(track.id.as_str()),
|
||||||
liked: liked.contains(&track.id),
|
liked: liked.contains(&track.id),
|
||||||
on_like: Message::LikeTrack(track.clone(), !liked.contains(&track.id)),
|
on_like: Message::LikeTrack(track.clone(), !liked.contains(&track.id)),
|
||||||
on_more: Message::OpenSheet(Sheet::Track {
|
menu: Target::Track {
|
||||||
track: track.clone(),
|
track: track.clone(),
|
||||||
playlist: key.playlist.map(|id| (id, index, tracks.len())),
|
from: Source::List { playlist: key.playlist.map(|id| (id, index, tracks.len())) },
|
||||||
choosing: false,
|
},
|
||||||
}),
|
lit: dragged || key.menu.as_deref() == Some(track.id.as_str()),
|
||||||
|
on_grip: match (key.playlist, key.drag) {
|
||||||
|
(Some(playlist), None) => Some(Message::DragStart { playlist, track: track.clone(), index }),
|
||||||
|
_ => None,
|
||||||
|
},
|
||||||
|
on_drag_over: key.drag.map(|_| Message::DragOver(index)),
|
||||||
cover,
|
cover,
|
||||||
columns,
|
columns,
|
||||||
shift: shifts.as_ref().and_then(|s| s.get(index).copied()).unwrap_or(0),
|
shift: shifts.as_ref().and_then(|s| s.get(index).copied()).unwrap_or(0),
|
||||||
@@ -108,3 +148,16 @@ fn build<'a>(
|
|||||||
})
|
})
|
||||||
.into()
|
.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::moved;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn moving_an_item_shifts_the_ones_between() {
|
||||||
|
assert_eq!(&*moved(&[0, 1, 2, 3, 4], 1, 3), &[0, 2, 3, 1, 4]);
|
||||||
|
assert_eq!(&*moved(&[0, 1, 2, 3, 4], 3, 0), &[3, 0, 1, 2, 4]);
|
||||||
|
assert_eq!(&*moved(&[0, 1, 2], 2, 2), &[0, 1, 2]);
|
||||||
|
assert_eq!(&*moved(&[0, 1, 2], 0, 9), &[1, 2, 0], "past the end lands last");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,14 @@
|
|||||||
//! One row in a track list: number (or a playing marker), cover, title and
|
//! One row in a track list: number (or a playing marker), cover, title and
|
||||||
//! artists, album, like state, duration. Clicking anywhere plays it.
|
//! artists, album, like state, duration. Clicking anywhere plays it; a
|
||||||
|
//! right-click or the "…" button opens its menu.
|
||||||
|
|
||||||
use iced::widget::{button, column, container, row, space};
|
use iced::widget::{button, column, container, mouse_area, row, space};
|
||||||
use iced::{Alignment, Element, Fill, Length};
|
use iced::{Alignment, Element, Fill, Length, mouse};
|
||||||
use ym_api::Track;
|
use ym_api::Track;
|
||||||
|
|
||||||
use crate::app::Message;
|
use crate::app::Message;
|
||||||
|
use crate::widgets::anchor::anchor;
|
||||||
|
use crate::widgets::menu::{Anchor, Menu, Target};
|
||||||
use crate::ui::icons::{Icon, icon, sized};
|
use crate::ui::icons::{Icon, icon, sized};
|
||||||
use crate::ui::line;
|
use crate::ui::line;
|
||||||
use crate::ui::theme::{self, Tokens, size};
|
use crate::ui::theme::{self, Tokens, size};
|
||||||
@@ -21,14 +24,21 @@ pub struct Columns {
|
|||||||
pub album: bool,
|
pub album: bool,
|
||||||
/// Chart lists show how far each track moved.
|
/// Chart lists show how far each track moved.
|
||||||
pub shift: bool,
|
pub shift: bool,
|
||||||
|
/// The user's own playlists: a handle to drag rows into a new order.
|
||||||
|
pub grip: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Columns {
|
impl Columns {
|
||||||
pub const FULL: Columns = Columns { cover: true, album: true, shift: false };
|
pub const FULL: Columns = Columns { cover: true, album: true, shift: false, grip: false };
|
||||||
pub const ALBUM_PAGE: Columns = Columns { cover: false, album: false, shift: false };
|
pub const ALBUM_PAGE: Columns = Columns { cover: false, album: false, shift: false, grip: false };
|
||||||
pub const CHART: Columns = Columns { cover: true, album: true, shift: true };
|
pub const CHART: Columns = Columns { cover: true, album: true, shift: true, grip: false };
|
||||||
|
pub const OWN_PLAYLIST: Columns = Columns { grip: true, ..Columns::FULL };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const GRIP: f32 = 20.0;
|
||||||
|
/// The heart button's width: an icon and its padding.
|
||||||
|
const LIKE_SLOT: f32 = theme::shell::ICON + 16.0;
|
||||||
|
|
||||||
pub struct Row<'a> {
|
pub struct Row<'a> {
|
||||||
pub index: usize,
|
pub index: usize,
|
||||||
pub track: &'a Track,
|
pub track: &'a Track,
|
||||||
@@ -40,7 +50,14 @@ pub struct Row<'a> {
|
|||||||
pub shift: i32,
|
pub shift: i32,
|
||||||
pub on_press: Message,
|
pub on_press: Message,
|
||||||
pub on_like: Message,
|
pub on_like: Message,
|
||||||
pub on_more: Message,
|
/// What the row's menu is for.
|
||||||
|
pub menu: Target,
|
||||||
|
/// Held lit: its menu is open, or it's the row being dragged.
|
||||||
|
pub lit: bool,
|
||||||
|
/// Pressing the drag handle (own playlists, when no drag is under way).
|
||||||
|
pub on_grip: Option<Message>,
|
||||||
|
/// While a row is being dragged: the pointer reached this one.
|
||||||
|
pub on_drag_over: Option<Message>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds an owned (`'static`) row so lists can sit inside `lazy`.
|
/// Builds an owned (`'static`) row so lists can sit inside `lazy`.
|
||||||
@@ -59,10 +76,16 @@ pub fn view(t: &'static Tokens, r: Row<'_>) -> Element<'static, Message> {
|
|||||||
(false, false) => t.fg,
|
(false, false) => t.fg,
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut content = row![container(number).width(36).center_x(36)]
|
let mut content = row![].spacing(12).align_y(Alignment::Center).height(HEIGHT);
|
||||||
.spacing(12)
|
if r.columns.grip {
|
||||||
.align_y(Alignment::Center)
|
let grip = container(icon(Icon::Grip, if r.lit { t.fg } else { t.muted })).width(GRIP).center_x(GRIP);
|
||||||
.height(HEIGHT);
|
let grip = mouse_area(grip).interaction(mouse::Interaction::Grab);
|
||||||
|
content = content.push(match r.on_grip {
|
||||||
|
Some(msg) => grip.on_press(msg),
|
||||||
|
None => grip,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
content = content.push(container(number).width(36).center_x(36));
|
||||||
if r.columns.shift {
|
if r.columns.shift {
|
||||||
content = content.push(crate::screens::browse::shift_marker(t, r.shift));
|
content = content.push(crate::screens::browse::shift_marker(t, r.shift));
|
||||||
}
|
}
|
||||||
@@ -81,7 +104,7 @@ pub fn view(t: &'static Tokens, r: Row<'_>) -> Element<'static, Message> {
|
|||||||
if r.columns.album {
|
if r.columns.album {
|
||||||
content = content.push(
|
content = content.push(
|
||||||
container(line(
|
container(line(
|
||||||
track.album.as_ref().map(|a| a.title.clone()).unwrap_or_default(),
|
track.album_title().unwrap_or_default().to_owned(),
|
||||||
theme::BODY,
|
theme::BODY,
|
||||||
size::META,
|
size::META,
|
||||||
t.muted,
|
t.muted,
|
||||||
@@ -90,43 +113,55 @@ pub fn view(t: &'static Tokens, r: Row<'_>) -> Element<'static, Message> {
|
|||||||
.clip(true),
|
.clip(true),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
content = content
|
// Server tracks can't be liked; an empty slot keeps the columns lined up.
|
||||||
.push(
|
let heart: Element<'static, Message> = if track.is_yandex() {
|
||||||
button(icon(
|
button(icon(
|
||||||
if r.liked { Icon::HeartFilled } else { Icon::Heart },
|
if r.liked { Icon::HeartFilled } else { Icon::Heart },
|
||||||
if r.liked { t.like } else { t.muted.scale_alpha(0.35) },
|
if r.liked { t.like } else { t.muted.scale_alpha(0.35) },
|
||||||
))
|
))
|
||||||
.padding(8)
|
.padding(8)
|
||||||
.style(theme::icon_button(None))
|
.style(theme::icon_button(None))
|
||||||
.on_press(r.on_like),
|
.on_press(r.on_like)
|
||||||
)
|
.into()
|
||||||
|
} else {
|
||||||
|
space().width(LIKE_SLOT).into()
|
||||||
|
};
|
||||||
|
content = content
|
||||||
|
.push(heart)
|
||||||
.push(
|
.push(
|
||||||
container(line(clock(track.duration.as_secs_f32()), theme::BODY, size::META, t.muted))
|
container(line(clock(track.duration.as_secs_f32()), theme::BODY, size::META, t.muted))
|
||||||
.width(52)
|
.width(52)
|
||||||
.align_right(52),
|
.align_right(52),
|
||||||
)
|
)
|
||||||
.push(
|
.push({
|
||||||
button(icon(Icon::More, t.muted))
|
let target = r.menu.clone();
|
||||||
.padding(8)
|
// The anchor takes the click and reports where the button is; `on_press`
|
||||||
.style(theme::icon_button(None))
|
// only keeps the hover style, and its message is never sent.
|
||||||
.on_press(r.on_more),
|
anchor(button(icon(Icon::More, t.muted)).padding(8).style(theme::icon_button(None)).on_press(Message::CloseMenu))
|
||||||
);
|
.on_press(move |bounds| Message::OpenMenu(Box::new(Menu::new(target.clone(), Anchor::Below(bounds)))))
|
||||||
|
});
|
||||||
|
|
||||||
button(content)
|
let row = button(content)
|
||||||
.width(Fill)
|
.width(Fill)
|
||||||
.padding([0, 10])
|
.padding([0, 10])
|
||||||
.style(theme::nav_item(false))
|
.style(theme::nav_item(r.lit))
|
||||||
.on_press_maybe((!unavailable).then_some(r.on_press))
|
.on_press_maybe((!unavailable && r.on_drag_over.is_none()).then_some(r.on_press));
|
||||||
.into()
|
let target = r.menu;
|
||||||
|
let row = anchor(row).on_right_press(move |at| Message::OpenMenu(Box::new(Menu::new(target.clone(), Anchor::Point(at)))));
|
||||||
|
match r.on_drag_over {
|
||||||
|
Some(msg) => mouse_area(row).on_enter(msg).interaction(mouse::Interaction::Grabbing).into(),
|
||||||
|
None => row.into(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Column headings above a track list, aligned with [`view`].
|
/// Column headings above a track list, aligned with [`view`].
|
||||||
pub fn header(t: &'static Tokens, columns: Columns) -> Element<'static, Message> {
|
pub fn header(t: &'static Tokens, columns: Columns) -> Element<'static, Message> {
|
||||||
let label = |s: &'static str| line(s, theme::BODY, size::SMALL, t.muted);
|
let label = |s: &'static str| line(s, theme::BODY, size::SMALL, t.muted);
|
||||||
let mut heads = row![container(label("#")).width(36).center_x(36)]
|
let mut heads = row![].spacing(12).align_y(Alignment::Center).padding([0, 10]);
|
||||||
.spacing(12)
|
if columns.grip {
|
||||||
.align_y(Alignment::Center)
|
heads = heads.push(space().width(GRIP));
|
||||||
.padding([0, 10]);
|
}
|
||||||
|
heads = heads.push(container(label("#")).width(36).center_x(36));
|
||||||
if columns.shift {
|
if columns.shift {
|
||||||
heads = heads.push(space().width(14));
|
heads = heads.push(space().width(14));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
[package]
|
||||||
|
name = "subsonic-api"
|
||||||
|
description = "Client for Subsonic-compatible music servers such as Navidrome"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
publish.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
serde_json = "1"
|
||||||
|
thiserror = "2"
|
||||||
|
md-5 = "0.10"
|
||||||
|
rand = "0.9"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
@@ -0,0 +1,584 @@
|
|||||||
|
//! Requests, authentication and the `subsonic-response` envelope.
|
||||||
|
|
||||||
|
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use md5::{Digest, Md5};
|
||||||
|
use rand::Rng;
|
||||||
|
use rand::distr::Alphanumeric;
|
||||||
|
use reqwest::Url;
|
||||||
|
use serde::de::DeserializeOwned;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::models::{
|
||||||
|
self, Album, AlbumSummary, Artist, ArtistSummary, Playlist, PlaylistSummary, RawAlbum, RawArtist,
|
||||||
|
RawIndex, RawMixed, RawPlaylist, SearchResults, Song,
|
||||||
|
};
|
||||||
|
use crate::{Error, Result};
|
||||||
|
|
||||||
|
/// The REST version Musyx speaks. 1.13 added token auth; 1.16.1 is what Navidrome reports.
|
||||||
|
const API_VERSION: &str = "1.16.1";
|
||||||
|
const CLIENT_NAME: &str = "musyx";
|
||||||
|
const API_TIMEOUT: Duration = Duration::from_secs(30);
|
||||||
|
/// Whole files are downloaded before playback; a long FLAC on a slow link takes a while.
|
||||||
|
const STREAM_TIMEOUT: Duration = Duration::from_secs(300);
|
||||||
|
|
||||||
|
/// What the user types to connect. Stored in the system keychain as JSON.
|
||||||
|
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Config {
|
||||||
|
pub url: String,
|
||||||
|
pub username: String,
|
||||||
|
pub password: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The password stays out of logs.
|
||||||
|
impl std::fmt::Debug for Config {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("Config").field("url", &self.url).field("username", &self.username).finish_non_exhaustive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Config {
|
||||||
|
/// The server's `/rest/` base. Accepts what people paste: no scheme
|
||||||
|
/// (`music.example.com` means https), trailing slashes, or the web UI's
|
||||||
|
/// own address (`…/app/#/album/…`).
|
||||||
|
pub fn rest_base(&self) -> Result<Url> {
|
||||||
|
let raw = self.url.trim();
|
||||||
|
if raw.is_empty() {
|
||||||
|
return Err(Error::InvalidUrl("empty".into()));
|
||||||
|
}
|
||||||
|
let with_scheme = if raw.contains("://") { raw.to_owned() } else { format!("https://{raw}") };
|
||||||
|
let mut url = Url::parse(&with_scheme).map_err(|e| Error::InvalidUrl(e.to_string()))?;
|
||||||
|
if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
|
||||||
|
return Err(Error::InvalidUrl(format!("unsupported address {raw}")));
|
||||||
|
}
|
||||||
|
url.set_query(None);
|
||||||
|
url.set_fragment(None);
|
||||||
|
let mut path = format!("{}/", url.path().trim_end_matches('/'));
|
||||||
|
// Everything from a pasted API path (`/rest/ping`) or the web UI (`/app/`) on.
|
||||||
|
for marker in ["/rest/", "/app/"] {
|
||||||
|
if let Some(i) = path.find(marker) {
|
||||||
|
path.truncate(i + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let path = path.trim_end_matches('/');
|
||||||
|
url.set_path(&format!("{path}/rest/"));
|
||||||
|
Ok(url)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How to ask for a song's audio: the file as stored, when the player decodes
|
||||||
|
/// it and it fits the quality cap, or an MP3 the server transcodes.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct StreamPlan {
|
||||||
|
pub transcode: bool,
|
||||||
|
/// The cap sent as `maxBitRate`; also the label's bitrate when transcoding.
|
||||||
|
pub max_kbps: Option<u32>,
|
||||||
|
/// "mp3", "flac" or "aac-mp4", the codec names the player's decoder expects.
|
||||||
|
pub codec: &'static str,
|
||||||
|
pub bitrate_kbps: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StreamPlan {
|
||||||
|
/// `max_kbps: None` means no cap; `lossless` lets FLAC through untouched.
|
||||||
|
pub fn for_song(suffix: &str, bit_rate: u32, max_kbps: Option<u32>, lossless: bool) -> Self {
|
||||||
|
// Unknown bitrates only pass when there's no cap to break.
|
||||||
|
let fits = max_kbps.is_none_or(|cap| bit_rate != 0 && bit_rate <= cap);
|
||||||
|
let raw = |codec, bitrate_kbps| StreamPlan { transcode: false, max_kbps: None, codec, bitrate_kbps };
|
||||||
|
match suffix {
|
||||||
|
"flac" if lossless => raw("flac", 0),
|
||||||
|
"mp3" if fits => raw("mp3", bit_rate),
|
||||||
|
"m4a" | "mp4" if fits => raw("aac-mp4", bit_rate),
|
||||||
|
_ => {
|
||||||
|
let cap = max_kbps.unwrap_or(320).min(320);
|
||||||
|
StreamPlan { transcode: true, max_kbps: Some(cap), codec: "mp3", bitrate_kbps: cap }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A downloaded song, ready for the decoder.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Audio {
|
||||||
|
pub bytes: Vec<u8>,
|
||||||
|
pub codec: &'static str,
|
||||||
|
pub bitrate_kbps: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for Audio {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("Audio")
|
||||||
|
.field("codec", &self.codec)
|
||||||
|
.field("bitrate_kbps", &self.bitrate_kbps)
|
||||||
|
.field("bytes", &self.bytes.len())
|
||||||
|
.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||||
|
pub enum AlbumSort {
|
||||||
|
/// Recently added to the library.
|
||||||
|
#[default]
|
||||||
|
Newest,
|
||||||
|
AlphabeticalByName,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AlbumSort {
|
||||||
|
fn param(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
AlbumSort::Newest => "newest",
|
||||||
|
AlbumSort::AlphabeticalByName => "alphabeticalByName",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A signed-in connection. Cheap to clone: the HTTP pool is shared.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Client {
|
||||||
|
http: reqwest::Client,
|
||||||
|
base: Url,
|
||||||
|
username: String,
|
||||||
|
password: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for Client {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("Client").field("base", &self.base.as_str()).field("username", &self.username).finish_non_exhaustive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialEq for Client {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
self.base == other.base && self.username == other.username && self.password == other.password
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Client {
|
||||||
|
/// Builds the client; nothing is sent until the first call (see [`Client::ping`]).
|
||||||
|
pub fn new(config: &Config) -> Result<Self> {
|
||||||
|
let base = config.rest_base()?;
|
||||||
|
let http = reqwest::Client::builder()
|
||||||
|
.connect_timeout(Duration::from_secs(10))
|
||||||
|
.user_agent(concat!("musyx/", env!("CARGO_PKG_VERSION")))
|
||||||
|
.build()
|
||||||
|
.map_err(|e| Error::Network(e.to_string()))?;
|
||||||
|
Ok(Self { http, base, username: config.username.trim().to_owned(), password: config.password.clone() })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn username(&self) -> &str {
|
||||||
|
&self.username
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `music.example.com` or `10.0.0.2:4533`, for display.
|
||||||
|
pub fn host(&self) -> String {
|
||||||
|
let host = self.base.host_str().unwrap_or_default();
|
||||||
|
match self.base.port() {
|
||||||
|
Some(port) => format!("{host}:{port}"),
|
||||||
|
None => host.to_owned(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn url(&self, method: &str, params: &[(&str, &str)]) -> Url {
|
||||||
|
let salt: String = rand::rng().sample_iter(Alphanumeric).take(12).map(char::from).collect();
|
||||||
|
self.url_with_salt(method, params, &salt)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Token auth: `t = md5(password + salt)`, so the password never travels.
|
||||||
|
fn url_with_salt(&self, method: &str, params: &[(&str, &str)], salt: &str) -> Url {
|
||||||
|
let mut url = self.base.join(method).expect("method names are plain path segments");
|
||||||
|
url.query_pairs_mut()
|
||||||
|
.append_pair("u", &self.username)
|
||||||
|
.append_pair("t", &token(&self.password, salt))
|
||||||
|
.append_pair("s", salt)
|
||||||
|
.append_pair("v", API_VERSION)
|
||||||
|
.append_pair("c", CLIENT_NAME)
|
||||||
|
.append_pair("f", "json")
|
||||||
|
.extend_pairs(params);
|
||||||
|
url
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn call<T: DeserializeOwned>(&self, method: &str, params: &[(&str, &str)]) -> Result<T> {
|
||||||
|
let body = self
|
||||||
|
.http
|
||||||
|
.get(self.url(method, params))
|
||||||
|
.timeout(API_TIMEOUT)
|
||||||
|
.send()
|
||||||
|
.await?
|
||||||
|
.error_for_status()?
|
||||||
|
.text()
|
||||||
|
.await?;
|
||||||
|
unwrap_envelope(&body)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Endpoints that answer with a file, or with an error envelope.
|
||||||
|
async fn bytes(&self, method: &str, params: &[(&str, &str)], timeout: Duration) -> Result<Vec<u8>> {
|
||||||
|
let reply = self.http.get(self.url(method, params)).timeout(timeout).send().await?.error_for_status()?;
|
||||||
|
let is_envelope = reply
|
||||||
|
.headers()
|
||||||
|
.get(reqwest::header::CONTENT_TYPE)
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.is_some_and(|ct| ct.contains("json") || ct.contains("xml"));
|
||||||
|
let body = reply.bytes().await?;
|
||||||
|
if is_envelope {
|
||||||
|
let text = String::from_utf8_lossy(&body);
|
||||||
|
unwrap_envelope::<serde_json::Value>(&text)?;
|
||||||
|
return Err(Error::Api(format!("{method} answered with a message instead of a file")));
|
||||||
|
}
|
||||||
|
Ok(body.to_vec())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks the address and the credentials.
|
||||||
|
pub async fn ping(&self) -> Result<()> {
|
||||||
|
self.call::<serde_json::Value>("ping", &[]).await.map(drop)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn albums(&self, sort: AlbumSort, offset: usize, size: usize) -> Result<Vec<AlbumSummary>> {
|
||||||
|
let (offset, size) = (offset.to_string(), size.to_string());
|
||||||
|
let reply: AlbumListReply = self
|
||||||
|
.call("getAlbumList2", &[("type", sort.param()), ("offset", &offset), ("size", &size)])
|
||||||
|
.await?;
|
||||||
|
Ok(reply.resolve())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn album(&self, id: &str) -> Result<Album> {
|
||||||
|
let reply: AlbumReply = self.call("getAlbum", &[("id", id)]).await?;
|
||||||
|
reply.resolve()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn artists(&self) -> Result<Vec<ArtistSummary>> {
|
||||||
|
let reply: ArtistsReply = self.call("getArtists", &[]).await?;
|
||||||
|
Ok(reply.resolve())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn artist(&self, id: &str) -> Result<Artist> {
|
||||||
|
let reply: ArtistReply = self.call("getArtist", &[("id", id)]).await?;
|
||||||
|
reply.resolve()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn playlists(&self) -> Result<Vec<PlaylistSummary>> {
|
||||||
|
let reply: PlaylistsReply = self.call("getPlaylists", &[]).await?;
|
||||||
|
Ok(reply.resolve())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn playlist(&self, id: &str) -> Result<Playlist> {
|
||||||
|
let reply: PlaylistReply = self.call("getPlaylist", &[("id", id)]).await?;
|
||||||
|
reply.resolve()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starred songs, newest first as the server orders them.
|
||||||
|
pub async fn starred(&self) -> Result<Vec<Song>> {
|
||||||
|
let reply: StarredReply = self.call("getStarred2", &[]).await?;
|
||||||
|
Ok(reply.starred.resolve().songs)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn search(&self, query: &str) -> Result<SearchResults> {
|
||||||
|
let reply: SearchReply = self
|
||||||
|
.call(
|
||||||
|
"search3",
|
||||||
|
&[("query", query.trim()), ("artistCount", "12"), ("albumCount", "24"), ("songCount", "60")],
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
Ok(reply.result.resolve())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cover image bytes at about `size` pixels square.
|
||||||
|
pub async fn cover_art(&self, id: &str, size: u32) -> Result<Vec<u8>> {
|
||||||
|
self.bytes("getCoverArt", &[("id", id), ("size", &size.to_string())], API_TIMEOUT).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Downloads a whole song as `plan` says.
|
||||||
|
pub async fn stream(&self, song_id: &str, plan: StreamPlan) -> Result<Audio> {
|
||||||
|
let cap = plan.max_kbps.map(|k| k.to_string());
|
||||||
|
let mut params = vec![("id", song_id), ("format", if plan.transcode { "mp3" } else { "raw" })];
|
||||||
|
if let Some(cap) = &cap {
|
||||||
|
params.push(("maxBitRate", cap));
|
||||||
|
}
|
||||||
|
let bytes = self.bytes("stream", ¶ms, STREAM_TIMEOUT).await?;
|
||||||
|
if bytes.is_empty() {
|
||||||
|
return Err(Error::Api("empty stream".into()));
|
||||||
|
}
|
||||||
|
Ok(Audio { bytes, codec: plan.codec, bitrate_kbps: plan.bitrate_kbps })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `submission: false` sets "now playing"; `true` records a play.
|
||||||
|
pub async fn scrobble(&self, song_id: &str, submission: bool) -> Result<()> {
|
||||||
|
let now = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis()).to_string();
|
||||||
|
let mut params = vec![("id", song_id), ("submission", if submission { "true" } else { "false" })];
|
||||||
|
if submission {
|
||||||
|
params.push(("time", &now));
|
||||||
|
}
|
||||||
|
self.call::<serde_json::Value>("scrobble", ¶ms).await.map(drop)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn token(password: &str, salt: &str) -> String {
|
||||||
|
format!("{:x}", Md5::digest(format!("{password}{salt}").as_bytes()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct Envelope {
|
||||||
|
#[serde(rename = "subsonic-response")]
|
||||||
|
response: serde_json::Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens `{"subsonic-response": {...}}`, turning `"status": "failed"` into an error.
|
||||||
|
fn unwrap_envelope<T: DeserializeOwned>(body: &str) -> Result<T> {
|
||||||
|
let Ok(Envelope { response }) = serde_json::from_str(body) else {
|
||||||
|
return Err(Error::Api("not a Subsonic server reply".into()));
|
||||||
|
};
|
||||||
|
if response.get("status").and_then(serde_json::Value::as_str) != Some("ok") {
|
||||||
|
let error = response.get("error");
|
||||||
|
let code = error.and_then(|e| e.get("code")).and_then(serde_json::Value::as_i64).unwrap_or(0);
|
||||||
|
let message =
|
||||||
|
error.and_then(|e| e.get("message")).and_then(serde_json::Value::as_str).unwrap_or("failed").to_owned();
|
||||||
|
return Err(Error::from_code(code, message));
|
||||||
|
}
|
||||||
|
serde_json::from_value(response).map_err(|e| Error::Api(e.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
struct AlbumList {
|
||||||
|
album: Vec<RawAlbum>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct AlbumListReply {
|
||||||
|
#[serde(rename = "albumList2", default)]
|
||||||
|
list: AlbumList,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AlbumListReply {
|
||||||
|
fn resolve(self) -> Vec<AlbumSummary> {
|
||||||
|
models::albums(self.list.album)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct AlbumReply {
|
||||||
|
album: RawAlbum,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AlbumReply {
|
||||||
|
fn resolve(self) -> Result<Album> {
|
||||||
|
self.album.resolve().ok_or_else(|| Error::Api("album without id".into()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
struct ArtistIndex {
|
||||||
|
index: Vec<RawIndex>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct ArtistsReply {
|
||||||
|
#[serde(default)]
|
||||||
|
artists: ArtistIndex,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ArtistsReply {
|
||||||
|
fn resolve(self) -> Vec<ArtistSummary> {
|
||||||
|
models::artists(self.artists.index.into_iter().flat_map(|i| i.artist).collect())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct ArtistReply {
|
||||||
|
artist: RawArtist,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ArtistReply {
|
||||||
|
fn resolve(self) -> Result<Artist> {
|
||||||
|
self.artist.resolve().ok_or_else(|| Error::Api("artist without id".into()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
struct PlaylistList {
|
||||||
|
playlist: Vec<RawPlaylist>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct PlaylistsReply {
|
||||||
|
#[serde(default)]
|
||||||
|
playlists: PlaylistList,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PlaylistsReply {
|
||||||
|
fn resolve(self) -> Vec<PlaylistSummary> {
|
||||||
|
models::playlists(self.playlists.playlist)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct PlaylistReply {
|
||||||
|
playlist: RawPlaylist,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PlaylistReply {
|
||||||
|
fn resolve(self) -> Result<Playlist> {
|
||||||
|
self.playlist.resolve().ok_or_else(|| Error::Api("playlist without id".into()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct StarredReply {
|
||||||
|
#[serde(rename = "starred2", default)]
|
||||||
|
starred: RawMixed,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct SearchReply {
|
||||||
|
#[serde(rename = "searchResult3", default)]
|
||||||
|
result: RawMixed,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn config(url: &str) -> Config {
|
||||||
|
Config { url: url.into(), username: "yp".into(), password: "sesame".into() }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ok(body: &str) -> String {
|
||||||
|
format!(r#"{{"subsonic-response":{{"status":"ok","version":"1.16.1",{body}}}}}"#)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn token_matches_the_subsonic_docs_example() {
|
||||||
|
assert_eq!(token("sesame", "c19b2d"), "26719a1196d2a940705a59634eb18eab");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn urls_carry_a_token_never_the_password() {
|
||||||
|
let client = Client::new(&config("https://music.example.com")).unwrap();
|
||||||
|
let url = client.url_with_salt("getAlbum", &[("id", "al 1")], "c19b2d");
|
||||||
|
assert_eq!(
|
||||||
|
url.as_str(),
|
||||||
|
"https://music.example.com/rest/getAlbum?u=yp&t=26719a1196d2a940705a59634eb18eab&s=c19b2d&v=1.16.1&c=musyx&f=json&id=al+1"
|
||||||
|
);
|
||||||
|
let fresh = client.url("ping", &[]);
|
||||||
|
assert!(!fresh.as_str().contains("sesame"));
|
||||||
|
assert!(!format!("{client:?}{:?}", config("x")).contains("sesame"), "password leaked into Debug");
|
||||||
|
assert_ne!(client.url("ping", &[]), fresh, "every request gets a new salt");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pasted_addresses_become_rest_bases() {
|
||||||
|
let base = |u: &str| config(u).rest_base().map(|u| u.to_string());
|
||||||
|
assert_eq!(base("music.example.com/").unwrap(), "https://music.example.com/rest/");
|
||||||
|
assert_eq!(base(" http://10.0.0.2:4533 ").unwrap(), "http://10.0.0.2:4533/rest/");
|
||||||
|
assert_eq!(base("https://example.com/music/app/#/album/1").unwrap(), "https://example.com/music/rest/");
|
||||||
|
assert_eq!(base("https://example.com/rest/ping?u=x").unwrap(), "https://example.com/rest/");
|
||||||
|
assert!(matches!(base(""), Err(Error::InvalidUrl(_))));
|
||||||
|
assert!(matches!(base("ftp://example.com"), Err(Error::InvalidUrl(_))));
|
||||||
|
let client = Client::new(&config("http://10.0.0.2:4533")).unwrap();
|
||||||
|
assert_eq!(client.host(), "10.0.0.2:4533");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn failed_envelopes_become_errors() {
|
||||||
|
let failed = r#"{"subsonic-response":{"status":"failed","version":"1.16.1",
|
||||||
|
"error":{"code":40,"message":"Wrong username or password"}}}"#;
|
||||||
|
assert_eq!(
|
||||||
|
unwrap_envelope::<serde_json::Value>(failed),
|
||||||
|
Err(Error::Unauthorized("Wrong username or password".into()))
|
||||||
|
);
|
||||||
|
assert!(matches!(unwrap_envelope::<serde_json::Value>("<html>Nginx</html>"), Err(Error::Api(_))));
|
||||||
|
assert!(unwrap_envelope::<serde_json::Value>(&ok(r#""type":"navidrome""#)).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn album_lists_and_albums_parse() {
|
||||||
|
let list: AlbumListReply = unwrap_envelope(&ok(
|
||||||
|
r#""albumList2":{"album":[{"id":"a1","name":"One","artist":"X","coverArt":"al-a1","songCount":2},
|
||||||
|
{"id":"a2","name":"Two"}]}"#,
|
||||||
|
))
|
||||||
|
.unwrap();
|
||||||
|
let list = list.resolve();
|
||||||
|
assert_eq!(list.iter().map(|a| a.id.as_str()).collect::<Vec<_>>(), ["a1", "a2"]);
|
||||||
|
assert_eq!(list[0].cover_art.as_deref(), Some("al-a1"));
|
||||||
|
let empty: AlbumListReply = unwrap_envelope(&ok(r#""albumList2":{}"#)).unwrap();
|
||||||
|
assert!(empty.resolve().is_empty(), "Navidrome omits empty arrays");
|
||||||
|
|
||||||
|
let album: AlbumReply = unwrap_envelope(&ok(
|
||||||
|
r#""album":{"id":"a1","name":"One","artist":"X","artistId":"ar1","year":2001,"duration":400,
|
||||||
|
"song":[{"id":"s1","title":"First","track":1,"duration":200,"suffix":"mp3","bitRate":320},
|
||||||
|
{"id":"s2","title":"Second","track":2,"duration":200,"suffix":"opus"}]}"#,
|
||||||
|
))
|
||||||
|
.unwrap();
|
||||||
|
let album = album.resolve().unwrap();
|
||||||
|
assert_eq!(album.info.subtitle(), "X · 2001");
|
||||||
|
assert_eq!(album.songs.len(), 2);
|
||||||
|
assert_eq!(album.songs[1].suffix, "opus");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn artists_flatten_the_index_and_artist_pages_list_albums() {
|
||||||
|
let artists: ArtistsReply = unwrap_envelope(&ok(
|
||||||
|
r#""artists":{"ignoredArticles":"The","index":[
|
||||||
|
{"name":"A","artist":[{"id":"ar1","name":"Aquarium","albumCount":3,"coverArt":"ar-ar1"}]},
|
||||||
|
{"name":"K","artist":[{"id":"ar2","name":"Kino"}]}]}"#,
|
||||||
|
))
|
||||||
|
.unwrap();
|
||||||
|
let artists = artists.resolve();
|
||||||
|
assert_eq!(artists.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), ["Aquarium", "Kino"]);
|
||||||
|
assert_eq!(artists[0].album_count, 3);
|
||||||
|
|
||||||
|
let artist: ArtistReply = unwrap_envelope(&ok(
|
||||||
|
r#""artist":{"id":"ar2","name":"Kino","album":[{"id":"a1","name":"45"},{"id":"a2","name":"Nachalnik Kamchatki"}]}"#,
|
||||||
|
))
|
||||||
|
.unwrap();
|
||||||
|
let artist = artist.resolve().unwrap();
|
||||||
|
assert_eq!(artist.info.name, "Kino");
|
||||||
|
assert_eq!(artist.albums.len(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn playlists_starred_and_search_parse() {
|
||||||
|
let lists: PlaylistsReply = unwrap_envelope(&ok(
|
||||||
|
r#""playlists":{"playlist":[{"id":"p1","name":"Road","owner":"yp","songCount":12,"duration":3000}]}"#,
|
||||||
|
))
|
||||||
|
.unwrap();
|
||||||
|
let lists = lists.resolve();
|
||||||
|
assert_eq!((lists[0].name.as_str(), lists[0].song_count), ("Road", 12));
|
||||||
|
|
||||||
|
let list: PlaylistReply = unwrap_envelope(&ok(
|
||||||
|
r#""playlist":{"id":"p1","name":"Road","entry":[{"id":"s1","title":"A"},{"id":"s2","title":"B"}]}"#,
|
||||||
|
))
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(list.resolve().unwrap().songs.len(), 2);
|
||||||
|
|
||||||
|
let starred: StarredReply =
|
||||||
|
unwrap_envelope(&ok(r#""starred2":{"song":[{"id":"s9","title":"Fav","starred":"2026-01-01T00:00:00Z"}]}"#))
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(starred.starred.resolve().songs[0].id, "s9");
|
||||||
|
|
||||||
|
let found: SearchReply = unwrap_envelope(&ok(
|
||||||
|
r#""searchResult3":{"artist":[{"id":"ar1","name":"Kino"}],"song":[{"id":"s1","title":"Kukushka"}]}"#,
|
||||||
|
))
|
||||||
|
.unwrap();
|
||||||
|
let found = found.result.resolve();
|
||||||
|
assert_eq!((found.artists.len(), found.albums.len(), found.songs.len()), (1, 0, 1));
|
||||||
|
let nothing: SearchReply = unwrap_envelope(&ok(r#""searchResult3":{}"#)).unwrap();
|
||||||
|
assert!(nothing.result.resolve().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stream_plans_keep_files_the_player_decodes_within_the_cap() {
|
||||||
|
let plan = StreamPlan::for_song;
|
||||||
|
assert_eq!(plan("mp3", 320, None, false), StreamPlan { transcode: false, max_kbps: None, codec: "mp3", bitrate_kbps: 320 });
|
||||||
|
assert_eq!(plan("m4a", 256, None, false).codec, "aac-mp4");
|
||||||
|
assert_eq!(plan("flac", 1000, None, true), StreamPlan { transcode: false, max_kbps: None, codec: "flac", bitrate_kbps: 0 });
|
||||||
|
// FLAC without the Lossless setting, formats the player can't decode, and
|
||||||
|
// files over the cap all become server-side MP3s.
|
||||||
|
assert_eq!(plan("flac", 1000, None, false), StreamPlan { transcode: true, max_kbps: Some(320), codec: "mp3", bitrate_kbps: 320 });
|
||||||
|
assert_eq!(plan("opus", 128, None, true).max_kbps, Some(320));
|
||||||
|
assert_eq!(plan("ogg", 160, Some(128), false).max_kbps, Some(128));
|
||||||
|
assert_eq!(plan("mp3", 320, Some(192), false), StreamPlan { transcode: true, max_kbps: Some(192), codec: "mp3", bitrate_kbps: 192 });
|
||||||
|
assert!(!plan("mp3", 128, Some(192), false).transcode);
|
||||||
|
assert!(plan("mp3", 0, Some(192), false).transcode, "unknown bitrate under a cap");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
/// Errors the app can act on. Messages are for logs, not for display.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum Error {
|
||||||
|
/// Wrong username or password, or the server refuses token sign-in.
|
||||||
|
#[error("unauthorized: {0}")]
|
||||||
|
Unauthorized(String),
|
||||||
|
/// The address isn't a usable http(s) URL.
|
||||||
|
#[error("invalid server address: {0}")]
|
||||||
|
InvalidUrl(String),
|
||||||
|
/// The album, artist or playlist doesn't exist (any more).
|
||||||
|
#[error("not found: {0}")]
|
||||||
|
NotFound(String),
|
||||||
|
/// No connection, DNS failure, timeout: worth retrying.
|
||||||
|
#[error("network: {0}")]
|
||||||
|
Network(String),
|
||||||
|
/// Anything else the server rejected, or a reply that isn't Subsonic.
|
||||||
|
#[error("api: {0}")]
|
||||||
|
Api(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type Result<T> = std::result::Result<T, Error>;
|
||||||
|
|
||||||
|
impl Error {
|
||||||
|
/// Subsonic error codes: 40 wrong credentials, 41 token auth unsupported
|
||||||
|
/// (LDAP users), 70 not found.
|
||||||
|
pub(crate) fn from_code(code: i64, message: String) -> Self {
|
||||||
|
match code {
|
||||||
|
40 | 41 => Error::Unauthorized(message),
|
||||||
|
70 => Error::NotFound(message),
|
||||||
|
_ => Error::Api(format!("{code}: {message}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<reqwest::Error> for Error {
|
||||||
|
fn from(e: reqwest::Error) -> Self {
|
||||||
|
if e.is_decode() {
|
||||||
|
Error::Api(e.to_string())
|
||||||
|
} else if e.status() == Some(reqwest::StatusCode::UNAUTHORIZED) {
|
||||||
|
Error::Unauthorized(e.to_string())
|
||||||
|
} else if e.status() == Some(reqwest::StatusCode::NOT_FOUND) {
|
||||||
|
// Usually a wrong address: the host answers, but has no /rest.
|
||||||
|
Error::Api(e.to_string())
|
||||||
|
} else {
|
||||||
|
Error::Network(e.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn subsonic_codes_map_to_actionable_errors() {
|
||||||
|
assert!(matches!(Error::from_code(40, "Wrong username or password".into()), Error::Unauthorized(_)));
|
||||||
|
assert!(matches!(Error::from_code(41, String::new()), Error::Unauthorized(_)));
|
||||||
|
assert!(matches!(Error::from_code(70, "Album not found".into()), Error::NotFound(_)));
|
||||||
|
assert_eq!(Error::from_code(0, "boom".into()), Error::Api("0: boom".into()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
//! Client for Subsonic-compatible music servers (Navidrome, Gonic, Airsonic).
|
||||||
|
//!
|
||||||
|
//! Like `ym-api`, it hands the app its own resolved types and keeps the wire
|
||||||
|
//! format, authentication and error codes in here.
|
||||||
|
|
||||||
|
mod client;
|
||||||
|
mod error;
|
||||||
|
mod models;
|
||||||
|
|
||||||
|
pub use client::{AlbumSort, Audio, Client, Config, StreamPlan};
|
||||||
|
pub use error::{Error, Result};
|
||||||
|
pub use models::{
|
||||||
|
Album, AlbumSummary, Artist, ArtistSummary, Playlist, PlaylistSummary, SearchResults, Song,
|
||||||
|
};
|
||||||
@@ -0,0 +1,348 @@
|
|||||||
|
//! The app-facing shapes of Subsonic objects, converted from the wire format
|
||||||
|
//! with every `Option` the UI doesn't care about resolved here.
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Song {
|
||||||
|
pub id: String,
|
||||||
|
pub title: String,
|
||||||
|
pub artist: Option<String>,
|
||||||
|
pub artist_id: Option<String>,
|
||||||
|
pub album: Option<String>,
|
||||||
|
pub album_id: Option<String>,
|
||||||
|
pub duration: Duration,
|
||||||
|
pub track: Option<u32>,
|
||||||
|
pub disc: Option<u32>,
|
||||||
|
/// Id for `getCoverArt`.
|
||||||
|
pub cover_art: Option<String>,
|
||||||
|
/// File extension on the server: "mp3", "flac", "m4a", "opus"…
|
||||||
|
pub suffix: String,
|
||||||
|
/// Kbps of the stored file; 0 when the server doesn't say.
|
||||||
|
pub bit_rate: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct AlbumSummary {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub artist: Option<String>,
|
||||||
|
pub artist_id: Option<String>,
|
||||||
|
pub cover_art: Option<String>,
|
||||||
|
pub song_count: u32,
|
||||||
|
pub duration: Duration,
|
||||||
|
pub year: Option<u32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AlbumSummary {
|
||||||
|
/// "Artist · 2019", or whichever half is known.
|
||||||
|
pub fn subtitle(&self) -> String {
|
||||||
|
match (&self.artist, self.year) {
|
||||||
|
(Some(a), Some(y)) => format!("{a} · {y}"),
|
||||||
|
(Some(a), None) => a.clone(),
|
||||||
|
(None, Some(y)) => y.to_string(),
|
||||||
|
(None, None) => String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Album {
|
||||||
|
pub info: AlbumSummary,
|
||||||
|
pub songs: Vec<Song>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct ArtistSummary {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub cover_art: Option<String>,
|
||||||
|
pub album_count: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Artist {
|
||||||
|
pub info: ArtistSummary,
|
||||||
|
pub albums: Vec<AlbumSummary>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct PlaylistSummary {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub owner: Option<String>,
|
||||||
|
pub cover_art: Option<String>,
|
||||||
|
pub song_count: u32,
|
||||||
|
pub duration: Duration,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Playlist {
|
||||||
|
pub info: PlaylistSummary,
|
||||||
|
pub songs: Vec<Song>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||||
|
pub struct SearchResults {
|
||||||
|
pub artists: Vec<ArtistSummary>,
|
||||||
|
pub albums: Vec<AlbumSummary>,
|
||||||
|
pub songs: Vec<Song>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SearchResults {
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.artists.is_empty() && self.albums.is_empty() && self.songs.is_empty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Wire format ----------------------------------------------------------
|
||||||
|
|
||||||
|
/// Ids are strings in Navidrome, numbers in some older servers.
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
#[serde(untagged)]
|
||||||
|
pub(crate) enum Id {
|
||||||
|
Text(String),
|
||||||
|
Number(i64),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Id {
|
||||||
|
fn into_string(self) -> Option<String> {
|
||||||
|
match self {
|
||||||
|
Id::Text(s) if s.is_empty() => None,
|
||||||
|
Id::Text(s) => Some(s),
|
||||||
|
Id::Number(n) => Some(n.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn id(raw: Option<Id>) -> Option<String> {
|
||||||
|
raw.and_then(Id::into_string)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn non_empty(s: Option<String>) -> Option<String> {
|
||||||
|
s.filter(|s| !s.trim().is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn count(n: Option<i64>) -> u32 {
|
||||||
|
n.unwrap_or(0).clamp(0, i64::from(u32::MAX)) as u32
|
||||||
|
}
|
||||||
|
|
||||||
|
fn secs(n: Option<i64>) -> Duration {
|
||||||
|
Duration::from_secs(n.unwrap_or(0).max(0) as u64)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase", default)]
|
||||||
|
pub(crate) struct RawSong {
|
||||||
|
id: Option<Id>,
|
||||||
|
title: Option<String>,
|
||||||
|
artist: Option<String>,
|
||||||
|
artist_id: Option<Id>,
|
||||||
|
album: Option<String>,
|
||||||
|
album_id: Option<Id>,
|
||||||
|
duration: Option<i64>,
|
||||||
|
track: Option<i64>,
|
||||||
|
disc_number: Option<i64>,
|
||||||
|
cover_art: Option<Id>,
|
||||||
|
suffix: Option<String>,
|
||||||
|
bit_rate: Option<i64>,
|
||||||
|
is_dir: Option<bool>,
|
||||||
|
is_video: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RawSong {
|
||||||
|
pub(crate) fn resolve(self) -> Option<Song> {
|
||||||
|
if self.is_dir == Some(true) || self.is_video == Some(true) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let positive = |n: Option<i64>| n.filter(|&n| n > 0).map(|n| n as u32);
|
||||||
|
Some(Song {
|
||||||
|
id: id(self.id)?,
|
||||||
|
title: non_empty(self.title).unwrap_or_else(|| "Untitled".into()),
|
||||||
|
artist: non_empty(self.artist),
|
||||||
|
artist_id: id(self.artist_id),
|
||||||
|
album: non_empty(self.album),
|
||||||
|
album_id: id(self.album_id),
|
||||||
|
duration: secs(self.duration),
|
||||||
|
track: positive(self.track),
|
||||||
|
disc: positive(self.disc_number),
|
||||||
|
cover_art: id(self.cover_art),
|
||||||
|
suffix: self.suffix.unwrap_or_default().to_ascii_lowercase(),
|
||||||
|
bit_rate: count(self.bit_rate),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn songs(raw: Vec<RawSong>) -> Vec<Song> {
|
||||||
|
raw.into_iter().filter_map(RawSong::resolve).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase", default)]
|
||||||
|
pub(crate) struct RawAlbum {
|
||||||
|
id: Option<Id>,
|
||||||
|
name: Option<String>,
|
||||||
|
/// Older servers send `title` instead of `name`.
|
||||||
|
title: Option<String>,
|
||||||
|
artist: Option<String>,
|
||||||
|
artist_id: Option<Id>,
|
||||||
|
cover_art: Option<Id>,
|
||||||
|
song_count: Option<i64>,
|
||||||
|
duration: Option<i64>,
|
||||||
|
year: Option<i64>,
|
||||||
|
pub(crate) song: Vec<RawSong>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RawAlbum {
|
||||||
|
pub(crate) fn summary(&mut self) -> Option<AlbumSummary> {
|
||||||
|
Some(AlbumSummary {
|
||||||
|
id: id(self.id.take())?,
|
||||||
|
name: non_empty(self.name.take().or(self.title.take())).unwrap_or_else(|| "Untitled".into()),
|
||||||
|
artist: non_empty(self.artist.take()),
|
||||||
|
artist_id: id(self.artist_id.take()),
|
||||||
|
cover_art: id(self.cover_art.take()),
|
||||||
|
song_count: count(self.song_count),
|
||||||
|
duration: secs(self.duration),
|
||||||
|
year: self.year.filter(|&y| y > 0).map(|y| y as u32),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn resolve(mut self) -> Option<Album> {
|
||||||
|
let info = self.summary()?;
|
||||||
|
Some(Album { info, songs: songs(self.song) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn albums(raw: Vec<RawAlbum>) -> Vec<AlbumSummary> {
|
||||||
|
raw.into_iter().filter_map(|mut a| a.summary()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase", default)]
|
||||||
|
pub(crate) struct RawArtist {
|
||||||
|
id: Option<Id>,
|
||||||
|
name: Option<String>,
|
||||||
|
cover_art: Option<Id>,
|
||||||
|
album_count: Option<i64>,
|
||||||
|
pub(crate) album: Vec<RawAlbum>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RawArtist {
|
||||||
|
pub(crate) fn summary(&mut self) -> Option<ArtistSummary> {
|
||||||
|
Some(ArtistSummary {
|
||||||
|
id: id(self.id.take())?,
|
||||||
|
name: non_empty(self.name.take()).unwrap_or_else(|| "Unknown artist".into()),
|
||||||
|
cover_art: id(self.cover_art.take()),
|
||||||
|
album_count: count(self.album_count),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn resolve(mut self) -> Option<Artist> {
|
||||||
|
let info = self.summary()?;
|
||||||
|
Some(Artist { info, albums: albums(self.album) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn artists(raw: Vec<RawArtist>) -> Vec<ArtistSummary> {
|
||||||
|
raw.into_iter().filter_map(|mut a| a.summary()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase", default)]
|
||||||
|
pub(crate) struct RawPlaylist {
|
||||||
|
id: Option<Id>,
|
||||||
|
name: Option<String>,
|
||||||
|
owner: Option<String>,
|
||||||
|
cover_art: Option<Id>,
|
||||||
|
song_count: Option<i64>,
|
||||||
|
duration: Option<i64>,
|
||||||
|
pub(crate) entry: Vec<RawSong>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RawPlaylist {
|
||||||
|
pub(crate) fn summary(&mut self) -> Option<PlaylistSummary> {
|
||||||
|
Some(PlaylistSummary {
|
||||||
|
id: id(self.id.take())?,
|
||||||
|
name: non_empty(self.name.take()).unwrap_or_else(|| "Untitled".into()),
|
||||||
|
owner: non_empty(self.owner.take()),
|
||||||
|
cover_art: id(self.cover_art.take()),
|
||||||
|
song_count: count(self.song_count),
|
||||||
|
duration: secs(self.duration),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn resolve(mut self) -> Option<Playlist> {
|
||||||
|
let info = self.summary()?;
|
||||||
|
Some(Playlist { info, songs: songs(self.entry) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn playlists(raw: Vec<RawPlaylist>) -> Vec<PlaylistSummary> {
|
||||||
|
raw.into_iter().filter_map(|mut p| p.summary()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `search3` and `getStarred2` share this shape.
|
||||||
|
#[derive(Debug, Default, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
pub(crate) struct RawMixed {
|
||||||
|
artist: Vec<RawArtist>,
|
||||||
|
album: Vec<RawAlbum>,
|
||||||
|
song: Vec<RawSong>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RawMixed {
|
||||||
|
pub(crate) fn resolve(self) -> SearchResults {
|
||||||
|
SearchResults { artists: artists(self.artist), albums: albums(self.album), songs: songs(self.song) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
pub(crate) struct RawIndex {
|
||||||
|
pub(crate) artist: Vec<RawArtist>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn songs_resolve_and_skip_folders_and_videos() {
|
||||||
|
let raw: Vec<RawSong> = serde_json::from_str(
|
||||||
|
r#"[{"id":"s1","title":"Kukushka","artist":"Kino","artistId":"ar1","album":"Chorny Albom",
|
||||||
|
"albumId":"al1","duration":402,"track":3,"discNumber":1,"coverArt":"al-al1",
|
||||||
|
"suffix":"FLAC","bitRate":1011},
|
||||||
|
{"id":"d1","title":"Folder","isDir":true},
|
||||||
|
{"id":"v1","title":"Clip","isVideo":true},
|
||||||
|
{"id":7,"title":"","suffix":"mp3","track":0},
|
||||||
|
{"title":"no id"}]"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let s = songs(raw);
|
||||||
|
assert_eq!(s.len(), 2);
|
||||||
|
assert_eq!(s[0].id, "s1");
|
||||||
|
assert_eq!(s[0].duration, Duration::from_secs(402));
|
||||||
|
assert_eq!((s[0].track, s[0].disc), (Some(3), Some(1)));
|
||||||
|
assert_eq!(s[0].suffix, "flac", "suffix is lowercased");
|
||||||
|
assert_eq!(s[0].cover_art.as_deref(), Some("al-al1"));
|
||||||
|
assert_eq!(s[1].id, "7", "numeric ids become strings");
|
||||||
|
assert_eq!(s[1].title, "Untitled");
|
||||||
|
assert_eq!(s[1].track, None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn albums_take_name_or_title_and_build_subtitles() {
|
||||||
|
let mut a: RawAlbum =
|
||||||
|
serde_json::from_str(r#"{"id":"al1","name":"Gruppa krovi","artist":"Kino","year":1988,"songCount":11}"#)
|
||||||
|
.unwrap();
|
||||||
|
let a = a.summary().unwrap();
|
||||||
|
assert_eq!(a.subtitle(), "Kino · 1988");
|
||||||
|
assert_eq!(a.song_count, 11);
|
||||||
|
let mut old: RawAlbum = serde_json::from_str(r#"{"id":5,"title":"Old","year":0}"#).unwrap();
|
||||||
|
let old = old.summary().unwrap();
|
||||||
|
assert_eq!((old.id.as_str(), old.name.as_str(), old.year), ("5", "Old", None));
|
||||||
|
assert_eq!(old.subtitle(), "");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
//! Talks to a real server. Run with
|
||||||
|
//! `SUBSONIC_URL=… SUBSONIC_USER=… SUBSONIC_PASSWORD=… cargo test -p subsonic-api -- --ignored`.
|
||||||
|
|
||||||
|
use subsonic_api::{AlbumSort, Client, Config, StreamPlan};
|
||||||
|
|
||||||
|
fn client() -> Client {
|
||||||
|
let var = |name: &str| std::env::var(name).unwrap_or_else(|_| panic!("set {name}"));
|
||||||
|
Client::new(&Config { url: var("SUBSONIC_URL"), username: var("SUBSONIC_USER"), password: var("SUBSONIC_PASSWORD") })
|
||||||
|
.expect("server address")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
#[ignore = "network"]
|
||||||
|
async fn browses_and_streams_the_first_album() {
|
||||||
|
let client = client();
|
||||||
|
client.ping().await.expect("ping");
|
||||||
|
let albums = client.albums(AlbumSort::Newest, 0, 5).await.expect("albums");
|
||||||
|
let first = albums.first().expect("the library has an album");
|
||||||
|
let album = client.album(&first.id).await.expect("album");
|
||||||
|
let song = album.songs.first().expect("the album has a song");
|
||||||
|
let plan = StreamPlan::for_song(&song.suffix, song.bit_rate, Some(128), false);
|
||||||
|
let audio = client.stream(&song.id, plan).await.expect("stream");
|
||||||
|
assert!(audio.bytes.len() > 10_000);
|
||||||
|
if let Some(cover) = &first.cover_art {
|
||||||
|
assert!(!client.cover_art(cover, 100).await.expect("cover").is_empty());
|
||||||
|
}
|
||||||
|
client.artists().await.expect("artists");
|
||||||
|
client.playlists().await.expect("playlists");
|
||||||
|
client.starred().await.expect("starred");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
#[ignore = "network"]
|
||||||
|
async fn wrong_password_is_unauthorized() {
|
||||||
|
let url = std::env::var("SUBSONIC_URL").expect("set SUBSONIC_URL");
|
||||||
|
let client = Client::new(&Config { url, username: "musyx-nobody".into(), password: "wrong".into() }).unwrap();
|
||||||
|
assert!(matches!(client.ping().await, Err(subsonic_api::Error::Unauthorized(_))));
|
||||||
|
}
|
||||||
@@ -8,6 +8,8 @@ publish.workspace = true
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
yamuse = "0.3.2"
|
yamuse = "0.3.2"
|
||||||
|
# Same major as yamuse, so LRCLIB calls share its client and TLS setup.
|
||||||
|
reqwest = { version = "0.12", default-features = false }
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
thiserror = "2"
|
thiserror = "2"
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
|
|||||||
@@ -426,11 +426,16 @@ impl YmClient {
|
|||||||
.unwrap_or_default())
|
.unwrap_or_default())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `settings3` takes JSON only: yamuse's form body gets `415 unsupported-media-type`.
|
||||||
pub async fn set_wave_settings(&self, station: &str, settings: WaveSettings) -> Result<()> {
|
pub async fn set_wave_settings(&self, station: &str, settings: WaveSettings) -> Result<()> {
|
||||||
let (mood, diversity, language) = settings.to_yamuse();
|
let (mood, diversity, language) = settings.to_yamuse();
|
||||||
self.inner
|
let body = serde_json::json!({
|
||||||
.rotor_set_station_settings(station, mood, diversity, language, yamuse::StationType::Rotor)
|
"moodEnergy": mood.as_str(),
|
||||||
.await?;
|
"diversity": diversity.as_str(),
|
||||||
|
"language": language.as_str(),
|
||||||
|
"type": yamuse::StationType::Rotor.as_str(),
|
||||||
|
});
|
||||||
|
self.post_json(&format!("/rotor/station/{station}/settings3"), &body).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -695,8 +700,19 @@ impl YmClient {
|
|||||||
|
|
||||||
// ---- Lyrics ----
|
// ---- Lyrics ----
|
||||||
|
|
||||||
/// Synced lyrics when Yandex has them, else plain text; `None` when there are none.
|
/// Synced lyrics when Yandex has them, else plain text, else whatever LRCLIB
|
||||||
pub async fn lyrics(&self, track_id: &str) -> Result<Option<Lyrics>> {
|
/// has; `None` when neither has any. Non-Yandex tracks go straight to LRCLIB.
|
||||||
|
pub async fn lyrics(&self, track: &Track) -> Result<Option<Lyrics>> {
|
||||||
|
// Tracks from other libraries have no Yandex id to ask about.
|
||||||
|
if track.is_yandex()
|
||||||
|
&& let Some(lyrics) = self.yandex_lyrics(&track.id).await?
|
||||||
|
{
|
||||||
|
return Ok(Some(lyrics));
|
||||||
|
}
|
||||||
|
crate::lrclib::lyrics(self.inner.transport().http(), track).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn yandex_lyrics(&self, track_id: &str) -> Result<Option<Lyrics>> {
|
||||||
for format in [yamuse::LyricsFormat::Lrc, yamuse::LyricsFormat::Text] {
|
for format in [yamuse::LyricsFormat::Lrc, yamuse::LyricsFormat::Text] {
|
||||||
let meta = match self.inner.track_lyrics(track_id, format).await {
|
let meta = match self.inner.track_lyrics(track_id, format).await {
|
||||||
Ok(meta) => meta,
|
Ok(meta) => meta,
|
||||||
|
|||||||
@@ -23,11 +23,19 @@ pub struct LyricLine {
|
|||||||
pub text: String,
|
pub text: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Where lyrics came from, so the UI can credit a source other than Yandex.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum LyricsSource {
|
||||||
|
Yandex,
|
||||||
|
Lrclib,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct Lyrics {
|
pub struct Lyrics {
|
||||||
pub lines: Vec<LyricLine>,
|
pub lines: Vec<LyricLine>,
|
||||||
pub synced: bool,
|
pub synced: bool,
|
||||||
pub writers: Vec<String>,
|
pub writers: Vec<String>,
|
||||||
|
pub source: LyricsSource,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Lyrics {
|
impl Lyrics {
|
||||||
@@ -45,6 +53,7 @@ impl Lyrics {
|
|||||||
lines: text.lines().map(|l| LyricLine { at: None, text: l.trim_end().to_owned() }).collect(),
|
lines: text.lines().map(|l| LyricLine { at: None, text: l.trim_end().to_owned() }).collect(),
|
||||||
synced: false,
|
synced: false,
|
||||||
writers,
|
writers,
|
||||||
|
source: LyricsSource::Yandex,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,7 +81,7 @@ impl Lyrics {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
lines.sort_by_key(|l| l.at);
|
lines.sort_by_key(|l| l.at);
|
||||||
Self { lines, synced: true, writers }
|
Self { lines, synced: true, writers, source: LyricsSource::Yandex }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ mod discover;
|
|||||||
mod edit;
|
mod edit;
|
||||||
mod error;
|
mod error;
|
||||||
mod library;
|
mod library;
|
||||||
|
mod lrclib;
|
||||||
mod models;
|
mod models;
|
||||||
mod wave;
|
mod wave;
|
||||||
|
|
||||||
@@ -19,10 +20,13 @@ pub use library::{
|
|||||||
AlbumKind, AlbumPage, AlbumSummary, ArtistPage, ArtistSummary, LibraryPlaylists, PlaylistId,
|
AlbumKind, AlbumPage, AlbumSummary, ArtistPage, ArtistSummary, LibraryPlaylists, PlaylistId,
|
||||||
PlaylistPage, PlaylistSummary,
|
PlaylistPage, PlaylistSummary,
|
||||||
};
|
};
|
||||||
pub use models::{AlbumRef, ArtistRef, Stream, Track};
|
pub use models::{
|
||||||
|
AlbumRef, ArtistRef, SUBSONIC_COVER_PREFIX, Source, Stream, SubsonicSong, Track, hash_str, hues_for,
|
||||||
|
parse_subsonic_cover, subsonic_cover_url,
|
||||||
|
};
|
||||||
pub use wave::{
|
pub use wave::{
|
||||||
Character, Language, MY_WAVE, Mood, PlayReport, Station, WaveBatch, WaveEvent, WaveSettings,
|
Character, Language, MY_WAVE, Mood, PlayReport, Station, WaveBatch, WaveEvent, WaveSettings,
|
||||||
};
|
};
|
||||||
pub use discover::{BestMatch, ChartEntry, Genre, Home, Personal, SearchKind, SearchResults, Totals};
|
pub use discover::{BestMatch, ChartEntry, Genre, Home, Personal, SearchKind, SearchResults, Totals};
|
||||||
pub use edit::{LikedIds, LyricLine, Lyrics};
|
pub use edit::{LikedIds, LyricLine, Lyrics, LyricsSource};
|
||||||
pub use error::{Error, Result};
|
pub use error::{Error, Result};
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
//! LRCLIB (lrclib.net), the open lyrics database, for tracks Yandex has no lyrics for.
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use crate::edit::{Lyrics, LyricsSource};
|
||||||
|
use crate::models::Track;
|
||||||
|
use crate::{Error, Result};
|
||||||
|
|
||||||
|
const BASE: &str = "https://lrclib.net/api";
|
||||||
|
/// LRCLIB asks clients to name themselves.
|
||||||
|
const USER_AGENT: &str = concat!("musyx/", env!("CARGO_PKG_VERSION"));
|
||||||
|
const TIMEOUT: Duration = Duration::from_secs(10);
|
||||||
|
/// How far a match's length may stray from the track's; LRCLIB's own `get` uses ±2 s.
|
||||||
|
const SLACK: f64 = 2.0;
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct Record {
|
||||||
|
#[serde(default)]
|
||||||
|
duration: Option<f64>,
|
||||||
|
#[serde(default)]
|
||||||
|
instrumental: bool,
|
||||||
|
plain_lyrics: Option<String>,
|
||||||
|
synced_lyrics: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Record {
|
||||||
|
fn has_lyrics(&self) -> bool {
|
||||||
|
!self.instrumental && (filled(&self.synced_lyrics).is_some() || filled(&self.plain_lyrics).is_some())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Synced when there are timings, else plain text.
|
||||||
|
fn into_lyrics(self) -> Option<Lyrics> {
|
||||||
|
if self.instrumental {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let lyrics = match (filled(&self.synced_lyrics), filled(&self.plain_lyrics)) {
|
||||||
|
(Some(lrc), _) => Lyrics::from_lrc(lrc, vec![]),
|
||||||
|
(None, Some(text)) => Lyrics::from_text(text, vec![]),
|
||||||
|
(None, None) => return None,
|
||||||
|
};
|
||||||
|
Some(Lyrics { source: LyricsSource::Lrclib, ..lyrics })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn filled(s: &Option<String>) -> Option<&str> {
|
||||||
|
s.as_deref().filter(|s| !s.trim().is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Looks the track up by its exact signature first, then by a looser search
|
||||||
|
/// filtered on length so a live cut or a remix doesn't borrow the studio timings.
|
||||||
|
pub(crate) async fn lyrics(http: &reqwest::Client, track: &Track) -> Result<Option<Lyrics>> {
|
||||||
|
let Some(artist) = track.artists.first().map(|a| a.name.as_str()) else { return Ok(None) };
|
||||||
|
let secs = track.duration.as_secs_f64();
|
||||||
|
|
||||||
|
if let Some(album) = track.album_title()
|
||||||
|
&& secs > 0.0
|
||||||
|
{
|
||||||
|
let duration = secs.round().to_string();
|
||||||
|
let query = [
|
||||||
|
("track_name", track.title.as_str()),
|
||||||
|
("artist_name", artist),
|
||||||
|
("album_name", album),
|
||||||
|
("duration", duration.as_str()),
|
||||||
|
];
|
||||||
|
if let Some(record) = get::<Record>(http, "get", &query).await?
|
||||||
|
&& let Some(lyrics) = record.into_lyrics()
|
||||||
|
{
|
||||||
|
return Ok(Some(lyrics));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let query = [("track_name", track.title.as_str()), ("artist_name", artist)];
|
||||||
|
let found = get::<Vec<Record>>(http, "search", &query).await?.unwrap_or_default();
|
||||||
|
Ok(pick(found, secs).and_then(Record::into_lyrics))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The closest-length match that has words, preferring synced ones.
|
||||||
|
fn pick(found: Vec<Record>, secs: f64) -> Option<Record> {
|
||||||
|
let off = |r: &Record| match r.duration {
|
||||||
|
Some(d) if secs > 0.0 => (d - secs).abs(),
|
||||||
|
_ => 0.0,
|
||||||
|
};
|
||||||
|
found
|
||||||
|
.into_iter()
|
||||||
|
.filter(|r| r.has_lyrics() && (secs <= 0.0 || r.duration.is_none_or(|d| (d - secs).abs() <= SLACK)))
|
||||||
|
.min_by(|a, b| {
|
||||||
|
filled(&b.synced_lyrics)
|
||||||
|
.is_some()
|
||||||
|
.cmp(&filled(&a.synced_lyrics).is_some())
|
||||||
|
.then(off(a).total_cmp(&off(b)))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `None` on 404, which LRCLIB answers when it has no such track.
|
||||||
|
async fn get<T: serde::de::DeserializeOwned>(
|
||||||
|
http: &reqwest::Client,
|
||||||
|
endpoint: &str,
|
||||||
|
query: &[(&str, &str)],
|
||||||
|
) -> Result<Option<T>> {
|
||||||
|
let network = |e: reqwest::Error| Error::Network(format!("lrclib: {e}"));
|
||||||
|
let response = http
|
||||||
|
.get(format!("{BASE}/{endpoint}"))
|
||||||
|
.query(query)
|
||||||
|
.header(reqwest::header::USER_AGENT, USER_AGENT)
|
||||||
|
.timeout(TIMEOUT)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(network)?;
|
||||||
|
let status = response.status();
|
||||||
|
if status == reqwest::StatusCode::NOT_FOUND {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
if !status.is_success() {
|
||||||
|
return Err(if status.is_server_error() || status == reqwest::StatusCode::TOO_MANY_REQUESTS {
|
||||||
|
Error::Network(format!("lrclib: {status}"))
|
||||||
|
} else {
|
||||||
|
Error::Api(format!("lrclib: {status}"))
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let body = response.bytes().await.map_err(network)?;
|
||||||
|
serde_json::from_slice(&body).map(Some).map_err(|e| Error::Api(format!("lrclib: {e}")))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn records(json: &str) -> Vec<Record> {
|
||||||
|
serde_json::from_str(json).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn prefers_synced_then_closest_length() {
|
||||||
|
let found = records(
|
||||||
|
r#"[
|
||||||
|
{"duration":200,"instrumental":false,"plainLyrics":"far","syncedLyrics":"[00:01.00]far"},
|
||||||
|
{"duration":181,"instrumental":false,"plainLyrics":"plain","syncedLyrics":null},
|
||||||
|
{"duration":182,"instrumental":false,"plainLyrics":"x","syncedLyrics":"[00:01.00]near"},
|
||||||
|
{"duration":180,"instrumental":false,"plainLyrics":"y","syncedLyrics":"[00:01.00]exact"}
|
||||||
|
]"#,
|
||||||
|
);
|
||||||
|
let l = pick(found, 180.0).unwrap().into_lyrics().unwrap();
|
||||||
|
assert!(l.synced);
|
||||||
|
assert_eq!(l.lines[0].text, "exact");
|
||||||
|
assert_eq!(l.source, LyricsSource::Lrclib);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn skips_instrumentals_and_wrong_lengths() {
|
||||||
|
let found = records(
|
||||||
|
r#"[
|
||||||
|
{"duration":180,"instrumental":true,"plainLyrics":null,"syncedLyrics":null},
|
||||||
|
{"duration":240,"instrumental":false,"plainLyrics":"live","syncedLyrics":null}
|
||||||
|
]"#,
|
||||||
|
);
|
||||||
|
assert!(pick(found, 180.0).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn falls_back_to_plain_text() {
|
||||||
|
let r = records(r#"[{"duration":180,"instrumental":false,"plainLyrics":"a\nb","syncedLyrics":" "}]"#);
|
||||||
|
let l = pick(r, 180.0).unwrap().into_lyrics().unwrap();
|
||||||
|
assert!(!l.synced);
|
||||||
|
assert_eq!(l.lines.len(), 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
+139
-6
@@ -31,6 +31,48 @@ pub struct Track {
|
|||||||
pub available: bool,
|
pub available: bool,
|
||||||
pub explicit: bool,
|
pub explicit: bool,
|
||||||
pub lyrics_available: bool,
|
pub lyrics_available: bool,
|
||||||
|
/// Where the audio and cover come from.
|
||||||
|
pub source: Source,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a track lives. Yandex tracks come from this crate; the app builds
|
||||||
|
/// others from another library and plays them through that library's client.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||||
|
pub enum Source {
|
||||||
|
#[default]
|
||||||
|
Yandex,
|
||||||
|
/// A song on a Subsonic-compatible server, such as Navidrome.
|
||||||
|
Subsonic(Box<SubsonicSong>),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the app needs to stream a server song and link to its album and artist.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct SubsonicSong {
|
||||||
|
pub song_id: String,
|
||||||
|
pub album_id: Option<String>,
|
||||||
|
pub album_title: Option<String>,
|
||||||
|
pub artist_id: Option<String>,
|
||||||
|
/// Id for the server's `getCoverArt`.
|
||||||
|
pub cover_art: Option<String>,
|
||||||
|
/// File extension on the server: "mp3", "flac", "opus"…
|
||||||
|
pub suffix: String,
|
||||||
|
pub bit_rate: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cover URLs of server songs: `subsonic://cover/{id}?size={n}`. They carry no
|
||||||
|
/// credentials, so they're safe as cache keys; the app resolves them itself.
|
||||||
|
pub const SUBSONIC_COVER_PREFIX: &str = "subsonic://cover/";
|
||||||
|
|
||||||
|
/// The cover id and size in a [`SUBSONIC_COVER_PREFIX`] URL.
|
||||||
|
pub fn parse_subsonic_cover(url: &str) -> Option<(&str, u32)> {
|
||||||
|
let rest = url.strip_prefix(SUBSONIC_COVER_PREFIX)?;
|
||||||
|
let (id, size) = rest.split_once("?size=")?;
|
||||||
|
Some((id, size.parse().ok()?)).filter(|(id, _)| !id.is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A [`SUBSONIC_COVER_PREFIX`] URL for cover `id` at `size` pixels.
|
||||||
|
pub fn subsonic_cover_url(id: &str, size: u32) -> String {
|
||||||
|
format!("{SUBSONIC_COVER_PREFIX}{id}?size={size}")
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Track {
|
impl Track {
|
||||||
@@ -66,9 +108,48 @@ impl Track {
|
|||||||
Some(i) => i.has_available_sync_lyrics.unwrap_or(false) || i.has_available_text_lyrics.unwrap_or(false),
|
Some(i) => i.has_available_sync_lyrics.unwrap_or(false) || i.has_available_text_lyrics.unwrap_or(false),
|
||||||
None => t.lyrics_available.unwrap_or(false),
|
None => t.lyrics_available.unwrap_or(false),
|
||||||
},
|
},
|
||||||
|
source: Source::Yandex,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A song from a Subsonic server. Its id is `sub-{song_id}`: unique next to
|
||||||
|
/// Yandex ids and free of the `:` that [`Track::full_id`] splits on.
|
||||||
|
pub fn from_subsonic(title: String, artist: Option<String>, duration: Duration, song: SubsonicSong) -> Self {
|
||||||
|
Self {
|
||||||
|
id: format!("sub-{}", song.song_id),
|
||||||
|
title,
|
||||||
|
version: None,
|
||||||
|
artists: artist.into_iter().map(|name| ArtistRef { id: None, name }).collect(),
|
||||||
|
album: None,
|
||||||
|
duration,
|
||||||
|
cover_uri: None,
|
||||||
|
available: true,
|
||||||
|
explicit: false,
|
||||||
|
lyrics_available: false,
|
||||||
|
source: Source::Subsonic(Box::new(song)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_yandex(&self) -> bool {
|
||||||
|
matches!(self.source, Source::Yandex)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn subsonic(&self) -> Option<&SubsonicSong> {
|
||||||
|
match &self.source {
|
||||||
|
Source::Subsonic(song) => Some(song),
|
||||||
|
Source::Yandex => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The album's title, whichever library the track is from.
|
||||||
|
pub fn album_title(&self) -> Option<&str> {
|
||||||
|
let title = match &self.source {
|
||||||
|
Source::Yandex => self.album.as_ref().map(|a| a.title.as_str()),
|
||||||
|
Source::Subsonic(song) => song.album_title.as_deref(),
|
||||||
|
};
|
||||||
|
title.filter(|t| !t.is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
/// Decodes a track from the API's JSON, e.g. a recorded fixture.
|
/// Decodes a track from the API's JSON, e.g. a recorded fixture.
|
||||||
pub fn from_json(json: &str) -> crate::Result<Self> {
|
pub fn from_json(json: &str) -> crate::Result<Self> {
|
||||||
let raw = serde_json::from_str(json).map_err(|e| crate::Error::Api(e.to_string()))?;
|
let raw = serde_json::from_str(json).map_err(|e| crate::Error::Api(e.to_string()))?;
|
||||||
@@ -98,15 +179,19 @@ impl Track {
|
|||||||
|
|
||||||
/// Absolute cover URL at `size`×`size` pixels.
|
/// Absolute cover URL at `size`×`size` pixels.
|
||||||
pub fn cover_url(&self, size: u32) -> Option<String> {
|
pub fn cover_url(&self, size: u32) -> Option<String> {
|
||||||
cover_url(self.cover_uri.as_deref(), size)
|
match &self.source {
|
||||||
|
Source::Yandex => cover_url(self.cover_uri.as_deref(), size),
|
||||||
|
Source::Subsonic(song) => song.cover_art.as_deref().map(|id| subsonic_cover_url(id, size)),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Two stable hues for placeholder art, derived from the album (or track) id.
|
/// Two stable hues for placeholder art, derived from the album (or track) id.
|
||||||
pub fn hues(&self) -> (f32, f32) {
|
pub fn hues(&self) -> (f32, f32) {
|
||||||
hues_for(self.album.as_ref().map_or_else(
|
if let Some(album) = &self.album {
|
||||||
|| self.id.bytes().fold(7u64, |h, b| h.wrapping_mul(31).wrapping_add(u64::from(b))),
|
return hues_for(album.id as u64);
|
||||||
|a| a.id as u64,
|
}
|
||||||
))
|
let seed = self.subsonic().and_then(|s| s.album_id.as_deref()).unwrap_or(&self.id);
|
||||||
|
hues_for(hash_str(seed))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,8 +201,13 @@ pub(crate) fn cover_url(uri: Option<&str>, size: u32) -> Option<String> {
|
|||||||
Some(yamuse::models::normalize_image_url(uri, &format!("{size}x{size}")))
|
Some(yamuse::models::normalize_image_url(uri, &format!("{size}x{size}")))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A stable hash of a text id, for [`hues_for`].
|
||||||
|
pub fn hash_str(s: &str) -> u64 {
|
||||||
|
s.bytes().fold(7u64, |h, b| h.wrapping_mul(31).wrapping_add(u64::from(b)))
|
||||||
|
}
|
||||||
|
|
||||||
/// Two hues for placeholder art; equal seeds give equal art.
|
/// Two hues for placeholder art; equal seeds give equal art.
|
||||||
pub(crate) fn hues_for(seed: u64) -> (f32, f32) {
|
pub fn hues_for(seed: u64) -> (f32, f32) {
|
||||||
((seed.wrapping_mul(47) % 360) as f32, (seed.wrapping_mul(131).wrapping_add(90) % 360) as f32)
|
((seed.wrapping_mul(47) % 360) as f32, (seed.wrapping_mul(131).wrapping_add(90) % 360) as f32)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -247,6 +337,49 @@ mod tests {
|
|||||||
assert!((0.0..360.0).contains(&h1) && (0.0..360.0).contains(&h2));
|
assert!((0.0..360.0).contains(&h1) && (0.0..360.0).contains(&h2));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn server_song() -> Track {
|
||||||
|
Track::from_subsonic(
|
||||||
|
"Kukushka".into(),
|
||||||
|
Some("Kino".into()),
|
||||||
|
Duration::from_secs(402),
|
||||||
|
SubsonicSong {
|
||||||
|
song_id: "s1".into(),
|
||||||
|
album_id: Some("al1".into()),
|
||||||
|
album_title: Some("Chorny Albom".into()),
|
||||||
|
artist_id: Some("ar1".into()),
|
||||||
|
cover_art: Some("al-al1".into()),
|
||||||
|
suffix: "flac".into(),
|
||||||
|
bit_rate: 1000,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn server_songs_keep_their_own_ids_and_credential_free_covers() {
|
||||||
|
let t = server_song();
|
||||||
|
assert_eq!(t.id, "sub-s1");
|
||||||
|
assert_eq!(t.full_id(), "sub-s1", "no album id appended");
|
||||||
|
assert!(!t.is_yandex() && t.album.is_none() && t.artists[0].id.is_none());
|
||||||
|
assert_eq!(t.album_title(), Some("Chorny Albom"));
|
||||||
|
assert!(!t.lyrics_available);
|
||||||
|
let cover = t.cover_url(200).unwrap();
|
||||||
|
assert_eq!(cover, "subsonic://cover/al-al1?size=200");
|
||||||
|
assert_eq!(parse_subsonic_cover(&cover), Some(("al-al1", 200)));
|
||||||
|
assert_eq!(parse_subsonic_cover("https://avatars.yandex.net/x"), None);
|
||||||
|
assert_eq!(parse_subsonic_cover("subsonic://cover/?size=1"), None);
|
||||||
|
let mut other = server_song();
|
||||||
|
other.id = "sub-s2".into();
|
||||||
|
assert_eq!(t.hues(), other.hues(), "same album, same art");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn yandex_album_titles_come_from_the_album() {
|
||||||
|
let t = track(r#"{"id":1,"albums":[{"id":5,"title":"A"}]}"#);
|
||||||
|
assert!(t.is_yandex() && t.subsonic().is_none());
|
||||||
|
assert_eq!(t.album_title(), Some("A"));
|
||||||
|
assert_eq!(track(r#"{"id":1,"albums":[{"id":5,"title":""}]}"#).album_title(), None);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn best_variant_prefers_full_mp3_at_top_bitrate() {
|
fn best_variant_prefers_full_mp3_at_top_bitrate() {
|
||||||
let v: Vec<yamuse::models::DownloadInfo> = serde_json::from_str(
|
let v: Vec<yamuse::models::DownloadInfo> = serde_json::from_str(
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
<!-- Historical: the first Musyx exploration. The build has moved on; DESIGN.md is the
|
||||||
|
authority (see its History section for what changed). -->
|
||||||
<title>Musyx Desktop Mockup</title>
|
<title>Musyx Desktop Mockup</title>
|
||||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# Maintainer: Yuriy Panov <uriy.panov@gmail.com>
|
# Maintainer: Yuriy Panov <uriy.panov@gmail.com>
|
||||||
# Builds the checked-out commit of this repository: run `makepkg -si` in this directory.
|
# Builds the checked-out commit of this repository: run `makepkg -si` in this directory.
|
||||||
pkgname=musyx
|
pkgname=musyx
|
||||||
pkgver=0.2.1
|
pkgver=0.4.0
|
||||||
pkgrel=1
|
pkgrel=1
|
||||||
pkgdesc='Desktop player for Yandex Music (unofficial)'
|
pkgdesc='Desktop player for Yandex Music (unofficial)'
|
||||||
arch=('x86_64' 'aarch64')
|
arch=('x86_64' 'aarch64')
|
||||||
|
|||||||
@@ -23,6 +23,10 @@
|
|||||||
</categories>
|
</categories>
|
||||||
<content_rating type="oars-1.1"/>
|
<content_rating type="oars-1.1"/>
|
||||||
<releases>
|
<releases>
|
||||||
|
<release version="0.4.0" date="2026-11-16"/>
|
||||||
|
<release version="0.3.2" date="2026-10-30"/>
|
||||||
|
<release version="0.3.1" date="2026-10-26"/>
|
||||||
|
<release version="0.3.0" date="2026-10-22"/>
|
||||||
<release version="0.2.1" date="2026-10-18"/>
|
<release version="0.2.1" date="2026-10-18"/>
|
||||||
<release version="0.2.0" date="2026-10-16"/>
|
<release version="0.2.0" date="2026-10-16"/>
|
||||||
</releases>
|
</releases>
|
||||||
|
|||||||
Reference in new issue
Block a user