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

346 lines
11 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// CrossSound Remote's widgets — one device each: what it's playing, with
// ‹ ⏯ › that work from the Smart Stack.
//
// watchOS has no widget settings screen: a configurable widget is chosen
// from its recommendations in the gallery, so every known device is offered
// there by name (plus "Now Playing", which follows whichever device is
// playing). The list comes from the App Group (RemoteAppGroup), which the
// Remote app keeps current; each timeline also reads the devices fresh over
// REST, and the buttons send their command the same way (RemoteREST) — a
// widget can't hold the stream the apps listen on.
import AppIntents
import CrossSoundKit
import RedWhiteUI
import SwiftUI
import WidgetKit
@main
struct RemoteWidgets: WidgetBundle {
var body: some Widget {
DeviceWidget()
}
}
struct DeviceWidget: Widget {
var body: some WidgetConfiguration {
AppIntentConfiguration(
kind: "fi.RedLintu16.CrossSound.remote.device",
intent: SelectDeviceIntent.self,
provider: DeviceProvider()
) { entry in
DeviceWidgetView(entry: entry)
.rwTheme(entry.appearance)
}
.configurationDisplayName("CrossSound Remote")
.description("What a device is playing, with its controls.")
.supportedFamilies([.accessoryRectangular, .accessoryCircular, .accessoryInline, .accessoryCorner])
}
}
// MARK: - Configuration
struct SelectDeviceIntent: WidgetConfigurationIntent {
static var title: LocalizedStringResource = "Device"
static var description = IntentDescription("The device this widget shows and controls.")
/// nil = "Now Playing": whichever device is playing.
@Parameter(title: "Device")
var device: DeviceEntity?
init() {}
init(device: DeviceEntity?) {
self.device = device
}
}
struct DeviceEntity: AppEntity {
static var typeDisplayRepresentation: TypeDisplayRepresentation = "Device"
static var defaultQuery = DeviceQuery()
let id: String
let name: String
var displayRepresentation: DisplayRepresentation { DisplayRepresentation(title: "\(name)") }
}
struct DeviceQuery: EntityQuery {
func entities(for identifiers: [String]) async throws -> [DeviceEntity] {
let known = RemoteAppGroup.devices
return identifiers.map { id in
DeviceEntity(id: id, name: known.first { $0.id == id }?.name ?? "Device")
}
}
func suggestedEntities() async throws -> [DeviceEntity] {
RemoteAppGroup.devices.map { DeviceEntity(id: $0.id, name: $0.name) }
}
}
// MARK: - Buttons
/// ‹ ⏯ ›: one command to one device. WidgetKit reloads the timeline when
/// this returns, so it waits a moment for the device to publish its new
/// state first.
struct RemoteCommandIntent: AppIntent {
static var title: LocalizedStringResource = "Control a CrossSound device"
static var isDiscoverable = false
@Parameter(title: "Device")
var deviceId: String
@Parameter(title: "Command")
var command: String
init() {}
init(deviceId: String, command: String) {
self.deviceId = deviceId
self.command = command
}
func perform() async throws -> some IntentResult {
guard let userId = RemoteAppGroup.userId else { return .result() }
try await RemoteREST.send(command, to: deviceId, userId: userId, from: "watch-widget")
try? await Task.sleep(for: .milliseconds(1500))
return .result()
}
}
// MARK: - Timeline
struct DeviceEntry: TimelineEntry {
let date: Date
/// The device to show; nil = it's offline / unknown, or nothing plays.
let device: RemoteDevice?
/// The configured device's name, for "<name> is offline".
let configuredName: String?
/// CrossSound on this watch has shared an account.
let isSetUp: Bool
let appearance: RwAppearance
static let sample = DeviceEntry(
date: .now,
device: RemoteDevice(
id: "sample", name: "MacBook", platform: "desktop", online: true, syncEnabled: false,
lastSeenMs: 0, trackId: nil, title: "Midnight Drive", artist: "Neon Coast", artworkUrl: nil,
positionMs: 60_000, durationMs: 200_000, isPlaying: true, updatedAt: 0, queue: [],
queueIndex: 0, queueTotal: 0),
configuredName: nil, isSetUp: true, appearance: RwAppearance())
}
struct DeviceProvider: AppIntentTimelineProvider {
func placeholder(in context: Context) -> DeviceEntry { .sample }
func snapshot(for configuration: SelectDeviceIntent, in context: Context) async -> DeviceEntry {
context.isPreview ? .sample : await entry(for: configuration)
}
func timeline(for configuration: SelectDeviceIntent, in context: Context) async
-> Timeline<DeviceEntry>
{
let entry = await entry(for: configuration)
// Sooner while it plays: the song moves on. (The Remote app also reloads
// every widget whenever it sees a change.)
let minutes: Double = entry.device?.isPlaying == true ? 5 : 20
return Timeline(entries: [entry], policy: .after(.now.addingTimeInterval(minutes * 60)))
}
/// The gallery's choices: "Now Playing", then every device by name.
func recommendations() -> [AppIntentRecommendation<SelectDeviceIntent>] {
var list = [
AppIntentRecommendation(intent: SelectDeviceIntent(device: nil), description: Text("Now Playing"))
]
for device in RemoteAppGroup.devices.prefix(10) {
list.append(
AppIntentRecommendation(
intent: SelectDeviceIntent(device: DeviceEntity(id: device.id, name: device.name)),
description: Text(device.name)))
}
return list
}
private func entry(for configuration: SelectDeviceIntent) async -> DeviceEntry {
let appearance = theme()
guard let userId = RemoteAppGroup.userId else {
return DeviceEntry(
date: .now, device: nil, configuredName: nil, isSetUp: false, appearance: appearance)
}
var devices = RemoteAppGroup.devices
if let live = try? await RemoteREST.devices(userId: userId) {
devices = live
RemoteAppGroup.saveDevices(live)
}
let device: RemoteDevice?
if let id = configuration.device?.id {
device = devices.first { $0.id == id }
} else {
// Now Playing: the playing device that reported last, else the online
// one that did.
device = devices.filter(\.online).max { a, b in
(a.isPlaying ? 1 : 0, a.updatedAt) < (b.isPlaying ? 1 : 0, b.updatedAt)
}
}
return DeviceEntry(
date: .now, device: device, configuredName: configuration.device?.name, isSetUp: true,
appearance: appearance)
}
/// The phone's theme, as CrossSound on this watch received it.
private func theme() -> RwAppearance {
guard let json = RemoteAppGroup.themeJSON,
let value = try? JSONDecoder().decode(RwAppearance.self, from: Data(json.utf8))
else { return RwAppearance() }
return value.widgetSafe()
}
}
// MARK: - Views
struct DeviceWidgetView: View {
@Environment(\.widgetFamily) private var family
@Environment(\.rw) private var p
let entry: DeviceEntry
var body: some View {
let q = p.crossSound
Group {
switch family {
case .accessoryCircular: DeviceCircular(entry: entry)
case .accessoryInline: DeviceInline(entry: entry)
case .accessoryCorner: DeviceCorner(entry: entry)
default: DeviceRectangular(entry: entry)
}
}
.foregroundStyle(q.red.color)
.environment(\.rw, q)
.containerBackground(for: .widget) { q.bg.color }
.widgetURL(entry.device.map { URL(string: "csremote://device/\($0.id)") } ?? nil)
}
}
extension DeviceEntry {
/// What to say when there's no device to show.
var emptyText: String {
if !isSetUp { return "Open CrossSound once" }
if let configuredName { return "\(configuredName) is offline" }
return "Nothing playing"
}
}
/// The Smart Stack's: device, song, artist and the three buttons.
struct DeviceRectangular: View {
let entry: DeviceEntry
var body: some View {
if let device = entry.device {
VStack(alignment: .leading, spacing: 2) {
HStack(spacing: 4) {
Image(systemName: DeviceRow.icon(device.platform))
Text(device.name).lineLimit(1)
}
.font(.system(size: 12, weight: .semibold))
.widgetAccentable()
Text(device.title ?? "Nothing playing")
.rw(.titleSmall)
.lineLimit(1)
HStack(spacing: 4) {
Text(device.artist ?? "")
.rw(.labelSmall)
.lineLimit(1)
Spacer(minLength: 2)
DeviceControls(device: device)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
} else {
VStack(alignment: .leading, spacing: 2) {
Text("CrossSound Remote").rw(.titleSmall).widgetAccentable()
Text(entry.emptyText).rw(.labelSmall)
}
.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
/// ‹ ⏯ ›, working from the widget itself.
struct DeviceControls: View {
let device: RemoteDevice
var body: some View {
HStack(spacing: 8) {
Button(intent: RemoteCommandIntent(deviceId: device.id, command: "prev")) {
Image(systemName: "backward.fill")
}
Button(
intent: RemoteCommandIntent(deviceId: device.id, command: device.isPlaying ? "pause" : "play")
) {
Image(systemName: device.isPlaying ? "pause.fill" : "play.fill")
}
Button(intent: RemoteCommandIntent(deviceId: device.id, command: "next")) {
Image(systemName: "forward.fill")
}
}
.buttonStyle(.plain)
.font(.system(size: 15, weight: .semibold))
.disabled(!device.online)
}
}
/// One button: play / pause, round the device's progress.
struct DeviceCircular: View {
let entry: DeviceEntry
var body: some View {
if let device = entry.device {
Button(
intent: RemoteCommandIntent(deviceId: device.id, command: device.isPlaying ? "pause" : "play")
) {
ZStack {
AccessoryWidgetBackground()
Gauge(value: Double(device.positionMs), in: 0...Double(max(device.durationMs, 1))) {
EmptyView()
} currentValueLabel: {
Image(systemName: device.isPlaying ? "pause.fill" : "play.fill")
.font(.system(size: 16, weight: .semibold))
}
.gaugeStyle(.accessoryCircularCapacity)
.widgetAccentable()
}
}
.buttonStyle(.plain)
} else {
ZStack {
AccessoryWidgetBackground()
Image(systemName: "dot.radiowaves.left.and.right")
}
}
}
}
struct DeviceInline: View {
let entry: DeviceEntry
var body: some View {
if let device = entry.device, let title = device.title, !title.isEmpty {
Label(title, systemImage: device.isPlaying ? "play.fill" : "pause.fill")
} else {
Label(entry.emptyText, systemImage: "dot.radiowaves.left.and.right")
}
}
}
struct DeviceCorner: View {
let entry: DeviceEntry
var body: some View {
Image(systemName: entry.device.map { DeviceRow.icon($0.platform) } ?? "dot.radiowaves.left.and.right")
.font(.system(size: 20, weight: .semibold))
.widgetAccentable()
.widgetLabel {
Text(entry.device?.title ?? entry.emptyText)
}
}
}