~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/hydraulophone

An unofficial YouTube Music app for iPhone, iPad, and Mac.

0
0
main
851 lines · 31.2 KB Raw History
import CarPlay
import Combine
import HydraulophoneCore
import OSLog
import UIKit

/// Presents the existing authenticated catalog and playback queue through
/// Apple's CarPlay templates. The phone and car always share one AppModel.
@MainActor
final class CarPlaySceneDelegate: NSObject, CPTemplateApplicationSceneDelegate,
  @preconcurrency CPNowPlayingTemplateObserver
{
  private enum RootState: Equatable {
    case restoring
    case signIn
    case offline
    case online
  }

  private static let maximumRows = 40
  private let model = AppModel.shared
  private let logger = Logger(subsystem: "com.hydraulophone", category: "carplay")
  private var interfaceController: CPInterfaceController?
  private var modelSubscription: AnyCancellable?
  private var playbackSubscription: AnyCancellable?
  private var previousRootState: RootState?
  private var connectionGeneration = UUID()
  private var cachedQueueKey: String?
  private var queueTemplate: CPListTemplate?
  private var queueWindow: CarPlayListWindow?
  private var navigationRevision = 0
  private var navigationTasks: [UUID: Task<Void, Never>] = [:]
  private var repeatButton: CPNowPlayingRepeatButton?
  private var shuffleButton: CPNowPlayingShuffleButton?

  func templateApplicationScene(
    _ templateApplicationScene: CPTemplateApplicationScene,
    didConnect interfaceController: CPInterfaceController
  ) {
    connectionGeneration = UUID()
    self.interfaceController = interfaceController
    let nowPlaying = CPNowPlayingTemplate.shared
    nowPlaying.upNextTitle = "Queue"
    nowPlaying.isUpNextButtonEnabled = false
    nowPlaying.add(self)
    installPlaybackButtons(on: nowPlaying)

    modelSubscription = model.objectWillChange.sink { [weak self] in
      Task { @MainActor [weak self] in self?.refreshAuthenticationState() }
    }
    playbackSubscription = model.playback.objectWillChange.sink { [weak self] in
      Task { @MainActor [weak self] in self?.refreshPlaybackState() }
    }
    previousRootState = rootState
    setRootTemplate(makeRootTemplate(), animated: false)
    refreshPlaybackState()
    if #available(iOS 27.0, *) {
      model.playback.carPlaySceneDidConnect()
    }
    logger.info("CarPlay scene connected")
  }

  func templateApplicationScene(
    _ templateApplicationScene: CPTemplateApplicationScene,
    didDisconnectInterfaceController interfaceController: CPInterfaceController
  ) {
    guard self.interfaceController === interfaceController else { return }
    connectionGeneration = UUID()
    CPNowPlayingTemplate.shared.remove(self)
    modelSubscription = nil
    playbackSubscription = nil
    cancelNavigationTasks()
    self.interfaceController = nil
    queueTemplate = nil
    queueWindow = nil
    cachedQueueKey = nil
    if #available(iOS 27.0, *) {
      model.playback.carPlaySceneDidDisconnect()
    }
    logger.info("CarPlay scene disconnected")
  }

  func nowPlayingTemplateUpNextButtonTapped(_ nowPlayingTemplate: CPNowPlayingTemplate) {
    refreshQueueTemplate()
    guard let queueTemplate else { return }
    push(queueTemplate)
  }

  private var isAuthenticated: Bool {
    !model.isRestoringSession && !model.isSessionTransitioning
      && model.session?.isAuthenticated == true
  }

  private var rootState: RootState {
    if model.isRestoringSession || model.isSessionTransitioning { return .restoring }
    guard isAuthenticated else { return .signIn }
    return model.isOfflineOnly ? .offline : .online
  }

  private func refreshAuthenticationState() {
    guard interfaceController != nil else { return }
    let current = rootState
    guard current != previousRootState else { return }
    invalidateCatalogRequests()
    previousRootState = current
    setRootTemplate(makeRootTemplate(), animated: false)
  }

  private func captureRequestGeneration() -> CarPlayRequestGeneration {
    CarPlayRequestGeneration(
      connection: connectionGeneration,
      catalogSession: model.catalogSessionID
    )
  }

  private func isCurrent(_ generation: CarPlayRequestGeneration) -> Bool {
    interfaceController != nil
      && connectionGeneration == generation.connection
      && model.catalogSessionID == generation.catalogSession
      && isAuthenticated
      && !model.isOfflineOnly
  }

  private func invalidateCatalogRequests() {
    connectionGeneration = UUID()
    cancelNavigationTasks()
    cachedQueueKey = nil
    queueTemplate = nil
    queueWindow = nil
  }

  private func cancelNavigationTasks() {
    for task in navigationTasks.values {
      task.cancel()
    }
    navigationTasks.removeAll()
  }

  private func performNavigation(
    _ action: @escaping @MainActor () async -> Void,
    completion: @escaping @MainActor () -> Void = {}
  ) {
    let taskID = UUID()
    let task = Task { @MainActor [weak self] in
      defer {
        self?.navigationTasks[taskID] = nil
        completion()
      }
      guard !Task.isCancelled else { return }
      await action()
    }
    navigationTasks[taskID] = task
  }

  private func refreshPlaybackState() {
    guard interfaceController != nil else { return }
    let hasCurrentSong = model.playback.currentSong != nil
    let entries = model.playback.queueEntries
    let currentIndex = entries.firstIndex { $0.id == model.playback.currentQueueEntryID }
    let nowPlaying = CPNowPlayingTemplate.shared
    nowPlaying.isUpNextButtonEnabled =
      hasCurrentSong && currentIndex.map { $0 + 1 < entries.count } == true
    repeatButton?.isSelected = model.playback.repeatMode != .off
    shuffleButton?.isSelected = model.playback.isShuffling
    refreshQueueTemplate()
  }

  private func installPlaybackButtons(on template: CPNowPlayingTemplate) {
    let repeatButton = CPNowPlayingRepeatButton { [weak self] _ in
      Task { @MainActor [weak self] in self?.model.playback.cycleRepeatMode() }
    }
    let shuffleButton = CPNowPlayingShuffleButton { [weak self] _ in
      Task { @MainActor [weak self] in self?.model.playback.toggleShuffle() }
    }
    self.repeatButton = repeatButton
    self.shuffleButton = shuffleButton
    template.updateNowPlayingButtons([repeatButton, shuffleButton])
  }

  private func makeRootTemplate() -> CPListTemplate {
    let title: String
    let rows: [CPListItem]
    if model.isRestoringSession || model.isSessionTransitioning {
      title = "Hydraulophone"
      rows = [messageItem("Connecting to your library…")]
    } else if !isAuthenticated {
      title = "Sign In Required"
      rows = [messageItem("Sign in on your iPhone before using CarPlay.")]
    } else if model.isOfflineOnly {
      title = "Offline Downloads"
      rows = [
        makeItem("Downloads", detail: "Saved on this iPhone", symbol: "arrow.down.circle") {
          [weak self] in self?.openDownloads()
        },
        makeItem("Up Next", detail: "View queued tracks", symbol: "list.bullet") {
          [weak self] in await self?.showQueue()
        },
      ]
    } else {
      title = "Hydraulophone"
      rows = [
        makeItem("Home", detail: "Recommended music", symbol: "house") { [weak self] in
          await self?.openHome()
        },
        makeItem(
          "Library", detail: "Songs, playlists, albums and artists", symbol: "books.vertical"
        ) {
          [weak self] in await self?.openLibraryCategories()
        },
        makeItem("Downloads", detail: "Saved on this iPhone", symbol: "arrow.down.circle") {
          [weak self] in self?.openDownloads()
        },
        makeItem("Up Next", detail: "View and select queued tracks", symbol: "list.bullet") {
          [weak self] in await self?.showQueue()
        },
      ]
    }
    return listTemplate(title: title, items: rows)
  }

  private func makeItem(
    _ title: String, detail: String? = nil, symbol: String,
    action: @escaping @MainActor () async -> Void
  ) -> CPListItem {
    let item = CPListItem(
      text: title, detailText: detail, image: UIImage(systemName: symbol))
    item.handler = { _, completion in
      self.performNavigation(action, completion: completion)
    }
    return item
  }

  private func messageItem(_ title: String) -> CPListItem {
    let item = CPListItem(text: title, detailText: nil)
    item.isEnabled = false
    return item
  }

  private func listTemplate(title: String, items: [CPListItem]) -> CPListTemplate {
    CPListTemplate(
      title: title, sections: [CPListSection(items: Array(items.prefix(Self.maximumRows)))])
  }

  private func windowTemplate(title: String, window: CarPlayListWindow) -> CPListTemplate {
    let template = listTemplate(title: title, items: [messageItem("Loading…")])
    render(window, startingAt: 0, in: template)
    return template
  }

  private func render(
    _ window: CarPlayListWindow, startingAt start: Int, in template: CPListTemplate
  ) {
    window.displayedStartIndex = start
    let end = min(start + Self.maximumRows - 1, window.items.count)
    var items = Array(window.items[start..<end])
    if end < window.items.count {
      items.append(
        moreItem(title: "More") { [weak self, weak template] in
          guard let self, let template else { return }
          self.render(window, startingAt: end, in: template)
        })
    } else if window.continuation != nil, window.loadNextPage != nil {
      if window.isLoadingNextPage {
        items.append(messageItem("Loading more…"))
      } else {
        let title = window.failedLoadingNextPage ? "Retry loading more" : "Load more"
        items.append(
          moreItem(title: title) { [weak self, weak template] in
            guard let self, let template else { return }
            await self.loadNextPage(window, startingAt: end, in: template)
            await self.loadRemainingPages(window, in: template)
          })
      }
    }
    template.updateSections([CPListSection(items: items)])
  }

  private func loadNextPage(
    _ window: CarPlayListWindow, startingAt start: Int, in template: CPListTemplate
  ) async {
    guard isAuthenticated, !model.isOfflineOnly,
      !window.isLoadingNextPage,
      let token = window.continuation, let loadPage = window.loadNextPage
    else { return }
    let generation = captureRequestGeneration()
    window.isLoadingNextPage = true
    window.failedLoadingNextPage = false
    render(window, startingAt: start, in: template)
    do {
      let page = try await loadPage(token)
      try Task.checkCancellation()
      guard isCurrent(generation) else {
        window.isLoadingNextPage = false
        return
      }
      window.items.append(contentsOf: page.items)
      if page.stopIfEmpty && page.items.isEmpty {
        window.continuation = nil
      } else if let next = page.continuation, !next.rawValue.isEmpty,
        next.rawValue != token.rawValue,
        window.seenContinuations.insert(next.rawValue).inserted
      {
        window.continuation = next
      } else {
        window.continuation = nil
      }
      window.isLoadingNextPage = false
      render(window, startingAt: window.displayedStartIndex, in: template)
    } catch is CancellationError {
      window.isLoadingNextPage = false
      return
    } catch {
      window.isLoadingNextPage = false
      guard isCurrent(generation) else { return }
      window.failedLoadingNextPage = true
      render(window, startingAt: window.displayedStartIndex, in: template)
      logger.error("CarPlay list continuation failed code=\((error as NSError).code)")
    }
  }

  private func loadRemainingPages(_ window: CarPlayListWindow, in template: CPListTemplate) async {
    guard window.eagerlyLoadsContinuations else { return }
    while let token = window.continuation, !window.failedLoadingNextPage,
      !Task.isCancelled
    {
      let start = window.displayedStartIndex
      await loadNextPage(window, startingAt: start, in: template)
      guard window.continuation?.rawValue != token.rawValue else { return }
    }
  }

  private func setRootTemplate(_ template: CPTemplate, animated: Bool) {
    interfaceController?.setRootTemplate(template, animated: animated) {
      [weak self] success, error in
      guard !success else { return }
      self?.logger.error("CarPlay root template failed code=\((error as NSError?)?.code ?? -1)")
    }
  }

  private func showNowPlaying() {
    guard let interfaceController else { return }
    let template = CPNowPlayingTemplate.shared
    guard interfaceController.topTemplate !== template else { return }
    push(template)
  }

  private func openHome() async {
    guard isAuthenticated, !model.isOfflineOnly,
      let service = model.musicService as? any PaginatedCatalogMusicService
    else { return }
    let generation = captureRequestGeneration()
    do {
      let page = try await service.homePage(
        audience: .authenticated, filter: nil, continuation: nil, policy: .cacheFirst)
      guard isCurrent(generation) else { return }
      let catalog = page.sections.flatMap(\.items)
      var seenCatalogIDs = Set<String>()
      let uniqueCatalog = uniqueCatalogItems(catalog, seenIDs: &seenCatalogIDs)
      let songs = catalogSongs(uniqueCatalog)
      let context = CarPlaySongQueueContext(songs: songs)
      let rows = makeCatalogRows(uniqueCatalog, context: context, startingSongIndex: 0)
      let window = CarPlayListWindow(
        items: rows, continuation: page.next, eagerlyLoadsContinuations: true
      ) { [weak self] token in
        guard let self else { throw CancellationError() }
        let nextPage = try await service.homePage(
          audience: .authenticated, filter: nil, continuation: token, policy: .cacheFirst)
        let pageHasContent = nextPage.sections.contains { !$0.items.isEmpty }
        let additions = self.uniqueCatalogItems(
          nextPage.sections.flatMap(\.items), seenIDs: &seenCatalogIDs)
        let firstSongIndex = context.songs.count
        _ = context.appendUnique(self.catalogSongs(additions))
        return CarPlayListPage(
          items: self.makeCatalogRows(
            additions, context: context, startingSongIndex: firstSongIndex),
          continuation: nextPage.next,
          stopIfEmpty: !pageHasContent
        )
      }
      let template = windowTemplate(title: "Home", window: window)
      push(template)
      await loadRemainingPages(window, in: template)
    } catch is CancellationError {
      return
    } catch {
      guard isCurrent(generation) else { return }
      pushMessage("Home could not be loaded. Go back and try again.", title: "Home")
      logger.error("CarPlay home failed code=\((error as NSError).code)")
    }
  }

  private func openLibraryCategories() async {
    guard isAuthenticated, !model.isOfflineOnly else { return }
    let items = LibraryCategory.allCases.map { category in
      makeItem(category.title, symbol: librarySymbol(category)) { [weak self] in
        await self?.openLibrary(category)
      }
    }
    push(listTemplate(title: "Library", items: items))
  }

  private func openLibrary(_ category: LibraryCategory) async {
    guard isAuthenticated, !model.isOfflineOnly,
      let service = model.musicService as? any PaginatedLibraryMusicService
    else { return }
    let generation = captureRequestGeneration()
    do {
      let page = try await service.libraryPage(
        category: category, continuation: nil, policy: .cacheFirst)
      guard isCurrent(generation) else { return }
      let values = uniqueLibraryItems(page.items)
      let context = CarPlaySongQueueContext(
        songs: values.compactMap { value in
          guard case .song(let song) = value else { return nil }
          return song
        })
      var seenItemIDs = Set(values.map(libraryIdentity))
      let rows = makeLibraryRows(values, context: context, startingSongIndex: 0)
      let window = CarPlayListWindow(items: rows, continuation: page.next) { [weak self] token in
        guard let self else { throw CancellationError() }
        let nextPage = try await service.libraryPage(
          category: category, continuation: token, policy: .cacheFirst)
        let additions = nextPage.items.filter {
          seenItemIDs.insert(self.libraryIdentity($0)).inserted
        }
        let firstSongIndex = context.songs.count
        let newSongs = additions.compactMap { value -> Song? in
          guard case .song(let song) = value else { return nil }
          return song
        }
        _ = context.appendUnique(newSongs)
        return CarPlayListPage(
          items: self.makeLibraryRows(
            additions, context: context, startingSongIndex: firstSongIndex),
          continuation: nextPage.next
        )
      }
      push(windowTemplate(title: category.title, window: window))
    } catch {
      guard isCurrent(generation) else { return }
      pushMessage(
        "\(category.title) could not be loaded. Go back and try again.", title: category.title)
      logger.error("CarPlay library failed code=\((error as NSError).code)")
    }
  }

  private func uniqueLibraryItems(
    _ values: [HydraulophoneCore.LibraryItem]
  ) -> [HydraulophoneCore.LibraryItem] {
    var seen = Set<String>()
    return values.filter { seen.insert(libraryIdentity($0)).inserted }
  }

  private func libraryIdentity(_ value: HydraulophoneCore.LibraryItem) -> String {
    switch value {
    case .song(let song): "song:\(song.id)"
    case .playlist(let playlist): "playlist:\(playlist.id)"
    case .album(let album): "album:\(album.id)"
    case .artist(let artist): "artist:\(artist.id)"
    }
  }

  private func catalogIdentity(_ value: CatalogItem) -> String {
    switch value {
    case .song(let song): "song:\(song.id)"
    case .playlist(let playlist): "playlist:\(playlist.id)"
    case .album(let album): "album:\(album.id)"
    }
  }

  private func uniqueCatalogItems(
    _ values: [CatalogItem], seenIDs: inout Set<String>
  ) -> [CatalogItem] {
    values.filter { seenIDs.insert(catalogIdentity($0)).inserted }
  }

  private func catalogSongs(_ values: [CatalogItem]) -> [Song] {
    values.compactMap { value in
      guard case .song(let song) = value else { return nil }
      return song
    }
  }

  private func makeCatalogRows(
    _ values: [CatalogItem], context: CarPlaySongQueueContext, startingSongIndex: Int
  ) -> [CPListItem] {
    var songIndex = startingSongIndex
    return values.map { value in
      switch value {
      case .song(let song):
        defer { songIndex += 1 }
        return trackItem(song, index: songIndex, context: context)
      case .playlist(let playlist):
        return makeItem(playlist.title, detail: playlist.subtitle, symbol: "music.note.list") {
          [weak self] in await self?.openPlaylist(playlist)
        }
      case .album(let album):
        return makeItem(album.title, detail: album.subtitle, symbol: "square.stack") {
          [weak self] in
          await self?.openAlbum(album)
        }
      }
    }
  }

  private func makeLibraryRows(
    _ values: [HydraulophoneCore.LibraryItem], context: CarPlaySongQueueContext,
    startingSongIndex: Int
  ) -> [CPListItem] {
    var songIndex = startingSongIndex
    return values.map { value in
      switch value {
      case .song(let song):
        defer { songIndex += 1 }
        return trackItem(song, index: songIndex, context: context)
      default:
        return libraryItem(value)
      }
    }
  }

  private func libraryItem(_ value: HydraulophoneCore.LibraryItem) -> CPListItem {
    switch value {
    case .song:
      return messageItem("Song")
    case .playlist(let playlist):
      return makeItem(playlist.title, detail: playlist.subtitle, symbol: "music.note.list") {
        [weak self] in await self?.openPlaylist(playlist)
      }
    case .album(let album):
      return makeItem(album.title, detail: album.subtitle, symbol: "square.stack") { [weak self] in
        await self?.openAlbum(album)
      }
    case .artist(let artist):
      return makeItem(artist.title, symbol: "person.crop.circle") { [weak self] in
        await self?.openArtist(artist)
      }
    }
  }

  private func openPlaylist(_ playlist: Playlist) async {
    guard isAuthenticated, !model.isOfflineOnly,
      let service = model.musicService as? any PaginatedCatalogMusicService
    else { return }
    let generation = captureRequestGeneration()
    do {
      let page = try await service.trackPage(
        in: playlist, continuation: nil, policy: .cacheFirst)
      guard isCurrent(generation) else { return }
      showTracks(title: playlist.title, songs: page.items, continuation: page.next) { token in
        try await service.trackPage(in: playlist, continuation: token, policy: .cacheFirst)
      }
    } catch {
      guard isCurrent(generation) else { return }
      pushMessage("Playlist could not be opened. Go back and try again.", title: playlist.title)
      logger.error("CarPlay playlist failed code=\((error as NSError).code)")
    }
  }

  private func openAlbum(_ album: Album) async {
    guard isAuthenticated, !model.isOfflineOnly,
      let service = model.musicService as? any PaginatedCatalogMusicService
    else { return }
    let generation = captureRequestGeneration()
    do {
      let page = try await service.albumTrackPage(
        in: album, continuation: nil, policy: .cacheFirst)
      guard isCurrent(generation) else { return }
      let songs = page.items.map { CollectionTrackMetadata.applying($0, from: album) }
      showTracks(title: album.title, songs: songs, continuation: page.next) { token in
        let nextPage = try await service.albumTrackPage(
          in: album, continuation: token, policy: .cacheFirst)
        return Page(
          items: nextPage.items.map { CollectionTrackMetadata.applying($0, from: album) },
          next: nextPage.next
        )
      }
    } catch {
      guard isCurrent(generation) else { return }
      pushMessage("Album could not be opened. Go back and try again.", title: album.title)
      logger.error("CarPlay album failed code=\((error as NSError).code)")
    }
  }

  private func openArtist(_ artist: Artist) async {
    guard isAuthenticated, !model.isOfflineOnly,
      let service = model.musicService as? any ArtistBrowsingMusicService
    else { return }
    let generation = captureRequestGeneration()
    do {
      let page = try await service.artistPage(artist, continuation: nil, policy: .cacheFirst)
      guard isCurrent(generation) else { return }
      let firstItems = page.sections.flatMap(\.items)
      var seenIDs = Set<String>()
      let values = uniqueCatalogItems(firstItems, seenIDs: &seenIDs)
      let context = CarPlaySongQueueContext(songs: catalogSongs(values))
      let rows = makeCatalogRows(values, context: context, startingSongIndex: 0)
      let window = CarPlayListWindow(items: rows, continuation: page.next) { [weak self] token in
        guard let self else { throw CancellationError() }
        let nextPage = try await service.artistPage(
          artist, continuation: token, policy: .cacheFirst)
        let additions = self.uniqueCatalogItems(
          nextPage.sections.flatMap(\.items), seenIDs: &seenIDs)
        let firstSongIndex = context.songs.count
        _ = context.appendUnique(self.catalogSongs(additions))
        return CarPlayListPage(
          items: self.makeCatalogRows(
            additions, context: context, startingSongIndex: firstSongIndex),
          continuation: nextPage.next
        )
      }
      push(windowTemplate(title: artist.title, window: window))
    } catch {
      guard isCurrent(generation) else { return }
      pushMessage("Artist could not be opened. Go back and try again.", title: artist.title)
      logger.error("CarPlay artist failed code=\((error as NSError).code)")
    }
  }

  private func showTracks(
    title: String, songs: [Song], continuation: PaginationToken?,
    loadPage: @escaping @MainActor (PaginationToken) async throws -> Page<Song>
  ) {
    let context = CarPlaySongQueueContext(songs: songs)
    let rows = context.songs.enumerated().map { index, song in
      trackItem(song, index: index, context: context)
    }
    let window = CarPlayListWindow(items: rows, continuation: continuation) { [weak self] token in
      guard let self else { throw CancellationError() }
      let page = try await loadPage(token)
      let additions = context.appendUnique(page.items)
      let firstIndex = context.songs.count - additions.count
      let newRows = additions.enumerated().map { offset, song in
        self.trackItem(song, index: firstIndex + offset, context: context)
      }
      return CarPlayListPage(items: newRows, continuation: page.next)
    }
    push(windowTemplate(title: title, window: window))
  }

  private func trackItem(_ song: Song, index: Int, context: CarPlaySongQueueContext) -> CPListItem {
    makeItem(song.title, detail: song.artist, symbol: "music.note") { [weak self] in
      self?.play(context.songs, startingAt: index)
    }
  }

  private func moreItem(
    title: String, action: @escaping @MainActor () async -> Void
  ) -> CPListItem {
    makeItem(title, symbol: "ellipsis") { await action() }
  }

  private func pushMessage(_ message: String, title: String) {
    push(listTemplate(title: title, items: [messageItem(message)]))
  }

  private func push(_ template: CPTemplate) {
    guard let interfaceController else { return }
    navigationRevision &+= 1
    let requestedNavigationRevision = navigationRevision
    let requestedConnectionGeneration = connectionGeneration
    let requestedCatalogSession = model.catalogSessionID
    let requestedRootState = rootState
    if interfaceController.topTemplate === template { return }
    if let existing = interfaceController.templates.first(where: { $0 === template }) {
      interfaceController.pop(to: existing, animated: true) { [weak self] success, error in
        guard let self,
          self.interfaceController === interfaceController,
          self.connectionGeneration == requestedConnectionGeneration,
          self.model.catalogSessionID == requestedCatalogSession,
          self.rootState == requestedRootState,
          self.navigationRevision == requestedNavigationRevision
        else { return }
        guard success else {
          self.logger.error("CarPlay template pop failed code=\((error as NSError?)?.code ?? -1)")
          return
        }
      }
      return
    }
    guard interfaceController.templates.count < 5 else {
      interfaceController.popToRootTemplate(animated: false) { [weak self] success, error in
        guard let self,
          self.interfaceController === interfaceController,
          self.connectionGeneration == requestedConnectionGeneration,
          self.model.catalogSessionID == requestedCatalogSession,
          self.rootState == requestedRootState,
          self.navigationRevision == requestedNavigationRevision
        else { return }
        guard success else {
          self.logger.error("CarPlay root pop failed code=\((error as NSError?)?.code ?? -1)")
          return
        }
        self.push(template)
      }
      return
    }
    interfaceController.pushTemplate(template, animated: true) { [weak self] success, error in
      guard !success else { return }
      self?.logger.error("CarPlay template push failed code=\((error as NSError?)?.code ?? -1)")
    }
  }

  private func play(_ songs: [Song], startingAt index: Int) {
    guard isAuthenticated, !songs.isEmpty else { return }
    if model.isOfflineOnly {
      let downloadedIDs = Set(model.downloads.availableSongs.map(\.id))
      guard songs.allSatisfy({ downloadedIDs.contains($0.id) }) else { return }
    }
    model.playback.setQueue(songs, startAt: index)
    showNowPlaying()
  }

  private func openDownloads() {
    guard isAuthenticated else { return }
    let songs = model.downloads.tracks.filter(\.isAvailable).map(model.downloads.localSong)
    let context = CarPlaySongQueueContext(songs: songs)
    let items = context.songs.enumerated().map { index, song in
      trackItem(song, index: index, context: context)
    }
    push(windowTemplate(title: "Downloads", window: CarPlayListWindow(items: items)))
  }

  private func showQueue() async {
    guard isAuthenticated else { return }
    refreshQueueTemplate()
    guard let queueTemplate else {
      pushMessage("Your queue is empty.", title: "Up Next")
      return
    }
    push(queueTemplate)
  }

  private func refreshQueueTemplate() {
    let playback = model.playback
    let queueEntries = playback.queueEntries
    let upcoming: [PlaybackQueueEntry]
    if let currentIndex = queueEntries.firstIndex(where: { $0.id == playback.currentQueueEntryID })
    {
      upcoming = Array(queueEntries.dropFirst(currentIndex + 1))
    } else {
      upcoming = queueEntries
    }
    let key =
      "\(playback.currentQueueEntryID?.uuidString ?? "")|"
      + upcoming.map { $0.id.uuidString }.joined(separator: ",")
    guard key != cachedQueueKey else { return }
    cachedQueueKey = key
    let items = upcoming.map { entry in
      let item = CPListItem(text: entry.song.title, detailText: entry.song.artist)
      item.handler = { [weak self] _, completion in
        Task { @MainActor [weak self] in
          if let self, self.isAuthenticated,
            self.model.playback.queueEntries.contains(where: { $0.id == entry.id })
          {
            self.model.playback.playQueueEntry(id: entry.id)
            self.showNowPlaying()
          }
          completion()
        }
      }
      return item
    }
    if items.isEmpty {
      queueTemplate?.updateSections([
        CPListSection(items: [messageItem("No upcoming tracks.")])
      ])
      queueWindow = nil
    } else {
      let window = CarPlayListWindow(items: items)
      queueWindow = window
      if let queueTemplate {
        render(window, startingAt: 0, in: queueTemplate)
      } else {
        queueTemplate = windowTemplate(title: "Up Next", window: window)
      }
    }
  }

  private func librarySymbol(_ category: LibraryCategory) -> String {
    switch category {
    case .playlists: "music.note.list"
    case .songs: "music.note"
    case .albums: "square.stack"
    case .artists: "person.2"
    }
  }

}

private struct CarPlayRequestGeneration: Equatable {
  let connection: UUID
  let catalogSession: Int
}

private struct CarPlayListPage {
  let items: [CPListItem]
  let continuation: PaginationToken?
  let stopIfEmpty: Bool

  init(items: [CPListItem], continuation: PaginationToken?, stopIfEmpty: Bool = false) {
    self.items = items
    self.continuation = continuation
    self.stopIfEmpty = stopIfEmpty
  }
}

@MainActor
private final class CarPlayListWindow {
  var items: [CPListItem]
  var continuation: PaginationToken?
  let loadNextPage: (@MainActor (PaginationToken) async throws -> CarPlayListPage)?
  var seenContinuations: Set<String>
  let eagerlyLoadsContinuations: Bool
  var displayedStartIndex = 0
  var isLoadingNextPage = false
  var failedLoadingNextPage = false

  init(
    items: [CPListItem], continuation: PaginationToken? = nil,
    eagerlyLoadsContinuations: Bool = false,
    loadNextPage: (@MainActor (PaginationToken) async throws -> CarPlayListPage)? = nil
  ) {
    self.items = items
    self.continuation = continuation.flatMap { $0.rawValue.isEmpty ? nil : $0 }
    self.loadNextPage = loadNextPage
    self.eagerlyLoadsContinuations = eagerlyLoadsContinuations
    seenContinuations = self.continuation.map { Set([$0.rawValue]) } ?? []
  }
}

@MainActor
private final class CarPlaySongQueueContext {
  var songs: [Song]
  private var seenIDs: Set<String>

  init(songs: [Song]) {
    var unique: [Song] = []
    var ids: Set<String> = []
    for song in songs where ids.insert(song.id).inserted { unique.append(song) }
    self.songs = unique
    seenIDs = ids
  }

  func appendUnique(_ incoming: [Song]) -> [Song] {
    var additions: [Song] = []
    for song in incoming where seenIDs.insert(song.id).inserted { additions.append(song) }
    songs.append(contentsOf: additions)
    return additions
  }
}