Skip to content

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 on a page of its own, showing the lyrics, the queue or a control menu

Vojtěch Škopek01111bbf8581
diff --git a/docs/tweaks.md b/docs/tweaks.md
index ecd99bca..720f1535 100644
--- a/docs/tweaks.md
+++ b/docs/tweaks.md
@@ -17,7 +17,7 @@
tweak/Sources/Diagnostics/ screen dumps, the tree server and the main thread hang sampler of FLEX builds
extension/LiveActivity/ the redesign's Live Activity widget, a WidgetKit extension of its own
scripts/ pipeline.sh (build + inject), build-extension.sh (the widget extension, without an
- Xcode project), install.sh (sign + install), record-trees.py, record-session.py,
+ Xcode project), merge-appintents.py (the widget's intents into Spotify's), install.sh (sign + install), record-trees.py, record-session.py,
dump-log.sh, extract-flags.py, publish.sh (release: version bump, site release.json)
trees/ recorded view trees, one per screen; the input for every new hook. trees/clean/ holds
the numbered snapshots per screen of record-session.py, taken of Spotify as it came
@@ -146,11 +146,14 @@ Redesigned:
samples go through a drum and bass analyzer on the render thread (SGRMusicAnalyzer.m, plain C), and a
thread of its own schedules the taps and the rumble for when the sound is heard (MusicHaptics.x). Both
switches apply at once; nothing plays while Spotify is not the active app
- LiveActivity/ the line being sung, with the next one under it, as a Live Activity on the lock screen and in the
- Dynamic Island, lyrics only (LiveActivity.h lists its files): a timer polls the player and sends a
- new state only when the line or the pause changes, local updates only, no push. The widget is extension/LiveActivity; ActivityKit pairs the two
+ LiveActivity/ a Live Activity on the lock screen and in the Dynamic Island in one of three views, the line being
+ sung with the next one under it, the tracks up next (a tap on one skipping ahead to it), or a control
+ menu of tabs, Controls (previous, play and pause, next, shuffle, repeat), Queue and a sleep Timer of
+ the mod's own that pauses Spotify (LiveActivity.h lists its files): a timer polls the player and
+ sends a new state only when what the view shows changes, local updates only, no push. Taps are
+ LiveActivityIntents run inside Spotify and take a second or two to show on the card. The widget is extension/LiveActivity; ActivityKit pairs the two
by the attributes' type in LiveActivityShared.swift, compiled into both. It starts only with Spotify
- in front, and its switch applies at once
+ in front; its switch and its view apply at once
App:
@@ -193,13 +196,14 @@ is set. Redesigned UI is the one switch between the two looks (see Layers): it g
The pages show only what the stored look has: a page opened after flipping the switch already shows
what the restart will bring. Then a card of parts. Navbar: the tab editor of the stored look, each with
its own list of tabs. Player: Gestures, Lyrics (the ordered list of lyrics sources, lyrics for every track,
-naming the source in the redesign, the lock screen, the Live Activity in the redesign, and glass lyrics in the native look), Blocked artists (with the count on the row) and Lock screen widget, which work with either look;
+naming the source in the redesign, the lock screen, and glass lyrics in the native look), Blocked artists (with the count on the row) and Lock screen widget, which work with either look;
in the native look also Now playing bar (its device button and its flags), Queue & devices, and
Spotify's own player screen (artwork background, glass header buttons, Disable Canvas and the sheet,
header, slider and sticky header flags, the cards under the player and the lyrics preview and player
buttons to hide); in the redesign instead Now playing (its device button), Vibrations, Controls (on until switched off) and Music Haptics
(off until switched on, with an ⓘ saying it follows the sound this iPhone plays while Spotify is open), both
-applying straight away. Home & Library, in the native look only:
+applying straight away. Live Activity, in the redesign only: its switch and which view it shows, Lyrics, Queue or Control menu, both
+applying straight away, the row reading out the view or Off. Home & Library, in the native look only:
the Gradient page (the wash behind the top of Home in one of eight colours, at three strengths and
four heights) and the Home flags, the parts of Home to hide including the DJ button and badge, the
playlist header, buttons and pills to hide, and the Library flags. Then Premium, ads & privacy
diff --git a/extension/LiveActivity/LiveActivityWidget.swift b/extension/LiveActivity/LiveActivityWidget.swift
index 19c62ede..84b357c5 100644
--- a/extension/LiveActivity/LiveActivityWidget.swift
+++ b/extension/LiveActivity/LiveActivityWidget.swift
@@ -1,10 +1,19 @@
-// The Live Activity's face: the line being sung with the next one under it, and nothing else. Built
-// with the tweak's LiveActivityShared.swift by scripts/build-extension.sh.
+// The Live Activity's face, one of three views: the line being sung with the next one under it, the
+// tracks up next, or the control menu, a tab bar over Controls, Queue and Timer. A tap reaches the
+// tweak as an intent and the new state takes over a second to render, so every on/off control is a
+// Toggle, whose look the system flips the moment it is tapped, and what only changes after the render
+// is marked invalidatable. iOS clips a lock screen Live Activity at 160 points, so every view is kept
+// under it. Built with the tweak's LiveActivityShared.swift by scripts/build-extension.sh.
import ActivityKit
+import AppIntents
import SwiftUI
import WidgetKit
-private let spotifyGreen = Color(red: 0.12, green: 0.84, blue: 0.38)
+private let green = Color(red: 0.12, green: 0.84, blue: 0.38)
+private let idle = Color.white.opacity(0.08)
+
+private typealias State = SGLyricsAttributes.ContentState
+private typealias Tab = SGLyricsAttributes.Tab
@main
struct SGLiveActivityBundle: WidgetBundle {
@@ -13,12 +22,31 @@ struct SGLiveActivityBundle: WidgetBundle {
}
}
+extension SGLyricsAttributes.Tab {
+ var symbol: String {
+ switch self {
+ case .controls: "slider.horizontal.3"
+ case .queue: "list.bullet"
+ case .timer: "moon.zzz"
+ }
+ }
+
+ var title: String {
+ switch self {
+ case .controls: "Controls"
+ case .queue: "Queue"
+ case .timer: "Timer"
+ }
+ }
+}
+
struct SGLyricsLiveActivity: Widget {
var body: some WidgetConfiguration {
ActivityConfiguration(for: SGLyricsAttributes.self) { context in
- LyricsView(state: context.state)
+ ContentView(state: context.state, upNext: 4)
.frame(maxWidth: .infinity, alignment: .leading)
- .padding(16)
+ .padding(.horizontal, context.state.view == .panel ? 12 : 16)
+ .padding(.vertical, 12)
.foregroundStyle(.white)
.activityBackgroundTint(Color.black.opacity(0.75))
.activitySystemActionForegroundColor(.white)
@@ -26,27 +54,55 @@ struct SGLyricsLiveActivity: Widget {
} dynamicIsland: { context in
DynamicIsland {
DynamicIslandExpandedRegion(.bottom) {
- LyricsView(state: context.state)
- .frame(maxWidth: .infinity, alignment: .leading)
- .padding(.horizontal, 4)
+ Group {
+ if context.state.view == .panel {
+ Summary(state: context.state)
+ } else {
+ ContentView(state: context.state, upNext: 3)
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, 4)
}
} compactLeading: {
Image(systemName: "music.note")
- .foregroundStyle(spotifyGreen)
+ .foregroundStyle(green)
} compactTrailing: {
- Image(systemName: context.state.paused ? "pause.fill" : "waveform")
- .foregroundStyle(spotifyGreen)
+ if let end = context.state.timerEnd, end > Date() {
+ Text(timerInterval: Date()...end, countsDown: true)
+ .monospacedDigit()
+ .foregroundStyle(green)
+ .frame(maxWidth: 44)
+ } else {
+ Image(systemName: context.state.paused ? "pause.fill" : "waveform")
+ .foregroundStyle(green)
+ }
} minimal: {
Image(systemName: "music.note")
- .foregroundStyle(spotifyGreen)
+ .foregroundStyle(green)
}
.widgetURL(URL(string: "spotify:"))
}
}
}
+private struct ContentView: View {
+ let state: State
+ let upNext: Int
+
+ var body: some View {
+ switch state.view {
+ case .lyrics: LyricsView(state: state)
+ case .queue: QueueView(state: state, upNext: upNext)
+ case .panel: PanelView(state: state)
+ }
+ }
+}
+
+// MARK: - Lyrics and queue
+
private struct LyricsView: View {
- let state: SGLyricsAttributes.ContentState
+ let state: State
var body: some View {
VStack(alignment: .leading, spacing: 4) {
@@ -63,3 +119,263 @@ private struct LyricsView: View {
}
}
}
+
+private struct QueueView: View {
+ let state: State
+ let upNext: Int
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 3) {
+ Text("Up next")
+ .font(.caption.weight(.semibold))
+ .foregroundStyle(.white.opacity(0.45))
+ if state.tracks.isEmpty {
+ Text("Nothing up next")
+ .font(.subheadline)
+ .foregroundStyle(.white.opacity(0.6))
+ }
+ ForEach(Array(state.tracks.prefix(upNext).enumerated()), id: \.offset) { _, track in
+ // A tap skips ahead to the track.
+ Button(intent: SGRPlayQueuedTrackIntent(track.uri)) {
+ (Text(track.title).fontWeight(.semibold) + Text(" " + track.artist).foregroundColor(.white.opacity(0.5)))
+ .font(.subheadline)
+ .lineLimit(1)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ }
+ }
+ }
+}
+
+// MARK: - Control menu
+
+// The expanded Dynamic Island has room for one line of the menu.
+private struct Summary: View {
+ let state: State
+
+ var body: some View {
+ Group {
+ switch state.tab {
+ case .controls:
+ Text("\(state.title) · \(state.artist)")
+ case .queue:
+ Text(state.tracks.first.map { "Next: \($0.title)" } ?? "Nothing up next")
+ case .timer:
+ if let end = state.timerEnd, end > Date() {
+ Text("Music stops in \(Text(timerInterval: Date()...end, countsDown: true))")
+ } else if state.timerEndOfTrack {
+ Text("Music stops at the end of this track")
+ } else {
+ Text("No sleep timer")
+ }
+ }
+ }
+ .font(.subheadline.weight(.semibold))
+ .lineLimit(1)
+ .invalidatableContent()
+ }
+}
+
+private struct PanelView: View {
+ let state: State
+
+ var body: some View {
+ VStack(spacing: 8) {
+ HStack(spacing: 6) {
+ ForEach(Tab.allCases, id: \.self) { tab in
+ Toggle(isOn: tab == state.tab, intent: SGRLiveActivityActionIntent("tab:\(tab.rawValue)")) {
+ EmptyView()
+ }
+ .toggleStyle(TabStyle(tab: tab))
+ }
+ }
+ Group {
+ switch state.tab {
+ case .controls: ControlsPage(state: state)
+ case .queue: QueuePage(state: state)
+ case .timer: TimerPage(state: state)
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ }
+}
+
+private struct TabStyle: ToggleStyle {
+ let tab: Tab
+
+ func makeBody(configuration: Configuration) -> some View {
+ HStack(spacing: 4) {
+ Image(systemName: tab.symbol)
+ if configuration.isOn {
+ Text(tab.title)
+ }
+ }
+ .font(.caption.weight(.semibold))
+ .frame(maxWidth: .infinity)
+ .frame(height: 24)
+ .background(Capsule().fill(configuration.isOn ? green.opacity(0.22) : idle))
+ .foregroundStyle(configuration.isOn ? green : .white.opacity(0.7))
+ }
+}
+
+private struct ChipLabel: View {
+ let symbol: String
+ let label: String
+
+ var body: some View {
+ VStack(spacing: 3) {
+ Image(systemName: symbol)
+ .font(.body.weight(.semibold))
+ Text(label)
+ .font(.caption2.weight(.medium))
+ .lineLimit(1)
+ .minimumScaleFactor(0.8)
+ }
+ .frame(maxWidth: .infinity)
+ .frame(height: 48)
+ }
+}
+
+private struct ChipStyle: ToggleStyle {
+ let symbol: String
+ var onSymbol: String?
+ let label: String
+ 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
+
+ func makeBody(configuration: Configuration) -> some View {
+ let on = configuration.isOn
+ ChipLabel(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)
+ }
+}
+
+private struct ChipButton: View {
+ let action: String
+ let symbol: String
+ let label: String
+ var lit = false
+
+ var body: some View {
+ Button(intent: SGRLiveActivityActionIntent(action)) {
+ ChipLabel(symbol: symbol, label: label)
+ .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(lit ? green.opacity(0.22) : idle))
+ .foregroundStyle(lit ? green : .white)
+ }
+ .buttonStyle(.plain)
+ }
+}
+
+private struct ControlsPage: View {
+ let state: State
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ HStack(spacing: 6) {
+ Text(state.title)
+ .font(.subheadline.weight(.semibold))
+ Text(state.artist)
+ .font(.subheadline)
+ .foregroundStyle(.white.opacity(0.55))
+ }
+ .lineLimit(1)
+ .invalidatableContent()
+ HStack(spacing: 6) {
+ ChipButton(action: "previous", symbol: "backward.fill", label: "Previous")
+ Toggle(isOn: !state.paused, intent: SGRLiveActivityActionIntent("toggle")) { EmptyView() }
+ .toggleStyle(ChipStyle(symbol: "play.fill", onSymbol: "pause.fill", label: "Play", onLabel: "Pause", lights: false))
+ ChipButton(action: "next", symbol: "forward.fill", label: "Next")
+ Toggle(isOn: state.shuffle, intent: SGRLiveActivityActionIntent("shuffle")) { EmptyView() }
+ .toggleStyle(ChipStyle(symbol: "shuffle", label: "Shuffle"))
+ // Three states, so a button: the new one shows once the render lands.
+ ChipButton(action: "repeat", symbol: state.repeatMode == 2 ? "repeat.1" : "repeat",
+ label: "Repeat", lit: state.repeatMode != 0)
+ .invalidatableContent()
+ }
+ }
+ }
+}
+
+private struct QueuePage: View {
+ let state: State
+
+ var body: some View {
+ VStack(spacing: 4) {
+ if state.tracks.isEmpty {
+ Text("Nothing up next")
+ .font(.footnote)
+ .foregroundStyle(.white.opacity(0.55))
+ .frame(maxWidth: .infinity, minHeight: 60)
+ }
+ ForEach(Array(state.tracks.prefix(3).enumerated()), id: \.offset) { _, track in
+ Button(intent: SGRPlayQueuedTrackIntent(track.uri)) {
+ HStack(spacing: 10) {
+ Image(systemName: "play.fill")
+ .font(.caption)
+ .foregroundStyle(green)
+ Text(track.title)
+ .font(.footnote.weight(.semibold))
+ Text(track.artist)
+ .font(.footnote)
+ .foregroundStyle(.white.opacity(0.55))
+ Spacer(minLength: 0)
+ }
+ .lineLimit(1)
+ .padding(.horizontal, 10)
+ .frame(height: 28)
+ .background(RoundedRectangle(cornerRadius: 10, style: .continuous).fill(idle))
+ }
+ .buttonStyle(.plain)
+ }
+ }
+ .invalidatableContent()
+ }
+}
+
+private struct TimerPage: View {
+ let state: State
+
+ var body: some View {
+ Group {
+ if (state.timerEnd.map { $0 > Date() } ?? false) || state.timerEndOfTrack {
+ HStack(alignment: .center, spacing: 12) {
+ VStack(alignment: .leading, spacing: 0) {
+ Text("Music stops")
+ .font(.caption)
+ .foregroundStyle(.white.opacity(0.55))
+ if let end = state.timerEnd {
+ Text(timerInterval: Date()...end, countsDown: true)
+ .font(.system(size: 34, weight: .bold).monospacedDigit())
+ .foregroundStyle(green)
+ } else {
+ Text("End of track")
+ .font(.title2.weight(.bold))
+ .foregroundStyle(green)
+ }
+ }
+ Spacer(minLength: 0)
+ HStack(spacing: 8) {
+ if state.timerEnd != nil {
+ ChipButton(action: "timer:add", symbol: "plus", label: "15 min")
+ }
+ ChipButton(action: "timer:cancel", symbol: "xmark", label: "Cancel")
+ }
+ .frame(width: state.timerEnd != nil ? 140 : 66)
+ }
+ } else {
+ HStack(spacing: 8) {
+ ChipButton(action: "timer:15", symbol: "moon", label: "15 min")
+ ChipButton(action: "timer:30", symbol: "moon", label: "30 min")
+ ChipButton(action: "timer:60", symbol: "moon", label: "1 hour")
+ ChipButton(action: "timer:track", symbol: "music.note", label: "End of track")
+ }
+ }
+ }
+ .invalidatableContent()
+ }
+}
diff --git a/scripts/build-extension.sh b/scripts/build-extension.sh
index 8e8fdb2d..335ed312 100755
--- a/scripts/build-extension.sh
+++ b/scripts/build-extension.sh
@@ -1,10 +1,12 @@
#!/usr/bin/env bash
-# Builds the Live Activity widget extension without an Xcode project.
+# Builds the Live Activity widget extension without an Xcode project, and the App Intents metadata
+# the host app needs for the widget's taps.
#
# scripts/build-extension.sh <host Info.plist> <out dir>
#
-# Writes <out dir>/SpotifyGlassLiveActivity.appex. Needs Xcode (xcode-select or DEVELOPER_DIR) for the
-# iPhoneOS Swift toolchain.
+# Writes <out dir>/SpotifyGlassLiveActivity.appex and <out dir>/app/Metadata.appintents, whose actions
+# pipeline.sh merges into Spotify's own. Needs Xcode (xcode-select or DEVELOPER_DIR): the metadata
+# processor ships only with it.
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
@@ -15,12 +17,37 @@ APPEX="$OUT/$NAME.appex"
SHARED="$ROOT/tweak/Sources/Redesigned/LiveActivity/LiveActivityShared.swift"
WIDGET="$ROOT/extension/LiveActivity/LiveActivityWidget.swift"
-rm -rf "$APPEX"
-mkdir -p "$APPEX"
+SDK="$(xcrun --sdk iphoneos --show-sdk-path)"
+TOOLCHAIN="$(dirname "$(dirname "$(dirname "$(xcrun --find swiftc)")")")"
+XCODE_BUILD="$(xcodebuild -version | sed -n 's/^Build version //p')"
+PROCESSOR="$(xcrun --find appintentsmetadataprocessor)"
+
+WORK="$OUT/.build"
+rm -rf "$APPEX" "$OUT/app" "$WORK"
+mkdir -p "$APPEX" "$OUT/app" "$WORK"
+
+# The protocols Xcode has swiftc record constant values for (SWIFT_EMIT_CONST_VALUE_PROTOCOLS in
+# Xcode's App Intents build rules); the metadata processor reads the intents out of those values.
+printf '%s\n' '["AppIntent","EntityQuery","AppEntity","TransientEntity","AppEnum","AppShortcutProviding","AppShortcutsProvider","AnyResolverProviding","AppIntentsPackage","DynamicOptionsProvider","_IntentValueRepresentable","_AssistantIntentsProvider","_GenerativeFunctionExtractable","IntentValueQuery","Resolver"]' > "$WORK/protocols.json"
+
+# metadata <module> <deployment target> <bundle dir> <sources...>
+metadata() {
+ local module="$1" deploy="$2" bundle="$3"; shift 3
+ local triple="arm64-apple-ios$deploy" dir="$WORK/$module"
+ mkdir -p "$dir"
+ printf '%s\n' "$@" > "$dir/sources.txt"
+ echo "$dir/$module.swiftconstvalues" > "$dir/constvals.txt"
+ xcrun --sdk iphoneos swiftc -typecheck -wmo -parse-as-library -target "$triple" -module-name "$module" \
+ -emit-const-values-path "$dir/$module.swiftconstvalues" -Xfrontend -const-gather-protocols-file -Xfrontend "$WORK/protocols.json" "$@"
+ "$PROCESSOR" --output "$bundle" --toolchain-dir "$TOOLCHAIN" --module-name "$module" --sdk-root "$SDK" \
+ --xcode-version "$XCODE_BUILD" --platform-family iOS --deployment-target "$deploy" --target-triple "$triple" \
+ --source-file-list "$dir/sources.txt" --swift-const-vals-list "$dir/constvals.txt" --force >/dev/null
+}
echo "==> building $NAME.appex"
xcrun --sdk iphoneos swiftc -O -wmo -parse-as-library -target arm64-apple-ios17.0 -module-name "$NAME" \
-Xlinker -e -Xlinker _NSExtensionMain -o "$APPEX/$NAME" "$SHARED" "$WIDGET"
+metadata "$NAME" 17.0 "$APPEX" "$SHARED" "$WIDGET"
sed -e "s/HOST_BUNDLE_ID/$(plutil -extract CFBundleIdentifier raw -o - "$HOST_PLIST")/" \
-e "s/HOST_SHORT_VERSION/$(plutil -extract CFBundleShortVersionString raw -o - "$HOST_PLIST")/" \
@@ -28,5 +55,10 @@ sed -e "s/HOST_BUNDLE_ID/$(plutil -extract CFBundleIdentifier raw -o - "$HOST_PL
"$ROOT/extension/LiveActivity/Info.plist" > "$APPEX/Info.plist"
plutil -convert binary1 "$APPEX/Info.plist"
+# The taps' intents run inside Spotify, so Spotify's metadata has to name them too, under the
+# module the tweak compiles them in (Theos names it after the tweak instance).
+metadata spotifyglass 16.0 "$OUT/app" "$SHARED"
+
codesign -f -s - "$APPEX" >/dev/null 2>&1
+rm -rf "$WORK"
echo " $APPEX"
diff --git a/scripts/merge-appintents.py b/scripts/merge-appintents.py
new file mode 100755
index 00000000..5287654f
--- /dev/null
+++ b/scripts/merge-appintents.py
@@ -0,0 +1,38 @@
+#!/usr/bin/env python3
+"""Adds the actions of a Metadata.appintents to the app's own inside an IPA, in place.
+
+ scripts/merge-appintents.py <ipa> <Payload/X.app/> <Metadata.appintents dir>
+
+The system looks an intent up in the metadata of the bundle that runs it, and a LiveActivityIntent
+runs in the app, so the widget's intents have to be listed in Spotify's file next to its own.
+"""
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+import zipfile
+
+ipa, app_dir, ours = sys.argv[1:4]
+member = f"{app_dir}Metadata.appintents/extract.actionsdata"
+version = f"{app_dir}Metadata.appintents/version.json"
+
+with zipfile.ZipFile(ipa) as z:
+ theirs = json.loads(z.read(member)) if member in z.namelist() else None
+with open(os.path.join(ours, "extract.actionsdata")) as f:
+ added = json.load(f)
+
+merged = added if theirs is None else {**theirs, "actions": {**theirs["actions"], **added["actions"]}}
+
+with tempfile.TemporaryDirectory() as tmp:
+ os.makedirs(os.path.join(tmp, os.path.dirname(member)))
+ with open(os.path.join(tmp, member), "w") as f:
+ json.dump(merged, f)
+ entries = [member]
+ if theirs is None:
+ shutil.copy(os.path.join(ours, "version.json"), os.path.join(tmp, version))
+ entries.append(version)
+ subprocess.run(["zip", "-q", os.path.abspath(ipa), *entries], cwd=tmp, check=True)
+
+print(f" {len(added['actions'])} actions added to {len(merged['actions']) - len(added['actions'])} of the app's")
diff --git a/scripts/pipeline.sh b/scripts/pipeline.sh
index 7ef22fec..bea0356b 100755
--- a/scripts/pipeline.sh
+++ b/scripts/pipeline.sh
@@ -98,6 +98,11 @@ echo "==> injecting"
# -w drops the Watch app: its companion-app key would still name com.spotify.client and block the install.
cyan -i "$IN" -o "$OUT" -f "${FILES[@]}" -l "$ROOT/plist/liquid-glass.plist" ${BUNDLE_ID:+-b "$BUNDLE_ID"} ${NAME:+-n "$NAME"} ${ICON:+-k "$ICON"} -w -s --overwrite
+if [ -n "${EXT_DIR:-}" ]; then
+ echo "==> adding the Live Activity intents to Spotify's App Intents metadata"
+ "$ROOT/scripts/merge-appintents.py" "$OUT" "$APP_DIR" "$EXT_DIR/app/Metadata.appintents"
+fi
+
echo "==> done: $OUT"
[ "$INSTALL" = 1 ] && exec "$ROOT/scripts/install.sh" "$OUT"
exit 0
diff --git a/tweak/Sources/App/ModSettings.x b/tweak/Sources/App/ModSettings.x
index 6781e59e..4da8f880 100644
--- a/tweak/Sources/App/ModSettings.x
+++ b/tweak/Sources/App/ModSettings.x
@@ -18,6 +18,7 @@
#import "Native/Home/Home.h"
#import "Shared/AdBlock/AdBlock.h"
#import "Shared/Flags/Flags.h"
+#import "Redesigned/LiveActivity/LiveActivity.h"
#import "App/About/About.h"
#import "Pages.h"
@@ -38,12 +39,19 @@ static UIViewController *modSettingsPage(void) {
if (signing) [sections addObject:SGSection(nil, @[signing])];
SGModRow *mod = pageRow(@"Mod", @"info.circle", ^UIViewController *{ return SGAboutPage(); });
mod.value = ^NSString *{ return @(SG_VERSION); };
- // Home & Library holds only the native look's switches, so the redesign has no such page.
+ // Home & Library holds only the native look's switches, so the redesign has no such page; the
+ // Live Activity is the redesign's alone.
NSMutableArray<SGModRow *> *parts = [NSMutableArray arrayWithArray:@[
pageRow(@"Navbar", @"dock.rectangle", ^UIViewController *{ return SGNavbarPage(); }),
pageRow(@"Player", @"play.circle", ^UIViewController *{ return SGPlayerSettingsPage(); }),
]];
- if (!SGRedesignedUIStored()) [parts addObject:pageRow(@"Home & Library", @"house", ^UIViewController *{ return SGHomeSettingsPage(); })];
+ if (SGRedesignedUIStored()) {
+ SGModRow *liveActivity = pageRow(@"Live Activity", @"platter.filled.top.iphone", ^UIViewController *{ return SGRLiveActivitySettingsPage(); });
+ liveActivity.value = ^NSString *{ return SGRLiveActivitySummary(); };
+ [parts addObject:liveActivity];
+ } else {
+ [parts addObject:pageRow(@"Home & Library", @"house", ^UIViewController *{ return SGHomeSettingsPage(); })];
+ }
[sections addObjectsFromArray:@[
SGAppearanceSection(),
SGSection(nil, parts),
diff --git a/tweak/Sources/App/Pages.m b/tweak/Sources/App/Pages.m
index 3aaa5fc0..5d6eaed8 100644
--- a/tweak/Sources/App/Pages.m
+++ b/tweak/Sources/App/Pages.m
@@ -52,13 +52,12 @@ UIViewController *SGNavbarPage(void) {
return SGRedesignedUIStored() ? SGRNavbarSettingsPage() : SGNavbarSettingsPage();
}
-// The redesign always draws Apple Music style lyrics, and only it names their source and has the Live
-// Activity; the native look has its glass card and page instead.
+// The redesign always draws Apple Music style lyrics, and only it names their source; the native look
+// has its glass card and page instead.
static UIViewController *lyricsPage(void) {
BOOL redesigned = SGRedesignedUIStored();
NSMutableArray<SGModRow *> *more = [NSMutableArray arrayWithObject:SGLockScreenLyricsRow()];
- if (redesigned) [more addObject:SGRLiveActivityRow()];
- else [more insertObject:SGGlassLyricsRow() atIndex:0];
+ if (!redesigned) [more insertObject:SGGlassLyricsRow() atIndex:0];
NSArray<SGModSection *> *sections = @[SGLyricsSourcesSection(redesigned), SGSection(nil, more)];
return [[SGModPage alloc] initWithTitle:@"Lyrics" intro:SGRestartNote sections:sections footer:nil];
}
diff --git a/tweak/Sources/Headers/SPTPlayer.h b/tweak/Sources/Headers/SPTPlayer.h
index 42eb0d69..3a3d12f7 100644
--- a/tweak/Sources/Headers/SPTPlayer.h
+++ b/tweak/Sources/Headers/SPTPlayer.h
@@ -13,6 +13,8 @@
@interface SPTPlayerOptions : NSObject
@property (nonatomic, readonly) BOOL shufflingContext;
+@property (nonatomic, readonly) BOOL repeatingContext;
+@property (nonatomic, readonly) BOOL repeatingTrack;
@end
@interface SPTPlayerState : NSObject
@@ -25,6 +27,8 @@
// Seconds. position runs on from positionAsOfTimestamp by the time elapsed since the state was made.
@property (nonatomic, readonly) double position;
@property (nonatomic, readonly) double positionAsOfTimestamp;
+// The track's length, in the same unit as position.
+@property (nonatomic, readonly) double duration;
// The tracks to come and the ones played, nearest first; SPTPlayerTrack each, read with a type check.
@property (nonatomic, readonly) NSArray *future;
@property (nonatomic, readonly) NSArray *reverse;
@@ -35,4 +39,15 @@
- (void)addPlayerObserver:(id)observer;
- (void)skipToNextTrack;
- (void)seekTo:(double)seconds;
+// The commands below take Spotify's options object, nil for the defaults, and return the command's
+// pending result.
+- (id)pause:(id)options;
+- (id)resume:(id)options;
+- (id)skipToNextTrackWithOptions:(id)options;
+- (id)skipToPreviousTrackWithOptions:(id)options;
+// Skips ahead to `track`, one of the state's future tracks.
+- (id)skipToNextTrackWithOptions:(id)options track:(SPTPlayerTrack *)track;
+- (id)setShufflingContext:(BOOL)on;
+- (id)setRepeatingContext:(BOOL)on;
+- (id)setRepeatingTrack:(BOOL)on;
@end
diff --git a/tweak/Sources/Redesigned/LiveActivity/LiveActivity.h b/tweak/Sources/Redesigned/LiveActivity/LiveActivity.h
index 4969a019..8cbe78d7 100644
--- a/tweak/Sources/Redesigned/LiveActivity/LiveActivity.h
+++ b/tweak/Sources/Redesigned/LiveActivity/LiveActivity.h
@@ -1,22 +1,37 @@
-// The redesign's Live Activity (Mod Settings > Player > Lyrics): the line being sung, with the next one
-// under it, on the lock screen and in the Dynamic Island (iOS 17+).
+// The redesign's Live Activity (Mod Settings > Live Activity), on the lock screen and in the Dynamic
+// Island (iOS 17+), in one of three views: the line being sung with the next one under it, the tracks
+// up next (a tap on one skipping ahead to it), or the control menu, tabs of Controls (previous, play and
+// pause, next, shuffle, repeat), Queue and a sleep Timer of the mod's own that pauses Spotify.
//
// LiveActivity.x polls the player, sends the activity a new state when what it shows changes
// LiveActivityBridge.swift ActivityKit, which is Swift only
-// LiveActivityShared.swift the attributes, compiled into the extension too
-// LiveActivitySettings.m the Lyrics page's row
+// LiveActivityShared.swift the attributes and the taps' intents, compiled into the extension too
+// LiveActivitySettings.m its page, opened from the root of Mod Settings
//
-// The widget is extension/LiveActivity, built into the IPA by scripts/build-extension.sh. The lines and
-// the clock come from Shared/Lyrics. The switch applies at once: iOS lets an activity start only while
-// the app is in front, which it is when the switch is flipped.
+// Every tap in the card runs an intent inside Spotify and takes a second or two to show on the card.
+//
+// The widget is extension/LiveActivity, built into the IPA by scripts/build-extension.sh; the tap's
+// 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.
// Threading: main thread only.
#import <Foundation/Foundation.h>
#define SGRKeyLiveActivity @"spotifyglass.redesign.liveActivity"
+// Which view it shows, the index into the page's list.
+#define SGRKeyLiveActivityView @"spotifyglass.redesign.liveActivity.view"
+
+typedef NS_ENUM(NSInteger, SGRLiveActivityView) {
+ SGRLiveActivityLyrics = 0,
+ SGRLiveActivityQueue,
+ SGRLiveActivityPanel, // the control menu
+};
// From the switch: starts following the player (and the activity, the app being in front) or ends both.
void SGRSetLiveActivityEnabled(BOOL on);
-@class SGModRow;
-// The Live Activity row of the Lyrics page.
-SGModRow *SGRLiveActivityRow(void);
+@class UIViewController;
+// The Live Activity page: its switch and which view it shows.
+UIViewController *SGRLiveActivitySettingsPage(void);
+// What the root's row reads out beside its chevron: the view shown, or Off.
+NSString *SGRLiveActivitySummary(void);
diff --git a/tweak/Sources/Redesigned/LiveActivity/LiveActivity.x b/tweak/Sources/Redesigned/LiveActivity/LiveActivity.x
index ed54fcf9..f023cee4 100644
--- a/tweak/Sources/Redesigned/LiveActivity/LiveActivity.x
+++ b/tweak/Sources/Redesigned/LiveActivity/LiveActivity.x
@@ -1,7 +1,10 @@
-// Polls the player and sends the activity a new state only when what it shows changes: a new line or
-// a pause. Spotify keeps playing in the background, so the timer keeps running there too.
+// Polls the player and sends the activity a new state only when what its view shows changes: the
+// lyrics' line, what is up next, the control menu's tab, track, shuffle, repeat or sleep timer, or a
+// pause. The view is read on every tick, so picking another one shows within a tick. Spotify keeps
+// playing in the background, so the timer keeps running there too, and with it the sleep timer.
// The activity is started only while the app is in front, the one place ActivityKit allows it.
#import <UIKit/UIKit.h>
+#import <objc/runtime.h>
#import "Core/SGCore.h"
#import "Headers/SPTPlayer.h"
#import "Shared/Lyrics/Lyrics.h"
@@ -10,28 +13,82 @@
API_AVAILABLE(ios(17.0))
@interface SGRLiveActivityBridge : NSObject
@property (class, nonatomic, readonly) BOOL isShowing;
-+ (void)showWithLine:(NSString *)line nextLine:(NSString *)nextLine paused:(BOOL)paused;
++ (void)showWithView:(NSInteger)view paused:(BOOL)paused line:(NSString *)line nextLine:(NSString *)nextLine
+ titles:(NSArray<NSString *> *)titles artists:(NSArray<NSString *> *)artists uris:(NSArray<NSString *> *)uris
+ tab:(NSInteger)tab title:(NSString *)title artist:(NSString *)artist shuffle:(BOOL)shuffle repeatMode:(NSInteger)repeatMode
+ timerEnd:(NSDate *)timerEnd timerEndOfTrack:(BOOL)timerEndOfTrack;
+ (void)end;
@end
+// The control menu's tabs, SGLyricsAttributes.Tab's values.
+typedef NS_ENUM(NSInteger, SGRLiveActivityTab) {
+ SGRLiveActivityTabControls = 0,
+ SGRLiveActivityTabQueue,
+ SGRLiveActivityTabTimer,
+};
+
static const NSTimeInterval kTick = 0.25;
// Past a line's sung end by this much, with the next line at least this far off, the line gives way to a note.
static const NSInteger kBreakMs = 4000;
// Seconds between attempts to start one, so a refused request (activities turned off) is not retried every tick.
static const NSTimeInterval kStartRetry = 10;
+// Tracks up next: the queue view shows four on the lock screen (three in the Dynamic Island), the
+// control menu's queue tab three.
+static const NSUInteger kUpNextQueue = 4;
+static const NSUInteger kUpNextPanel = 3;
+// The end of track timer pauses this close to the end, so the next track never starts.
+static const NSInteger kEndOfTrackMs = 500;
static NSTimer *sg_timer;
static NSString *sg_shown;
static NSString *sg_missingLyrics;
static NSDate *sg_lastStart;
+static SGRLiveActivityTab sg_tab;
+// The sleep timer: an end, or the end of the track it was set on.
+static NSDate *sg_sleepEnd;
+static NSString *sg_sleepTrack;
-static void tick(void) API_AVAILABLE(ios(17.0)) {
- id<SPTPlayer> player = SGKaraokePlayer();
- SPTPlayerState *state = player.state;
- SPTPlayerTrack *track = state.track;
- if (!track.trackTitle.length) return;
+// Sends `shown`, what the activity is to show as one string, unless it is showing that already; starts
+// the activity when there is none and the app is in front.
+static void send(NSString *shown, void (^show)(void)) API_AVAILABLE(ios(17.0)) {
+ if (SGRLiveActivityBridge.isShowing) {
+ if ([shown isEqualToString:sg_shown]) return;
+ } else {
+ if (UIApplication.sharedApplication.applicationState != UIApplicationStateActive) return;
+ if (sg_lastStart && -sg_lastStart.timeIntervalSinceNow < kStartRetry) return;
+ sg_lastStart = [NSDate date];
+ }
+ sg_shown = shown;
+ show();
+}
- NSString *trackID = SGKaraokePlayingTrack();
+// A track's URI as a string; the player hands out NSURL or NSString.
+static NSString *uriOf(SPTPlayerTrack *track) {
+ id uri = track.URI;
+ if ([uri isKindOfClass:NSURL.class]) return [(NSURL *)uri absoluteString];
+ return [uri isKindOfClass:NSString.class] ? uri : nil;
+}
+
+// The state's tracks up next, skipping what is not a track or has no title or URI.
+static NSArray<SPTPlayerTrack *> *upNext(SPTPlayerState *state) {
+ NSMutableArray<SPTPlayerTrack *> *tracks = [NSMutableArray array];
+ id future = [state respondsToSelector:@selector(future)] ? state.future : nil;
+ for (id track in [future isKindOfClass:NSArray.class] ? future : @[]) {
+ if (![track isKindOfClass:objc_getClass("SPTPlayerTrack")]) continue;
+ if (![(SPTPlayerTrack *)track trackTitle].length || !uriOf(track)) continue;
+ [tracks addObject:track];
+ }
+ return tracks;
+}
+
+// 0 off, 1 the playlist or album, 2 the track.
+static NSInteger repeatModeOf(SPTPlayerOptions *options) {
+ return options.repeatingTrack ? 2 : options.repeatingContext ? 1 : 0;
+}
+
+// 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) {
NSArray<SGKaraokeLine *> *lines = SGKaraokeLinesForTrack(trackID);
if (!lines) {
SGKaraokeRequestLyrics(trackID);
@@ -40,28 +97,142 @@ static void tick(void) API_AVAILABLE(ios(17.0)) {
SGLog(@"live activity: no lyrics yet for %@", trackID);
}
}
-
NSInteger position = SGKaraokePositionMs();
NSInteger index = -1;
while (index + 1 < (NSInteger)lines.count && lines[index + 1].start <= position) index++;
- // Before the first line, between lines and without lyrics at all, a note holds the place.
- NSString *line = @"♪", *next = index + 1 < (NSInteger)lines.count ? SGKaraokeLineText(lines[index + 1]) : @"";
- if (index >= 0) {
- SGKaraokeLine *current = lines[index];
- BOOL nextFarOff = index + 1 == (NSInteger)lines.count || lines[index + 1].start - position > kBreakMs;
- line = position > current.end + kBreakMs && nextFarOff ? @"♪" : SGKaraokeLineText(current);
+ *next = index + 1 < (NSInteger)lines.count ? SGKaraokeLineText(lines[index + 1]) : @"";
+ if (index < 0) return @"♪";
+ SGKaraokeLine *current = lines[index];
+ BOOL nextFarOff = index + 1 == (NSInteger)lines.count || lines[index + 1].start - position > kBreakMs;
+ return position > current.end + kBreakMs && nextFarOff ? @"♪" : SGKaraokeLineText(current);
+}
+
+static void clearSleepTimer(void) {
+ sg_sleepEnd = nil;
+ sg_sleepTrack = nil;
+}
+
+// Pauses once the sleep timer is up: at its end, or just before the end of the track it was set on
+// (on the next track, should the length not be known).
+static void checkSleepTimer(id<SPTPlayer> player, SPTPlayerState *state, NSString *trackID) {
+ BOOL up = NO;
+ if (sg_sleepEnd) {
+ up = sg_sleepEnd.timeIntervalSinceNow <= 0;
+ } else if (sg_sleepTrack) {
+ double duration = [state respondsToSelector:@selector(duration)] ? state.duration : 0;
+ NSInteger position = SGKaraokePositionMs();
+ up = ![trackID isEqualToString:sg_sleepTrack]
+ || (duration > 0 && position >= 0 && duration * 1000 - position < kEndOfTrackMs);
}
+ if (!up) return;
+ clearSleepTimer();
+ if (!state.isPaused) [player pause:nil];
+ SGLog(@"live activity: sleep timer up, paused");
+}
- NSString *shown = [@[line, next, state.isPaused ? @"1" : @"0"] componentsJoinedByString:@"\n"];
- if (SGRLiveActivityBridge.isShowing) {
- if ([shown isEqualToString:sg_shown]) return;
+static void tick(void) API_AVAILABLE(ios(17.0)) {
+ id<SPTPlayer> player = SGKaraokePlayer();
+ SPTPlayerState *state = player.state;
+ SPTPlayerTrack *track = state.track;
+ if (!track.trackTitle.length) return;
+ NSString *trackID = SGKaraokePlayingTrack();
+ checkSleepTimer(player, state, trackID);
+
+ NSInteger view = SGInt(SGRKeyLiveActivityView, SGRLiveActivityLyrics);
+ BOOL paused = state.isPaused;
+ NSString *line = @"", *next = @"";
+ if (view == SGRLiveActivityLyrics) line = lyricsLine(trackID, &next);
+
+ NSMutableArray<NSString *> *titles = [NSMutableArray array], *artists = [NSMutableArray array], *uris = [NSMutableArray array];
+ if (view != SGRLiveActivityLyrics) {
+ NSUInteger limit = view == SGRLiveActivityQueue ? kUpNextQueue : kUpNextPanel;
+ for (SPTPlayerTrack *upcoming in upNext(state)) {
+ if (titles.count == limit) break;
+ [titles addObject:upcoming.trackTitle];
+ [artists addObject:upcoming.artistName ?: @""];
+ [uris addObject:uriOf(upcoming)];
+ }
+ }
+
+ BOOL panel = view == SGRLiveActivityPanel;
+ NSString *title = panel ? track.trackTitle : @"", *artist = panel ? track.artistName ?: @"" : @"";
+ BOOL shuffle = panel && state.options.shufflingContext;
+ NSInteger repeatMode = panel ? repeatModeOf(state.options) : 0;
+ NSInteger tab = panel ? sg_tab : 0;
+ NSDate *sleepEnd = sg_sleepEnd;
+ BOOL endOfTrack = sg_sleepTrack != nil;
+
+ NSMutableArray<NSString *> *parts = [NSMutableArray arrayWithObjects:@(view).stringValue, paused ? @"1" : @"0", line, next,
+ @(tab).stringValue, title, artist, shuffle ? @"1" : @"0", @(repeatMode).stringValue,
+ @((long long)sleepEnd.timeIntervalSince1970).stringValue, endOfTrack ? @"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"], ^{
+ [SGRLiveActivityBridge showWithView:view paused:paused line:line nextLine:next titles:titles artists:artists uris:uris
+ tab:tab title:title artist:artist shuffle:shuffle repeatMode:repeatMode
+ timerEnd:sleepEnd timerEndOfTrack:endOfTrack];
+ });
+}
+
+// A tap on a track up next: skips ahead to it, found again by its URI in case the queue moved since
+// the card was drawn.
+static void playQueued(NSString *uri) {
+ id<SPTPlayer> player = SGKaraokePlayer();
+ SPTPlayerTrack *target = nil;
+ for (SPTPlayerTrack *track in upNext(player.state)) {
+ if ([uriOf(track) isEqualToString:uri]) { target = track; break; }
+ }
+ if (!target || ![player respondsToSelector:@selector(skipToNextTrackWithOptions:track:)]) {
+ SGLog(@"live activity: cannot play %@ (in the queue: %@, player %@)", uri, target ? @"yes" : @"no", player ? NSStringFromClass([player class]) : @"nil");
+ return;
+ }
+ id result = [player skipToNextTrackWithOptions:nil track:target];
+ SGLog(@"live activity: play %@ -> %@", uri, result);
+}
+
+// A tap in the control menu, one of SGRLiveActivityActionIntent's actions.
+static void runAction(NSString *action) {
+ id<SPTPlayer> player = SGKaraokePlayer();
+ SPTPlayerState *state = player.state;
+ NSArray<NSString *> *parts = [action componentsSeparatedByString:@":"];
+ NSString *name = parts.firstObject, *value = parts.count > 1 ? parts[1] : @"";
+ id result = nil;
+ if ([name isEqualToString:@"tab"]) {
+ sg_tab = MAX(SGRLiveActivityTabControls, MIN(SGRLiveActivityTabTimer, value.integerValue));
+ } else if ([name isEqualToString:@"toggle"]) {
+ result = state.isPaused ? [player resume:nil] : [player pause:nil];
+ } else if ([name isEqualToString:@"previous"]) {
+ result = [player skipToPreviousTrackWithOptions:nil];
+ } else if ([name isEqualToString:@"next"]) {
+ result = [player skipToNextTrackWithOptions:nil];
+ } else if ([name isEqualToString:@"shuffle"]) {
+ result = [player setShufflingContext:!state.options.shufflingContext];
+ } else if ([name isEqualToString:@"repeat"]) {
+ // Off, then the playlist or album, then the track, then off again, the way Spotify's button goes.
+ switch (repeatModeOf(state.options)) {
+ case 0: result = [player setRepeatingContext:YES]; break;
+ case 1: result = [player setRepeatingTrack:YES]; break;
+ default:
+ [player setRepeatingTrack:NO];
+ result = [player setRepeatingContext:NO];
+ }
+ } else if ([name isEqualToString:@"timer"]) {
+ if ([value isEqualToString:@"cancel"]) {
+ clearSleepTimer();
+ } else if ([value isEqualToString:@"track"]) {
+ clearSleepTimer();
+ sg_sleepTrack = SGKaraokePlayingTrack();
+ } else if ([value isEqualToString:@"add"]) {
+ NSDate *from = sg_sleepEnd && sg_sleepEnd.timeIntervalSinceNow > 0 ? sg_sleepEnd : [NSDate date];
+ sg_sleepEnd = [from dateByAddingTimeInterval:15 * 60];
+ } else if (value.integerValue > 0) {
+ clearSleepTimer();
+ sg_sleepEnd = [NSDate dateWithTimeIntervalSinceNow:value.integerValue * 60];
+ }
} else {
- if (UIApplication.sharedApplication.applicationState != UIApplicationStateActive) return;
- if (sg_lastStart && -sg_lastStart.timeIntervalSinceNow < kStartRetry) return;
- sg_lastStart = [NSDate date];
+ SGLog(@"live activity: unknown action %@", action);
+ return;
}
- sg_shown = shown;
- [SGRLiveActivityBridge showWithLine:line nextLine:next paused:state.isPaused];
+ SGLog(@"live activity: %@ -> %@", action, result);
}
void SGRSetLiveActivityEnabled(BOOL on) {
@@ -71,11 +242,25 @@ void SGRSetLiveActivityEnabled(BOOL on) {
sg_timer = nil;
sg_shown = nil;
sg_lastStart = nil;
+ clearSleepTimer();
if (!on) {
[SGRLiveActivityBridge end];
SGLog(@"live activity: off");
return;
}
+ static dispatch_once_t observing;
+ dispatch_once(&observing, ^{
+ NSNotificationCenter *center = NSNotificationCenter.defaultCenter;
+ [center addObserverForName:@"SGRLiveActivityPlay" object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *note) {
+ if ([note.object isKindOfClass:NSString.class]) playQueued(note.object);
+ }];
+ // The new state goes out at once rather than on the next tick, the card being slow enough to redraw.
+ [center addObserverForName:@"SGRLiveActivityAction" object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *note) {
+ if (![note.object isKindOfClass:NSString.class]) return;
+ runAction(note.object);
+ if (sg_timer) tick();
+ }];
+ });
sg_timer = [NSTimer timerWithTimeInterval:kTick repeats:YES block:^(NSTimer *t) { tick(); }];
[NSRunLoop.mainRunLoop addTimer:sg_timer forMode:NSRunLoopCommonModes];
SGLog(@"live activity: on");
diff --git a/tweak/Sources/Redesigned/LiveActivity/LiveActivityBridge.swift b/tweak/Sources/Redesigned/LiveActivity/LiveActivityBridge.swift
index 244ca60b..8e781bc4 100644
--- a/tweak/Sources/Redesigned/LiveActivity/LiveActivityBridge.swift
+++ b/tweak/Sources/Redesigned/LiveActivity/LiveActivityBridge.swift
@@ -15,8 +15,20 @@ public final class SGRLiveActivityBridge: NSObject {
@objc public static var isShowing: Bool { current != nil }
// A new activity can only be requested while the app is in the foreground; an update works from the background.
- @objc public static func show(line: String, nextLine: String, paused: Bool) {
- let state = SGLyricsAttributes.ContentState(line: line, nextLine: nextLine, paused: paused)
+ // One call per new state. View and tab are SGRLiveActivityView's and SGRLiveActivityTab's values;
+ // titles, artists and URIs pair up by index, the tracks up next; timerEnd is nil without a timer.
+ @objc public static func show(view: Int, paused: Bool, line: String, nextLine: String,
+ titles: [String], artists: [String], uris: [String],
+ tab: Int, title: String, artist: String, shuffle: Bool, repeatMode: Int,
+ timerEnd: Date?, timerEndOfTrack: Bool) {
+ let tracks = titles.indices.map {
+ SGLyricsAttributes.Track(title: titles[$0], artist: artists[$0], uri: uris[$0])
+ }
+ let state = SGLyricsAttributes.ContentState(
+ view: SGLyricsAttributes.View(rawValue: view) ?? .lyrics, paused: paused,
+ line: line, nextLine: nextLine, tracks: tracks,
+ tab: SGLyricsAttributes.Tab(rawValue: tab) ?? .controls, title: title, artist: artist,
+ shuffle: shuffle, repeatMode: repeatMode, timerEnd: timerEnd, timerEndOfTrack: timerEndOfTrack)
let content = ActivityContent(state: state, staleDate: nil)
if let activity = current {
Task { await activity.update(content) }
diff --git a/tweak/Sources/Redesigned/LiveActivity/LiveActivitySettings.m b/tweak/Sources/Redesigned/LiveActivity/LiveActivitySettings.m
index 0299d56d..fced0c03 100644
--- a/tweak/Sources/Redesigned/LiveActivity/LiveActivitySettings.m
+++ b/tweak/Sources/Redesigned/LiveActivity/LiveActivitySettings.m
@@ -1,10 +1,24 @@
-// The Live Activity row of the Lyrics page, in the redesign only (App/Pages.m puts it there).
+// The Live Activity page, in the redesign only (App/ModSettings.x links it from the root).
#import "Core/SGCore.h"
#import "Settings/SGModPage.h"
#import "LiveActivity.h"
-SGModRow *SGRLiveActivityRow(void) {
- SGModRow *row = SGOptionRow(@"Live Activity", @"The line being sung on the lock screen and in the Dynamic Island", SGRKeyLiveActivity);
- row.changed = ^(BOOL on) { SGRSetLiveActivityEnabled(on); };
- return row;
+static NSArray<NSString *> *viewNames(void) {
+ return @[@"Lyrics", @"Queue", @"Control menu"];
+}
+
+UIViewController *SGRLiveActivitySettingsPage(void) {
+ SGModRow *on = SGOptionRow(@"Live Activity", @"On the lock screen and in the Dynamic Island", SGRKeyLiveActivity);
+ on.changed = ^(BOOL value) { SGRSetLiveActivityEnabled(value); };
+ SGModRow *view = SGChoiceRow(@"Shows", nil, SGRKeyLiveActivityView, viewNames(), SGRLiveActivityLyrics);
+ return [[SGModPage alloc] initWithTitle:@"Live Activity" intro:nil sections:@[
+ SGSection(nil, @[on, view]),
+ ] footer:nil];
+}
+
+NSString *SGRLiveActivitySummary(void) {
+ if (!SGFlag(SGRKeyLiveActivity, NO)) return @"Off";
+ NSInteger index = SGInt(SGRKeyLiveActivityView, SGRLiveActivityLyrics);
+ NSArray<NSString *> *names = viewNames();
+ return index >= 0 && index < (NSInteger)names.count ? names[index] : names.firstObject;
}
diff --git a/tweak/Sources/Redesigned/LiveActivity/LiveActivityShared.swift b/tweak/Sources/Redesigned/LiveActivity/LiveActivityShared.swift
index ea443363..fdcf591c 100644
--- a/tweak/Sources/Redesigned/LiveActivity/LiveActivityShared.swift
+++ b/tweak/Sources/Redesigned/LiveActivity/LiveActivityShared.swift
@@ -1,13 +1,88 @@
// Compiled into both the tweak and extension/LiveActivity: ActivityKit pairs the two sides by the
-// attributes' type name, so this must stay identical in both.
+// attributes' type name and App Intents by the intent's, so this must stay identical in both.
import ActivityKit
+import AppIntents
import Foundation
@available(iOS 16.1, *)
struct SGLyricsAttributes: ActivityAttributes {
+ // Which of the three the activity shows, SGRLiveActivityView's values.
+ enum View: Int, Codable, Hashable {
+ case lyrics, queue, panel
+ }
+
+ // The control menu's tabs.
+ enum Tab: Int, Codable, Hashable, CaseIterable {
+ case controls, queue, timer
+ }
+
+ struct Track: Codable, Hashable {
+ var title: String
+ var artist: String
+ // What a tap on the track asks the player for.
+ var uri: String
+ }
+
struct ContentState: Codable, Hashable {
+ var view: View
+ var paused: Bool
+ // Lyrics: the line being sung and the one after it.
var line: String
var nextLine: String
- var paused: Bool
+ // Queue, and the control menu's queue tab: the tracks up next.
+ var tracks: [Track]
+ // The control menu.
+ var tab: Tab
+ var title: String
+ var artist: String
+ var shuffle: Bool
+ var repeatMode: Int // 0 off, 1 the playlist or album, 2 the track
+ var timerEnd: Date? // the sleep timer's end, nil when none is set
+ var timerEndOfTrack: Bool
+ }
+}
+
+// LiveActivityIntents run in the app's process, where the tweak acts on these notifications.
+let SGRLiveActivityPlayNotification = Notification.Name("SGRLiveActivityPlay")
+let SGRLiveActivityActionNotification = Notification.Name("SGRLiveActivityAction")
+
+@available(iOS 17.0, *)
+struct SGRPlayQueuedTrackIntent: LiveActivityIntent {
+ static let title: LocalizedStringResource = "Play a track up next"
+ static let isDiscoverable = false
+
+ @Parameter(title: "Track")
+ var uri: String
+
+ init() {}
+
+ init(_ uri: String) {
+ self.uri = uri
+ }
+
+ func perform() async throws -> some IntentResult {
+ NotificationCenter.default.post(name: SGRLiveActivityPlayNotification, object: uri)
+ return .result()
+ }
+}
+
+// A control menu action: tab:N, toggle, previous, next, shuffle, repeat, timer:15|30|60|track|add|cancel.
+@available(iOS 17.0, *)
+struct SGRLiveActivityActionIntent: LiveActivityIntent {
+ static let title: LocalizedStringResource = "Control menu action"
+ static let isDiscoverable = false
+
+ @Parameter(title: "Action")
+ var action: String
+
+ init() {}
+
+ init(_ action: String) {
+ self.action = action
+ }
+
+ func perform() async throws -> some IntentResult {
+ NotificationCenter.default.post(name: SGRLiveActivityActionNotification, object: action)
+ return .result()
}
}