feat(reco): playlist Suggested Songs UI (T8-T10)

The Slint UI for the artist_vectors suggestions, 1:1 with the Svelte
PlaylistSuggestions component (backend T1-T7 already landed):
- T8: PlaylistSuggestionsState/Actions globals (distinct from the immersive
  SuggestionsState) + a controller (crates/qbz/src/playlist_suggestions.rs)
  that holds the pool/pagination/dedup and calls core.generate_playlist_suggestions
  on a spawned task; wired into main.rs; per-row cover artwork target; suggestions
  reset on playlist navigation.
- T9: the Suggested Songs section in PlaylistView.slint (docked after the
  virtualized track list), manual activation via a header wand-sparkles button,
  per-row Add/Play/info/dismiss + loading/empty states; a Close (x) button hides
  the panel (activated is in-out).
- T10: per-playlist dismissed-track store (playlist_suggestions_dismiss.rs),
  filtered out of the pool.
- i18n keys added to es/de/fr/pt.

Owner-built and verified working.

cc
This commit is contained in:
vicrodh committed 2026-06-27 01:57:30 -06:00
1 parent 49a78c2ca0
commit 2e1d8e431d
13 files changed
+1438 -1

No files matched your search

@@ -4061,3 +4061,19 @@ msgstr "Download konnte nicht gestartet werden. Bitte versuche es erneut."
msgid "No downloadable formats available" msgid "No downloadable formats available"
msgstr "Keine herunterladbaren Formate verfügbar" msgstr "Keine herunterladbaren Formate verfügbar"
# Playlist "Suggested Songs" section (T8)
msgid "Suggested songs"
msgstr "Vorgeschlagene Titel"
msgid "Suggest songs for this playlist"
msgstr "Titel für diese Playlist vorschlagen"
msgid "Finding similar artists..."
msgstr "Ähnliche Künstler werden gesucht..."
msgid "Refresh suggestions"
msgstr "Vorschläge aktualisieren"
msgid "Not interested"
msgstr "Kein Interesse"
@@ -4044,3 +4044,19 @@ msgstr "No se pudo iniciar la descarga. Inténtalo de nuevo."
msgid "No downloadable formats available" msgid "No downloadable formats available"
msgstr "No hay formatos disponibles para descargar" msgstr "No hay formatos disponibles para descargar"
# Playlist "Suggested Songs" section (T8)
msgid "Suggested songs"
msgstr "Canciones sugeridas"
msgid "Suggest songs for this playlist"
msgstr "Sugerir canciones para esta lista"
msgid "Finding similar artists..."
msgstr "Buscando artistas similares..."
msgid "Refresh suggestions"
msgstr "Actualizar sugerencias"
msgid "Not interested"
msgstr "No me interesa"
@@ -4060,3 +4060,19 @@ msgstr "Échec du démarrage du téléchargement. Veuillez réessayer."
msgid "No downloadable formats available" msgid "No downloadable formats available"
msgstr "Aucun format téléchargeable disponible" msgstr "Aucun format téléchargeable disponible"
# Playlist "Suggested Songs" section (T8)
msgid "Suggested songs"
msgstr "Titres suggérés"
msgid "Suggest songs for this playlist"
msgstr "Suggérer des titres pour cette playlist"
msgid "Finding similar artists..."
msgstr "Recherche d'artistes similaires..."
msgid "Refresh suggestions"
msgstr "Actualiser les suggestions"
msgid "Not interested"
msgstr "Pas intéressé"
@@ -4033,3 +4033,19 @@ msgstr "Falha ao iniciar o download. Tente novamente."
msgid "No downloadable formats available" msgid "No downloadable formats available"
msgstr "Nenhum formato disponível para download" msgstr "Nenhum formato disponível para download"
# Playlist "Suggested Songs" section (T8)
msgid "Suggested songs"
msgstr "Músicas sugeridas"
msgid "Suggest songs for this playlist"
msgstr "Sugerir músicas para esta playlist"
msgid "Finding similar artists..."
msgstr "Procurando artistas semelhantes..."
msgid "Refresh suggestions"
msgstr "Atualizar sugestões"
msgid "Not interested"
msgstr "Sem interesse"
+1 -1
View File
@@ -26,7 +26,7 @@ export { Theme, ThemeColors } from "foundation/semantic-colors.slint";
export { ThemeState } from "foundation/theme-state.slint"; export { ThemeState } from "foundation/theme-state.slint";
// Re-export the state globals so the Rust layer can populate them. // Re-export the state globals so the Rust layer can populate them.
export { HomeState, HomeActions, DiscoverState, DiscoverActions, SectionDescriptor, ConfigRow, DiscoverBrowseState, DiscoverBrowseActions, ForYouState, MixState, GenreFilterState, GenreFilterActions, AlbumState, ArtistState, NavState, ShellState, SessionState, SettingsState, AlbumActions, ArtistActions, ArtworkActions, NowPlayingState, QueueState, LyricsState, LyricsLineItem, SearchState, SearchActions, NetworkSidebarState, NetworkSidebarActions, MusicianState, MusicianActions, LabelState, LabelActions, AwardState, AwardActions, AwardEntry, ArtistReleasesState, ArtistReleasesActions, LocationViewState, LocationViewActions, FavoritesState, FavoritesActions, PlaylistPickerState, PlaylistPickerActions, DuplicateConfirmState, DuplicateConfirmActions, PlaylistState, PlaylistActions, SidebarState, SidebarActions, SidebarFolderPopupState, CreatePlaylistState, CreatePlaylistActions, EditPlaylistState, EditPlaylistActions, CreateFolderState, CreateFolderActions, MyQbzCreateState, MyQbzCreateActions, DragState, DragActions, PlaylistManagerState, PlaylistManagerActions, OfflineManagerState, OfflineManagerActions, BlacklistState, BlacklistActions, BlacklistedArtistItem, MyQbzState, MyQbzActions, MixtapeCardItem, MyQbzAddState, MyQbzAddActions, MyQbzAddRow, MyQbzDetailState, MyQbzDetailActions, MixtapeDetailItem, MyQbzEditState, MyQbzEditActions, MyQbzMixState, MyQbzMixActions, DiscoBuilderState, DiscoBuilderActions, DiscoGroup, DiscoCandidate, LocalLibraryState, LocalLibraryActions, LibraryFoldersState, LibFolderEditState, LibraryManageActions, LibraryScanState, LibAlbumFilterState, LocalAlbumState, LocalAlbumActions, TagEditorState, TagEditorActions, FolderEditState, FolderEditActions, ToastState, TextUtil, QconnectDevState, QconnectDevice, CastState, CastDevice, CastActions, AppearanceState, MyQbzBrandingState, EphemeralPlayChoiceState, EphemeralPlayChoiceActions, PlexSettingsState, PlexAuthActions, PlexSectionItem, ScrobbleState, ScrobbleActions, DiscordState, OfflineState, OfflineModeActions, OfflineFavoritesState, OfflineFavoritesActions, ImportLogEntry, PlaylistImportState, PlaylistImportActions, DacWizardState, DacWizardActions, DacCandidateRow, RemediationRow, DacConfigRow, InfoCreditRow, InfoCreditPair, AlbumCreditPerformer, AlbumCreditTrack, TrackInfoState, TrackInfoActions, AlbumInfoState, AlbumInfoActions, BookletState, BookletActions, SuggestionsState, SuggestionsActions, SuggestionCard, VisualizerState, ImmersiveState, ImmersiveSearchActions, ImmersiveActions, MiniPlayerState, WindowControlActions, PurchasesState, PurchasesActions, PurchaseAlbumItem, PurchaseTrackItem, PurchaseAlbumGroup, PurchaseTrackGroup, PurchaseFormatItem, PurchaseDetailState, PurchaseDetailActions, PurchaseDetailTrack, KeybindingRow, KeybindingCategoryGroup, KeybindingsState, KeybindingsActions, KeyboardShortcutsState, LinkResolverState, LinkResolverActions, UiFocusState } from "state.slint"; export { HomeState, HomeActions, DiscoverState, DiscoverActions, SectionDescriptor, ConfigRow, DiscoverBrowseState, DiscoverBrowseActions, ForYouState, MixState, GenreFilterState, GenreFilterActions, AlbumState, ArtistState, NavState, ShellState, SessionState, SettingsState, AlbumActions, ArtistActions, ArtworkActions, NowPlayingState, QueueState, LyricsState, LyricsLineItem, SearchState, SearchActions, NetworkSidebarState, NetworkSidebarActions, MusicianState, MusicianActions, LabelState, LabelActions, AwardState, AwardActions, AwardEntry, ArtistReleasesState, ArtistReleasesActions, LocationViewState, LocationViewActions, FavoritesState, FavoritesActions, PlaylistPickerState, PlaylistPickerActions, DuplicateConfirmState, DuplicateConfirmActions, PlaylistState, PlaylistActions, SidebarState, SidebarActions, SidebarFolderPopupState, CreatePlaylistState, CreatePlaylistActions, EditPlaylistState, EditPlaylistActions, CreateFolderState, CreateFolderActions, MyQbzCreateState, MyQbzCreateActions, DragState, DragActions, PlaylistManagerState, PlaylistManagerActions, OfflineManagerState, OfflineManagerActions, BlacklistState, BlacklistActions, BlacklistedArtistItem, MyQbzState, MyQbzActions, MixtapeCardItem, MyQbzAddState, MyQbzAddActions, MyQbzAddRow, MyQbzDetailState, MyQbzDetailActions, MixtapeDetailItem, MyQbzEditState, MyQbzEditActions, MyQbzMixState, MyQbzMixActions, DiscoBuilderState, DiscoBuilderActions, DiscoGroup, DiscoCandidate, LocalLibraryState, LocalLibraryActions, LibraryFoldersState, LibFolderEditState, LibraryManageActions, LibraryScanState, LibAlbumFilterState, LocalAlbumState, LocalAlbumActions, TagEditorState, TagEditorActions, FolderEditState, FolderEditActions, ToastState, TextUtil, QconnectDevState, QconnectDevice, CastState, CastDevice, CastActions, AppearanceState, MyQbzBrandingState, EphemeralPlayChoiceState, EphemeralPlayChoiceActions, PlexSettingsState, PlexAuthActions, PlexSectionItem, ScrobbleState, ScrobbleActions, DiscordState, OfflineState, OfflineModeActions, OfflineFavoritesState, OfflineFavoritesActions, ImportLogEntry, PlaylistImportState, PlaylistImportActions, DacWizardState, DacWizardActions, DacCandidateRow, RemediationRow, DacConfigRow, InfoCreditRow, InfoCreditPair, AlbumCreditPerformer, AlbumCreditTrack, TrackInfoState, TrackInfoActions, AlbumInfoState, AlbumInfoActions, BookletState, BookletActions, SuggestionsState, SuggestionsActions, SuggestionCard, PlaylistSuggestionsState, PlaylistSuggestionsActions, PlaylistSuggestionRow, VisualizerState, ImmersiveState, ImmersiveSearchActions, ImmersiveActions, MiniPlayerState, WindowControlActions, PurchasesState, PurchasesActions, PurchaseAlbumItem, PurchaseTrackItem, PurchaseAlbumGroup, PurchaseTrackGroup, PurchaseFormatItem, PurchaseDetailState, PurchaseDetailActions, PurchaseDetailTrack, KeybindingRow, KeybindingCategoryGroup, KeybindingsState, KeybindingsActions, KeyboardShortcutsState, LinkResolverState, LinkResolverActions, UiFocusState } from "state.slint";
// Which top-level screen is shown. The app starts on `splash` while it // Which top-level screen is shown. The app starts on `splash` while it
// restores a saved session, then resolves to `shell` or `login`. // restores a saved session, then resolves to `shell` or `login`.
@@ -0,0 +1,10 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72" />
<path d="m14 7 3 3" />
<path d="M5 6v4" />
<path d="M19 14v4" />
<path d="M10 2v2" />
<path d="M7 8H3" />
<path d="M21 16h-4" />
<path d="M11 3H9" />
</svg>

After

Width:  |  Height:  |  Size: 505 B

@@ -7,6 +7,7 @@ import { Theme } from "../foundation/semantic-colors.slint";
import { Typography } from "../foundation/typography.slint"; import { Typography } from "../foundation/typography.slint";
import { Radius } from "../foundation/radius.slint"; import { Radius } from "../foundation/radius.slint";
import { PlaylistState, PlaylistActions, DragState, NavState, OfflineState, BulkAction } from "../state.slint"; import { PlaylistState, PlaylistActions, DragState, NavState, OfflineState, BulkAction } from "../state.slint";
import { PlaylistSuggestionsState, PlaylistSuggestionsActions, PlaylistSuggestionRow, TooltipState } from "../state.slint";
import { QbzIcon } from "../primitives/QbzIcon.slint"; import { QbzIcon } from "../primitives/QbzIcon.slint";
import { CircleAction } from "../primitives/CircleAction.slint"; import { CircleAction } from "../primitives/CircleAction.slint";
import { TrackRow } from "../primitives/TrackRow.slint"; import { TrackRow } from "../primitives/TrackRow.slint";
@@ -59,6 +60,242 @@ component SortOption inherits Rectangle {
} }
} }
// Small ghost icon button for the "Suggested Songs" rows (info / add /
// dismiss) and the section refresh. Surface-hover fill on hover (NOT a pill —
// a 4px-rounded square; ADR-008). Mirrors the Svelte `.action-btn`.
component SuggestionActionButton inherits Rectangle {
in property <image> icon;
in property <color> icon-tint: Theme.text-muted;
in property <color> hover-bg: Theme.surface-hover;
in property <color> hover-tint: Theme.text-primary;
in property <bool> enabled: true;
in property <length> diameter: 28px;
in property <length> glyph: 15px;
in property <string> tooltip;
// Exposed so the row can OR it into its `row-hovered` (a child TouchArea
// otherwise steals the row's hover, making the reveal flicker off).
out property <bool> hovered: sab-ta.has-hover;
callback clicked();
width: root.diameter;
height: root.diameter;
border-radius: 4px;
opacity: root.enabled ? 1.0 : 0.45;
background: (sab-ta.has-hover && root.enabled) ? root.hover-bg : transparent;
animate background { duration: 150ms; }
QbzIcon {
source: root.icon;
width: root.glyph;
height: root.glyph;
x: (parent.width - self.width) / 2;
y: (parent.height - self.height) / 2;
tint: (sab-ta.has-hover && root.enabled) ? root.hover-tint : root.icon-tint;
}
sab-ta := TouchArea {
mouse-cursor: root.enabled ? pointer : default;
clicked => {
if (root.enabled) {
root.clicked();
}
}
changed has-hover => {
if (self.has-hover && root.tooltip != "") {
TooltipState.text = root.tooltip;
TooltipState.anchor-x = root.absolute-position.x + root.width / 2;
TooltipState.anchor-y = root.absolute-position.y;
TooltipState.show = true;
} else if (!self.has-hover) {
TooltipState.show = false;
}
}
}
}
// One "Suggested Songs" row — 40px cover (play on hover), title + clickable
// artist · album meta, duration, and the info / add / dismiss actions (shown
// on row hover). 1:1 with the Svelte `.suggestion-row`.
component PlaylistSuggestionRowView inherits Rectangle {
in property <PlaylistSuggestionRow> entry;
// OR the background detector with every interactive child's hover so the
// cover-play overlay + the trailing actions stay revealed (and clickable)
// when the pointer moves onto them (mirrors TrackRow.row-hovered).
property <bool> row-hovered:
psr-ta.has-hover || play-ta.has-hover
|| info-btn.hovered || add-btn.hovered || dismiss-btn.hovered;
height: 56px;
border-radius: 8px;
background: root.row-hovered ? Theme.surface-hover : transparent;
animate background { duration: 150ms; }
// Background hover detector (below the interactive children).
psr-ta := TouchArea {
mouse-cursor: default;
}
HorizontalLayout {
padding-left: 12px;
padding-right: 12px;
spacing: 12px;
// Artwork + hover play overlay.
VerticalLayout {
horizontal-stretch: 0;
alignment: center;
Rectangle {
width: 40px;
height: 40px;
border-radius: 4px;
clip: true;
background: Theme.surface-elevated;
Image {
source: root.entry.artwork;
image-fit: cover;
width: parent.width;
height: parent.height;
}
play-ov := Rectangle {
width: 100%;
height: 100%;
background: #00000080;
opacity: root.row-hovered ? 1.0 : 0.0;
animate opacity { duration: 150ms; }
QbzIcon {
source: @image-url("../assets/icons/play-fill.svg");
width: 14px;
height: 14px;
x: (parent.width - self.width) / 2;
y: (parent.height - self.height) / 2;
tint: #ffffff;
}
play-ta := TouchArea {
mouse-cursor: pointer;
clicked => {
PlaylistSuggestionsActions.play-track(root.entry.track-id);
}
}
}
}
}
// Title + meta (artist · album, clickable links).
VerticalLayout {
horizontal-stretch: 1;
alignment: center;
spacing: 2px;
Text {
text: root.entry.title;
color: Theme.text-primary;
font-size: Typography.body;
font-weight: Typography.medium;
overflow: elide;
}
HorizontalLayout {
spacing: 4px;
alignment: start;
// Artist link (content width; clickable when artist-id set).
VerticalLayout {
horizontal-stretch: 0;
alignment: center;
artist-ta := TouchArea {
width: artist-txt.preferred-width;
height: artist-txt.preferred-height;
mouse-cursor: root.entry.artist-id != "" ? pointer : default;
enabled: root.entry.artist-id != "";
clicked => {
PlaylistSuggestionsActions.go-artist(root.entry.artist-id);
}
artist-txt := Text {
text: root.entry.artist-name;
color: (artist-ta.has-hover && root.entry.artist-id != "")
? Theme.accent : Theme.text-muted;
font-size: Typography.legal;
}
}
}
if root.entry.album-title != "": Text {
text: "·";
color: Theme.text-muted;
font-size: Typography.legal;
vertical-alignment: center;
}
// Album link (stretches + elides in the remaining space).
if root.entry.album-title != "": album-ta := TouchArea {
horizontal-stretch: 1;
mouse-cursor: root.entry.album-id != "" ? pointer : default;
enabled: root.entry.album-id != "";
clicked => {
PlaylistSuggestionsActions.go-album(root.entry.album-id);
}
album-txt := Text {
width: parent.width;
text: root.entry.album-title;
color: (album-ta.has-hover && root.entry.album-id != "")
? Theme.accent : Theme.text-muted;
font-size: Typography.legal;
overflow: elide;
}
}
}
}
// Duration.
VerticalLayout {
horizontal-stretch: 0;
alignment: center;
Text {
text: root.entry.duration-label;
color: Theme.text-muted;
font-size: Typography.legal;
horizontal-alignment: right;
width: 44px;
}
}
// Actions (info / add / dismiss) — fade in on row hover. The buttons'
// own hover feeds root.row-hovered so the cluster stays up while used.
VerticalLayout {
horizontal-stretch: 0;
alignment: center;
HorizontalLayout {
spacing: 4px;
opacity: root.row-hovered ? 1.0 : 0.0;
animate opacity { duration: 150ms; }
info-btn := SuggestionActionButton {
icon: @image-url("../assets/icons/info.svg");
tooltip: @tr("Track info");
clicked => {
PlaylistSuggestionsActions.show-info(root.entry.track-id);
}
}
add-btn := SuggestionActionButton {
icon: root.entry.added
? @image-url("../assets/icons/check.svg")
: @image-url("../assets/icons/plus.svg");
icon-tint: Theme.accent;
hover-bg: Theme.accent;
hover-tint: #ffffff;
enabled: !root.entry.adding && !root.entry.added;
tooltip: @tr("Add to playlist");
clicked => {
PlaylistSuggestionsActions.add-track(root.entry.track-id);
}
}
dismiss-btn := SuggestionActionButton {
icon: @image-url("../assets/icons/x.svg");
enabled: !root.entry.adding && !root.entry.added;
tooltip: @tr("Not interested");
clicked => {
PlaylistSuggestionsActions.dismiss-track(root.entry.track-id);
}
}
}
}
}
}
export component PlaylistView inherits Rectangle { export component PlaylistView inherits Rectangle {
callback play-track(string); callback play-track(string);
callback play-all(); callback play-all();
@@ -408,6 +645,26 @@ export component PlaylistView inherits Rectangle {
} }
} }
// "Suggest songs" — generates the Suggested Songs
// section below the track list. Owner-only and hidden at
// >= 2000 tracks (the Qobuz playlist cap, can't add
// more). Manual activation mirrors the Svelte (it never
// auto-computes — large playlists shouldn't pay for it).
if PlaylistState.is-owner && !PlaylistState.is-local
&& PlaylistState.track-count > 0
&& PlaylistState.track-count < 2000: VerticalLayout {
horizontal-stretch: 0;
alignment: center;
CircleAction {
icon: @image-url("../assets/icons/wand-sparkles.svg");
active: PlaylistSuggestionsState.activated;
tooltip: @tr("Suggest songs for this playlist");
clicked => {
PlaylistSuggestionsActions.activate();
}
}
}
// Spacer floats the search + sort to the right. // Spacer floats the search + sort to the right.
Rectangle { horizontal-stretch: 1; } Rectangle { horizontal-stretch: 1; }
@@ -707,6 +964,156 @@ export component PlaylistView inherits Rectangle {
viewport-y <=> track-list.viewport-y; viewport-y <=> track-list.viewport-y;
} }
} }
// --- Suggested Songs (T8) ----------------------------------
// 1:1 port of the Svelte PlaylistSuggestions component. Docked
// below the (virtualized) track list: PlaylistView's track list is
// a ListView that owns its own scroll, so — unlike the Svelte page
// flow — this section can't scroll INTO view; it docks at the
// bottom (vertical-stretch: 0) and the list takes the rest. Shown
// only after manual activation, and self-hides once the filtered
// pool is exhausted (is-empty) — matching the Svelte guard.
if PlaylistSuggestionsState.activated && !PlaylistSuggestionsState.is-empty
&& PlaylistState.is-owner && PlaylistState.track-count < 2000: VerticalLayout {
vertical-stretch: 0;
padding-top: 16px;
padding-right: 14px;
spacing: 0px;
Rectangle {
height: 1px;
background: Theme.border-subtle;
}
Rectangle { height: 14px; }
// Header: star + "Suggested songs" + refresh (trailing edge).
HorizontalLayout {
padding-left: 12px;
spacing: 8px;
VerticalLayout {
horizontal-stretch: 0;
alignment: center;
QbzIcon {
source: @image-url("../assets/icons/wand-sparkles.svg");
width: 17px;
height: 17px;
tint: Theme.accent;
}
}
Text {
text: @tr("Suggested songs");
color: Theme.text-primary;
font-size: Typography.section;
font-weight: Typography.semibold;
vertical-alignment: center;
horizontal-stretch: 1;
}
VerticalLayout {
horizontal-stretch: 0;
alignment: center;
SuggestionActionButton {
icon: @image-url("../assets/icons/refresh-cw.svg");
diameter: 32px;
glyph: 16px;
icon-tint: Theme.text-secondary;
enabled: !PlaylistSuggestionsState.loading
&& !PlaylistSuggestionsState.loading-more;
tooltip: @tr("Refresh suggestions");
clicked => {
PlaylistSuggestionsActions.refresh();
}
}
}
// Close (×) — hide the panel (re-open via the header wand).
VerticalLayout {
horizontal-stretch: 0;
alignment: center;
SuggestionActionButton {
icon: @image-url("../assets/icons/x.svg");
diameter: 32px;
glyph: 16px;
icon-tint: Theme.text-secondary;
tooltip: @tr("Close");
clicked => {
PlaylistSuggestionsState.activated = false;
}
}
}
}
Rectangle { height: 12px; }
// Loading (first fetch, no rows yet).
if PlaylistSuggestionsState.loading
&& PlaylistSuggestionsState.rows.length == 0: VerticalLayout {
alignment: center;
spacing: 12px;
padding: 24px;
HorizontalLayout {
alignment: center;
LoadingSpinner { size: 26px; }
}
Text {
text: @tr("Finding similar artists...");
color: Theme.text-muted;
font-size: Typography.body;
horizontal-alignment: center;
}
}
// Error state with a Retry (re-activates).
if PlaylistSuggestionsState.error != "": VerticalLayout {
alignment: center;
spacing: 12px;
padding: 24px;
Text {
text: PlaylistSuggestionsState.error;
color: Theme.text-muted;
font-size: Typography.body;
horizontal-alignment: center;
wrap: word-wrap;
}
HorizontalLayout {
alignment: center;
retry-btn := Rectangle {
width: retry-label.preferred-width + 32px;
height: 34px;
border-radius: Radius.sm;
background: retry-ta.has-hover ? Theme.accent-hover : Theme.accent;
retry-label := Text {
text: @tr("Retry");
color: #ffffff;
font-size: Typography.body;
font-weight: Typography.semibold;
x: (parent.width - self.width) / 2;
y: (parent.height - self.height) / 2;
}
retry-ta := TouchArea {
mouse-cursor: pointer;
clicked => {
PlaylistSuggestionsActions.activate();
}
}
}
}
}
// The visible page of suggestion rows.
if PlaylistSuggestionsState.error == ""
&& !(PlaylistSuggestionsState.loading
&& PlaylistSuggestionsState.rows.length == 0): VerticalLayout {
spacing: 2px;
for srow in PlaylistSuggestionsState.rows: PlaylistSuggestionRowView {
entry: srow;
}
if PlaylistSuggestionsState.loading-more: HorizontalLayout {
alignment: center;
padding: 12px;
LoadingSpinner { size: 16px; }
}
}
Rectangle { height: 12px; }
}
} }
// Back to top — appears once the list is scrolled past one // Back to top — appears once the list is scrolled past one
+66
View File
@@ -678,6 +678,72 @@ export global SuggestionsActions {
callback load(string /* track-id */); callback load(string /* track-id */);
} }
// Playlist "Suggested Songs" section (T8). 1:1 port of the Svelte
// `PlaylistSuggestions` component: a fixed page of suggested tracks (6
// visible) with per-row add / play / info / dismiss + play-on-hover,
// driven by a Rust-held pool + pagination (crate::playlist_suggestions).
// DISTINCT from the immersive SuggestionsState/Actions above (different
// surface, different controller) — the name split is deliberate.
export struct PlaylistSuggestionRow {
// Qobuz ids carried as STRINGS (parsed to u64 in Rust) — matches the
// shared TrackItem id convention; Qobuz catalog ids can exceed Slint's
// 32-bit `int`, and album ids are alphanumeric.
track-id: string,
title: string,
artist-name: string,
artist-id: string,
album-title: string,
album-id: string,
// Remote cover URL (artwork-job input) + the decoded thumbnail.
artwork-url: string,
artwork: image,
duration-label: string,
// Dev-mode "why suggested" string (empty in production — include_reasons=false).
reason: string,
// True while this row's add call is in flight; flips to `added` (a brief
// check state) on success, just before the row leaves the pool.
adding: bool,
added: bool,
}
// Playlist suggestions section state. Populated by
// crate::playlist_suggestions::*; the row list reuses PlaylistSuggestionRow.
export global PlaylistSuggestionsState {
// The user has launched suggestions for the open playlist (manual
// activation gate — mirrors the Svelte `suggestionsActivated`). Until
// then the section shows only the "Suggest Songs" CTA.
in-out property <bool> activated: false;
in property <bool> loading: false;
// A background pool expansion (load-more / auto-variety) is in flight.
in property <bool> loading-more: false;
// More pages are available beyond the visible 6 (drives the refresh hint).
in property <bool> has-more: false;
// The filtered pool is exhausted (nothing left to suggest) — the loaded
// section hides itself, matching the Svelte `isEmpty` branch.
in property <bool> is-empty: false;
in property <string> error: "";
in property <[PlaylistSuggestionRow]> rows: [];
}
export global PlaylistSuggestionsActions {
// Launch suggestions for the open playlist: gather seed artists +
// exclude ids off the loaded Qobuz tracks, then fetch the first pool page.
callback activate();
// Advance the visible page (wraps + expands the pool on cycle — Svelte parity).
callback refresh();
// Add a suggested track to the open playlist, then drop it from the pool.
callback add-track(string /* track-id */);
// Preview / play a single suggested track now.
callback play-track(string /* track-id */);
// Dismiss a suggestion (sticky per-playlist) + drop it from the pool.
callback dismiss-track(string /* track-id */);
// Open the Track Info modal for a suggestion.
callback show-info(string /* track-id */);
// Navigate to a suggestion's album / artist.
callback go-album(string /* album-id */);
callback go-artist(string /* artist-id */);
}
// Album Info modal — opened from the AlbumPageView header (i) button via // Album Info modal — opened from the AlbumPageView header (i) button via
// media-action("album", id, "info"). // media-action("album", id, "info").
export global AlbumInfoState { export global AlbumInfoState {
+13
View File
@@ -202,6 +202,9 @@ pub enum ArtworkTarget {
/// A row thumbnail in the immersive Suggestions recommended-tracks list /// A row thumbnail in the immersive Suggestions recommended-tracks list
/// (`SuggestionsState.tracks[idx]`). /// (`SuggestionsState.tracks[idx]`).
SuggestionTrackCover { idx: usize }, SuggestionTrackCover { idx: usize },
/// A row thumbnail in the playlist "Suggested Songs" section
/// (`PlaylistSuggestionsState.rows[idx]`). 40px row art — decode small.
PlaylistSuggestionCover { idx: usize },
/// A cover of `PurchasesState.albums-full[index]` (the stable artwork-target /// A cover of `PurchasesState.albums-full[index]` (the stable artwork-target
/// full set). The apply arm writes here, then dual-sets by id into the /// full set). The apply arm writes here, then dual-sets by id into the
/// rendered flat + grouped models (which a filter/sort/group re-derives). /// rendered flat + grouped models (which a filter/sort/group re-derives).
@@ -226,6 +229,7 @@ impl ArtworkTarget {
| ArtworkTarget::MixTrack { .. } | ArtworkTarget::MixTrack { .. }
| ArtworkTarget::PlaylistTrack { .. } | ArtworkTarget::PlaylistTrack { .. }
| ArtworkTarget::SuggestionTrackCover { .. } | ArtworkTarget::SuggestionTrackCover { .. }
| ArtworkTarget::PlaylistSuggestionCover { .. }
| ArtworkTarget::LocalArtistRowImage { .. } => 96, | ArtworkTarget::LocalArtistRowImage { .. } => 96,
// Sidebar micro-collage tiles render at ~10-20px; decode tiny. // Sidebar micro-collage tiles render at ~10-20px; decode tiny.
ArtworkTarget::SidebarPlaylistCover { .. } => 48, ArtworkTarget::SidebarPlaylistCover { .. } => 48,
@@ -1380,5 +1384,14 @@ fn apply_artwork(
model.set_row_data(idx, item); model.set_row_data(idx, item);
} }
} }
ArtworkTarget::PlaylistSuggestionCover { idx } => {
let model = window
.global::<crate::PlaylistSuggestionsState>()
.get_rows();
if let Some(mut item) = model.row_data(idx) {
item.artwork = image;
model.set_row_data(idx, item);
}
}
} }
} }
+119
View File
@@ -95,6 +95,8 @@ mod playlist;
mod playlist_import; mod playlist_import;
mod playlist_manager; mod playlist_manager;
mod playlist_snapshot; mod playlist_snapshot;
mod playlist_suggestions;
mod playlist_suggestions_dismiss;
mod purchases; mod purchases;
mod plex_auth; mod plex_auth;
mod plex_settings; mod plex_settings;
@@ -11925,6 +11927,123 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
}); });
} }
// --- Playlist "Suggested Songs" section (T8) ----------------------------
// 1:1 port of the Svelte PlaylistSuggestions component. The pool +
// pagination + dedupe live in crate::playlist_suggestions; the nav actions
// route through the shared media-action arms the playlist track rows use.
{
let runtime = app_runtime.clone();
let weak = window.as_weak();
let handle = tokio_rt.handle().clone();
window
.global::<PlaylistSuggestionsActions>()
.on_activate(move || {
if let Some(w) = weak.upgrade() {
playlist_suggestions::activate(&w, runtime.clone(), handle.clone());
}
});
}
{
let runtime = app_runtime.clone();
let weak = window.as_weak();
let handle = tokio_rt.handle().clone();
window
.global::<PlaylistSuggestionsActions>()
.on_refresh(move || {
if let Some(w) = weak.upgrade() {
playlist_suggestions::refresh(&w, runtime.clone(), handle.clone());
}
});
}
{
let runtime = app_runtime.clone();
let weak = window.as_weak();
let handle = tokio_rt.handle().clone();
window
.global::<PlaylistSuggestionsActions>()
.on_add_track(move |track_id| {
if let Some(w) = weak.upgrade() {
playlist_suggestions::add_track(
&w,
runtime.clone(),
handle.clone(),
track_id.to_string(),
);
}
});
}
{
let runtime = app_runtime.clone();
let weak = window.as_weak();
let handle = tokio_rt.handle().clone();
window
.global::<PlaylistSuggestionsActions>()
.on_play_track(move |track_id| {
playlist_suggestions::play_track(
runtime.clone(),
weak.clone(),
handle.clone(),
track_id.to_string(),
);
});
}
{
let runtime = app_runtime.clone();
let weak = window.as_weak();
let handle = tokio_rt.handle().clone();
window
.global::<PlaylistSuggestionsActions>()
.on_dismiss_track(move |track_id| {
if let Some(w) = weak.upgrade() {
playlist_suggestions::dismiss_track(
&w,
runtime.clone(),
handle.clone(),
track_id.to_string(),
);
}
});
}
{
// show-info / go-album / go-artist reuse the shared media-action arms:
// ("track","track-info") opens the Track Info modal; ("album"/"artist",
// "open") navigate — the same routing the playlist track rows use.
let weak = window.as_weak();
window
.global::<PlaylistSuggestionsActions>()
.on_show_info(move |track_id| {
if let Some(w) = weak.upgrade() {
if !track_id.is_empty() {
w.invoke_media_action("track".into(), track_id, "track-info".into());
}
}
});
}
{
let weak = window.as_weak();
window
.global::<PlaylistSuggestionsActions>()
.on_go_album(move |album_id| {
if let Some(w) = weak.upgrade() {
if !album_id.is_empty() {
w.invoke_media_action("album".into(), album_id, "open".into());
}
}
});
}
{
let weak = window.as_weak();
window
.global::<PlaylistSuggestionsActions>()
.on_go_artist(move |artist_id| {
if let Some(w) = weak.upgrade() {
if !artist_id.is_empty() {
w.invoke_media_action("artist".into(), artist_id, "open".into());
}
}
});
}
// Artist Blacklist Manager actions (Task 11). Mutations are synchronous // Artist Blacklist Manager actions (Task 11). Mutations are synchronous
// (in-memory set + single SQLite ops via the artist_blacklist wrapper), so // (in-memory set + single SQLite ops via the artist_blacklist wrapper), so
// no tokio handle is needed; each callback runs on the event-loop thread. // no tokio handle is needed; each callback runs on the event-loop thread.
+3
View File
@@ -582,6 +582,9 @@ pub fn reset(window: &AppWindow) {
// Drop the previous detail's queue snapshot — the local/offline/mixed // Drop the previous detail's queue snapshot — the local/offline/mixed
// applies repopulate it after this shared reset. // applies repopulate it after this shared reset.
crate::local_playlist::clear_open_snapshot(); crate::local_playlist::clear_open_snapshot();
// Reset the "Suggested Songs" section so a new playlist shows its own
// "Suggest songs" CTA instead of the previous playlist's rows (T8).
crate::playlist_suggestions::reset(window);
let state = window.global::<PlaylistState>(); let state = window.global::<PlaylistState>();
state.set_tracks(ModelRc::new(VecModel::from(Vec::<TrackItem>::new()))); state.set_tracks(ModelRc::new(VecModel::from(Vec::<TrackItem>::new())));
state.set_track_count(0); state.set_track_count(0);
+669
View File
@@ -0,0 +1,669 @@
//! Playlist "Suggested Songs" section controller (T8).
//!
//! 1:1 port of the Svelte `PlaylistSuggestions.svelte` + the slice of
//! `PlaylistDetailView.svelte` that derives the seed artists / excludes and
//! mounts the component. All assembly logic lives in Rust (ADR-006): a
//! Rust-held pool + pagination feeds `PlaylistSuggestionsState`; the `.slint`
//! section only renders the projected rows + flags and fires the `Actions`.
//!
//! DISTINCT from the immersive `crate::suggestions` controller (different
//! surface, different engine). The backend engine is `qbz_reco` via
//! `core.generate_playlist_suggestions(...)`; the per-playlist dismiss store is
//! `crate::playlist_suggestions_dismiss` (T10).
//!
//! Pool sizing + pagination mirror the Svelte constants:
//! VISIBLE_COUNT=6, INITIAL_POOL=30, EXPANDED_POOL=100, MAX_POOL=200,
//! auto-expand when the filtered (available) pool falls below 12.
//! Filtering removes: dismissed ids (T10 store), excluded ids (already in the
//! playlist), suggestions that duplicate an existing track by `title|artist`,
//! and duplicates within the pool itself by the same key.
use std::collections::HashSet;
use std::sync::{LazyLock, Mutex};
use qbz_app::shell::AppRuntime;
use qbz_models::Track;
use slint::{ComponentHandle, Model, ModelRc, VecModel};
use crate::adapter::SlintAdapter;
use crate::artwork::{ArtworkJob, ArtworkTarget};
use crate::{AppWindow, PlaylistSuggestionRow, PlaylistSuggestionsState, PlaylistState};
type Runtime = std::sync::Arc<AppRuntime<SlintAdapter>>;
type Handle = tokio::runtime::Handle;
type Weak = slint::Weak<AppWindow>;
// --- Svelte parity constants -----------------------------------------------
const VISIBLE_COUNT: usize = 6;
const INITIAL_POOL: usize = 30;
const EXPANDED_POOL: usize = 100;
const MAX_POOL: usize = 200;
/// Auto-expand the pool once the available (filtered) tracks drop below this.
const MIN_AVAILABLE_THRESHOLD: usize = 12;
/// Which fetch we are running — drives the merge-vs-replace + error handling.
#[derive(Clone, Copy, PartialEq)]
enum Phase {
/// First load for the open playlist: replaces the pool, surfaces errors.
Initial,
/// Background pool growth (cycle-wrap load-more / variety): merges, silent.
Merge,
}
/// The live suggestions session for the open playlist. Held in Rust (the UI
/// only ever sees the projected rows + flags on `PlaylistSuggestionsState`).
#[derive(Default)]
struct Session {
/// Open playlist id (Qobuz catalog id). 0 = no active session.
playlist_id: u64,
/// Seed artists sent to the engine — stable across load-more within a
/// session (Svelte: the `artists` prop only recomputes on track change).
artists: Vec<(Option<u64>, String)>,
/// Track ids already in the playlist (excluded from suggestions). Grows as
/// the user adds suggested tracks.
exclude_ids: HashSet<u64>,
/// `title|artist` keys of existing playlist tracks (de-dupe vs the playlist).
existing_keys: HashSet<String>,
/// The full fetched pool (de-duped on merge by id).
pool: Vec<qbz_reco::SuggestedTrack>,
/// Current visible page (0-based; window of VISIBLE_COUNT).
page: usize,
/// How many full cycles through the pages the user has completed.
completed_cycles: usize,
/// True once the first fetch has returned.
loaded_once: bool,
/// A foreground (initial) fetch is in flight.
loading: bool,
/// A background pool expansion (load-more / variety) is in flight.
loading_more: bool,
/// True once a MAX_POOL request has been issued — prevents auto-expand from
/// looping when the engine returns fewer than MAX_POOL tracks.
max_requested: bool,
}
static SESSION: LazyLock<Mutex<Session>> = LazyLock::new(|| Mutex::new(Session::default()));
// --- string helpers (mirror the Svelte normalizeForComparison/makeTrackKey) -
fn normalize(s: &str) -> String {
s.to_lowercase().split_whitespace().collect::<Vec<_>>().join(" ")
}
fn make_key(title: &str, artist: &str) -> String {
format!("{}|{}", normalize(title), normalize(artist))
}
fn mmss(secs: u32) -> String {
format!("{}:{:02}", secs / 60, secs % 60)
}
/// Deterministic splitmix64 step (qbz-radio's RNG family) — used for the
/// adaptive-artist shuffle so the seed selection is varied but reproducible per
/// playlist (no `rand` pulled into this hot path).
fn splitmix64(state: &mut u64) -> u64 {
*state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = *state;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
fn shuffle<T>(items: &mut [T], seed: u64) {
let mut state = seed ^ 0xD1B5_4A32_D192_ED03;
for i in (1..items.len()).rev() {
let j = (splitmix64(&mut state) % (i as u64 + 1)) as usize;
items.swap(i, j);
}
}
/// Adaptive seed-artist selection — 1:1 with the Svelte `extractAdaptiveArtists`
/// (quantity scales with playlist size; a 60/40 top-frequency/random mix for
/// coherence + discovery; the final selection shuffled). Keeps the engine's
/// per-artist MusicBrainz resolution bounded on large playlists.
fn extract_adaptive_artists(tracks: &[Track], playlist_id: u64) -> Vec<(Option<u64>, String)> {
// Count tracks per artist name (first-seen qobuz id retained).
let mut order: Vec<String> = Vec::new();
let mut counts: std::collections::HashMap<String, (usize, Option<u64>)> =
std::collections::HashMap::new();
for track in tracks {
let Some(performer) = track.performer.as_ref() else {
continue;
};
let name = performer.name.trim();
if name.is_empty() {
continue;
}
let entry = counts.entry(name.to_string()).or_insert_with(|| {
order.push(name.to_string());
(0, Some(performer.id))
});
entry.0 += 1;
}
let unique = order.len();
if unique == 0 {
return Vec::new();
}
let n = tracks.len();
let limit = if n < 15 {
5.min(n).max(3)
} else if n < 50 {
10.min(((n as f64) * 0.3).ceil() as usize)
} else if n < 100 {
15.min(((n as f64) * 0.2).ceil() as usize)
} else {
20.min(((n as f64) * 0.15).ceil() as usize)
};
let actual = limit.min(unique);
// Sorted (count desc, then first-seen order for stability).
let mut sorted: Vec<(String, Option<u64>)> = order
.iter()
.map(|name| {
let (_, qid) = counts[name];
(name.clone(), qid)
})
.collect();
let count_of = |name: &str| counts.get(name).map(|c| c.0).unwrap_or(0);
sorted.sort_by(|a, b| count_of(b.0.as_str()).cmp(&count_of(a.0.as_str())));
let to_pair = |(name, qid): (String, Option<u64>)| (qid, name);
// Few artists: return all, shuffled.
if unique <= actual {
let mut all: Vec<(String, Option<u64>)> = sorted;
shuffle(&mut all, playlist_id);
return all.into_iter().map(to_pair).collect();
}
let top_count = 1.max(((actual as f64) * 0.6).floor() as usize);
let random_count = actual - top_count;
let top: Vec<(String, Option<u64>)> = sorted[..top_count].to_vec();
let mut rest: Vec<(String, Option<u64>)> = sorted[top_count..].to_vec();
shuffle(&mut rest, playlist_id ^ 0x5EED);
let random: Vec<(String, Option<u64>)> = rest.into_iter().take(random_count).collect();
let mut combined: Vec<(String, Option<u64>)> = top.into_iter().chain(random).collect();
shuffle(&mut combined, playlist_id ^ 0xA5A5);
combined.into_iter().map(to_pair).collect()
}
/// Compute the indices into `session.pool` that survive filtering, in pool
/// order: not dismissed, not excluded, not a duplicate of an existing playlist
/// track, and de-duplicated within the pool by `title|artist`.
fn filtered_indices(session: &Session) -> Vec<usize> {
let dismissed = crate::playlist_suggestions_dismiss::dismissed_for_playlist(session.playlist_id);
let mut seen_keys: HashSet<String> = HashSet::new();
let mut out = Vec::new();
for (idx, item) in session.pool.iter().enumerate() {
if dismissed.contains(&item.track_id) || session.exclude_ids.contains(&item.track_id) {
continue;
}
let key = make_key(&item.title, &item.artist_name);
if session.existing_keys.contains(&key) {
continue;
}
if !seen_keys.insert(key) {
continue;
}
out.push(idx);
}
out
}
fn to_row(track: &qbz_reco::SuggestedTrack) -> PlaylistSuggestionRow {
PlaylistSuggestionRow {
track_id: track.track_id.to_string().into(),
title: track.title.clone().into(),
artist_name: track.artist_name.clone().into(),
artist_id: track
.artist_id
.map(|id| id.to_string())
.unwrap_or_default()
.into(),
album_title: track.album_title.clone().into(),
album_id: track.album_id.clone().into(),
artwork_url: track.album_image_url.clone().unwrap_or_default().into(),
artwork: slint::Image::default(),
duration_label: mmss(track.duration).into(),
reason: track.reason.clone().unwrap_or_default().into(),
adding: false,
added: false,
}
}
/// Project the current session onto `PlaylistSuggestionsState` (visible page +
/// flags) and fire the row-cover artwork jobs. UI thread.
fn project(window: &AppWindow) {
let (rows, has_more, is_empty, loading, loading_more, jobs): (
Vec<PlaylistSuggestionRow>,
bool,
bool,
bool,
bool,
Vec<ArtworkJob>,
) = {
let mut session = SESSION.lock().unwrap();
let filtered = filtered_indices(&session);
let total_pages = filtered.len().div_ceil(VISIBLE_COUNT);
// Clamp + persist the page so a dismiss/add that shrinks the pool below
// the current window snaps back to the last real page (no empty view).
session.page = session.page.min(total_pages.saturating_sub(1));
let page = session.page;
let start = page * VISIBLE_COUNT;
let visible: Vec<&qbz_reco::SuggestedTrack> = filtered
.iter()
.skip(start)
.take(VISIBLE_COUNT)
.map(|&i| &session.pool[i])
.collect();
let mut jobs = Vec::new();
let rows: Vec<PlaylistSuggestionRow> = visible
.iter()
.enumerate()
.map(|(idx, track)| {
if !track.album_image_url.as_deref().unwrap_or("").is_empty() {
jobs.push(ArtworkJob {
url: track.album_image_url.clone().unwrap_or_default(),
target: ArtworkTarget::PlaylistSuggestionCover { idx },
});
}
to_row(track)
})
.collect();
let has_more = page + 1 < total_pages;
let is_empty = filtered.is_empty() && !session.loading && session.loaded_once;
(
rows,
has_more,
is_empty,
session.loading,
session.loading_more,
jobs,
)
};
let state = window.global::<PlaylistSuggestionsState>();
state.set_rows(ModelRc::new(VecModel::from(rows)));
state.set_has_more(has_more);
state.set_is_empty(is_empty);
state.set_loading(loading);
state.set_loading_more(loading_more);
if !jobs.is_empty() {
if let Some(cache) = crate::artwork::shared_cache() {
crate::artwork::spawn_loads(jobs, window.as_weak(), cache);
}
}
}
/// Fetch a pool page and (Initial) replace or (Merge) merge it, then re-project.
fn spawn_fetch(runtime: Runtime, weak: Weak, handle: Handle, pool_size: usize, phase: Phase) {
// Capture which playlist this fetch is for; a navigation / re-activate that
// swaps the session before it returns must discard the stale result.
let (pid, artists, exclude): (u64, Vec<(Option<u64>, String)>, Vec<u64>) = {
let mut session = SESSION.lock().unwrap();
match phase {
Phase::Initial => session.loading = true,
Phase::Merge => {
session.loading_more = true;
if pool_size >= MAX_POOL {
session.max_requested = true;
}
}
}
(
session.playlist_id,
session.artists.clone(),
session.exclude_ids.iter().copied().collect(),
)
};
let runtime2 = runtime.clone();
let weak2 = weak.clone();
let handle2 = handle.clone();
handle.spawn(async move {
let config = qbz_reco::SuggestionConfig {
max_pool_size: pool_size,
..Default::default()
};
let result = runtime2
.core()
.generate_playlist_suggestions(artists, exclude, false, Some(config))
.await;
match result {
Ok(result) => {
let applied = {
let mut session = SESSION.lock().unwrap();
if session.playlist_id != pid {
false // superseded by a navigation / re-activate
} else {
match phase {
Phase::Initial => {
session.pool = result.tracks;
session.page = 0;
session.completed_cycles = 0;
session.loading = false;
}
Phase::Merge => {
let existing: HashSet<u64> =
session.pool.iter().map(|t| t.track_id).collect();
for track in result.tracks {
if !existing.contains(&track.track_id) {
session.pool.push(track);
}
}
session.loading_more = false;
}
}
session.loaded_once = true;
true
}
};
if applied {
let _ = weak2.upgrade_in_event_loop(|w| project(&w));
maybe_auto_expand(runtime2, weak2, handle2);
}
}
Err(e) => {
let surface = {
let mut session = SESSION.lock().unwrap();
if session.playlist_id != pid {
None // stale — leave the current session untouched
} else {
match phase {
Phase::Initial => {
session.loading = false;
session.pool.clear();
session.loaded_once = true;
Some(true)
}
Phase::Merge => {
session.loading_more = false;
Some(false)
}
}
}
};
let Some(surface) = surface else {
return;
};
log::warn!("[qbz-slint] playlist suggestions fetch failed: {e}");
let _ = weak2.upgrade_in_event_loop(move |w| {
let state = w.global::<PlaylistSuggestionsState>();
state.set_loading(false);
state.set_loading_more(false);
if surface {
state.set_error(e.into());
project(&w);
}
});
}
}
});
}
/// Grow the pool to MAX_POOL when the filtered (available) tracks fall below
/// the threshold (Svelte's pool-exhaustion auto-refresh). One-shot per session
/// (guarded by `max_requested`) so a thin engine result never loops.
fn maybe_auto_expand(runtime: Runtime, weak: Weak, handle: Handle) {
let should = {
let session = SESSION.lock().unwrap();
let available = filtered_indices(&session).len();
available > 0
&& available < MIN_AVAILABLE_THRESHOLD
&& session.loaded_once
&& !session.loading
&& !session.loading_more
&& !session.max_requested
&& session.pool.len() < MAX_POOL
};
if should {
let _ = weak.upgrade_in_event_loop(|w| {
w.global::<PlaylistSuggestionsState>().set_loading_more(true);
});
spawn_fetch(runtime, weak, handle, MAX_POOL, Phase::Merge);
}
}
/// Launch suggestions for the open playlist: gather the seed artists + excludes
/// off the loaded Qobuz tracks, then fetch the first pool page. UI thread.
pub fn activate(window: &AppWindow, runtime: Runtime, handle: Handle) {
let playlist_id = window
.global::<PlaylistState>()
.get_id()
.parse::<u64>()
.unwrap_or(0);
let tracks = crate::playlist::current_tracks();
let artists = extract_adaptive_artists(&tracks, playlist_id);
let exclude_ids: HashSet<u64> = tracks.iter().map(|t| t.id).collect();
let existing_keys: HashSet<String> = tracks
.iter()
.map(|t| {
let artist = t.performer.as_ref().map(|p| p.name.as_str()).unwrap_or("");
make_key(&t.title, artist)
})
.collect();
{
let mut session = SESSION.lock().unwrap();
*session = Session {
playlist_id,
artists: artists.clone(),
exclude_ids,
existing_keys,
..Default::default()
};
}
let state = window.global::<PlaylistSuggestionsState>();
state.set_activated(true);
state.set_error("".into());
state.set_is_empty(false);
state.set_rows(ModelRc::new(VecModel::from(Vec::<PlaylistSuggestionRow>::new())));
// No resolvable seed artists (e.g. a fully-local playlist) -> empty, hidden.
if playlist_id == 0 || artists.is_empty() {
let mut session = SESSION.lock().unwrap();
session.loaded_once = true;
drop(session);
state.set_loading(false);
state.set_is_empty(true);
return;
}
state.set_loading(true);
spawn_fetch(runtime, window.as_weak(), handle, INITIAL_POOL, Phase::Initial);
}
/// Advance the visible page; on a full cycle, wrap to page 0 and (first cycle)
/// kick the EXPANDED_POOL load-more. UI thread.
pub fn refresh(window: &AppWindow, runtime: Runtime, handle: Handle) {
let expand = {
let mut session = SESSION.lock().unwrap();
if session.loading {
return;
}
let total_pages = filtered_indices(&session).len().div_ceil(VISIBLE_COUNT);
if session.page + 1 < total_pages {
session.page += 1;
false
} else if total_pages > 0 {
session.page = 0;
session.completed_cycles += 1;
session.completed_cycles == 1
&& !session.loading_more
&& session.pool.len() < EXPANDED_POOL
} else {
false
}
};
project(window);
if expand {
window.global::<PlaylistSuggestionsState>().set_loading_more(true);
spawn_fetch(
runtime.clone(),
window.as_weak(),
handle.clone(),
EXPANDED_POOL,
Phase::Merge,
);
} else {
maybe_auto_expand(runtime, window.as_weak(), handle);
}
}
/// Add a suggested track to the open playlist, drop it from the pool, and
/// reload the detail so the new track appears in the list. UI thread.
pub fn add_track(window: &AppWindow, runtime: Runtime, handle: Handle, track_id: String) {
let Ok(tid) = track_id.parse::<u64>() else {
return;
};
let playlist_id = {
let session = SESSION.lock().unwrap();
session.playlist_id
};
if playlist_id == 0 {
return;
}
// Optimistic "adding" flag on the visible row.
set_row_flag(window, &track_id, true, false);
let weak = window.as_weak();
let runtime2 = runtime.clone();
let handle2 = handle.clone();
handle.spawn(async move {
match runtime2
.core()
.add_tracks_to_playlist(playlist_id, &[tid])
.await
{
Ok(()) => {
{
let mut session = SESSION.lock().unwrap();
session.exclude_ids.insert(tid);
if let Some(track) = session.pool.iter().find(|t| t.track_id == tid) {
let key = make_key(&track.title, &track.artist_name);
session.existing_keys.insert(key);
}
session.pool.retain(|t| t.track_id != tid);
}
let runtime3 = runtime2.clone();
let weak3 = weak.clone();
let handle3 = handle2.clone();
let _ = weak.upgrade_in_event_loop(move |w| {
project(&w);
reload_open_playlist(&w, runtime3, handle3, playlist_id);
maybe_auto_expand(runtime2, weak3, handle2);
});
}
Err(e) => {
log::warn!("[qbz-slint] add suggested track {tid} failed: {e}");
let _ = weak.upgrade_in_event_loop(move |w| {
set_row_flag(&w, &track_id, false, false);
});
}
}
});
}
/// Preview / play a single suggested track now. UI thread.
pub fn play_track(runtime: Runtime, weak: Weak, handle: Handle, track_id: String) {
let Ok(tid) = track_id.parse::<u64>() else {
return;
};
let handle2 = handle.clone();
handle.spawn(async move {
match runtime.core().get_track(tid).await {
Ok(track) => {
crate::playback::play_tracks(runtime, weak, handle2, vec![track], 0);
}
Err(e) => log::warn!("[qbz-slint] preview suggested track {tid} failed: {e}"),
}
});
}
/// Dismiss a suggestion (sticky per-playlist via the T10 store) and drop it from
/// the pool. UI thread.
pub fn dismiss_track(window: &AppWindow, runtime: Runtime, handle: Handle, track_id: String) {
let Ok(tid) = track_id.parse::<u64>() else {
return;
};
{
let mut session = SESSION.lock().unwrap();
if session.playlist_id == 0 {
return;
}
crate::playlist_suggestions_dismiss::dismiss(session.playlist_id, tid);
session.pool.retain(|t| t.track_id != tid);
}
project(window);
maybe_auto_expand(runtime, window.as_weak(), handle);
}
/// Flip the `adding` flag on the visible row that matches `track_id` (so the
/// per-row add button can show its in-flight state).
fn set_row_flag(window: &AppWindow, track_id: &str, adding: bool, added: bool) {
let model = window.global::<PlaylistSuggestionsState>().get_rows();
for i in 0..model.row_count() {
if let Some(mut row) = model.row_data(i) {
if row.track_id.as_str() == track_id {
row.adding = adding;
row.added = added;
model.set_row_data(i, row);
break;
}
}
}
}
/// Quietly reload the open Qobuz playlist detail after a mutation (no nav
/// record / view change — we are already on the playlist view). Refreshes the
/// track list + counts so an added suggestion shows immediately.
fn reload_open_playlist(window: &AppWindow, runtime: Runtime, handle: Handle, playlist_id: u64) {
let weak = window.as_weak();
handle.spawn(async move {
if let Some(data) = crate::playlist::load(&runtime, playlist_id).await {
let (http_jobs, local_jobs, plex_jobs) = crate::playlist::artwork_jobs(&data);
let _ = weak.upgrade_in_event_loop(move |w| {
crate::playlist::apply(&w, data);
});
if let Some(cache) = crate::artwork::shared_cache() {
if !http_jobs.is_empty() {
crate::artwork::spawn_loads(http_jobs, weak.clone(), cache.clone());
}
if !local_jobs.is_empty() {
crate::artwork::spawn_local_loads(local_jobs, weak.clone(), cache.clone());
}
if !plex_jobs.is_empty() {
let plex = crate::plex_settings::get();
crate::artwork::spawn_local_or_plex_loads(
plex_jobs,
plex.base_url,
plex.token,
weak.clone(),
cache,
);
}
}
}
});
}
/// Reset the section to its pre-activation state. Called from
/// `crate::playlist::reset` on every playlist navigation so a new playlist
/// shows its own "Suggest songs" CTA instead of stale rows. UI thread.
pub fn reset(window: &AppWindow) {
*SESSION.lock().unwrap() = Session::default();
let state = window.global::<PlaylistSuggestionsState>();
state.set_activated(false);
state.set_loading(false);
state.set_loading_more(false);
state.set_has_more(false);
state.set_is_empty(false);
state.set_error("".into());
state.set_rows(ModelRc::new(VecModel::from(Vec::<PlaylistSuggestionRow>::new())));
}
@@ -0,0 +1,86 @@
//! Per-playlist "Suggested Songs" dismiss store (T10).
//!
//! The playlist suggestions section lets the user dismiss ("not interested")
//! a suggested track. The rejection is sticky for that playlist, so the same
//! track never re-appears in future suggestion runs for it. A single JSON
//! file at the shared QBZ data path holds the dismissals — small enough for a
//! full read on each suggestions call, no SQLite needed at this layer.
//!
//! This is the Slint-side replacement for the Svelte service's
//! `getDismissedTrackIds` / `dismissTrack` localStorage pair
//! (`playlist_suggestions_dismissed_<playlistId>`). Modeled on
//! `discovery_dismiss.rs`; the only shape change is the value type
//! (track-id `u64` lists, keyed by playlist id string).
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
/// Map of playlist id (as string) -> dismissed Qobuz track ids.
#[derive(Default, Serialize, Deserialize)]
struct DismissStore {
#[serde(flatten)]
by_playlist: HashMap<String, Vec<u64>>,
}
fn store_path() -> Option<PathBuf> {
Some(
dirs::data_dir()?
.join("qbz")
.join("playlist_suggestions_dismiss.json"),
)
}
fn load_store() -> DismissStore {
let Some(path) = store_path() else {
return DismissStore::default();
};
match std::fs::read(&path) {
Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_default(),
Err(_) => DismissStore::default(),
}
}
fn write_store(store: &DismissStore) {
let Some(path) = store_path() else {
return;
};
if let Some(parent) = path.parent() {
if let Err(e) = std::fs::create_dir_all(parent) {
log::warn!("[qbz-slint] playlist-suggestions-dismiss dir failed: {e}");
return;
}
}
match serde_json::to_vec_pretty(store) {
Ok(json) => {
if let Err(e) = std::fs::write(&path, json) {
log::warn!("[qbz-slint] playlist-suggestions-dismiss write failed: {e}");
}
}
Err(e) => log::warn!("[qbz-slint] playlist-suggestions-dismiss serialize failed: {e}"),
}
}
/// Return the set of dismissed track ids for `playlist_id`. Used as a filter
/// input by the suggestions controller's pool filter.
pub fn dismissed_for_playlist(playlist_id: u64) -> HashSet<u64> {
let store = load_store();
store
.by_playlist
.get(&playlist_id.to_string())
.cloned()
.unwrap_or_default()
.into_iter()
.collect()
}
/// Record a dismissal of `track_id` for `playlist_id` (idempotent).
pub fn dismiss(playlist_id: u64, track_id: u64) {
let mut store = load_store();
let entry = store.by_playlist.entry(playlist_id.to_string()).or_default();
if !entry.contains(&track_id) {
entry.push(track_id);
}
write_store(&store);
}