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: put the sung line in the system now playing instead of a Live Activity

Vojtěch Škopek0a750651b5ef
diff --git a/extension/LiveActivity/Info.plist b/extension/LiveActivity/Info.plist
deleted file mode 100644
index 2294917f..00000000
--- a/extension/LiveActivity/Info.plist
+++ /dev/null
@@ -1,46 +0,0 @@
-<?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>CFBundleDevelopmentRegion</key>
- <string>en</string>
- <key>CFBundleDisplayName</key>
- <string>Spotify</string>
- <key>CFBundleExecutable</key>
- <string>SpotifyGlassLiveActivity</string>
- <key>CFBundleIdentifier</key>
- <string>HOST_BUNDLE_ID.liveactivity</string>
- <key>CFBundleInfoDictionaryVersion</key>
- <string>6.0</string>
- <key>CFBundleName</key>
- <string>SpotifyGlassLiveActivity</string>
- <key>CFBundlePackageType</key>
- <string>XPC!</string>
- <key>CFBundleShortVersionString</key>
- <string>HOST_SHORT_VERSION</string>
- <key>CFBundleSupportedPlatforms</key>
- <array>
- <string>iPhoneOS</string>
- </array>
- <key>CFBundleVersion</key>
- <string>HOST_VERSION</string>
- <key>DTPlatformName</key>
- <string>iphoneos</string>
- <key>MinimumOSVersion</key>
- <string>17.0</string>
- <key>NSExtension</key>
- <dict>
- <key>NSExtensionPointIdentifier</key>
- <string>com.apple.widgetkit-extension</string>
- </dict>
- <key>UIDeviceFamily</key>
- <array>
- <integer>1</integer>
- <integer>2</integer>
- </array>
- <key>UIRequiredDeviceCapabilities</key>
- <array>
- <string>arm64</string>
- </array>
-</dict>
-</plist>
diff --git a/extension/LiveActivity/LiveActivityWidget.swift b/extension/LiveActivity/LiveActivityWidget.swift
deleted file mode 100644
index 2b508b8a..00000000
--- a/extension/LiveActivity/LiveActivityWidget.swift
+++ /dev/null
@@ -1,131 +0,0 @@
-// The Live Activity's face: the playing track, the line being sung with the next one under it,
-// and previous, play/pause and next. 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)
-
-@main
-struct SGLiveActivityBundle: WidgetBundle {
- var body: some Widget {
- SGLyricsLiveActivity()
- }
-}
-
-struct SGLyricsLiveActivity: Widget {
- var body: some WidgetConfiguration {
- ActivityConfiguration(for: SGLyricsAttributes.self) { context in
- LockScreenView(state: context.state)
- .activityBackgroundTint(Color.black.opacity(0.75))
- .activitySystemActionForegroundColor(.white)
- .widgetURL(URL(string: "spotify:"))
- } dynamicIsland: { context in
- DynamicIsland {
- DynamicIslandExpandedRegion(.leading) {
- TrackView(state: context.state)
- .padding(.leading, 4)
- }
- DynamicIslandExpandedRegion(.trailing) {
- ControlsView(paused: context.state.paused)
- .padding(.trailing, 4)
- }
- DynamicIslandExpandedRegion(.bottom) {
- LyricsView(state: context.state)
- .frame(maxWidth: .infinity, alignment: .leading)
- .padding(.horizontal, 4)
- }
- } compactLeading: {
- Image(systemName: "music.note")
- .foregroundStyle(spotifyGreen)
- } compactTrailing: {
- Image(systemName: context.state.paused ? "pause.fill" : "waveform")
- .foregroundStyle(spotifyGreen)
- } minimal: {
- Image(systemName: "music.note")
- .foregroundStyle(spotifyGreen)
- }
- .widgetURL(URL(string: "spotify:"))
- }
- }
-}
-
-private struct LockScreenView: View {
- let state: SGLyricsAttributes.ContentState
-
- var body: some View {
- VStack(alignment: .leading, spacing: 10) {
- HStack(alignment: .center, spacing: 12) {
- TrackView(state: state)
- Spacer(minLength: 8)
- ControlsView(paused: state.paused)
- }
- LyricsView(state: state)
- }
- .padding(16)
- .foregroundStyle(.white)
- }
-}
-
-private struct TrackView: View {
- let state: SGLyricsAttributes.ContentState
-
- var body: some View {
- VStack(alignment: .leading, spacing: 1) {
- Text(state.title)
- .font(.subheadline.weight(.semibold))
- .lineLimit(1)
- Text(state.artist)
- .font(.caption)
- .foregroundStyle(.white.opacity(0.6))
- .lineLimit(1)
- }
- }
-}
-
-private struct LyricsView: View {
- let state: SGLyricsAttributes.ContentState
-
- var body: some View {
- if !state.line.isEmpty || !state.nextLine.isEmpty {
- VStack(alignment: .leading, spacing: 4) {
- if !state.line.isEmpty {
- Text(state.line)
- .font(.title3.weight(.bold))
- .lineLimit(2)
- .minimumScaleFactor(0.8)
- }
- if !state.nextLine.isEmpty {
- Text(state.nextLine)
- .font(.subheadline.weight(.semibold))
- .foregroundStyle(.white.opacity(0.45))
- .lineLimit(1)
- }
- }
- }
- }
-}
-
-private struct ControlsView: View {
- let paused: Bool
-
- var body: some View {
- HStack(spacing: 18) {
- Button(intent: SGPreviousTrackIntent()) {
- Image(systemName: "backward.fill")
- }
- Button(intent: SGTogglePlaybackIntent()) {
- Image(systemName: paused ? "play.fill" : "pause.fill")
- .font(.title2)
- }
- Button(intent: SGNextTrackIntent()) {
- Image(systemName: "forward.fill")
- }
- }
- .buttonStyle(.plain)
- .font(.title3)
- .foregroundStyle(.white)
- }
-}
diff --git a/plist/liquid-glass.plist b/plist/liquid-glass.plist
index c99005f5..243a2f46 100644
--- a/plist/liquid-glass.plist
+++ b/plist/liquid-glass.plist
@@ -4,7 +4,5 @@
<dict>
<key>UIDesignRequiresCompatibility</key>
<false/>
- <key>NSSupportsLiveActivities</key>
- <true/>
</dict>
</plist>
diff --git a/scripts/build-extension.sh b/scripts/build-extension.sh
deleted file mode 100755
index 3c3b9249..00000000
--- a/scripts/build-extension.sh
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/env bash
-# Builds the Live Activity widget extension without an Xcode project, and the App Intents metadata
-# the host app needs for the widget's buttons.
-#
-# scripts/build-extension.sh <host Info.plist> <out dir>
-#
-# 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)"
-HOST_PLIST="${1:?usage: $0 <host Info.plist> <out dir>}"
-OUT="${2:?usage: $0 <host Info.plist> <out dir>}"
-NAME=SpotifyGlassLiveActivity
-APPEX="$OUT/$NAME.appex"
-SHARED="$ROOT/tweak/Sources/Features/LiveActivity/LiveActivityShared.swift"
-WIDGET="$ROOT/extension/LiveActivity/LiveActivityWidget.swift"
-
-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")/" \
- -e "s/HOST_VERSION/$(plutil -extract CFBundleVersion raw -o - "$HOST_PLIST")/" \
- "$ROOT/extension/LiveActivity/Info.plist" > "$APPEX/Info.plist"
-plutil -convert binary1 "$APPEX/Info.plist"
-
-# The buttons' 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
deleted file mode 100755
index 5287654f..00000000
--- a/scripts/merge-appintents.py
+++ /dev/null
@@ -1,38 +0,0 @@
-#!/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 45538b70..193e8832 100755
--- a/scripts/pipeline.sh
+++ b/scripts/pipeline.sh
@@ -83,16 +83,6 @@ echo " $TWEAK_DEB"
FILES=("$TWEAK_DEB")
[ "$WITH_FLEX" = 1 ] && FILES+=("$FLEX_DEB")
-if xcrun --sdk iphoneos --find swiftc >/dev/null 2>&1; then
- EXT_DIR="$ROOT/out/extension"
- unzip -p "$IN" "${APP_DIR}Info.plist" > "$ROOT/out/.info.plist"
- "$ROOT/scripts/build-extension.sh" "$ROOT/out/.info.plist" "$EXT_DIR"
- rm -f "$ROOT/out/.info.plist"
- FILES+=("$EXT_DIR/SpotifyGlassLiveActivity.appex")
-else
- echo "==> no Xcode selected: building without the Live Activity extension"
-fi
-
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
diff --git a/tweak/Sources/Features/Karaoke/KaraokeSource.x b/tweak/Sources/Features/Karaoke/KaraokeSource.x
index 376e3fc1..3a15aa22 100644
--- a/tweak/Sources/Features/Karaoke/KaraokeSource.x
+++ b/tweak/Sources/Features/Karaoke/KaraokeSource.x
@@ -4,7 +4,7 @@
// every frame: the player is caught the first time the app asks it, and its position runs on by itself.
#import "Core/SGCore.h"
#import "Karaoke.h"
-#import "Features/LiveActivity/LiveActivity.h"
+#import "Features/LockScreenLyrics/LockScreenLyrics.h"
#import "Headers/SPTPlayer.h"
static const NSUInteger kKeptTracks = 40;
@@ -153,7 +153,7 @@ void SGKaraokeSeek(NSInteger ms) {
%end
%ctor {
- if (!SGFlag(SGKeyKaraokeLyrics, NO) && !SGFlag(SGKeyLiveActivity, NO)) return;
+ if (!SGFlag(SGKeyKaraokeLyrics, NO) && !SGFlag(SGKeyLockScreenLyrics, NO)) return;
sg_lyrics = [NSMutableDictionary dictionary];
sg_requested = [NSMutableSet set];
%init;
diff --git a/tweak/Sources/Features/LiveActivity/LiveActivity.h b/tweak/Sources/Features/LiveActivity/LiveActivity.h
deleted file mode 100644
index c5a86ba9..00000000
--- a/tweak/Sources/Features/LiveActivity/LiveActivity.h
+++ /dev/null
@@ -1,6 +0,0 @@
-// The playing track and the line being sung as a Live Activity on the lock screen and in the Dynamic
-// Island, with previous, play/pause and next (iOS 17+). The lines and the clock come from Karaoke, the
-// widget is extension/LiveActivity, built into the IPA by scripts/build-extension.sh.
-#import <Foundation/Foundation.h>
-
-#define SGKeyLiveActivity @"spotifyglass.liveActivity"
diff --git a/tweak/Sources/Features/LiveActivity/LiveActivity.x b/tweak/Sources/Features/LiveActivity/LiveActivity.x
deleted file mode 100644
index 622b9455..00000000
--- a/tweak/Sources/Features/LiveActivity/LiveActivity.x
+++ /dev/null
@@ -1,96 +0,0 @@
-// Polls the player and pushes a new state to the activity only when what it shows changes: a new
-// line, track or pause. Spotify keeps playing in the background, so the timer keeps running there too.
-// The activity is started only while the app is in front, the one place ActivityKit allows it.
-#import <UIKit/UIKit.h>
-#import "Core/SGCore.h"
-#import "LiveActivity.h"
-#import "Features/Karaoke/Karaoke.h"
-#import "Headers/SPTPlayer.h"
-
-API_AVAILABLE(ios(17.0))
-@interface SGLiveActivityBridge : NSObject
-@property (class, nonatomic, readonly) BOOL isShowing;
-+ (void)showWithTitle:(NSString *)title artist:(NSString *)artist line:(NSString *)line nextLine:(NSString *)nextLine paused:(BOOL)paused;
-+ (void)end;
-@end
-
-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;
-
-static NSString *sg_shown;
-static NSString *sg_missingLyrics;
-static NSDate *sg_lastStart;
-
-static NSString *textOf(SGKaraokeLine *line) {
- return [[line.words valueForKey:@"text"] componentsJoinedByString:@" "] ?: @"";
-}
-
-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();
- NSArray<SGKaraokeLine *> *lines = SGKaraokeLinesForTrack(trackID);
- if (!lines) {
- SGKaraokeRequestLyrics(trackID);
- if (trackID && ![trackID isEqualToString:sg_missingLyrics]) {
- sg_missingLyrics = trackID;
- 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++;
- NSString *line = @"", *next = index + 1 < (NSInteger)lines.count ? textOf(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 ? @"♪" : textOf(current);
- }
-
- NSString *artist = track.artistName ?: @"";
- NSString *shown = [@[track.trackTitle, artist, line, next, state.isPaused ? @"1" : @"0"] componentsJoinedByString:@"\n"];
- if (SGLiveActivityBridge.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;
- [SGLiveActivityBridge showWithTitle:track.trackTitle artist:artist line:line nextLine:next paused:state.isPaused];
-}
-
-static void runCommand(NSString *command) {
- id<SPTPlayer> player = SGKaraokePlayer();
- id result = nil;
- if ([command isEqualToString:@"toggle"]) {
- result = player.state.isPaused ? [player resume:nil] : [player pause:nil];
- } else if ([command isEqualToString:@"next"]) {
- result = [player skipToNextTrackWithOptions:nil];
- } else if ([command isEqualToString:@"previous"]) {
- result = [player skipToPreviousTrackWithOptions:nil];
- }
- SGLog(@"live activity: %@ -> %@ (player %@)", command, result, player ? NSStringFromClass([player class]) : @"nil");
-}
-
-%ctor {
- if (@available(iOS 17.0, *)) {
- if (!SGFlag(SGKeyLiveActivity, NO)) {
- dispatch_async(dispatch_get_main_queue(), ^{ [SGLiveActivityBridge end]; });
- return;
- }
- [NSNotificationCenter.defaultCenter addObserverForName:@"SGLiveActivityCommand" object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *note) {
- runCommand(note.object);
- }];
- NSTimer *timer = [NSTimer timerWithTimeInterval:kTick repeats:YES block:^(NSTimer *t) { tick(); }];
- [NSRunLoop.mainRunLoop addTimer:timer forMode:NSRunLoopCommonModes];
- SGLog(@"live activity: on");
- }
-}
diff --git a/tweak/Sources/Features/LiveActivity/LiveActivityBridge.swift b/tweak/Sources/Features/LiveActivity/LiveActivityBridge.swift
deleted file mode 100644
index d53ce890..00000000
--- a/tweak/Sources/Features/LiveActivity/LiveActivityBridge.swift
+++ /dev/null
@@ -1,42 +0,0 @@
-// ActivityKit is Swift only, so LiveActivity.x reaches it through this class.
-import ActivityKit
-import Foundation
-import os
-
-@available(iOS 17.0, *)
-@objc(SGLiveActivityBridge)
-public final class SGLiveActivityBridge: NSObject {
- private static let log = Logger(subsystem: "spotifyglass", category: "live activity")
-
- private static var current: Activity<SGLyricsAttributes>? {
- Activity<SGLyricsAttributes>.activities.first { $0.activityState == .active || $0.activityState == .stale }
- }
-
- @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(title: String, artist: String, line: String, nextLine: String, paused: Bool) {
- let state = SGLyricsAttributes.ContentState(title: title, artist: artist, line: line, nextLine: nextLine, paused: paused)
- let content = ActivityContent(state: state, staleDate: nil)
- if let activity = current {
- Task { await activity.update(content) }
- return
- }
- guard ActivityAuthorizationInfo().areActivitiesEnabled else {
- log.notice("[spotifyglass] live activity: activities are off for this app")
- return
- }
- do {
- let activity = try Activity.request(attributes: SGLyricsAttributes(), content: content, pushType: nil)
- log.notice("[spotifyglass] live activity: started \(activity.id, privacy: .public)")
- } catch {
- log.error("[spotifyglass] live activity: request failed: \(String(describing: error), privacy: .public)")
- }
- }
-
- @objc public static func end() {
- for activity in Activity<SGLyricsAttributes>.activities {
- Task { await activity.end(nil, dismissalPolicy: .immediate) }
- }
- }
-}
diff --git a/tweak/Sources/Features/LiveActivity/LiveActivityShared.swift b/tweak/Sources/Features/LiveActivity/LiveActivityShared.swift
deleted file mode 100644
index 9084a095..00000000
--- a/tweak/Sources/Features/LiveActivity/LiveActivityShared.swift
+++ /dev/null
@@ -1,57 +0,0 @@
-// Compiled into both the tweak and extension/LiveActivity: ActivityKit pairs the two sides by the
-// attributes' type name and App Intents by the intent's, so these must stay identical in both.
-import ActivityKit
-import AppIntents
-import Foundation
-
-@available(iOS 16.1, *)
-struct SGLyricsAttributes: ActivityAttributes {
- struct ContentState: Codable, Hashable {
- var title: String
- var artist: String
- var line: String
- var nextLine: String
- var paused: Bool
- }
-}
-
-// A LiveActivityIntent runs in the app's process, where the tweak turns the notification into a player call.
-let SGLiveActivityCommandNotification = Notification.Name("SGLiveActivityCommand")
-
-@available(iOS 17.0, *)
-private func sendPlayerCommand(_ command: String) {
- NotificationCenter.default.post(name: SGLiveActivityCommandNotification, object: command)
-}
-
-@available(iOS 17.0, *)
-struct SGPreviousTrackIntent: LiveActivityIntent {
- static let title: LocalizedStringResource = "Previous track"
- static let isDiscoverable = false
-
- func perform() async throws -> some IntentResult {
- sendPlayerCommand("previous")
- return .result()
- }
-}
-
-@available(iOS 17.0, *)
-struct SGTogglePlaybackIntent: LiveActivityIntent {
- static let title: LocalizedStringResource = "Play or pause"
- static let isDiscoverable = false
-
- func perform() async throws -> some IntentResult {
- sendPlayerCommand("toggle")
- return .result()
- }
-}
-
-@available(iOS 17.0, *)
-struct SGNextTrackIntent: LiveActivityIntent {
- static let title: LocalizedStringResource = "Next track"
- static let isDiscoverable = false
-
- func perform() async throws -> some IntentResult {
- sendPlayerCommand("next")
- return .result()
- }
-}
diff --git a/tweak/Sources/Features/LockScreenLyrics/LockScreenLyrics.h b/tweak/Sources/Features/LockScreenLyrics/LockScreenLyrics.h
new file mode 100644
index 00000000..afee277e
--- /dev/null
+++ b/tweak/Sources/Features/LockScreenLyrics/LockScreenLyrics.h
@@ -0,0 +1,6 @@
+// The line being sung in place of the artist in the system's now playing: lock screen, Dynamic Island,
+// Control Center, CarPlay. A Live Activity cannot do it: iOS stops taking its updates from an app that
+// plays audio in the background within half a minute. The lines and the clock come from Karaoke.
+#import <Foundation/Foundation.h>
+
+#define SGKeyLockScreenLyrics @"spotifyglass.lockScreenLyrics"
diff --git a/tweak/Sources/Features/LockScreenLyrics/LockScreenLyrics.x b/tweak/Sources/Features/LockScreenLyrics/LockScreenLyrics.x
new file mode 100644
index 00000000..637fa783
--- /dev/null
+++ b/tweak/Sources/Features/LockScreenLyrics/LockScreenLyrics.x
@@ -0,0 +1,143 @@
+// Spotify's now playing info passes through with the artist swapped for the current line, and a timer
+// sends it again each time the line changes. Spotify itself only ever sees its own dictionary back.
+#import <MediaPlayer/MediaPlayer.h>
+#import "Core/SGCore.h"
+#import "LockScreenLyrics.h"
+#import "Features/Karaoke/Karaoke.h"
+#import "Headers/SPTPlayer.h"
+
+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 artist comes back.
+static const NSInteger kBreakMs = 4000;
+// About what the lock screen's artist row fits before it cuts the text off.
+static const NSUInteger kMaxChars = 30;
+
+// Spotify may set the info from any thread; the timer reads it on the main one.
+static NSObject *sg_lock;
+static NSDictionary *sg_spotifyInfo;
+static CFAbsoluteTime sg_spotifyInfoAt;
+static NSString *sg_shownLine;
+static BOOL sg_resending;
+
+static NSString *textOf(NSArray<SGKaraokeWord *> *words) {
+ return [[words valueForKey:@"text"] componentsJoinedByString:@" "];
+}
+
+// A line longer than the artist row holds, split into even pieces rather than a full one and a stub.
+// Each piece shows from its first word's estimated start.
+static NSArray<NSArray<SGKaraokeWord *> *> *piecesOf(SGKaraokeLine *line) {
+ NSUInteger length = textOf(line.words).length;
+ NSUInteger count = MAX((length + kMaxChars - 1) / kMaxChars, 1);
+ NSUInteger target = (length + count - 1) / count;
+ NSMutableArray<NSArray<SGKaraokeWord *> *> *pieces = [NSMutableArray array];
+ NSMutableArray<SGKaraokeWord *> *piece = [NSMutableArray array];
+ NSUInteger pieceLength = 0;
+ for (SGKaraokeWord *word in line.words) {
+ NSUInteger withWord = pieceLength ? pieceLength + 1 + word.text.length : word.text.length;
+ if (pieceLength && (withWord > kMaxChars || (withWord > target && pieces.count + 1 < count))) {
+ [pieces addObject:piece];
+ piece = [NSMutableArray array];
+ withWord = word.text.length;
+ }
+ [piece addObject:word];
+ pieceLength = withWord;
+ }
+ if (piece.count) [pieces addObject:piece];
+ return pieces;
+}
+
+// Seconds into the track at `now`, run on from what Spotify last reported.
+static double elapsedAt(NSDictionary *info, CFAbsoluteTime reportedAt, CFAbsoluteTime now) {
+ double rate = [info[MPNowPlayingInfoPropertyPlaybackRate] doubleValue];
+ return [info[MPNowPlayingInfoPropertyElapsedPlaybackTime] doubleValue] + rate * (now - reportedAt);
+}
+
+// nil between lines and for a track without synced lyrics.
+static NSString *lineFor(NSDictionary *info, double elapsed) {
+ SPTPlayerState *state = [(id<SPTPlayer>)SGKaraokePlayer() state];
+ // The player's track can lag behind the now playing info; its lyrics would then be another song's.
+ if (![state.track.trackTitle isEqualToString:info[MPMediaItemPropertyTitle]]) return nil;
+ NSString *trackID = SGKaraokePlayingTrack();
+ NSArray<SGKaraokeLine *> *lines = SGKaraokeLinesForTrack(trackID);
+ if (!lines) {
+ SGKaraokeRequestLyrics(trackID);
+ return nil;
+ }
+ NSInteger position = (NSInteger)(elapsed * 1000);
+ NSInteger index = -1;
+ while (index + 1 < (NSInteger)lines.count && lines[index + 1].start <= position) index++;
+ if (index < 0) return nil;
+ BOOL nextFarOff = index + 1 == (NSInteger)lines.count || lines[index + 1].start - position > kBreakMs;
+ if (position > lines[index].end + kBreakMs && nextFarOff) return nil;
+ NSString *shown = nil;
+ for (NSArray<SGKaraokeWord *> *piece in piecesOf(lines[index])) {
+ if (!shown || piece.firstObject.start <= position) shown = textOf(piece);
+ }
+ return shown;
+}
+
+static NSDictionary *withLine(NSDictionary *info, NSString *line, double elapsed) {
+ NSMutableDictionary *shown = [info mutableCopy];
+ shown[MPMediaItemPropertyArtist] = line;
+ shown[MPNowPlayingInfoPropertyElapsedPlaybackTime] = @(elapsed);
+ return shown;
+}
+
+static void tick(void) {
+ NSDictionary *info;
+ CFAbsoluteTime reportedAt;
+ @synchronized (sg_lock) {
+ info = sg_spotifyInfo;
+ reportedAt = sg_spotifyInfoAt;
+ }
+ if (!info[MPNowPlayingInfoPropertyElapsedPlaybackTime]) return;
+ CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
+ double elapsed = elapsedAt(info, reportedAt, now);
+ NSString *line = lineFor(info, elapsed);
+ if (line == sg_shownLine || [line isEqualToString:sg_shownLine]) return;
+ sg_shownLine = line;
+ sg_resending = YES;
+ MPNowPlayingInfoCenter.defaultCenter.nowPlayingInfo = line ? withLine(info, line, elapsed) : info;
+ sg_resending = NO;
+}
+
+%hook MPNowPlayingInfoCenter
+- (void)setNowPlayingInfo:(NSDictionary *)info {
+ if (sg_resending) {
+ %orig;
+ return;
+ }
+ CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
+ @synchronized (sg_lock) {
+ sg_spotifyInfo = info;
+ sg_spotifyInfoAt = now;
+ }
+ // Karaoke's lyrics are main-thread state; off it the info goes out as it is and the next tick adds the line.
+ if (!NSThread.isMainThread || !info[MPNowPlayingInfoPropertyElapsedPlaybackTime]) {
+ dispatch_async(dispatch_get_main_queue(), ^{ sg_shownLine = nil; });
+ %orig;
+ return;
+ }
+ double elapsed = elapsedAt(info, now, now);
+ NSString *line = lineFor(info, elapsed);
+ sg_shownLine = line;
+ %orig(line ? withLine(info, line, elapsed) : info);
+}
+
+- (NSDictionary *)nowPlayingInfo {
+ NSDictionary *info;
+ @synchronized (sg_lock) {
+ info = sg_spotifyInfo;
+ }
+ return info ?: %orig;
+}
+%end
+
+%ctor {
+ if (!SGFlag(SGKeyLockScreenLyrics, NO)) return;
+ sg_lock = [NSObject new];
+ %init;
+ NSTimer *timer = [NSTimer timerWithTimeInterval:kTick repeats:YES block:^(NSTimer *t) { tick(); }];
+ [NSRunLoop.mainRunLoop addTimer:timer forMode:NSRunLoopCommonModes];
+ SGLog(@"lock screen lyrics: on");
+}
diff --git a/tweak/Sources/Features/NowPlaying/NowPlayingSettings.m b/tweak/Sources/Features/NowPlaying/NowPlayingSettings.m
index 8ac6fa7b..aa89811a 100644
--- a/tweak/Sources/Features/NowPlaying/NowPlayingSettings.m
+++ b/tweak/Sources/Features/NowPlaying/NowPlayingSettings.m
@@ -5,7 +5,7 @@
#import "Features/Gestures/Gestures.h"
#import "Features/ArtistBlock/ArtistBlock.h"
#import "Features/Karaoke/Karaoke.h"
-#import "Features/LiveActivity/LiveActivity.h"
+#import "Features/LockScreenLyrics/LockScreenLyrics.h"
static UIViewController *nowPlayingBarPage(void) {
return [[SGModPage alloc] initWithTitle:@"Now playing bar" intro:SGRestartNote sections:@[
@@ -30,7 +30,7 @@ static UIViewController *lyricsPage(void) {
SGSection(nil, @[
SGOptionRow(@"Apple Music style", @"Word by word on the full screen page; timing inside a line is estimated", SGKeyKaraokeLyrics),
SGOptionRow(@"Glass lyrics", @"Glass card, and the page it expands into", SGKeyLyricsCard),
- SGOptionRow(@"Live Activity", @"The line being sung and playback controls on the lock screen and in the Dynamic Island", SGKeyLiveActivity),
+ SGOptionRow(@"Lyrics on the lock screen", @"The line being sung in place of the artist, also in the Dynamic Island, Control Center and CarPlay", SGKeyLockScreenLyrics),
]),
SGSection(@"Hide in the player", @[
SGHideRow(@"Lyrics card", @"The lyrics card below the player", SGHideLyricsCard),
diff --git a/tweak/Sources/Headers/SPTPlayer.h b/tweak/Sources/Headers/SPTPlayer.h
index e9981de6..537d5477 100644
--- a/tweak/Sources/Headers/SPTPlayer.h
+++ b/tweak/Sources/Headers/SPTPlayer.h
@@ -23,9 +23,4 @@
@property (nonatomic, readonly) SPTPlayerState *state;
- (void)skipToNextTrack;
- (void)seekTo:(double)seconds;
-// Each takes Spotify's options object, nil for the defaults, and returns the command's pending result.
-- (id)pause:(id)options;
-- (id)resume:(id)options;
-- (id)skipToNextTrackWithOptions:(id)options;
-- (id)skipToPreviousTrackWithOptions:(id)options;
@end