feat(slint): port Discord Rich Presence (opt-in) from Tauri

Frontend-agnostic core in qbz-integrations::discord (DiscordRpc +
NowListening) — the Tauri backend minus the tauri::command/State
wrappers: lazy IPC connect, Listening activity (details/state/assets +
"Get QBZ" button + timestamps), and the opt-in Flatpak socket bridge.
qbz-slint discord_rpc controller: process-global client, init AFTER the
session is active (PR #477 persistence fix — both online and offline
entry, never at early boot), push on the track-change and play/pause
edges, clear on logout. Opt-in toggle in Settings > Integrations
(DiscordState, persisted in ui_prefs.discord_rpc_enabled) + a Flatpak
socket-access note. The opt-in is per-machine (ui_prefs) rather than
Tauri's per-user.

cc
This commit is contained in:
vicrodh committed 2026-06-22 22:56:05 -06:00
1 parent e7c969549c
commit ef38e7a04e
11 files changed
+414 -10

No files matched your search

+97
View File
@@ -0,0 +1,97 @@
//! Discord Rich Presence controller (Slint side).
//!
//! Owns a process-global [`DiscordRpc`] (the frontend-agnostic core in
//! `qbz-integrations`) and wires it to:
//! - the opt-in toggle (Settings › Integrations), persisted in `ui_prefs`;
//! - playback track-change + play/pause transitions, which push the
//! "now listening" activity;
//! - the shell session lifecycle: [`init`] runs AFTER the session is active
//! (the PR #477 fix — never at early boot), [`clear`] on logout / exit.
//!
//! The IPC is blocking, so every Discord call runs inside `spawn_blocking`.
//! All calls are no-ops when the user has not opted in.
use std::sync::{Arc, LazyLock};
use qbz_app::shell::AppRuntime;
use qbz_integrations::{DiscordRpc, NowListening};
use crate::adapter::SlintAdapter;
type Runtime = Arc<AppRuntime<SlintAdapter>>;
/// Process-global Discord client. Holds the lazy IPC connection + opt-in flag;
/// `set_enabled(false)` tears the connection down so the presence disappears.
static DISCORD: LazyLock<DiscordRpc> = LazyLock::new(DiscordRpc::default);
/// Apply the persisted opt-in. Called from `init_shell_for_user` — i.e. AFTER
/// the session is active, for BOTH the online and offline entry paths. This is
/// the persistence fix from PR #477: initializing here (not at early boot,
/// before the session/prefs existed) makes "enabled on restart" actually launch.
pub fn init(runtime: &Runtime, handle: &tokio::runtime::Handle) {
let enabled = crate::ui_prefs::load().discord_rpc_enabled;
DISCORD.set_enabled(enabled);
if enabled {
push(runtime, handle);
}
}
/// Settings toggle: persist the opt-in, apply it, and push the current track
/// (enable) or let `set_enabled(false)` clear the activity (disable).
pub fn set_enabled(enabled: bool, runtime: &Runtime, handle: &tokio::runtime::Handle) {
let mut prefs = crate::ui_prefs::load();
prefs.discord_rpc_enabled = enabled;
crate::ui_prefs::save(&prefs);
DISCORD.set_enabled(enabled);
if enabled {
push(runtime, handle);
}
}
/// Tear down the live activity + IPC connection (logout / app exit). No-op when
/// not connected.
pub fn clear(handle: &tokio::runtime::Handle) {
handle.spawn(async {
let _ = tokio::task::spawn_blocking(|| DISCORD.clear()).await;
});
}
/// Build the "now listening" snapshot from the live queue + playback state and
/// push it to Discord. No-op when disabled (cheap early return — nothing is
/// fetched). Called on track change and play/pause, mirroring the Tauri
/// service's (track_id, is_playing) transition pushes.
pub fn push(runtime: &Runtime, handle: &tokio::runtime::Handle) {
if !DISCORD.is_enabled() {
return;
}
let runtime = runtime.clone();
handle.spawn(async move {
let state = runtime.core().get_queue_state().await;
let Some(track) = state.current_track else {
// Nothing playing — drop the activity.
let _ = tokio::task::spawn_blocking(|| DISCORD.clear()).await;
return;
};
let pb = runtime.core().get_playback_state();
let title = match track.version.as_deref().filter(|v| !v.is_empty()) {
Some(version) => format!("{} ({version})", track.title),
None => track.title.clone(),
};
// Discord's large_image needs an http(s) URL or an asset key; local /
// Plex covers are filesystem paths Discord can't fetch, so drop them
// (the core falls back to the "cover" asset key).
let cover_url = track
.artwork_url
.filter(|u| u.starts_with("http://") || u.starts_with("https://"));
let meta = NowListening {
title,
artist: track.artist,
album: track.album,
is_playing: pb.is_playing,
current_time: pb.position as f64,
duration: track.duration_secs as f64,
cover_url,
};
let _ = tokio::task::spawn_blocking(move || DISCORD.update(&meta)).await;
});
}
+21
View File
@@ -30,6 +30,7 @@ mod commands;
mod custom_artwork;
mod dates;
mod discover_browse;
mod discord_rpc;
mod discover_prefs;
mod discovery_dismiss;
mod fav_cache;
@@ -174,6 +175,12 @@ fn init_shell_for_user(
scrobbler_settings::init_for_user(user_id);
scrobble::start(tokio::runtime::Handle::current());
// Discord Rich Presence: apply the persisted opt-in AFTER the session is
// active (PR #477 — never at early boot). Runs for both the online and
// offline entry paths since both call init_shell_for_user. No-op + no IPC
// when the user hasn't opted in.
discord_rpc::init(runtime, &tokio::runtime::Handle::current());
// Bind "My QBZ" nav branding (custom label + icon) to this user
// (per-user myqbz_branding.json). Seeded into MyQbzBrandingState by the
// caller so the sidebar row + Settings row reflect the persisted values.
@@ -6433,6 +6440,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let weak = window.as_weak();
let handle = tokio_rt.handle().clone();
window.on_logout(move || {
// Drop any Discord "now listening" activity on logout.
discord_rpc::clear(&handle);
let runtime = runtime.clone();
let weak = weak.clone();
handle.spawn(async move {
@@ -6453,6 +6462,18 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
});
}
// Discord Rich Presence (Settings > Integrations): seed the toggle from the
// persisted opt-in and wire the change to the controller (persist + apply).
{
let de = window.global::<DiscordState>();
de.set_enabled(crate::ui_prefs::load().discord_rpc_enabled);
let runtime = app_runtime.clone();
let handle = tokio_rt.handle().clone();
de.on_set_enabled(move |enabled| {
discord_rpc::set_enabled(enabled, &runtime, &handle);
});
}
// Settings — a toggle changed: persist it and apply audio ones to the
// live player.
{
+8
View File
@@ -1462,6 +1462,10 @@ pub(crate) async fn refresh_now_playing_meta(runtime: &Runtime, weak: &slint::We
// peer's track (Q7). Fire-and-forget; the stale-response guard (F2)
// lives in `lyrics::on_track_changed`.
crate::lyrics::on_track_changed(weak.clone(), &track);
// Discord Rich Presence: push the new track on this de-duped
// track-change edge (no-op + no IPC when not opted in). Mirrors the
// Tauri service's track_id transition push.
crate::discord_rpc::push(runtime, &tokio::runtime::Handle::current());
// Warm the NEXT queued track's lyrics in the background so the panel is
// instant when it becomes current (cache-only; no UI). Generated here
// because Tauri only ever fetches the CURRENT track.
@@ -3786,6 +3790,10 @@ pub fn start_poll_loop(
};
mc.set_playback(status, Some(std::time::Duration::from_secs(position as u64)));
}
// Discord Rich Presence: re-push on the play/pause edge so the
// "Playing" / "Paused at mm:ss" state + timestamps stay correct
// (no-op when not opted in). Mirrors the Tauri service.
crate::discord_rpc::push(&runtime, &tokio::runtime::Handle::current());
}
was_playing = is_playing;
+6
View File
@@ -168,6 +168,11 @@ pub struct UiPrefs {
/// Default ON (the notify backend ships default-on; this is the user gate).
#[serde(default = "default_system_notifications")]
pub system_notifications: bool,
/// Discord Rich Presence "now listening" opt-in. Default OFF — external
/// integrations are opt-in. (Tauri scoped this per Qobuz user; here it is a
/// per-machine app preference — your Discord client is per-machine.)
#[serde(default)]
pub discord_rpc_enabled: bool,
/// Immersive in-view search action: `"disabled"` | `"replace"` | `"next"` |
/// `"queue"`. Doubles as the enable switch (`"disabled"` keeps the field
/// inert). See [`DEFAULT_IMMERSIVE_SEARCH_ACTION`].
@@ -275,6 +280,7 @@ impl Default for UiPrefs {
album_header_gradient: default_album_header_gradient(),
intelligent_search: default_intelligent_search(),
system_notifications: default_system_notifications(),
discord_rpc_enabled: false,
immersive_search_action: default_immersive_search_action(),
immersive_default_view: default_immersive_default_view(),
immersive_last_view_mode: 0,
+1 -1
View File
@@ -26,7 +26,7 @@ export { Theme, ThemeColors } from "foundation/semantic-colors.slint";
export { ThemeState } from "foundation/theme-state.slint";
// 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, 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 } 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, VisualizerState, ImmersiveState, ImmersiveSearchActions, ImmersiveActions, MiniPlayerState, WindowControlActions } from "state.slint";
// Which top-level screen is shown. The app starts on `splash` while it
// restores a saved session, then resolves to `shell` or `login`.
@@ -8,7 +8,7 @@
import { Theme } from "../foundation/semantic-colors.slint";
import { Typography } from "../foundation/typography.slint";
import { Radius } from "../foundation/radius.slint";
import { ScrobbleState, ScrobbleActions } from "../state.slint";
import { ScrobbleState, ScrobbleActions, DiscordState } from "../state.slint";
import { SettingRow } from "SettingRow.slint";
import { QbzIcon } from "../primitives/QbzIcon.slint";
import { QbzToggle } from "../primitives/QbzToggle.slint";
@@ -264,4 +264,28 @@ export component IntegrationsSettings inherits VerticalLayout {
wrap: word-wrap;
}
}
// ===================================================================
// DISCORD — Rich Presence "now listening" (opt-in, independent of the
// scrobblers above). State + persistence live in DiscordState / ui_prefs;
// the fire + IPC live in the `discord_rpc` controller.
// ===================================================================
Rectangle { height: 12px; }
GroupHeader { text: @tr("DISCORD"); }
Rectangle { height: 4px; }
SettingRow {
label: @tr("Discord Rich Presence");
description: @tr("Show what you're listening to as your Discord status. Opt-in — Discord must be running.");
QbzToggle {
checked: DiscordState.enabled;
toggled(v) => {
DiscordState.enabled = v;
DiscordState.set-enabled(v);
}
}
}
SettingRow {
label: @tr("Flatpak socket access");
description: @tr("Flatpak install and the presence isn't showing? Grant access to Discord's IPC socket, then restart QBZ:\nflatpak override --user --filesystem=xdg-run/discord-ipc-0 com.blitzfc.qbz");
}
}
+7
View File
@@ -1314,6 +1314,13 @@ export global PlexAuthActions {
// `scrobble` controller (auth flows + the now-playing/scrobble fire live
// there). ADR-008: no pills.
// Discord Rich Presence (Settings > Integrations). Opt-in, default OFF; the
// `enabled` flag is seeded from ui_prefs and `set-enabled` persists + applies it.
export global DiscordState {
in-out property <bool> enabled: false;
callback set-enabled(bool);
}
export global ScrobbleState {
// --- Master section toggles -------------------------------------------
in-out property <bool> enabled: false; // master toggle (default OFF)