Mulberry/ios/App/UI/SettingsView.swift
astar76 abb6bd4c31 iOS 1.0.7: ListenBrainz connect and full listens, scrobble queue that can't get stuck
- Token is checked (Connected as …), hidden, Disconnect; submit toggle
- Listens carry MusicBrainz ids / ISRC read from tags (Vorbis, ID3 TXXX/UFID/TSRC, MP4)
- Each service flushes on its own; dead Last.fm sessions sign out and keep the queue
- Sign out stays visible when scrobbling is off; per-service queue counts
- tools/deploy: don't fail on zsh when no old packages exist

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-03 08:39:03 -06:00

252 lines
14 KiB
Swift

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import SwiftUI
struct SettingsView: View {
@EnvironmentObject var theme: Theme
@EnvironmentObject var prefs: Prefs
@EnvironmentObject var lib: Library
@EnvironmentObject var ui: UIState
@EnvironmentObject var scrobbler: Scrobbler
@State private var cacheSize: Int64 = 0
@State private var showEQ = false
@State private var lbToken = ""
@State private var askLB = false
@State private var fetching = false
var body: some View {
let p = theme.palette
ScrollView {
VStack(alignment: .leading, spacing: 0) {
Text("Settings").font(.system(size: 34, weight: .bold)).foregroundColor(p.cOnSurface)
.padding(.horizontal, 20).padding(.top, 8)
SectionLabel(text: "Appearance")
Card {
MenuRow(icon: "paintpalette", title: "Colours", value: colourLabel, options: [
("From album art", "album"), ("Custom colour", "custom"), ("Mulberry purple", "system")], selection: $prefs.colorSource)
if prefs.colorSource == "custom" {
ColorPicker(selection: Binding(get: { Color(rgb: UInt32(truncatingIfNeeded: prefs.customColor)) },
set: { prefs.customColor = Int($0.rgb) }), supportsOpacity: false) {
RowLabel(icon: "eyedropper", title: "Pick colour", sub: nil)
}
.padding(.trailing, 16)
}
MenuRow(icon: "circle.lefthalf.filled", title: "Theme", value: ["system": "Follow system", "dark": "Dark", "light": "Light"][prefs.themeMode] ?? "",
options: [("Follow system", "system"), ("Dark", "dark"), ("Light", "light")], selection: $prefs.themeMode)
ToggleRow(icon: "waveform", title: "Visualizer", sub: "Spectrum bars around the cover (from the audio itself, no microphone needed)", on: $prefs.visualizer)
ToggleRow(icon: "sparkle", title: "Floating bass shape", sub: "A shape at the bottom-left that morphs, spins and pulses with the beat", on: $prefs.bassShape)
ToggleRow(icon: "leaf", title: "Low-power mode", sub: "Fewer animations, no visualizer, 30 fps", on: $prefs.lowPower)
}
SectionLabel(text: "Playback")
Card {
MenuRow(icon: "hifispeaker", title: "Playback engine",
value: (EngineKind(rawValue: prefs.engine) ?? .standard).title + " — " + (EngineKind(rawValue: prefs.engine) ?? .standard).detail,
options: EngineKind.allCases.map { ($0.title, $0.rawValue) },
selection: Binding(get: { prefs.engine }, set: { prefs.engine = $0; Player.shared.engineChanged() }))
MenuRow(icon: "slider.horizontal.below.rectangle", title: "Crossfade", value: prefs.crossfade == 0 ? "Off" : "\(prefs.crossfade) seconds — songs blend into each other",
options: [("Off", "0"), ("2 seconds", "2"), ("3 seconds", "3"), ("5 seconds", "5"), ("8 seconds", "8"), ("12 seconds", "12")],
selection: Binding(get: { String(prefs.crossfade) }, set: { prefs.crossfade = Int($0) ?? 0 }))
ToggleRow(icon: "waveform.path", title: "Fade on play / pause", sub: "A short, smooth volume fade instead of a hard stop", on: $prefs.fadePause)
ToggleRow(icon: "arrow.right.to.line", title: "Gapless playback",
sub: prefs.crossfade > 0 ? "Crossfade is on, so it takes over between songs" : "No silence between tracks of an album", on: $prefs.gapless)
ToggleRow(icon: "clock.arrow.circlepath", title: "Remember position", sub: "Resume the last song where you left off", on: $prefs.resume)
ToggleRow(icon: "headphones", title: "Pause when headphones disconnect", sub: nil, on: $prefs.pauseOnDetach)
ToggleRow(icon: "speaker.wave.2", title: "ReplayGain", sub: "Even out loudness using the tags in your files", on: $prefs.replayGain)
MenuRow(icon: "music.note", title: "Hide short clips", value: prefs.minDuration == 0 ? "Off" : "Shorter than \(prefs.minDuration) s",
options: [("Off", "0"), ("10 s", "10"), ("20 s", "20"), ("30 s", "30"), ("60 s", "60")],
selection: Binding(get: { String(prefs.minDuration) }, set: { prefs.minDuration = Int($0) ?? 0; lib.scan() }))
ButtonRow(icon: "slider.vertical.3", title: "Equalizer",
sub: prefs.engine == "fx" ? (prefs.eqOn ? "On" : "Off") : "Needs the Sound FX engine") { showEQ = true }
}
SectionLabel(text: "Lyrics & covers")
Card {
MenuRow(icon: "text.quote", title: "Lyrics source", value: lyricsLabel,
options: [("Auto — synced first, local last", "auto"), ("Local .lrc / embedded", "local"), ("LRCLIB", "lrclib"),
("NetEase", "netease"), ("Off", "off")], selection: $prefs.lyricsSource)
ToggleRow(icon: "text.alignleft", title: "Plain lyrics", sub: "Show lyrics as text without timing", on: $prefs.lyricsPlain)
ToggleRow(icon: "icloud.and.arrow.down", title: "Fetch lyrics online", sub: "LRCLIB and NetEase", on: $prefs.onlineLyrics)
ToggleRow(icon: "photo", title: "Fetch missing covers", sub: "iTunes, Deezer and Last.fm", on: $prefs.onlineCovers)
ButtonRow(icon: "photo.stack", title: "Fetch covers for the whole library", sub: fetching ? "Working…" : "Saves them in the cover cache") { fetchAllCovers() }
ButtonRow(icon: "trash", title: "Clear lyrics & cover cache", sub: ByteCountFormatter.string(fromByteCount: cacheSize, countStyle: .file)) {
Covers.clearCache(); Lyrics.clearAllCache(); cacheSize = Covers.cacheSize(); ui.show("Cache cleared")
}
}
SectionLabel(text: "Library")
Card {
RowLabel(icon: "folder", title: "Music folder", sub: "Files › On My iPhone › Mulberry — put music in Music, playlists in Playlists, .lrc files next to songs or in Lyrics")
ButtonRow(icon: "arrow.clockwise", title: "Rescan library", sub: lib.scanning ? "Scanning… \(lib.scanned)" : "\(lib.songs.count) songs") {
lib.scan(force: true); ui.show("Rescanning…")
}
ButtonRow(icon: "folder.badge.gearshape", title: "Open in Files", sub: nil) {
if let u = URL(string: "shareddocuments://" + Library.root.path) { UIApplication.shared.open(u) }
}
}
SectionLabel(text: "Last.fm")
Card {
RowLabel(icon: "person.icloud", title: scrobbler.lfmLoggedIn ? "Signed in as \(prefs.lfmUser)" : "Not signed in",
sub: scrobbler.lfmLoggedIn ? (scrobbler.pending("lastfm") == 0 ? "All scrobbles sent" : "\(scrobbler.pending("lastfm")) scrobbles waiting to be sent") : (scrobbler.pending("lastfm") > 0 ? "Sign in again to send \(scrobbler.pending("lastfm")) waiting scrobbles" : "Sign in to scrobble directly from Mulberry"))
if scrobbler.lfmLoggedIn {
ToggleRow(icon: "dot.radiowaves.left.and.right", title: "Scrobble", sub: "“Now playing” and scrobbles after half the song or 4 minutes", on: $prefs.lfmEnabled)
ButtonRow(icon: "rectangle.portrait.and.arrow.right", title: "Sign out", sub: nil) { scrobbler.logout() }
} else {
ButtonRow(icon: "person.badge.key", title: "Sign in to Last.fm", sub: nil) { scrobbler.login() }
}
}
SectionLabel(text: "ListenBrainz")
Card {
RowLabel(icon: "person.icloud",
title: scrobbler.lbChecking ? "Checking token…" : scrobbler.lbConnected ? (prefs.lbUser.isEmpty ? "Token saved" : "Connected as \(prefs.lbUser)") : "Not connected",
sub: scrobbler.lbConnected ? (scrobbler.pending("listenbrainz") == 0 ? "All listens sent" : "\(scrobbler.pending("listenbrainz")) listens waiting to be sent") : "Paste your user token from listenbrainz.org › Settings")
if scrobbler.lbConnected {
ToggleRow(icon: "dot.radiowaves.left.and.right", title: "Submit listens", sub: "With MusicBrainz ids, ISRC and more from your tags", on: $prefs.lbEnabled)
ButtonRow(icon: "key", title: "Change token", sub: nil) { lbToken = ""; askLB = true }
ButtonRow(icon: "rectangle.portrait.and.arrow.right", title: "Disconnect", sub: nil) { scrobbler.lbDisconnect() }
} else {
ButtonRow(icon: "key", title: "Connect ListenBrainz", sub: nil) { lbToken = ""; askLB = true }
ButtonRow(icon: "safari", title: "Get your token", sub: "listenbrainz.org/settings") {
if let u = URL(string: "https://listenbrainz.org/settings/") { UIApplication.shared.open(u) }
}
}
}
SectionLabel(text: "About")
Card {
RowLabel(icon: "info.circle", title: "Mulberry for iOS \(AppVersion.version)",
sub: "Build \(AppVersion.build) · engine: \(Player.shared.engineName.isEmpty ? "—" : Player.shared.engineName) · Coded by Claude (Anthropic) · MIT licence")
ButtonRow(icon: "desktopcomputer", title: "Mulberry for desktop", sub: "astar76.com/git/astar76/Mulberry") {
if let u = URL(string: "https://astar76.com/git/astar76/Mulberry") { UIApplication.shared.open(u) }
}
}
}
.padding(.bottom, 24)
}
.surface(p)
.tint(p.cPrimary)
.onAppear { cacheSize = Covers.cacheSize() }
.sheet(isPresented: $showEQ) { EqualizerSheet().environmentObjects() }
.alert("ListenBrainz token", isPresented: $askLB) {
SecureField("User token", text: $lbToken)
Button("Connect") { scrobbler.lbConnect(lbToken) }
Button("Cancel", role: .cancel) {}
}
.onChange(of: prefs.visualizer) { _ in }
}
private var colourLabel: String {
["album": "From album art", "custom": "Custom colour", "system": "Mulberry purple"][prefs.colorSource] ?? ""
}
private var widgetLabel: String {
switch prefs.widgetAnim {
case 0: return "Off"
case 5: return "Battery saver — 5 fps"
case 30: return "Smooth — 30 fps"
default: return "Balanced — 15 fps"
}
}
private var lyricsLabel: String {
["auto": "Auto — synced first, local last", "local": "Local .lrc / embedded", "lrclib": "LRCLIB",
"netease": "NetEase", "off": "Off"][prefs.lyricsSource] ?? ""
}
private func fetchAllCovers() {
guard !fetching else { return }
fetching = true
let albums = lib.albums.compactMap { $0.songs.first }
Task.detached(priority: .utility) {
var n = 0
for s in albums where Covers.localData(s) == nil {
if let d = Covers.best(artist: s.groupArtist, album: s.album, title: s.displayTitle) {
try? d.write(to: Covers.onlineFile(s)); Covers.forget(s); n += 1
}
}
let found = n
await MainActor.run { fetching = false; UIState.shared.show("Found \(found) covers") }
}
}
}
struct RowLabel: View {
let icon: String
let title: String
let sub: String?
@EnvironmentObject var theme: Theme
var body: some View {
let p = theme.palette
HStack(alignment: .center, spacing: 18) {
Image(systemName: icon).font(.system(size: 18)).foregroundColor(p.cOnSurfaceVar).frame(width: 26)
VStack(alignment: .leading, spacing: 2) {
Text(title).font(.system(size: 16)).foregroundColor(p.cOnSurface)
if let sub, !sub.isEmpty { Text(sub).font(.system(size: 13)).foregroundColor(p.cOnSurfaceVar) }
}
Spacer(minLength: 0)
}
.padding(.horizontal, 18)
.padding(.vertical, 13)
.contentShape(Rectangle())
}
}
struct ToggleRow: View {
let icon: String
let title: String
let sub: String?
@Binding var on: Bool
@EnvironmentObject var theme: Theme
var body: some View {
HStack {
RowLabel(icon: icon, title: title, sub: sub)
Toggle("", isOn: $on).labelsHidden().tint(theme.palette.cPrimary).padding(.trailing, 18)
}
.onTapGesture { on.toggle() }
}
}
struct ButtonRow: View {
let icon: String
let title: String
let sub: String?
let action: () -> Void
var body: some View {
Button(action: action) { RowLabel(icon: icon, title: title, sub: sub) }.buttonStyle(.plain)
}
}
struct MenuRow: View {
let icon: String
let title: String
let value: String
let options: [(String, String)]
@Binding var selection: String
var body: some View {
Menu {
ForEach(options, id: \.1) { o in
Button { selection = o.1 } label: {
if selection == o.1 { Label(o.0, systemImage: "checkmark") } else { Text(o.0) }
}
}
} label: {
RowLabel(icon: icon, title: title, sub: value)
}
.buttonStyle(.plain)
}
}
extension Color {
/// 0xRRGGBB of a SwiftUI colour.
var rgb: UInt32 {
var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
UIColor(self).getRed(&r, green: &g, blue: &b, alpha: &a)
func c(_ v: CGFloat) -> UInt32 { UInt32(max(0, min(255, (v * 255).rounded()))) }
return c(r) << 16 | c(g) << 8 | c(b)
}
}