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

1396 lines
65 KiB
Swift
Executable File

// AppRoot — the boot gate: loads auth, gates on credentials, and hosts the
// tabbed AppShell once the session is good.
//
// Ownership still mirrors the Flutter AppState split: the services live here
// as @State so a single instance of each survives the whole scene
// (PlayerEngine especially — recreating it would tear down the
// AVContentKeySession mid-song). The Phase-3 shell pass added the provider
// layer back in: the same instances are wrapped once in AppServices and
// dropped into the environment, and everything visual — tabs, screens, and
// the mini player that lived here through Phase 2 — belongs to AppShell now.
// What stays here is the plumbing no screen should own: the bootstrap/reauth
// recovery ladder, the control-plane hookup (wireControlHooks), and the Now
// Playing pump.
//
// Login lives here too: the signed-out state opens LoginSheet (WKWebView on
// soundcloud.com), and the API's recovery hooks are wired to SessionHarvester —
// an expired session silently re-captures from the persistent WebView cookies
// first, exactly like the Flutter app's headless refresh; only when that fails
// does the "session expired" banner ask for a real re-login.
//
// The Themes phase added ONE layer above AppRoot: CrossSoundScene (below) owns
// the user's appearance and applies the theme, because the theme modifier can
// never live in AppRoot's own body (see that type's doc comment). AppearanceStore
// is its disk half — the pref, the clipboard JSON, and the theme-FILE import
// (RwAppearance.load(contentsOf:)) — and the one place the RedWhiteUI "everything
// is square" rule meets a saved radius (see `squared`). On iOS it is also how
// the appearance reaches the home-screen widget: publishToWidget hands the
// same JSON to the App Group (np_appearance) and reloads the widget, which
// keeps the colors and keeps the font only where a widget can render it
// (see that method).
import CrossSoundKit
import Inject
import RedWhiteUI
import SwiftUI
#if os(iOS)
// AppearanceStore.publishToWidget: the App Group key is the bridge's and the
// reload is WidgetKit's — the pair NowPlayingCenter links for the snapshot.
import CrossSoundBridge
import WidgetKit
#endif
// MARK: - Scene root (the appearance layer above AppRoot)
/// What each app target mounts in its scene: the appearance layer wrapped
/// around AppRoot.
///
/// WHY this type exists instead of AppRoot owning the RwAppearanceController
/// itself: `.rwTheme(_:)` is what publishes `\.rw`, `\.rwMetrics` and
/// `\.rwFontFamily`, and **a view cannot read environment values its own body
/// installs** — AppRoot reads `\.rw` for its banners and the signed-out
/// screen, so the modifier has to sit ABOVE AppRoot. That is why the app
/// entries applied a bare `.rwTheme()` before this phase; the modifier takes
/// the appearance VALUE, so the controller now has to live one level up too.
///
/// It lives here rather than duplicated in the two app entries so the pref key,
/// the load rules and the save-on-every-change rule exist exactly once — the
/// Flutter split was the same (main.dart's loadAppearance() owned the
/// controller, MaterialApp took its value, screens read it from a Provider).
@MainActor
public struct CrossSoundScene: View {
let platformName: String
/// Hydrated from UserDefaults by the first init and then kept by @State for
/// the life of the scene. A re-init only re-reads one string; SwiftUI keeps
/// the first instance and discards the rest (AppRoot's seeded-@State
/// contract, same reasoning).
@State private var appearance = AppearanceStore.load()
public init(platformName: String) {
self.platformName = platformName
}
@ObserveInjection var inject
public var body: some View {
AppRoot(platformName: platformName)
// All text primary, and bare buttons by default (BareButtons.swift).
// Inside .rwTheme() below, so it wins over the theme's own defaults.
.modifier(CrossSoundLook())
// Reachable from every screen the way AppServices is — an @Observable in
// the environment — so ServicesView's dark-mode row and ThemesView's
// panel drive the SAME controller (Flutter: Provider<RwAppearanceController>).
// Sheets inherit it too, since AppRoot's own .environment(services) sits
// below this one in the same chain.
.environment(appearance)
// ABOVE AppRoot on purpose — see the type's doc comment. Passing the
// value (not the controller) is what makes an edit re-theme the whole
// app: the controller is @Observable, reading .value here subscribes
// this body, and the re-render hands the modifier fresh palette,
// metrics, font family and color scheme.
.rwTheme(appearance.value)
// Forces the native navigation bar OPAQUE. On iOS 26+ it defaults to
// translucent Liquid Glass — that floating circular back button on
// pushed screens — and nothing in SwiftUI turns it off. No
// .rwTabBarAppearance(): the tab bar is gone, RwShell's drawer
// replaced it.
.rwNavigationBarAppearance()
// Flutter parity (main.dart: appearance.addListener(… setString)): the
// save rides every change — every accent pick, density step, and an
// imported theme (clipboard or file) the moment ThemesView assigns it.
// RwAppearance is Equatable, so onChange fires only on real changes, and
// a UserDefaults write is an in-memory update with a coalesced flush —
// nothing here needs debouncing. The iOS widget's copy rides the same
// save (AppearanceStore.publishToWidget).
.onChange(of: appearance.value) { _, value in
AppearanceStore.save(value)
}
// Once at launch too: the save above fires only on a CHANGE, so an
// appearance that load() restored as-is is never saved by this process
// — and an install upgraded from a build before np_appearance existed
// would leave its widget on the defaults until the next panel edit.
// Cheap when nothing changed: the publish compares against the App
// Group first, so a routine launch writes nothing and reloads nothing.
.task {
AppearanceStore.publishToWidget(appearance.value)
}
.enableInjection()
}
}
// MARK: - Appearance persistence
/// The preference the appearance system reads and writes (plus the theme-font
/// record beside it, `fontFileKey`) — and the theme-FILE import
/// (`loadThemeFile(at:)`), the other way an appearance gets into the app. On
/// iOS it is also the appearance's one way OUT: `publishToWidget(_:)` mirrors
/// every save into the App Group for the home-screen widget.
///
/// Key and JSON shape are Flutter's (main.dart `_kAppearance` = "appearance",
/// `RwAppearance.toJson`), so an install migrated from the Flutter build keeps
/// the look it had — all but the corner radius, which `squared(_:)` pins to
/// the library default. Not a store object with state: the live value lives
/// in the RwAppearanceController, and this is only the disk half.
enum AppearanceStore {
static let prefKey = "appearance"
/// The FILE NAME (not path — the iOS container path changes between
/// launches) of the theme font copied into `themeFontsDirectory()` by the
/// last theme-file import that carried a "fontFile". The library registers
/// a theme's font with CoreText for the current PROCESS only and stores just
/// its family name in `font`, so without this record the saved family would
/// resolve to nothing on the next launch and Font.custom would silently fall
/// back to the system font. load() re-registers it before the controller
/// exists; save() clears it whenever the font is a built-in family again.
static let fontFileKey = "appearance.fontFile"
/// The keys RwAppearance encodes — used to tell a real exported theme from
/// any other valid JSON (see `decode(_:requireKeys:)`). "palette" is the
/// theme's per-token override block (RwPaletteOverrides), so a hand-written
/// theme that only recolors counts too.
private static let jsonKeys: Set<String> = [
"themeMode", "accent", "radius", "density", "font", "palette",
]
/// What a theme FILE may say on top of that: "fontFile" (.ttf/.otf next to
/// the theme, registered on load — RwAppearance.load's own key).
private static let themeFileKeys: Set<String> = jsonKeys.union(["fontFile"])
/// The saved appearance, or the house defaults when there is nothing (or
/// nothing readable) to restore.
static func load() -> RwAppearanceController {
let d = UserDefaults.standard
// One-time flutter.* adoption, MOVE not copy: the flutter.appearance key
// is deleted even when nothing was adopted, or the next launch would
// re-adopt the stale Flutter value over a newer native save (the
// AuthStore.load convention every store here follows). Any Flutter install
// HAS this key — its loadAppearance() wrote `appearance` on first launch
// even when nothing was saved, after folding the older theme_base /
// theme_accent / theme_font / theme_tl / theme_density prefs into it — so
// this one key covers the whole migration history.
if d.object(forKey: prefKey) == nil, let v = d.string(forKey: "flutter.\(prefKey)") {
d.set(v, forKey: prefKey)
}
d.removeObject(forKey: "flutter.\(prefKey)")
guard let raw = d.string(forKey: prefKey), let saved = decodeRaw(raw) else {
return RwAppearanceController()
}
// The persisted-appearance trap: RwSizes.radius is 0 by design and the
// appearance panel offers no Corners slider any more, but a pref from
// before that rule — or the Flutter value adopted above, whose default
// radius is 6 — still carries one, and .rwTheme() turns it straight into
// RwMetrics, rounding every control the moment it loads. Square it BEFORE
// the controller exists, so nothing ever renders rounded, and write the
// corrected JSON back so this is a one-time fix rather than a per-launch
// one (and an export shows what the app actually draws).
var value = squared(saved)
if saved.radius != value.radius {
CSLog.shared.log(
"appearance",
"reset saved radius \(Int(saved.radius)) → \(Int(value.radius)) — corners are square by design")
save(value)
}
// The theme-font half of the persisted-appearance story: a family from a
// theme file's "fontFile" only resolves while its file is registered with
// THIS process (see fontFileKey). Re-register the copy we kept; when there
// is none, or CoreText refuses it, fall back to Raleway rather than let
// Font.custom(<family>) silently render San Francisco everywhere.
if !isBuiltInFont(value.font) {
if let url = savedThemeFontURL() {
do {
try RwFonts.register(fileAt: url)
CSLog.shared.log("appearance", "re-registered theme font \(url.lastPathComponent)")
} catch {
CSLog.shared.log(
"appearance",
"theme font \(url.lastPathComponent) failed to register (\(error.localizedDescription)) "
+ "— falling back to Raleway")
value.font = RwFonts.raleway
save(value)
}
} else {
CSLog.shared.log(
"appearance",
"saved font \(value.font) has no theme font file on record — falling back to Raleway")
value.font = RwFonts.raleway
save(value)
}
}
CSLog.shared.log(
"appearance",
"loaded mode=\(value.themeMode.rawValue) accent=\(String(value.accent.argb32, radix: 16)) "
+ "radius=\(Int(value.radius)) density=\(value.density.rawValue) font=\(value.font) "
+ "palette=\(value.palette.isEmpty ? "derived" : "overridden")")
return RwAppearanceController(value)
}
static func save(_ value: RwAppearance) {
guard let json = encode(value) else { return }
UserDefaults.standard.set(json, forKey: prefKey)
// The widget's copy rides every save — load()'s own corrective saves
// included, so a squared radius or a Raleway fallback reaches it too.
publishToWidget(value)
// A built-in family (the panel's Raleway/System rows, or a reset) no
// longer needs the theme font file; forget it so a later launch never
// re-registers a stale one.
if isBuiltInFont(value.font) {
clearThemeFont()
}
}
// MARK: Widget (the App Group copy of the appearance — iOS only)
/// Hands the appearance to the home-screen widget: the SAME JSON as the pref
/// (`encode(_:)`), under the bridge's np_appearance key in the App Group
/// UserDefaults, then a WidgetCenter reload so a placed widget re-renders in
/// the new colors. The widget is a separate process that cannot read this
/// app's own UserDefaults (NowPlayingSnapshot's story), which is why the
/// pref alone never reached it.
///
/// The font crosses over only as a family NAME (the Codable keys have no
/// "fontFile" — `fontFileKey` and the ThemeFonts copy are this app's, and
/// stay here), and the widget runs it through widgetSafe() before theming:
/// System and the bundled Raleway pass through, anything else falls back to
/// Raleway. The library's contract (RwFonts.register(fileAt:), "Never from a
/// widget extension") is that on a device the WidgetKit render process
/// cannot use a font outside the widget's own bundle — a theme font would
/// take the whole widget down to a placeholder. So nothing font-shaped is
/// copied into the
/// group, and the widget decodes this string with a plain JSONDecoder rather
/// than RwAppearance.load(contentsOf:), which registers a theme's "fontFile"
/// as a side effect of loading.
///
/// Skipped when the group already holds this exact JSON, so the launch
/// publish (CrossSoundScene's .task) costs no write and no reload on a
/// routine start; a real change always differs. macOS has no widget: no-op.
static func publishToWidget(_ value: RwAppearance) {
#if os(iOS)
guard let json = encode(value) else { return }
// The watch app wears the same theme (the link de-dupes on its own).
Task { @MainActor in WatchLink.shared.setTheme(json) }
guard json != CrossSoundWidgetBridge.loadAppearanceJSON() else { return }
CrossSoundWidgetBridge.saveAppearanceJSON(json)
WidgetCenter.shared.reloadTimelines(ofKind: CrossSoundWidgetBridge.widgetKind)
CSLog.shared.log(
"appearance",
"published to widget: mode=\(value.themeMode.rawValue) "
+ "accent=\(String(value.accent.argb32, radix: 16)) "
+ "palette=\(value.palette.isEmpty ? "derived" : "overridden")")
#endif
}
// MARK: Theme fonts (the persisted half of a theme file's "fontFile")
/// Raleway (bundled by the library) and the system font need no file.
static func isBuiltInFont(_ font: String) -> Bool {
font == RwFonts.raleway || font == RwFonts.system
}
/// Application Support/ThemeFonts — not user-visible, survives updates.
static func themeFontsDirectory() -> URL {
let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
let dir = base.appendingPathComponent("ThemeFonts", isDirectory: true)
if !FileManager.default.fileExists(atPath: dir.path) {
try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
}
return dir
}
/// The kept copy of the last imported theme font, if the record names a
/// file that still exists.
static func savedThemeFontURL() -> URL? {
guard let name = UserDefaults.standard.string(forKey: fontFileKey), !name.isEmpty else {
return nil
}
let url = themeFontsDirectory().appendingPathComponent(name)
return FileManager.default.fileExists(atPath: url.path) ? url : nil
}
/// Copies a theme's font file into `themeFontsDirectory()` (replacing a same-
/// named copy) and records it under fontFileKey. The source is the path the
/// theme JSON named, resolved exactly as the library does (absolute, else
/// beside the theme file). Only called after the library already registered
/// the file successfully, so the copy failing is logged, not thrown.
private static func keepThemeFont(_ file: String, besideTheme themeURL: URL) {
let source: URL =
file.hasPrefix("/")
? URL(fileURLWithPath: file)
: themeURL.deletingLastPathComponent().appendingPathComponent(file)
let destination = themeFontsDirectory().appendingPathComponent(source.lastPathComponent)
let fm = FileManager.default
do {
if fm.fileExists(atPath: destination.path) {
try fm.removeItem(at: destination)
}
try fm.copyItem(at: source, to: destination)
UserDefaults.standard.set(source.lastPathComponent, forKey: fontFileKey)
CSLog.shared.log("appearance", "kept theme font \(source.lastPathComponent) for later launches")
} catch {
CSLog.shared.log(
"appearance",
"couldn't keep theme font \(source.lastPathComponent): \(error.localizedDescription) "
+ "— the font will not survive a relaunch")
clearThemeFont()
}
}
/// Forgets the kept theme font (record and file).
private static func clearThemeFont() {
let d = UserDefaults.standard
if let name = d.string(forKey: fontFileKey), !name.isEmpty {
try? FileManager.default.removeItem(at: themeFontsDirectory().appendingPathComponent(name))
}
d.removeObject(forKey: fontFileKey)
}
/// RwAppearance as JSON. [pretty] is for the clipboard export (Flutter used
/// `JsonEncoder.withIndent(' ')`); the pref itself stays compact.
static func encode(_ value: RwAppearance, pretty: Bool = false) -> String? {
let encoder = JSONEncoder()
if pretty { encoder.outputFormatting = [.prettyPrinted, .sortedKeys] }
guard let data = try? encoder.encode(value) else { return nil }
return String(decoding: data, as: UTF8.self)
}
/// JSON back to an RwAppearance — squared like every other way in (see
/// `squared(_:)`), which is what keeps a Flutter export's radius 6 out of
/// the clipboard import.
///
/// WHY [requireKeys] exists: RwAppearance's own decoder is deliberately
/// tolerant — it starts from the defaults and `try?`s every field, and even
/// swallows a missing keyed container — so `[]`, `42` and `{"hello":1}` all
/// decode "successfully" into the house defaults. That is right for loading a
/// corrupt pref (never strand the user on an unreadable theme, just show the
/// defaults), and wrong for a clipboard paste, where it would report "Theme
/// imported" after silently resetting everything. Import passes true.
static func decode(_ json: String, requireKeys: Bool = false) -> RwAppearance? {
decodeRaw(json, requireKeys: requireKeys).map { squared($0) }
}
/// The decode itself, radius as written. Private on purpose: only load()
/// wants the unsquared value, to notice a rounded pref and correct it.
private static func decodeRaw(_ json: String, requireKeys: Bool = false) -> RwAppearance? {
let data = Data(json.utf8)
if requireKeys {
guard let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
!jsonKeys.isDisjoint(with: object.keys)
else { return nil }
}
return try? JSONDecoder().decode(RwAppearance.self, from: data)
}
/// RedWhiteUI's "everything is square": the corner radius is not a user
/// setting in this app (RwSizes.radius == 0, and ThemesView never hands the
/// panel `.corners`), so whatever a pref, a pasted theme or a theme file
/// says, the radius is the library default. Every way an appearance enters
/// the app runs through here — load() alone looks at the value first, to log
/// and correct a rounded pref. Nothing else is touched: a theme's mode,
/// accent, density, font and palette overrides are exactly what themes are
/// FOR, and the library owns how they render.
static func squared(_ value: RwAppearance) -> RwAppearance {
var squared = value
squared.radius = Double(RwSizes.radius)
return squared
}
// MARK: Theme files
/// What `loadThemeFile(at:)` throws on top of the library's own
/// RwThemeError (an unreadable or unregisterable font file).
enum ThemeFileError: LocalizedError {
/// Valid JSON, but none of the theme keys — the file-import twin of
/// decode's requireKeys: the library decoder is as tolerant as ours, so
/// without this a picked `{"hello":1}` would report success after
/// silently resetting everything.
case notATheme(String)
var errorDescription: String? {
switch self {
case .notATheme(let name): "\(name) doesn't look like a theme file."
}
}
}
/// The theme-FILE import: a .json the user picked (ThemesView's
/// .fileImporter), read by the LIBRARY's loader so everything a theme can
/// say works — hex colors, the "palette" block overriding any token (with
/// its aliases: "primary", "background", "icons" …) and a "fontFile"
/// (.ttf/.otf, registered with CoreText; its family name becomes `font`).
/// Returns the appearance for the caller to apply: `controller.value = …`
/// is the whole apply, since CrossSoundScene's onChange re-themes the app
/// AND persists it through save(_:), exactly like a panel edit (an explicit
/// save(_:) after it is harmless).
///
/// Throws: a file that can't be read, one that isn't a theme
/// (ThemeFileError), or a font file CoreText rejected (RwThemeError) — all
/// with a user-facing localizedDescription. The JSON itself never throws;
/// malformed values fall back to the defaults, the saved pref's rule. The
/// security scope is taken here because a picked URL is outside the sandbox
/// until it is — balanced, so a caller already holding it is fine too.
static func loadThemeFile(at url: URL) throws -> RwAppearance {
let scoped = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
let data = try Data(contentsOf: url)
guard let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
!themeFileKeys.isDisjoint(with: object.keys)
else { throw ThemeFileError.notATheme(url.lastPathComponent) }
let value = try squared(RwAppearance.load(contentsOf: url))
// The library registered the "fontFile" for THIS process only; keep a copy
// so load() can register it again next launch (see fontFileKey). A theme
// without one switches to a built-in or already-known family, so any
// earlier theme's font file is no longer wanted.
if let file = object["fontFile"] as? String, !file.isEmpty, !isBuiltInFont(value.font) {
keepThemeFont(file, besideTheme: url)
} else if isBuiltInFont(value.font) {
clearThemeFont()
}
// (A theme naming a non-built-in family WITHOUT a fontFile keeps whatever
// file is on record — it may well be that family; load() re-validates.)
CSLog.shared.log(
"appearance",
"loaded theme file \(url.lastPathComponent): mode=\(value.themeMode.rawValue) "
+ "accent=\(String(value.accent.argb32, radix: 16)) font=\(value.font) "
+ "palette=\(value.palette.isEmpty ? "derived" : "overridden")")
return value
}
}
@MainActor
public struct AppRoot: View {
// The active RedWhiteUI palette (set by CrossSoundScene's .rwTheme() wrapper,
// which is one level ABOVE this view — see that type's doc comment).
@Environment(\.rw) private var p
/// Foreground return is the third resume path: a session-grabbing app that
/// never sends a resumable interruption "ended" gets reclaimed when we come
/// back to front (InterruptionGuard.appBecameActive).
@Environment(\.scenePhase) private var scenePhase
private enum Phase {
case loading
case notSignedIn
// No .failed: with stored credentials a getMe throw still mounts the
// shell (bootWarning banner instead — Flutter parity: a network hiccup
// on startup doesn't bounce the user), and without them the credentials
// guard lands on .notSignedIn first, so a fatal boot phase had nothing
// left to represent.
case ready
}
let platformName: String
@State private var engine: PlayerEngine
@State private var auth: AuthStore
@State private var api: SoundCloudAPI
@State private var harvester: SessionHarvester
@State private var queueController: QueueController
@State private var nowPlaying: NowPlayingCenter
@State private var interruptionGuard: InterruptionGuard
/// The same instances, wrapped once for the environment: screens under
/// AppShell read @Environment(AppServices.self) instead of taking
/// constructor parameters.
@State private var services: AppServices
/// Play-history context harvester (Dart: AppState._getPlayEventContext).
/// Not in AppServices on purpose: only the queue's ~10s record trigger
/// ever consumes it, through the closure wired in wireControlHooks.
@State private var playContext: PlayContextProvider
@State private var showLogin = false
/// PKCE still works but the V2 session needs a fresh WebView login
/// (the onV2SessionNeedsReauth hook) — soft banner, no logout.
@State private var needsReauth = false
@State private var phase: Phase = .loading
/// The last session is back (bootstrap got past restorePersistedState), so
/// a play command has something to play. A widget button can launch the
/// app and arrive before that.
@State private var sessionRestored = false
/// Brief, auto-dismissing play failure banner. The message itself comes from
/// queueController.lastError (resolve failures live with the DRM/clear
/// routing now, matching Flutter's `_restorePreviousTrack` + snackbar split);
/// only the show-for-4s presentation is this view's.
@State private var playError: String?
/// getMe failed on boot but credentials exist, so the shell mounted anyway
/// (offline cold start). Sticky until tapped (retry) or dismissed — unlike
/// playError it does NOT auto-hide, since it flags a degraded session.
@State private var bootWarning: String?
/// Volume shadow the loopback API reports and updates (Dart:
/// AppState._apiVolume): the snapshot's `volume` reflects ONLY what the
/// API's volume command set — default 1.0, never the engine's real level.
/// A reference box, so the two localAPI closures wired in wireControlHooks
/// share one live value (a captured Double copy would go stale).
@State private var apiVolume = APIVolumeShadow()
public init(platformName: String) {
self.platformName = platformName
// @State wrappers are seeded by hand because api needs the same AuthStore
// instance and the queue/interruption layers the same engine — default
// property values can't see their siblings.
let auth = AuthStore()
let engine = PlayerEngine()
let api = SoundCloudAPI(auth: auth)
_auth = State(initialValue: auth)
_api = State(initialValue: api)
_engine = State(initialValue: engine)
let queueController = QueueController(engine: engine, api: api)
_harvester = State(initialValue: SessionHarvester(auth: auth))
_playContext = State(initialValue: PlayContextProvider(auth: auth))
_queueController = State(initialValue: queueController)
_nowPlaying = State(initialValue: NowPlayingCenter())
_interruptionGuard = State(initialValue: InterruptionGuard(engine: engine))
_services = State(
initialValue: AppServices(auth: auth, api: api, engine: engine, queue: queueController))
}
@ObserveInjection var inject
public var body: some View {
Group {
VStack(spacing: 0) {
Group {
switch phase {
case .loading:
ProgressView()
// .color: ProgressView only honors the Color overload of .tint.
.tint(p.red.color)
.frame(maxWidth: .infinity, maxHeight: .infinity)
case .notSignedIn:
notSignedIn(p)
case .ready:
// The tabbed shell (and the mini player with it) reads everything
// it needs from the AppServices container in the environment.
AppShell()
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
if needsReauth {
Button {
showLogin = true
} label: {
// labelMedium (12.5/medium) carries the old 12/medium. The notice
// look (Outlined.swift): primary text, 2pt primary edge, no fill.
Text("Session expired — tap to sign in again")
.rw(.labelMedium)
.padding(.horizontal, RwSizes.gap)
.padding(.vertical, 6)
.frame(maxWidth: .infinity)
.noticeChrome()
}
.buttonStyle(.bareRow())
.transition(.move(edge: .bottom).combined(with: .opacity))
}
if let bootWarning {
// playError's notice look, split into two bare buttons in one strip:
// the message (tap = retry the whole bootstrap) and an X (dismiss).
HStack(spacing: 0) {
Button {
Task { await bootstrap() }
} label: {
Text("Couldn't refresh your account — tap to retry. (\(bootWarning))")
.rw(.labelMedium)
.padding(.horizontal, RwSizes.gap)
.padding(.vertical, 6)
.frame(maxWidth: .infinity)
.contentShape(Rectangle())
}
.buttonStyle(.bareRow())
Button {
withAnimation { self.bootWarning = nil }
} label: {
Image(systemName: "xmark")
.font(.system(size: 11, weight: .semibold))
.padding(.horizontal, RwSizes.gap)
.padding(.vertical, 6)
.contentShape(Rectangle())
}
.buttonStyle(.bareRow())
}
.noticeChrome()
.transition(.move(edge: .bottom).combined(with: .opacity))
}
if let playError {
Text(playError)
.rw(.labelMedium)
.padding(.horizontal, RwSizes.gap)
.padding(.vertical, 6)
.frame(maxWidth: .infinity)
.noticeChrome()
.transition(.move(edge: .bottom).combined(with: .opacity))
}
}
// No hand-set page background: the scene root's .rwTheme() owns it now.
.task {
wireControlHooks()
#if os(iOS)
// Widget transport buttons must work before the first track plays —
// the original registered its Darwin observers at app launch.
nowPlaying.activateWidgetObserversEarly()
#endif
await bootstrap()
// Loopback API for the desktop companions, started once after
// bootstrap like Dart's AppState init (fire-and-forget: a busy port —
// usually the Electron app serving the same API — is logged and
// skipped, never a failure). No-op off macOS.
services.localAPI.start()
}
.task { await nowPlayingPump() }
.onChange(of: queueController.lastError) { _, message in
// playTrack resets lastError to nil at the top of every attempt, so a
// repeat of the SAME failure still arrives as a fresh transition here.
if let message { showPlayError(message) }
}
.onChange(of: queueController.currentTrack?.id) { _, _ in
// A track change must stamp nowPlaying even while the paused pump is
// silent (adoption picks the newest peer BY updatedAt): auto-advance
// rides the playing pump anyway, but a paused skip/jump/restore/adopt
// lands only here.
services.remote.publishState(force: true)
services.remote.publishQueue()
}
.onChange(of: queueController.currentTrack?.isLiked) { _, _ in
// A like made here must reach the remotes' hearts even while paused,
// when the pump publishes nothing.
services.remote.publishState(force: true)
}
.onChange(of: scenePhase) { _, newPhase in
if newPhase == .active { interruptionGuard.appBecameActive() }
// Leaving the foreground may be the last chance before the app is
// closed: keep where you were (song, playhead, station).
if newPhase == .background { services.queue.persistNow() }
}
#if os(macOS)
// Best-effort presence teardown on quit — RemoteService.stop() marks
// this device offline; without it a quit Mac looks alive to peers
// until the prune. Best-effort on purpose: the process may die before
// the Task runs. iOS has no counterpart because termination there is
// rarely graceful, and the 2-day device prune + updatedAt tolerance
// cover a vanished device — matching the Dart app.
.onReceive(
NotificationCenter.default.publisher(
for: NSApplication.willTerminateNotification)
) { _ in
// Synchronously, first: the process may not live to run a Task.
services.queue.persistNow()
Task { await services.remote.stop() }
}
#endif
.sheet(isPresented: $showLogin) {
LoginSheet { token, clientId in
Task {
await auth.saveSession(token: token, clientId: clientId)
withAnimation { needsReauth = false }
await bootstrap()
}
} onAuthorizationCode: { code, verifier in
// Leg 2. Deliberately NOT fatal: the session is already saved by the
// time this runs, so a failure here leaves the app usable for reads
// and playback and only the v1 writes (like, repost) stay broken —
// which is exactly the state the app shipped in before this leg
// existed. Better degraded than bounced back to a login screen.
Task {
do {
try await auth.exchangePkceCode(code, verifier: verifier)
CSLog.shared.log("auth", "PKCE leg complete — v1 writes enabled")
} catch {
CSLog.shared.log("auth", "PKCE exchange FAILED: \(error) — likes/reposts will not work")
}
await bootstrap()
}
}
}
// Outermost so presented sheets inherit it too; every screen under
// AppShell reads the service container from here.
.environment(services)
// .rwTheme() is applied by CrossSoundScene ABOVE AppRoot, not here: a view
// cannot see environment values set by its own body modifiers, so applying
// it in this body left AppRoot's own chrome (banners, the signed-out
// screen) reading the default light palette forever. The scene root owns
// the RwAppearanceController for the same reason.
}
.enableInjection()
}
// MARK: - Bootstrap
private func bootstrap() async {
phase = .loading
#if os(iOS)
// A Live Activity outlives the process that started it, so a build from
// before the feature was removed can leave one frozen in the Dynamic
// Island with nothing in it. Nothing starts them any more; this clears
// whatever is left over.
await LiveActivityCleanup.endAll()
#endif
// A banner tap re-runs bootstrap; clear the old warning so success leaves
// no trace and a repeat failure re-animates in.
withAnimation { bootWarning = nil }
await auth.load()
#if os(iOS)
// The watch app signs in with this phone's login. After load(), never
// before: started on an empty store, the link would tell the watch the
// phone signed out. Once per process; a re-bootstrap is a no-op.
await WatchLink.shared.start(auth: auth)
#endif
// Recovery ladder (mirrors the Flutter AppState wiring): a 401 first tries
// the silent WebView re-capture; if PKCE keeps things alive but the V2
// session is gone, show the soft banner; only an unrecoverable failure
// drops to the signed-out screen.
await api.setHooks(
onSessionExpired: { [harvester] in await harvester.refreshSession() },
onAuthFailed: {
Task { @MainActor in withAnimation { phase = .notSignedIn } }
},
onV2SessionNeedsReauth: {
Task { @MainActor in withAnimation { needsReauth = true } }
})
// Restore the last session UNCONDITIONALLY (Flutter restores outside the
// credentials/getMe path): an offline cold start or a getMe hiccup still
// shows the last track paused at 0:00 in the mini player; the first play
// press lazy-loads the audio via togglePlay → playTrack. Guarded on
// currentTrack so a re-bootstrap (Retry, re-login) can't clobber a
// session that is already live.
if queueController.currentTrack == nil {
queueController.restorePersistedState()
}
sessionRestored = true
guard await auth.hasCredentials else {
CSLog.shared.log("approot", "no credentials — showing signed-out placeholder")
phase = .notSignedIn
return
}
do {
let me = try await api.getMe()
CSLog.shared.log("approot", "signed in as \(me.username)")
services.currentUser = me // shell avatar + anything else profile-shaped
#if os(iOS)
WatchLink.shared.setUserId(me.id) // the watch's remote namespace
#endif
// Cross-device remote: the SoundCloud uid is the RTDB namespace, so the
// service can only start HERE, once getMe names it (Dart: ensureRemote()
// right after getMe in tryAutoLogin). start() is a no-op when already
// started, so a re-bootstrap (retry banner, re-login) is safe; fired,
// not awaited, so a slow Firebase round-trip can't hold up boot.
Task { await services.remote.start(scUid: me.id) }
phase = .ready
} catch {
// Credentials exist (the guard above returned otherwise), so mount the
// shell anyway — Flutter parity: a network hiccup on startup doesn't
// bounce the user, and the restored session keeps the mini player
// usable offline. The failure surfaces as the tappable bootWarning
// banner instead of a blocking error screen.
CSLog.shared.log("approot", "getMe failed: \(error.localizedDescription)")
withAnimation { bootWarning = error.localizedDescription }
phase = .ready
}
}
// MARK: - Control plane (Now Playing commands + interruption hookup)
/// One-time hookup of the control plane around the queue: system remote
/// commands (media keys / Control Center / Lock Screen / CarPlay) route into
/// QueueController, and a manual pause tells the InterruptionGuard to drop
/// any pending auto-resume. Runs from .task, not init, so the closures are
/// bound to the @State-kept instances (an init re-run seeds fresh instances
/// that SwiftUI then discards).
private func wireControlHooks() {
// Log out (AppServices.signOut): straight back to the signed-out screen,
// the way an unrecoverable auth failure already gets there.
services.onSignedOut = {
withAnimation {
needsReauth = false
bootWarning = nil
phase = .notSignedIn
}
}
queueController.onUserPause = { [interruptionGuard] in
// onUserPause always fires from the controller's MainActor togglePlay;
// assumeIsolated keeps the flag-clear SYNCHRONOUS (a task hop could let
// an in-flight interruption notification see a stale pending-resume).
MainActor.assumeIsolated { interruptionGuard.userTookControl() }
}
// Play-history recording (Dart: AppState handing _getPlayEventContext
// into recordPlay): without this assignment the queue's ~10s record
// trigger finds no provider and silently never records a single play.
// Capture the instance, not self — the provider is lazy, so nothing
// runs until the first qualifying play's (once-per-process) harvest.
let playContext = self.playContext
queueController.playContextProvider = { await playContext.current() }
// Sync-adoption gate for EVERY play entry point (Dart gated inside
// AppState.togglePlay, so in-app buttons and API plays were covered
// too — a per-call-site check reached only the Now Playing commands):
// QueueController consults this before any not-playing → play, and true
// means the press was consumed by adopting a newer peer session.
queueController.onBeforeUserPlay = { await maybeAdoptOnPlay() }
// One body for every control surface. Async, so a caller that has to
// know when it is done (the widget's intents, below) can wait for it.
let run: @MainActor (RemoteCommand) async -> Void = { [queueController, services] command in
// Push a fresh snapshot immediately after acting (defer = every exit
// path): the 500ms pump alone leaves playbackState stale long enough
// for a quick second media-key press to resolve the WRONG toggle.
// The remote force-publish rides the same edge (Dart force-published
// after every handled command): the pump below is silent while
// paused, so a media-key pause must stamp nowPlaying HERE — once —
// or peers never see the paused frame.
defer {
pushNowPlaying()
services.remote.publishState(force: true)
}
switch command {
case .play:
// Explicitly play-when-not-playing, NOT toggle: surfaces can send a
// bare .play while we are already playing, and toggling would pause.
// Going through togglePlay (not engine.resume) keeps the restored-
// session lazy-load and the stall-watchdog restart.
// No adoption pre-check here anymore: togglePlay itself consults
// onBeforeUserPlay (wired above to maybeAdoptOnPlay), so this path
// shares ONE gate with the mini player and the loopback API.
if !queueController.isPlaying {
await queueController.togglePlay()
}
case .pause:
// Through the controller's pause path so onUserPause fires and a
// pending interruption auto-resume is dropped.
if queueController.isPlaying { await queueController.togglePlay() }
case .toggle:
// Adoption gate lives inside togglePlay (onBeforeUserPlay).
await queueController.togglePlay()
case .next:
await queueController.playNext()
case .prev:
await queueController.playPrev()
case .like:
await queueController.toggleLike()
case .seek(let ms):
queueController.seek(toMs: ms)
}
}
nowPlaying.onCommand = { command in
Task { @MainActor in await run(command) }
}
#if os(iOS)
// The home-screen widget's buttons. The system runs their intents in
// THIS process (TransportIntents) — waking the app when it is suspended,
// which is what a paused app is — and they come in through here.
WidgetCommandRelay.handler = { [queueController] command in
// Launched for the tap: the last session may not be back yet.
var waited = 0
while !sessionRestored && waited < 100 {
try? await Task.sleep(for: .milliseconds(100))
waited += 1
}
CSLog.shared.log("widget", "\(command.rawValue) from the widget")
switch command {
case .playPause: await run(queueController.isPlaying ? .pause : .play)
case .next: await run(.next)
case .prev: await run(.prev)
case .like: await run(.like)
}
}
#endif
#if os(macOS)
// Hand the live NowPlayingCenter up to the macOS app target's menu-bar
// layer: the status item lives ABOVE the Kit in the dependency graph,
// so it can never be named here, yet the instance it needs sits in this
// view's @State. MacAppDelegate planted itself in MacControlSurface
// before this scene mounted (applicationWillFinishLaunching) and does
// the actual wiring on its side — onState for the menu text, and menu
// commands back through the SAME nowPlaying.onCommand switch above.
MacControlSurface.registry?.registerControlServices(nowPlaying: nowPlaying)
#endif
// Loopback API for the desktop companions (Stream Deck / DockDoor / Game
// Bar) — Dart: AppState.startLocalApi's _apiSnapshot/_apiCommand. The
// server is transport-only; the byte-compatible payload is built HERE.
let apiVolume = self.apiVolume
services.localAPI.snapshotProvider = { [queueController, engine] in
// No current track → literally {} — companions key off the empty map,
// and /queue et al. then serve JSON nulls.
guard let track = queueController.currentTrack else { return [:] }
// shownPositionMs: a restored, not-yet-loaded song reports its saved spot.
let positionMs = queueController.shownPositionMs
// BUG-COMPATIBLE, deliberate: NO top-level numeric duration — the
// Electron payload never had one and companions parse durationStr.
// Queue entries DO carry numeric duration in ms (trackJSON).
return [
"isPlaying": queueController.isPlaying,
"isLiked": track.isLiked,
"title": track.title,
"artist": track.user.username,
"artwork": track.artworkUrl ?? "",
"position": positionMs / 1000,
"currentTimeStr": LocalAPIServer.clock(ms: positionMs),
"durationStr": LocalAPIServer.clock(ms: engine.durationMs),
"shuffle": queueController.shuffle,
"autoplay": queueController.autoplay,
// Hardcoded: no repeat mode exists yet, but companions may read it.
"repeat": "off",
"volume": apiVolume.value,
"queue": queueController.queue.map(LocalAPIServer.trackJSON),
"queueIndex": queueController.queueIndex,
]
}
services.localAPI.commandHandler = { [services, queueController, engine] action, args in
let ok = await Self.runAPICommand(
action: action, args: args, queueController: queueController, engine: engine,
apiVolume: apiVolume)
if ok {
// A command's effect hits /events immediately, like Dart's
// notifyListeners-driven broadcast — not on the next 500ms pump tick.
services.localAPI.broadcast()
}
return ok
}
// Cross-device remote (Phase 7) — RemoteService is transport-only (RTDB
// over REST+SSE), so the app layer supplies state and executes peer
// commands, the same split the localAPI wiring above uses. Dart's
// RemoteService(app) read AppState directly; here the providers close
// over the same @State-kept instances instead.
let remote = services.remote
remote.stateProvider = { [queueController, engine] in
guard let track = queueController.currentTrack else { return nil }
return RemoteNowPlaying(
trackId: track.id,
title: track.title,
artist: track.user.username,
artworkUrl: track.artworkUrl,
durationMs: engine.durationMs > 0 ? engine.durationMs : track.duration,
positionMs: queueController.shownPositionMs,
isPlaying: queueController.isPlaying,
isLiked: track.isLiked)
}
remote.queueProvider = { [queueController] in
// The PUBLISHED shape, not the raw queue: items capped at 60 with the
// FULL length in total (spec: trimmed = q.sublist(0, 60)) — peers
// render "Showing X of Y" from the difference, and adoptions resolve
// only the published items.
let q = queueController.queue
let items = q.prefix(60).map { t in
RemoteQueueItem(
trackId: t.id,
title: t.title,
artist: t.user.username,
artworkUrl: t.artworkUrlSmall ?? t.artworkUrl)
}
return RemoteQueueSnapshot(
index: queueController.queueIndex,
total: q.count,
items: Array(items))
}
remote.onCommand = { [services, queueController] message in
Task { @MainActor in
await Self.runRemoteCommand(
message, queueController: queueController, api: services.api)
// Reflect the new state promptly (Dart force-published after every
// inbound command) instead of waiting out the publish throttle —
// this is the sender's only ack channel.
services.remote.publishState(force: true)
services.remote.publishQueue()
}
}
// onDevices/onPeerState stay unwired: the Devices screen reads
// remote.devices through Observation, and the adoption decision reads
// remote.bestSyncPeer() at press time (the newer-than-me comparison needs
// myUpdatedAt, a server timestamp only the service holds).
}
// MARK: - Cross-device remote (Phase 7 wiring)
/// Dart RemoteService.maybeAdoptOnPlay(), relocated app-side — the service
/// owns the peer pick (bestSyncPeer: synced, has a session, newer than me
/// by SERVER time) and this owns the app-state gates, exactly the split its
/// doc names. Reached via QueueController.onBeforeUserPlay from EVERY
/// play entry point (UI, media keys, loopback API, remote peers) before
/// the toggle plays; true = the press was consumed by a sync handoff.
/// The spec's conditions, in order:
/// 1. my sync toggle off → false (it gates ONLY adoption, never publish);
/// 2. divergedFromSync → false — "this device is playing its own pick, so
/// resume that locally instead of hijacking to a peer's session";
/// 3. no candidate peer → false;
/// 4. else adopt fire-and-forget (Dart: unawaited adoptFrom) and swallow
/// the press.
private func maybeAdoptOnPlay() -> Bool {
let remote = services.remote
guard remote.syncEnabled else { return false }
guard !queueController.divergedFromSync else { return false }
guard let peer = remote.bestSyncPeer() else { return false }
Task {
await RemoteAdoption.adopt(
from: peer, remote: remote, queue: queueController, api: api)
}
return true
}
/// The inbound peer-command switch — Dart _onCommand's executor semantics.
/// play/pause are ABSOLUTE (state-guarded), NOT the loopback API's
/// all-three-toggle above: the service replays unconsumed commands after a
/// reconnect, and a replayed absolute is harmless where a toggle flips.
/// Index commands lean on QueueController's own bounds guards (removeAt
/// refuses the playing row, reorder validates both ends) — the same guards
/// the Dart receiver relied on.
private static func runRemoteCommand(
_ message: RemoteCommandMessage, queueController: QueueController,
api: SoundCloudAPI
) async {
let args = message.args
CSLog.shared.log("remote", "command \(message.cmd) args=\(args)")
switch message.cmd {
case "play":
if !queueController.isPlaying { await queueController.togglePlay() }
case "pause":
if queueController.isPlaying { await queueController.togglePlay() }
case "next":
await queueController.playNext()
case "prev":
await queueController.playPrev()
case "like":
// On this device's own login (the controller may have none — the watch
// remote holds only the uid). The args say which song and which state,
// so a double tap or a tap that lands on the next song changes nothing.
guard
RemoteService.likeCommandApplies(
args: args, currentTrackId: queueController.currentTrack?.id,
isLiked: queueController.currentTrack?.isLiked ?? false)
else { return }
await queueController.toggleLike()
case "seek":
queueController.seek(toMs: apiInt(args["ms"]) ?? 0)
case "jump":
let index = apiInt(args["index"]) ?? 0
guard index >= 0 && index < queueController.queue.count else { return }
await queueController.playQueueIndex(index)
case "removeAt":
queueController.removeQueueAt(apiInt(args["index"]) ?? -1)
case "reorder":
queueController.reorderQueue(
from: apiInt(args["from"]) ?? -1, to: apiInt(args["to"]) ?? -1)
case "clearQueue":
queueController.clearQueue()
case "enqueue":
// Dart _enqueueByIds: hydrate, keep the REQUESTED order (the batch
// endpoint returns a map), append — and addTracksToQueue itself starts
// playback when nothing is loaded yet.
let ids = (args["trackIds"] as? [Any])?.compactMap { raw -> String? in
(raw as? String) ?? (raw as? NSNumber)?.stringValue
} ?? []
guard !ids.isEmpty else { return }
let byId = await api.getTracksByIds(ids)
let tracks = ids.compactMap { byId[$0] }
guard !tracks.isEmpty else {
CSLog.shared.log("remote", "enqueue: 0 of \(ids.count) ids resolved")
return
}
await queueController.addTracksToQueue(tracks)
default:
CSLog.shared.log("remote", "unknown command \(message.cmd) — ignored")
}
}
private static func runAPICommand(
action: String, args: [String: Any], queueController: QueueController,
engine: PlayerEngine, apiVolume: APIVolumeShadow
) async -> Bool {
switch action {
case "playpause", "play", "pause":
// ALL THREE toggle — play/pause are NOT absolute (Electron/Dart
// parity; the Now Playing .play/.pause cases above are the absolute
// ones, this API's never were).
await queueController.togglePlay()
return true
case "next", "skip":
await queueController.playNext()
return true
case "prev", "previous":
await queueController.playPrev()
return true
case "like":
guard queueController.currentTrack != nil else { return false }
await queueController.toggleLike()
return true
case "shuffle":
queueController.toggleShuffle()
return true
case "autoplay":
await queueController.toggleAutoplay()
return true
case "seek":
// positionMs wins over ms (Dart parity), then "position" — which is
// what the DockDoor widget actually sends. Without that third key its
// scrub bar silently did nothing: the guard failed, the handler
// returned false, and the widget got a 400 it does not surface.
// Neither → false → 400.
guard let ms = AppRoot.apiInt(args["positionMs"], args["ms"], args["position"])
else { return false }
queueController.seek(toMs: ms)
return true
case "volume":
// value (Stream Deck sends {value}) wins over volume (Electron API
// shape); clamped, pushed to the engine AND remembered as the shadow
// the snapshot reports.
guard let raw = [args["value"], args["volume"]].compactMap({ $0 is NSNull ? nil : AppRoot.apiNumber($0) }).first
else { return false }
let v = min(max(raw, 0.0), 1.0)
engine.setVolume(v)
apiVolume.value = v
return true
case "play-index", "jump":
guard let index = AppRoot.apiInt(args["index"]) else { return false }
guard index >= 0 && index < queueController.queue.count else { return false }
await queueController.playQueueIndex(index)
return true
default:
// Unknown (or empty) action → false → HTTP 400 {"ok":false,...}.
return false
}
}
/// JSON numbers arrive as NSNumber whether the client sent an int or a
/// double; Dart's `is num` check excluded bools, so CFBoolean is rejected
/// here too (JSON true must not read as 1.0).
private static func apiNumber(_ value: Any?) -> Double? {
guard let n = value as? NSNumber, CFGetTypeID(n as CFTypeRef) != CFBooleanGetTypeID() else {
return nil
}
return n.doubleValue
}
/// First non-NSNull candidate → clamped Int. Two jobs in one helper:
/// JSONSerialization maps JSON null to NSNull (non-nil), so `a ?? b` never
/// falls through — Dart's jsonDecode produced real nulls and did. And
/// Swift's Int(Double) TRAPS out of range where Dart's toInt() clamps —
/// `{"positionMs":1e19}` from any loopback client must not kill the app.
private static func apiInt(_ candidates: Any?...) -> Int? {
for c in candidates where !(c is NSNull) {
guard let d = apiNumber(c) else { continue }
if d >= Double(Int.max) { return Int.max }
if d <= Double(Int.min) { return Int.min }
return Int(d)
}
return nil
}
/// Now Playing pump: pushes a full-state snapshot every 500ms while the view
/// lives. NowPlayingCenter.update's contract is "called on every position
/// tick and every state change"; a fixed 0.5s cadence — the same interval as
/// the engine's periodic time observer — covers both, reflecting any engine/
/// queue change within half a tick (the latency the Flutter channel had too)
/// without observation plumbing across engine AND queue. update() itself
/// dedupes the expensive part (artwork refetches only on URL change), so the
/// steady ticks are cheap. The loop dies with the view via .task
/// cancellation.
private func nowPlayingPump() async {
// Edge detector for the remote publish below: the playing → paused tick
// still publishes ONE final (forced) frame, then the device goes silent.
var remoteWasPlaying = false
while !Task.isCancelled {
pushNowPlaying()
// SSE riders get the same cadence: the Dart broadcast rode every
// notifyListeners; here the pump's 500ms tick pushes a frame and the
// server de-dupes byte-identical snapshots, so this is cheap.
services.localAPI.broadcast()
// Remote nowPlaying rides this tick ONLY while playing (Dart parity:
// publish on change + a playing-only heartbeat). An unconditional
// publish here rewrote nowPlaying.updatedAt every ~1s on a PAUSED
// device forever — hammering RTDB and poisoning adoption, whose
// newest-peer pick compares exactly that timestamp. The pause EDGE
// still publishes one forced frame so peers render the paused state
// before we go silent; other paused-state changes publish once via
// their own event edges (the onCommand force-publishes and the
// track-change onChange). No-op before start(), as before.
let playing = queueController.isPlaying
if playing || remoteWasPlaying {
services.remote.publishState(force: !playing)
}
remoteWasPlaying = playing
// The queue keeps every tick: its signature guard writes only on a
// real change, so a paused device stays silent unless the user
// actually edits the queue (Dart's on-change publish).
services.remote.publishQueue()
try? await Task.sleep(nanoseconds: 500_000_000)
}
}
private func pushNowPlaying() {
// Tuneshine LAN displays ride this same blind push — its publish() doc is
// explicit: "Call it blind from the app's 500ms Now Playing pump, exactly
// like NowPlayingCenter.update and localAPI.broadcast()". The per-track-id
// dedupe inside the service is what turns this cadence into ONE HTTP POST
// per track change, so there is nothing to throttle here.
//
// WHY it sits ABOVE the no-track guard: publish(track: nil) IS the stop
// edge — it blanks the displays (the service's improvement 2: Dart left a
// finished track on screen forever) — and the guard below returns before
// anything else runs. Riding the onCommand defer too is a bonus, not a
// problem: a media-key skip reaches the display immediately instead of up
// to half a tick later, and the dedupe swallows the repeat.
//
// Nothing to kick off at bootstrap: the singleton's init loads the prefs
// (enabled + saved devices), and discovery is one-shot and user-initiated
// from the Tuneshine screen's Scan button — there is no start()/background
// browse to arm here.
TuneshineService.shared.publish(
track: queueController.currentTrack, isPlaying: queueController.isPlaying)
// Scrobbling rides the same tick. It does its OWN timekeeping rather than
// trusting the pump's cadence — it accumulates only while playing, so a
// long pause never earns a scrobble.
LastFMService.shared.publish(
track: queueController.currentTrack,
isPlaying: queueController.isPlaying,
durationMs: engine.durationMs)
#if os(macOS)
// Rides the same 500ms full-state push as Tuneshine and the local API —
// blind cadence here, dedupe downstream. DiscordPresence drops an
// unchanged activity, which matters because Discord rate-limits updates.
// Above the no-track guard on purpose: publishing nil IS the stop edge,
// and it is what clears the presence.
DiscordPresence.shared.publish(
track: queueController.currentTrack,
isPlaying: queueController.isPlaying,
positionMs: engine.positionMs,
durationMs: engine.durationMs)
#endif
guard let track = queueController.currentTrack else { return }
nowPlaying.update(
title: track.title,
artist: track.user.username,
isPlaying: queueController.isPlaying,
// The restored song's saved spot and its own length until it loads, so
// the lock screen and the widget agree with the bar (2:46 / 4:35).
positionMs: queueController.shownPositionMs,
durationMs: engine.durationMs > 0 ? engine.durationMs : track.duration,
isLiked: track.isLiked,
artworkUrl: track.artworkUrl)
}
private func showPlayError(_ message: String) {
withAnimation { playError = message }
Task {
try? await Task.sleep(nanoseconds: 4_000_000_000)
withAnimation { if playError == message { playError = nil } }
}
}
// MARK: - Signed-out state (PlaceholderHomeView's language)
private func notSignedIn(_ p: RwPalette) -> some View {
VStack(alignment: .leading, spacing: RwSizes.gap) {
Spacer()
// displayMedium IS the old 40/heavy — the wordmark rides the library's
// type ramp now.
Text("CrossSound")
.rw(.displayMedium)
Text("Sign in with your SoundCloud account to get started.")
// The house button (page-colored, red hairline, inverted on press)
// replaces the old hand-rolled solid-red pill.
Button("Sign In to SoundCloud") { showLogin = true }
.buttonStyle(.bare)
Text("Native \(platformName)")
.rw(.bodySmall)
Spacer()
}
.padding(RwSizes.pagePadding)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
}
}
#if os(macOS)
// MARK: - macOS app-target bridge (menu bar)
/// What the macOS app layer implements to receive this scene's live
/// services (MacAppDelegate, which fans out to StatusBarController).
///
/// WHY a protocol + one static weak slot, and not a Kit-level closure hook
/// or NotificationCenter: the consumer sits in the app target above the
/// Kit, the services live in AppRoot's @State, and this seam keeps the
/// hand-off typed, single-registrant, and impossible to broadcast to the
/// wrong listener. NowPlayingCenter alone is handed over because both
/// directions already flow through it: state out via onState, commands in
/// via onCommand.
@MainActor
public protocol MacControlRegistry: AnyObject {
/// Called once per scene from AppRoot.wireControlHooks.
func registerControlServices(nowPlaying: NowPlayingCenter)
}
/// The slot the app target's delegate plants itself into at launch —
/// guaranteed filled before wireControlHooks runs, because a .task cannot
/// fire until the app finished launching. weak: the Kit must never keep
/// the app layer alive.
@MainActor
public enum MacControlSurface {
public static weak var registry: (any MacControlRegistry)?
}
#endif
/// Shared mutable box for the loopback API's volume shadow (Dart:
/// AppState._apiVolume). A class on purpose: the snapshot and command
/// closures both capture the SAME live value, and it survives AppRoot's
/// struct re-inits via @State. Updated only by the API's volume command.
@MainActor
final class APIVolumeShadow {
var value: Double = 1.0
}
// MARK: - Sync adoption (Phase 7)
/// Dart RemoteService.adoptFrom(), relocated to the app layer: the Swift
/// service is transport-only, and adoption needs the API (track hydration)
/// and the queue (adoptSession) — both app-side. Shared by the play-press
/// auto-adopt (AppRoot.maybeAdoptOnPlay) and the Devices screen's manual
/// "Resume here" button, which deliberately BYPASSES the divergedFromSync
/// gate (the spec: divergedFromSync gates auto-adopt only).
@MainActor
enum RemoteAdoption {
/// End-to-end handoff (the spec's adoptFrom steps, verbatim):
/// 1. ids = the peer's published queue (capped at its 60 published
/// items — never the full queue), else its single current track;
/// nothing → abort.
/// 2. Hydrate via the batch endpoint, keep the REQUESTED order; 0
/// resolved → abort.
/// 3. Index = the peer's current track id in the resolved list, else its
/// queueIndex clamped (the current track may be among the unresolved).
/// 4. adoptSession hands the position INTO the load (playTrack
/// startPositionMs + fromSync: true) — a post-play seek races the
/// loading stream and is dropped, the classic track-start bug class.
/// 5. Pause the source — "true handoff — stop the source".
static func adopt(
from device: RemoteDevice, remote: RemoteService, queue: QueueController,
api: SoundCloudAPI
) async {
let currentId = device.trackId
var ids = device.queue.compactMap(\.trackId)
if ids.isEmpty, let currentId, !currentId.isEmpty { ids = [currentId] }
guard !ids.isEmpty else {
CSLog.shared.log("remote", "adopt(\(device.id)): nothing to adopt")
return
}
let byId = await api.getTracksByIds(ids)
let tracks = ids.compactMap { byId[$0] }
guard !tracks.isEmpty else {
CSLog.shared.log(
"remote", "adopt(\(device.id)): 0 of \(ids.count) ids resolved")
return
}
var index =
currentId.flatMap { id in tracks.firstIndex { $0.id == id } } ?? -1
if index < 0 { index = min(max(device.queueIndex, 0), tracks.count - 1) }
CSLog.shared.log(
"remote",
"adopting from \(device.name): \(tracks.count) tracks, index \(index), "
+ "pos \(device.positionMs)ms")
await queue.adoptSession(
tracks: tracks, index: index, positionMs: device.positionMs)
// "True handoff — stop the source."
await remote.sendCommand(to: device.id, cmd: "pause", args: nil)
}
}