Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.
C
feat: the Live Activity page shows a preview of the card and has more options
My-Name-Is-Jeff71c4ac6798dc
diff --git a/docs/tweaks.md b/docs/tweaks.mdindex 505bbee5..85b5d2c6 100644--- a/docs/tweaks.md+++ b/docs/tweaks.md@@ -323,7 +323,13 @@ Shared:is tinted with the cover's colour and shows the cover itself, a JPEG of a few dozen pixels insidethe state, which ActivityKit caps at 4 KB (the bridge sends it without the cover when it wouldnot fit); the colour is darkened to a luminance of 0.04 at most, so the white text keeps 4.5:1 on any- cover, and the cover is read only once the now playing title is the new track's. Taps are+ cover, and the cover is read only once the now playing title is the new track's. The page's options+ ride in the state too, read on every tick, so they apply within a tick: the lines' alignment, what the+ lyrics view shows on a track with no timed lyrics (a note under the track, or the track large), the+ colours (Spotify's green; Artwork, the cover's colour lightened to about the green's luminance in its+ place; Plain, white on the system's own background), and the progress bar. Artwork off sends no+ cover at all. The page's preview (SGLiveActivityPreview.m) is a mock of the card in UIKit, not the+ widget, checked in the simulator against harness/live-activity-page/. Taps areLiveActivityIntents run inside Spotify and take a second or two to show on the card. The widget is extension/LiveActivity; ActivityKit pairs the twoby the attributes' type in LiveActivityShared.swift, compiled into both. It starts only with Spotifyin front; its settings apply at once. It ends when Spotify is swiped away while running; killed@@ -660,8 +666,13 @@ Follows, greyed out the same way, Everything (a tap on each kick and snare and ataps without the rumble) or Bass (the kicks' taps and the rumble); In the Background a Status row (Paused, Waiting,Checking, Ready, Playing or Unavailable) while it is on, or, while Music Haptics is off in Settings > Accessibility, arow saying so whose tap opens its ⓘ, all applying straight away. Live Activity, on iOS 17 and up under either look: its switch and which view it-shows, Lyrics, Queue or Control menu, and for Lyrics its Translations (off until switched on) and Text-size (Small, Medium or Large), all applying straight away, the row reading out the view or Off. Audio effects, in either look (Shared/AudioEffects/AudioEffectsPage.m):+shows, Lyrics, Queue or Control menu, and for Lyrics its Without lyrics (Note or Track), Alignment (Center, or Left),+Translations (off until switched on) and Text size (Small, Medium or Large); then for every view a Card section of+Artwork and Progress bar (both on until switched off) and Colors (Spotify, Artwork or Plain), with a note that the+card shows on a paired Apple Watch and in CarPlay too, all applying straight away, the row reading out the view or+Off. At its top a preview, a slice of the lock screen with a mock of the card with a made-up song, follows the+options as they change and steps every 3 s through the picked view, the lines being sung or the menu's tabs, with+a crossfade; under Reduce Motion it rests and a tap moves it on, and it stops while the page is off screen. Audio effects, in either look (Shared/AudioEffects/AudioEffectsPage.m):the effects' switch with what the engine is doing under it, Presets (built-in ones and your own, saved, loadedand deleted there) and Headphones (AutoEq's corrections, searched and applied to the Graphic EQ, with Use for <theoutput playing now> keeping the pick for that output and the remembered outputs listed, a swipe removing one), either of whichdiff --git a/extension/LiveActivity/LiveActivityWidget.swift b/extension/LiveActivity/LiveActivityWidget.swiftindex ac1faa23..a9e415e2 100644--- a/extension/LiveActivity/LiveActivityWidget.swift+++ b/extension/LiveActivity/LiveActivityWidget.swift@@ -13,6 +13,19 @@ import WidgetKitprivate let green = Color(red: 0.12, green: 0.84, blue: 0.38)private let idle = Color.white.opacity(0.08)+// The accent, Spotify's green or what the page's Colors puts in its place (accentOf), set at the card's+// root and each of the island's, so the views under them read it.+private struct AccentKey: EnvironmentKey {+ static let defaultValue = green+}++private extension EnvironmentValues {+ var accent: Color {+ get { self[AccentKey.self] }+ set { self[AccentKey.self] = newValue }+ }+}+private typealias State = SGLyricsAttributes.ContentStateprivate typealias Tab = SGLyricsAttributes.Tab@@ -29,13 +42,35 @@ struct SGLiveActivityBundle: WidgetBundle {}}-// The cover's colour, RRGGBB, as the card's background; the old translucent black without one.-private func tint(_ state: State) -> Color {- guard let hex = state.tint, hex.count == 6, let value = Int(hex, radix: 16) else { return Color.black.opacity(0.75) }+private func color(hex: String?) -> Color? {+ guard let hex, hex.count == 6, let value = Int(hex, radix: 16) else { return nil }return Color(red: Double((value >> 16) & 0xFF) / 255, green: Double((value >> 8) & 0xFF) / 255,blue: Double(value & 0xFF) / 255)}+// The cover's color, RRGGBB, as the card's background, the old translucent black without one; under Plain+// nil, the system's own background.+private func tint(_ state: State) -> Color? {+ if state.colors == 2 { return nil }+ return color(hex: state.tint) ?? Color.black.opacity(0.75)+}++// Spotify's green; under Artwork the cover's color, lightened by the tweak to keep 4.5:1 on the card; under+// Plain white.+private func accentOf(_ state: State) -> Color {+ switch state.colors {+ case 1: color(hex: state.accent) ?? green+ case 2: .white+ default: green+ }+}++private extension View {+ func accented(_ state: State) -> some View {+ environment(\.accent, accentOf(state))+ }+}+private func coverImage(_ state: State) -> UIImage? {state.cover.flatMap(UIImage.init(data:))}@@ -59,13 +94,14 @@ private struct Cover: View {// cover, or a note before it is read.private struct Badge: View {let state: State+ @Environment(\.accent) private var accentvar body: some View {if let image = coverImage(state) {Cover(image: image, side: 22)} else {Image(systemName: "music.note")- .foregroundStyle(green)+ .foregroundStyle(accent)}}}@@ -108,6 +144,7 @@ private func lyricsActivity<A: ActivityAttributes, Card: View>() -> ActivityConfiguration<A> where A.ContentState == State {ActivityConfiguration(for: A.self) { context incard(context.state)+ .accented(context.state).foregroundStyle(.white).activityBackgroundTint(tint(context.state)).activitySystemActionForegroundColor(.white)@@ -116,7 +153,7 @@ private func lyricsActivity<A: ActivityAttributes, Card: View>(// The row beside the camera: a note, and the sleep timer or whether it plays.DynamicIslandExpandedRegion(.leading) {Image(systemName: "music.note")- .foregroundStyle(green)+ .foregroundStyle(accentOf(context.state)).padding(.leading, 6)}DynamicIslandExpandedRegion(.trailing) {@@ -128,6 +165,7 @@ private func lyricsActivity<A: ActivityAttributes, Card: View>(}}.padding(.trailing, 6)+ .accented(context.state)}DynamicIslandExpandedRegion(.bottom) {Group {@@ -141,18 +179,24 @@ private func lyricsActivity<A: ActivityAttributes, Card: View>(.padding(.horizontal, 4)// The island is always black, whatever the card's tint..foregroundStyle(.white)+ .accented(context.state)}} compactLeading: {Badge(state: context.state)+ .accented(context.state)} compactTrailing: {- if let end = runningTimer(context.state) {- Countdown(end: end)- .frame(maxWidth: 44)- } else {- ProgressRing(state: context.state)+ Group {+ if let end = runningTimer(context.state) {+ Countdown(end: end)+ .frame(maxWidth: 44)+ } else {+ ProgressRing(state: context.state)+ }}+ .accented(context.state)} minimal: {Badge(state: context.state)+ .accented(context.state)}}}@@ -244,27 +288,30 @@ private func runningTimer(_ state: State) -> Date? {private struct Countdown: View {let end: Date+ @Environment(\.accent) private var accentvar body: some View {Text(timerInterval: Date()...end, countsDown: true).monospacedDigit()- .foregroundStyle(green)+ .foregroundStyle(accent)}}// Paused or playing, where there is no progress or sleep timer to show.private struct PlayingSymbol: View {let state: State+ @Environment(\.accent) private var accentvar body: some View {Image(systemName: state.paused ? "pause.fill" : "waveform")- .foregroundStyle(green)+ .foregroundStyle(accent)}}// The track's progress as a ring, for the compact Dynamic Island, which Apple Watch and CarPlay show too.private struct ProgressRing: View {let state: State+ @Environment(\.accent) private var accentvar body: some View {if let start = state.trackStart, let end = state.trackEnd, end > start {@@ -276,7 +323,7 @@ private struct ProgressRing: View {}}.progressViewStyle(.circular)- .tint(green)+ .tint(accent).frame(width: 18, height: 18)} else {PlayingSymbol(state: state)@@ -289,7 +336,7 @@ private struct ProgressBar: View {let state: Statevar body: some View {- if let start = state.trackStart, let end = state.trackEnd, end > start {+ if state.progressBar ?? true, let start = state.trackStart, let end = state.trackEnd, end > start {Group {if state.paused, let at = state.pausedAt {ProgressView(value: at)@@ -331,45 +378,82 @@ private struct LyricsView: View {}}+ // The page's Alignment: centered by default, or left. Left is the leading edge, so a line written right to+ // left still starts at the right (direction(of:)).+ private var centered: Bool { (state.alignment ?? 1) == 1 }+ private var edge: HorizontalAlignment { centered ? .center : .leading }+ private var frameEdge: Alignment { centered ? .center : .leading }+var body: some View {- // No line being sung (before the first, in a break, without lyrics): the track holds the place.+ // No line being sung (before the first, in a break, without lyrics): the track holds the place, and on a+ // track with no timed lyrics under Without lyrics' Note, at its own size over a line saying so.if state.line.isEmpty || state.line == "♪" {- VStack(alignment: .center, spacing: 2) {- Text(state.title.isEmpty ? "♪" : state.title)- .font(lineFont.weight(.bold))- .lineLimit(1)- .frame(maxWidth: .infinity)- .direction(of: state.title)- if !state.title.isEmpty, !state.artist.isEmpty {- Text(state.artist)- .font(.subheadline.weight(.medium))- .foregroundStyle(.white.opacity(0.6))- .lineLimit(1)- .frame(maxWidth: .infinity)- .direction(of: state.artist)- }+ if state.noLyrics == true, (state.withoutLyrics ?? 0) == 0 {+ note+ } else {+ track}} else {line}}+ private var track: some View {+ VStack(alignment: edge, spacing: 2) {+ Text(state.title.isEmpty ? "♪" : state.title)+ .font(lineFont.weight(.bold))+ .lineLimit(1)+ .frame(maxWidth: .infinity, alignment: frameEdge)+ .direction(of: state.title)+ if !state.title.isEmpty, !state.artist.isEmpty {+ Text(state.artist)+ .font(.subheadline.weight(.medium))+ .foregroundStyle(.white.opacity(0.6))+ .lineLimit(1)+ .frame(maxWidth: .infinity, alignment: frameEdge)+ .direction(of: state.artist)+ }+ }+ }++ private var note: some View {+ VStack(alignment: edge, spacing: 2) {+ Text(state.title)+ .font(.headline)+ .lineLimit(1)+ .frame(maxWidth: .infinity, alignment: frameEdge)+ .direction(of: state.title)+ Text(state.artist)+ .font(.subheadline.weight(.medium))+ .foregroundStyle(.white.opacity(0.6))+ .lineLimit(1)+ .frame(maxWidth: .infinity, alignment: frameEdge)+ .direction(of: state.artist)+ Text("No synced lyrics for this song")+ .font(.caption.weight(.medium))+ .foregroundStyle(.white.opacity(0.6))+ .lineLimit(1)+ .frame(maxWidth: .infinity, alignment: frameEdge)+ .padding(.top, 4)+ }+ }+private var line: some View {- VStack(alignment: .center, spacing: 4) {+ VStack(alignment: edge, spacing: 4) {Text(state.line).font(lineFont.weight(.bold)).lineLimit(2).minimumScaleFactor(0.7)- .multilineTextAlignment(.center)- .frame(maxWidth: .infinity)+ .multilineTextAlignment(centered ? .center : .leading)+ .frame(maxWidth: .infinity, alignment: frameEdge).direction(of: state.line)if let translation = state.translation, !translation.isEmpty {Text(translation).font(.subheadline.weight(.medium)).foregroundStyle(.white.opacity(0.7)).lineLimit(2)- .multilineTextAlignment(.center)- .frame(maxWidth: .infinity)+ .multilineTextAlignment(centered ? .center : .leading)+ .frame(maxWidth: .infinity, alignment: frameEdge).direction(of: translation)}if !state.nextLine.isEmpty {@@ -377,6 +461,7 @@ private struct LyricsView: View {.font(.subheadline.weight(.semibold)).foregroundStyle(.white.opacity(0.6)).lineLimit(1)+ .frame(maxWidth: .infinity, alignment: frameEdge).direction(of: state.nextLine)}}@@ -502,6 +587,7 @@ private struct PanelView: View {private struct TabStyle: ToggleStyle {let tab: Tab+ @Environment(\.accent) private var accentfunc makeBody(configuration: Configuration) -> some View {HStack(spacing: 4) {@@ -513,8 +599,8 @@ private struct TabStyle: ToggleStyle {.font(.caption.weight(.semibold)).frame(maxWidth: .infinity).frame(height: 32)- .background(Capsule().fill(configuration.isOn ? green.opacity(0.22) : idle))- .foregroundStyle(configuration.isOn ? green : .white.opacity(0.7))+ .background(Capsule().fill(configuration.isOn ? accent.opacity(0.22) : idle))+ .foregroundStyle(configuration.isOn ? accent : .white.opacity(0.7))}}@@ -542,12 +628,13 @@ private struct ChipStyle: ToggleStyle {var onLabel: String?// Play and pause flips its symbol but is not a setting, so it keeps the idle fill either way.var lights = true+ @Environment(\.accent) private var accentfunc makeBody(configuration: Configuration) -> some View {let on = configuration.isOnChipLabel(symbol: on ? onSymbol ?? symbol : symbol, label: on ? onLabel ?? label : label)- .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(on && lights ? green.opacity(0.22) : idle))- .foregroundStyle(on && lights ? green : .white)+ .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(on && lights ? accent.opacity(0.22) : idle))+ .foregroundStyle(on && lights ? accent : .white)}}@@ -558,12 +645,13 @@ private struct ChipButton: View {var lit = false// What VoiceOver and Voice Control say, where the short label on the chip would read wrong: "15m" as 15 metres.var spoken: String?+ @Environment(\.accent) private var accentvar body: some View {Button(intent: SGLiveActivityActionIntent(action)) {ChipLabel(symbol: symbol, label: label)- .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(lit ? green.opacity(0.22) : idle))- .foregroundStyle(lit ? green : .white)+ .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(lit ? accent.opacity(0.22) : idle))+ .foregroundStyle(lit ? accent : .white)}.buttonStyle(.plain).accessibilityLabel(spoken ?? label)@@ -607,6 +695,7 @@ private struct ControlsPage: View {private struct QueuePage: View {let state: State+ @Environment(\.accent) private var accentvar body: some View {VStack(spacing: 4) {@@ -621,7 +710,7 @@ private struct QueuePage: View {HStack(spacing: 10) {Image(systemName: "play.fill").font(.caption)- .foregroundStyle(green)+ .foregroundStyle(accent)Text(track.title).font(.footnote.weight(.semibold))Text(track.artist)@@ -644,6 +733,7 @@ private struct QueuePage: View {private struct TimerPage: View {let state: State+ @Environment(\.accent) private var accentvar body: some View {Group {@@ -656,11 +746,11 @@ private struct TimerPage: View {if let end = state.timerEnd {Text(timerInterval: Date()...end, countsDown: true).font(.system(size: 34, weight: .bold).monospacedDigit())- .foregroundStyle(green)+ .foregroundStyle(accent)} else {Text(state.timerEndOfAlbum == true ? "End of album" : "End of track").font(.title2.weight(.bold))- .foregroundStyle(green)+ .foregroundStyle(accent)}}Spacer(minLength: 0)diff --git a/harness/live-activity-page/README.md b/harness/live-activity-page/README.mdnew file mode 100644index 00000000..5f07f8e7--- /dev/null+++ b/harness/live-activity-page/README.md@@ -0,0 +1,22 @@+# Live Activity page harness++Mod Settings > Live Activity as `Shared/LiveActivity/LiveActivitySettings.m` builds it, with its preview+(`SGLiveActivityPreview.m`) and the real `Settings/` framework. `stubs.m` stands in for the activity's switch and+the sleep timer's fade names. `main.m` lists the setup words and the actions.++ THEOS=$HOME/theos ./build.sh+ xcrun simctl install <udid> build/LiveActivityPageHarness.app+ xcrun simctl launch --console-pty <udid> com.vojta.liveactivitypageharness view=2 dump wait wait wait dump tap dump+ xcrun simctl io <udid> screenshot shot.png++Make a simulator of your own (`xcrun simctl create`) and address it by UDID. The app takes a few seconds to show+after the launch, so wait before the screenshot.++2026-10-06, iPhone 17 Pro on iOS 27.0: the preview is 325 pt high and keeps that height in every view. Control+menu steps from Controls to Queue to Timer about every 3 s, a tap goes on to the next, and `stop` holds it.+Lyrics steps through three lines and then a track with no lyrics. Queue rests. With Control menu picked, the+lyrics' four rows are hidden. Seen in screenshots: Lyrics with translations, the no-lyrics track under Note,+Plain with Center, Track and Artwork off, Controls under Artwork colors, Queue with the bar off.++What it does not cover: Reduce Motion, which the simulator cannot switch from the command line; the real card,+which only a phone shows.diff --git a/harness/live-activity-page/build.sh b/harness/live-activity-page/build.shnew file mode 100755index 00000000..0ab2ac13--- /dev/null+++ b/harness/live-activity-page/build.sh@@ -0,0 +1,41 @@+#!/bin/sh+# Builds the Live Activity page harness for the simulator: Shared/LiveActivity's page and its preview, the+# Settings/ framework as they are in the tweak, stubs.m for the activity and the sleep timer.+set -e+SRC=$(cd "$(dirname "$0")/../../tweak/Sources" && pwd)+OUT=$(dirname "$0")/build+rm -rf "$OUT"; mkdir -p "$OUT/LiveActivityPageHarness.app"++SDK=$(xcrun --sdk iphonesimulator --show-sdk-path)+xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-arc -g -O0 \+ -I"$SRC" -isysroot "$SDK" -Wall -Werror -Wno-deprecated-declarations \+ "$(dirname "$0")/main.m" "$(dirname "$0")/stubs.m" "$(dirname "$0")/../scene.m" \+ "$SRC"/Shared/LiveActivity/LiveActivitySettings.m "$SRC"/Shared/LiveActivity/SGLiveActivityPreview.m \+ "$SRC"/Settings/SGPage.m "$SRC"/Settings/SGPageStyle.m "$SRC"/Settings/SGModPage.m "$SRC"/Settings/SGGlowSwitch.m \+ "$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGViewTree.m "$SRC"/Core/SGFlagForce.m "$SRC"/Core/SGUIMode.m \+ -framework UIKit -framework QuartzCore -framework CoreGraphics -framework Foundation \+ -o "$OUT/LiveActivityPageHarness.app/LiveActivityPageHarness"++cat > "$OUT/LiveActivityPageHarness.app/Info.plist" <<'PLIST'+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0"><dict>+<key>CFBundleExecutable</key><string>LiveActivityPageHarness</string>+<key>CFBundleIdentifier</key><string>com.vojta.liveactivitypageharness</string>+<key>CFBundleName</key><string>LiveActivityPageHarness</string>+<key>CFBundleVersion</key><string>1</string>+<key>CFBundleShortVersionString</key><string>1.0</string>+<key>UIUserInterfaceStyle</key><string>Dark</string>+<key>UILaunchScreen</key><dict/>+<key>UIApplicationSceneManifest</key><dict>+ <key>UIApplicationSupportsMultipleScenes</key><false/>+ <key>UISceneConfigurations</key><dict>+ <key>UIWindowSceneSessionRoleApplication</key><array><dict>+ <key>UISceneConfigurationName</key><string>Default</string>+ <key>UISceneDelegateClassName</key><string>SGRHarnessScene</string>+ </dict></array>+ </dict>+</dict>+</dict></plist>+PLIST+echo "built $OUT/LiveActivityPageHarness.app"diff --git a/harness/live-activity-page/main.m b/harness/live-activity-page/main.mnew file mode 100644index 00000000..46cd6f63--- /dev/null+++ b/harness/live-activity-page/main.m@@ -0,0 +1,87 @@+// Mod Settings > Live Activity (Shared/LiveActivity/LiveActivitySettings.m) and its preview (SGLiveActivityPreview.m),+// with the real Settings/ framework behind them and stubs.m for the activity and the sleep timer. The launch line+// sets the page's options up, then plays actions, one every 0.7 s from 1 s in; screenshot after.+//+// THEOS=$HOME/theos ./build.sh && xcrun simctl install <udid> build/LiveActivityPageHarness.app+// xcrun simctl launch <udid> com.vojta.liveactivitypageharness [setup...] [action...]+//+// Setup (every Live Activity key is cleared first): view=<n> (Lyrics 0, Queue 1, Control menu 2), size=<n>,+// without=<n> (Note 0, Track 1), align=<n> (Left 0, Center 1), colors=<n> (Spotify 0, Artwork 1, Plain 2),+// translation, artwork-off, bar-off.+// Actions: tap (the preview's next step, as VoiceOver's double tap), stop (the page's off screen: the preview stops+// stepping), wait (nothing, for a step to pass), dump (the preview's value and the rows each section shows, to the log).+#import <UIKit/UIKit.h>+#import "Core/SGCore.h"+#import "Settings/SGModPage.h"+#import "Shared/LiveActivity/LiveActivity.h"++@interface AppDelegate : UIResponder <UIApplicationDelegate>+@property (nonatomic, strong) UIWindow *window;+@property (nonatomic, strong) UINavigationController *nav;+@end++@implementation AppDelegate++- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)options {+ NSArray<NSString *> *args = NSProcessInfo.processInfo.arguments;+ NSUserDefaults *store = NSUserDefaults.standardUserDefaults;+ for (NSString *key in store.dictionaryRepresentation.allKeys) {+ if ([key hasPrefix:@"spotifyglass.liveActivity"]) [store removeObjectForKey:key];+ }+ NSDictionary<NSString *, NSString *> *ints = @{@"view": SGKeyLiveActivityView, @"size": SGKeyLiveActivityTextSize,+ @"without": SGKeyLiveActivityWithoutLyrics, @"align": SGKeyLiveActivityAlignment, @"colors": SGKeyLiveActivityColors};+ NSMutableArray<NSString *> *actions = [NSMutableArray array];+ for (NSString *arg in [args subarrayWithRange:NSMakeRange(1, args.count - 1)]) {+ NSArray<NSString *> *parts = [arg componentsSeparatedByString:@"="];+ if (parts.count == 2 && ints[parts[0]]) SGSetInt(ints[parts[0]], parts[1].integerValue);+ else if ([arg isEqualToString:@"translation"]) SGSetEnabled(SGKeyLiveActivityTranslation, YES);+ else if ([arg isEqualToString:@"artwork-off"]) SGSetEnabled(SGKeyLiveActivityArtwork, NO);+ else if ([arg isEqualToString:@"bar-off"]) SGSetEnabled(SGKeyLiveActivityProgressBar, NO);+ else if (![arg hasPrefix:@"-"]) [actions addObject:arg];+ }++ self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];+ self.window.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;+ self.nav = [[UINavigationController alloc] initWithRootViewController:SGLiveActivitySettingsPage()];+ self.window.rootViewController = self.nav;+ [self.window makeKeyAndVisible];++ [actions enumerateObjectsUsingBlock:^(NSString *action, NSUInteger i, BOOL *stop) {+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((1 + 0.7 * i) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ NSLog(@"[harness] %@", action);+ [self run:action];+ });+ }];+ return YES;+}++- (void)run:(NSString *)action {+ UITableView *table = ((UITableViewController *)self.nav.topViewController).tableView;+ UIView *preview = table.tableHeaderView;+ if ([action isEqualToString:@"tap"]) {+ [preview accessibilityActivate];+ } else if ([action isEqualToString:@"stop"]) {+ [preview setValue:@NO forKey:@"running"];+ } else if ([action isEqualToString:@"dump"]) {+ NSLog(@"[harness] preview \"%@\", \"%@\", %.0f pt high", preview.accessibilityLabel, preview.accessibilityValue, preview.bounds.size.height);+ for (NSInteger section = 0; section < table.numberOfSections; section++) {+ NSMutableArray<NSString *> *rows = [NSMutableArray array];+ for (NSInteger row = 0; row < [table numberOfRowsInSection:section]; row++) {+ NSIndexPath *path = [NSIndexPath indexPathForRow:row inSection:section];+ if ([table rectForRowAtIndexPath:path].size.height < 1) continue;+ UITableViewCell *cell = [table cellForRowAtIndexPath:path];+ NSString *title = [(UIListContentConfiguration *)cell.contentConfiguration text] ?: cell.textLabel.text ?: @"?";+ [rows addObject:title];+ }+ NSLog(@"[harness] section %ld: %@", (long)section, [rows componentsJoinedByString:@", "]);+ }+ }+}++@end++int main(int argc, char *argv[]) {+ @autoreleasepool {+ return UIApplicationMain(argc, argv, nil, NSStringFromClass(AppDelegate.class));+ }+}diff --git a/harness/live-activity-page/stubs.m b/harness/live-activity-page/stubs.mnew file mode 100644index 00000000..82b9e64a--- /dev/null+++ b/harness/live-activity-page/stubs.m@@ -0,0 +1,17 @@+// The activity's and the sleep timer's side of the page (LiveActivity.x and SleepTimer.m in the tweak): the switch is+// logged, the fade's names are the tweak's.+#import "Core/SGCore.h"+#import "Shared/LiveActivity/LiveActivity.h"+#import "Shared/Player/SleepTimer.h"++void SGSetLiveActivityEnabled(BOOL on) {+ NSLog(@"[harness] the Live Activity is switched %@", on ? @"on" : @"off");+}++NSArray<NSString *> *SGSleepTimerFadeNames(void) {+ return @[@"Off", @"10 s", @"30 s", @"1 minute", @"2 minutes"];+}++NSInteger SGSleepTimerFadeChoice(void) {+ return SGInt(SGKeySleepTimerFade, 1);+}diff --git a/tweak/Sources/Shared/LiveActivity/LiveActivity.h b/tweak/Sources/Shared/LiveActivity/LiveActivity.hindex 621ffd77..d9d54e74 100644--- a/tweak/Sources/Shared/LiveActivity/LiveActivity.h+++ b/tweak/Sources/Shared/LiveActivity/LiveActivity.h@@ -14,6 +14,7 @@// with the activity on or off; checked in the simulator (harness/shortcuts)// AppShortcuts.swift Spotify's App Shortcuts, tweak only// LiveActivitySettings.m its page, opened from the root of Mod Settings+// SGLiveActivityPreview.m the page's preview, a mock of the card on a slice of the lock screen//// Every tap in the card runs an intent inside Spotify and takes a second or two to show on the card.//@@ -21,6 +22,7 @@// intent runs in Spotify, so scripts/merge-appintents.py adds it to Spotify's App Intents metadata. The lines and// the clock come from Shared/Lyrics, the queue from the player's state. The switch and the view apply at// once: iOS lets an activity start only while the app is in front, which it is when the switch is flipped.+// The page's other options are read on every tick and sent in the state, so they apply within a tick too.//// The Swift names crossing into the widget (SGLyricsAttributes, the intents and their enums, the notifications)// are a contract with extension/LiveActivity and with the App Intents metadata merged into Spotify:@@ -35,6 +37,15 @@// SGLiveActivityTextSize.#define SGKeyLiveActivityTranslation @"spotifyglass.liveActivity.translation"#define SGKeyLiveActivityTextSize @"spotifyglass.liveActivity.textSize"+// The lyrics view's too: what it shows on a track with no timed lyrics, an SGLiveActivityWithoutLyrics, and+// the lines' alignment, an SGLiveActivityAlignment.+#define SGKeyLiveActivityWithoutLyrics @"spotifyglass.liveActivity.withoutLyrics"+#define SGKeyLiveActivityAlignment @"spotifyglass.liveActivity.alignment"+// Every view's: the cover beside the track and in the Dynamic Island (on until switched off), the card's+// colors, an SGLiveActivityColors, and the progress bar (on until switched off).+#define SGKeyLiveActivityArtwork @"spotifyglass.liveActivity.artwork"+#define SGKeyLiveActivityColors @"spotifyglass.liveActivity.colors"+#define SGKeyLiveActivityProgressBar @"spotifyglass.liveActivity.progressBar"// What the keys were called while this was the redesign's alone; LiveActivity.x's %ctor moves them over.#define SGKeyLiveActivityWas @"spotifyglass.redesign.liveActivity"#define SGKeyLiveActivityViewWas @"spotifyglass.redesign.liveActivity.view"@@ -52,9 +63,30 @@ typedef NS_ENUM(NSInteger, SGLiveActivityTextSize) {SGLiveActivityTextLarge,};+// SGLyricsAttributes.ContentState's withoutLyrics: a note under the track, or the track large in place of the lines.+typedef NS_ENUM(NSInteger, SGLiveActivityWithoutLyrics) {+ SGLiveActivityWithoutLyricsNote = 0,+ SGLiveActivityWithoutLyricsTrack,+};++// SGLyricsAttributes.ContentState's alignment, of the lyric lines.+typedef NS_ENUM(NSInteger, SGLiveActivityAlignment) {+ SGLiveActivityAlignLeft = 0,+ SGLiveActivityAlignCenter,+};++// SGLyricsAttributes.ContentState's colors: Spotify's (the cover's color darkened behind Spotify's green),+// the cover's (the same behind the cover's color lightened) or plain (white on the system's background).+typedef NS_ENUM(NSInteger, SGLiveActivityColors) {+ SGLiveActivityColorsSpotify = 0,+ SGLiveActivityColorsArtwork,+ SGLiveActivityColorsPlain,+};+// From the switch: starts following the player (and the activity, the app being in front) or ends both.void SGSetLiveActivityEnabled(BOOL on);@class UIViewController;-// The Live Activity page: its switch, which view it shows, and the lyrics' translation and size.+// The Live Activity page: a preview of the card (SGLiveActivityPreview.m), its switch, which view it shows, the+// lyrics' options and the card's.UIViewController *SGLiveActivitySettingsPage(void);diff --git a/tweak/Sources/Shared/LiveActivity/LiveActivity.x b/tweak/Sources/Shared/LiveActivity/LiveActivity.xindex b56346ee..8dec1764 100644--- a/tweak/Sources/Shared/LiveActivity/LiveActivity.x+++ b/tweak/Sources/Shared/LiveActivity/LiveActivity.x@@ -28,7 +28,9 @@ API_AVAILABLE(ios(17.0))tab:(NSInteger)tab title:(NSString *)title artist:(NSString *)artist shuffle:(BOOL)shuffle repeatMode:(NSInteger)repeatModetimerEnd:(NSDate *)timerEnd timerEndOfTrack:(BOOL)timerEndOfTrack timerEndOfAlbum:(BOOL)timerEndOfAlbumtint:(NSString *)tint trackStart:(NSDate *)trackStart trackEnd:(NSDate *)trackEnd pausedAt:(NSNumber *)pausedAt- translation:(NSString *)translation cover:(NSData *)cover textSize:(NSInteger)textSize;+ translation:(NSString *)translation cover:(NSData *)cover textSize:(NSInteger)textSize+ alignment:(NSInteger)alignment noLyrics:(BOOL)noLyrics withoutLyrics:(NSInteger)withoutLyrics+ colors:(NSInteger)colors accent:(NSString *)accent progressBar:(BOOL)progressBar;+ (void)end;+ (void)endBeforeExit;@end@@ -67,11 +69,19 @@ static const NSTimeInterval kStartSlack = 1.5;// The card's background is at most this light, as relative luminance (about #383838), so every white on// it keeps 4.5:1: the dimmest, at 0.6, comes to about 5.3:1 there, the line itself over 11:1.static const double kTintLuminance = 0.04;+// Colors' Artwork accent is at least this light, as relative luminance: about Spotify's green's, so a lit chip+// reads as well as it does in Spotify's colors, and text in it keeps over 5:1 on the lightest card,+// (0.48 + 0.05) / (0.04 + 0.05).+static const double kAccentLuminance = 0.48;static NSTimer *sg_timer;static NSTimeInterval sg_tickEvery;static NSString *sg_shown;static NSString *sg_missingLyrics;+// The tracks whose look for lyrics ended (SGKaraokeLinesKeptNotification), with lines or without: a set, since+// the track up next is looked up too, ahead of the one playing.+// ponytail: grows by one short ID a track for the session; clear it on a track change if that ever matters.+static NSMutableSet<NSString *> *sg_lookEnded;static NSDate *sg_lastStart;static NSDate *sg_lastSent;static SGLiveActivityTab sg_tab;@@ -126,8 +136,10 @@ static NSInteger repeatModeOf(SPTPlayerOptions *options) {}// The line being sung and the one after it; before the first line, between lines and without lyrics-// at all, a note holds the place.-static NSString *lyricsLine(NSString *trackID, NSString **next, NSString **translation) {+// at all, a note holds the place. `none` says the track has no timed lines to follow, no lyrics or plain text,+// and only once a look for them has ended and no other is under way: a look that never ends, as with+// EeveeSpotify answering the lyrics, leaves the track in the note's place without the line saying so.+static NSString *lyricsLine(NSString *trackID, NSString **next, NSString **translation, BOOL *none) {NSArray<SGKaraokeLine *> *lines = SGKaraokeLinesForTrack(trackID);if (!lines) {SGKaraokeRequestLyrics(trackID);@@ -138,6 +150,7 @@ static NSString *lyricsLine(NSString *trackID, NSString **next, NSString **trans}// Plain text has no line being sung: the note, as for a track with no lyrics.if (lines && SGKaraokeLinesTiming(lines) == SGKaraokeTimingNone) lines = nil;+ *none = !lines && [sg_lookEnded containsObject:trackID] && !SGKaraokeLooking(trackID);NSInteger position = SGKaraokePositionMs();if (position >= 0 && !SGPlayerState().isPaused) position += kRenderLeadMs;if (position >= 0) position -= SGKaraokeDelayMs();@@ -152,17 +165,17 @@ static NSString *lyricsLine(NSString *trackID, NSString **next, NSString **transreturn SGKaraokeLineText(current);}-// The cover for the card, read once a track from Spotify's now playing artwork: its colour, darkened so+// The cover for the card, read once a track from Spotify's now playing artwork: its color, darkened so// white text keeps its contrast, and a small JPEG of it. At a track change the player moves a moment// before Spotify hands over the new artwork, so it is read only once the now playing title is the// track's (as Shared/LockScreenLyrics/LyricsArtwork.x does); until then the last track's stays. Spotify// hands over a placeholder first and the cover after it, a new artwork object each time, so a new// object for the same track is read again.-static NSString *sg_artTrack, *sg_tint;+static NSString *sg_artTrack, *sg_tint, *sg_accent;static NSData *sg_cover;static __weak id sg_artObject;-// The cover at the largest of a few sizes whose JPEG fits kCoverBytes, drawn in device RGB so no colour+// The cover at the largest of a few sizes whose JPEG fits kCoverBytes, drawn in device RGB so no color// profile rides along; nil when none fits.static NSData *coverJPEG(CGImageRef image) {for (NSNumber *side in @[@56, @48, @40, @32]) {@@ -188,7 +201,7 @@ static double linear(double channel) {return channel <= 0.04045 ? channel / 12.92 : pow((channel + 0.055) / 1.055, 2.4);}-// The card's background, RRGGBB: at most 0.55 of the cover's colour, the rest black, and darker still+// The card's background, RRGGBB: at most 0.55 of the cover's color, the rest black, and darker still// until it is no lighter than kTintLuminance. At a fixed 0.55 a white or yellow cover came out #8C8C8C.static NSString *tintOf(double red, double green, double blue) {double keep = 0.55;@@ -197,6 +210,16 @@ static NSString *tintOf(double red, double green, double blue) {return [NSString stringWithFormat:@"%02X%02X%02X", (int)(red * keep), (int)(green * keep), (int)(blue * keep)];}+// Colors' Artwork accent, RRGGBB: the cover's color mixed with white until it is at least kAccentLuminance.+static NSString *accentOf(double red, double green, double blue) {+ double white = 0;+ while (white < 1 && 0.2126 * linear(red + (255 - red) * white) + 0.7152 * linear(green + (255 - green) * white)+ + 0.0722 * linear(blue + (255 - blue) * white) < kAccentLuminance) white += 0.02;+ white = MIN(white, 1);+ return [NSString stringWithFormat:@"%02X%02X%02X", (int)(red + (255 - red) * white), (int)(green + (255 - green) * white),+ (int)(blue + (255 - blue) * white)];+}+static void readArtwork(SPTPlayerState *state, NSString *trackID) {if (!trackID) return;NSDictionary *info = MPNowPlayingInfoCenter.defaultCenter.nowPlayingInfo;@@ -216,6 +239,7 @@ static void readArtwork(SPTPlayerState *state, NSString *trackID) {CGContextRelease(context);sg_artTrack = trackID;sg_tint = tintOf(pixel[0], pixel[1], pixel[2]);+ sg_accent = accentOf(pixel[0], pixel[1], pixel[2]);sg_cover = coverJPEG(image.CGImage);static int logged;if (logged++ < 6) SGLog(@"live activity: cover of %@, %lu bytes", trackID, (unsigned long)sg_cover.length);@@ -233,12 +257,19 @@ static void tick(void) API_AVAILABLE(ios(17.0)) {NSTimeInterval every = paused ? kPausedTick : kTick;if (sg_timer && sg_tickEvery != every) startTimer(every);NSString *line = @"", *next = @"", *translation = nil;- if (view == SGLiveActivityLyrics) line = lyricsLine(trackID, &next, &translation);+ BOOL noLyrics = NO;+ if (view == SGLiveActivityLyrics) line = lyricsLine(trackID, &next, &translation, &noLyrics);if (!SGFlag(SGKeyLiveActivityTranslation, NO)) translation = nil;NSInteger textSize = view == SGLiveActivityLyrics ? SGInt(SGKeyLiveActivityTextSize, SGLiveActivityTextMedium) : SGLiveActivityTextMedium;+ NSInteger alignment = SGInt(SGKeyLiveActivityAlignment, SGLiveActivityAlignCenter);+ NSInteger withoutLyrics = SGInt(SGKeyLiveActivityWithoutLyrics, SGLiveActivityWithoutLyricsNote);readArtwork(state, trackID);NSString *tint = sg_tint;- NSData *cover = sg_cover;+ // Artwork off: no cover anywhere, the Dynamic Island's note in its place; the color is still the cover's.+ NSData *cover = SGEnabled(SGKeyLiveActivityArtwork) ? sg_cover : nil;+ NSInteger colors = SGInt(SGKeyLiveActivityColors, SGLiveActivityColorsSpotify);+ NSString *accent = colors == SGLiveActivityColorsArtwork ? sg_accent : nil;+ BOOL progressBar = SGEnabled(SGKeyLiveActivityProgressBar);// The bar runs by itself from where the track started; paused, it holds at the share played.double duration = [state respondsToSelector:@selector(duration)] ? state.duration : 0;NSInteger position = SGKaraokePositionMs();@@ -281,7 +312,8 @@ static void tick(void) API_AVAILABLE(ios(17.0)) {@(tab).stringValue, title, artist, shuffle ? @"1" : @"0", @(repeatMode).stringValue,@((long long)sleepEnd.timeIntervalSince1970).stringValue, @(sleepMode).stringValue, tint ?: @"", translation ?: @"",paused ? @"" : @((long long)trackStart.timeIntervalSince1970).stringValue, paused ? @(round(pausedAt.doubleValue * 100)).stringValue : @"",- cover ? sg_artTrack : @"", @(textSize).stringValue, nil];+ cover ? sg_artTrack : @"", @(textSize).stringValue, @(alignment).stringValue, noLyrics ? @"1" : @"0",+ @(withoutLyrics).stringValue, @(colors).stringValue, accent ?: @"", progressBar ? @"1" : @"0", nil];for (NSUInteger i = 0; i < titles.count; i++) [parts addObject:[NSString stringWithFormat:@"%@\t%@\t%@", titles[i], artists[i], uris[i]]];send([parts componentsJoinedByString:@"\n"], ^{[SGLiveActivityBridge showWithView:view paused:paused line:line nextLine:next titles:titles artists:artists uris:uris@@ -289,7 +321,8 @@ static void tick(void) API_AVAILABLE(ios(17.0)) {timerEnd:sleepEnd timerEndOfTrack:sleepMode == SGSleepTimerEndOfTracktimerEndOfAlbum:sleepMode == SGSleepTimerEndOfAlbumtint:tint trackStart:trackStart trackEnd:trackEnd pausedAt:pausedAt translation:translation- cover:cover textSize:textSize];+ cover:cover textSize:textSize alignment:alignment noLyrics:noLyrics+ withoutLyrics:withoutLyrics colors:colors accent:accent progressBar:progressBar];});}@@ -445,6 +478,12 @@ void SGSetLiveActivityEnabled(BOOL on) {SGMigrateKey(SGKeyLiveActivityWas, SGKeyLiveActivity);SGMigrateKey(SGKeyLiveActivityViewWas, SGKeyLiveActivityView);BOOL on = SGFlag(SGKeyLiveActivity, NO);+ // From launch, card on or off, so a look that ends before the card is switched on still counts. Posted on+ // the main queue, so no queue: it is noted before the post returns.+ sg_lookEnded = [NSMutableSet set];+ [NSNotificationCenter.defaultCenter addObserverForName:SGKaraokeLinesKeptNotification object:nil queue:nil usingBlock:^(NSNotification *note) {+ if ([note.object isKindOfClass:NSString.class]) [sg_lookEnded addObject:note.object];+ }];// Answered inside the post, which the intent makes on the main thread, so the reply is there when it returns.[NSNotificationCenter.defaultCenter addObserverForName:@"SGShortcut" object:nil queue:nil usingBlock:^(NSNotification *note) {NSMutableDictionary *reply = note.userInfo[@"reply"];diff --git a/tweak/Sources/Shared/LiveActivity/LiveActivityBridge.swift b/tweak/Sources/Shared/LiveActivity/LiveActivityBridge.swiftindex 2ceea468..9318b4db 100644--- a/tweak/Sources/Shared/LiveActivity/LiveActivityBridge.swift+++ b/tweak/Sources/Shared/LiveActivity/LiveActivityBridge.swift@@ -93,7 +93,8 @@ public final class SGLiveActivityBridge: NSObject {tab: Int, title: String, artist: String, shuffle: Bool, repeatMode: Int,timerEnd: Date?, timerEndOfTrack: Bool, timerEndOfAlbum: Bool,tint: String?, trackStart: Date?, trackEnd: Date?, pausedAt: NSNumber?, translation: String?,- cover: Data?, textSize: Int) {+ cover: Data?, textSize: Int, alignment: Int, noLyrics: Bool, withoutLyrics: Int,+ colors: Int, accent: String?, progressBar: Bool) {let tracks = titles.indices.map {SGLyricsAttributes.Track(title: titles[$0], artist: artists[$0], uri: uris[$0])}@@ -103,7 +104,9 @@ public final class SGLiveActivityBridge: NSObject {tab: SGLyricsAttributes.Tab(rawValue: tab) ?? .controls, title: title, artist: artist,shuffle: shuffle, repeatMode: repeatMode, timerEnd: timerEnd, timerEndOfTrack: timerEndOfTrack,tint: tint, trackStart: trackStart, trackEnd: trackEnd, pausedAt: pausedAt?.doubleValue,- translation: translation, cover: cover, textSize: textSize, timerEndOfAlbum: timerEndOfAlbum)+ translation: translation, cover: cover, textSize: textSize, timerEndOfAlbum: timerEndOfAlbum,+ alignment: alignment, noLyrics: noLyrics, withoutLyrics: withoutLyrics, colors: colors, accent: accent,+ progressBar: progressBar)// ActivityKit drops a state over 4 KB without a word and the card freezes, so with long lines and// a busy cover the cover gives way.if cover != nil, let size = try? JSONEncoder().encode(state).count, size > maxStateBytes {diff --git a/tweak/Sources/Shared/LiveActivity/LiveActivitySettings.m b/tweak/Sources/Shared/LiveActivity/LiveActivitySettings.mindex 77a335d2..dfc627a5 100644--- a/tweak/Sources/Shared/LiveActivity/LiveActivitySettings.m+++ b/tweak/Sources/Shared/LiveActivity/LiveActivitySettings.m@@ -1,29 +1,105 @@-// The Live Activity page (App/ModSettings.x links it from the root, under either look).+// The Live Activity page (App/ModSettings.x links it from the root, under either look): the preview at its top+// (SGLiveActivityPreview.m), then the switch, the view and the card's options, which the tick reads, so they+// apply at once to a card that is showing.#import "Core/SGCore.h"#import "Settings/SGModPage.h"#import "Shared/Player/SleepTimer.h"#import "LiveActivity.h"+#import "SGLiveActivityPreview.h"static NSArray<NSString *> *viewNames(void) {return @[@"Lyrics", @"Queue", @"Control menu"];}+@interface SGLiveActivityPage : SGModPage+@property (nonatomic, strong) SGLiveActivityPreview *preview;+@end++@implementation SGLiveActivityPage++- (void)viewDidLoad {+ [super viewDidLoad];+ self.tableView.tableHeaderView = self.preview;+}++// Handed back to the table only when its size changes (SGFitNote's way: the table lays out again on every handing back).+- (void)viewWillLayoutSubviews {+ [super viewWillLayoutSubviews];+ UITableView *table = self.tableView;+ CGFloat width = table.bounds.size.width;+ self.preview.layoutMargins = UIEdgeInsetsMake(0, table.layoutMargins.left, 0, table.layoutMargins.right);+ CGSize size = CGSizeMake(width, [self.preview heightForWidth:width]);+ if (CGSizeEqualToSize(self.preview.bounds.size, size)) return;+ self.preview.frame = (CGRect){CGPointZero, size};+ table.tableHeaderView = self.preview;+}++// Back from Shows' or Text size's list, the preview reads them again.+- (void)viewWillAppear:(BOOL)animated {+ [super viewWillAppear:animated];+ [self.preview reload];+}++- (void)viewDidAppear:(BOOL)animated {+ [super viewDidAppear:animated];+ self.preview.running = YES;+}++- (void)viewWillDisappear:(BOOL)animated {+ [super viewWillDisappear:animated];+ self.preview.running = NO;+}++@end++// A menu row of `names` stored under `key`, which shows the preview the new choice.+static SGModRow *menuRow(NSString *title, NSString *key, NSArray<NSString *> *names, NSInteger fallback, SGLiveActivityPreview *preview) {+ __weak SGLiveActivityPreview *weakPreview = preview;+ return SGMenuRow(title, names, ^NSString *{+ NSInteger index = SGInt(key, fallback);+ return names[(NSUInteger)(index >= 0 && index < (NSInteger)names.count ? index : fallback)];+ }, ^(NSInteger index) {+ SGSetInt(key, index);+ [weakPreview reload];+ });+}+UIViewController *SGLiveActivitySettingsPage(void) {+ SGLiveActivityPreview *preview = [SGLiveActivityPreview new];+ __weak SGLiveActivityPreview *weakPreview = preview;+ void (^switched)(BOOL) = ^(BOOL on) { [weakPreview reload]; };+SGModRow *on = SGOptionRow(@"Live Activity", nil, SGKeyLiveActivity);on.changed = ^(BOOL value) { SGSetLiveActivityEnabled(value); };SGModRow *view = SGChoiceRow(@"Shows", nil, SGKeyLiveActivityView, viewNames(), SGLiveActivityLyrics);- // The lyrics view's own rows, shown while it is picked; the tick reads them, so they apply at once.+ // The lyrics view's own rows, shown while it is picked.+ SGModRow *without = menuRow(@"Without lyrics", SGKeyLiveActivityWithoutLyrics, @[@"Note", @"Track"], SGLiveActivityWithoutLyricsNote, preview);+ SGModRow *alignment = menuRow(@"Alignment", SGKeyLiveActivityAlignment, @[@"Left", @"Center"], SGLiveActivityAlignCenter, preview);SGModRow *translation = SGOptionRow(@"Translations", @"Under the line, when the lyrics have one", SGKeyLiveActivityTranslation);+ translation.changed = switched;SGModRow *size = SGChoiceRow(@"Text size", nil, SGKeyLiveActivityTextSize, @[@"Small", @"Medium", @"Large"], SGLiveActivityTextMedium);- for (SGModRow *row in @[translation, size]) row.visible = ^BOOL { return SGInt(SGKeyLiveActivityView, SGLiveActivityLyrics) == SGLiveActivityLyrics; };+ for (SGModRow *row in @[without, alignment, translation, size]) row.visible = ^BOOL { return SGInt(SGKeyLiveActivityView, SGLiveActivityLyrics) == SGLiveActivityLyrics; };+ // Every view's.+ SGModRow *artwork = SGSwitchRow(@"Artwork", @"The cover beside the track's name and in the Dynamic Island", SGKeyLiveActivityArtwork);+ artwork.changed = switched;+ SGModRow *colors = menuRow(@"Colors", SGKeyLiveActivityColors, @[@"Spotify", @"Artwork", @"Plain"], SGLiveActivityColorsSpotify, preview);+ SGModRow *progress = SGSwitchRow(@"Progress bar", nil, SGKeyLiveActivityProgressBar);+ progress.changed = switched;// The sleep timer's own: the card's Timer tab, the Sleep Timer shortcut and its control all fade by it, card on or// off, and so does Spotify's own timer from the player's menu (Shared/Player/SpotifySleepTimer.m).NSArray<NSString *> *fades = SGSleepTimerFadeNames();SGModRow *fade = SGMenuRow(@"Fade out", fades, ^NSString *{ return fades[(NSUInteger)SGSleepTimerFadeChoice()]; },^(NSInteger index) { SGSetInt(SGKeySleepTimerFade, index); });- return [[SGModPage alloc] initWithTitle:@"Live Activity" intro:nil sections:@[- SGSection(nil, @[on, view, translation, size]),+ SGLiveActivityPage *page = [[SGLiveActivityPage alloc] initWithTitle:@"Live Activity" intro:nil sections:@[+ SGSection(nil, @[on, view, without, alignment, translation, size]),+ SGNotedSection(@"Card", @[artwork, colors, progress],+ @"Colors: Spotify puts the cover's color behind Spotify's green, Artwork takes the green from the cover too, "+ @"and Plain is white on the lock screen's own background. "+ @"The card also shows on a paired Apple Watch, in its Smart Stack, from iOS 18, and in CarPlay from iOS 26, "+ @"as a smaller card of the line or the track. A tap there opens Spotify on the iPhone."),SGNotedSection(@"Sleep timer", @[fade],@"How long the sound fades before a sleep timer pauses Spotify: the one set from the Timer tab, the Sleep Timer shortcut or Control Center, and Spotify's own from the player's ⋯ menu."),] footer:nil];+ page.preview = preview;+ return page;}diff --git a/tweak/Sources/Shared/LiveActivity/LiveActivityShared.swift b/tweak/Sources/Shared/LiveActivity/LiveActivityShared.swiftindex 3fae1c4f..79f959eb 100644--- a/tweak/Sources/Shared/LiveActivity/LiveActivityShared.swift+++ b/tweak/Sources/Shared/LiveActivity/LiveActivityShared.swift@@ -39,7 +39,7 @@ struct SGLyricsAttributes: ActivityAttributes {var repeatMode: Int // 0 off, 1 the playlist or album, 2 the trackvar timerEnd: Date? // the sleep timer's end, nil when none is setvar timerEndOfTrack: Bool- // The cover's colour as RRGGBB, darkened for white text; nil before it is read.+ // The cover's color as RRGGBB, darkened for white text; nil before it is read.var tint: String?// When the track started and ends at the speed it plays, for a progress bar that runs by itself;// nil when the length is not known. Paused, the bar holds at `pausedAt`.@@ -55,6 +55,20 @@ struct SGLyricsAttributes: ActivityAttributes {var textSize: Int?// The sleep timer pauses at the end of the album or playlist playing.var timerEndOfAlbum: Bool?+ // The page's options (LiveActivity.h), nil in a state from a build before them, which reads as each+ // one's default. The lyric lines' alignment, SGLiveActivityAlignment's values: 0 left, 1 center.+ var alignment: Int?+ // The track has no lyrics with a time on them, so the lyrics view has no line to show for all of it,+ // and what it shows then, SGLiveActivityWithoutLyrics's values: 0 a note under the track, 1 the track large.+ var noLyrics: Bool?+ var withoutLyrics: Int?+ // The card's colors, SGLiveActivityColors's values: 0 Spotify's (the cover's color, darkened, behind+ // green), 1 the cover's (the same behind `accent`, the cover's color lightened, RRGGBB), 2 white on the+ // system's own background.+ var colors: Int?+ var accent: String?+ // The track's progress bar; nil or true shows it.+ var progressBar: Bool?}}diff --git a/tweak/Sources/Shared/LiveActivity/SGLiveActivityPreview.h b/tweak/Sources/Shared/LiveActivity/SGLiveActivityPreview.hnew file mode 100644index 00000000..20b72534--- /dev/null+++ b/tweak/Sources/Shared/LiveActivity/SGLiveActivityPreview.h@@ -0,0 +1,16 @@+// The top of the Live Activity page: a slice of the lock screen, its date and clock over a mock of the card,+// drawn here in UIKit after extension/LiveActivity/LiveActivityWidget.swift's layout, with a made-up song. It+// follows the page's settings as they change, and shows the view picked under Shows, stepping through it every+// 3 s with a crossfade: the Lyrics view through a few lines being sung and then a track with no lyrics, the+// Control menu through its tabs. The Queue view rests, as the card does. Under Reduce Motion it rests on the+// first step and a tap moves it on. Threading: main thread only.+#import <UIKit/UIKit.h>++@interface SGLiveActivityPreview : UIView+// Steps only while this is on; the page turns it on while it shows.+@property (nonatomic) BOOL running;+// Reads the page's settings again. Another view crossfades in from its first step.+- (void)reload;+// The same at every width: the card is clipped at the 160 points iOS gives it, so the slice never changes height.+- (CGFloat)heightForWidth:(CGFloat)width;+@enddiff --git a/tweak/Sources/Shared/LiveActivity/SGLiveActivityPreview.m b/tweak/Sources/Shared/LiveActivity/SGLiveActivityPreview.mnew file mode 100644index 00000000..a6681fba--- /dev/null+++ b/tweak/Sources/Shared/LiveActivity/SGLiveActivityPreview.m@@ -0,0 +1,496 @@+// The card is built again for every step, from stack views that follow the widget's SwiftUI stacks one for one+// (FamilyView, LyricsView, QueueView, PanelView and its pages), at the sizes its text styles have at the default+// text size: it is a picture of the lock screen, so it does not grow with the page's text. The new card+// crossfades over the old one. The step timer runs only while the page shows and Spotify is in front.+#import "Core/SGCore.h"+#import "LiveActivity.h"+#import "SGLiveActivityPreview.h"++static const NSTimeInterval kStep = 3, kFade = 0.35;+static const CGFloat kTop = 4, kBottom = 16; // around the slice, inside the table's header+static const CGFloat kCorner = 30, kDateTop = 16, kCardGap = 8, kCardInset = 12, kSliceBottom = 14;+// iOS clips a lock screen Live Activity at this height, and the card here with it.+static const CGFloat kClip = 160;++// The widget's colors: Spotify's green, the chips' idle fill, and the made-up cover's color as LiveActivity.x+// works it out: darkened behind the card, lightened as Colors' Artwork accent.+static UIColor *green(void) { return [UIColor colorWithRed:0.12 green:0.84 blue:0.38 alpha:1]; }+static UIColor *idle(void) { return [UIColor colorWithWhite:1 alpha:0.08]; }+static UIColor *dim(CGFloat alpha) { return [UIColor colorWithWhite:1 alpha:alpha]; }+static UIColor *sampleTint(void) { return [UIColor colorWithRed:0x54 / 255.0 green:0x2C / 255.0 blue:0x32 / 255.0 alpha:1]; }+static UIColor *sampleAccent(void) { return [UIColor colorWithRed:0xD7 / 255.0 green:0xB0 / 255.0 blue:0xB5 / 255.0 alpha:1]; }++// The text styles the widget uses, at the default text size.+static UIFont *font(CGFloat size, UIFontWeight weight) { return [UIFont systemFontOfSize:size weight:weight]; }+static const CGFloat kHeadline = 17, kTitle3 = 20, kTitle2 = 22, kSubheadline = 15, kFootnote = 13, kCaption = 12, kCaption2 = 11;++// A made-up song.+static NSString *const kTitle = @"Paper Lanterns", *const kArtist = @"The Quiet Harbour";+static NSString *const kQuietTitle = @"Low Tide (Interlude)";+typedef struct { __unsafe_unretained NSString *line, *next, *translation; } Line;+static const Line kLines[] = {+ {@"We hung our wishes on paper lanterns", @"and watched them drift across the bay", @"Colgamos nuestros deseos en farolillos de papel"},+ {@"and watched them drift across the bay", @"Every light a little promise", @"y los vimos flotar por la bahía"},+ {@"Every light a little promise", @"the morning couldn't take away", @"Cada luz, una pequeña promesa"},+};+static const NSInteger kLineCount = 3;+static NSString *const kQueue[][2] = {+ {@"Salt and Static", @"Mira Vale"},+ {@"Northbound Lights", @"The Quiet Harbour"},+ {@"Glasshouse", @"Juniper & Cole"},+};++typedef NS_ENUM(NSInteger, Tab) { TabControls, TabQueue, TabTimer, TabCount };++static NSInteger stepsIn(NSInteger view) {+ switch (view) {+ case SGLiveActivityLyrics: return kLineCount + 1; // the lines, then a track with no lyrics+ case SGLiveActivityPanel: return TabCount;+ default: return 1;+ }+}++#pragma mark - pieces++static UILabel *label(NSString *text, UIFont *font, UIColor *color, NSInteger lines, NSTextAlignment alignment) {+ UILabel *label = [UILabel new];+ label.text = text;+ label.font = font;+ label.textColor = color;+ label.numberOfLines = lines;+ label.textAlignment = alignment;+ label.lineBreakMode = NSLineBreakByTruncatingTail;+ return label;+}++static UIStackView *stack(NSArray<UIView *> *views, UILayoutConstraintAxis axis, CGFloat spacing) {+ UIStackView *stack = [[UIStackView alloc] initWithArrangedSubviews:views];+ stack.axis = axis;+ stack.spacing = spacing;+ return stack;+}++static UIImageView *symbol(NSString *name, CGFloat size, UIFontWeight weight, UIColor *color) {+ UIImageSymbolWeight symbolWeight = weight >= UIFontWeightSemibold ? UIImageSymbolWeightSemibold : UIImageSymbolWeightRegular;+ UIImageSymbolConfiguration *config = [UIImageSymbolConfiguration configurationWithPointSize:size weight:symbolWeight];+ UIImageView *view = [[UIImageView alloc] initWithImage:[UIImage systemImageNamed:name withConfiguration:config]];+ view.tintColor = color;+ view.contentMode = UIViewContentModeCenter;+ [view setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];+ return view;+}++static void pin(UIView *view, CGFloat height) {+ [view.heightAnchor constraintEqualToConstant:height].active = YES;+}++// A rounded fill holding `content`, centered, or along its leading edge when `inset` is above 0.+static UIView *filled(UIView *content, UIColor *fill, CGFloat corner, CGFloat height, CGFloat inset) {+ UIView *box = [UIView new];+ box.backgroundColor = fill;+ box.layer.cornerRadius = corner;+ box.layer.cornerCurve = kCACornerCurveContinuous;+ content.translatesAutoresizingMaskIntoConstraints = NO;+ [box addSubview:content];+ pin(box, height);+ [content.centerYAnchor constraintEqualToAnchor:box.centerYAnchor].active = YES;+ if (inset > 0) {+ [content.leadingAnchor constraintEqualToAnchor:box.leadingAnchor constant:inset].active = YES;+ [content.trailingAnchor constraintEqualToAnchor:box.trailingAnchor constant:-inset].active = YES;+ } else {+ [content.centerXAnchor constraintEqualToAnchor:box.centerXAnchor].active = YES;+ [content.leadingAnchor constraintGreaterThanOrEqualToAnchor:box.leadingAnchor constant:2].active = YES;+ }+ return box;+}++// The made-up cover: a dusk over the bay, coral into plum, with a lantern low in it.+static UIImage *coverImage(void) {+ static UIImage *image;+ if (image) return image;+ CGFloat side = 104;+ image = [[[UIGraphicsImageRenderer alloc] initWithSize:CGSizeMake(side, side)] imageWithActions:^(UIGraphicsImageRendererContext *context) {+ CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();+ NSArray *colors = @[(id)[UIColor colorWithRed:0.94 green:0.54 blue:0.36 alpha:1].CGColor,+ (id)[UIColor colorWithRed:0.42 green:0.17 blue:0.44 alpha:1].CGColor];+ CGGradientRef gradient = CGGradientCreateWithColors(space, (__bridge CFArrayRef)colors, NULL);+ CGContextDrawLinearGradient(context.CGContext, gradient, CGPointZero, CGPointMake(side, side), 0);+ CGGradientRelease(gradient);+ CGColorSpaceRelease(space);+ [[UIColor colorWithRed:1 green:0.86 blue:0.55 alpha:0.9] setFill];+ [[UIBezierPath bezierPathWithOvalInRect:CGRectMake(side * 0.38, side * 0.5, side * 0.24, side * 0.28)] fill];+ [[UIColor colorWithWhite:0 alpha:0.25] setFill];+ UIRectFill(CGRectMake(0, side * 0.82, side, side * 0.18));+ }];+ return image;+}++static UIView *cover(CGFloat side) {+ UIImageView *view = [[UIImageView alloc] initWithImage:coverImage()];+ view.layer.cornerRadius = side / 6;+ view.layer.cornerCurve = kCACornerCurveContinuous;+ view.clipsToBounds = YES;+ [view.widthAnchor constraintEqualToConstant:side].active = YES;+ pin(view, side);+ return view;+}++// The widget's ProgressBar: SwiftUI's linear bar tinted white, held a little further on at each step.+static UIView *progressBar(CGFloat share) {+ UIView *track = [UIView new];+ track.backgroundColor = dim(0.22);+ track.layer.cornerRadius = 2;+ pin(track, 4);+ UIView *fill = [UIView new];+ fill.backgroundColor = UIColor.whiteColor;+ fill.layer.cornerRadius = 2;+ fill.translatesAutoresizingMaskIntoConstraints = NO;+ [track addSubview:fill];+ [NSLayoutConstraint activateConstraints:@[+ [fill.leadingAnchor constraintEqualToAnchor:track.leadingAnchor],+ [fill.topAnchor constraintEqualToAnchor:track.topAnchor],+ [fill.bottomAnchor constraintEqualToAnchor:track.bottomAnchor],+ [fill.widthAnchor constraintEqualToAnchor:track.widthAnchor multiplier:share],+ ]];+ return track;+}++#pragma mark - the card's views++// What the page's settings ask of the card.+typedef struct {+ NSInteger view, textSize, withoutLyrics, colors;+ BOOL centered, translation, artwork, progress;+} Look;++static UIColor *accentOf(Look look) {+ switch (look.colors) {+ case SGLiveActivityColorsArtwork: return sampleAccent();+ case SGLiveActivityColorsPlain: return UIColor.whiteColor;+ default: return green();+ }+}++static UIFont *lineFont(Look look) {+ CGFloat size = look.textSize == SGLiveActivityTextSmall ? kHeadline : look.textSize == SGLiveActivityTextLarge ? kTitle2 : kTitle3;+ return font(size, UIFontWeightBold);+}++static UIView *lyricsView(Look look, NSInteger step) {+ NSTextAlignment edge = look.centered ? NSTextAlignmentCenter : NSTextAlignmentNatural;+ if (step < kLineCount) {+ Line line = kLines[step];+ UILabel *sung = label(line.line, lineFont(look), UIColor.whiteColor, 2, edge);+ sung.adjustsFontSizeToFitWidth = YES;+ sung.minimumScaleFactor = 0.7;+ NSMutableArray<UIView *> *views = [NSMutableArray arrayWithObject:sung];+ if (look.translation) [views addObject:label(line.translation, font(kSubheadline, UIFontWeightMedium), dim(0.7), 2, edge)];+ [views addObject:label(line.next, font(kSubheadline, UIFontWeightSemibold), dim(0.6), 1, edge)];+ return stack(views, UILayoutConstraintAxisVertical, 4);+ }+ // A track with no lyrics: under Note, the track at its own size over a line saying so; under Track, the+ // track in the lines' size.+ if (look.withoutLyrics == SGLiveActivityWithoutLyricsNote) {+ UIStackView *note = stack(@[label(kQuietTitle, font(kHeadline, UIFontWeightSemibold), UIColor.whiteColor, 1, edge),+ label(kArtist, font(kSubheadline, UIFontWeightMedium), dim(0.6), 1, edge),+ label(@"No synced lyrics for this song", font(kCaption, UIFontWeightMedium), dim(0.6), 1, edge)],+ UILayoutConstraintAxisVertical, 2);+ [note setCustomSpacing:6 afterView:note.arrangedSubviews[1]];+ return note;+ }+ return stack(@[label(kQuietTitle, lineFont(look), UIColor.whiteColor, 1, edge),+ label(kArtist, font(kSubheadline, UIFontWeightMedium), dim(0.6), 1, edge)],+ UILayoutConstraintAxisVertical, 2);+}++static NSAttributedString *trackLine(NSString *title, NSString *artist, CGFloat size) {+ NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:title+ attributes:@{NSFontAttributeName: font(size, UIFontWeightSemibold), NSForegroundColorAttributeName: UIColor.whiteColor}];+ [text appendAttributedString:[[NSAttributedString alloc] initWithString:[@" " stringByAppendingString:artist]+ attributes:@{NSFontAttributeName: font(size, UIFontWeightRegular), NSForegroundColorAttributeName: dim(0.6)}]];+ return text;+}++static UIView *queueView(void) {+ NSMutableArray<UIView *> *views = [NSMutableArray arrayWithObject:label(@"Up next", font(kCaption, UIFontWeightSemibold), dim(0.6), 1, NSTextAlignmentNatural)];+ for (NSInteger i = 0; i < 3; i++) {+ UILabel *row = label(nil, nil, nil, 1, NSTextAlignmentNatural);+ row.attributedText = trackLine(kQueue[i][0], kQueue[i][1], kSubheadline);+ [row.heightAnchor constraintGreaterThanOrEqualToConstant:28].active = YES;+ [views addObject:row];+ }+ return stack(views, UILayoutConstraintAxisVertical, 4);+}++static UIView *chip(NSString *name, NSString *text, BOOL lit, Look look) {+ UIColor *color = lit ? accentOf(look) : UIColor.whiteColor;+ UIStackView *content = stack(@[symbol(name, kHeadline, UIFontWeightSemibold, color),+ label(text, font(kCaption2, UIFontWeightMedium), color, 1, NSTextAlignmentCenter)],+ UILayoutConstraintAxisVertical, 3);+ content.alignment = UIStackViewAlignmentCenter;+ return filled(content, lit ? [accentOf(look) colorWithAlphaComponent:0.22] : idle(), 12, 56, 0);+}++static UIStackView *chipRow(NSArray<UIView *> *chips, CGFloat spacing) {+ UIStackView *row = stack(chips, UILayoutConstraintAxisHorizontal, spacing);+ row.distribution = UIStackViewDistributionFillEqually;+ return row;+}++static UIView *panelView(Look look, NSInteger tab) {+ NSArray<NSString *> *symbols = @[@"slider.horizontal.3", @"list.bullet", @"moon.zzz"];+ NSArray<NSString *> *titles = @[@"Controls", @"Queue", @"Timer"];+ NSMutableArray<UIView *> *tabs = [NSMutableArray array];+ for (NSInteger i = 0; i < TabCount; i++) {+ BOOL on = i == tab;+ UIColor *color = on ? accentOf(look) : dim(0.7);+ NSMutableArray<UIView *> *parts = [NSMutableArray arrayWithObject:symbol(symbols[i], kCaption, UIFontWeightSemibold, color)];+ if (on) [parts addObject:label(titles[i], font(kCaption, UIFontWeightSemibold), color, 1, NSTextAlignmentCenter)];+ UIView *capsule = filled(stack(parts, UILayoutConstraintAxisHorizontal, 4), on ? [accentOf(look) colorWithAlphaComponent:0.22] : idle(), 16, 32, 0);+ [tabs addObject:capsule];+ }+ UIView *page;+ switch (tab) {+ case TabControls: {+ UILabel *track = label(nil, nil, nil, 1, NSTextAlignmentNatural);+ track.attributedText = trackLine(kTitle, kArtist, kSubheadline);+ page = stack(@[track, chipRow(@[chip(@"backward.fill", @"Previous", NO, look), chip(@"pause.fill", @"Pause", NO, look),+ chip(@"forward.fill", @"Next", NO, look), chip(@"shuffle", @"Shuffle", YES, look),+ chip(@"repeat", @"Repeat", NO, look)], 10)],+ UILayoutConstraintAxisVertical, 8);+ break;+ }+ case TabQueue: {+ NSMutableArray<UIView *> *rows = [NSMutableArray array];+ for (NSInteger i = 0; i < 3; i++) {+ UILabel *title = label(kQueue[i][0], font(kFootnote, UIFontWeightSemibold), UIColor.whiteColor, 1, NSTextAlignmentNatural);+ UILabel *artist = label(kQueue[i][1], font(kFootnote, UIFontWeightRegular), dim(0.6), 1, NSTextAlignmentNatural);+ [title setContentCompressionResistancePriority:UILayoutPriorityDefaultHigh + 1 forAxis:UILayoutConstraintAxisHorizontal];+ [artist setContentHuggingPriority:UILayoutPriorityDefaultLow - 1 forAxis:UILayoutConstraintAxisHorizontal];+ UIStackView *line = stack(@[symbol(@"play.fill", kCaption, UIFontWeightRegular, accentOf(look)), title, artist], UILayoutConstraintAxisHorizontal, 10);+ [rows addObject:filled(line, idle(), 10, 28, 10)];+ }+ page = stack(rows, UILayoutConstraintAxisVertical, 4);+ break;+ }+ default:+ page = chipRow(@[chip(@"moon", @"15m", NO, look), chip(@"moon", @"30m", NO, look), chip(@"moon", @"1h", NO, look),+ chip(@"music.note", @"Track", NO, look), chip(@"square.stack", @"Album", NO, look)], 8);+ }+ UIStackView *tabRow = chipRow(tabs, 6);+ return stack(@[tabRow, page], UILayoutConstraintAxisVertical, 6);+}++// FamilyView: the cover beside what the view shows, the bar under both; the control menu without the cover.+static UIView *card(Look look, NSInteger step) {+ BOOL panel = look.view == SGLiveActivityPanel;+ UIView *content = look.view == SGLiveActivityLyrics ? lyricsView(look, step) : panel ? panelView(look, step) : queueView();+ NSMutableArray<UIView *> *top = [NSMutableArray array];+ if (look.artwork && !panel) [top addObject:cover(52)];+ [top addObject:content];+ UIStackView *row = stack(top, UILayoutConstraintAxisHorizontal, 12);+ row.alignment = UIStackViewAlignmentCenter;+ NSMutableArray<UIView *> *rows = [NSMutableArray arrayWithObject:row];+ if (look.progress) [rows addObject:progressBar(0.3 + 0.06 * step)];+ UIStackView *family = stack(rows, UILayoutConstraintAxisVertical, panel ? 6 : 10);+ family.layoutMarginsRelativeArrangement = YES;+ family.directionalLayoutMargins = panel ? NSDirectionalEdgeInsetsMake(8, 12, 8, 12) : NSDirectionalEdgeInsetsMake(12, 16, 12, 16);++ // The card's background: the cover's color, or under Plain the system's material.+ UIView *background;+ if (look.colors == SGLiveActivityColorsPlain) {+ background = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleSystemMaterialDark]];+ } else {+ background = [UIView new];+ background.backgroundColor = sampleTint();+ }+ background.layer.cornerRadius = 22;+ background.layer.cornerCurve = kCACornerCurveContinuous;+ background.clipsToBounds = YES;+ family.translatesAutoresizingMaskIntoConstraints = NO;+ UIView *holder = [background isKindOfClass:UIVisualEffectView.class] ? ((UIVisualEffectView *)background).contentView : background;+ [holder addSubview:family];+ [NSLayoutConstraint activateConstraints:@[+ [family.leadingAnchor constraintEqualToAnchor:holder.leadingAnchor],+ [family.trailingAnchor constraintEqualToAnchor:holder.trailingAnchor],+ [family.topAnchor constraintEqualToAnchor:holder.topAnchor],+ ]];+ // Fitted at its width, the card's own height is the stack's; past the clip the stack runs on under it.+ NSLayoutConstraint *bottom = [family.bottomAnchor constraintEqualToAnchor:holder.bottomAnchor];+ bottom.priority = UILayoutPriorityDefaultHigh;+ bottom.active = YES;+ return background;+}++static NSString *stepName(NSInteger view, NSInteger step) {+ switch (view) {+ case SGLiveActivityLyrics:+ return step < kLineCount ? [NSString stringWithFormat:@"Lyrics, line %ld of %ld", (long)step + 1, (long)kLineCount]+ : @"Lyrics, a track with no synced lyrics";+ case SGLiveActivityPanel:+ return [@"Control menu, " stringByAppendingString:@[@"Controls tab", @"Queue tab", @"Timer tab"][step]];+ default:+ return @"Queue, the tracks up next";+ }+}++#pragma mark - the preview++@implementation SGLiveActivityPreview {+ UIView *_slice;+ CAGradientLayer *_wallpaper;+ UILabel *_date, *_clock;+ UIView *_card;+ NSTimer *_timer;+ NSInteger _view, _step;+}++- (instancetype)initWithFrame:(CGRect)frame {+ if (!(self = [super initWithFrame:frame])) return nil;+ _slice = [UIView new];+ _slice.layer.cornerRadius = kCorner;+ _slice.layer.cornerCurve = kCACornerCurveContinuous;+ _slice.clipsToBounds = YES;+ _slice.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;+ [self addSubview:_slice];+ // A dusk wallpaper, for the Plain card's material to have something to blur.+ _wallpaper = [CAGradientLayer layer];+ _wallpaper.colors = @[(id)[UIColor colorWithRed:0.16 green:0.29 blue:0.48 alpha:1].CGColor,+ (id)[UIColor colorWithRed:0.34 green:0.22 blue:0.52 alpha:1].CGColor,+ (id)[UIColor colorWithRed:0.09 green:0.06 blue:0.17 alpha:1].CGColor];+ _wallpaper.locations = @[@0, @0.45, @1];+ [_slice.layer addSublayer:_wallpaper];+ _date = label(nil, font(17, UIFontWeightSemibold), dim(0.85), 1, NSTextAlignmentCenter);+ UIFontDescriptor *rounded = [[UIFont systemFontOfSize:72 weight:UIFontWeightSemibold].fontDescriptor fontDescriptorWithDesign:UIFontDescriptorSystemDesignRounded];+ _clock = label(nil, [UIFont fontWithDescriptor:rounded size:72], dim(0.9), 1, NSTextAlignmentCenter);+ [_slice addSubview:_date];+ [_slice addSubview:_clock];++ _view = -1;+ [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(advance)]];+ self.isAccessibilityElement = YES;+ self.accessibilityLabel = @"Preview of the Live Activity on the lock screen";+ [self reload];+ return self;+}++- (CGFloat)sliceHeight {+ return kDateTop + ceil(_date.font.lineHeight) + ceil(_clock.font.lineHeight) + kCardGap + kClip + kSliceBottom;+}++- (CGFloat)heightForWidth:(CGFloat)width {+ return kTop + [self sliceHeight] + kBottom;+}++- (void)layoutSubviews {+ [super layoutSubviews];+ CGFloat inset = self.layoutMargins.left, width = self.bounds.size.width - inset - self.layoutMargins.right;+ _slice.frame = CGRectMake(inset, kTop, width, [self sliceHeight]);+ [CATransaction begin];+ [CATransaction setDisableActions:YES];+ _wallpaper.frame = _slice.bounds;+ [CATransaction commit];+ _date.frame = CGRectMake(0, kDateTop, width, ceil(_date.font.lineHeight));+ _clock.frame = CGRectMake(0, CGRectGetMaxY(_date.frame), width, ceil(_clock.font.lineHeight));+ [self placeCard:_card];+}++- (void)placeCard:(UIView *)card {+ CGFloat width = _slice.bounds.size.width - 2 * kCardInset;+ if (!card || width <= 0) return;+ CGSize fits = [card systemLayoutSizeFittingSize:CGSizeMake(width, UILayoutFittingCompressedSize.height)+ withHorizontalFittingPriority:UILayoutPriorityRequired verticalFittingPriority:UILayoutPriorityFittingSizeLevel];+ card.frame = CGRectMake(kCardInset, CGRectGetMaxY(_clock.frame) + kCardGap, width, MIN(kClip, ceil(fits.height)));+}++- (Look)look {+ NSInteger colors = SGInt(SGKeyLiveActivityColors, SGLiveActivityColorsSpotify);+ return (Look){+ .view = _view,+ .textSize = SGInt(SGKeyLiveActivityTextSize, SGLiveActivityTextMedium),+ .withoutLyrics = SGInt(SGKeyLiveActivityWithoutLyrics, SGLiveActivityWithoutLyricsNote),+ .colors = colors,+ .centered = SGInt(SGKeyLiveActivityAlignment, SGLiveActivityAlignCenter) == SGLiveActivityAlignCenter,+ .translation = SGFlag(SGKeyLiveActivityTranslation, NO),+ .artwork = SGEnabled(SGKeyLiveActivityArtwork),+ .progress = SGEnabled(SGKeyLiveActivityProgressBar),+ };+}++- (void)reload {+ NSInteger view = SGInt(SGKeyLiveActivityView, SGLiveActivityLyrics);+ if (view < SGLiveActivityLyrics || view > SGLiveActivityPanel) view = SGLiveActivityLyrics;+ if (view != _view) {+ _view = view;+ _step = 0;+ }+ [self show];+}++- (void)advance {+ _step = (_step + 1) % stepsIn(_view);+ [self show];+}++// Builds the step's card and crossfades it over the one showing; the clock is read again with it.+- (void)show {+ NSDate *now = [NSDate date];+ NSLocale *locale = NSLocale.currentLocale;+ NSDateFormatter *formatter = [NSDateFormatter new];+ formatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"EEEEdMMMM" options:0 locale:locale];+ _date.text = [formatter stringFromDate:now];+ // The lock screen's clock leaves AM and PM out.+ NSString *format = [NSDateFormatter dateFormatFromTemplate:@"jmm" options:0 locale:locale];+ formatter.dateFormat = [[format stringByReplacingOccurrencesOfString:@"a" withString:@""]+ stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];+ _clock.text = [formatter stringFromDate:now];++ UIView *old = _card;+ _card = card([self look], _step);+ [self placeCard:_card];+ NSInteger steps = stepsIn(_view);+ self.accessibilityValue = stepName(_view, _step);+ self.accessibilityTraits = steps > 1 ? UIAccessibilityTraitButton : UIAccessibilityTraitNone;+ self.accessibilityHint = steps > 1 ? @"Shows the next step" : nil;+ if (!old || !self.window) {+ [old removeFromSuperview];+ [_slice addSubview:_card];+ return;+ }+ [UIView transitionWithView:_slice duration:kFade+ options:UIViewAnimationOptionTransitionCrossDissolve | UIViewAnimationOptionAllowUserInteraction+ animations:^{+ [old removeFromSuperview];+ [self->_slice addSubview:self->_card];+ } completion:nil];+}++- (BOOL)accessibilityActivate {+ if (stepsIn(_view) < 2) return NO;+ [self advance];+ UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil);+ return YES;+}++- (void)setRunning:(BOOL)running {+ _running = running;+ [_timer invalidate];+ _timer = nil;+ if (!running) return;+ [self show];+ __weak SGLiveActivityPreview *weakSelf = self;+ _timer = [NSTimer scheduledTimerWithTimeInterval:kStep repeats:YES block:^(NSTimer *timer) { [weakSelf tick]; }];+}++// Under Reduce Motion it waits for a tap; off screen or with Spotify behind another app, it waits.+- (void)tick {+ if (!self.window || UIApplication.sharedApplication.applicationState != UIApplicationStateActive) return;+ if (UIAccessibilityIsReduceMotionEnabled() || stepsIn(_view) < 2) return;+ [self advance];+}++- (void)dealloc {+ [_timer invalidate];+}++@end