Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion src-tauri/src/persistence/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,12 @@ pub struct Preferences {
/// when Reverb closed — or [`STARTUP_SYSTEM_DEFAULT`] for none. `None` —
/// or an id no config has — starts on the one last active.
pub startup_device_config: Option<String>,
/// Show a device config picker in the player bar, beside the volume. Off
/// by default: switching is a Settings job until the listener asks.
pub show_output_picker: bool,
/// Show the button that opens the parametric EQ in the player bar. On by
/// default, as it was before it could be hidden.
pub show_eq_button: bool,
/// "raw" for the original file, or "mp3-320" / "mp3-192" / "mp3-128"
/// for server-side transcoding.
pub streaming_format: String,
Expand Down Expand Up @@ -185,6 +191,8 @@ impl Default for Preferences {
device_configs: Vec::new(),
active_device_config: None,
startup_device_config: None,
show_output_picker: false,
show_eq_button: true,
streaming_format: "raw".into(),
replay_gain: ReplayGainSettings::default(),
crossfade_secs: 0,
Expand Down Expand Up @@ -426,7 +434,9 @@ mod tests {
"seekBarThickness": "thick",
"syncQueue": false,
"checkForUpdates": false,
"discordPresence": true
"discordPresence": true,
"showOutputPicker": true,
"showEqButton": false
}"#;
let prefs: Preferences = serde_json::from_str(raw).expect("camelCase names must match");
assert!(prefs.direct_scrobble);
Expand All @@ -439,6 +449,8 @@ mod tests {
assert!(!prefs.sync_queue);
assert!(!prefs.check_for_updates);
assert!(prefs.discord_presence);
assert!(prefs.show_output_picker);
assert!(!prefs.show_eq_button);

// ...and come back out under the same names.
let back = serde_json::to_value(&prefs).unwrap();
Expand All @@ -452,6 +464,8 @@ mod tests {
assert_eq!(back["syncQueue"], serde_json::json!(false));
assert_eq!(back["checkForUpdates"], serde_json::json!(false));
assert_eq!(back["discordPresence"], serde_json::json!(true));
assert_eq!(back["showOutputPicker"], serde_json::json!(true));
assert_eq!(back["showEqButton"], serde_json::json!(false));
}

/// Before ListenBrainz, direct scrobbling was "Last.fm only". A settings
Expand Down Expand Up @@ -790,6 +804,8 @@ mod tests {
assert_eq!(s.prefs.output(), OutputSettings::default());
assert!(s.prefs.check_for_updates, "update checks default to on");
assert!(!s.prefs.discord_presence, "Discord presence defaults to off");
assert!(!s.prefs.show_output_picker, "the player bar output picker defaults to off");
assert!(s.prefs.show_eq_button, "the player bar EQ button stays shown");
// And the new shape round-trips.
let back = serde_json::to_string(&s).unwrap();
let s2: Settings = serde_json::from_str(&back).unwrap();
Expand Down
11 changes: 8 additions & 3 deletions src/components/layout/PlayerBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { ArtistLinks } from "../library/ArtistLinks";
import { CoverImage } from "../library/CoverImage";
import { StarButton } from "../library/StarButton";
import { IconButton } from "../ui/Button";
import { OutputPicker } from "../player/OutputPicker";
import { SeekBar } from "../player/SeekBar";
import { SignalPathIndicator } from "../player/SignalPathIndicator";
import { TransportControls } from "../player/TransportControls";
Expand Down Expand Up @@ -41,6 +42,7 @@ export function PlayerBar() {
const { setQueuePanelOpen, setNowPlayingOpen } = useUiStore.getState();
const queuePanelOpen = useUiStore((s) => s.queuePanelOpen);
const liquid = usePrefsStore((s) => s.prefs.layout) === "liquid";
const showEqButton = usePrefsStore((s) => s.prefs.showEqButton);
const navigate = useNavigate();

const song = item?.song;
Expand Down Expand Up @@ -94,16 +96,19 @@ export function PlayerBar() {
{/* Right controls */}
<div className="flex w-64 items-center justify-end gap-1">
<SignalPathIndicator />
<IconButton label={t("player.eqInSettings")} onClick={() => navigate(EQ_PATH)}>
<SlidersVertical className="size-4" />
</IconButton>
{showEqButton && (
<IconButton label={t("player.eqInSettings")} onClick={() => navigate(EQ_PATH)}>
<SlidersVertical className="size-4" />
</IconButton>
)}
<IconButton
label={t("queue.title")}
onClick={() => setQueuePanelOpen(!queuePanelOpen)}
className={queuePanelOpen ? "text-accent" : ""}
>
<ListMusic className="size-4" />
</IconButton>
<OutputPicker />
<VolumeSlider />
</div>
</footer>
Expand Down
141 changes: 141 additions & 0 deletions src/components/player/OutputPicker.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
// Output picker: switches the active device config from the player bar, so
// moving between, say, headphones and speakers needs no trip to Settings. Shown
// only when turned on in Settings → Audio, which is still where configs are
// made and edited.

import { useQuery } from "@tanstack/react-query";
import { DropdownMenu } from "radix-ui";
import { Settings2, Speaker } from "lucide-react";
import { useNavigate } from "react-router";
import { activeDeviceConfig, AUDIO_PATH, deviceConfigSummary } from "../../lib/deviceConfigs";
import { useT } from "../../lib/i18n";
import { cmd } from "../../lib/ipc/commands";
import { usePrefsStore } from "../../stores/prefsStore";
import { useUiStore } from "../../stores/uiStore";

/** Radio value for the system default, which has no config id. */
const SYSTEM_DEFAULT = "";

const itemClass =
"group flex cursor-pointer items-center gap-2.5 rounded px-2.5 py-1.5 text-sm outline-none select-none data-highlighted:bg-surface-2";

function Choice({
value,
name,
summary,
missing = false,
}: {
value: string;
name: string;
summary: string;
/** The config's device is not plugged in. */
missing?: boolean;
}) {
return (
<DropdownMenu.RadioItem value={value} className={`${itemClass} text-text`}>
<span
aria-hidden
className="flex size-4 shrink-0 items-center justify-center rounded-full border border-faint group-data-[state=checked]:border-accent"
>
<DropdownMenu.ItemIndicator>
<span className="block size-2 rounded-full bg-accent" />
</DropdownMenu.ItemIndicator>
</span>
<span className="min-w-0">
<span className="block truncate">{name}</span>
<span className={`block truncate text-xs ${missing ? "text-danger" : "text-faint"}`}>
{summary}
</span>
</span>
</DropdownMenu.RadioItem>
);
}

function Picker() {
const t = useT();
const navigate = useNavigate();
const prefs = usePrefsStore((s) => s.prefs);
const set = usePrefsStore((s) => s.set);
// Fetched with the button rather than on open, so the list reads right the
// moment it opens. The engine bridge refetches it when a device comes or goes.
const devices = useQuery({ queryKey: ["audio-devices"], queryFn: () => cmd("audio_list_devices") });
const active = activeDeviceConfig(prefs);

const activeName = active?.name ?? t("settings.systemDefault");
// A config locked to its device stays active while the device is away, so
// the button says playback is waiting on it.
const activeMissing = active != null && deviceConfigSummary(active, devices.data, t).missing;
const label = t("signal.output", { device: activeName });
const title = activeMissing ? `${label} · ${t("settings.deviceNotConnected")}` : label;

function manage() {
// From the full-screen player too, which would otherwise cover Settings.
useUiStore.getState().setNowPlayingOpen(false);
navigate(AUDIO_PATH);
}

return (
<DropdownMenu.Root>
<DropdownMenu.Trigger asChild>
<button
aria-label={title}
title={title}
className={`inline-flex cursor-pointer items-center justify-center rounded-full p-2 transition-colors hover:bg-surface-2 data-[state=open]:bg-surface-2 ${
activeMissing ? "text-danger" : "text-dim hover:text-text"
}`}
>
<Speaker className="size-4" />
</button>
</DropdownMenu.Trigger>
<DropdownMenu.Portal>
<DropdownMenu.Content
side="top"
align="end"
sideOffset={8}
collisionPadding={8}
// Above the full-screen player (z-20), which renders this too.
className="z-50 w-72 rounded-lg border border-edge bg-surface p-1 shadow-xl focus:outline-none"
>
<DropdownMenu.Label className="px-2.5 pt-1.5 pb-1 text-xs font-semibold text-dim">
{t("player.outputHeading")}
</DropdownMenu.Label>
<DropdownMenu.RadioGroup
value={active?.id ?? SYSTEM_DEFAULT}
onValueChange={(id) => set({ activeDeviceConfig: id || null })}
>
<Choice
value={SYSTEM_DEFAULT}
name={t("settings.systemDefault")}
summary={t("player.outputSystemDefaultHint")}
/>
{prefs.deviceConfigs.map((config) => {
const { text, missing } = deviceConfigSummary(config, devices.data, t);
return (
<Choice
key={config.id}
value={config.id}
name={config.name}
summary={text}
missing={missing}
/>
);
})}
</DropdownMenu.RadioGroup>
<DropdownMenu.Separator className="my-1 h-px bg-edge" />
<DropdownMenu.Item
className={`${itemClass} text-dim data-highlighted:text-text`}
onSelect={manage}
>
<Settings2 className="size-4" /> {t("player.manageDeviceConfigs")}
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu.Root>
);
}

/** The player bar's device config picker, when Settings has it shown. */
export function OutputPicker() {
const show = usePrefsStore((s) => s.prefs.showOutputPicker);
return show ? <Picker /> : null;
}
33 changes: 33 additions & 0 deletions src/lib/deviceConfigs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
afterDeviceLost,
canGoExclusive,
deleteDeviceConfig,
deviceConfigSummary,
deviceLabel,
hqplayerAddress,
isConnected,
Expand All @@ -12,6 +13,7 @@ import {
STARTUP_SYSTEM_DEFAULT,
startupDeviceConfig,
} from "./deviceConfigs";
import { translator } from "./i18n/core";
import type { DeviceConfig, OutputDevice } from "./subsonic/types";

const desk: DeviceConfig = {
Expand Down Expand Up @@ -149,6 +151,37 @@ describe("devices", () => {
});
});

describe("deviceConfigSummary", () => {
const t = translator("en");
const fiioDesk: DeviceConfig = { ...desk, device: fiio.id, lockDevice: true };

it("names the device and how the config plays through it", () => {
expect(deviceConfigSummary(fiioDesk, [fiio], t)).toEqual({
text: "FiiO BTR17 · Exclusive · Matches source rate · Locked",
missing: false,
});
expect(deviceConfigSummary(speakers, [fiio], t)).toEqual({
text: "System default · Shared",
missing: false,
});
});

it("leads with an unplugged device", () => {
expect(deviceConfigSummary(fiioDesk, [mac], t)).toEqual({
text: "Device not connected · Exclusive · Matches source rate · Locked",
missing: true,
});
});

it("names the HQPlayer an HQPlayer config hands playback to", () => {
const hq = { ...desk, hqplayer: { host: "studio.local", port: 4321 } };
expect(deviceConfigSummary(hq, [], t)).toEqual({
text: "HQPlayer at studio.local",
missing: false,
});
});
});

describe("canGoExclusive", () => {
it("needs a direct device where devices are told apart that way (Linux)", () => {
const linux: OutputDevice[] = [fiio];
Expand Down
34 changes: 34 additions & 0 deletions src/lib/deviceConfigs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,13 @@
// These helpers return preference patches; the prefs store persists them, and
// the backend reopens the output when the setup they describe changes.

import type { T } from "./i18n/core";
import type { DeviceConfig, HqPlayerEndpoint, OutputDevice, Preferences } from "./subsonic/types";

/** Settings' audio section, where device configs are made and edited. */
export const AUDIO_SECTION_ID = "audio";
export const AUDIO_PATH = `/settings#${AUDIO_SECTION_ID}`;

/**
* `startupDeviceConfig` value that starts every launch on the system default.
* Config ids are nanoids or UUIDs, so none can be this.
Expand Down Expand Up @@ -115,6 +120,35 @@ export function parsePort(text: string): number | null {
return port >= 1 && port <= 65535 ? port : null;
}

/**
* One line on what a config plays through and how: its device (or HQPlayer),
* shared or exclusive, and the options it turns on. `missing` when its device
* is not plugged in, in which case that is what the line leads with.
*/
export function deviceConfigSummary(
config: DeviceConfig,
devices: OutputDevice[] | undefined,
t: T,
): { text: string; missing: boolean } {
if (config.hqplayer) {
return {
text: t("settings.configHqplayer", { address: hqplayerAddress(config.hqplayer) }),
missing: false,
};
}
const missing = !isConnected(devices, config.device);
const device = missing
? t("settings.deviceNotConnected")
: (deviceLabel(devices, config.device) ?? t("settings.systemDefault"));
const parts = [
device,
config.exclusiveOutput ? t("settings.configExclusive") : t("settings.configShared"),
];
if (config.matchSourceRate) parts.push(t("settings.configMatchRate"));
if (config.lockDevice) parts.push(t("settings.configLocked"));
return { text: parts.join(" · "), missing };
}

/** Whether a config's device is plugged in. Unknown counts as yes. */
export function isConnected(devices: OutputDevice[] | undefined, device: string | null): boolean {
return device == null || devices == null || findDevice(devices, device) != null;
Expand Down
9 changes: 9 additions & 0 deletions src/lib/i18n/messages/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ export const de: Messages = {
"player.mute": "Stumm schalten",
"player.unmute": "Stummschaltung aufheben",
"player.volume": "Lautstärke",
"player.outputHeading": "Ausgabe",
"player.outputSystemDefaultHint": "Geteilt, mit der eigenen Abtastrate des Geräts",
"player.manageDeviceConfigs": "Gerätekonfigurationen verwalten",
"player.repeat": "Wiederholung: {mode}",
"repeat.off": "aus",
"repeat.all": "alle",
Expand Down Expand Up @@ -470,6 +473,12 @@ export const de: Messages = {
"settings.startupDeviceConfigHint":
"Die Gerätekonfiguration, mit der Reverb startet, egal welche beim Beenden aktiv war. „Zuletzt verwendet“ macht dort weiter, wo du aufgehört hast.",
"settings.startupDeviceConfigLastUsed": "Zuletzt verwendet",
"settings.outputPicker": "Ausgabewahl in der Player-Leiste",
"settings.outputPickerHint":
"Eine Schaltfläche neben der Lautstärke, die zwischen Gerätekonfigurationen wechselt, ohne die Einstellungen zu öffnen.",
"settings.eqButton": "Schaltfläche für den parametrischen EQ in der Player-Leiste",
"settings.eqButtonHint":
"Öffnet den EQ weiter unten. Strg+E (⌘E auf dem Mac) funktioniert in jedem Fall.",
"settings.deviceConfigName": "Name",
"settings.deviceConfigNameHint": "Leer lassen, um den Namen des Geräts zu verwenden.",
"settings.systemDefaultConfigHint":
Expand Down
8 changes: 8 additions & 0 deletions src/lib/i18n/messages/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ export const en = {
"player.mute": "Mute",
"player.unmute": "Unmute",
"player.volume": "Volume",
"player.outputHeading": "Output",
"player.outputSystemDefaultHint": "Shared, at the device's own rate",
"player.manageDeviceConfigs": "Manage device configs",
"player.repeat": "Repeat: {mode}",
"repeat.off": "off",
"repeat.all": "all",
Expand Down Expand Up @@ -495,6 +498,11 @@ export const en = {
"settings.startupDeviceConfigHint":
"Reverb starts on this config every time, whichever one was in use when it closed. “Last used” picks up where you left off.",
"settings.startupDeviceConfigLastUsed": "Last used",
"settings.outputPicker": "Output picker in the player bar",
"settings.outputPickerHint":
"A button beside the volume that switches device configs without opening Settings.",
"settings.eqButton": "Parametric EQ button in the player bar",
"settings.eqButtonHint": "Opens the EQ below. Ctrl+E (⌘E on a Mac) works either way.",
"settings.deviceConfigName": "Name",
"settings.deviceConfigNameHint": "Leave empty to use the device's name.",
"settings.systemDefaultConfigHint":
Expand Down
Loading
Loading