Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
342 lines
13 KiB
Swift
Executable File
342 lines
13 KiB
Swift
Executable File
// CrossSoundNowPlayingWidget.swift — CrossSoundWidget extension target ONLY.
|
|
//
|
|
// Ported from CrossSound-Flutter ios/CrossSoundWidget/CrossSoundNowPlayingWidget.swift.
|
|
// The shared app<->widget types (NowPlayingSnapshot, CrossSoundWidgetBridge, the
|
|
// transport AppIntents) now come from the CrossSoundBridge SPM module instead of
|
|
// dual-target source membership; everything else is lifted as-is.
|
|
//
|
|
// Home-screen now-playing widget, small + medium.
|
|
//
|
|
// Look: a flat page-coloured tile, everything square (the Flutter port's blurred
|
|
// art + material pane never made it into this file). Icons are outline SF Symbols
|
|
// (the non-.fill variants) and the type is Raleway via RedWhiteUI — the library's
|
|
// bundled Raleway is the ONE font a widget may use; see `appearance()` below.
|
|
//
|
|
// Colour follows the app's own theme: AppRoot mirrors its RwAppearance JSON into
|
|
// the App Group under `np_appearance` (CrossSoundWidgetBridge.appearanceKey) and
|
|
// reloads this timeline, so a new accent, mode or theme file shows up on the next
|
|
// render. The legacy np_themeBase / np_accent keys stay for the Flutter contract
|
|
// and are not read here.
|
|
//
|
|
// Everything is read from the App Group, so the widget renders correctly even
|
|
// when the app process is gone.
|
|
|
|
import AppIntents
|
|
import CrossSoundBridge
|
|
import RedWhiteUI
|
|
import SwiftUI
|
|
import UIKit
|
|
import WidgetKit
|
|
|
|
// MARK: - Timeline
|
|
|
|
struct NowPlayingEntry: TimelineEntry {
|
|
let date: Date
|
|
let snapshot: NowPlayingSnapshot
|
|
let artwork: UIImage?
|
|
/// The app's theme, for `.rwTheme` at the widget root. Font already pinned.
|
|
let appearance: RwAppearance
|
|
}
|
|
|
|
struct NowPlayingProvider: TimelineProvider {
|
|
private func current() -> NowPlayingEntry {
|
|
let snapshot = NowPlayingSnapshot.load()
|
|
var image: UIImage?
|
|
if let url = CrossSoundWidgetBridge.artworkFile,
|
|
let data = try? Data(contentsOf: url) {
|
|
image = UIImage(data: data)
|
|
}
|
|
return NowPlayingEntry(
|
|
date: Date(), snapshot: snapshot, artwork: image, appearance: Self.appearance())
|
|
}
|
|
|
|
/// The app's appearance from the JSON AppRoot mirrors into the App Group, or
|
|
/// the library defaults (red on white, system mode) when nothing has been
|
|
/// published yet or the blob does not parse.
|
|
///
|
|
/// Plain JSONDecoder on purpose — NEVER `RwAppearance.load(contentsOf:)` /
|
|
/// `init(themeData:)`, and never `RwFonts.register(fileAt:)`. Those register a
|
|
/// theme's "fontFile" with CoreText as a side effect of loading, and on a
|
|
/// device the WidgetKit render process cannot use a font outside the widget's
|
|
/// own bundle: the whole widget drops to a placeholder, colours included. The
|
|
/// Codable JSON has no fontFile key, so decoding it registers nothing.
|
|
/// widgetSafe() then keeps the user's font when the widget can render it
|
|
/// (System default, the bundled Raleway) and swaps only a theme font the
|
|
/// widget's bundle doesn't hold for Raleway. Mode, accent and palette
|
|
/// overrides are kept as published.
|
|
private static func appearance() -> RwAppearance {
|
|
let appearance = CrossSoundWidgetBridge.loadAppearanceJSON()
|
|
.flatMap { try? JSONDecoder().decode(RwAppearance.self, from: Data($0.utf8)) }
|
|
?? RwAppearance()
|
|
return appearance.widgetSafe()
|
|
}
|
|
|
|
/// Themed too: the gallery preview and redacted states should not flash the
|
|
/// stock red-on-white over a widget the user has recoloured.
|
|
func placeholder(in context: Context) -> NowPlayingEntry {
|
|
NowPlayingEntry(
|
|
date: Date(), snapshot: NowPlayingSnapshot(), artwork: nil, appearance: Self.appearance())
|
|
}
|
|
|
|
func getSnapshot(in context: Context, completion: @escaping (NowPlayingEntry) -> Void) {
|
|
completion(current())
|
|
}
|
|
|
|
/// Refreshes are pushed by the app (WidgetCenter.reloadTimelines) whenever the
|
|
/// track changes. The hourly entry is only a backstop so a widget left stale by
|
|
/// a missed reload eventually corrects itself.
|
|
func getTimeline(in context: Context, completion: @escaping (Timeline<NowPlayingEntry>) -> Void) {
|
|
let entry = current()
|
|
completion(Timeline(entries: [entry], policy: .after(Date().addingTimeInterval(3600))))
|
|
}
|
|
}
|
|
|
|
// MARK: - Widget
|
|
|
|
struct CrossSoundNowPlayingWidget: Widget {
|
|
var body: some WidgetConfiguration {
|
|
StaticConfiguration(
|
|
kind: CrossSoundWidgetBridge.widgetKind,
|
|
provider: NowPlayingProvider()
|
|
) { entry in
|
|
// The theme root: palette and Raleway into the environment for everything
|
|
// below (`@Environment(\.rw)`). `.rwTheme` picks light or dark from the
|
|
// colorScheme it finds and asks the host to switch via
|
|
// .preferredColorScheme — which a window honours and the WidgetKit host
|
|
// does not — so a mode forced in the app is written into the environment
|
|
// above it here. `.system` leaves the home screen's scheme alone.
|
|
NowPlayingView(entry: entry)
|
|
.modifier(WidgetTextPrimary())
|
|
.rwTheme(entry.appearance)
|
|
.transformEnvironment(\.colorScheme) { scheme in
|
|
if let forced = entry.appearance.themeMode.colorScheme { scheme = forced }
|
|
}
|
|
}
|
|
.configurationDisplayName("Now Playing")
|
|
.description("What's playing on CrossSound, with controls.")
|
|
.supportedFamilies([.systemSmall, .systemMedium])
|
|
}
|
|
}
|
|
|
|
// MARK: - View
|
|
|
|
struct NowPlayingView: View {
|
|
@Environment(\.widgetFamily) private var family
|
|
/// The active RedWhiteUI palette, light or dark, set by `.rwTheme` at the root.
|
|
/// Tokens only, never literals: `red` is the accent (progress fill, liked
|
|
/// heart), `text` the titles and live controls, `iconInactive` the one idle
|
|
/// icon, `hair` the hairlines and progress track — the same mapping the app's
|
|
/// own SquareProgressBar uses, so the two read as one product.
|
|
@Environment(\.rw) private var p
|
|
let entry: NowPlayingEntry
|
|
|
|
private var s: NowPlayingSnapshot { entry.snapshot }
|
|
|
|
var body: some View {
|
|
Group {
|
|
if family == .systemSmall { small } else { medium }
|
|
}
|
|
.containerBackground(for: .widget) { background }
|
|
}
|
|
|
|
/// The theme's page colour, flat. No artwork, no material, no scrim.
|
|
///
|
|
/// This one view IS the entire background: `.containerBackground(for: .widget)`
|
|
/// above takes whatever this returns and paints it edge to edge behind the
|
|
/// content. A bare Color expands to fill all offered space, so nothing else is
|
|
/// needed.
|
|
@ViewBuilder private var background: some View {
|
|
p.bg.color
|
|
}
|
|
|
|
// MARK: Small
|
|
|
|
@ViewBuilder private var small: some View {
|
|
VStack(spacing: 8) {
|
|
if let art = entry.artwork {
|
|
Image(uiImage: art)
|
|
.resizable()
|
|
.scaledToFill()
|
|
.frame(width: 54, height: 54)
|
|
.clipped()
|
|
// The app's artwork edge: 2pt, the primary.
|
|
.rwBorder(.accent, width: 2)
|
|
} else {
|
|
Rectangle()
|
|
.strokeBorder(p.hair.color, lineWidth: 1)
|
|
.frame(width: 54, height: 54)
|
|
.overlay(Image(systemName: "music.note").font(.system(size: 20)).foregroundStyle(p.iconInactive.color))
|
|
}
|
|
|
|
Text(s.hasTrack ? s.title : "Nothing playing")
|
|
.rw(.titleSmall)
|
|
.lineLimit(1)
|
|
|
|
transportButton(
|
|
systemName: s.isPlaying ? "pause" : "play",
|
|
size: 20,
|
|
intent: PlayPauseIntent())
|
|
}
|
|
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
|
}
|
|
|
|
// MARK: Medium
|
|
|
|
@ViewBuilder private var medium: some View {
|
|
VStack(alignment: .leading, spacing: 8) {
|
|
HStack(spacing: 12) {
|
|
if let art = entry.artwork {
|
|
Image(uiImage: art)
|
|
.resizable()
|
|
.scaledToFill()
|
|
.frame(width: 52, height: 52)
|
|
.clipped()
|
|
// The app's artwork edge: 2pt, the primary.
|
|
.rwBorder(.accent, width: 2)
|
|
} else {
|
|
Rectangle()
|
|
.strokeBorder(p.hair.color, lineWidth: 1)
|
|
.frame(width: 52, height: 52)
|
|
.overlay(Image(systemName: "music.note").font(.system(size: 18)).foregroundStyle(p.iconInactive.color))
|
|
}
|
|
|
|
VStack(alignment: .leading, spacing: 2) {
|
|
Text(s.hasTrack ? s.title : "Nothing playing")
|
|
.rw(.titleMedium)
|
|
.lineLimit(1)
|
|
// bodySmall's muted role colour is primary here (WidgetTextPrimary).
|
|
Text(s.hasTrack ? s.artist : "Tap to open CrossSound")
|
|
.rw(.bodySmall)
|
|
.lineLimit(1)
|
|
}
|
|
Spacer(minLength: 0)
|
|
}
|
|
|
|
progress
|
|
|
|
HStack(spacing: 0) {
|
|
transportButton(systemName: "backward.end", size: 15, intent: PreviousTrackIntent())
|
|
.frame(maxWidth: .infinity)
|
|
transportButton(
|
|
systemName: s.isPlaying ? "pause" : "play", size: 19, intent: PlayPauseIntent())
|
|
.frame(maxWidth: .infinity)
|
|
transportButton(systemName: "forward.end", size: 15, intent: NextTrackIntent())
|
|
.frame(maxWidth: .infinity)
|
|
transportButton(
|
|
systemName: s.isLiked ? "heart.fill" : "heart",
|
|
size: 15,
|
|
intent: ToggleLikeIntent(),
|
|
tint: s.isLiked ? p.red.color : p.text.color)
|
|
.frame(maxWidth: .infinity)
|
|
}
|
|
}
|
|
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
|
|
}
|
|
|
|
// MARK: Pieces
|
|
|
|
/// While playing we hand WidgetKit a timer interval so the bar AND the
|
|
/// elapsed time advance on their own — no timeline reloads needed to move
|
|
/// them (the app deliberately doesn't send any: reloads are budgeted).
|
|
///
|
|
/// That live bar is the one thing here that is not square: WidgetKit only
|
|
/// animates the system `.linear` style, which has round caps, and a custom
|
|
/// ProgressViewStyle would freeze it at the rendered value. Kept for the
|
|
/// behaviour; the paused bar below is the square two-Rectangle one.
|
|
@ViewBuilder private var progress: some View {
|
|
VStack(spacing: 3) {
|
|
if let playing = playingInterval {
|
|
ProgressView(timerInterval: playing,
|
|
countsDown: false) { EmptyView() } currentValueLabel: { EmptyView() }
|
|
.progressViewStyle(.linear)
|
|
.tint(p.red.color)
|
|
} else {
|
|
GeometryReader { geo in
|
|
ZStack(alignment: .leading) {
|
|
Rectangle().fill(p.hair.color)
|
|
Rectangle().fill(p.red.color).frame(width: geo.size.width * s.fractionElapsed)
|
|
}
|
|
}
|
|
.frame(height: 3)
|
|
}
|
|
|
|
// labelMedium: muted by default, like the artist line.
|
|
HStack {
|
|
if let playing = playingInterval {
|
|
// Counts up live, in step with the bar above.
|
|
Text(timerInterval: playing, countsDown: false).rw(.labelMedium)
|
|
} else {
|
|
Text(Self.time(s.position)).rw(.labelMedium)
|
|
}
|
|
Spacer()
|
|
Text(Self.time(s.duration)).rw(.labelMedium)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The track's span in wall-clock time while it plays, or nil when paused
|
|
/// or the duration is unknown. Anchored to when the app SAMPLED the position
|
|
/// (positionAt), not to entry.date: WidgetKit may rebuild the timeline long
|
|
/// after the write (budgeted reloads, the hourly backstop), and anchoring on
|
|
/// the rebuild time would restart the clock from a stale position. Flutter-
|
|
/// written snapshots carry no positionAt (0), so they fall back to the entry.
|
|
private var playingInterval: ClosedRange<Date>? {
|
|
guard s.isPlaying, s.duration > 0 else { return nil }
|
|
let sampledAt = s.positionAt > 0
|
|
? Date(timeIntervalSince1970: s.positionAt) : entry.date
|
|
let start = sampledAt.addingTimeInterval(-s.position)
|
|
return start...start.addingTimeInterval(s.duration)
|
|
}
|
|
|
|
/// Interactive when there is something to control; otherwise a tap just
|
|
/// opens the app, like anywhere else on the tile. The intents run in the
|
|
/// app's process (TransportIntents), so they work on a paused app too.
|
|
@ViewBuilder private func transportButton(
|
|
systemName: String,
|
|
size: CGFloat,
|
|
intent: some AppIntent,
|
|
tint: Color? = nil
|
|
) -> some View {
|
|
let icon = Image(systemName: systemName)
|
|
.font(.system(size: size, weight: .regular))
|
|
.foregroundStyle(tint ?? p.text.color)
|
|
|
|
if s.hasTrack {
|
|
// The button is its whole share of the row, not just the glyph: a tap
|
|
// that misses a button lands on the tile and opens the app instead.
|
|
Button(intent: intent) {
|
|
icon
|
|
.frame(maxWidth: .infinity, minHeight: 30)
|
|
.contentShape(Rectangle())
|
|
}
|
|
.buttonStyle(.plain)
|
|
} else {
|
|
icon
|
|
}
|
|
}
|
|
|
|
private static func time(_ seconds: TimeInterval) -> String {
|
|
guard seconds.isFinite, seconds > 0 else { return "0:00" }
|
|
let total = Int(seconds)
|
|
let h = total / 3600, m = (total % 3600) / 60, sec = total % 60
|
|
return h > 0
|
|
? String(format: "%d:%02d:%02d", h, m, sec)
|
|
: String(format: "%d:%02d", m, sec)
|
|
}
|
|
}
|
|
|
|
/// All text primary, as in the app (CrossSoundUI's CrossSoundLook, which the
|
|
/// widget cannot reach): every text token takes the primary colour. Inside
|
|
/// `.rwTheme`, because the closest `.environment` wins.
|
|
private struct WidgetTextPrimary: ViewModifier {
|
|
@Environment(\.rw) private var p
|
|
|
|
func body(content: Content) -> some View {
|
|
var q = p
|
|
q.text = p.red
|
|
q.textMuted = p.red
|
|
q.contentText = p.red
|
|
return content.environment(\.rw, q)
|
|
}
|
|
}
|