Files
RedLintu16andClaude Opus 5.5 64ec524ba0 CrossSound for Apple platforms
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-14 13:28:34 -07:00

503 lines
20 KiB
Swift
Executable File

// ServicesView — the "Everything Else" services hub (port of the Flutter
// services_screen.dart).
//
// Structure matches the Dart screen one-to-one: the same four groups
// ("Devices & display", "Playback", "Appearance", "App"), each an
// RwSectionHeader over ONE zero-padding RwCard holding that group's rows —
// the Dart file's reasoning ("a card per row would stack a header + divider
// around every single setting") applies unchanged here.
//
// Row dispositions:
// - Native now: Radio Tuner (AppDestination.radioTuner), Equalizer
// (AppDestination.equalizer — the tap-based EqualizerEngine, same
// cs_equalizer blob the Flutter build wrote), Shuffle whole
// list (QueueController.shuffleFromStart — the SAME persisted pref the
// Flutter toggle wrote, adopted from the flutter.* copy on first load),
// Log out (AuthStore.clearAll), plus a Console row
// (AppDestination.console) in the App group: the shell has a native
// console destination and this hub is where tools live.
// - Native now, macOS only: a Notifications group (master switch + the
// three per-type switches) bound to DesktopNotifications.shared — the
// prefs the Dart service READ (cs_notifications_enabled /
// cs_notification_types) but never had a settings UI to WRITE; the
// Flutter hub carried no notifications row, so this group is additive
// rather than a Soon-row promotion. Hidden on iOS: the feature is
// desktop-only by design (PlatformSupport.notifications), and a switch
// that can never fire a banner would be a lie.
// - Native now (Phase 7): Devices (AppDestination.devices — the
// cross-device remote screen over RemoteService) and Visualizer
// (AppDestination.visualizerSettings — the preset editor, under
// Appearance).
// - Native now (Phase 9): Tuneshine (AppDestination.tuneshine — LAN display
// mirroring over TuneshineService.shared), Themes
// (AppDestination.themes — RwAppearancePanel over the app-wide
// RwAppearanceController) plus the LIVE light/dark row beside it (the
// Dart's appearance.toggleDark, no longer parked), and Update
// (AppDestination.update — UpdateChecker's manifest fetch).
// - Still a disabled row with a "Soon" pill, so the hub reads the same as
// Flutter's: Meta Glasses, and only that one. It is parked on PURPOSE,
// not for lack of a phase — the Flutter app's iOS Display integration is
// an open upstream bug (the scene renders blank against the Meta SDK), so
// there is nothing working to port yet. See the row's own comment.
//
// No version footer: the Dart services_screen.dart renders none, so this
// screen doesn't invent one. (Update's own screen prints the installed
// version and build, which is where a user goes looking for it.)
//
// MARK: The Android glasses-companion launcher/install flow is not ported —
// Android-only (the Display work lives in a separate APK there, see the Dart
// _openGlassesCompanion); iOS/macOS get the in-app screen once the blank-scene
// bug upstream is fixed.
import CrossSoundKit
import Inject
import RedWhiteUI
import SwiftUI
@MainActor
public struct ServicesView: View {
// The active RedWhiteUI palette (set once by AppRoot's .rwTheme()).
@Environment(\.rw) private var p
// Still needed beyond the palette: the light/dark row's icon and title flip
// with the CURRENT scheme, and toggleDark(current:) needs it too — from
// .system it flips to the opposite of whatever is showing.
@Environment(\.colorScheme) private var scheme
@Environment(AppServices.self) private var services
/// The app-wide appearance, planted in the environment by CrossSoundScene
/// (see AppRoot.swift) — the same controller ThemesView's panel edits, so a
/// flip here and a flip there cannot disagree.
@Environment(RwAppearanceController.self) private var appearance
/// Log out is destructive AND (unlike Flutter, where AppState.logout()
/// rebuilt the provider tree straight to the login screen) only finishes
/// after a relaunch here — AppRoot's boot gate re-checks credentials at
/// launch, and driving its phase is not this screen's job. A single stray
/// tap stranding the session behind a restart is a worse failure than an
/// extra tap, so this row confirms where the Dart one didn't.
@State private var confirmLogout = false
/// Set after clearAll() so the row reports what actually happened instead
/// of pretending the session is still alive.
@State private var signedOut = false
public init() {}
@ObserveInjection var inject
public var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 0) {
header(p)
devicesSection(p)
playbackSection(p)
appearanceSection(p)
#if os(macOS)
notificationsSection(p)
richPresenceSection(p)
#endif
appSection(p)
}
.padding(.bottom, RwSizes.section)
}
.background(p.bg)
// The library dialog (an overlay, hence attached at the screen root)
// dismisses itself before an action runs, so nothing here clears
// confirmLogout by hand.
.rwDialog(
isPresented: $confirmLogout,
title: "Log out of SoundCloud?",
message: "Playback stops and the sign-in screen appears. Your Apple Watch signs out too.",
actions: [
.cancel(),
.destructive("Log Out") { Task { await logout() } },
])
.enableInjection()
}
// MARK: - Header
/// The family's page header (28pt title + AccentBar), same as
/// FollowingView: Flutter gave this screen an RwAppBar, but pushed screens
/// in this app carry their titles in-content.
private func header(_ p: RwPalette) -> some View {
VStack(alignment: .leading, spacing: 6) {
// headlineLarge is the library's page-title role (the old hand-set
// 28/heavy).
Text("Everything Else")
.rw(.headlineLarge)
AccentBar(width: 40)
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.top, RwSizes.pagePadding)
.padding(.bottom, RwSizes.section)
}
// MARK: - Sections (Dart order: Devices & display, Playback, Appearance, App)
private func devicesSection(_ p: RwPalette) -> some View {
section("Devices & display", palette: p) {
pushRow(
.devices, icon: "laptopcomputer.and.iphone", title: "Devices",
subtitle: "Control playback on your other devices", palette: p)
hairline(p)
// The Dart subtitle branches on Platform.isAndroid; neither platform
// here is Android, so the manage-in-app wording is the right branch.
//
// DELIBERATELY still a Soon row, and the only one left in this hub: the
// Flutter app's iOS Meta Display integration does not work either — the
// scene renders blank against the Meta SDK, an OPEN UPSTREAM bug, so
// there is no working behaviour to port. Promote this to
// pushRow(.metaGlasses, …) when that is fixed, not before: a live row
// over a blank scene would be worse than an honest "Soon".
soonRow(
icon: "eyeglasses", title: "Meta Glasses",
subtitle: "Manage connected Meta Ray-Ban glasses", palette: p)
hairline(p)
pushRow(
.lastfm, icon: "waveform.badge.magnifyingglass", title: "Last.fm",
subtitle: LastFMService.shared.isConnected
? "Scrobbling as \(LastFMService.shared.username ?? "—")"
: "Scrobble what you play", palette: p)
hairline(p)
pushRow(
.tuneshine, icon: "airplayvideo", title: "Tuneshine",
subtitle: "Cast the now playing display", palette: p)
}
}
private func playbackSection(_ p: RwPalette) -> some View {
section("Playback", palette: p) {
pushRow(
.radioTuner, icon: "radio", title: "Radio Tuner",
subtitle: "Tune how stations pick similar tracks", palette: p)
hairline(p)
pushRow(
.equalizer, icon: "slider.vertical.3", title: "Equalizer",
subtitle: "Bass, treble & 10-band presets", palette: p)
hairline(p)
pushRow(
.ambience, icon: "cloud.rain", title: "Rain",
subtitle: "Synthesised ambience that layers over playback", palette: p)
hairline(p)
shuffleRow(p)
}
}
private func appearanceSection(_ p: RwPalette) -> some View {
section("Appearance", palette: p) {
// Phase 7: the Visualizer row is live — it pushes the preset editor,
// which itself opens the fullscreen canvas, matching the Dart
// Services → Appearance → Visualizer path.
pushRow(
.visualizerSettings, icon: "waveform", title: "Visualizer",
subtitle: "Presets, styles & colors for the visualizer", palette: p)
hairline(p)
// No "corners" in the subtitle: everything is square by design and the
// panel offers no corner slider, so the row must not promise one.
pushRow(
.themes, icon: "paintpalette", title: "Themes",
subtitle: "Customize colors, fonts, and layout, or import a theme file",
palette: p)
hairline(p)
darkModeRow(p)
}
}
#if os(macOS)
/// Discord Rich Presence. macOS-only for the same reason the service is:
/// it talks to the desktop Discord client over a local socket, and there
/// is no such client to talk to on the phone.
private func richPresenceSection(_ p: RwPalette) -> some View {
let discord = DiscordPresence.shared
return section("Rich Presence", palette: p) {
toggleRow(
icon: "gamecontroller", title: "Discord",
subtitle: !discord.enabled
? "Show what you're listening to on your profile"
: (discord.connected
? "Connected"
: "Waiting for Discord — is the desktop app running?"),
isOn: Binding(
get: { discord.enabled },
set: { discord.enabled = $0 }),
palette: p)
}
}
/// Desktop notifications — the settings UI the Flutter app never had (its
/// service only READ these prefs). Master switch + one switch per banner
/// type, all bound straight to DesktopNotifications.shared; every flip
/// persists via save(). macOS-only: see the header comment.
private func notificationsSection(_ p: RwPalette) -> some View {
let notify = DesktopNotifications.shared
return section("Notifications", palette: p) {
toggleRow(
icon: "bell.badge", title: "Desktop notifications",
subtitle: notify.enabled
? "Banners for playback events"
: "All banners are off",
isOn: Binding(
get: { notify.enabled },
set: {
notify.enabled = $0
notify.save()
}),
palette: p)
hairline(p)
// Per-type switches, muted while the master switch is off — they keep
// their persisted values (the master gate is a separate pref), they
// just can't fire.
typeRow(
"nowPlaying", icon: "play.circle", title: "Now Playing",
subtitle: "When a new track starts playing", palette: p)
hairline(p)
typeRow(
"paused", icon: "pause.circle", title: "Paused",
subtitle: "When you pause playback", palette: p)
hairline(p)
typeRow(
"liked", icon: "heart.circle", title: "Liked Song",
subtitle: "When you like the current track", palette: p)
}
}
/// One banner type's row: membership of DesktopNotifications.types, CSV-
/// persisted on every flip (same "nowPlaying"/"paused"/"liked" names the
/// Dart service gated on).
private func typeRow(
_ type: String, icon: String, title: String, subtitle: String,
palette p: RwPalette
) -> some View {
let notify = DesktopNotifications.shared
return toggleRow(
icon: icon, title: title, subtitle: subtitle,
isOn: Binding(
get: { notify.types.contains(type) },
set: { on in
if on { notify.types.insert(type) } else { notify.types.remove(type) }
notify.save()
}),
enabled: notify.enabled,
palette: p)
}
/// A switch row in the hub's chrome (shuffleRow's shape, generalized): the
/// whole row flips the switch, matching the Dart ListTiles' onTap-next-to-
/// Switch convention this hub inherited.
private func toggleRow(
icon: String, title: String, subtitle: String, isOn: Binding<Bool>,
enabled: Bool = true, palette p: RwPalette
) -> some View {
rowLabel(
icon: icon, title: title, subtitle: subtitle, enabled: enabled, palette: p
) {
// fixedSize: the library switch is drawn as label + spacer + track,
// so without it the (label-less) toggle would claim the row's width
// from the title column. See shuffleRow.
Toggle("", isOn: isOn)
.labelsHidden()
.toggleStyle(.rwSwitch)
.fixedSize(horizontal: true, vertical: false)
.disabled(!enabled)
}
.onTapGesture { if enabled { isOn.wrappedValue.toggle() } }
}
#endif
private func appSection(_ p: RwPalette) -> some View {
section("App", palette: p) {
pushRow(
.update, icon: "arrow.up.circle", title: "Update",
subtitle: "Check for the latest CrossSound", palette: p)
hairline(p)
pushRow(
.console, icon: "terminal", title: "Console",
subtitle: "Live app logs and diagnostics", palette: p)
hairline(p)
logoutRow(p)
}
}
// MARK: - Section / row building blocks
/// One Dart group: RwSectionHeader + gap + a zero-padding RwCard of rows,
/// with the Dart ListView's section spacing underneath.
private func section(
_ title: String, palette p: RwPalette, @ViewBuilder rows: () -> some View
) -> some View {
VStack(alignment: .leading, spacing: RwSizes.gap) {
RwSectionHeader(title)
// Zero insets: the rows own their padding (the old CGFloat 0 spelled
// in the library's EdgeInsets vocabulary).
RwCard(padding: EdgeInsets()) {
VStack(spacing: 0) { rows() }
}
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.bottom, RwSizes.section)
}
/// The shared row chrome (icon column + title/subtitle stack) every row
/// variant composes, so the four groups line up like the Dart ListTiles
/// did. `enabled: false` mutes the icon and title — "Soon" rows should
/// read as present-but-parked, not tappable.
private func rowLabel(
icon: String, title: String, subtitle: String, enabled: Bool = true,
palette p: RwPalette, @ViewBuilder trailing: () -> some View
) -> some View {
HStack(spacing: RwSizes.gap) {
// Parked dims to 40% primary, icon and title alike (the disabled tone;
// the old pastel is primary now, BareButtons.swift).
Image(systemName: icon)
.font(.system(size: 17))
.foregroundStyle(enabled ? p.red : p.red.withAlpha(0.4))
.frame(width: 28)
VStack(alignment: .leading, spacing: 2) {
// The role's primary; dimmed = parked.
Text(title)
.rw(.bodyLarge, color: (enabled ? p.text : p.red.withAlpha(0.4)).color)
.lineLimit(1)
Text(subtitle)
.rw(.labelMedium)
.lineLimit(2)
.multilineTextAlignment(.leading)
}
Spacer(minLength: RwSizes.gap)
trailing()
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.vertical, 10)
.contentShape(Rectangle())
}
/// A row with a native destination: value-based link → AppShell's single
/// .navigationDestination switch, same as every other push in the app.
private func pushRow(
_ destination: AppDestination, icon: String, title: String,
subtitle: String, palette p: RwPalette
) -> some View {
NavigationLink(value: destination) {
LitPalette { p in
rowLabel(icon: icon, title: title, subtitle: subtitle, palette: p) {
// Inactive chrome, not a hint: the icon token, not a text one.
Image(systemName: "chevron.right")
.font(.system(size: 12, weight: .semibold))
.foregroundStyle(p.iconInactive)
}
}
}
.buttonStyle(.bareRow())
}
/// A later-phase row: kept in place (same title/subtitle/group as the Dart
/// hub) but inert, marked with the neutral "Soon" pill.
private func soonRow(
icon: String, title: String, subtitle: String, palette p: RwPalette
) -> some View {
rowLabel(icon: icon, title: title, subtitle: subtitle, enabled: false, palette: p) {
OutlinedBadge("Soon")
}
}
/// "Shuffle whole list" — the one settings row with a live native target
/// today. Writing queue.shuffleFromStart persists via its didSet (pref
/// cs_shuffle_from_start), and the subtitle re-renders through Observation
/// because body reads the same property. Row tap flips it too, matching
/// the Dart ListTile's onTap next to its Switch.
private func shuffleRow(_ p: RwPalette) -> some View {
let isOn = Binding(
get: { services.queue.shuffleFromStart },
set: { services.queue.shuffleFromStart = $0 })
return rowLabel(
icon: "shuffle",
title: "Shuffle whole list",
subtitle: services.queue.shuffleFromStart
? "Shuffle reorders everything and starts from the top"
: "The track you tap plays first, the rest is shuffled",
palette: p
) {
// The library's .rwSwitch chrome is label + Spacer + track, so a
// label-less Toggle is horizontally greedy; fixedSize pins it to its
// ideal width (the track) and leaves the row's width to the title and
// subtitle, the way the old fixed-width switch did.
Toggle("", isOn: isOn)
.labelsHidden()
.toggleStyle(.rwSwitch)
.fixedSize(horizontal: true, vertical: false)
}
.onTapGesture { services.queue.shuffleFromStart.toggle() }
}
/// Light/dark, live — Flutter called appearance.toggleDark(context) from both
/// the row tap and the switch, and so does this. The switch shows the scheme
/// the app is CURRENTLY rendering (that is what `.system` means), so the
/// setter ignores its incoming value and just flips: toggleDark resolves
/// .system against the current scheme itself. The subtitle names where the
/// setting actually stands, since following the system is not the same state
/// as being pinned.
///
/// Built on rowLabel rather than toggleRow on purpose: that helper lives
/// inside `#if os(macOS)` (it exists for the notifications group) and this
/// row ships on both platforms.
private func darkModeRow(_ p: RwPalette) -> some View {
let isDark = scheme == .dark
let isOn = Binding(
get: { isDark },
set: { _ in appearance.toggleDark(current: scheme) })
return rowLabel(
icon: isDark ? "sun.max" : "moon",
title: isDark ? "Light mode" : "Dark mode",
subtitle: appearance.value.themeMode == .system
? "Following the system appearance (full settings under Themes)"
: "Pinned to \(isDark ? "dark" : "light") (full settings under Themes)",
palette: p
) {
// fixedSize: see shuffleRow.
Toggle("", isOn: isOn)
.labelsHidden()
.toggleStyle(.rwSwitch)
.fixedSize(horizontal: true, vertical: false)
}
.onTapGesture { appearance.toggleDark(current: scheme) }
}
private func logoutRow(_ p: RwPalette) -> some View {
Button {
confirmLogout = true
} label: {
rowLabel(
icon: "rectangle.portrait.and.arrow.right",
title: "Log out",
subtitle: signedOut
? "Signed out — restart CrossSound to sign in again"
: "Sign out of your SoundCloud account",
enabled: !signedOut,
palette: p
) {
EmptyView()
}
}
.buttonStyle(.bareRow())
.disabled(signedOut)
}
// MARK: - Actions
/// Flutter's state.logout() flipped the provider tree straight back to the
/// login screen; AppServices.signOut does the same here (credentials,
/// playback, queue, remote presence, then AppRoot's signed-out screen).
/// The row only asks for a restart if nothing could take the screen over.
private func logout() async {
signedOut = !(await services.signOut())
CSLog.shared.log("services", "logged out" + (signedOut ? " — restart re-gates" : ""))
}
/// Hair separators are the list's job, not the row's (see LikesView) —
/// inset to the card's content edge like FollowingView's.
private func hairline(_ p: RwPalette) -> some View {
Rectangle()
.fill(p.hair)
.frame(height: 1)
.padding(.leading, RwSizes.pagePadding)
}
}