From 23e3b693136e1bdbbbdc1397de9a4163b3296881 Mon Sep 17 00:00:00 2001 From: David Sansome Date: Mon, 23 Nov 2026 13:06:49 +1100 Subject: [PATCH] Fix UI, Watch, Widget, Intent, audio session, and localization issues across ClementineRemote Fixes AVAudioSession coordination between Renderer, PhonePlayer, and VolumeButtons; removes the Last.fm Ban button (along with RemoteSession.ban()); improves Apple Watch contrast and artwork updates, Widget theming, App Intents, Downloads/Library/Search/Connect UI, localization, and archive script Release handling. Release-note: Removed the Last.fm Ban button and improved playback controls, audio session coordination, Apple Watch contrast, widget theming, downloads, library browsing, and iPad wording. --- App/AppModel.swift | 116 +++++++++-- App/Connect/ConnectView.swift | 22 ++- App/Connection/ConnectionSheet.swift | 3 +- App/Downloads/DownloadsModel.swift | 25 +-- App/Downloads/DownloadsView.swift | 55 ++++-- App/Intents/AppIntents.swift | 3 +- App/Internet/InternetView.swift | 13 +- App/Library/BrowseViews.swift | 12 +- App/Library/LibraryModel.swift | 18 +- App/Library/LibraryView.swift | 29 ++- App/Player/OutputSheet.swift | 7 +- App/Player/PlayerView.swift | 70 ++++++- App/Player/SongDetailsView.swift | 83 +++++--- App/Queue/QueueView.swift | 55 +++--- App/Resources/Localizable.xcstrings | 23 +++ App/Search/SearchModel.swift | 6 +- App/Settings/SettingsView.swift | 49 ++++- App/Streaming/AVPlayback.swift | 182 ++++++++++++++---- App/Streaming/NowPlaying.swift | 16 +- App/Support/VolumeButtons.swift | 18 +- App/Theme/Components.swift | 43 ++++- App/Watch/WatchLink.swift | 39 ++-- ClementineRemote.xcodeproj/project.pbxproj | 2 + .../ClementineKit/Session/RemoteSession.swift | 6 - Shared/CommandIntents.swift | 33 +++- WatchApp/NowPlayingView.swift | 80 +++++--- WatchApp/PhoneLink.swift | 30 ++- Widget/ClementineWidget.swift | 19 +- design/DESIGN.md | 2 +- project.yml | 1 + scripts/archive.sh | 15 ++ 31 files changed, 819 insertions(+), 256 deletions(-) diff --git a/App/AppModel.swift b/App/AppModel.swift index f074145..e572493 100644 --- a/App/AppModel.swift +++ b/App/AppModel.swift @@ -1,3 +1,4 @@ +import AVFoundation import BackgroundTasks import ClementineKit import SwiftUI @@ -71,7 +72,16 @@ final class AppModel { init() { let session = RemoteSession() self.session = session - renderer = Renderer(playback: AVPlayback(), server: { session.endpoint }) { session.send($0) } + renderer = Renderer( + playback: AVPlayback( + // Use AppModel.shared because `self` isn't fully initialized yet (nowPlaying/watch + // come later), and route session changes through the central coordinator. + onActivateAudio: { AppModel.shared?.activatePlaybackSession(for: .clementine) }, + onDeactivateAudio: { AppModel.shared?.deactivateAudioSessionIfIdle() }), + // Prefer the active TCP socket's resolved IP so AVPlayer HTTP requests hit the same + // IP family; Clementine's MediaHttpServer rejects mismatched peer IPs with 403. + server: { session.connectedEndpoint ?? session.endpoint } + ) { session.send($0) } internet = InternetBrowser { session.send($0) } syncer = Syncer( session: session, store: TestingFeatures.enabled ? Self.openSyncStore() : nil, folder: Self.syncedFolder) @@ -84,6 +94,7 @@ final class AppModel { self.nowPlaying = nowPlaying renderer.onUpdate = { nowPlaying.update() } phonePlayer.onUpdate = { nowPlaying.update() } + phonePlayer.onActivateAudio = { [weak self] in self?.activatePlaybackSession(for: .phone) } syncer.networkAllows = { [network] in network.allows($0) } session.addObserver { [weak self, renderer, internet] message in renderer.handle(message) @@ -138,7 +149,8 @@ final class AppModel { func connectFromPhone() { isWithoutClementine = false let name = settings.lastServerName - connect(host: settings.lastHost, name: name.isEmpty ? nil : name) + // Pass saved lastPort so non-default ports are preserved when reconnecting from offline mode. + connect(host: settings.lastHost, port: settings.lastPort, name: name.isEmpty ? nil : name) } /// Offers Play on this phone on the app's icon while there's something to play. @@ -209,6 +221,54 @@ final class AppModel { } } + /// Coordinates the single shared `AVAudioSession` between remote streaming (`Renderer`), + /// local phone playback (`PhonePlayer`), and physical volume-button interception. + var volumeButtonsShouldBeActive: Bool { + volumeButtonsShouldBeActive(enabled: settings.volumeButtons, scenePhase: scenePhase) + } + + /// Takes `enabled` and `scenePhase` explicitly so `VolumeButtonsView` participates in SwiftUI + /// updates, and yields hardware buttons to iOS whenever audio plays on this phone. + func volumeButtonsShouldBeActive(enabled: Bool, scenePhase: ScenePhase) -> Bool { + enabled && scenePhase == .active && session.status.isActive + && !session.isPlayingHere && !isPlayingFromPhone + } + + func activatePlaybackSession(for source: PlayFrom) { + // Pause the competing local audio owner before claiming the shared `.playback` session. + if source == .clementine, phonePlayer.isPlaying { + phonePlayer.pause() + } else if source == .phone { + pauseClementine() + renderer.pauseLocally() + } + let audio = AVAudioSession.sharedInstance() + try? audio.setCategory(.playback, mode: .default, policy: .longFormAudio) + try? audio.setActive(true) + } + + func activateVolumeButtonSession() -> Bool { + // Never downgrade an active `.playback` session to `.ambient`, which would let the mute + // switch or screen lock silence audio playing on this phone. + guard renderer.item == nil, !phonePlayer.isPlaying else { return false } + let audio = AVAudioSession.sharedInstance() + do { + try audio.setCategory(.ambient, options: [.mixWithOthers]) + try audio.setActive(true) + return true + } catch { + return false + } + } + + func deactivateAudioSessionIfIdle(includingVolumeButtons: Bool = false) { + // Keep the session active if another owner (`PhonePlayer`, `Renderer`, or active + // volume-button monitoring) still relies on it. + guard renderer.item == nil, !phonePlayer.isPlaying, + includingVolumeButtons || !volumeButtonsShouldBeActive else { return } + try? AVAudioSession.sharedInstance().setActive(false, options: [.notifyOthersOnDeactivation]) + } + /// Where synced songs go: beside the downloaded ones, so the Files app shows them too. static let syncedFolder = URL.documentsDirectory.appending(path: "Clementine/Synced", directoryHint: .isDirectory) @@ -270,7 +330,7 @@ final class AppModel { func connect(host: String, port: UInt16? = nil, name: String? = nil) { let host = host.trimmingCharacters(in: .whitespaces) guard !host.isEmpty else { return } - settings.remember(host: host, name: name) + settings.remember(host: host, name: name, port: port) stopAutoConnecting() connectProblem = nil session.connect( @@ -286,7 +346,7 @@ final class AppModel { guard settings.autoConnect, !isAutoConnectOver, !settings.lastHost.isEmpty, session.status == .disconnected else { return } let name = settings.lastServerName - connect(host: settings.lastHost, name: name.isEmpty ? nil : name) + connect(host: settings.lastHost, port: settings.lastPort, name: name.isEmpty ? nil : name) autoConnectName = name.isEmpty ? nil : name } @@ -299,7 +359,9 @@ final class AppModel { case .disconnected: // Only when the saved address couldn't be reached: not, say, for a wrong auth code. guard case .couldNotConnect? = session.closeReason else { return } - case .connecting where server.host != session.endpoint?.host: + // Compare host and port so a server restarted on a new port at the same IP still triggers + // reconnect. + case .connecting where Endpoint(host: server.host, port: server.port) != session.endpoint: break default: return @@ -451,12 +513,17 @@ extension AppModel { /// Syncs for [task], over a network Download over allows, and asks for the next one. private func runBackgroundSync(_ task: BGTask) { scheduleBackgroundSync() - let run = Task { - guard let path = await NetworkMonitor.currentPath(), + let completion = BGTaskCompletion(task) + let run = Task { + // Check cancellation around the async path lookup so an already-expired task bails out + // without opening a connection. + guard !Task.isCancelled, + let path = await NetworkMonitor.currentPath(), BackgroundSync.allows( - settings.downloadNetwork, expensive: path.expensive, constrained: path.constrained) - else { return } - await BackgroundSync.run(session: session, syncer: syncer, settings: settings) { + settings.downloadNetwork, expensive: path.expensive, constrained: path.constrained), + !Task.isCancelled + else { return false } + return await BackgroundSync.run(session: session, syncer: syncer, settings: settings) { UIApplication.shared.applicationState == .background } } @@ -465,11 +532,36 @@ extension AppModel { Task { @MainActor in syncer.stop() run.cancel() + // Report completion immediately on expiration rather than waiting for `run` to + // unwind so iOS doesn't terminate the process for missing the deadline. + completion.complete(success: false) } } Task { - await run.value - task.setTaskCompleted(success: true) + let success = await run.value + completion.complete(success: success) + } + } +} + +/// Ensures `BGTask.setTaskCompleted(success:)` is invoked at most once across the competing +/// normal-finish and iOS-expiration paths. +private final class BGTaskCompletion: @unchecked Sendable { + private let task: BGTask + private let lock = NSLock() + private var finished = false + + init(_ task: BGTask) { + self.task = task + } + + func complete(success: Bool) { + lock.lock() + let shouldComplete = !finished + finished = true + lock.unlock() + if shouldComplete { + task.setTaskCompleted(success: success) } } } diff --git a/App/Connect/ConnectView.swift b/App/Connect/ConnectView.swift index 993ceea..23e33f5 100644 --- a/App/Connect/ConnectView.swift +++ b/App/Connect/ConnectView.swift @@ -137,7 +137,7 @@ struct ConnectView: View { .keyboardType(.numberPad) Button("Cancel", role: .cancel) {} Button("Connect") { - if let code = Int32(authCode) { + if let code = Int32(authCode.trimmingCharacters(in: .whitespaces)) { model.connect(authCode: code) } else { model.toasts.show("That isn't a valid code") @@ -149,15 +149,25 @@ struct ConnectView: View { } else { Button("OK") {} if model.songsOnPhone > 0 { - Button(String( - localized: "Play on this phone", - comment: "A button in the dialog when connecting fails, and a shortcut on the app's icon: play the music saved on the phone instead of connecting."), + Button(UIDevice.current.userInterfaceIdiom == .pad + ? String( + localized: "Play on this iPad", + comment: "A button in the dialog when connecting fails on iPad: play the music saved on the iPad instead of connecting.") + : String( + localized: "Play on this phone", + comment: "A button in the dialog when connecting fails, and a shortcut on the app's icon: play the music saved on the phone instead of connecting."), action: model.playWithoutClementine) } } } message: { problem in Text(problemMessage(problem)) } + .onChange(of: model.connectProblem) { _, problem in + // Clear any previously entered code so re-prompting doesn't prefill a rejected one. + if problem == .authCode { + authCode = "" + } + } } static let clementineVersion = "1.3" @@ -425,9 +435,9 @@ private struct OnPhoneRow: View { var body: some View { Button(action: action) { HStack(spacing: Metrics.space4) { - IconTile(systemImage: UIDevice.current.userInterfaceIdiom == .pad ? "ipad" : "iphone") + IconTile(systemImage: ThisDevice.systemImage) VStack(alignment: .leading, spacing: 2) { - Text("On this phone") + Text(ThisDevice.label) .textStyle(.bodyLarge) .foregroundStyle(Palette.onSurface) Text(connecting diff --git a/App/Connection/ConnectionSheet.swift b/App/Connection/ConnectionSheet.swift index 01cab88..1facaa5 100644 --- a/App/Connection/ConnectionSheet.swift +++ b/App/Connection/ConnectionSheet.swift @@ -32,7 +32,8 @@ struct ConnectionSheet: View { } Section { - if let endpoint = session.endpoint { + // Prefer the active socket's resolved IP over the configured hostname. + if let endpoint = session.connectedEndpoint ?? session.endpoint { LabeledContent("Address", value: "\(endpoint.host) · port \(String(endpoint.port))") } if !session.clementineVersion.isEmpty { diff --git a/App/Downloads/DownloadsModel.swift b/App/Downloads/DownloadsModel.swift index 31cf362..0d9eace 100644 --- a/App/Downloads/DownloadsModel.swift +++ b/App/Downloads/DownloadsModel.swift @@ -15,9 +15,8 @@ final class DownloadsModel { let id: Int let kind: Kind var status = DownloadStatus() - /// Bytes a second, over the last few seconds. var speed: Int64 = 0 - fileprivate var samples: [(time: ContinuousClock.Instant, bytes: Int64)] = [] + fileprivate var rate = TrafficRate(window: .seconds(3)) var isFinished: Bool { if case .finished = status.state { return true } @@ -91,7 +90,9 @@ final class DownloadsModel { } private func start(_ kind: Kind, _ request: RemoteMessage, playlistName: String?) { - guard let endpoint = model.session.endpoint else { return } + // Use the active socket's resolved IP so downloads hit the same address family as the + // session. + guard let endpoint = model.session.connectedEndpoint ?? model.session.endpoint else { return } let id = nextID nextID += 1 var job = Job(id: id, kind: kind) @@ -109,7 +110,10 @@ final class DownloadsModel { endpoint: endpoint, authCode: model.session.authCode, request: request, playlistName: playlistName, options: DownloadOptions(directory: directory, settings: model.settings)) let background = UIApplication.shared.beginBackgroundTask(withName: "Download") { [weak self] in - self?.cancel(id) + // iOS can invoke expiration handlers off the main thread; hop to @MainActor for cancel(_:). + Task { @MainActor [weak self] in + self?.cancel(id) + } } tasks[id] = Task { let (updates, continuation) = AsyncStream.makeStream(of: DownloadStatus.self, bufferingPolicy: .bufferingNewest(1)) @@ -133,12 +137,8 @@ final class DownloadsModel { guard let index = jobs.firstIndex(where: { $0.id == id }) else { return } var job = jobs[index] job.status = status - let now = ContinuousClock.now - job.samples.append((now, status.bytes)) - job.samples.removeAll { now - $0.time > .seconds(3) } - if let first = job.samples.first, let last = job.samples.last, last.time > first.time { - let seconds = (last.time - first.time).timeInterval - job.speed = Int64(Double(last.bytes - first.bytes) / max(seconds, 0.001)) + if let rate = job.rate.add(Int(clamping: status.bytes)) { + job.speed = Int64(rate) } jobs[index] = job } @@ -224,8 +224,11 @@ extension DownloadsModel.Job { /// Bytes so far, of the total, and the speed while downloading. var sizes: String { + // Hide counts and speed until chunk 0 arrives or bytes transfer (e.g. while starting or on + // early failure). + guard status.totalBytes > 0 || status.bytes > 0 else { return "" } var text = "\(formatBytes(status.bytes)) / \(formatBytes(status.totalBytes))" - if !isFinished { + if !isFinished, speed > 0 { text += " (\(formatBytes(speed))/s)" } return text diff --git a/App/Downloads/DownloadsView.swift b/App/Downloads/DownloadsView.swift index 1067617..1dd0974 100644 --- a/App/Downloads/DownloadsView.swift +++ b/App/Downloads/DownloadsView.swift @@ -123,8 +123,12 @@ struct DownloadsView: View { description: Text("Download songs, albums and playlists from the player, the queue and the library. They're saved in the Files app.")) } } - .navigationTitle(model.isOnThisPhone ? String(localized: "On this phone") : String(localized: "Downloads")) - .navigationSubtitle(downloads.freeSpace.map { String(localized: "\(formatBytes($0)) free on this phone") } ?? "") + .navigationTitle(model.isOnThisPhone ? ThisDevice.label : String(localized: "Downloads")) + .navigationSubtitle(downloads.freeSpace.map { + UIDevice.current.userInterfaceIdiom == .pad + ? String(localized: "\(formatBytes($0)) free on this iPad", comment: "Navigation subtitle showing free storage space on the iPad.") + : String(localized: "\(formatBytes($0)) free on this phone") + } ?? "") .connectionToolbar() .navigationDestination(for: KeptRoute.self) { route in KeptRuleView(ruleID: route.ruleID) @@ -196,11 +200,12 @@ private struct PhoneArtistRows: View { let songs: [DownloadedSong] var body: some View { - let albums = DownloadedSong.albums(of: songs) + // Pre-group once per body pass to avoid scanning all albums and songs per artist row. + let albumsByArtist = Dictionary(grouping: DownloadedSong.albums(of: songs), by: \.artist) + let looseByArtist = Dictionary(grouping: songs.filter(\.album.isEmpty), by: \.artist) ForEach(DownloadedSong.artists(of: songs), id: \.self) { artist in // Counted as the library counts: albums, and songs on none. - let count = albums.filter { $0.artist == artist }.count - + songs.filter { $0.artist == artist && $0.album.isEmpty }.count + let count = (albumsByArtist[artist]?.count ?? 0) + (looseByArtist[artist]?.count ?? 0) NavigationLink(value: BrowseRoute.artist(artist)) { MediaRow(title: artist, meta: String(localized: "\(count) items")) { IconTile(systemImage: ItemKind.artist.systemImage) @@ -408,6 +413,12 @@ private struct KeptRow: View { /// The songs of something kept on this phone, to play on the phone: Play plays them in order, /// Shuffle at random, and a song plays them from it. The song playing is marked. private struct KeptRuleView: View { + // Include running so the song list also reloads when a sync completes with the same count. + private struct ReloadKey: Equatable { + let songs: Int? + let running: Bool + } + let ruleID: Int64 @Environment(AppModel.self) private var model @State private var songs: [KeptSong]? @@ -472,8 +483,8 @@ private struct KeptRuleView: View { } .navigationTitle(kept?.rule.title ?? "") .navigationBarTitleDisplayMode(.inline) - // Read again as syncing changes them. - .task(id: kept?.songs) { + // Read again as syncing progresses or completes. + .task(id: ReloadKey(songs: kept?.songs, running: model.syncer.status.running)) { songs = await model.syncer.songs(ruleID) } } @@ -506,7 +517,12 @@ extension KeptRule { } switch result { case .needsSetup(let message): - return message + let trimmed = message.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty + ? String( + localized: "Configure this in Clementine on your computer.", + comment: "Fallback status under a kept rule when Clementine needs setup without providing a custom message.") + : trimmed case .gone: return String( localized: "No longer in Clementine", @@ -573,13 +589,25 @@ private struct JobRow: View { // Once finished it may be an error, which should be read in full. .lineLimit(job.isFinished ? nil : 1) if !job.isFinished { - ProgressView(value: job.status.progress) + // Show an indeterminate bar until chunk sizes are known, and clamp against + // server total-byte rounding. + if case .downloading = job.status.state { + ProgressView(value: min(max(job.status.progress, 0), 1)) + } else { + ProgressView() + .progressViewStyle(.linear) + } + } + if !job.sizes.isEmpty { + Text(job.sizes) + .textStyle(.labelMedium) + .monospacedDigit() + .foregroundStyle(Palette.onSurfaceVariant) } - Text(job.sizes) - .textStyle(.labelMedium) - .monospacedDigit() - .foregroundStyle(Palette.onSurfaceVariant) } + // Combine only the info stack so VoiceOver doesn't merge the cancel button into row + // activation. + .accessibilityElement(children: .combine) Spacer(minLength: 0) if let cancel { Button("Cancel download", systemImage: "xmark", action: cancel) @@ -590,7 +618,6 @@ private struct JobRow: View { } .contentShape(.rect) .listRowBackground(Palette.surface) - .accessibilityElement(children: .combine) } } diff --git a/App/Intents/AppIntents.swift b/App/Intents/AppIntents.swift index a74032d..f29c563 100644 --- a/App/Intents/AppIntents.swift +++ b/App/Intents/AppIntents.swift @@ -16,7 +16,8 @@ struct ConnectIntent: AppIntent { } if model.session.status == .disconnected { let name = model.settings.lastServerName - model.connect(host: model.settings.lastHost, name: name.isEmpty ? nil : name) + // Include the saved port so Shortcuts connects when Clementine uses a custom port. + model.connect(host: model.settings.lastHost, port: model.settings.lastPort, name: name.isEmpty ? nil : name) } return .result() } diff --git a/App/Internet/InternetView.swift b/App/Internet/InternetView.swift index b87fefa..65d4c89 100644 --- a/App/Internet/InternetView.swift +++ b/App/Internet/InternetView.swift @@ -127,10 +127,15 @@ private struct InternetLevelView: View { case .loading: ProgressView("Loading…") case .needsSetup(let message): + let trimmed = message.trimmingCharacters(in: .whitespacesAndNewlines) ContentUnavailableView { Label("Set up in Clementine", systemImage: "gearshape") } description: { - Text(message) + Text(trimmed.isEmpty + ? String( + localized: "Configure this service in Clementine on your computer.", + comment: "Fallback message when an internet service needs setup in Clementine without custom instructions.") + : trimmed) } case .ready: ContentUnavailableView("Nothing here", systemImage: "globe") @@ -144,10 +149,14 @@ private struct InternetLevelView: View { /// What can be done with a node that can go on the playlist. struct InternetAddActions: View { let add: (BrowseAddAction) -> Void + @Environment(RemoteSession.self) private var session var body: some View { Button("Play now", systemImage: "play.fill") { add(.playNow) } - Button("Play next", systemImage: "text.line.first.and.arrowtriangle.forward") { add(.playNext) } + // Match BrowseAddActions: only offer Play next when the connected Clementine supports it. + if session.canEnqueueNext { + Button("Play next", systemImage: "text.line.first.and.arrowtriangle.forward") { add(.playNext) } + } Button("Add to playlist", systemImage: "plus") { add(.append) } Button("Replace playlist", systemImage: "arrow.triangle.2.circlepath") { add(.replace) } } diff --git a/App/Library/BrowseViews.swift b/App/Library/BrowseViews.swift index a7b4ca6..5e1658b 100644 --- a/App/Library/BrowseViews.swift +++ b/App/Library/BrowseViews.swift @@ -63,15 +63,9 @@ struct BrowseRows: View { ForEach(rows, id: \.offset) { index, item in Group { if isEditing { - Button { - if selection.contains(index) { - selection.remove(index) - } else { - selection.insert(index) - } - } label: { - BrowseRow(item: item, icon: icon(item), meta: meta(item)) - } + // Let List handle edit-mode selection via .tag(index); a Button intercepts + // row taps. + BrowseRow(item: item, icon: icon(item), meta: meta(item)) } else if item.kind == .song { Button { add([item], .selected, .playIfStopped) diff --git a/App/Library/LibraryModel.swift b/App/Library/LibraryModel.swift index 568e5cc..3d9371f 100644 --- a/App/Library/LibraryModel.swift +++ b/App/Library/LibraryModel.swift @@ -46,7 +46,9 @@ final class LibraryModel { } func download() { - guard downloadTask == nil, let endpoint = model.session.endpoint else { return } + // Use the active socket's resolved IP so library downloads hit the same IP family as the + // session. + guard downloadTask == nil, let endpoint = model.session.connectedEndpoint ?? model.session.endpoint else { return } if !model.network.allows(model.settings.downloadNetwork) { model.toasts.show(DownloadFailure.networkNotAllowed.message) return @@ -117,12 +119,13 @@ final class LibraryModel { return (try? await store.songURLs(of: items, grouping: settings.libraryGrouping, sorting: settings.librarySorting)) ?? [] } - /// Whether [item] can be kept on this phone, when Clementine syncs: an artist or an album, by - /// name. Albums are kept by album artist, as Clementine files them; artists by artist. + /// Whether [item] can be kept on this phone, when Clementine syncs: an artist, album artist, + /// or album, by name (excluding Various Artists compilations). func canKeep(_ item: BrowseItem) -> Bool { let fields = model.settings.libraryGrouping.fields - return model.session.syncing.available && !item.value.isEmpty && item.level < fields.count - && SyncSources.keepableFields.contains(fields[item.level]) + // Various Artists is a synthetic grouping with no real artist value to keep by. + return model.session.syncing.available && !item.value.isEmpty && !item.isVariousArtists + && item.level < fields.count && SyncSources.keepableFields.contains(fields[item.level]) } /// Keeps [item] on this phone ([canKeep]): its albums, or the artist's songs, updated from @@ -132,11 +135,10 @@ final class LibraryModel { let serverID = model.session.syncing.serverID let grouping = model.settings.libraryGrouping let rules: [SyncRule] - if grouping.fields[item.level] == "artist" { + if grouping.fields[item.level] == "artist", !item.isVariousArtists { rules = [SyncSources.artistRule(serverID: serverID, artist: item.value, refreshPolicy: refreshPolicy)] } else { - // One album here can be several in Clementine, filed under different album artists: - // keep each. + // One album (or album artist) can correspond to several albums in Clementine: keep each. rules = ((try? await store.albums(of: item, grouping: grouping)) ?? []).map { SyncSources.albumRule( serverID: serverID, albumArtist: $0.albumArtist, album: $0.album, refreshPolicy: refreshPolicy) diff --git a/App/Library/LibraryView.swift b/App/Library/LibraryView.swift index 730e743..0cfda56 100644 --- a/App/Library/LibraryView.swift +++ b/App/Library/LibraryView.swift @@ -60,17 +60,13 @@ private struct LibraryLevelView: View { .navigationTitle(opened == nil ? String(localized: "Library") : "") .navigationSubtitle(opened == nil && !isSearching && level != nil ? String(localized: "\(level?.items.count ?? 0) items") : "") .navigationBarTitleDisplayMode(opened == nil ? .large : .inline) - .refreshable { - if opened == nil { - library.download() - } - } + .modifier(RefreshableIf(enabled: opened == nil) { await library.download() }) .toolbar { toolbar } - .task(id: LoadKey(revision: library.revision, grouping: grouping, sorting: sorting, status: library.status)) { + .task(id: LoadKey(revision: library.revision, grouping: grouping, sorting: sorting)) { level = await library.level(below: opened) selection = [] } - .task(id: SearchKey(revision: library.revision, query: query, status: library.status)) { + .task(id: SearchKey(revision: library.revision, query: query)) { guard opened == nil else { return } if isSearching { // Waits for a pause in typing. @@ -186,17 +182,17 @@ private struct LibraryLevelView: View { .accessibilityIdentifier("librarySmartPlaylists") } + // Deliberately omit library.status: keying on it would blank the list and cancel/restart + // loads and searches on every download progress chunk; revision bumps once ready. private struct LoadKey: Equatable { let revision: Int let grouping: String let sorting: String - let status: LibraryModel.Status } private struct SearchKey: Equatable { let revision: Int let query: String - let status: LibraryModel.Status } @ViewBuilder @@ -313,3 +309,18 @@ struct ProgressBanner: View { .accessibilityElement(children: .combine) } } + +/// Attaches `.refreshable` only at the root level so drilled-down pages don't show a no-op +/// pull-to-refresh spinner. +private struct RefreshableIf: ViewModifier { + let enabled: Bool + let action: @Sendable () async -> Void + + func body(content: Content) -> some View { + if enabled { + content.refreshable(action: action) + } else { + content + } + } +} diff --git a/App/Player/OutputSheet.swift b/App/Player/OutputSheet.swift index 0b28240..8cd2e9f 100644 --- a/App/Player/OutputSheet.swift +++ b/App/Player/OutputSheet.swift @@ -128,7 +128,6 @@ struct PlayFromSheet: View { @Environment(\.dismiss) private var dismiss var body: some View { - let isPad = UIDevice.current.userInterfaceIdiom == .pad NavigationStack { List { Section { @@ -141,10 +140,8 @@ struct PlayFromSheet: View { ) { pick(.clementine) } .accessibilityIdentifier("playFromClementine") PlayFromRow( - name: isPad - ? String(localized: "On this iPad", comment: "As \"On this phone\", on an iPad: music saved on the iPad, as opposed to Clementine on the computer.") - : String(localized: "On this phone"), - systemImage: isPad ? "ipad" : "iphone", + name: ThisDevice.label, + systemImage: ThisDevice.systemImage, song: model.phonePlayer.playingSong, isPlaying: model.phonePlayer.isPlaying, isChosen: model.playFrom == .phone diff --git a/App/Player/PlayerView.swift b/App/Player/PlayerView.swift index 1adbd67..0fe8e61 100644 --- a/App/Player/PlayerView.swift +++ b/App/Player/PlayerView.swift @@ -71,11 +71,39 @@ struct PlayerView: View { HStack(alignment: .center, spacing: Metrics.space6) { artwork .frame(width: max(side, 0), height: max(side, 0)) - controls + // Allow scrolling when landscape height or larger Dynamic Type can't fit + // the controls stack cleanly. + ScrollView { + controls + } + .scrollBounceBehavior(.basedOnSize) } .padding(.horizontal, Metrics.space6) .padding(.bottom, Metrics.space4) .frame(maxHeight: .infinity) + } else if geometry.size.height < 600 { + // Compact portrait heights (e.g. small phones or split view) scroll instead + // of clipping controls. + ScrollView { + VStack(spacing: 0) { + artwork + .frame(maxHeight: 160) + .padding(.top, Metrics.space3) + songInfo + .padding(.top, Metrics.space4) + SeekBar() + .padding(.top, Metrics.space3) + TransportControls() + .padding(.top, Metrics.space1) + VolumeSlider() + .padding(.top, Metrics.space2) + actions + .padding(.top, Metrics.space2) + } + .padding(.horizontal, Metrics.space6) + .padding(.bottom, Metrics.space2) + } + .scrollBounceBehavior(.basedOnSize) } else { VStack(spacing: 0) { artwork @@ -363,7 +391,12 @@ struct SeekBar: View { VStack(spacing: 0) { Slider( value: Binding( - get: { dragging ?? min(seconds, Double(max(length, 1))) }, + get: { + // Streams and stopped tracks can report length <= 0; park the disabled + // slider at 0 rather than computing a position against the fallback 0...1 range. + guard length > 0 else { return 0 } + return dragging ?? min(seconds, Double(length)) + }, set: { dragging = $0 }), in: 0...Double(max(length, 1)) ) { editing in @@ -487,6 +520,10 @@ private struct TransportButton: View { struct VolumeSlider: View { @Environment(AppModel.self) private var model @Environment(RemoteSession.self) private var session + // Hold the thumb position while dragging so delayed server volume echoes don't snap it back; + // isEditingVolume ensures non-drag updates (e.g. VoiceOver) don't strand draggingVolume. + @State private var draggingVolume: Double? + @State private var isEditingVolume = false var body: some View { HStack(spacing: Metrics.space3) { @@ -498,13 +535,34 @@ struct VolumeSlider: View { } else { Slider( value: Binding( - get: { Double(session.volume) }, + get: { draggingVolume ?? Double(session.volume) }, set: { value in - if Int(value.rounded()) != session.volume { - session.setVolume(Int(value.rounded())) + if isEditingVolume { + draggingVolume = value + } + let target = Int(value.rounded()) + if target != session.volume { + session.setVolume(target) } }), - in: 0...100) + in: 0...100 + ) { editing in + isEditingVolume = editing + if !editing { + if let draggingVolume { + let target = Int(draggingVolume.rounded()) + if target != session.volume { + session.setVolume(target) + } + } + draggingVolume = nil + } + } + .onChange(of: session.volume) { _, _ in + if !isEditingVolume { + draggingVolume = nil + } + } .accessibilityLabel("Clementine volume") .accessibilityValue("\(session.volume)%") } diff --git a/App/Player/SongDetailsView.swift b/App/Player/SongDetailsView.swift index bf70d4f..a671cdf 100644 --- a/App/Player/SongDetailsView.swift +++ b/App/Player/SongDetailsView.swift @@ -29,6 +29,9 @@ struct SongDetailsView: View { case .lyrics: LyricsView() } + } else { + ContentUnavailableView("No song playing", systemImage: "music.note") + .padding(.top, Metrics.space4) } } .padding(.horizontal, Metrics.space6) @@ -82,20 +85,7 @@ struct SongDetailsView: View { DetailRow(label: "File", value: song.filename) } - HStack(spacing: 0) { - Text("Rating") - .textStyle(.bodyMedium) - .foregroundStyle(Palette.onSurfaceVariant) - .frame(width: 96, alignment: .leading) - Rating(stars: song.rating * 5) { stars in - session.rate(stars: stars) - if stars == stars.rounded() { - model.toasts.show("Rated \(Int(stars)) stars") - } else { - model.toasts.show("Rated \(stars.formatted()) stars") - } - } - } + ratingRow(for: song) if showLastFM { HStack(spacing: Metrics.space3) { @@ -106,16 +96,43 @@ struct SongDetailsView: View { Label("Love", systemImage: session.isLoved ? "heart.fill" : "heart") } .disabled(session.isLoved) - Button { - session.ban() - model.toasts.show("Banned on Last.fm") - } label: { - Label("Ban", systemImage: "hand.thumbsdown") - } } .buttonStyle(.bordered) } } + + @ViewBuilder + private func ratingRow(for song: Song) -> some View { + // Stack vertically when narrow widths or large Dynamic Type can't fit five 44pt stars inline. + ViewThatFits(in: .horizontal) { + HStack(spacing: 0) { + Text("Rating") + .textStyle(.bodyMedium) + .foregroundStyle(Palette.onSurfaceVariant) + .frame(width: 96, alignment: .leading) + Rating(stars: song.rating * 5) { stars in + rateSong(stars) + } + } + VStack(alignment: .leading, spacing: Metrics.space1) { + Text("Rating") + .textStyle(.bodyMedium) + .foregroundStyle(Palette.onSurfaceVariant) + Rating(stars: song.rating * 5) { stars in + rateSong(stars) + } + } + } + } + + private func rateSong(_ stars: Float) { + session.rate(stars: stars) + if stars == stars.rounded() { + model.toasts.show("Rated \(Int(stars)) stars") + } else { + model.toasts.show("Rated \(stars.formatted()) stars") + } + } } private struct DetailRow: View { @@ -175,6 +192,14 @@ private struct Rating: View { .accessibilityElement(children: .contain) .accessibilityLabel("Rating") .accessibilityValue("\(stars.formatted(.number.precision(.fractionLength(0...1)))) stars") + .accessibilityAdjustableAction { direction in + // Step in half-star increments for VoiceOver swipe adjustments. + switch direction { + case .increment: rate(min(5, (stars * 2).rounded() / 2 + 0.5)) + case .decrement: rate(max(0.5, (stars * 2).rounded() / 2 - 0.5)) + @unknown default: break + } + } } private func symbol(_ star: Int) -> String { @@ -190,9 +215,20 @@ private struct Rating: View { /// The song's lyrics, asking Clementine for them the first time. private struct LyricsView: View { + // Key only on URL and title (for changing stream tracks) so arriving artwork or rating changes + // don't re-request lyrics or reset the timeout. + private struct TrackKey: Equatable { + let url: String + let title: String + } + @Environment(RemoteSession.self) private var session @State private var gaveUp = false + private var trackKey: TrackKey? { + session.song.map { TrackKey(url: $0.url, title: $0.title) } + } + var body: some View { Group { if let lyrics = session.lyrics.flatMap(Lyrics.best(of:)), !lyrics.content.isEmpty { @@ -219,11 +255,12 @@ private struct LyricsView: View { } } .frame(maxWidth: .infinity, alignment: .leading) - .task(id: session.song) { + .task(id: trackKey) { gaveUp = false session.requestLyrics() - // Clementine doesn't always answer when it finds nothing. - try? await Task.sleep(for: .seconds(15)) + // Clementine doesn't always answer when it finds nothing. Don't set gaveUp if cancelled + // (view dismissed or track changed). + guard (try? await Task.sleep(for: .seconds(15))) != nil, !Task.isCancelled else { return } gaveUp = true } } diff --git a/App/Queue/QueueView.swift b/App/Queue/QueueView.swift index beab967..e4e4cbc 100644 --- a/App/Queue/QueueView.swift +++ b/App/Queue/QueueView.swift @@ -33,7 +33,9 @@ struct QueueView: View { var body: some View { NavigationStack { ScrollViewReader { scroller in - List(selection: $selection) { + // Bind selection only while editing so SwiftUI List doesn't accept selections + // outside edit mode. + List(selection: editMode.isEditing ? $selection : nil) { Section { ForEach(songs, id: \.index) { song in row(song) @@ -64,6 +66,7 @@ struct QueueView: View { } } .onChange(of: shown?.id) { _, _ in + // Selection holds row indices scoped to one playlist; clear on playlist switch. selection = [] scrollToPlaying(scroller) } @@ -153,33 +156,41 @@ struct QueueView: View { } private func row(_ song: Song) -> some View { - Button { + let content = MediaRow( + title: song.title, + meta: [song.artist, song.album].filter { !$0.isEmpty }.joined(separator: " · "), + trailing: song.prettyLength, + playing: song.index == playingIndex + ) { + SongThumbnail() + } + return Group { if editMode.isEditing { - toggle(song) + // Let List handle edit-mode selection via .tag(song.index); a Button intercepts row + // taps. + content } else { - play(song) - } - } label: { - MediaRow( - title: song.title, - meta: [song.artist, song.album].filter { !$0.isEmpty }.joined(separator: " · "), - trailing: song.prettyLength, - playing: song.index == playingIndex - ) { - SongThumbnail() + Button { + play(song) + } label: { + content + } } } .buttonStyle(.plain) .listRowBackground(selection.contains(song.index) ? Palette.secondaryContainer : Palette.surface) .listRowSeparator(.hidden) + .tag(song.index) .id(song.index) .accessibilityIdentifier("song-\(song.index)") .contextMenu { - Button("Play", systemImage: "play") { - play(song) - } - Button("Remove from playlist", systemImage: "trash", role: .destructive) { - remove([song]) + if !editMode.isEditing { + Button("Play", systemImage: "play") { + play(song) + } + Button("Remove from playlist", systemImage: "trash", role: .destructive) { + remove([song]) + } } } } @@ -277,14 +288,6 @@ struct QueueView: View { title: playlist.name) } - private func toggle(_ song: Song) { - if selection.contains(song.index) { - selection.remove(song.index) - } else { - selection.insert(song.index) - } - } - private func endSelection() { selection = [] editMode = .inactive diff --git a/App/Resources/Localizable.xcstrings b/App/Resources/Localizable.xcstrings index 4d8534f..f01e3ff 100644 --- a/App/Resources/Localizable.xcstrings +++ b/App/Resources/Localizable.xcstrings @@ -175,6 +175,9 @@ } } }, + "%@ free on this iPad" : { + "comment" : "Navigation subtitle showing free storage space on the iPad." + }, "%@ free on this phone" : { "localizations" : { "cs" : { @@ -4875,6 +4878,7 @@ } }, "Ban" : { + "extractionState" : "stale", "localizations" : { "ca" : { "stringUnit" : { @@ -5035,6 +5039,7 @@ } }, "Banned on Last.fm" : { + "extractionState" : "stale", "localizations" : { "ca" : { "stringUnit" : { @@ -6076,6 +6081,9 @@ } } }, + "Clementine closed the connection." : { + "comment" : "Shortcut and widget error when Clementine rejects or closes a control command connection." + }, "Clementine creates the playlist and shows it." : { "localizations" : { "cs" : { @@ -6626,6 +6634,7 @@ } }, "Clementine only accepts connections from its local network." : { + "comment" : "Shortcut and widget error when Clementine refuses connections outside its local network.", "localizations" : { "cs" : { "stringUnit" : { @@ -7242,6 +7251,12 @@ } } }, + "Configure this in Clementine on your computer." : { + "comment" : "Fallback status under a kept rule when Clementine needs setup without providing a custom message." + }, + "Configure this service in Clementine on your computer." : { + "comment" : "Fallback message when an internet service needs setup in Clementine without custom instructions." + }, "Connect" : { "localizations" : { "ca" : { @@ -12268,6 +12283,7 @@ } }, "Enter the auth code shown in Clementine's Network Remote settings." : { + "comment" : "Shortcut and widget error when Clementine rejects the saved auth code.", "localizations" : { "el" : { "stringUnit" : { @@ -18124,6 +18140,9 @@ } } }, + "Play on this iPad" : { + "comment" : "A button in the dialog when connecting fails on iPad: play the music saved on the iPad instead of connecting." + }, "Play on this phone" : { "comment" : "A button in the dialog when connecting fails, and a shortcut on the app's icon: play the music saved on the phone instead of connecting.", "localizations" : { @@ -22891,7 +22910,11 @@ } } }, + "Show a button to love songs." : { + "comment" : "Settings toggle subtitle under Last.fm." + }, "Show buttons to love and ban songs." : { + "extractionState" : "stale", "localizations" : { "ca" : { "stringUnit" : { diff --git a/App/Search/SearchModel.swift b/App/Search/SearchModel.swift index 80037a9..b94cc65 100644 --- a/App/Search/SearchModel.swift +++ b/App/Search/SearchModel.swift @@ -13,6 +13,7 @@ final class SearchModel: SearchResults { /// Bumped when results arrive, so screens reload them. private(set) var revision = 0 private(set) var icons: [String: UIImage] = [:] + private var iconData: [String: Data] = [:] private let store = SearchStore() private unowned let model: AppModel @@ -52,8 +53,11 @@ final class SearchModel: SearchResults { if finished { isSearching = false } - guard sections != self.sections || icons.count != self.icons.count else { return } + // Compare the raw icon Data so a replaced icon still applies even if the entry count + // didn't change, and unchanged icons aren't decoded again on every search chunk. + guard sections != self.sections || icons != self.iconData else { return } self.sections = sections + self.iconData = icons self.icons = icons.compactMapValues(UIImage.init(data:)) revision += 1 } diff --git a/App/Settings/SettingsView.swift b/App/Settings/SettingsView.swift index 618776c..00ca4d7 100644 --- a/App/Settings/SettingsView.swift +++ b/App/Settings/SettingsView.swift @@ -18,6 +18,8 @@ struct SettingsView: View { @AppStorage(SettingKey.albumFolder) private var albumFolder = true @AppStorage(SettingKey.autoConnect) private var autoConnect = true @AppStorage(SettingKey.port) private var port = Int(RemoteProtocol.defaultPort) + @State private var portText = "" + @FocusState private var portFocused: Bool @AppStorage(SettingKey.keepScreenOn) private var keepScreenOn = false @AppStorage(SettingKey.renderer) private var renderer = true @AppStorage(SettingKey.crashReports) private var crashReports = true @@ -53,7 +55,7 @@ struct SettingsView: View { } Toggle(isOn: $showLastFM) { Text("Last.fm") - Text("Show buttons to love and ban songs.") + Text("Show a button to love songs.", comment: "Settings toggle subtitle under Last.fm.") } } @@ -122,14 +124,37 @@ struct SettingsView: View { Text("Clementine can send its music here, when it plays on other devices. Takes effect the next time the app connects.") } LabeledContent("Port") { - TextField("Port", value: $port, format: .number.grouping(.never)) + // Edit a draft string instead of binding directly to @AppStorage so clearing or + // typing intermediate digits doesn't snap back to 5500 mid-edit; commit on blur + // or via the keyboard Done button since .numberPad has no Return key. + TextField("Port", text: $portText) .keyboardType(.numberPad) .multilineTextAlignment(.trailing) + .focused($portFocused) + .onSubmit { commitPort() } + .onAppear { portText = String(validatedPort(port)) } .onChange(of: port) { _, value in - if !(1...65535).contains(value) { - port = Int(RemoteProtocol.defaultPort) + // Avoid overwriting what the user is currently typing. + if !portFocused { + portText = String(validatedPort(value)) } } + .onChange(of: portFocused) { _, focused in + if !focused { + commitPort() + } + } + } + } + .toolbar { + ToolbarItemGroup(placement: .keyboard) { + if portFocused { + Spacer() + Button("Done") { + commitPort() + portFocused = false + } + } } } @@ -178,6 +203,22 @@ struct SettingsView: View { .scrollContentBackground(.hidden) .background(Palette.surface) } + + private func validatedPort(_ value: Int) -> Int { + (1...65535).contains(value) ? value : Int(RemoteProtocol.defaultPort) + } + + private func commitPort() { + let trimmed = portText.trimmingCharacters(in: .whitespaces) + if let parsed = Int(trimmed), (1...65535).contains(parsed) { + port = parsed + portText = String(parsed) + } else { + let valid = validatedPort(port) + port = valid + portText = String(valid) + } + } } extension Appearance { diff --git a/App/Streaming/AVPlayback.swift b/App/Streaming/AVPlayback.swift index 40e745a..a8b5d36 100644 --- a/App/Streaming/AVPlayback.swift +++ b/App/Streaming/AVPlayback.swift @@ -8,20 +8,77 @@ import ClementineKit final class AVPlayback: Playback { weak var listener: PlaybackListener? + /// Holds KVO, notification, and timer tokens behind an NSLock so `deinit` (which is + /// nonisolated on a @MainActor class) can always tear them down if `stop()` wasn't called. + private final class CleanupBag: @unchecked Sendable { + private let lock = NSLock() + private var kvo: NSKeyValueObservation? + private var routeObserver: NSObjectProtocol? + private var timer: Timer? + + func attach(kvo: NSKeyValueObservation, routeObserver: NSObjectProtocol, timer: Timer) { + lock.lock() + let oldKVO = self.kvo + let oldRoute = self.routeObserver + let oldTimer = self.timer + self.kvo = kvo + self.routeObserver = routeObserver + self.timer = timer + lock.unlock() + oldKVO?.invalidate() + if let oldRoute { NotificationCenter.default.removeObserver(oldRoute) } + oldTimer?.invalidate() + } + + func clear() { + lock.lock() + let kvo = self.kvo + let routeObserver = self.routeObserver + let timer = self.timer + self.kvo = nil + self.routeObserver = nil + self.timer = nil + lock.unlock() + kvo?.invalidate() + if let routeObserver { NotificationCenter.default.removeObserver(routeObserver) } + timer?.invalidate() + } + + deinit { + clear() + } + } + + private let onActivateAudio: @MainActor () -> Void + private let onDeactivateAudio: @MainActor () -> Void + private var player: AVQueuePlayer? private var volume: Float = 1 /// What's playing, and what's queued to follow it. Kept here rather than read from the /// player, which may have moved on by the time it says an item ended. private var current: AVPlayerItem? private var queued: AVPlayerItem? - /// KVO can call back on any thread: its handlers are @Sendable and hop to the main actor. - private var playerObservation: NSKeyValueObservation? + /// Monotonic counter so async `AVPlayerItem.seek` completions ignore superseded seeks or clears. + private var seekGeneration: UInt64 = 0 + private let cleanup = CleanupBag() /// Per item: its status, and the notifications of its end. private var itemObservations: [ObjectIdentifier: [Any]] = [:] /// Per item: the bytes it has fetched that are already counted in [Traffic]. private var counted: [ObjectIdentifier: Int] = [:] - /// Counts what's being fetched while there's a player. - private var trafficTimer: Timer? + + init( + onActivateAudio: @escaping @MainActor () -> Void = { + let session = AVAudioSession.sharedInstance() + try? session.setCategory(.playback, mode: .default, policy: .longFormAudio) + try? session.setActive(true) + }, + onDeactivateAudio: @escaping @MainActor () -> Void = { + try? AVAudioSession.sharedInstance().setActive(false, options: [.notifyOthersOnDeactivation]) + } + ) { + self.onActivateAudio = onActivateAudio + self.onDeactivateAudio = onDeactivateAudio + } var state: PlaybackState { guard let player, let current else { return .idle } @@ -50,15 +107,25 @@ final class AVPlayback: Playback { } func load(_ source: PlaybackSource, startMs: Int64, playing: Bool) { - activateSession() + onActivateAudio() let player = makePlayer() clear() let item = makeItem(source) current = item player.insert(item, after: nil) if startMs > 0 { - item.seek(to: CMTime(value: startMs, timescale: 1000), toleranceBefore: .zero, toleranceAfter: .zero, - completionHandler: nil) + let generation = seekGeneration + item.seek( + to: CMTime(value: startMs, timescale: 1000), + toleranceBefore: .zero, toleranceAfter: .zero + ) { @Sendable [weak self, weak item] _ in + // Notify only once AVPlayerItem finishes seeking so Desktop gets the post-seek + // timestamp rather than the pre-seek position. + Task { @MainActor in + guard let self, let item, item === self.current, self.seekGeneration == generation else { return } + self.listener?.playbackSeeked() + } + } } player.volume = volume if playing { @@ -85,7 +152,7 @@ final class AVPlayback: Playback { } func play() { - activateSession() + onActivateAudio() player?.play() } @@ -94,8 +161,18 @@ final class AVPlayback: Playback { } func seek(toMs positionMs: Int64) { - current?.seek(to: CMTime(value: positionMs, timescale: 1000), toleranceBefore: .zero, toleranceAfter: .zero, - completionHandler: nil) + guard let item = current else { return } + seekGeneration &+= 1 + let generation = seekGeneration + item.seek( + to: CMTime(value: positionMs, timescale: 1000), + toleranceBefore: .zero, toleranceAfter: .zero + ) { @Sendable [weak self, weak item] _ in + Task { @MainActor in + guard let self, let item, item === self.current, self.seekGeneration == generation else { return } + self.listener?.playbackSeeked() + } + } } func setVolume(_ volume: Float) { @@ -107,7 +184,9 @@ final class AVPlayback: Playback { guard let player else { return } player.pause() clear() - try? AVAudioSession.sharedInstance().setActive(false, options: [.notifyOthersOnDeactivation]) + cleanup.clear() + self.player = nil + onDeactivateAudio() listener?.playbackStateChanged() } @@ -119,14 +198,24 @@ final class AVPlayback: Playback { } let player = AVQueuePlayer() player.actionAtItemEnd = .advance - playerObservation = player.observe(\.timeControlStatus) { @Sendable [weak self] _, _ in + let playerObservation = player.observe(\.timeControlStatus) { @Sendable [weak self] _, _ in Task { @MainActor in self?.listener?.playbackStateChanged() } } + let routeObserver = NotificationCenter.default.addObserver( + forName: AVAudioSession.routeChangeNotification, object: AVAudioSession.sharedInstance(), queue: .main + ) { [weak self] notification in + // Pause when headphones or Bluetooth disconnect instead of playing out of the speaker. + let reason = (notification.userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt) + .flatMap(AVAudioSession.RouteChangeReason.init(rawValue:)) + guard reason == .oldDeviceUnavailable else { return } + MainActor.assumeIsolated { self?.pause() } + } self.player = player // Twice a second, as the connection sheet reads it. - trafficTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { [weak self] _ in + let trafficTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { [weak self] _ in MainActor.assumeIsolated { self?.countTraffic() } } + cleanup.attach(kvo: playerObservation, routeObserver: routeObserver, timer: trafficTimer) return player } @@ -146,12 +235,6 @@ final class AVPlayback: Playback { counted[id] = fetched } - private func activateSession() { - let session = AVAudioSession.sharedInstance() - try? session.setCategory(.playback, mode: .default, policy: .longFormAudio) - try? session.setActive(true) - } - private func makeItem(_ source: PlaybackSource) -> AVPlayerItem { // Clementine's URLs have no extension: the type it gives says what the audio is. var options: [String: Any] = [:] @@ -165,6 +248,7 @@ final class AVPlayback: Playback { /// Removes what's playing and queued. private func clear() { + seekGeneration &+= 1 for item in [current, queued].compactMap({ $0 }) { forget(item) } @@ -176,23 +260,32 @@ final class AVPlayback: Playback { private func watch(_ item: AVPlayerItem) { let center = NotificationCenter.default let id = ObjectIdentifier(item) + // Capture item weakly and check object identity (===) so late callbacks can't collide with + // reused ObjectIdentifiers after an item is forgotten. itemObservations[id] = [ - item.observe(\.status) { @Sendable [weak self] item, _ in - let failure = item.status == .failed ? AVPlayback.describe(item.error) : nil + item.observe(\.status) { @Sendable [weak self, weak item] observed, _ in + let failure = observed.status == .failed ? AVPlayback.describe(observed.error) : nil Task { @MainActor in - self?.listener?.playbackStateChanged() + guard let self, let item, item === self.current || item === self.queued else { return } + self.listener?.playbackStateChanged() if let failure { - self?.failed(id, message: failure.message, transient: failure.transient) + self.failed(item, message: failure.message, transient: failure.transient) } } }, - center.addObserver(forName: AVPlayerItem.didPlayToEndTimeNotification, object: item, queue: .main) { [weak self] _ in - MainActor.assumeIsolated { self?.ended(id) } + center.addObserver(forName: AVPlayerItem.didPlayToEndTimeNotification, object: item, queue: .main) { [weak self, weak item] _ in + MainActor.assumeIsolated { + guard let item else { return } + self?.ended(item) + } }, - center.addObserver(forName: AVPlayerItem.failedToPlayToEndTimeNotification, object: item, queue: .main) { [weak self] notification in + center.addObserver(forName: AVPlayerItem.failedToPlayToEndTimeNotification, object: item, queue: .main) { [weak self, weak item] notification in // Stopping partway through is the network's doing: worth loading again. let message = AVPlayback.describe(notification.userInfo?[AVPlayerItemFailedToPlayToEndTimeErrorKey] as? Error).message - MainActor.assumeIsolated { self?.failed(id, message: message, transient: true) } + MainActor.assumeIsolated { + guard let item else { return } + self?.failed(item, message: message, transient: true) + } }, ] } @@ -209,9 +302,10 @@ final class AVPlayback: Playback { } } - /// Item [id] played to its end: the queued item follows, if there's one. - private func ended(_ id: ObjectIdentifier) { - guard let ended = current, ObjectIdentifier(ended) == id else { return } + /// [item] played to its end: the queued item follows, if there's one. + private func ended(_ item: AVPlayerItem) { + guard let ended = current, ended === item else { return } + seekGeneration &+= 1 forget(ended) current = queued queued = nil @@ -222,19 +316,35 @@ final class AVPlayback: Playback { } } - private func failed(_ id: ObjectIdentifier, message: String, transient: Bool) { + private func failed(_ item: AVPlayerItem, message: String, transient: Bool) { // Only the item playing matters: a queued one is loaded again if Clementine sends it. - guard let current, ObjectIdentifier(current) == id else { return } + guard let current, current === item else { return } listener?.playbackFailed(message, transient: transient) } /// What went wrong, and whether it's the network's doing, worth trying again. private nonisolated static func describe(_ error: Error?) -> (message: String, transient: Bool) { guard let error = error as NSError? else { return ("Playback failed", false) } - let network = error.domain == NSURLErrorDomain && [ + return (error.localizedDescription, isTransientNetwork(error)) + } + + private nonisolated static func isTransientNetwork(_ error: NSError) -> Bool { + if error.domain == NSURLErrorDomain, [ NSURLErrorNetworkConnectionLost, NSURLErrorNotConnectedToInternet, NSURLErrorTimedOut, - NSURLErrorCannotConnectToHost, - ].contains(error.code) - return (error.localizedDescription, network) + NSURLErrorCannotConnectToHost, NSURLErrorCannotFindHost, NSURLErrorDNSLookupFailed, + NSURLErrorResourceUnavailable, + ].contains(error.code) { + return true + } + if error.domain == NSPOSIXErrorDomain, [ + Int(ECONNRESET), Int(ETIMEDOUT), Int(ENETDOWN), Int(ENETUNREACH), Int(EHOSTUNREACH), Int(EPIPE), + ].contains(error.code) { + return true + } + if let underlying = error.userInfo[NSUnderlyingErrorKey] as? NSError { + // AVFoundation often wraps the real NSURL/POSIX network drop inside NSUnderlyingErrorKey. + return isTransientNetwork(underlying) + } + return false } } diff --git a/App/Streaming/NowPlaying.swift b/App/Streaming/NowPlaying.swift index 977a9fa..52fef30 100644 --- a/App/Streaming/NowPlaying.swift +++ b/App/Streaming/NowPlaying.swift @@ -65,8 +65,10 @@ final class NowPlaying { if let duration = phone.duration { info[MPMediaItemPropertyPlaybackDuration] = duration } + if let artwork = artwork(from: phone.artwork) { + info[MPMediaItemPropertyArtwork] = artwork + } MPNowPlayingInfoCenter.default().nowPlayingInfo = info - cover = nil setCommandsEnabled(true) setSeekEnabled(phone.duration != nil) return @@ -103,7 +105,17 @@ final class NowPlaying { /// with the item, and the two can arrive in either order: the cover is only the item's once /// they're the same song. private func artwork(for item: RenderItem) -> MPMediaItemArtwork? { - guard let song = model.session.song, song.url == item.song.url, let data = song.artData else { + guard let song = model.session.song, song.url == item.song.url else { + return nil + } + return artwork(from: song.artData) + } + + /// Shared artwork cache for both remote streaming and local phone playback; only clears + /// `cover` when no image data is present so position updates don't wipe or re-decode it. + private func artwork(from data: Data?) -> MPMediaItemArtwork? { + guard let data, !data.isEmpty else { + cover = nil return nil } if let cover, cover.data == data { diff --git a/App/Support/VolumeButtons.swift b/App/Support/VolumeButtons.swift index 78f4251..f045030 100644 --- a/App/Support/VolumeButtons.swift +++ b/App/Support/VolumeButtons.swift @@ -39,13 +39,10 @@ final class VolumeButtonController { private func start() { guard observation == nil else { return } + // Arbitrate the shared AVAudioSession through AppModel so volume buttons never downgrade + // active playback to .ambient. + guard model.activateVolumeButtonSession() else { return } let audio = AVAudioSession.sharedInstance() - do { - try audio.setCategory(.ambient, options: [.mixWithOthers]) - try audio.setActive(true) - } catch { - return - } reference = audio.outputVolume // At either end, a press one way wouldn't register. if reference <= 0.05 || reference >= 0.95 { @@ -61,10 +58,7 @@ final class VolumeButtonController { guard observation != nil else { return } observation?.invalidate() observation = nil - // While Clementine plays here, the session is the renderer's, playing. - if model.renderer.item == nil { - try? AVAudioSession.sharedInstance().setActive(false, options: [.notifyOthersOnDeactivation]) - } + model.deactivateAudioSessionIfIdle(includingVolumeButtons: true) } private func changed(to volume: Float) { @@ -110,8 +104,10 @@ struct VolumeButtonsView: UIViewRepresentable { } func updateUIView(_ view: MPVolumeView, context: Context) { + // Pass SwiftUI-tracked enabled and scenePhase so updates re-evaluate alongside AppModel's + // observable playback state. context.coordinator.update( - enabled: enabled && scenePhase == .active && model.session.status.isActive && !model.session.isPlayingHere) + enabled: model.volumeButtonsShouldBeActive(enabled: enabled, scenePhase: scenePhase)) } static func dismantleUIView(_ view: MPVolumeView, coordinator: VolumeButtonController) { diff --git a/App/Theme/Components.swift b/App/Theme/Components.swift index 64bd55a..bc2c41b 100644 --- a/App/Theme/Components.swift +++ b/App/Theme/Components.swift @@ -86,15 +86,41 @@ struct PlayPauseButton: View { var iconSize: CGFloat = 36 let action: () -> Void var longPress: (() -> Void)? + // simultaneousGesture(LongPressGesture) preserves the button's pressed style, so Button's tap + // still fires on lift unless suppressed; isPressing resets the flag if the user drags off to + // cancel the tap without consuming it. + @State private var suppressNextTap = false + @GestureState private var isPressing = false var body: some View { - Button(action: action) { + Button { + if suppressNextTap { + suppressNextTap = false + } else { + action() + } + } label: { Image(systemName: playing ? "pause.fill" : "play.fill") .font(.system(size: iconSize)) .contentTransition(.symbolEffect(.replace)) } .buttonStyle(PlayPauseStyle(width: width, height: height)) - .simultaneousGesture(LongPressGesture().onEnded { _ in longPress?() }) + .simultaneousGesture( + LongPressGesture() + .updating($isPressing) { pressing, state, _ in + state = pressing + } + .onEnded { _ in + guard let longPress else { return } + suppressNextTap = true + longPress() + } + ) + .onChange(of: isPressing) { _, pressing in + if pressing { + suppressNextTap = false + } + } .accessibilityLabel(playing ? "Pause" : "Play") .accessibilityAction(named: "Stop after this song") { longPress?() } .accessibilityIdentifier("playPause") @@ -295,6 +321,19 @@ func formatBytes(_ bytes: Int64) -> String { ByteCountFormatter.string(fromByteCount: bytes, countStyle: .binary) } +/// Device-specific wording and SF Symbol matching "On this phone" vs "On this iPad". +enum ThisDevice { + @MainActor static var systemImage: String { + UIDevice.current.userInterfaceIdiom == .pad ? "ipad" : "iphone" + } + + @MainActor static var label: String { + UIDevice.current.userInterfaceIdiom == .pad + ? String(localized: "On this iPad", comment: "As \"On this phone\", on an iPad: music saved on the iPad, as opposed to Clementine on the computer.") + : String(localized: "On this phone") + } +} + extension ShuffleMode { var label: LocalizedStringResource { switch self { diff --git a/App/Watch/WatchLink.swift b/App/Watch/WatchLink.swift index 2b73bc9..de9e845 100644 --- a/App/Watch/WatchLink.swift +++ b/App/Watch/WatchLink.swift @@ -70,22 +70,36 @@ final class WatchLink: NSObject { return name.isEmpty ? model.settings.lastHost : name } - /// The cover, made small enough to send. + /// The cover, made small enough to stay comfortably within WatchConnectivity's 65 KB payload + /// budget (including base64 JSON reply mode). private func smallCover(_ data: Data?) -> Data? { guard data != coverSource else { return cover } coverSource = data cover = data.flatMap(UIImage.init(data:)).flatMap { image in - let side = Self.coverSize - let format = UIGraphicsImageRendererFormat() - format.scale = 1 - let scaled = UIGraphicsImageRenderer(size: CGSize(width: side, height: side), format: format).image { _ in - // Fill the square, cropping a cover that isn't. - let scale = max(side / image.size.width, side / image.size.height) - let size = CGSize(width: image.size.width * scale, height: image.size.height * scale) - image.draw(in: CGRect( - x: (side - size.width) / 2, y: (side - size.height) / 2, width: size.width, height: size.height)) + // 36 KB raw JPEG expands to ~48 KB in base64 JSON replies, leaving room for metadata + // under WatchConnectivity's 65 KB payload limit. + let maxBytes = 36_000 + for (side, quality) in [ + (Self.coverSize, CGFloat(0.6)), + (Self.coverSize, CGFloat(0.4)), + (CGFloat(240), CGFloat(0.45)), + (CGFloat(180), CGFloat(0.35)), + ] { + let format = UIGraphicsImageRendererFormat() + format.scale = 1 + let scaled = UIGraphicsImageRenderer(size: CGSize(width: side, height: side), format: format).image { _ in + // Fill the square, cropping a cover that isn't. + let scale = max(side / image.size.width, side / image.size.height) + let size = CGSize(width: image.size.width * scale, height: image.size.height * scale) + image.draw(in: CGRect( + x: (side - size.width) / 2, y: (side - size.height) / 2, width: size.width, height: size.height)) + } + if let jpeg = scaled.jpegData(compressionQuality: quality), jpeg.count <= maxBytes { + return jpeg + } } - return scaled.jpegData(compressionQuality: 0.6) + // Drop oversized artwork rather than failing delivery of playback state. + return nil } return cover } @@ -147,7 +161,8 @@ final class WatchLink: NSObject { case .disconnected: guard !model.settings.lastHost.isEmpty else { return false } let name = model.settings.lastServerName - model.connect(host: model.settings.lastHost, name: name.isEmpty ? nil : name) + // Include the saved port so Watch-triggered connects work with non-default ports. + model.connect(host: model.settings.lastHost, port: model.settings.lastPort, name: name.isEmpty ? nil : name) case .connecting, .downloadingData, .reconnecting: break } diff --git a/ClementineRemote.xcodeproj/project.pbxproj b/ClementineRemote.xcodeproj/project.pbxproj index b79dd0d..21dec9b 100644 --- a/ClementineRemote.xcodeproj/project.pbxproj +++ b/ClementineRemote.xcodeproj/project.pbxproj @@ -10,6 +10,7 @@ 015B3D7098D15696CE753DCA /* LibraryView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4806AC63E537A5050C1E6BD /* LibraryView.swift */; }; 02B054CAB79B78B9185BBFC3 /* InternetView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D46866E6F5E51462F605F0CA /* InternetView.swift */; }; 05AD1BE1767A45392CD494C5 /* ClementineWatch in Frameworks */ = {isa = PBXBuildFile; productRef = D1190B34E085877802608D00 /* ClementineWatch */; }; + 0A1647092676A3852AD79904 /* Theme.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4856A6293D1829361A2A9A17 /* Theme.swift */; }; 0B99087E44B26407F87B9201 /* ClementineRemoteWatchApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6944EAAD175AE565B5AE573E /* ClementineRemoteWatchApp.swift */; }; 10F30E7ECA7C1265A6F085C4 /* Sentry-Dynamic in Frameworks */ = {isa = PBXBuildFile; productRef = F6D75D7AD5992D41069F4420 /* Sentry-Dynamic */; }; 198DA2CE0EAEC3C225F8AC81 /* SwiftUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 761E362C08E663B70599A6DD /* SwiftUI.framework */; }; @@ -732,6 +733,7 @@ 5B2423FA1DE74D6BB9A80BBC /* ClementineWidget.swift in Sources */, 1DBC787744D19CBA495822CC /* CommandIntents.swift in Sources */, 35E7D5066C04B7AD89E61632 /* SharedState.swift in Sources */, + 0A1647092676A3852AD79904 /* Theme.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/Packages/ClementineKit/Sources/ClementineKit/Session/RemoteSession.swift b/Packages/ClementineKit/Sources/ClementineKit/Session/RemoteSession.swift index 1dddb01..4979e44 100644 --- a/Packages/ClementineKit/Sources/ClementineKit/Session/RemoteSession.swift +++ b/Packages/ClementineKit/Sources/ClementineKit/Session/RemoteSession.swift @@ -471,12 +471,6 @@ public final class RemoteSession { send(RemoteMessage(.love)) } - /// Bans the current song on Last.fm. - public func ban() { - guard song != nil else { return } - send(RemoteMessage(.ban)) - } - /// Sets Clementine's volume, from 0 to 100. public func setVolume(_ percent: Int) { volume = max(0, min(100, percent)) diff --git a/Shared/CommandIntents.swift b/Shared/CommandIntents.swift index b0a87c7..0299a1f 100644 --- a/Shared/CommandIntents.swift +++ b/Shared/CommandIntents.swift @@ -16,20 +16,49 @@ extension CommandIntent { do { try await RemoteCommand.send(message, to: endpoint, authCode: state.authCode) } catch { - throw CommandError.unreachable + throw Self.mapError(error) } return .result() } + + /// Maps server-side disconnect causes separately so auth and local-network rejections aren't + /// reported as generic unreachability. + static func mapError(_ error: Error) -> CommandError { + guard let remoteError = error as? RemoteCommandError else { return .unreachable } + switch remoteError { + case .disconnected(.wrongAuthCode), .disconnected(.notAuthenticated): + return .wrongAuthCode + case .disconnected(.notLocalNetwork): + return .notLocalNetwork + case .disconnected: + return .refused + } + } } enum CommandError: Error, CustomLocalizedStringResourceConvertible { case noClementine case unreachable + case wrongAuthCode + case notLocalNetwork + case refused var localizedStringResource: LocalizedStringResource { switch self { case .noClementine: "Connect to Clementine in Clementine Remote first." case .unreachable: "Couldn't reach Clementine." + case .wrongAuthCode: + LocalizedStringResource( + "Enter the auth code shown in Clementine's Network Remote settings.", + comment: "Shortcut and widget error when Clementine rejects the saved auth code.") + case .notLocalNetwork: + LocalizedStringResource( + "Clementine only accepts connections from its local network.", + comment: "Shortcut and widget error when Clementine refuses connections outside its local network.") + case .refused: + LocalizedStringResource( + "Clementine closed the connection.", + comment: "Shortcut and widget error when Clementine rejects or closes a control command connection.") } } } @@ -57,7 +86,7 @@ struct PlayPauseIntent: CommandIntent { do { try await RemoteCommand.send(message, to: endpoint, authCode: state.authCode) } catch { - throw CommandError.unreachable + throw Self.mapError(error) } // Show the change at once in the widget. var changed = state diff --git a/WatchApp/NowPlayingView.swift b/WatchApp/NowPlayingView.swift index c191ca7..d1a20cf 100644 --- a/WatchApp/NowPlayingView.swift +++ b/WatchApp/NowPlayingView.swift @@ -55,8 +55,10 @@ private struct PlayerView: View { Button { link.send(.love) } label: { + // Use white rather than Palette.onPrimary (dark brown on orange), which is + // nearly invisible against watchOS's dark translucent toolbar. Label("Love", systemImage: state.isLoved ? "heart.fill" : "heart") - .foregroundStyle(Palette.onPrimary) + .foregroundStyle(.white) } .disabled(state.isLoved) } @@ -167,20 +169,26 @@ private struct Backdrop: View { .resizable() .scaledToFill() } else { - Palette.surfaceContainerHighest - Group { - if hasSong { - Image(systemName: "music.note") - .font(.system(size: 56)) - .foregroundStyle(Palette.onSurfaceVariant) - } else { - Image("ClementineMark") - .resizable() - .scaledToFit() - .frame(width: 80) + // Scale placeholder art and vertical offset proportionally so smaller watch screens + // don't overlap the bottom song info and transport controls. + GeometryReader { geometry in + ZStack { + Palette.surfaceContainerHighest + Group { + if hasSong { + Image(systemName: "music.note") + .font(.system(size: min(56, geometry.size.width * 0.28))) + .foregroundStyle(Palette.onSurfaceVariant) + } else { + Image("ClementineMark") + .resizable() + .scaledToFit() + .frame(width: min(80, geometry.size.width * 0.4)) + } + } + .offset(y: -geometry.size.height * 0.16) } } - .offset(y: -64) } LinearGradient( stops: [ @@ -201,27 +209,35 @@ private struct Transport: View { @Environment(PhoneLink.self) private var link var body: some View { - HStack { - Button("Previous", systemImage: "backward.end.fill") { link.send(.previous) } - .foregroundStyle(.white) + // Tighten button widths on narrower watches (< 175pt) so Previous/Next stay tappable; pin + // height because GeometryReader otherwise expands greedily. + GeometryReader { geometry in + let compact = geometry.size.width < 175 + let playWidth: CGFloat = compact ? min(64, geometry.size.width * 0.38) : 76 + let playHeight: CGFloat = compact ? 52 : 60 + HStack { + Button("Previous", systemImage: "backward.end.fill") { link.send(.previous) } + .foregroundStyle(.white) + .buttonStyle(.plain) + .frame(maxWidth: .infinity, minHeight: compact ? 46 : 52) + Button(isPlaying ? "Pause" : "Play", systemImage: isPlaying ? "pause.fill" : "play.fill") { + link.send(.playPause) + } + .font(compact ? .title2 : .title) + .foregroundStyle(Palette.onPrimaryContainer) .buttonStyle(.plain) - .frame(maxWidth: .infinity, minHeight: 52) - Button(isPlaying ? "Pause" : "Play", systemImage: isPlaying ? "pause.fill" : "play.fill") { - link.send(.playPause) + .frame(width: playWidth, height: playHeight) + .background(Palette.primaryContainer, in: .rect(cornerRadius: compact ? 16 : 20)) + Button("Next", systemImage: "forward.end.fill") { link.send(.next) } + .foregroundStyle(.white) + .buttonStyle(.plain) + .frame(maxWidth: .infinity, minHeight: compact ? 46 : 52) } - .font(.title) - .foregroundStyle(Palette.onPrimaryContainer) - .buttonStyle(.plain) - .frame(width: 76, height: 60) - .background(Palette.primaryContainer, in: .rect(cornerRadius: 20)) - Button("Next", systemImage: "forward.end.fill") { link.send(.next) } - .foregroundStyle(.white) - .buttonStyle(.plain) - .frame(maxWidth: .infinity, minHeight: 52) + .labelStyle(.iconOnly) + .font(compact ? .title3 : .title2) + .environment(\.layoutDirection, .leftToRight) } - .labelStyle(.iconOnly) - .font(.title2) - .environment(\.layoutDirection, .leftToRight) + .frame(height: 60) } } @@ -273,6 +289,8 @@ private struct NotConnectedView: View { .padding(.top, 4) } } + // Keep error copy clear of curved watch screen edges. + .padding(.horizontal, 8) .frame(maxWidth: .infinity) } } diff --git a/WatchApp/PhoneLink.swift b/WatchApp/PhoneLink.swift index 9feb547..0833dec 100644 --- a/WatchApp/PhoneLink.swift +++ b/WatchApp/PhoneLink.swift @@ -90,8 +90,19 @@ final class PhoneLink: NSObject { } } + // Replies to sendMessageData arrive as Data (with base64 cover in JSON), whereas application + // context and push messages arrive as dictionaries with a separate raw cover Data key. private func received(_ data: Data?) { guard let state = WatchLinkCoding.decodeState(data) else { return } + apply(state) + } + + private func received(_ dictionary: [String: Any]) { + guard let state = WatchLinkCoding.decodeState(dictionary) else { return } + apply(state) + } + + private func apply(_ state: WatchNowPlaying) { isPhoneUnreachable = false if isAskingToConnect, state.connection != .connecting { isAskingToConnect = false @@ -112,24 +123,31 @@ extension PhoneLink: WCSessionDelegate { nonisolated func session( _ session: WCSession, activationDidCompleteWith state: WCSessionActivationState, error: Error? ) { - let data = session.receivedApplicationContext[WatchLinkCoding.stateKey] as? Data + let context = SendableDictionary(session.receivedApplicationContext) Task { @MainActor in - self.received(data) + self.received(context.value) self.reachabilityChanged() } } nonisolated func session(_ session: WCSession, didReceiveApplicationContext context: [String: Any]) { - let data = context[WatchLinkCoding.stateKey] as? Data - Task { @MainActor in self.received(data) } + let wrapped = SendableDictionary(context) + Task { @MainActor in self.received(wrapped.value) } } nonisolated func session(_ session: WCSession, didReceiveMessage message: [String: Any]) { - let data = message[WatchLinkCoding.stateKey] as? Data - Task { @MainActor in self.received(data) } + let wrapped = SendableDictionary(message) + Task { @MainActor in self.received(wrapped.value) } } nonisolated func sessionReachabilityDidChange(_ session: WCSession) { Task { @MainActor in self.reachabilityChanged() } } } + +/// Transfers non-Sendable WatchConnectivity dictionaries across to @MainActor without stripping +/// the separate cover Data key. +private struct SendableDictionary: @unchecked Sendable { + let value: [String: Any] + init(_ value: [String: Any]) { self.value = value } +} diff --git a/Widget/ClementineWidget.swift b/Widget/ClementineWidget.swift index b36abd6..26d83f4 100644 --- a/Widget/ClementineWidget.swift +++ b/Widget/ClementineWidget.swift @@ -14,7 +14,7 @@ struct ClementineWidget: Widget { var body: some WidgetConfiguration { StaticConfiguration(kind: "Clementine", provider: Provider()) { entry in WidgetView(entry: entry) - .containerBackground(Color("Surface"), for: .widget) + .containerBackground(Palette.surface, for: .widget) } .configurationDisplayName("Clementine") .description("Play, pause and skip songs in Clementine.") @@ -55,10 +55,10 @@ struct WidgetView: View { Spacer() Text("Not connected") .font(.headline) - .foregroundStyle(Color("OnSurface")) + .foregroundStyle(Palette.onSurface) Text("Open Clementine Remote to connect") .font(.caption) - .foregroundStyle(Color("OnSurfaceVariant")) + .foregroundStyle(Palette.onSurfaceVariant) } .frame(maxWidth: .infinity, alignment: .leading) } else { @@ -71,31 +71,32 @@ struct WidgetView: View { if family != .systemSmall { Text(state.host) .font(.caption2) - .foregroundStyle(Color("OnSurfaceVariant")) + .foregroundStyle(Palette.onSurfaceVariant) + .lineLimit(1) } } Spacer(minLength: 0) Text(state.title.isEmpty ? String(localized: "No song playing") : state.title) .font(.headline) - .foregroundStyle(Color("OnSurface")) + .foregroundStyle(Palette.onSurface) .lineLimit(family == .systemSmall ? 2 : 1) if !state.artist.isEmpty { Text(state.artist) .font(.subheadline) - .foregroundStyle(Color("Primary")) + .foregroundStyle(Palette.primary) .lineLimit(1) } HStack(spacing: 8) { Button(intent: PlayPauseIntent()) { Image(systemName: state.isPlaying ? "pause.fill" : "play.fill") - .foregroundStyle(Color("OnPrimaryContainer")) + .foregroundStyle(Palette.onPrimaryContainer) .frame(width: 48, height: 36) - .background(Color("PrimaryContainer"), in: .rect(cornerRadius: 14)) + .background(Palette.primaryContainer, in: .rect(cornerRadius: 14)) } .accessibilityLabel(state.isPlaying ? "Pause" : "Play") Button(intent: NextIntent()) { Image(systemName: "forward.end.fill") - .foregroundStyle(Color("OnSurface")) + .foregroundStyle(Palette.onSurface) .frame(width: 40, height: 36) } .accessibilityLabel("Next") diff --git a/design/DESIGN.md b/design/DESIGN.md index 97a86e0..d5a0ae0 100644 --- a/design/DESIGN.md +++ b/design/DESIGN.md @@ -169,7 +169,7 @@ From the Song details sheet board. Medium and large detents, grabber, 28 pt corn Album, Genre, Year, Track, Disc, Length, Play count, Size, File. Empty values are left out. Tapping the cover thumbnail shows the cover full size. - Rating: five stars in `primary`, filled, half or empty from Clementine's rating. Tapping star *n* - rates the song *n* stars and shows "Rated *n* stars". When Last.fm buttons are on: Love and Ban. + rates the song *n* stars and shows "Rated *n* stars". When Last.fm buttons are on: Love. - Lyrics: asks Clementine for them the first time, with a spinner; shows the longest lyrics any provider found, with the provider's name, or "No lyrics found". diff --git a/project.yml b/project.yml index a093a9b..39d83b2 100644 --- a/project.yml +++ b/project.yml @@ -109,6 +109,7 @@ targets: sources: - path: Widget - path: Shared + - path: App/Theme/Theme.swift - path: App/Resources/Assets.xcassets # The app's strings and their translations: the widget's own strings are in it too. - path: App/Resources/Localizable.xcstrings diff --git a/scripts/archive.sh b/scripts/archive.sh index 1262808..be43b04 100755 --- a/scripts/archive.sh +++ b/scripts/archive.sh @@ -67,6 +67,21 @@ sign() { sign "$app/PlugIns/ClementineWidget.appex" Widget/ClementineWidget.entitlements # The Apple Watch app has no entitlements, but has to be signed for the app's signature to seal it. codesign --force --sign - "$app/Watch/ClementineRemoteWatch.app" +if [ "${TESTING_FEATURES:-NO}" != YES ]; then + # BackgroundSync is disabled unless TESTING_FEATURES=YES, so App Store builds must not declare + # unused `processing` background mode. + /usr/libexec/PlistBuddy -c 'Delete :BGTaskSchedulerPermittedIdentifiers' "$app/Info.plist" 2>/dev/null || true + if /usr/libexec/PlistBuddy -c 'Print :UIBackgroundModes' "$app/Info.plist" >/dev/null 2>&1; then + idx=0 + while mode=$(/usr/libexec/PlistBuddy -c "Print :UIBackgroundModes:$idx" "$app/Info.plist" 2>/dev/null); do + if [ "$mode" = "processing" ]; then + /usr/libexec/PlistBuddy -c "Delete :UIBackgroundModes:$idx" "$app/Info.plist" + else + idx=$((idx + 1)) + fi + done + fi +fi sign "$app" App/ClementineRemote.entitlements rm "$out/entitlements.plist"