Compare commits
23
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6dc8f0d9f2 | ||
|
|
d9594a5de5 | ||
|
|
c1defa565b | ||
|
|
e2ac2de9f4 | ||
|
|
899ab223b9 | ||
|
|
4ea9250e16 | ||
|
|
9c8ba2a4dc | ||
|
|
555d0ca749 | ||
|
|
9cbda56abc | ||
|
|
ac5c8c4c8c | ||
|
|
e5c43fbb77 | ||
|
|
766ed22726 | ||
|
|
dafa40cca8 | ||
|
|
365a28ce67 | ||
|
|
4b1f0bb8a0 | ||
|
|
c496275101 | ||
|
|
44f4a1f06e | ||
|
|
5b465e2859 | ||
|
|
118fa3cf11 | ||
|
|
ec64cf7f4b | ||
|
|
093c41435a | ||
|
|
f80de805c2 | ||
|
|
28e273c31e |
No files matched your search
@@ -1,3 +1,10 @@
|
||||
/target
|
||||
.DS_Store
|
||||
/design/shots
|
||||
.env
|
||||
/packaging/arch/src
|
||||
/packaging/arch/pkg
|
||||
/packaging/arch/musyx
|
||||
/packaging/arch/*.pkg.tar.*
|
||||
/.impeccable
|
||||
/.env
|
||||
Generated
+45
-2
@@ -2992,12 +2992,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "musyx"
|
||||
version = "0.2.0"
|
||||
version = "0.3.1"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"directories",
|
||||
"iced",
|
||||
"iced_test",
|
||||
"image",
|
||||
"keyring",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
@@ -3011,6 +3012,7 @@ dependencies = [
|
||||
"souvlaki",
|
||||
"sys-locale",
|
||||
"tokio",
|
||||
"winresource",
|
||||
"ym-api",
|
||||
]
|
||||
|
||||
@@ -4700,6 +4702,15 @@ dependencies = [
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_spanned"
|
||||
version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_urlencoded"
|
||||
version = "0.7.1"
|
||||
@@ -5361,6 +5372,21 @@ dependencies = [
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml"
|
||||
version = "1.1.8+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d"
|
||||
dependencies = [
|
||||
"indexmap",
|
||||
"serde_core",
|
||||
"serde_spanned",
|
||||
"toml_datetime",
|
||||
"toml_parser",
|
||||
"toml_writer",
|
||||
"winnow",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "1.1.2+spec-1.1.0"
|
||||
@@ -5391,6 +5417,12 @@ dependencies = [
|
||||
"winnow",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_writer"
|
||||
version = "1.1.3+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770"
|
||||
|
||||
[[package]]
|
||||
name = "tower"
|
||||
version = "0.5.3"
|
||||
@@ -6505,6 +6537,16 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winresource"
|
||||
version = "0.1.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2bc6d36480b829272a5bdabf08e6dca8004761c1da7e35efef800540c66221b"
|
||||
dependencies = [
|
||||
"toml",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.57.1"
|
||||
@@ -6629,8 +6671,9 @@ checksum = "e01738255b5a16e78bbb83e7fbba0a1e7dd506905cfc53f4622d89015a03fbb5"
|
||||
|
||||
[[package]]
|
||||
name = "ym-api"
|
||||
version = "0.2.0"
|
||||
version = "0.3.1"
|
||||
dependencies = [
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/ym-api", "crates/musyx"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.2.0"
|
||||
version = "0.3.1"
|
||||
edition = "2024"
|
||||
license = "MIT"
|
||||
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
|
||||
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.
|
||||
# Design System: Musyx
|
||||
|
||||
## 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.
|
||||
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.
|
||||
## Overview
|
||||
|
||||
## Colour
|
||||
**Creative North Star: "The Late-Night Tape Deck"**
|
||||
|
||||
| Token | Dark | Light | Used for |
|
||||
|--------------|-----------|-----------|----------|
|
||||
| `bg` | `#1C1A22` | `#F3F1F6` | Window and content background |
|
||||
| `panel` | `#23202B` | `#FFFFFF` | Sidebar, player bar, drawer, cards that need separation |
|
||||
| `raised` | `#2D2937` | `#EAE6F0` | Hover and selected rows, chip fills, progress track |
|
||||
| `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 |
|
||||
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
|
||||
one thing glows: an amber lamp that marks what is playing, what you chose and what you can
|
||||
press next. People leave the window open for hours, so nothing moves or competes for attention
|
||||
unless the music asks for it.
|
||||
|
||||
Covers that have no artwork yet get a placeholder made of two hues (`h1`, `h2`) derived from
|
||||
the item id, painted as a diagonal gradient between them.
|
||||
The layout is the familiar desktop player shell: sidebar, content, player bar, and an optional
|
||||
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 |
|
||||
|---------|----------------------|--------------------|-------|
|
||||
| Display | Unbounded SemiBold | 46 / 40 / 34 / 30 | My Wave hero, detail page titles, sign-in headline, screen titles |
|
||||
| Wordmark| Unbounded SemiBold | 20 | `musyx` + amber dot |
|
||||
| Section | Onest SemiBold | 19 | Section headings ("Made for you") |
|
||||
| Body | Onest Regular/Medium | 14 (rows 14, meta 13, small 12.5) | Everything else |
|
||||
**Key Characteristics:**
|
||||
- One amber accent on an aubergine ground. Amber means "this one, now".
|
||||
- Three tonal surfaces (bg, panel, raised) do the layering. Shadows appear only on things that float.
|
||||
- Unbounded for titles, Onest for everything else. Icons are Lucide at 18pt.
|
||||
- Dense, scannable lists with 52pt track rows.
|
||||
- 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
|
||||
counts use tabular figures.
|
||||
## Colors
|
||||
|
||||
## 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,
|
||||
and the gap between sections is 34.
|
||||
- Radii: cover 10 · control 8 · small cover 6 · pill/round 999 · hero 16 · window cards 14.
|
||||
- Shell: sidebar 232 · player bar 80 · drawer 320 · track row 52 tall.
|
||||
- Icons: Lucide 0.460 (ISC), 18px and tinted via `currentColor`. The `-fill` variants are for
|
||||
liked, play and pause.
|
||||
### Primary
|
||||
- **Indicator Amber** (`accent`): the playing track's title, the progress fill, primary buttons,
|
||||
selected chips, the active nav icon, the active tab underline, the focused search border, the
|
||||
wordmark dot, the My Wave hero lines, and on Now Playing the play disc and the line being sung.
|
||||
The Lossless quality badge also turns amber when Yandex
|
||||
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
|
||||
|
||||
- **Sidebar**: wordmark, five nav items (Home, My Wave, Search, Collection, Podcasts), a
|
||||
playlist list, and an account chip with sign-out. The active item sits on a `raised` fill
|
||||
and has an amber icon.
|
||||
- **Player bar**: shows cover, title/artist, like and dislike on the left. The centre has
|
||||
transport (shuffle, previous, play disc, next, repeat) over a progress bar with times. On
|
||||
the right are a quality badge, lyrics, queue and a volume bar.
|
||||
- **Track row**: index (or an equaliser when playing), cover, title/artist, album, like,
|
||||
duration and a "more" button that appears on hover. The playing row is amber.
|
||||
- **Cards**: a cover with a hover play button, the title, and one muted subtitle line.
|
||||
- **Drawer**: Queue | Lyrics tabs, sliding in from the right over the content edge.
|
||||
### Buttons
|
||||
- **Primary:** an amber pill with amber-ink label, medium or semibold, padded 10×18, with the
|
||||
primary lift. On hover it mixes 12% toward `fg`. When pressed it mixes 12% toward `bg`. When
|
||||
disabled it is `raised` with a `muted` label.
|
||||
- **Ghost:** a transparent pill with a 1px `line` outline and an `fg` label. It fills `raised` on
|
||||
hover. It pairs with Primary, as in Play + Shuffle.
|
||||
- **Icon button:** a 34pt square holding an 18pt icon. Idle it is `muted`. On hover the icon turns
|
||||
`fg` on a `raised` fill. A toggle that is on is tinted `accent`, and a liked heart is `like`.
|
||||
- **Play disc:** a 40pt `fg` circle with a `bg` glyph. When nothing is queued it becomes a
|
||||
`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.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Yuriy Panov
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -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/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
|
||||
|
||||
@@ -42,11 +44,34 @@ This builds a release `Musyx.app` into `target/release/bundle/`, signed with the
|
||||
`MUSYX_SIGN_IDENTITY` to sign with another identity, or to `-` for an ad-hoc signature
|
||||
(each ad-hoc build is a new code identity, so macOS asks again for keychain access).
|
||||
|
||||
## Install on Linux
|
||||
|
||||
```sh
|
||||
tool/bundle-linux.sh # tarball, .deb and AppImage into target/release/bundle/
|
||||
tool/bundle-linux.sh tar deb # only the formats named
|
||||
tool/bundle-linux.sh --install # install into ~/.local (PREFIX picks another prefix)
|
||||
```
|
||||
|
||||
On Arch, `makepkg -si` in `packaging/arch` builds and installs the committed `HEAD`.
|
||||
|
||||
Building needs `pkg-config` and the ALSA and D-Bus development files (`alsa-lib` and `dbus`
|
||||
on Arch, `libasound2-dev` and `libdbus-1-dev` on Debian/Ubuntu). The AppImage also needs
|
||||
[`appimagetool`](https://github.com/AppImage/appimagetool/releases) on `PATH` (or
|
||||
`APPIMAGETOOL`). A binary runs only on a glibc at least as new as the one it was built
|
||||
against, so build release packages on the oldest distro you want to support.
|
||||
|
||||
The desktop entry, metainfo and icons are installed as `it.panov.musyx.desktop`, which is also the
|
||||
window's Wayland app id. The token goes to the Secret Service (GNOME Keyring, KWallet,
|
||||
KeePassXC), and media keys and the desktop's player widget work through MPRIS. The menu bar
|
||||
mini player is macOS-only.
|
||||
|
||||
## Settings
|
||||
|
||||
Settings (streaming quality, appearance, language, volume) are kept in
|
||||
`~/Library/Application Support/Musyx/settings.json`. Covers are cached under
|
||||
`~/Library/Caches/Musyx/covers` and can be cleared from Settings.
|
||||
`~/Library/Application Support/Musyx/settings.json` on macOS and
|
||||
`~/.config/musyx/settings.json` on Linux. Covers are cached under
|
||||
`~/Library/Caches/Musyx/covers` (`~/.cache/musyx/covers` on Linux) and can be cleared from
|
||||
Settings.
|
||||
|
||||
Streaming quality **Lossless** asks Yandex for FLAC (through the signed `/get-file-info`
|
||||
endpoint, decrypting its AES-CTR stream in memory). Yandex decides what to grant by
|
||||
|
||||
@@ -20,6 +20,8 @@ tokio = { version = "1", features = ["time", "rt", "fs", "sync"] }
|
||||
directories = "6.0.0"
|
||||
sys-locale = "0.3.2"
|
||||
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]
|
||||
objc2 = "0.6.3"
|
||||
@@ -27,6 +29,9 @@ objc2-foundation = "0.3.2"
|
||||
objc2-app-kit = "0.3.2"
|
||||
block2 = "0.6.2"
|
||||
|
||||
[build-dependencies]
|
||||
winresource = "0.1.34"
|
||||
|
||||
[dev-dependencies]
|
||||
iced_test = "0.14"
|
||||
tokio = { version = "1", features = ["macros", "rt"] }
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 46 KiB |
@@ -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,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 |
@@ -0,0 +1,12 @@
|
||||
fn main() {
|
||||
// Embed the icon and version info into the Windows executable, so Explorer and the taskbar show them.
|
||||
println!("cargo:rerun-if-changed=assets/icon/musyx.ico");
|
||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
|
||||
let mut res = winresource::WindowsResource::new();
|
||||
res.set_icon("assets/icon/musyx.ico")
|
||||
.set("ProductName", "Musyx")
|
||||
.set("FileDescription", "Musyx")
|
||||
.set("OriginalFilename", "Musyx.exe");
|
||||
res.compile().expect("failed to embed Windows resources");
|
||||
}
|
||||
}
|
||||
@@ -74,10 +74,10 @@ async fn main() {
|
||||
if let Ok(found) = client.search("eminem without me", SearchKind::Tracks, 0).await {
|
||||
for track in found.tracks.iter().take(2) {
|
||||
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!(
|
||||
"lyrics {}: synced={} lines={} first_stamp={:?}",
|
||||
track.id, l.synced, l.lines.len(), l.lines.first().and_then(|x| x.at)
|
||||
"lyrics {}: {:?} synced={} lines={} first_stamp={:?}",
|
||||
track.id, l.source, l.synced, l.lines.len(), l.lines.first().and_then(|x| x.at)
|
||||
),
|
||||
Ok(None) => println!("lyrics {}: none", track.id),
|
||||
Err(e) => println!("lyrics {}: ERROR {e}", track.id),
|
||||
@@ -87,10 +87,10 @@ async fn main() {
|
||||
if let Ok(chart) = client.chart().await {
|
||||
for entry in chart.iter().take(3) {
|
||||
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!(
|
||||
"lyrics {}: synced={} lines={} first_stamp={:?}",
|
||||
entry.track.id, l.synced, l.lines.len(), l.lines.first().and_then(|x| x.at)
|
||||
"lyrics {}: {:?} synced={} lines={} first_stamp={:?}",
|
||||
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),
|
||||
Err(e) => println!("lyrics {}: ERROR {e}", entry.track.id),
|
||||
|
||||
+534
-50
@@ -25,12 +25,14 @@ use crate::screens::wave::WaveScreen;
|
||||
use crate::screens::detail::{self, Page};
|
||||
use crate::screens::{self, Loadable, sign_in};
|
||||
use crate::session::{self, Restored};
|
||||
use crate::shortcuts::{self, Shortcut};
|
||||
use crate::store::{self, Appearance, Locale, Quality, Settings};
|
||||
use crate::ui::theme::{self, shell};
|
||||
use crate::widgets::drawer::{self, Panel};
|
||||
use crate::widgets::player_bar;
|
||||
use crate::widgets::menu::{self, Menu};
|
||||
use crate::widgets::{now_playing, player_bar};
|
||||
use crate::widgets::sheet::{self, Sheet};
|
||||
use crate::widgets::track_list::Env;
|
||||
use crate::widgets::track_list::{Drag, Env};
|
||||
use crate::widgets::{sidebar, topbar};
|
||||
|
||||
/// Where sign-in stands. Everything but `SignedIn` takes the whole window.
|
||||
@@ -52,6 +54,8 @@ pub struct App {
|
||||
nav: Navigator,
|
||||
search: Search,
|
||||
drawer: Option<Panel>,
|
||||
/// Now Playing covers the window, player bar included.
|
||||
now_playing: bool,
|
||||
player: Player,
|
||||
library: Library,
|
||||
/// Album, artist and playlist pages visited this session.
|
||||
@@ -65,6 +69,11 @@ pub struct App {
|
||||
/// Albums, artists and playlists liked, and tracks disliked, by id.
|
||||
likes: LikedIds,
|
||||
sheet: Option<Sheet>,
|
||||
menu: Option<Menu>,
|
||||
/// A row of an own playlist being dragged to a new place.
|
||||
drag: Option<Drag>,
|
||||
/// Play this page's tracks once it loads ("Play" in a card's menu).
|
||||
pending_play: Option<(Route, bool)>,
|
||||
toast: Option<(String, std::time::Instant)>,
|
||||
/// Lyrics per track id, fetched while the lyrics panel is open.
|
||||
lyrics: HashMap<String, Loadable<Option<Arc<Lyrics>>>>,
|
||||
@@ -99,6 +108,7 @@ pub enum Message {
|
||||
Search(search::Msg),
|
||||
ToggleDrawer(Panel),
|
||||
CloseDrawer,
|
||||
ShowNowPlaying(bool),
|
||||
Player(player::Msg),
|
||||
PlayTracks { tracks: Arc<[Track]>, start: usize, shuffle: bool },
|
||||
LoadLiked,
|
||||
@@ -138,6 +148,10 @@ pub enum Message {
|
||||
ClearCoverCache,
|
||||
CoverCacheCleared(Result<(), String>),
|
||||
Media(crate::media::Command),
|
||||
Shortcut(Shortcut),
|
||||
/// A window opened; Windows media controls need its handle.
|
||||
WindowOpened(iced::window::Id),
|
||||
MediaWindow(u64),
|
||||
LoadLikedIds,
|
||||
LikedIdsLoaded(Result<LikedIds, Error>),
|
||||
LikeTrack(Track, bool),
|
||||
@@ -146,6 +160,22 @@ pub enum Message {
|
||||
LikeArtist(i64, bool),
|
||||
LikePlaylist(PlaylistId, bool),
|
||||
OpenSheet(Sheet),
|
||||
OpenMenu(Box<Menu>),
|
||||
CloseMenu,
|
||||
/// The pointer is over this menu entry.
|
||||
MenuHover(usize),
|
||||
MenuSubHover(usize),
|
||||
/// Show or hide the "Add to playlist" list.
|
||||
MenuSub(bool),
|
||||
/// A menu entry was chosen: close the menu, then do it.
|
||||
MenuPick(Box<Message>),
|
||||
/// Play an album, artist or playlist, loading its page first if needed.
|
||||
PlayRoute { route: Route, shuffle: bool },
|
||||
/// A drag handle in an own playlist was pressed on this row.
|
||||
DragStart { playlist: PlaylistId, track: Track, index: usize },
|
||||
/// The dragged row is over this place in the list.
|
||||
DragOver(usize),
|
||||
DragEnd,
|
||||
CloseSheet,
|
||||
SheetText(String),
|
||||
PlayNext(Track),
|
||||
@@ -180,6 +210,7 @@ impl App {
|
||||
nav: Navigator::new(Route::Home),
|
||||
search: Search::default(),
|
||||
drawer: None,
|
||||
now_playing: false,
|
||||
player: Player::default(),
|
||||
library: Library::default(),
|
||||
pages: HashMap::new(),
|
||||
@@ -190,6 +221,9 @@ impl App {
|
||||
covers: Covers::default(),
|
||||
likes: LikedIds::default(),
|
||||
sheet: None,
|
||||
menu: None,
|
||||
drag: None,
|
||||
pending_play: None,
|
||||
toast: None,
|
||||
lyrics: HashMap::new(),
|
||||
lyric_line: None,
|
||||
@@ -227,6 +261,14 @@ impl App {
|
||||
app.session = config.session();
|
||||
app.library.liked = Liked::loaded(config.sample_liked(), &Liked::NotLoaded);
|
||||
app.pages.insert(Route::Album(1), Loadable::Loaded(config.sample_album()));
|
||||
app.pages.insert(Route::Playlist(crate::snapshot::OWN_PLAYLIST), Loadable::Loaded(config.sample_playlist()));
|
||||
app.menu = config.menu();
|
||||
app.drag = config.drag();
|
||||
if config.now_playing {
|
||||
app.now_playing = true;
|
||||
let tracks = config.sample_liked().into();
|
||||
let _ = app.player.update(player::Msg::Play { tracks, start: 0, shuffle: None });
|
||||
}
|
||||
if let Some(route) = config.route {
|
||||
app.nav = Navigator::new(route);
|
||||
}
|
||||
@@ -264,9 +306,22 @@ impl App {
|
||||
let audio = player::engine::subscription().map(|e| Message::Player(player::Msg::Engine(e)));
|
||||
let keys = crate::media::subscription().map(Message::Media);
|
||||
let mut subs = vec![appearance, audio, keys];
|
||||
if cfg!(windows) {
|
||||
subs.push(iced::window::open_events().map(Message::WindowOpened));
|
||||
}
|
||||
if let Session::SignedOut(sign_in) = &self.session {
|
||||
subs.push(sign_in.subscription().map(Message::SignIn));
|
||||
}
|
||||
if matches!(self.session, Session::SignedIn { .. }) {
|
||||
subs.push(shortcuts::subscription().map(Message::Shortcut));
|
||||
}
|
||||
if self.drag.is_some() {
|
||||
// The button can come up anywhere, over the list or not.
|
||||
subs.push(iced::event::listen_with(|event, _, _| match event {
|
||||
iced::Event::Mouse(iced::mouse::Event::ButtonReleased(iced::mouse::Button::Left)) => Some(Message::DragEnd),
|
||||
_ => None,
|
||||
}));
|
||||
}
|
||||
// The hero's lines drift only while My Wave plays and the hero is on screen.
|
||||
let hero_visible = matches!(self.nav.current(), Route::Home | Route::Wave);
|
||||
let wave_playing = self.player.wave_station() == Some(MY_WAVE)
|
||||
@@ -322,6 +377,11 @@ impl App {
|
||||
pub fn update(&mut self, message: Message) -> Task<Message> {
|
||||
let traced = trace(&message);
|
||||
let task = self.update_inner(message);
|
||||
if self.now_playing
|
||||
&& let Some(url) = self.player.track().and_then(|t| t.cover_url(crate::covers::LARGE))
|
||||
{
|
||||
self.covers.make_backdrop(&url);
|
||||
}
|
||||
if traced {
|
||||
let now = self.player.track().map_or("-".to_owned(), |t| t.full_title());
|
||||
let next: Vec<String> = self
|
||||
@@ -448,6 +508,7 @@ impl App {
|
||||
self.session = Session::SignedOut(Box::default());
|
||||
self.nav = Navigator::new(Route::Home);
|
||||
self.drawer = None;
|
||||
self.now_playing = false;
|
||||
self.player.reset();
|
||||
self.mini_player.update(None, self.player.status());
|
||||
self.library = Library::default();
|
||||
@@ -462,9 +523,13 @@ impl App {
|
||||
}
|
||||
Message::Navigate(route) => {
|
||||
self.sheet = None;
|
||||
self.menu = None;
|
||||
self.now_playing = false;
|
||||
self.nav.go(route);
|
||||
let (close, _) = self.search.update(search::Msg::CloseSuggestions, None);
|
||||
return Task::batch([close, self.on_enter(route)]);
|
||||
// Opening Search is a request to type.
|
||||
let focus = if route == Route::Search { focus_search() } else { Task::none() };
|
||||
return Task::batch([close, self.on_enter(route), focus]);
|
||||
}
|
||||
Message::AccountRefreshed(Ok(fresh)) => {
|
||||
if let Session::SignedIn { account, .. } = &mut self.session {
|
||||
@@ -476,6 +541,8 @@ impl App {
|
||||
return task;
|
||||
}
|
||||
}
|
||||
// Back from Now Playing returns to the page under it.
|
||||
Message::Back if self.now_playing => self.now_playing = false,
|
||||
Message::Back => {
|
||||
self.nav.back();
|
||||
return self.on_enter(self.nav.current());
|
||||
@@ -495,6 +562,10 @@ impl App {
|
||||
return self.want_lyrics();
|
||||
}
|
||||
Message::CloseDrawer => self.drawer = None,
|
||||
Message::ShowNowPlaying(show) => {
|
||||
self.now_playing = show;
|
||||
return self.want_lyrics();
|
||||
}
|
||||
Message::Player(msg) => {
|
||||
let before = self.player.track().map(|t| t.id.clone());
|
||||
let seeked = matches!(msg, player::Msg::Seek(_) | player::Msg::SeekCommit);
|
||||
@@ -521,6 +592,11 @@ impl App {
|
||||
self.toast(trf("“{}” plays next", &[&track.full_title()]));
|
||||
return self.update(Message::Player(player::Msg::PlayNext(track)));
|
||||
}
|
||||
Message::WindowOpened(id) => return iced::window::raw_id::<Message>(id).map(Message::MediaWindow),
|
||||
Message::MediaWindow(raw_id) => {
|
||||
self.media.attach_window(raw_id);
|
||||
self.media.update(self.player.track(), self.player.status(), self.player.position(), true);
|
||||
}
|
||||
Message::Media(command) => {
|
||||
use crate::media::Command as C;
|
||||
let status = self.player.status();
|
||||
@@ -539,6 +615,7 @@ impl App {
|
||||
};
|
||||
return self.update(Message::Player(msg));
|
||||
}
|
||||
Message::Shortcut(shortcut) => return self.shortcut(shortcut),
|
||||
Message::SkipFromMenu => {
|
||||
self.sheet = None;
|
||||
return self.update(Message::Player(player::Msg::Next));
|
||||
@@ -580,6 +657,79 @@ impl App {
|
||||
}
|
||||
}
|
||||
Message::CloseSheet => self.sheet = None,
|
||||
Message::OpenMenu(menu) => {
|
||||
self.sheet = None;
|
||||
let (close, _) = self.search.update(search::Msg::CloseSuggestions, None);
|
||||
self.menu = Some(*menu);
|
||||
return close;
|
||||
}
|
||||
Message::CloseMenu => self.menu = None,
|
||||
Message::MenuHover(i) => {
|
||||
let submenu = self.menu_entry(i).is_some_and(|e| matches!(e.action, menu::Action::Submenu));
|
||||
if let Some(menu) = &mut self.menu {
|
||||
menu.highlight = Some(i);
|
||||
menu.sub = match (submenu, menu.sub) {
|
||||
(true, open @ Some(_)) => open,
|
||||
(true, None) => Some(None),
|
||||
(false, _) => None,
|
||||
};
|
||||
}
|
||||
}
|
||||
Message::MenuSubHover(j) => {
|
||||
if let Some(menu) = &mut self.menu {
|
||||
menu.sub = Some(Some(j));
|
||||
}
|
||||
}
|
||||
Message::MenuSub(open) => {
|
||||
if let Some(menu) = &mut self.menu {
|
||||
menu.sub = open.then_some(menu.sub.flatten());
|
||||
}
|
||||
}
|
||||
Message::MenuPick(msg) => {
|
||||
self.menu = None;
|
||||
return self.update(*msg);
|
||||
}
|
||||
Message::PlayRoute { route, shuffle } => {
|
||||
let tracks = match self.pages.get(&route) {
|
||||
Some(Loadable::Loaded(Page::Album { tracks, .. } | Page::Playlist { tracks, .. })) => tracks.clone(),
|
||||
Some(Loadable::Loaded(Page::Artist { popular, .. })) => popular.clone(),
|
||||
Some(Loadable::Loading) => {
|
||||
self.pending_play = Some((route, shuffle));
|
||||
return Task::none();
|
||||
}
|
||||
_ => {
|
||||
let Some(task) = self.client().and_then(|c| detail::load(c, route)) else { return Task::none() };
|
||||
self.pending_play = Some((route, shuffle));
|
||||
self.pages.insert(route, Loadable::Loading);
|
||||
return task;
|
||||
}
|
||||
};
|
||||
if tracks.is_empty() {
|
||||
self.toast(tr("There's nothing to play here."));
|
||||
return Task::none();
|
||||
}
|
||||
return self.update(Message::PlayTracks { tracks, start: 0, shuffle });
|
||||
}
|
||||
Message::DragStart { playlist, track, index } => {
|
||||
self.menu = None;
|
||||
self.drag = Some(Drag { playlist, track, from: index, to: index });
|
||||
}
|
||||
Message::DragOver(to) => {
|
||||
if let Some(drag) = &mut self.drag {
|
||||
drag.to = to;
|
||||
}
|
||||
}
|
||||
Message::DragEnd => {
|
||||
let Some(Drag { playlist, track, from, to }) = self.drag.take() else { return Task::none() };
|
||||
if from == to {
|
||||
return Task::none();
|
||||
}
|
||||
// Show the new order now; the refresh after the edit confirms it.
|
||||
if let Some(Loadable::Loaded(Page::Playlist { tracks, .. })) = self.pages.get_mut(&Route::Playlist(playlist)) {
|
||||
*tracks = crate::widgets::track_list::moved(tracks, from, to);
|
||||
}
|
||||
return self.update(Message::MovePlaylistTrack { id: playlist, track, from, to });
|
||||
}
|
||||
Message::SheetText(text) => {
|
||||
if let Some(Sheet::NewPlaylist { name, .. } | Sheet::Rename { name, .. }) = &mut self.sheet {
|
||||
*name = text;
|
||||
@@ -707,7 +857,18 @@ impl App {
|
||||
{
|
||||
return task;
|
||||
}
|
||||
let failed = result.is_err();
|
||||
self.pages.insert(route, Loadable::from_result(result));
|
||||
if let Some((wanted, shuffle)) = self.pending_play
|
||||
&& wanted == route
|
||||
{
|
||||
self.pending_play = None;
|
||||
if failed {
|
||||
self.toast(tr("Couldn't load the tracks. Try again."));
|
||||
return Task::none();
|
||||
}
|
||||
return self.update(Message::PlayRoute { route, shuffle });
|
||||
}
|
||||
}
|
||||
Message::LoadHome => {
|
||||
let Some(client) = self.client().cloned() else { return Task::none() };
|
||||
@@ -849,6 +1010,119 @@ impl App {
|
||||
Task::none()
|
||||
}
|
||||
|
||||
fn shortcut(&mut self, shortcut: Shortcut) -> Task<Message> {
|
||||
use crate::media::Command;
|
||||
let to_player = Message::Player;
|
||||
let msg = match shortcut {
|
||||
Shortcut::TogglePlay => to_player(player::Msg::Toggle),
|
||||
Shortcut::Next => to_player(player::Msg::Next),
|
||||
Shortcut::Previous => to_player(player::Msg::Previous),
|
||||
Shortcut::SeekForward => Message::Media(Command::SeekBy { forward: true, by: shortcuts::SEEK_STEP }),
|
||||
Shortcut::SeekBack => Message::Media(Command::SeekBy { forward: false, by: shortcuts::SEEK_STEP }),
|
||||
Shortcut::VolumeUp => to_player(player::Msg::SetVolume(self.player.volume + shortcuts::VOLUME_STEP)),
|
||||
Shortcut::VolumeDown => to_player(player::Msg::SetVolume(self.player.volume - shortcuts::VOLUME_STEP)),
|
||||
Shortcut::ToggleLike => {
|
||||
let Some(track) = self.player.track().cloned() else { return Task::none() };
|
||||
let liked = self.library.liked.contains(&track.id);
|
||||
Message::LikeTrack(track, !liked)
|
||||
}
|
||||
Shortcut::FocusSearch => return focus_search(),
|
||||
Shortcut::Back if self.now_playing || self.nav.can_go_back() => Message::Back,
|
||||
Shortcut::Back => return Task::none(),
|
||||
Shortcut::Dismiss => {
|
||||
if self.drag.is_some() {
|
||||
self.drag = None;
|
||||
} else if self.menu.is_some() {
|
||||
self.menu = None;
|
||||
} else if self.sheet.is_some() {
|
||||
self.sheet = None;
|
||||
} else if self.search.suggestions().is_some() {
|
||||
return self.update(Message::Search(search::Msg::CloseSuggestions));
|
||||
} else if self.drawer.is_some() {
|
||||
self.drawer = None;
|
||||
} else {
|
||||
self.now_playing = false;
|
||||
}
|
||||
return Task::none();
|
||||
}
|
||||
Shortcut::Go(route) => Message::Navigate(route),
|
||||
Shortcut::NowPlaying if self.now_playing => Message::ShowNowPlaying(false),
|
||||
Shortcut::NowPlaying if self.player.track().is_some() => Message::ShowNowPlaying(true),
|
||||
Shortcut::NowPlaying => return Task::none(),
|
||||
Shortcut::MenuUp | Shortcut::MenuDown | Shortcut::MenuIn | Shortcut::MenuOut | Shortcut::MenuEnter => {
|
||||
return self.menu_key(shortcut);
|
||||
}
|
||||
};
|
||||
self.update(msg)
|
||||
}
|
||||
|
||||
/// Arrow keys and Enter inside an open menu.
|
||||
fn menu_key(&mut self, key: Shortcut) -> Task<Message> {
|
||||
let Some(open) = &self.menu else { return Task::none() };
|
||||
let groups = menu::groups(&open.target, &self.menu_ctx(&open.target));
|
||||
let entries: Vec<&menu::Entry> = menu::flat(&groups).collect();
|
||||
let subs = match open.track() {
|
||||
Some(track) => menu::sub_entries(track, self.own_playlists()),
|
||||
None => Vec::new(),
|
||||
};
|
||||
let highlighted = open.highlight.and_then(|i| entries.get(i));
|
||||
let on_submenu = highlighted.is_some_and(|e| matches!(e.action, menu::Action::Submenu));
|
||||
let (mut highlight, mut sub) = (open.highlight, open.sub);
|
||||
let mut pick = None;
|
||||
match (key, sub) {
|
||||
(Shortcut::MenuDown | Shortcut::MenuUp, Some(Some(j))) if !subs.is_empty() => {
|
||||
let n = subs.len();
|
||||
sub = Some(Some(if key == Shortcut::MenuDown { (j + 1) % n } else { (j + n - 1) % n }));
|
||||
}
|
||||
(Shortcut::MenuDown | Shortcut::MenuUp, _) => {
|
||||
highlight = menu::step(&entries, highlight, key == Shortcut::MenuDown);
|
||||
sub = None;
|
||||
}
|
||||
(Shortcut::MenuIn, _) if on_submenu => sub = Some(Some(0)),
|
||||
(Shortcut::MenuOut, Some(_)) => sub = None,
|
||||
(Shortcut::MenuEnter, Some(Some(j))) => pick = subs.get(j).cloned(),
|
||||
(Shortcut::MenuEnter, _) if on_submenu => sub = Some(Some(0)),
|
||||
(Shortcut::MenuEnter, _) => pick = highlighted.map(|e| (*e).clone()),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(menu::Entry { action: menu::Action::Send(msg), .. }) = pick {
|
||||
return self.update(Message::MenuPick(msg));
|
||||
}
|
||||
if let Some(open) = &mut self.menu {
|
||||
open.highlight = highlight;
|
||||
open.sub = sub;
|
||||
}
|
||||
Task::none()
|
||||
}
|
||||
|
||||
fn own_playlists(&self) -> &[PlaylistSummary] {
|
||||
self.library.playlists.get().map_or(&[], |p| p.own.as_slice())
|
||||
}
|
||||
|
||||
fn menu_ctx(&self, target: &menu::Target) -> menu::Ctx<'_> {
|
||||
use menu::Target;
|
||||
let (playing, liked, disliked) = match target {
|
||||
Target::Track { track, .. } => (
|
||||
self.player.track().is_some_and(|tr| tr.id == track.id),
|
||||
self.library.liked.contains(&track.id),
|
||||
self.likes.disliked_tracks.contains(&track.id),
|
||||
),
|
||||
Target::Album(a) => (false, self.likes.albums.contains(&a.id), false),
|
||||
Target::Playlist(p) => (false, self.likes.playlists.contains(&p.id), false),
|
||||
Target::Artist(a) => (false, self.likes.artists.contains(&a.id), false),
|
||||
};
|
||||
let me = match &self.session {
|
||||
Session::SignedIn { account, .. } => account.uid,
|
||||
_ => 0,
|
||||
};
|
||||
menu::Ctx { playing, liked, disliked, own_playlists: self.own_playlists(), me }
|
||||
}
|
||||
|
||||
fn menu_entry(&self, i: usize) -> Option<menu::Entry> {
|
||||
let open = self.menu.as_ref()?;
|
||||
menu::flat(&menu::groups(&open.target, &self.menu_ctx(&open.target))).nth(i).cloned()
|
||||
}
|
||||
|
||||
/// Loads what a route shows on first visit, and retries after a failure.
|
||||
fn on_enter(&mut self, route: Route) -> Task<Message> {
|
||||
match route {
|
||||
@@ -980,6 +1254,42 @@ impl App {
|
||||
}
|
||||
|
||||
fn shell<'a>(&'a self, t: &'static theme::Tokens, account: &'a Account) -> Element<'a, Message> {
|
||||
let liked = self.player.track().is_some_and(|tr| self.library.liked.contains(&tr.id));
|
||||
let lyrics = self.player.track().and_then(|tr| self.lyrics.get(&tr.id));
|
||||
let window = if self.now_playing {
|
||||
now_playing::view(now_playing::Ctx {
|
||||
t,
|
||||
player: &self.player,
|
||||
liked,
|
||||
drawer: self.drawer,
|
||||
covers: &self.covers,
|
||||
lyrics,
|
||||
})
|
||||
} else {
|
||||
self.browsing(t, account, liked, lyrics)
|
||||
};
|
||||
|
||||
let mut layers = stack![container(window).width(Fill).height(Fill).style(theme::app)];
|
||||
if let Some((text, _)) = &self.toast {
|
||||
layers = layers.push(sheet::toast(t, text));
|
||||
}
|
||||
if let Some(open) = &self.sheet {
|
||||
layers = layers.push(sheet::overlay(t, open));
|
||||
}
|
||||
if let Some(open) = &self.menu {
|
||||
layers = layers.push(menu::layer(t, open, self.menu_ctx(&open.target)));
|
||||
}
|
||||
layers.into()
|
||||
}
|
||||
|
||||
/// Sidebar, page and drawer over the player bar.
|
||||
fn browsing<'a>(
|
||||
&'a self,
|
||||
t: &'static theme::Tokens,
|
||||
account: &'a Account,
|
||||
liked: bool,
|
||||
lyrics: Option<&'a Loadable<Option<Arc<Lyrics>>>>,
|
||||
) -> Element<'a, Message> {
|
||||
let route = self.nav.current();
|
||||
let env = Env {
|
||||
t,
|
||||
@@ -988,6 +1298,8 @@ impl App {
|
||||
likes: &self.likes,
|
||||
playing: self.player.track().map(|tr| tr.id.as_str()),
|
||||
me: account.uid,
|
||||
menu_track: self.menu.as_ref().and_then(Menu::track).map(|tr| tr.id.as_str()),
|
||||
drag: self.drag.as_ref(),
|
||||
};
|
||||
|
||||
let page = scrollable(screens::view(screens::Ctx {
|
||||
@@ -1030,46 +1342,17 @@ impl App {
|
||||
.height(Fill);
|
||||
|
||||
if let Some(panel) = self.drawer {
|
||||
let lyrics = self.player.track().and_then(|tr| self.lyrics.get(&tr.id));
|
||||
body = body.push(vline()).push(drawer::view(t, panel, &self.player, &self.covers, lyrics));
|
||||
}
|
||||
|
||||
let window = column![
|
||||
column![
|
||||
body,
|
||||
hline(),
|
||||
container(player_bar::view(
|
||||
t,
|
||||
&self.player,
|
||||
self.player.track().is_some_and(|tr| self.library.liked.contains(&tr.id)),
|
||||
self.drawer,
|
||||
&self.covers,
|
||||
))
|
||||
container(player_bar::view(t, &self.player, liked, self.drawer, &self.covers))
|
||||
.height(shell::PLAYER)
|
||||
.style(theme::panel),
|
||||
];
|
||||
|
||||
let mut layers = stack![container(window).width(Fill).height(Fill).style(theme::app)];
|
||||
if let Some((text, _)) = &self.toast {
|
||||
layers = layers.push(sheet::toast(t, text));
|
||||
}
|
||||
if let Some(open) = &self.sheet {
|
||||
let track_id = match open {
|
||||
Sheet::Track { track, .. } => Some(track.id.as_str()),
|
||||
_ => None,
|
||||
};
|
||||
let own: &[PlaylistSummary] = self.library.playlists.get().map_or(&[], |p| p.own.as_slice());
|
||||
layers = layers.push(sheet::overlay(
|
||||
t,
|
||||
open,
|
||||
sheet::Ctx {
|
||||
playing: track_id.is_some() && self.player.track().map(|tr| tr.id.as_str()) == track_id,
|
||||
liked: track_id.is_some_and(|id| self.library.liked.contains(id)),
|
||||
disliked: track_id.is_some_and(|id| self.likes.disliked_tracks.contains(id)),
|
||||
own_playlists: own,
|
||||
},
|
||||
));
|
||||
}
|
||||
layers.into()
|
||||
]
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Runs the player's requests against the API.
|
||||
@@ -1165,6 +1448,12 @@ fn trace(message: &Message) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Puts the cursor in the search field with its text selected, so typing replaces the last query.
|
||||
fn focus_search() -> Task<Message> {
|
||||
use iced::widget::operation;
|
||||
Task::batch([operation::focus(topbar::SEARCH_ID), operation::select_all(topbar::SEARCH_ID)])
|
||||
}
|
||||
|
||||
fn restore() -> Task<Message> {
|
||||
Task::future(session::restore()).map(Message::Restored)
|
||||
}
|
||||
@@ -1208,6 +1497,15 @@ mod tests {
|
||||
Track::from_json(&format!(r#"{{"id":"{id}","title":"T{id}","durationMs":100000}}"#)).unwrap()
|
||||
}
|
||||
|
||||
fn open_menu(app: &mut App, track: Track, from: menu::Source) {
|
||||
let at = menu::Anchor::Point(iced::Point::new(400.0, 200.0));
|
||||
let _ = app.update(Message::OpenMenu(Box::new(Menu::new(menu::Target::Track { track, from }, at))));
|
||||
}
|
||||
|
||||
fn pick(app: &mut App, msg: Message) {
|
||||
let _ = app.update(Message::MenuPick(Box::new(msg)));
|
||||
}
|
||||
|
||||
fn upcoming(app: &App) -> Vec<String> {
|
||||
app.player.queue().map(|q| q.upcoming().map(|(_, t)| t.id.clone()).collect()).unwrap_or_default()
|
||||
}
|
||||
@@ -1217,9 +1515,9 @@ mod tests {
|
||||
let mut app = signed_in();
|
||||
let tracks: Arc<[Track]> = vec![track("a"), track("b"), track("c")].into();
|
||||
let _ = app.update(Message::PlayTracks { tracks, start: 0, shuffle: false });
|
||||
let _ = app.update(Message::OpenSheet(Sheet::Track { track: track("n"), playlist: None, choosing: false }));
|
||||
let _ = app.update(Message::PlayNext(track("n")));
|
||||
assert!(app.sheet.is_none());
|
||||
open_menu(&mut app, track("n"), menu::Source::List { playlist: None });
|
||||
pick(&mut app, Message::PlayNext(track("n")));
|
||||
assert!(app.menu.is_none());
|
||||
assert_eq!(upcoming(&app), ["n", "b", "c"]);
|
||||
let _ = app.update(Message::Player(player::Msg::Next));
|
||||
assert_eq!(app.player.track().unwrap().id, "n");
|
||||
@@ -1230,14 +1528,77 @@ mod tests {
|
||||
let mut app = signed_in();
|
||||
let tracks: Arc<[Track]> = vec![track("a"), track("b")].into();
|
||||
let _ = app.update(Message::PlayTracks { tracks, start: 0, shuffle: false });
|
||||
let _ = app.update(Message::OpenSheet(Sheet::Track { track: track("a"), playlist: None, choosing: false }));
|
||||
open_menu(&mut app, track("a"), menu::Source::List { playlist: None });
|
||||
let messages = click_in_window(&app, "Next track");
|
||||
assert_eq!(messages, ["SkipFromMenu"]);
|
||||
let _ = app.update(Message::SkipFromMenu);
|
||||
assert!(app.sheet.is_none());
|
||||
assert_eq!(messages, ["MenuPick(SkipFromMenu)"]);
|
||||
pick(&mut app, Message::SkipFromMenu);
|
||||
assert!(app.menu.is_none());
|
||||
assert_eq!(app.player.track().unwrap().id, "b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_closes_the_menu_then_the_drawer() {
|
||||
let mut app = signed_in();
|
||||
let _ = app.update(Message::ToggleDrawer(Panel::Queue));
|
||||
open_menu(&mut app, track("a"), menu::Source::List { playlist: None });
|
||||
let _ = app.update(Message::Shortcut(Shortcut::Dismiss));
|
||||
assert!(app.menu.is_none());
|
||||
assert_eq!(app.drawer, Some(Panel::Queue));
|
||||
let _ = app.update(Message::Shortcut(Shortcut::Dismiss));
|
||||
assert_eq!(app.drawer, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn now_playing_opens_with_a_track_and_closes_after_the_drawer() {
|
||||
let mut app = signed_in();
|
||||
let _ = app.update(Message::Shortcut(Shortcut::NowPlaying));
|
||||
assert!(!app.now_playing, "nothing to show yet");
|
||||
let _ = app.update(Message::Player(player::Msg::Play { tracks: vec![track("a")].into(), start: 0, shuffle: None }));
|
||||
let _ = app.update(Message::Shortcut(Shortcut::NowPlaying));
|
||||
assert!(app.now_playing);
|
||||
assert!(app.lyrics.contains_key("a"), "the lyric glance wants the lyrics");
|
||||
let _ = app.update(Message::ToggleDrawer(Panel::Queue));
|
||||
let _ = app.update(Message::Shortcut(Shortcut::Dismiss));
|
||||
assert!(app.now_playing && app.drawer.is_none());
|
||||
let _ = app.update(Message::Shortcut(Shortcut::Dismiss));
|
||||
assert!(!app.now_playing);
|
||||
|
||||
// Back leaves Now Playing without leaving the page under it.
|
||||
let _ = app.update(Message::Navigate(Route::Search));
|
||||
let _ = app.update(Message::ShowNowPlaying(true));
|
||||
let _ = app.update(Message::Shortcut(Shortcut::Back));
|
||||
assert!(!app.now_playing);
|
||||
assert_eq!(app.nav.current(), Route::Search);
|
||||
|
||||
// Going somewhere from its menu closes it.
|
||||
let _ = app.update(Message::ShowNowPlaying(true));
|
||||
let _ = app.update(Message::Navigate(Route::Album(1)));
|
||||
assert!(!app.now_playing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shortcuts_drive_the_player_and_navigation() {
|
||||
let mut app = signed_in();
|
||||
let tracks: Arc<[Track]> = vec![track("a"), track("b")].into();
|
||||
let _ = app.update(Message::PlayTracks { tracks, start: 0, shuffle: false });
|
||||
let _ = app.update(Message::Shortcut(Shortcut::Next));
|
||||
assert_eq!(app.player.track().unwrap().id, "b");
|
||||
|
||||
let _ = app.update(Message::Player(player::Msg::SetVolume(0.03)));
|
||||
let _ = app.update(Message::Shortcut(Shortcut::VolumeDown));
|
||||
assert_eq!(app.player.volume, 0.0);
|
||||
let _ = app.update(Message::Shortcut(Shortcut::VolumeUp));
|
||||
assert!((app.player.volume - shortcuts::VOLUME_STEP).abs() < f32::EPSILON);
|
||||
|
||||
// Back does nothing on the first page, then returns from where ⌘2 went.
|
||||
let _ = app.update(Message::Shortcut(Shortcut::Back));
|
||||
assert_eq!(app.nav.current(), Route::Home);
|
||||
let _ = app.update(Message::Shortcut(Shortcut::Go(Route::Wave)));
|
||||
assert_eq!(app.nav.current(), Route::Wave);
|
||||
let _ = app.update(Message::Shortcut(Shortcut::Back));
|
||||
assert_eq!(app.nav.current(), Route::Home);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn play_next_on_the_playing_track_says_so() {
|
||||
let mut app = signed_in();
|
||||
@@ -1268,8 +1629,8 @@ mod tests {
|
||||
app.pages.insert(Route::Playlist(id), Loadable::Loaded(crate::screens::detail::Page::Playlist { info, tracks: tracks.clone() }));
|
||||
app.nav = Navigator::new(Route::Playlist(id));
|
||||
let _ = app.update(Message::PlayTracks { tracks: tracks.clone(), start: 0, shuffle: false });
|
||||
let _ = app.update(Message::OpenSheet(Sheet::Track { track: tracks[5].clone(), playlist: Some((id, 5, 30)), choosing: false }));
|
||||
for label in ["Play next", "Add to queue", "Move up"] {
|
||||
open_menu(&mut app, tracks[5].clone(), menu::Source::List { playlist: Some((id, 5, 30)) });
|
||||
for label in ["Play next", "Add to queue", "Move to top"] {
|
||||
let messages = click_in_window(&app, label);
|
||||
assert!(
|
||||
!messages.iter().any(|m| m.starts_with("PlayTracks")),
|
||||
@@ -1306,9 +1667,9 @@ mod tests {
|
||||
fn similar_tracks_replace_the_queue_and_say_so() {
|
||||
let mut app = signed_in();
|
||||
let _ = app.update(Message::PlayTracks { tracks: vec![track("a"), track("b")].into(), start: 0, shuffle: false });
|
||||
let _ = app.update(Message::OpenSheet(Sheet::Track { track: track("a"), playlist: None, choosing: false }));
|
||||
let _ = app.update(Message::PlaySimilar(track("a")));
|
||||
assert!(app.sheet.is_none());
|
||||
open_menu(&mut app, track("a"), menu::Source::List { playlist: None });
|
||||
pick(&mut app, Message::PlaySimilar(track("a")));
|
||||
assert!(app.menu.is_none());
|
||||
let _ = app.update(Message::SimilarLoaded(track("a"), Ok(vec![track("s1"), track("s2")])));
|
||||
assert_eq!(app.player.track().unwrap().id, "s1");
|
||||
assert_eq!(upcoming(&app), ["s2"]);
|
||||
@@ -1337,14 +1698,137 @@ mod tests {
|
||||
if toast {
|
||||
app.toast("Added to Liked tracks");
|
||||
}
|
||||
let _ = app.update(Message::OpenSheet(Sheet::Track { track: track("n"), playlist: None, choosing: false }));
|
||||
open_menu(&mut app, track("n"), menu::Source::List { playlist: None });
|
||||
for label in ["Play next", "Add to queue", "Add to Liked tracks"] {
|
||||
let messages = click_in_window(&app, label);
|
||||
assert!(
|
||||
messages.first().is_some_and(|m| !m.starts_with("CloseSheet")),
|
||||
messages.first().is_some_and(|m| m.starts_with("MenuPick")),
|
||||
"{label} (toast: {toast}) produced {messages:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn own_playlist(app: &mut App, n: usize) -> (PlaylistId, Arc<[Track]>) {
|
||||
let id = PlaylistId { owner: 1, kind: 1002 };
|
||||
let tracks: Arc<[Track]> = (0..n).map(|i| track(&i.to_string())).collect();
|
||||
let info = ym_api::PlaylistPage {
|
||||
playlist: ym_api::PlaylistSummary::for_tests(id, "Дорога"),
|
||||
description: None,
|
||||
tracks: Vec::new(),
|
||||
};
|
||||
app.pages.insert(Route::Playlist(id), Loadable::Loaded(crate::screens::detail::Page::Playlist { info, tracks: tracks.clone() }));
|
||||
app.nav = Navigator::new(Route::Playlist(id));
|
||||
(id, tracks)
|
||||
}
|
||||
|
||||
fn page_ids(app: &App, id: PlaylistId) -> Vec<String> {
|
||||
match app.pages.get(&Route::Playlist(id)) {
|
||||
Some(Loadable::Loaded(crate::screens::detail::Page::Playlist { tracks, .. })) => tracks.iter().map(|t| t.id.clone()).collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropping_a_dragged_row_shows_the_new_order_at_once() {
|
||||
let mut app = signed_in();
|
||||
let (id, tracks) = own_playlist(&mut app, 5);
|
||||
let _ = app.update(Message::DragStart { playlist: id, track: tracks[1].clone(), index: 1 });
|
||||
let _ = app.update(Message::DragOver(3));
|
||||
let _ = app.update(Message::DragEnd);
|
||||
assert!(app.drag.is_none());
|
||||
assert_eq!(page_ids(&app, id), ["0", "2", "3", "1", "4"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_cancels_a_drag_without_moving_anything() {
|
||||
let mut app = signed_in();
|
||||
let (id, tracks) = own_playlist(&mut app, 5);
|
||||
let _ = app.update(Message::DragStart { playlist: id, track: tracks[0].clone(), index: 0 });
|
||||
let _ = app.update(Message::DragOver(4));
|
||||
let _ = app.update(Message::Shortcut(Shortcut::Dismiss));
|
||||
assert!(app.drag.is_none());
|
||||
let _ = app.update(Message::DragEnd);
|
||||
assert_eq!(page_ids(&app, id), ["0", "1", "2", "3", "4"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_list_previews_the_order_while_dragging() {
|
||||
let mut app = signed_in();
|
||||
let (id, tracks) = own_playlist(&mut app, 4);
|
||||
let _ = app.update(Message::DragStart { playlist: id, track: tracks[0].clone(), index: 0 });
|
||||
let _ = app.update(Message::DragOver(2));
|
||||
// A press on a row mid-drag must not start playback.
|
||||
let messages = click_in_window(&app, "T1");
|
||||
assert!(!messages.iter().any(|m| m.starts_with("PlayTracks")), "{messages:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn play_from_a_card_waits_for_the_page_then_plays() {
|
||||
let mut app = signed_in();
|
||||
let route = Route::Album(9);
|
||||
let _ = app.update(Message::PlayRoute { route, shuffle: false });
|
||||
assert!(matches!(app.pages.get(&route), Some(Loadable::Loading)));
|
||||
assert!(app.player.track().is_none());
|
||||
let mut info = ym_api::AlbumPage::from_json(r#"{"id":9,"title":"A","volumes":[[{"id":"x","title":"X"},{"id":"y","title":"Y"}]]}"#).unwrap();
|
||||
let tracks = std::mem::take(&mut info.tracks).into();
|
||||
let _ = app.update(Message::PageLoaded(route, Ok(crate::screens::detail::Page::Album { info, tracks })));
|
||||
assert_eq!(app.player.track().unwrap().id, "x");
|
||||
assert!(app.pending_play.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn play_from_a_card_says_so_when_the_page_fails() {
|
||||
let mut app = signed_in();
|
||||
let route = Route::Playlist(PlaylistId { owner: 2, kind: 5 });
|
||||
let _ = app.update(Message::PlayRoute { route, shuffle: true });
|
||||
let _ = app.update(Message::PageLoaded(route, Err(Error::Network("offline".into()))));
|
||||
assert!(app.player.track().is_none());
|
||||
assert!(app.toast.as_ref().is_some_and(|(t, _)| t.starts_with("Couldn't load the tracks")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrow_keys_and_enter_pick_from_the_menu() {
|
||||
let mut app = signed_in();
|
||||
let tracks: Arc<[Track]> = vec![track("a"), track("b"), track("c")].into();
|
||||
let _ = app.update(Message::PlayTracks { tracks, start: 0, shuffle: false });
|
||||
open_menu(&mut app, track("c"), menu::Source::List { playlist: None });
|
||||
let _ = app.update(Message::Shortcut(Shortcut::MenuDown));
|
||||
assert_eq!(app.menu.as_ref().unwrap().highlight, Some(0));
|
||||
let _ = app.update(Message::Shortcut(Shortcut::MenuEnter));
|
||||
assert!(app.menu.is_none(), "picking closes the menu");
|
||||
assert_eq!(upcoming(&app), ["c", "b"], "Play next moved c up");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_playlist_submenu_opens_on_hover_and_with_the_right_arrow() {
|
||||
let mut app = signed_in();
|
||||
open_menu(&mut app, track("a"), menu::Source::List { playlist: None });
|
||||
// Entry 4 is "Add to playlist": the first group has three entries.
|
||||
let _ = app.update(Message::MenuHover(4));
|
||||
assert_eq!(app.menu.as_ref().unwrap().sub, Some(None));
|
||||
let _ = app.update(Message::MenuHover(3));
|
||||
assert_eq!(app.menu.as_ref().unwrap().sub, None, "moving off it closes the list");
|
||||
let _ = app.update(Message::Shortcut(Shortcut::MenuDown));
|
||||
let _ = app.update(Message::Shortcut(Shortcut::MenuIn));
|
||||
assert_eq!(app.menu.as_ref().unwrap().sub, Some(Some(0)));
|
||||
let _ = app.update(Message::Shortcut(Shortcut::MenuOut));
|
||||
assert_eq!(app.menu.as_ref().unwrap().sub, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_from_the_queue_drops_the_track() {
|
||||
let mut app = signed_in();
|
||||
let tracks: Arc<[Track]> = vec![track("a"), track("b"), track("c")].into();
|
||||
let _ = app.update(Message::PlayTracks { tracks, start: 0, shuffle: false });
|
||||
open_menu(&mut app, track("b"), menu::Source::Queue { pos: 1 });
|
||||
let messages = click_in_window(&app, "Remove from queue");
|
||||
assert!(messages.first().is_some_and(|m| m.starts_with("MenuPick(Player(Remove { pos: 1")), "{messages:?}");
|
||||
// A track queued meanwhile shifts positions; the stale one removes nothing.
|
||||
let _ = app.update(Message::PlayNext(track("n")));
|
||||
pick(&mut app, Message::Player(player::Msg::Remove { pos: 1, id: "b".into() }));
|
||||
assert_eq!(upcoming(&app), ["n", "b", "c"]);
|
||||
pick(&mut app, Message::Player(player::Msg::Remove { pos: 2, id: "b".into() }));
|
||||
assert_eq!(upcoming(&app), ["n", "c"]);
|
||||
}
|
||||
}
|
||||
@@ -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> {
|
||||
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();
|
||||
}
|
||||
let id = track.id.clone();
|
||||
self.lyrics.insert(id.clone(), Loadable::Loading);
|
||||
let track = track.clone();
|
||||
self.lyrics.insert(track.id.clone(), Loadable::Loading);
|
||||
Task::future(async move {
|
||||
let result = client.lyrics(&id).await.map(|l| l.map(Arc::new));
|
||||
Message::LyricsLoaded(id, result)
|
||||
let result = client.lyrics(&track).await.map(|l| l.map(Arc::new));
|
||||
Message::LyricsLoaded(track.id, result)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -24,10 +24,15 @@ pub const LARGE: u32 = 400;
|
||||
/// Downloads in flight at once.
|
||||
const PARALLEL: usize = 8;
|
||||
|
||||
/// Side of the Now Playing backdrop in pixels; it is stretched over the window.
|
||||
const BACKDROP: u32 = 32;
|
||||
|
||||
pub struct Covers {
|
||||
images: HashMap<String, image::Handle>,
|
||||
pending: 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.
|
||||
version: u64,
|
||||
dirty: bool,
|
||||
@@ -42,6 +47,7 @@ impl Default for Covers {
|
||||
images: HashMap::new(),
|
||||
pending: HashSet::new(),
|
||||
failed: HashSet::new(),
|
||||
backdrops: HashMap::new(),
|
||||
version: 0,
|
||||
dirty: false,
|
||||
dir,
|
||||
@@ -55,6 +61,20 @@ impl Covers {
|
||||
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 {
|
||||
self.version
|
||||
}
|
||||
@@ -136,6 +156,14 @@ async fn load(client: &YmClient, url: &str, dir: Option<PathBuf>, gate: &Semapho
|
||||
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).
|
||||
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));
|
||||
@@ -176,6 +204,27 @@ mod tests {
|
||||
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]
|
||||
fn arrivals_bump_version_only_on_flush() {
|
||||
let mut covers = Covers { dir: None, ..Covers::default() };
|
||||
|
||||
@@ -10,6 +10,17 @@ pub fn get(english: &str) -> Option<&'static str> {
|
||||
"Collection" => "Коллекция",
|
||||
"Podcasts" => "Подкасты",
|
||||
"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, Podcasts" => "Главная, Моя волна, Поиск, Коллекция, Подкасты",
|
||||
"Album" => "Альбом",
|
||||
"Artist" => "Исполнитель",
|
||||
"Playlist" => "Плейлист",
|
||||
@@ -264,12 +275,13 @@ pub fn get(english: &str) -> Option<&'static str> {
|
||||
"Очередь пока пуста. Здесь появятся треки, которые вы включите, и те, что за ними."
|
||||
}
|
||||
"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." => {
|
||||
"Не удалось загрузить текст. Проверьте подключение и попробуйте ещё раз."
|
||||
}
|
||||
"Loading lyrics…" => "Загружаем текст…",
|
||||
"Written by {}" => "Авторы: {}",
|
||||
"Lyrics from LRCLIB" => "Текст из LRCLIB",
|
||||
"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 down" => "Переместить ниже",
|
||||
"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" => "Новый плейлист",
|
||||
"Rename playlist" => "Переименовать плейлист",
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
// No console window behind the app in Windows release builds.
|
||||
#![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")]
|
||||
|
||||
mod app;
|
||||
mod covers;
|
||||
mod i18n;
|
||||
@@ -7,6 +10,7 @@ mod player;
|
||||
mod route;
|
||||
mod screens;
|
||||
mod session;
|
||||
mod shortcuts;
|
||||
mod store;
|
||||
#[cfg(feature = "snapshot")]
|
||||
mod snapshot;
|
||||
@@ -18,6 +22,10 @@ use iced::{Size, window};
|
||||
use app::App;
|
||||
use ui::theme;
|
||||
|
||||
/// The Linux application id: the window's Wayland app id / X11 class and the `.desktop` name.
|
||||
#[cfg(target_os = "linux")]
|
||||
const APP_ID: &str = "it.panov.musyx.desktop";
|
||||
|
||||
fn main() -> iced::Result {
|
||||
let app = iced::application(App::new, App::update, App::view)
|
||||
.title(App::title)
|
||||
@@ -28,6 +36,12 @@ fn main() -> iced::Result {
|
||||
size: Size::new(1280.0, 800.0),
|
||||
min_size: Some(Size::new(960.0, 620.0)),
|
||||
icon: window::icon::from_file_data(include_bytes!("../assets/icon/musyx.png"), None).ok(),
|
||||
// Matches the installed `it.panov.musyx.desktop.desktop`, so the shell shows its name and icon.
|
||||
#[cfg(target_os = "linux")]
|
||||
platform_specific: window::settings::PlatformSpecific {
|
||||
application_id: APP_ID.to_owned(),
|
||||
..Default::default()
|
||||
},
|
||||
..window::Settings::default()
|
||||
})
|
||||
.centered();
|
||||
|
||||
+22
-14
@@ -71,21 +71,16 @@ impl Media {
|
||||
{
|
||||
*inbox = Some(rx);
|
||||
}
|
||||
let controls = MediaControls::new(PlatformConfig { display_name: "Musyx", dbus_name: "musyx", hwnd: None })
|
||||
.and_then(|mut c| {
|
||||
c.attach(|event| {
|
||||
if let Some(command) = Command::from_event(event) {
|
||||
send(command);
|
||||
}
|
||||
})?;
|
||||
Ok(c)
|
||||
});
|
||||
match controls {
|
||||
Ok(c) => Self { controls: Some(c), shown: None },
|
||||
Err(e) => {
|
||||
eprintln!("media controls unavailable: {e:?}");
|
||||
Self { controls: None, shown: None }
|
||||
// Windows ties the controls to a window, so they wait for `attach_window`.
|
||||
let controls = if cfg!(windows) { None } else { connect(None) };
|
||||
Self { controls, shown: None }
|
||||
}
|
||||
|
||||
/// Connects the controls to the main window (Windows needs its HWND, from `window::raw_id`).
|
||||
pub fn attach_window(&mut self, raw_id: u64) {
|
||||
if cfg!(windows) && self.controls.is_none() {
|
||||
self.controls = connect(Some(raw_id as *mut std::ffi::c_void));
|
||||
self.shown = None;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,6 +120,19 @@ impl Media {
|
||||
}
|
||||
}
|
||||
|
||||
fn connect(hwnd: Option<*mut std::ffi::c_void>) -> Option<MediaControls> {
|
||||
let controls = MediaControls::new(PlatformConfig { display_name: "Musyx", dbus_name: "musyx", hwnd })
|
||||
.and_then(|mut c| {
|
||||
c.attach(|event| {
|
||||
if let Some(command) = Command::from_event(event) {
|
||||
send(command);
|
||||
}
|
||||
})?;
|
||||
Ok(c)
|
||||
});
|
||||
controls.map_err(|e| eprintln!("media controls unavailable: {e:?}")).ok()
|
||||
}
|
||||
|
||||
pub fn subscription() -> Subscription<Command> {
|
||||
Subscription::run(commands)
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ impl NowPlaying {
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
fn line(&self) -> String {
|
||||
if self.artist.is_empty() { self.title.clone() } else { format!("{} — {}", self.title, self.artist) }
|
||||
}
|
||||
|
||||
@@ -55,6 +55,9 @@ pub enum Msg {
|
||||
SetVolume(f32),
|
||||
ToggleMute,
|
||||
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> },
|
||||
Prefetched { track_id: String, result: Result<Audio, Error> },
|
||||
/// Start a station (`type:tag`).
|
||||
@@ -321,6 +324,14 @@ impl Player {
|
||||
}
|
||||
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) => {
|
||||
let mut effects = self.leave(false);
|
||||
if let Some(queue) = &mut self.queue {
|
||||
|
||||
@@ -161,6 +161,23 @@ impl<T> Queue<T> {
|
||||
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.
|
||||
pub fn clear_upcoming(&mut self) {
|
||||
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());
|
||||
}
|
||||
|
||||
#[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]
|
||||
fn start_is_clamped() {
|
||||
assert_eq!(*q(3, 99).current(), 2);
|
||||
|
||||
@@ -105,6 +105,7 @@ pub fn home<'a>(env: Env<'a>, discover: &'a Discover, hero: Element<'a, Message>
|
||||
hues: p.playlist.hues(),
|
||||
round: false,
|
||||
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::{duration_words, line, para, tracks_word};
|
||||
use crate::widgets::card::{self, Card};
|
||||
use crate::widgets::menu::Target;
|
||||
use crate::widgets::track_list::{self, Env};
|
||||
use crate::widgets::track_row::Columns;
|
||||
use crate::i18n::{tr, trf};
|
||||
@@ -277,6 +278,7 @@ pub fn album_card<'a>(t: &'static Tokens, covers: &Covers, a: &AlbumSummary) ->
|
||||
hues: a.hues(),
|
||||
round: false,
|
||||
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(),
|
||||
round: true,
|
||||
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(),
|
||||
round: false,
|
||||
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(),
|
||||
round: false,
|
||||
on_press: Message::OpenClip(c.clone()),
|
||||
menu: None,
|
||||
},
|
||||
liked,
|
||||
Message::LikeClip(c.clone(), !liked),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! 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 crate::app::Message;
|
||||
use crate::store::{Appearance, Locale, Quality, Settings};
|
||||
@@ -42,6 +42,7 @@ pub fn view<'a>(t: &'static Tokens, settings: &Settings, account: Element<'a, Me
|
||||
.spacing(12)
|
||||
.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),
|
||||
]
|
||||
.spacing(28)
|
||||
@@ -64,3 +65,17 @@ fn chip<'a>(t: &'static Tokens, label: &'static str, on: bool, msg: Message) ->
|
||||
.on_press_maybe((!on).then_some(msg))
|
||||
.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 code_box = row![
|
||||
container(line(spaced(&w.code.user_code), theme::DISPLAY, 30.0, t.fg))
|
||||
.padding([14, 18])
|
||||
// Taller line so descenders (j, g, y) aren't clipped; padding shrinks to keep the card size.
|
||||
container(line(spaced(&w.code.user_code), theme::DISPLAY, size::DISPLAY_S, t.fg).line_height(1.5))
|
||||
.padding([11, 18])
|
||||
.style(theme::card),
|
||||
ghost(t, Icon::Copy, if copied { tr("Copied") } else { tr("Copy code") }, Msg::CopyCode),
|
||||
]
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
//! 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'..='5' => 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, Podcasts"), vec![format!("{cmd}1 … {cmd}5")]),
|
||||
(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::Podcasts)));
|
||||
assert_eq!(press(ch("6"), Code::Digit6, 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_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.
|
||||
|
||||
use std::path::PathBuf;
|
||||
@@ -34,13 +40,20 @@ pub struct Config {
|
||||
pub lang: Option<Lang>,
|
||||
/// `MUSYX_SNAPSHOT_DELAY` in ms before capturing (default 1500; live runs need longer).
|
||||
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 {
|
||||
pub fn from_env() -> Option<Self> {
|
||||
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 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| {
|
||||
Some(match r.as_str() {
|
||||
"home" => Route::Home,
|
||||
@@ -50,6 +63,7 @@ impl Config {
|
||||
"podcasts" => Route::Podcasts,
|
||||
"settings" => Route::Settings,
|
||||
"album" => Route::Album(1),
|
||||
"playlist" => Route::Playlist(OWN_PLAYLIST),
|
||||
"chart" => Route::Chart,
|
||||
// `artist:41075`, for live runs.
|
||||
other => Route::Artist(other.strip_prefix("artist:")?.parse().ok()?),
|
||||
@@ -70,7 +84,9 @@ impl Config {
|
||||
let delay = var("MUSYX_SNAPSHOT_DELAY")
|
||||
.and_then(|d| d.parse().ok())
|
||||
.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.
|
||||
@@ -134,6 +150,43 @@ impl Config {
|
||||
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.
|
||||
pub fn capture<M: Send + 'static>(self) -> Task<M> {
|
||||
Task::future(tokio::time::sleep(self.delay))
|
||||
|
||||
@@ -65,6 +65,11 @@ icons! {
|
||||
Clock => "clock-3",
|
||||
Tune => "sliders-horizontal",
|
||||
Settings => "settings",
|
||||
MoveTop => "arrow-up-to-line",
|
||||
MoveBottom => "arrow-down-to-line",
|
||||
Artist => "user",
|
||||
Expand => "maximize-2",
|
||||
Collapse => "chevron-down",
|
||||
}
|
||||
|
||||
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 {
|
||||
container::Style {
|
||||
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.
|
||||
pub fn cover(h1: f32, h2: f32, corner: f32) -> impl Fn(&Theme) -> 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.
|
||||
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 {
|
||||
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 engaged = matches!(status, slider::Status::Hovered | slider::Status::Dragged);
|
||||
slider::Style {
|
||||
rail: slider::Rail {
|
||||
backgrounds: (fill.into(), t.raised.into()),
|
||||
width: 4.0,
|
||||
border: Border { radius: 2.0.into(), ..Border::default() },
|
||||
width,
|
||||
border: Border { radius: (width / 2.0).into(), ..Border::default() },
|
||||
},
|
||||
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(),
|
||||
border_width: 0.0,
|
||||
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::line;
|
||||
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.
|
||||
pub const WIDTH: f32 = 168.0;
|
||||
@@ -20,6 +22,8 @@ pub struct Card {
|
||||
/// Artists get a round cover.
|
||||
pub round: bool,
|
||||
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> {
|
||||
@@ -47,7 +51,7 @@ fn build<'a>(t: &'static Tokens, covers: &Covers, card: Card, action: Option<Ele
|
||||
.spacing(2)
|
||||
.width(Fill)
|
||||
.clip(true);
|
||||
button(
|
||||
let button = button(
|
||||
column![
|
||||
covers::view(covers, card.cover, card.hues, WIDTH, corner),
|
||||
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))
|
||||
.style(theme::nav_item(false))
|
||||
.on_press(card.on_press)
|
||||
.into()
|
||||
.on_press(card.on_press);
|
||||
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.
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
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 crate::app::Message;
|
||||
@@ -13,6 +13,8 @@ use crate::player::{Msg, Player, Queue};
|
||||
use crate::screens::Loadable;
|
||||
use crate::ui::icons::{Icon, icon};
|
||||
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::ui::{line, para};
|
||||
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, Some(_)) => match lyrics {
|
||||
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![
|
||||
note(t, tr("Couldn't load the lyrics. Check your connection and try again.")),
|
||||
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);
|
||||
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(
|
||||
container(para(trf("Written by {}", &[&l.writers.join(", ")]), size::SMALL, t.muted))
|
||||
.padding(iced::Padding::default().top(18).left(8).right(8)),
|
||||
container(para(credit, size::SMALL, t.muted)).padding(iced::Padding::default().top(18).left(8).right(8)),
|
||||
);
|
||||
}
|
||||
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| {
|
||||
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>| {
|
||||
button(
|
||||
let item = |track: &Track, now: bool, msg: Option<Message>, from: Source| {
|
||||
let target = Target::Track { track: track.clone(), from };
|
||||
let row = button(
|
||||
row![
|
||||
covers::view(covers, track.cover_url(covers::SMALL), track.hues(), 40.0, radius::SMALL_COVER),
|
||||
column![
|
||||
@@ -160,18 +167,19 @@ fn queue_list<'a>(t: &'static Tokens, queue: &'a Queue<Track>, covers: &Covers)
|
||||
.width(Fill)
|
||||
.padding([6, 8])
|
||||
.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 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 {
|
||||
tr("Nothing after this").into()
|
||||
} else {
|
||||
trf("Next up · {}", &[&remaining])
|
||||
}));
|
||||
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 {
|
||||
list = list.push(
|
||||
|
||||
@@ -0,0 +1,519 @@
|
||||
//! 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;
|
||||
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>> {
|
||||
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
|
||||
}
|
||||
|
||||
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 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 drawer;
|
||||
pub mod menu;
|
||||
pub mod now_playing;
|
||||
pub mod player_bar;
|
||||
pub mod sheet;
|
||||
pub mod sidebar;
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
//! 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.as_ref().filter(|a| !a.title.is_empty()) {
|
||||
info = info.push(line(album.title.as_str(), 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);
|
||||
|
||||
let heart = 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),
|
||||
heart,
|
||||
more,
|
||||
pill(Icon::Queue, Panel::Queue, tr("Queue")),
|
||||
pill(Icon::Lyrics, Panel::Lyrics, tr("Lyrics")),
|
||||
button(icon(if p.muted { Icon::Muted } else { Icon::Volume }, t.muted))
|
||||
.padding(8)
|
||||
.style(theme::icon_button(None))
|
||||
.on_press(send(Msg::ToggleMute)),
|
||||
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::line;
|
||||
use crate::ui::theme::{self, Tokens, radius, size};
|
||||
use crate::widgets::anchor::anchor;
|
||||
use crate::widgets::drawer::Panel;
|
||||
use crate::widgets::menu::{Anchor, Menu, Source, Target};
|
||||
use crate::i18n::tr;
|
||||
|
||||
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),
|
||||
};
|
||||
|
||||
// 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![
|
||||
cover,
|
||||
column![
|
||||
@@ -76,6 +81,15 @@ fn now_playing<'a>(t: &'static Tokens, p: &'a Player, liked: bool, covers: &Cove
|
||||
]
|
||||
.spacing(2)
|
||||
.width(Length::Shrink),
|
||||
]
|
||||
.spacing(12)
|
||||
.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)))));
|
||||
|
||||
row![
|
||||
about,
|
||||
button(icon(
|
||||
if liked { Icon::HeartFilled } else { Icon::Heart },
|
||||
if liked { t.like } else { t.muted },
|
||||
@@ -188,6 +202,12 @@ fn extras<'a>(t: &'static Tokens, p: &'a Player, drawer: Option<Panel>) -> Eleme
|
||||
|
||||
let volume = if p.muted { 0.0 } else { p.volume };
|
||||
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::Queue, Panel::Queue))
|
||||
.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::{Alignment, Element, Fill, Length};
|
||||
use ym_api::{PlaylistId, PlaylistSummary, Track};
|
||||
use iced::widget::{button, column, container, mouse_area, opaque, row, space, text_input};
|
||||
use iced::{Alignment, Element, Fill};
|
||||
use ym_api::{PlaylistId, Track};
|
||||
|
||||
use crate::app::Message;
|
||||
use crate::route::Route;
|
||||
use crate::ui::icons::{Icon, icon};
|
||||
use crate::ui::theme::{self, Tokens, radius, size};
|
||||
use crate::ui::{line, para};
|
||||
@@ -13,13 +13,6 @@ use crate::i18n::{tr, trf};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
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> },
|
||||
Rename { id: PlaylistId, name: String },
|
||||
ConfirmDelete { id: PlaylistId, title: String },
|
||||
@@ -27,17 +20,8 @@ pub enum Sheet {
|
||||
|
||||
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.
|
||||
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(
|
||||
container(space()).width(Fill).height(Fill).style(|_| container::Style {
|
||||
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);
|
||||
|
||||
let card = container(body(t, sheet, ctx))
|
||||
let card = container(body(t, sheet))
|
||||
.width(380)
|
||||
.padding(18)
|
||||
.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()
|
||||
}
|
||||
|
||||
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 {
|
||||
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 } => {
|
||||
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.") };
|
||||
@@ -198,19 +110,6 @@ fn frame<'a>(t: &'static Tokens, title: String, subtitle: Option<String>, conten
|
||||
.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> {
|
||||
text_input(placeholder, value)
|
||||
.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))
|
||||
.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::covers::{self, Covers};
|
||||
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::widgets::track_row::{self, Columns};
|
||||
|
||||
@@ -24,6 +24,29 @@ pub struct Env<'a> {
|
||||
pub playing: Option<&'a str>,
|
||||
/// The signed-in user's uid, to tell their own playlists apart.
|
||||
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)]
|
||||
@@ -37,6 +60,9 @@ struct Key {
|
||||
dark: bool,
|
||||
playlist: Option<PlaylistId>,
|
||||
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> {
|
||||
@@ -55,7 +81,7 @@ pub fn view_with<'a>(
|
||||
|
||||
/// 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> {
|
||||
build(env, tracks, Columns::FULL, None, Some(id))
|
||||
build(env, tracks, Columns::OWN_PLAYLIST, None, Some(id))
|
||||
}
|
||||
|
||||
fn build<'a>(
|
||||
@@ -65,7 +91,8 @@ fn build<'a>(
|
||||
shifts: Option<Arc<[i32]>>,
|
||||
playlist: Option<PlaylistId>,
|
||||
) -> 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 {
|
||||
list: (tracks.as_ptr() as usize, tracks.len()),
|
||||
columns,
|
||||
@@ -76,11 +103,19 @@ fn build<'a>(
|
||||
dark: t == &theme::DARK,
|
||||
playlist,
|
||||
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();
|
||||
|
||||
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(|| {
|
||||
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()),
|
||||
liked: 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(),
|
||||
playlist: key.playlist.map(|id| (id, index, tracks.len())),
|
||||
choosing: false,
|
||||
}),
|
||||
from: Source::List { playlist: key.playlist.map(|id| (id, index, tracks.len())) },
|
||||
},
|
||||
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,
|
||||
columns,
|
||||
shift: shifts.as_ref().and_then(|s| s.get(index).copied()).unwrap_or(0),
|
||||
@@ -108,3 +148,16 @@ fn build<'a>(
|
||||
})
|
||||
.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
|
||||
//! 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::{Alignment, Element, Fill, Length};
|
||||
use iced::widget::{button, column, container, mouse_area, row, space};
|
||||
use iced::{Alignment, Element, Fill, Length, mouse};
|
||||
use ym_api::Track;
|
||||
|
||||
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::line;
|
||||
use crate::ui::theme::{self, Tokens, size};
|
||||
@@ -21,14 +24,19 @@ pub struct Columns {
|
||||
pub album: bool,
|
||||
/// Chart lists show how far each track moved.
|
||||
pub shift: bool,
|
||||
/// The user's own playlists: a handle to drag rows into a new order.
|
||||
pub grip: bool,
|
||||
}
|
||||
|
||||
impl Columns {
|
||||
pub const FULL: Columns = Columns { cover: true, album: true, shift: false };
|
||||
pub const ALBUM_PAGE: Columns = Columns { cover: false, album: false, shift: false };
|
||||
pub const CHART: Columns = Columns { cover: true, album: true, shift: true };
|
||||
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, grip: false };
|
||||
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;
|
||||
|
||||
pub struct Row<'a> {
|
||||
pub index: usize,
|
||||
pub track: &'a Track,
|
||||
@@ -40,7 +48,14 @@ pub struct Row<'a> {
|
||||
pub shift: i32,
|
||||
pub on_press: 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`.
|
||||
@@ -59,10 +74,16 @@ pub fn view(t: &'static Tokens, r: Row<'_>) -> Element<'static, Message> {
|
||||
(false, false) => t.fg,
|
||||
};
|
||||
|
||||
let mut content = row![container(number).width(36).center_x(36)]
|
||||
.spacing(12)
|
||||
.align_y(Alignment::Center)
|
||||
.height(HEIGHT);
|
||||
let mut content = row![].spacing(12).align_y(Alignment::Center).height(HEIGHT);
|
||||
if r.columns.grip {
|
||||
let grip = container(icon(Icon::Grip, if r.lit { t.fg } else { t.muted })).width(GRIP).center_x(GRIP);
|
||||
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 {
|
||||
content = content.push(crate::screens::browse::shift_marker(t, r.shift));
|
||||
}
|
||||
@@ -105,28 +126,35 @@ pub fn view(t: &'static Tokens, r: Row<'_>) -> Element<'static, Message> {
|
||||
.width(52)
|
||||
.align_right(52),
|
||||
)
|
||||
.push(
|
||||
button(icon(Icon::More, t.muted))
|
||||
.padding(8)
|
||||
.style(theme::icon_button(None))
|
||||
.on_press(r.on_more),
|
||||
);
|
||||
.push({
|
||||
let target = r.menu.clone();
|
||||
// The anchor takes the click and reports where the button is; `on_press`
|
||||
// only keeps the hover style, and its message is never sent.
|
||||
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)
|
||||
.padding([0, 10])
|
||||
.style(theme::nav_item(false))
|
||||
.on_press_maybe((!unavailable).then_some(r.on_press))
|
||||
.into()
|
||||
.style(theme::nav_item(r.lit))
|
||||
.on_press_maybe((!unavailable && r.on_drag_over.is_none()).then_some(r.on_press));
|
||||
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`].
|
||||
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 mut heads = row![container(label("#")).width(36).center_x(36)]
|
||||
.spacing(12)
|
||||
.align_y(Alignment::Center)
|
||||
.padding([0, 10]);
|
||||
let mut heads = row![].spacing(12).align_y(Alignment::Center).padding([0, 10]);
|
||||
if columns.grip {
|
||||
heads = heads.push(space().width(GRIP));
|
||||
}
|
||||
heads = heads.push(container(label("#")).width(36).center_x(36));
|
||||
if columns.shift {
|
||||
heads = heads.push(space().width(14));
|
||||
}
|
||||
|
||||
@@ -8,6 +8,8 @@ publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
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"] }
|
||||
thiserror = "2"
|
||||
serde_json = "1"
|
||||
|
||||
@@ -695,8 +695,16 @@ impl YmClient {
|
||||
|
||||
// ---- Lyrics ----
|
||||
|
||||
/// Synced lyrics when Yandex has them, else plain text; `None` when there are none.
|
||||
pub async fn lyrics(&self, track_id: &str) -> Result<Option<Lyrics>> {
|
||||
/// Synced lyrics when Yandex has them, else plain text, else whatever LRCLIB
|
||||
/// has; `None` when neither has any.
|
||||
pub async fn lyrics(&self, track: &Track) -> Result<Option<Lyrics>> {
|
||||
if 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] {
|
||||
let meta = match self.inner.track_lyrics(track_id, format).await {
|
||||
Ok(meta) => meta,
|
||||
|
||||
@@ -23,11 +23,19 @@ pub struct LyricLine {
|
||||
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)]
|
||||
pub struct Lyrics {
|
||||
pub lines: Vec<LyricLine>,
|
||||
pub synced: bool,
|
||||
pub writers: Vec<String>,
|
||||
pub source: LyricsSource,
|
||||
}
|
||||
|
||||
impl Lyrics {
|
||||
@@ -45,6 +53,7 @@ impl Lyrics {
|
||||
lines: text.lines().map(|l| LyricLine { at: None, text: l.trim_end().to_owned() }).collect(),
|
||||
synced: false,
|
||||
writers,
|
||||
source: LyricsSource::Yandex,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,7 +81,7 @@ impl Lyrics {
|
||||
}
|
||||
}
|
||||
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 error;
|
||||
mod library;
|
||||
mod lrclib;
|
||||
mod models;
|
||||
mod wave;
|
||||
|
||||
@@ -24,5 +25,5 @@ pub use wave::{
|
||||
Character, Language, MY_WAVE, Mood, PlayReport, Station, WaveBatch, WaveEvent, WaveSettings,
|
||||
};
|
||||
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};
|
||||
@@ -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
|
||||
&& secs > 0.0
|
||||
{
|
||||
let duration = secs.round().to_string();
|
||||
let query = [
|
||||
("track_name", track.title.as_str()),
|
||||
("artist_name", artist),
|
||||
("album_name", album.title.as_str()),
|
||||
("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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
# Maintainer: Yuriy Panov <uriy.panov@gmail.com>
|
||||
# Builds the checked-out commit of this repository: run `makepkg -si` in this directory.
|
||||
pkgname=musyx
|
||||
pkgver=0.3.1
|
||||
pkgrel=1
|
||||
pkgdesc='Desktop player for Yandex Music (unofficial)'
|
||||
arch=('x86_64' 'aarch64')
|
||||
license=('MIT' 'OFL-1.1' 'ISC')
|
||||
depends=('alsa-lib' 'dbus' 'gcc-libs' 'glibc' 'libxkbcommon' 'wayland' 'hicolor-icon-theme')
|
||||
optdepends=('gnome-keyring: keeps the sign-in (any Secret Service provider works)'
|
||||
'vulkan-driver: GPU rendering')
|
||||
makedepends=('cargo' 'git' 'imagemagick')
|
||||
options=('!lto' '!debug')
|
||||
source=("$pkgname::git+file://${startdir%/packaging/arch}")
|
||||
sha256sums=('SKIP')
|
||||
|
||||
app_id=it.panov.musyx.desktop
|
||||
|
||||
pkgver() {
|
||||
cd "$pkgname"
|
||||
sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1
|
||||
}
|
||||
|
||||
prepare() {
|
||||
cd "$pkgname"
|
||||
export RUSTUP_TOOLCHAIN=stable
|
||||
cargo fetch --locked --target "$(rustc -vV | sed -n 's/host: //p')"
|
||||
}
|
||||
|
||||
build() {
|
||||
cd "$pkgname"
|
||||
export RUSTUP_TOOLCHAIN=stable CARGO_TARGET_DIR=target
|
||||
cargo build --frozen --release -p musyx
|
||||
}
|
||||
|
||||
check() {
|
||||
cd "$pkgname"
|
||||
export RUSTUP_TOOLCHAIN=stable CARGO_TARGET_DIR=target
|
||||
cargo test --frozen --release --workspace
|
||||
}
|
||||
|
||||
package() {
|
||||
cd "$pkgname"
|
||||
install -Dm755 target/release/musyx "$pkgdir/usr/bin/musyx"
|
||||
install -Dm644 "packaging/linux/$app_id.desktop" "$pkgdir/usr/share/applications/$app_id.desktop"
|
||||
install -Dm644 "packaging/linux/$app_id.metainfo.xml" "$pkgdir/usr/share/metainfo/$app_id.metainfo.xml"
|
||||
for size in 16 32 48 64 128 256 512; do
|
||||
install -dm755 "$pkgdir/usr/share/icons/hicolor/${size}x${size}/apps"
|
||||
magick crates/musyx/assets/icon/musyx.png -resize "${size}x${size}" \
|
||||
"$pkgdir/usr/share/icons/hicolor/${size}x${size}/apps/$app_id.png"
|
||||
done
|
||||
install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
|
||||
install -Dm644 crates/musyx/assets/fonts/OFL-*.txt -t "$pkgdir/usr/share/licenses/$pkgname"
|
||||
install -Dm644 crates/musyx/assets/icons/LICENSE.txt "$pkgdir/usr/share/licenses/$pkgname/LICENSE-lucide.txt"
|
||||
install -Dm644 README.md "$pkgdir/usr/share/doc/$pkgname/README.md"
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Musyx
|
||||
GenericName=Music Player
|
||||
GenericName[ru]=Музыкальный проигрыватель
|
||||
Comment=Desktop player for Yandex Music
|
||||
Comment[ru]=Настольный проигрыватель для Яндекс Музыки
|
||||
Exec=musyx
|
||||
Icon=it.panov.musyx.desktop
|
||||
Terminal=false
|
||||
Categories=AudioVideo;Audio;Player;
|
||||
Keywords=music;yandex;player;audio;
|
||||
Keywords[ru]=музыка;яндекс;плеер;аудио;
|
||||
StartupWMClass=it.panov.musyx.desktop
|
||||
SingleMainWindow=true
|
||||
@@ -0,0 +1,31 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<component type="desktop-application">
|
||||
<id>it.panov.musyx.desktop</id>
|
||||
<name>Musyx</name>
|
||||
<summary>Desktop player for Yandex Music</summary>
|
||||
<summary xml:lang="ru">Настольный проигрыватель для Яндекс Музыки</summary>
|
||||
<metadata_license>MIT</metadata_license>
|
||||
<project_license>MIT</project_license>
|
||||
<developer id="it.panov">
|
||||
<name>Yuriy Panov</name>
|
||||
</developer>
|
||||
<description>
|
||||
<p>
|
||||
An unofficial client for Yandex Music: My Wave, search, your collection, podcasts,
|
||||
lyrics and lossless streaming. Not affiliated with or endorsed by Yandex.
|
||||
</p>
|
||||
</description>
|
||||
<launchable type="desktop-id">it.panov.musyx.desktop.desktop</launchable>
|
||||
<categories>
|
||||
<category>AudioVideo</category>
|
||||
<category>Audio</category>
|
||||
<category>Player</category>
|
||||
</categories>
|
||||
<content_rating type="oars-1.1"/>
|
||||
<releases>
|
||||
<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.0" date="2026-10-16"/>
|
||||
</releases>
|
||||
</component>
|
||||
Executable
+143
@@ -0,0 +1,143 @@
|
||||
#!/usr/bin/env bash
|
||||
# Builds Linux release packages into target/release/bundle/.
|
||||
# tool/bundle-linux.sh # tarball, .deb and AppImage
|
||||
# tool/bundle-linux.sh tar deb # only the formats named (tar, deb, appimage)
|
||||
# tool/bundle-linux.sh --install # build, then install into ~/.local
|
||||
# The Arch package lives in packaging/arch (makepkg there).
|
||||
# The AppImage needs appimagetool on PATH, or APPIMAGETOOL pointing at it.
|
||||
# Binaries need the glibc they were built against or newer, so build releases on the
|
||||
# oldest distro you want to support (Ubuntu 22.04 covers most desktops).
|
||||
set -euo pipefail
|
||||
|
||||
root="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
cd "$root"
|
||||
|
||||
formats=()
|
||||
install=0
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
tar | deb | appimage) formats+=("$arg") ;;
|
||||
--install) install=1 ;;
|
||||
*) echo "unknown argument: $arg" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
if [[ ${#formats[@]} -eq 0 && $install -eq 0 ]]; then
|
||||
formats=(tar deb appimage)
|
||||
fi
|
||||
|
||||
app_id="it.panov.musyx.desktop"
|
||||
version="$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)"
|
||||
arch="$(uname -m)"
|
||||
case "$arch" in
|
||||
x86_64) deb_arch=amd64 ;;
|
||||
aarch64) deb_arch=arm64 ;;
|
||||
*) deb_arch="$arch" ;;
|
||||
esac
|
||||
out="target/release/bundle"
|
||||
work="$(mktemp -d)"
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
|
||||
cargo build --release -p musyx
|
||||
|
||||
# The installed layout, rooted at $1 (a prefix such as /usr): binary, desktop entry,
|
||||
# AppStream metadata, hicolor icons and licences.
|
||||
stage() {
|
||||
local dest="$1"
|
||||
install -Dm755 target/release/musyx "$dest/bin/musyx"
|
||||
install -Dm644 "packaging/linux/$app_id.desktop" "$dest/share/applications/$app_id.desktop"
|
||||
install -Dm644 "packaging/linux/$app_id.metainfo.xml" "$dest/share/metainfo/$app_id.metainfo.xml"
|
||||
for size in 16 32 48 64 128 256 512; do
|
||||
mkdir -p "$dest/share/icons/hicolor/${size}x${size}/apps"
|
||||
magick crates/musyx/assets/icon/musyx.png -resize "${size}x${size}" \
|
||||
"$dest/share/icons/hicolor/${size}x${size}/apps/$app_id.png"
|
||||
done
|
||||
local doc="$dest/share/doc/musyx"
|
||||
install -Dm644 LICENSE "$doc/LICENSE"
|
||||
install -Dm644 README.md "$doc/README.md"
|
||||
install -Dm644 crates/musyx/assets/fonts/OFL-*.txt -t "$doc"
|
||||
install -Dm644 crates/musyx/assets/icons/LICENSE.txt "$doc/LICENSE-lucide.txt"
|
||||
}
|
||||
|
||||
mkdir -p "$out"
|
||||
|
||||
if [[ $install -eq 1 ]]; then
|
||||
prefix="${PREFIX:-$HOME/.local}"
|
||||
stage "$prefix"
|
||||
update-desktop-database "$prefix/share/applications" 2>/dev/null || true
|
||||
gtk-update-icon-cache -q -t "$prefix/share/icons/hicolor" 2>/dev/null || true
|
||||
echo "Installed musyx $version into $prefix"
|
||||
fi
|
||||
|
||||
for format in "${formats[@]}"; do
|
||||
case "$format" in
|
||||
tar)
|
||||
# Unpack anywhere and run ./install.sh (to ~/.local, or PREFIX=/usr/local with sudo).
|
||||
name="musyx-$version-linux-$arch"
|
||||
dir="$work/$name"
|
||||
stage "$dir/files"
|
||||
cat > "$dir/install.sh" <<'SH'
|
||||
#!/bin/sh
|
||||
# Installs Musyx into $PREFIX (default ~/.local). Run with PREFIX=/usr/local as root for all users.
|
||||
set -eu
|
||||
prefix="${PREFIX:-$HOME/.local}"
|
||||
here="$(cd "$(dirname "$0")" && pwd)"
|
||||
mkdir -p "$prefix"
|
||||
cp -R "$here/files/." "$prefix/"
|
||||
update-desktop-database "$prefix/share/applications" 2>/dev/null || true
|
||||
gtk-update-icon-cache -q -t "$prefix/share/icons/hicolor" 2>/dev/null || true
|
||||
echo "Installed Musyx into $prefix"
|
||||
SH
|
||||
chmod 755 "$dir/install.sh"
|
||||
tar -C "$work" -czf "$out/$name.tar.gz" "$name"
|
||||
echo "Built $out/$name.tar.gz"
|
||||
;;
|
||||
|
||||
deb)
|
||||
# Assembled by hand (ar + tar), so dpkg-deb isn't needed on the build machine.
|
||||
pkg="$work/deb"
|
||||
stage "$pkg/usr"
|
||||
installed_kb="$(du -sk "$pkg/usr" | cut -f1)"
|
||||
mkdir -p "$pkg/DEBIAN"
|
||||
cat > "$pkg/DEBIAN/control" <<CONTROL
|
||||
Package: musyx
|
||||
Version: $version
|
||||
Architecture: $deb_arch
|
||||
Maintainer: Yuriy Panov <uriy.panov@gmail.com>
|
||||
Installed-Size: $installed_kb
|
||||
Depends: libc6, libgcc-s1, libasound2t64 | libasound2, libdbus-1-3, libxkbcommon0, libwayland-client0 | libx11-6
|
||||
Recommends: gnome-keyring | kwalletmanager, libvulkan1 | libgl1
|
||||
Section: sound
|
||||
Priority: optional
|
||||
Description: Desktop player for Yandex Music
|
||||
An unofficial client for Yandex Music: My Wave, search, your collection,
|
||||
podcasts, lyrics and lossless streaming. Not affiliated with Yandex.
|
||||
CONTROL
|
||||
(cd "$pkg" && find usr -type f -exec md5sum {} + > DEBIAN/md5sums)
|
||||
echo "2.0" > "$work/debian-binary"
|
||||
tar -C "$pkg/DEBIAN" --owner=0 --group=0 -cJf "$work/control.tar.xz" .
|
||||
tar -C "$pkg" --owner=0 --group=0 --exclude=./DEBIAN -cJf "$work/data.tar.xz" .
|
||||
deb="$out/musyx_${version}_${deb_arch}.deb"
|
||||
rm -f "$deb"
|
||||
(cd "$work" && ar rc "$root/$deb" debian-binary control.tar.xz data.tar.xz)
|
||||
echo "Built $deb"
|
||||
;;
|
||||
|
||||
appimage)
|
||||
tool="${APPIMAGETOOL:-$(command -v appimagetool || true)}"
|
||||
if [[ -z "$tool" ]]; then
|
||||
echo "appimagetool not found: put it on PATH or set APPIMAGETOOL" >&2
|
||||
echo " (https://github.com/AppImage/appimagetool/releases)" >&2
|
||||
exit 1
|
||||
fi
|
||||
appdir="$work/Musyx.AppDir"
|
||||
stage "$appdir/usr"
|
||||
ln -s usr/bin/musyx "$appdir/AppRun"
|
||||
cp "packaging/linux/$app_id.desktop" "$appdir/$app_id.desktop"
|
||||
cp "$appdir/usr/share/icons/hicolor/256x256/apps/$app_id.png" "$appdir/$app_id.png"
|
||||
ln -s "$app_id.png" "$appdir/.DirIcon"
|
||||
image="$out/Musyx-$version-$arch.AppImage"
|
||||
ARCH="$arch" "$tool" --no-appstream "$appdir" "$image" >/dev/null
|
||||
echo "Built $image"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
@@ -36,7 +36,7 @@ cat > "$bundle/Contents/Info.plist" <<PLIST
|
||||
<dict>
|
||||
<key>CFBundleName</key><string>Musyx</string>
|
||||
<key>CFBundleDisplayName</key><string>Musyx</string>
|
||||
<key>CFBundleIdentifier</key><string>dev.musyx.desktop</string>
|
||||
<key>CFBundleIdentifier</key><string>it.panov.musyx.desktop</string>
|
||||
<key>CFBundleDevelopmentRegion</key><string>en</string>
|
||||
<key>CFBundleLocalizations</key><array><string>en</string><string>ru</string></array>
|
||||
<key>CFBundleExecutable</key><string>Musyx</string>
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# Packs the app icon PNG into a multi-size Windows .ico (PNG-compressed entries).
|
||||
# Usage: powershell -File tool/make_ico.ps1 crates/musyx/assets/icon/musyx.png crates/musyx/assets/icon/musyx.ico
|
||||
param([string]$Src, [string]$Dst)
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
|
||||
$sizes = 16, 20, 24, 32, 40, 48, 64, 128, 256
|
||||
$source = [System.Drawing.Image]::FromFile((Resolve-Path $Src))
|
||||
$images = foreach ($s in $sizes) {
|
||||
$bmp = New-Object System.Drawing.Bitmap $s, $s, ([System.Drawing.Imaging.PixelFormat]::Format32bppArgb)
|
||||
$g = [System.Drawing.Graphics]::FromImage($bmp)
|
||||
$g.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
|
||||
$g.PixelOffsetMode = [System.Drawing.Drawing2D.PixelOffsetMode]::HighQuality
|
||||
$g.DrawImage($source, 0, 0, $s, $s)
|
||||
$g.Dispose()
|
||||
$ms = New-Object System.IO.MemoryStream
|
||||
$bmp.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)
|
||||
$bmp.Dispose()
|
||||
, $ms.ToArray()
|
||||
}
|
||||
$source.Dispose()
|
||||
|
||||
$out = New-Object System.IO.MemoryStream
|
||||
$w = New-Object System.IO.BinaryWriter $out
|
||||
$w.Write([uint16]0); $w.Write([uint16]1); $w.Write([uint16]$sizes.Count)
|
||||
$offset = 6 + 16 * $sizes.Count
|
||||
for ($i = 0; $i -lt $sizes.Count; $i++) {
|
||||
$dim = if ($sizes[$i] -ge 256) { 0 } else { $sizes[$i] } # 0 means 256
|
||||
$w.Write([byte]$dim); $w.Write([byte]$dim); $w.Write([byte]0); $w.Write([byte]0)
|
||||
$w.Write([uint16]1); $w.Write([uint16]32)
|
||||
$w.Write([uint32]$images[$i].Length); $w.Write([uint32]$offset)
|
||||
$offset += $images[$i].Length
|
||||
}
|
||||
foreach ($img in $images) { $w.Write($img) }
|
||||
$w.Flush()
|
||||
[System.IO.File]::WriteAllBytes((Join-Path (Get-Location) $Dst), $out.ToArray())
|
||||
Reference in new issue
Block a user