Mulberry/App/UI/SettingsView.swift
astar76 8e6f8a86a4 Mulberry for iOS: initial SwiftUI port of the Android app
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 19:30:49 -05:00

240 lines
13 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)
MenuRow(icon: "rectangle.3.group", title: "Widget animation", value: widgetLabel,
options: [("Off", "0"), ("Battery saver — 5 fps", "5"), ("Balanced — 15 fps", "15"), ("Smooth — 30 fps", "30")],
selection: Binding(get: { String(prefs.widgetAnim) }, set: { prefs.widgetAnim = Int($0) ?? 15; Player.shared.publishWidget() }))
ToggleRow(icon: "leaf", title: "Low-power mode", sub: "Fewer animations, no visualizer, 30 fps", on: $prefs.lowPower)
}
SectionLabel(text: "Playback")
Card {
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.eqOn ? "On" : "Off") { 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.lfmOn ? "Signed in as \(prefs.lfmUser)" : "Not signed in",
sub: scrobbler.lfmOn ? (scrobbler.pending.isEmpty ? "Scrobbling directly from Mulberry" : "\(scrobbler.pending.count) scrobbles waiting to be sent") : "Sign in to scrobble directly from Mulberry")
if scrobbler.lfmOn {
ToggleRow(icon: "dot.radiowaves.left.and.right", title: "Scrobble", sub: nil, 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 {
ButtonRow(icon: "key", title: prefs.lbToken.isEmpty ? "Add user token" : "Token saved",
sub: "Find it at listenbrainz.org › Settings") { lbToken = prefs.lbToken; askLB = true }
}
SectionLabel(text: "About")
Card {
RowLabel(icon: "info.circle", title: "Mulberry for iOS \(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "")",
sub: "Coded by Claude (Anthropic) · MIT licence")
ButtonRow(icon: "desktopcomputer", title: "Mulberry for desktop", sub: "archlinux.tail7c4f5e.ts.net/git/astar76/Mulberry") {
if let u = URL(string: "https://archlinux.tail7c4f5e.ts.net/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) {
TextField("User token", text: $lbToken)
Button("Save") { prefs.lbToken = lbToken.trimmingCharacters(in: .whitespaces) }
Button("Remove", role: .destructive) { prefs.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)
}
}