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

404 lines
17 KiB
Swift
Executable File

// MiniPlayerBar — the bottom transport strip while something is loaded.
//
// Reads PlayerEngine's @Observable state directly (position/duration tick every
// 0.5s from the periodic time observer), so there is no timer here. The track
// comes from QueueController (the engine deliberately knows nothing about
// SCTrack — it only speaks manifests and tokens), and every button routes
// through the controller rather than the engine: pause must fire onUserPause
// (drops any pending interruption auto-resume), play on a restored idle
// session must lazy-load via playTrack, and prev/next are queue moves — bare
// engine.pause()/resume() would do none of that.
//
// SCRUBBING — the port of Flutter's player_bar.dart → WaveformBar, its GESTURE
// semantics only. What is NOT ported is the waveform: WaveformBar painted the
// track's waveform_url envelope (1800 ints, peak-per-bucket, normalized by the
// loudest sample) in a 28pt-tall strip, and this bar draws a FLAT 2pt progress
// line instead. Deliberate, not an oversight — peaks need real vertical room,
// and this strip's whole height budget is a 2pt line inside a 10pt touch zone
// (see below); paying for a per-track waveform fetch to render it 2pt tall buys
// nothing. WaveformStore is the Kit's port of the same JSON loader + cache, and
// VisualizerView is where the envelope is actually drawn in this app.
// - The progress line is draggable. A drag PREVIEWS the position locally and
// commits exactly ONE seek on release; the line is never seeked per tick.
// The Dart comment names the bug that rule exists for: "Avoids hammering
// the player and the tug-of-war with the position stream that made the
// scrubber snap back on iOS."
// - Tap-to-seek and drag-to-seek are ONE DragGesture(minimumDistance: 0)
// here. Flutter needed a separate onTapUp because its drag has a minimum
// distance; a zero-distance drag already reports both, so there is no
// second handler that could double-seek at the start of a drag.
// - The strip's gesture area is 10pt tall around a 2pt line. A 2pt target is
// untouchable on a phone, and the 8pt of slop lives in vertical padding the
// content row already had (its top inset drops 8 → 2), so the bar grows by
// 2pt rather than 10. The line itself stays pinned to the bar's top edge.
// - The gesture is on a DESCENDANT of the bar, so it wins over AppShell's
// bar-wide onTapGesture (which opens the now-playing sheet) exactly the way
// the transport Buttons already do.
// - Scrubbing requires engine.durationMs > 0, i.e. a real loaded item. A
// restored session sits paused with NOTHING loaded while the bar still
// shows the track's own length (displayDurationMs), and seeking a nil
// AVPlayer would leave the line parked at a position nothing will reach.
//
// TrackDetailView's Slider is the other scrub surface and follows the same
// rules; the two deliberately share the 700ms post-release hold (see
// commitSeek).
import CrossSoundKit
import Inject
import RedWhiteUI
import SwiftUI
public struct MiniPlayerBar: View {
// The active RedWhiteUI palette (set once by AppRoot's .rwTheme()).
@Environment(\.rw) private var p
let engine: PlayerEngine
let controller: QueueController
/// Non-nil while a scrub is in flight (and for 700ms after release): the
/// position the USER is pointing at, 0...1. While it is set, the line and the
/// time readout both paint it and ignore the engine's ticks.
@State private var dragFraction: Double?
/// Queue button → the local up-next sheet (QueueView). Presented from HERE
/// rather than from AppShell so the button that opens it and the sheet that
/// shows it live in one file.
@State private var showQueue = false
/// macOS volume slider, 0...1. Seeded from the engine (which itself defaults
/// to 0.8, matching the Electron slider's default) and written straight back
/// through setVolume so the live player follows the drag.
@State private var volume: Double = 0.8
/// Persisted separately from the saved queue, exactly as the Electron
/// renderer does it: the slider position is a property of the INSTALL, not of
/// whatever track happened to be loaded, so it survives a queue that does not
/// restore.
private static let volumeKey = "cs_volume"
/// Where the mute toggle comes back to.
@State private var lastNonZeroVolume: Double = 0.8
#if os(iOS)
@Environment(\.horizontalSizeClass) private var sizeClass
#endif
/// An iPhone-width bar: shuffle / radio / autoplay fold into a ⋯ menu so the
/// row fits beside the cover and the title. The full player (tap the bar)
/// still shows them as buttons; a Mac and an iPad keep them here.
private var compact: Bool {
#if os(iOS)
sizeClass == .compact
#else
false
#endif
}
public init(engine: PlayerEngine, controller: QueueController) {
self.engine = engine
self.controller = controller
}
@ObserveInjection var inject
public var body: some View {
let track = controller.currentTrack
VStack(spacing: 0) {
scrubStrip(p)
// Tighter on an iPhone: every point between the cover and the controls
// is title.
HStack(spacing: compact ? 8 : RwSizes.gap) {
artwork(track)
VStack(alignment: .leading, spacing: 2) {
// titleSmall (14/bold) is the nearest role to the old 14/semibold;
// The role's primary red.
Text(track?.title ?? "—")
.rw(.titleSmall)
.lineLimit(1)
// On an iPhone the time rides on the artist line: beside the
// controls it left the title two letters and wrapped onto three
// lines (measured at 375 and 393pt).
HStack(spacing: 6) {
Text(track?.user.username ?? "")
.rw(.labelMedium, color: p.textMuted.color)
.lineLimit(1)
if compact { timeReadout }
}
}
Spacer(minLength: compact ? 0 : RwSizes.gap)
if !compact { timeReadout }
HStack(spacing: 2) {
// Narrower than the transport (28/13 vs 30/14): these three are
// secondary, and the bar already carries a title, a time readout and
// four buttons on a phone-width row. The heart leads, so shuffle sits
// to its right.
likeButton(track)
if compact {
RwMenu(PlayerModeControls.menuItems(controller: controller)) {
Image(systemName: "ellipsis")
.font(.system(size: 13, weight: .semibold))
}
.accessibilityLabel("Shuffle, radio and autoplay")
} else {
PlayerModeControls(
controller: controller, iconSize: 13, buttonWidth: 28, spacing: 0)
}
transportButton("backward.fill", size: 14, width: 30, palette: p) {
Task { await controller.playPrev() }
}
transportButton(
controller.isPlaying ? "pause.fill" : "play.fill", size: 18, width: 36, palette: p
) {
Task { await controller.togglePlay() }
}
transportButton("forward.fill", size: 14, width: 30, palette: p) {
Task { await controller.playNext() }
}
#if os(macOS)
volumeControl
#endif
// Up next. Same glyph the Devices screen uses for a peer's queue, and
// a Button here beats the shell's bar-wide onTapGesture (which opens
// the now-playing sheet) exactly like the transport buttons do.
transportButton("list.bullet", size: 14, width: 30, palette: p) {
showQueue = true
}
.help("Queue")
}
}
.padding(.horizontal, RwSizes.pagePadding)
// Top inset shrunk from 8 → 2: the scrub strip's 8pt of touch slop sits
// in exactly that space, so the whitespace above the content is unchanged
// and the bar is only 2pt taller than the display-only version.
.padding(.top, 2)
.padding(.bottom, 8)
}
.background(p.bg.color)
// QueueView takes no arguments: it reads the service container out of the
// environment, which AppRoot installs outermost precisely so presented
// sheets inherit it (DevicesView's RemoteQueueSheet rides the same rule).
// Detents match that sheet's so the two queue surfaces behave alike.
.sheet(isPresented: $showQueue) {
QueueView()
.presentationDetents([.medium, .large])
.presentationDragIndicator(.visible)
}
.enableInjection()
}
/// "0:03 / 4:35". Never wraps and never truncates: the artist name gives
/// way first.
private var timeReadout: some View {
Text("\(Self.mss(displayPositionMs)) / \(Self.mss(displayDurationMs))")
.font(.system(size: 11).monospacedDigit())
.foregroundStyle(dragFraction == nil ? p.textMuted : p.red)
.lineLimit(1)
.fixedSize()
}
// MARK: - Artwork and like
/// The playing track's cover with the 2pt hair edge every other artwork in
/// the app wears; the tinted note while it loads or when there is none
/// (TrackRow's rules).
private func artwork(_ track: SCTrack?) -> some View {
AsyncImage(url: track?.artworkUrlSmall.flatMap(URL.init(string:))) { image in
image.resizable().scaledToFill()
} placeholder: {
ZStack {
p.bg2.color
Image(systemName: "music.note")
.font(.system(size: 14))
.foregroundStyle(p.iconInactive)
}
}
.frame(width: 40, height: 40)
// scaledToFill overflows the frame without the clip; square like
// everything else.
.clipShape(Rectangle())
.rwBorder(.accent, width: 2)
}
/// Like / unlike the playing track: liked is the toggle's active state (the
/// hover colour, BareButtons.swift), at the mode controls' size. A Button,
/// so it wins the tap over the shell's bar-wide "open the player" gesture.
private func likeButton(_ track: SCTrack?) -> some View {
let liked = track?.isLiked == true
return Button {
Task { await controller.toggleLike() }
} label: {
LitPalette { p in
Image(systemName: liked ? "heart.fill" : "heart")
.font(.system(size: 13, weight: .semibold))
.foregroundStyle(p.red)
.frame(width: 28, height: 36)
.contentShape(Rectangle())
}
}
.buttonStyle(.bareRow(active: liked))
.disabled(track == nil)
.help(liked ? "Unlike" : "Like")
.accessibilityLabel(liked ? "Unlike" : "Like")
}
// MARK: - Scrubber
/// Full-bleed 2pt progress line pinned to the bar's top edge, inside a 10pt
/// gesture zone (see the header for why the slop goes downward).
private func scrubStrip(_ p: RwPalette) -> some View {
let seekable = engine.durationMs > 0
return GeometryReader { geo in
ZStack(alignment: .topLeading) {
// Unplayed track. Drawn, not a .background on the strip: the backing
// frame is 10pt tall now, and a 10pt hairline would be a visible bar.
Rectangle()
.fill(p.hair)
.frame(width: geo.size.width, height: 2)
Rectangle()
.fill(p.red)
.frame(width: geo.size.width * progressFraction, height: 2)
}
.frame(width: geo.size.width, height: geo.size.height, alignment: .topLeading)
// The slop is transparent, so it needs an explicit hit shape.
.contentShape(Rectangle())
// GestureMask.none (not an optional gesture — .gesture takes a Gesture)
// hands the touch back to AppShell's bar tap when nothing is loaded.
.gesture(scrubGesture(width: geo.size.width), including: seekable ? .all : .none)
}
.frame(height: 10)
}
private func scrubGesture(width: CGFloat) -> some Gesture {
DragGesture(minimumDistance: 0)
.onChanged { value in
dragFraction = Self.fraction(value.location.x, width: width)
}
.onEnded { value in
let target = Self.fraction(value.location.x, width: width)
dragFraction = target
commitSeek(target)
}
}
/// One seek per gesture, on release.
private func commitSeek(_ fraction: Double) {
let duration = displayDurationMs
guard duration > 0 else {
dragFraction = nil
return
}
let targetMs = Int((fraction * Double(duration)).rounded())
controller.seek(toMs: targetMs)
// HOLD the dragged value until the engine catches up. seek(toMs:) does not
// move positionMs synchronously, and AVPlayer's periodic observer keeps
// reporting the OLD position for up to one 0.5s tick — clearing now would
// snap the line backwards for half a second. The equality check means a
// NEWER drag's hold wins instead of this one clearing it out from under it.
// Explicit @MainActor: pins the delayed @State write to the view's actor
// instead of leaning on closure isolation inheritance.
Task { @MainActor in
try? await Task.sleep(nanoseconds: 700_000_000)
if dragFraction == fraction { dragFraction = nil }
}
}
private static func fraction(_ x: CGFloat, width: CGFloat) -> Double {
guard width > 0 else { return 0 }
return min(1, max(0, Double(x / width)))
}
// MARK: - Transport
private func transportButton(
_ systemName: String, size: CGFloat, width: CGFloat, palette p: RwPalette,
action: @escaping () -> Void
) -> some View {
Button(action: action) {
LitPalette { p in
Image(systemName: systemName)
.font(.system(size: size, weight: .semibold))
.foregroundStyle(p.red)
.frame(width: width, height: 36)
.contentShape(Rectangle())
}
}
.buttonStyle(.bareRow())
}
// MARK: - Derived state
/// Engine duration once an item is loaded; the track's own duration before
/// that. A restored session sits paused with NOTHING loaded (engine idle,
/// durationMs 0) — "0:00 / 0:00" would read broken, and the Flutter mini
/// player showed the track length there.
#if os(macOS)
/// Speaker glyph + slider, mirroring the Electron player bar's right-hand
/// cluster. macOS only on purpose: on iOS the hardware buttons and Control
/// Centre already own volume, and the bar is phone-width with four buttons
/// on it already.
private var volumeControl: some View {
HStack(spacing: 6) {
Image(systemName: volume == 0 ? "speaker.slash.fill" : "speaker.wave.2.fill")
.font(.system(size: 11))
// Icon chrome, so iconInactive — textMuted reads gray on a glyph.
.foregroundStyle(p.iconInactive)
// Click the glyph to mute, click again to come back. The restore
// target is the LAST NON-ZERO volume, so muting a quiet track does not
// resurrect it at full.
.onTapGesture {
if volume == 0 {
volume = lastNonZeroVolume
} else {
lastNonZeroVolume = volume
volume = 0
}
applyVolume()
}
.help(volume == 0 ? "Unmute" : "Mute")
RwSlider(value: $volume, in: 0...1)
.frame(width: 90)
.onChange(of: volume) { _, _ in applyVolume() }
.help("Volume")
}
.task {
// Seed from whatever the engine already has — the local API
// (Stream Deck / DockDoor) can have set it before this bar appeared.
let stored = UserDefaults.standard.object(forKey: Self.volumeKey) as? Double
volume = stored ?? engine.volume
if volume > 0 { lastNonZeroVolume = volume }
engine.setVolume(volume)
}
}
private func applyVolume() {
engine.setVolume(volume)
if volume > 0 { lastNonZeroVolume = volume }
UserDefaults.standard.set(volume, forKey: Self.volumeKey)
}
#endif
private var displayDurationMs: Int {
engine.durationMs > 0 ? engine.durationMs : (controller.currentTrack?.duration ?? 0)
}
/// The dragged position while scrubbing, else the engine's. Freezing the
/// readout with the line is what stops the two disagreeing mid-drag (and it's
/// the only place a scrubbed timestamp is legible — there is no bubble).
private var displayPositionMs: Int {
if let dragFraction {
return Int((dragFraction * Double(displayDurationMs)).rounded())
}
return controller.shownPositionMs
}
private var progressFraction: CGFloat {
if let dragFraction { return CGFloat(dragFraction) }
guard displayDurationMs > 0 else { return 0 }
return min(1, CGFloat(controller.shownPositionMs) / CGFloat(displayDurationMs))
}
/// m:ss — matches the Flutter mini player (no hour bucket; SoundCloud tracks
/// over an hour still read fine as e.g. 72:05).
private static func mss(_ ms: Int) -> String {
let totalSeconds = max(0, ms / 1000)
return String(format: "%d:%02d", totalSeconds / 60, totalSeconds % 60)
}
}