Files
stemify/ios/Stemify/UI/Nav.swift
T

201 lines
7.9 KiB
Swift

import SwiftUI
import UIKit
enum Tab: String, CaseIterable, Hashable {
case Library, Songs, Albums, Artists, Genres, Playlists, Search, Downloads, Settings
static let defaultLayout: [Tab] = [.Library, .Playlists, .Search, .Downloads, .Settings]
/// iOS folds anything past five tabs into "More", so the bar holds at most this many.
static let maxVisible = 5
/// Parses the saved comma list; Settings is always kept so the app can't lock itself out.
static func layout(_ raw: String) -> [Tab] {
var out: [Tab] = []
for part in raw.split(separator: ",") {
if let t = Tab(rawValue: String(part)), !out.contains(t) { out.append(t) }
}
if out.isEmpty { return defaultLayout }
if !out.contains(.Settings) { out = Array(out.prefix(maxVisible - 1)) + [.Settings] }
return Array(out.prefix(maxVisible))
}
static func encode(_ tabs: [Tab]) -> String { tabs.map(\.rawValue).joined(separator: ",") }
var icon: String {
switch self {
case .Library: "square.stack.fill"
case .Songs: "music.note"
case .Albums: "square.stack"
case .Artists: "music.mic"
case .Genres: "guitars.fill"
case .Playlists: "music.note.list"
case .Search: "magnifyingglass"
case .Downloads: "arrow.down.circle.fill"
case .Settings: "gearshape.fill"
}
}
}
/// The pages of the deck beside docked Now Playing on an unfolded iPhone Duo.
enum DeckPage: String, CaseIterable, Hashable {
case Stems, Lyrics, Queue, Eq
var title: String {
switch self {
case .Stems: "Stems"
case .Lyrics: "Lyrics"
case .Queue: "Playing Next"
case .Eq: "EQ"
}
}
}
enum Route: Hashable {
case Artists, Albums, Songs, RecentlyAdded, Playlists, Genres, Downloads, DownloadQueue, TabBar, WebRadio
case Eq, EqFilters(profileId: String), EqFilterPage(profileId: String, filterId: String)
case Servers, ServerList, Server(String), StemServer, Quality, Storage, Appearance, NowPlayingOptions, StemEditor, LibraryLayout, About
case GenrePage(String), ArtistPage(Artist), AlbumPage(Album), PlaylistPage(Playlist), StemPlaylistPage(String)
}
/// Tabs, their stacks and the Now Playing sheet: the things any screen can ask of the shell.
@MainActor
@Observable
final class Ui {
var tab: Tab = .Library
var paths: [Tab: [Route]] = [:]
var nowPlayingOpen = false {
didSet { overlays.level = nowPlayingOpen ? 1 : 0 }
}
/// True while an unfolded iPhone Duo shows Now Playing docked beside the library.
private(set) var split = false
/// Unfolded Duo in any orientation (a hinge is showing), even before it has turned to landscape.
private(set) var unfolded = false
/// Split only: the Now Playing tab (the deck) is selected instead of `tab`.
var deck = true
/// Split only: which of the deck's pages is showing.
var deckPage: DeckPage = .Stems
let overlays: Overlays
init(overlays: Overlays) { self.overlays = overlays }
func path(_ t: Tab) -> Binding<[Route]> {
Binding(get: { self.paths[t] ?? [] }, set: { self.paths[t] = $0 })
}
func push(_ r: Route) { paths[tab, default: []].append(r) }
func pop() { if paths[tab]?.isEmpty == false { paths[tab]?.removeLast() } }
/// Tapping the selected tab again pops it to its root.
func selectTab(_ t: Tab) {
if showsDeck { deck = false; tab = t; return }
if t == tab { paths[t] = [] } else { tab = t }
}
/// Split with something playing, the bar leads with a Now Playing item that opens the deck.
var hasDeckTab: Bool { split && AppGraph.shared.playback.current != nil }
var showsDeck: Bool { hasDeckTab && deck }
/// The tabs currently in the bar, in order. The Now Playing item takes one of the five places
/// (iOS folds a sixth into "More"), so the last one before Settings steps aside for it.
var tabs: [Tab] {
var t = Tab.layout(AppGraph.shared.settings.tabLayout)
if hasDeckTab && t.count >= Tab.maxVisible, let i = t.lastIndex(where: { $0 != .Settings }) { t.remove(at: i) }
return t
}
/// Where library pages open: Library if it's in the bar, else the first tab that is.
private var home: Tab { tabs.contains(.Library) ? .Library : (tabs.first ?? .Settings) }
/// Downloads as its own tab, or pushed onto the current one when it's hidden.
func openDownloads() {
if tabs.contains(.Downloads) { selectTab(.Downloads) } else { push(.Downloads) }
}
/// Falls back to the first tab when the selected one was just removed from the bar.
func ensureValidTab() {
if !tabs.contains(tab) { tab = tabs.first ?? .Settings }
}
/// Docked Now Playing is already on screen, so there's nothing to open while split.
func openNowPlaying() { if !split { nowPlayingOpen = true } }
/// Split only: brings the stems and queue (or the lyrics) back beside Now Playing.
func showDeck(_ page: DeckPage? = nil) { deck = true; if let page { deckPage = page } }
/// This phone has shown the Duo's folded status column at least once (saved).
private var duo = UserDefaults.standard.bool(forKey: "duoSeen")
/// Folded iPhone Duo: the outer display, kept upright.
var folded: Bool { duo && !split && !unfolded }
var isDuo: Bool { duo }
/// Called with the window's side insets. Upright, only the folded Duo has a trailing one.
func sawInsets(trailing: CGFloat, upright: Bool) {
if !duo && upright && !split && trailing > 20 {
duo = true
UserDefaults.standard.set(true, forKey: "duoSeen")
}
lockOrientation()
}
/// The Duo is never free to turn: folded is portrait only, unfolded is landscape only.
/// Hinge readings flicker while the window settles (coming back from the background, mid
/// fold), so the lock only changes once a reading has held for a moment. Other iPhones turn freely.
private var lockGen = 0
func resumed() { lockOrientation() }
/// Leaves the lock as it is: freeing it let iOS turn the window while audio kept the app alive.
func backgrounded() {}
private func lockOrientation() {
guard duo || split || unfolded else { Orientation.lock(.allButUpsideDown); return }
let want: UIInterfaceOrientationMask = (split || unfolded) ? .landscape : .portrait
lockGen += 1
let gen = lockGen
Task { @MainActor in
try? await Task.sleep(for: .milliseconds(450))
guard gen == self.lockGen else { return }
let now: UIInterfaceOrientationMask = (self.split || self.unfolded) ? .landscape : .portrait
guard now == want else { return }
Log.shared.info("orient", "lock \(want == .landscape ? "landscape" : "portrait") split=\(self.split) unfolded=\(self.unfolded)")
Orientation.lock(want)
}
}
func setUnfolded(_ on: Bool) {
guard on != unfolded else { return }
unfolded = on
Log.shared.info("orient", "unfolded \(on)")
lockOrientation()
}
func setSplit(_ on: Bool) {
guard on != split else { return }
split = on
Log.shared.info("orient", "split \(on)")
lockOrientation()
if on {
nowPlayingOpen = false
}
// Karaoke left on shows its lyrics in the deck.
if on && AppGraph.shared.playback.karaoke { deckPage = .Lyrics } else if deckPage == .Lyrics { deckPage = .Stems }
}
/// Switches to the Library tab and pushes [r] there.
func showInLibrary(_ r: Route) {
nowPlayingOpen = false
deck = false
let t = home
tab = t
paths[t, default: []].append(r)
}
/// Switches to Settings and opens [r] (the Equalizer) there.
func showInSettings(_ r: Route) {
nowPlayingOpen = false
deck = false
tab = .Settings
if paths[.Settings]?.last != r { paths[.Settings, default: []].append(r) }
}
}