Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.
C
feat: Add to Queue on an album page's menu with Spoof Premium (#88)
My-Name-Is-Jefff5473f76958b
diff --git a/docs/tweaks.md b/docs/tweaks.mdindex 02ada4db..41dc0d9b 100644--- a/docs/tweaks.md+++ b/docs/tweaks.md@@ -88,6 +88,18 @@ Shared:command's ESP request gets overrideRestrictions before the core receives it; other restrictionsand commands stay as Spotify supplied them. The hooks install together only when the expectedruntime signatures match. Checked by harness/radio-modes/; its README records device evidence.+ AlbumQueue/ With Spoof Premium on, adds Add to Queue to an album page's header menu when Spotify leaves+ that row out, under either look. The Creative Work page's template.creativeWork.uri is read+ by named Swift reflection and checked against the header's menu button; a track menu is+ never inferred from the page it happens to be on. Native marks the header button just before+ UIKit dispatches its registered touch-up or primary action (target/selector or UIAction);+ the redesign marks the original button before its pinned mirror fires it. One marker is+ consumed by one menu. Spotify's context resolver supplies the ordered track URIs, including+ repeats, then SPTPlayerQueueWrapperImpl's queueMultipleTracks:loggingParams: submits them+ with Spotify's own queue handling. Account attributes and restrictions are unchanged.+ A missing page or malformed response fails before submission; paginated answers are+ currently rejected rather than queueing part of an album. Checked by harness/album-queue/;+ Spotify 9.1.90 simulator evidence and the remaining device checks are in its README.Privacy/ telemetry blocking and its counters, and the tracking taken off shared open.spotify.com links(CleanLinks.x over the cleaner in CleanLinks.m)ArtistBlock/ tracks by blocked artists skipped as they start (ArtistSkip.x), the list and the Blocked artists page under Playerdiff --git a/harness/album-queue/README.md b/harness/album-queue/README.mdnew file mode 100644index 00000000..98c8ff1b--- /dev/null+++ b/harness/album-queue/README.md@@ -0,0 +1,74 @@+# Album queue++With Spoof Premium on, an album page's header menu gets an **Add to Queue** fallback when Spotify+omits its own row. The backend resolves the album through Spotify's signed-in context resolver and+passes its ordered track list to `SPTPlayerQueueWrapperImpl.queueMultipleTracks:loggingParams:`.+It does not change account attributes, `offline`, or player restrictions.++The native header records its original menu button immediately before UIKit dispatches its+registered touch-up or primary action, through either target/selector or UIAction. The+redesign marks that original button immediately before its mirror fires it. One menu appearance+consumes one marker. Identity comes from the named Swift fields `template.creativeWork.uri` on the+Creative Work page and must match its header's `Components.UI.ContextMenuButton-<album id>`.+A changed model shape yields no fallback. No song menu is inferred to be an album menu.++## Local checks++Run from the repository root:++```sh+harness/album-queue/build.sh+harness/album-queue/build-activation.sh+scripts/check-layers.sh tweak/Sources+env -u MAKELEVEL gmake -C tweak clean package+```++The Mac harness runs the production context parser and Swift page reader: 17 context checks and+4 page identity checks. They cover disc/page order, repeated tracks, wrong response identity,+malformed entries, invalid URI types and characters, missing pages and pagination. Parsing fails+as a whole, so a valid prefix of a malformed album is never submitted.++The activation harness compiles the production native Logos hook into a UIKit simulator app.+Install and launch `harness/album-queue/build/activation/AlbumActivation.app` with `simctl` using+bundle ID `com.vitrine.albumactivation`; its console reports nine checks. It checks a two-second+hold before release, target/selector and UIAction dispatch without touch-down, source availability+inside the handler, cancellation and unrelated controls. A direct UIKit `accessibilityActivate`+call returned NO in this standalone app, so this verifies the action dispatch paths rather than+end-to-end VoiceOver activation. Live Spotify holds and physical-device VoiceOver remain untested.++The system menu harness supplies a no-op album installer for its existing player-menu fixtures.+The album action itself is exercised in Spotify, not by that stub.++## Simulator evidence, 2026-10-15++Spotify 9.1.90, existing signed-in iPhone 18 Pro Max simulator, iOS 27 runtime, playback paused:++- Context resolution of DAMN. returned HTTP 200 and 14 ordered track URIs.+- A direct single-item queue request using an album URI only inserted an album placeholder. That+ path is not used by the feature.+- The native bulk method completed without error. Readback preserved the existing 37 queued tracks+ as an identical prefix and inserted the exact 14 album track URIs immediately afterward, in order.+ The following context tracks remained in order in the observed 80-item queue window.+- The redesigned album menu's new row was tapped through `scripts/phone.py menu.pick 'Add to Queue'`.+ It reported `album queue: 14 tracks added`; queue readback matched the same prefix/order checks.+- The native album menu also shows the fallback in its footer. Tapping it reported 14 tracks added;+ readback passed the same prefix, exact album order and following-context checks.+- A song's own menu had no `spotifyglass.albumQueue` control.+- With Spoof Premium off, the redesigned album menu had no fallback control.+- The normal tweak package and the existing system-menu harness both build. The system-menu+ `rows` regression scenario passed all 15 checks.+- Test queues were saved with `getQueueWithCallback:` and restored with `setQueue:` using the latest+ revision. After each menu test, all 80 observed entries matched its saved queue.+ Both changed preferences were restored from their saved values.++Simulator setup and its private authentication headers stay local. Never print the headers or export+a driver build. Port 8088 is the test simulator; use the recorded native tab identifier+`TabBar.Item.Search` when the driver's generic `tab Search` cannot find the native bar.++## Remaining limits++Physical iPhone behavior and Spotify 9.1.78/9.1.88 have not been validated for this addition. The native+queue command retains Spotify's own capacity and rejection behavior. Album responses with a nonempty+`next_page_url`, unresolved pages, no tracks, or over 5000 tracks currently fail before submission;+they are not partially queued. The action is on the album page's header menu, not every album card's+context menu elsewhere in the app.diff --git a/harness/album-queue/activation.m b/harness/album-queue/activation.mnew file mode 100644index 00000000..96cc2cce--- /dev/null+++ b/harness/album-queue/activation.m@@ -0,0 +1,71 @@+#import <UIKit/UIKit.h>+#import <QuartzCore/QuartzCore.h>+static NSInteger checks, failures, marks, targetCalls, actionCalls, accessibilityCalls;+static __weak UIView *marked;+static CFTimeInterval markedAt;+BOOL SGNativeUI(void) { return YES; }+BOOL SGHidden(NSString *key) { return YES; }+void SGAlbumQueueMarkSource(UIView *view) { marked = view; markedAt = CACurrentMediaTime(); marks++; }+static void check(BOOL ok, NSString *message) { checks++; if (!ok) failures++; NSLog(@"[album activation] %@ %@", ok ? @"PASS" : @"FAIL", message); }+static BOOL fresh(UIView *view) { return marked == view && CACurrentMediaTime() - markedAt < 0.25; }+@interface App : UIResponder <UIApplicationDelegate>+@property (nonatomic, strong) UIWindow *window;+@property (nonatomic, strong) UIButton *held, *primary, *accessible, *other;+@end+@implementation App+- (void)menu:(UIButton *)button { targetCalls++; check(fresh(button), @"target/selector sees a fresh marker before opening its menu"); }+- (void)down:(UIButton *)button { check(marks == 0, @"touch down alone does not mark an album source"); }+- (void)cancel:(UIButton *)button { check(marks == 0, @"cancellation alone does not mark an album source"); }+- (void)accessibleMenu:(UIButton *)button { accessibilityCalls++; check(fresh(button), @"target/selector without touch down sees the source before opening its menu"); }+- (void)otherMenu:(UIButton *)button { check(marks == 3, @"unrelated controls do not change the source"); }+- (UIButton *)buttonAt:(CGFloat)y {+ UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];+ button.frame = CGRectMake(20, y, 300, 44);+ [button setTitle:@"Album menu" forState:UIControlStateNormal];+ button.accessibilityIdentifier = @"Components.UI.ContextMenuButton-testAlbum";+ [self.window.rootViewController.view addSubview:button];+ return button;+}+- (BOOL)application:(UIApplication *)app didFinishLaunchingWithOptions:(NSDictionary *)options {+ self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];+ self.window.rootViewController = [UIViewController new];+ self.window.rootViewController.view.backgroundColor = UIColor.blackColor;+ [self.window makeKeyAndVisible];+ self.held = [self buttonAt:100];+ [self.held addTarget:self action:@selector(down:) forControlEvents:UIControlEventTouchDown];+ [self.held addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchCancel];+ [self.held addTarget:self action:@selector(menu:) forControlEvents:UIControlEventTouchUpInside];+ self.primary = [self buttonAt:160];+ __weak App *weakSelf = self;+ [self.primary addAction:[UIAction actionWithHandler:^(UIAction *action) {+ App *me = weakSelf; actionCalls++; check(fresh(me.primary), @"UIAction sees the source before opening its menu");+ }] forControlEvents:UIControlEventPrimaryActionTriggered];+ self.accessible = [self buttonAt:220];+ [self.accessible addTarget:self action:@selector(accessibleMenu:) forControlEvents:UIControlEventTouchUpInside];+ self.other = [self buttonAt:280];+ self.other.accessibilityIdentifier = @"unrelated";+ [self.other addTarget:self action:@selector(otherMenu:) forControlEvents:UIControlEventTouchUpInside];+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), dispatch_get_main_queue(), ^{+ [self.held sendActionsForControlEvents:UIControlEventTouchCancel];+ [self.held sendActionsForControlEvents:UIControlEventTouchDown];+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{+ [self.held sendActionsForControlEvents:UIControlEventTouchUpInside];+ check(targetCalls == 1 && marks == 1, @"a release after two seconds opens once with a newly recorded source");+ [self.primary sendActionsForControlEvents:UIControlEventPrimaryActionTriggered];+ check(actionCalls == 1 && marks == 2, @"primary action works without a preceding touch down");+ // Exercise the non-touch target/selector dispatch. Calling accessibilityActivate+ // directly on UIButton returns NO in this standalone simulator app; it is not+ // an end-to-end VoiceOver test.+ [self.accessible sendActionsForControlEvents:UIControlEventTouchUpInside];+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), dispatch_get_main_queue(), ^{+ check(accessibilityCalls == 1 && marks == 3, @"target/selector dispatches once without touch down");+ [self.other sendActionsForControlEvents:UIControlEventTouchUpInside];+ NSLog(@"[album activation] done: %ld checks, %ld failures", (long)checks, (long)failures);+ exit(failures ? 1 : 0);+ });+ });+ });+ return YES;+}+@end+int main(int argc, char **argv) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass(App.class)); } }diff --git a/harness/album-queue/build-activation.sh b/harness/album-queue/build-activation.shnew file mode 100755index 00000000..51507ff3--- /dev/null+++ b/harness/album-queue/build-activation.sh@@ -0,0 +1,16 @@+#!/bin/sh+set -eu+cd "$(dirname "$0")"+SRC=$(cd ../../tweak/Sources && pwd)+OUT=build/activation+mkdir -p "$OUT/AlbumActivation.app"+"${THEOS:-$HOME/theos}/bin/logos.pl" -c generator=internal "$SRC/Native/AlbumQueue/AlbumQueueMenu.x" > "$OUT/AlbumQueueMenu.m"+SDK=$(xcrun --sdk iphonesimulator --show-sdk-path)+xcrun --sdk iphonesimulator clang -target arm64-apple-ios17.4-simulator -fobjc-arc -O0 -g -I"$SRC" -isysroot "$SDK" \+ activation.m ../scene.m "$OUT/AlbumQueueMenu.m" -framework UIKit -framework Foundation -framework QuartzCore \+ -o "$OUT/AlbumActivation.app/AlbumActivation"+python3 - "$OUT/AlbumActivation.app/Info.plist" <<'PY'+import plistlib, sys+plistlib.dump(dict(CFBundleExecutable='AlbumActivation',CFBundleIdentifier='com.vitrine.albumactivation',CFBundleName='AlbumActivation',CFBundleVersion='1',CFBundleShortVersionString='1.0',UILaunchScreen={},UIApplicationSceneManifest={'UISceneConfigurations':{'UIWindowSceneSessionRoleApplication':[{'UISceneConfigurationName':'Default','UISceneDelegateClassName':'SGRHarnessScene'}]}}),open(sys.argv[1],'wb'))+PY+echo "built $OUT/AlbumActivation.app"diff --git a/harness/album-queue/build.sh b/harness/album-queue/build.shnew file mode 100755index 00000000..9864a8d2--- /dev/null+++ b/harness/album-queue/build.sh@@ -0,0 +1,11 @@+#!/bin/sh+set -eu+cd "$(dirname "$0")"+mkdir -p build+SRC=../../tweak/Sources+xcrun clang -fobjc-arc -Wall -Werror -target arm64-apple-macos13.0 -I"$SRC" \+ check.m "$SRC/Shared/AlbumQueue/AlbumQueueContext.m" -framework Foundation -o build/context-check+cat "$SRC/Shared/AlbumQueue/AlbumPage.swift" page.swift > build/page-check.swift+xcrun swiftc -module-cache-path build/module-cache build/page-check.swift -o build/page-check+build/context-check+build/page-checkdiff --git a/harness/album-queue/check.m b/harness/album-queue/check.mnew file mode 100644index 00000000..9c6df069--- /dev/null+++ b/harness/album-queue/check.m@@ -0,0 +1,35 @@+#import <Foundation/Foundation.h>+#import "Shared/AlbumQueue/AlbumQueue.h"+static int checks;+static void check(BOOL ok, NSString *name) {+ checks++;+ if (!ok) { NSLog(@"FAIL: %@", name); exit(1); }+}+int main(void) { @autoreleasepool {+ NSString *album = @"spotify:album:4eLPsYPBmXABThSJ821sqY";+ NSString *a = @"spotify:track:1n4jwRVXdkK2U34nBDUKKT", *b = @"spotify:track:6HZILIRieu8S0iqY8kIKhj";+ NSDictionary *(^context)(id) = ^NSDictionary *(id pages) { return @{@"uri":album,@"pages":pages}; };+ NSDictionary *(^page)(NSArray *) = ^NSDictionary *(NSArray *tracks) { return @{@"tracks":tracks}; };+ NSDictionary *ta = @{@"uri":a}, *tb = @{@"uri":b};+ NSString *error = @"stale";+ NSArray *result = SGAlbumQueueTrackURIs(context(@[page(@[ta,tb]),page(@[ta])]), album, &error);+ check([result isEqual:@[a,b,a]] && error == nil, @"disc/page order and repeated tracks survive");+ check(SGAlbumQueueIsAlbumURI(album), @"valid album identity");+ check(!SGAlbumQueueIsAlbumURI(a), @"a track is not an album");+ check(!SGAlbumQueueIsAlbumURI(@"spotify:album:../../../../../../../../"), @"invalid album characters");+ NSArray *bad = @[+ NSNull.null, @{}, @{@"uri":a,@"pages":@[page(@[ta])]},+ context(@[]), context(@[NSNull.null]), context(@[@{@"tracks":@"bad"}]),+ context(@[page(@[])]), context(@[page(@[ta,NSNull.null])]),+ context(@[page(@[ta,@{@"uri":album}])]),+ context(@[page(@[ta,@{@"uri":@"spotify:track:../bad"}])]),+ context(@[@{@"tracks":@[ta],@"next_page_url":@"hm://more"}]),+ context(@[page(@[ta]),@{@"page_url":@"hm://missing-page"}])+ ];+ for (id value in bad) {+ error = nil;+ check(SGAlbumQueueTrackURIs(value, album, &error) == nil && error.length > 0, @"incomplete or malformed context submits no tracks");+ }+ check(SGAlbumQueueTrackURIs(context(@[page(@[ta])]), @"not-an-album", NULL) == nil, @"invalid request identity rejected");+ NSLog(@"%d album context checks passed", checks);+} return 0; }diff --git a/harness/album-queue/page.swift b/harness/album-queue/page.swiftnew file mode 100644index 00000000..33091203--- /dev/null+++ b/harness/album-queue/page.swift@@ -0,0 +1,10 @@+struct CreativeWork { let uri: URL }+struct Template { let creativeWork: CreativeWork }+final class Page: NSObject { let template: Template; init(_ uri: String) { template = Template(creativeWork: CreativeWork(uri: URL(string: uri)!)) } }+final class WrongShape: NSObject { let creativeWork = CreativeWork(uri: URL(string: "spotify:album:4eLPsYPBmXABThSJ821sqY")!) }+let album = "spotify:album:4eLPsYPBmXABThSJ821sqY"+precondition(SGAlbumQueuePage.albumURI(Page(album)) == album)+precondition(SGAlbumQueuePage.albumURI(Page("spotify:episode:4eLPsYPBmXABThSJ821sqY")) == nil)+precondition(SGAlbumQueuePage.albumURI(WrongShape()) == nil)+precondition(SGAlbumQueuePage.albumURI(NSObject()) == nil)+print("4 album page identity checks passed")diff --git a/harness/system-menu/main.m b/harness/system-menu/main.mindex 0d42c146..b746d7a2 100644--- a/harness/system-menu/main.m+++ b/harness/system-menu/main.m@@ -16,6 +16,10 @@#import <objc/runtime.h>#import "Redesigned/ContextMenu/ContextMenu.h"+// The album footer is exercised by harness/album-queue and the Spotify simulator test. These+// player-menu fixtures do not provide an album page or the shared album footer.+void SGAlbumQueueInstall(UIViewController *menu) {}+void SGRPlayerMenuWatch(UIView *button);// touch.m: a finger's touches, through UIKit's own recognizers.extern void SGHarnessTap(UIWindow *window, CGPoint point);@@ -55,6 +59,7 @@ static NSInteger sg_background = 2;double SGPlayerSpeed(void) { return sg_speed; }BOOL SGPlayerSpeedAllowed(void) { return YES; }void SGSetPlayerSpeed(double speed) { sg_speed = speed; NSLog(@"[harness] speed %.2f", speed); }+void SGPlayerShowSpeedPitchPanel(UIView *from) { NSLog(@"[harness] speed and pitch panel requested"); }float SGPlayerPitch(void) { return sg_pitch; }void SGSetPlayerPitch(float semitones) { sg_pitch = semitones; NSLog(@"[harness] pitch %.0f", semitones); }BOOL SGPlayerPitchAvailable(void) { return YES; }diff --git a/tweak/Sources/Native/AlbumQueue/AlbumQueueMenu.x b/tweak/Sources/Native/AlbumQueue/AlbumQueueMenu.xnew file mode 100644index 00000000..db084f19--- /dev/null+++ b/tweak/Sources/Native/AlbumQueue/AlbumQueueMenu.x@@ -0,0 +1,39 @@+// Mark the native album header immediately before its menu action runs. Both UIKit dispatch+// paths are already used by Shared/Haptics/ControlHaptics.x: target/selector and UIAction.+#import "Core/SGCore.h"+#import "Shared/AdBlock/AdBlock.h"+#import "Shared/AlbumQueue/AlbumQueue.h"++static const UIControlEvents kActivationEvents = UIControlEventTouchUpInside | UIControlEventPrimaryActionTriggered;++static BOOL isMenuButton(UIControl *control) {+ return [control.accessibilityIdentifier hasPrefix:SGAlbumQueueButtonPrefix];+}++%hook UIControl+- (void)sendAction:(SEL)selector to:(id)target forEvent:(UIEvent *)event {+ if (isMenuButton(self)) {+ __block BOOL activates = NO;+ [self enumerateEventHandlers:^(UIAction *action, id registeredTarget, SEL registeredSelector, UIControlEvents events, BOOL *stop) {+ if (!action && registeredSelector == selector && (!registeredTarget || registeredTarget == target) && (events & kActivationEvents)) activates = YES;+ }];+ if (activates) SGAlbumQueueMarkSource(self);+ }+ %orig;+}+- (void)sendAction:(UIAction *)action {+ if (isMenuButton(self)) {+ __block BOOL activates = NO;+ [self enumerateEventHandlers:^(UIAction *registered, id target, SEL selector, UIControlEvents events, BOOL *stop) {+ if (registered == action && (events & kActivationEvents)) activates = YES;+ }];+ if (activates) SGAlbumQueueMarkSource(self);+ }+ %orig;+}+%end++%ctor {+ if (!SGNativeUI() || !SGHidden(SGKeyFakePremium)) return;+ %init;+}diff --git a/tweak/Sources/Redesigned/ContextMenu/ContextMenu.x b/tweak/Sources/Redesigned/ContextMenu/ContextMenu.xindex c69334f0..3da506ac 100644--- a/tweak/Sources/Redesigned/ContextMenu/ContextMenu.x+++ b/tweak/Sources/Redesigned/ContextMenu/ContextMenu.x@@ -26,6 +26,7 @@#import "Core/SGCore.h"#import "Redesigned/Kit/SGRKit.h"#import "Shared/Player/SpeedPitch.h"+#import "Shared/AlbumQueue/AlbumQueue.h"#import "ContextMenu.h"// After a pick of Spotify's, how long its sheet has to start going, or to push a page of its own (which shows@@ -845,6 +846,7 @@ static NSString *storedKey(NSString *kind) {if (_groups) return YES;UITableView *table = tableIn(self.sheet.viewIfLoaded, 0);if (!table || rowCount(table) == 0) return NO;+ SGAlbumQueueInstall(self.sheet);CFTimeInterval started = CACurrentMediaTime();[table layoutIfNeeded];_table = table;diff --git a/tweak/Sources/Redesigned/Kit/SGRActionRow.m b/tweak/Sources/Redesigned/Kit/SGRActionRow.mindex 791a8808..662d9d9d 100644--- a/tweak/Sources/Redesigned/Kit/SGRActionRow.m+++ b/tweak/Sources/Redesigned/Kit/SGRActionRow.m@@ -11,6 +11,7 @@#import "SGRTokens.h"#import "SGRAccent.h"#import "SGRDownload.h"+#import "Shared/AlbumQueue/AlbumQueue.h"// The capsule: the glyph is Spotify's own 48pt canvas with the triangle small in the middle of it, so the// lead is short and the gap to the word comes out of the canvas itself.@@ -394,6 +395,7 @@ static BOOL indicatorOn(UIView *button, BOOL *found) {}- (void)sgr_tap {+ if ([self.source.accessibilityIdentifier hasPrefix:SGAlbumQueueButtonPrefix]) SGAlbumQueueMarkSource(self.source);SGRActivate(self.source);// The word is watched where Spotify writes it, but a button that rebuilds its content on the state it// just took writes the new word into a label the watch has never seen. So a tap, and only a tap, asksdiff --git a/tweak/Sources/Shared/AlbumQueue/AlbumPage.swift b/tweak/Sources/Shared/AlbumQueue/AlbumPage.swiftnew file mode 100644index 00000000..17d153b7--- /dev/null+++ b/tweak/Sources/Shared/AlbumQueue/AlbumPage.swift@@ -0,0 +1,16 @@+import Foundation++// 9.1.90's CreativeWorkPageViewController keeps its identity here. Swift reflection reads the+// named fields without depending on offsets or importing Spotify's modules. A changed shape yields nil.+@objc(SGAlbumQueuePage)+public final class SGAlbumQueuePage: NSObject {+ @objc public static func albumURI(_ controller: AnyObject) -> String? {+ var value: Any = controller+ for field in ["template", "creativeWork", "uri"] {+ guard let child = Mirror(reflecting: value).children.first(where: { $0.label == field }) else { return nil }+ value = child.value+ }+ guard let url = value as? URL, url.absoluteString.hasPrefix("spotify:album:") else { return nil }+ return url.absoluteString+ }+}diff --git a/tweak/Sources/Shared/AlbumQueue/AlbumQueue.h b/tweak/Sources/Shared/AlbumQueue/AlbumQueue.hnew file mode 100644index 00000000..4f63bf3c--- /dev/null+++ b/tweak/Sources/Shared/AlbumQueue/AlbumQueue.h@@ -0,0 +1,14 @@+#import <Foundation/Foundation.h>+@class UIView, UIViewController;+BOOL SGAlbumQueueIsAlbumURI(NSString *uri);++// Spotify's ⋯ buttons. An album header's identifier ends in the album's id.+#define SGAlbumQueueButtonPrefix @"Components.UI.ContextMenuButton-"++// Records the album of a tapped header ⋯, checked against Spotify's Creative Work page.+void SGAlbumQueueMarkSource(UIView *view);+void SGAlbumQueueInstall(UIViewController *menu);+// Resolves the album, then uses Spotify's bulk queue command. Completion is on main.+void SGAlbumQueueAdd(NSString *uri, void (^done)(NSUInteger count, NSString *error));+// Strict context response parser: order and repeated tracks are preserved; partial albums fail.+NSArray<NSString *> *SGAlbumQueueTrackURIs(id context, NSString *uri, NSString **error);diff --git a/tweak/Sources/Shared/AlbumQueue/AlbumQueue.m b/tweak/Sources/Shared/AlbumQueue/AlbumQueue.mnew file mode 100644index 00000000..6016301e--- /dev/null+++ b/tweak/Sources/Shared/AlbumQueue/AlbumQueue.m@@ -0,0 +1,110 @@+#import "Core/SGCore.h"+#import "Shared/Lyrics/Lyrics.h"+#import "Shared/Player/PlayerState.h"+#import "Headers/SPTPlayer.h"+#import "AlbumQueue.h"++@interface SPTPlayerTrack (SGAlbumQueue)+- (instancetype)initWithURI:(NSURL *)uri albumURI:(NSURL *)album artistURI:(NSURL *)artist andUID:(NSString *)uid;+@end+@interface SPTask : NSObject+- (id)addCallback:(void (^)(id))callback on:(dispatch_queue_t)queue;+- (id)addErrorCallback:(void (^)(NSError *))callback on:(dispatch_queue_t)queue;+@end+@interface SPTPlayerQueueWrapperImpl : NSObject+- (instancetype)initWithPlayer:(id)player;+- (SPTask *)queueMultipleTracks:(NSArray *)tracks loggingParams:(id)params;+@end++// One request at a time, so repeated taps cannot append the same album while its metadata is loading.+@interface SGAlbumQueueRequest : NSObject+@property (nonatomic, copy) void (^done)(NSUInteger, NSString *);+@property (nonatomic, strong) id player;+@property (nonatomic, strong) SPTPlayerQueueWrapperImpl *wrapper;+@property (nonatomic, strong) SPTask *task;+@property (nonatomic) BOOL finished, submitted;+- (void)finish:(NSUInteger)count error:(NSString *)error;+@end+static SGAlbumQueueRequest *sg_request;+@implementation SGAlbumQueueRequest+- (void)finish:(NSUInteger)count error:(NSString *)error {+ if (self.finished) return;+ self.finished = YES;+ void (^done)(NSUInteger, NSString *) = self.done;+ self.done = nil;+ self.task = nil;+ self.wrapper = nil;+ sg_request = nil;+ done(count, error);+}+@end++void SGAlbumQueueAdd(NSString *uri, void (^done)(NSUInteger, NSString *)) {+ NSCAssert(NSThread.isMainThread, @"album queue runs on main");+ if (!SGAlbumQueueIsAlbumURI(uri)) { done(0, @"This is not a Spotify album."); return; }+ if (sg_request) { done(0, @"An album is already being added to the queue."); return; }+ id player = SGPlayer();+ Class wrapper = NSClassFromString(@"SPTPlayerQueueWrapperImpl"), track = NSClassFromString(@"SPTPlayerTrack");+ if (!player || ![wrapper instancesRespondToSelector:@selector(initWithPlayer:)] ||+ ![wrapper instancesRespondToSelector:@selector(queueMultipleTracks:loggingParams:)] ||+ ![track instancesRespondToSelector:@selector(initWithURI:albumURI:artistURI:andUID:)]) {+ done(0, @"Spotify's queue is not ready."); return;+ }+ SGAlbumQueueRequest *request = [SGAlbumQueueRequest new];+ request.player = player;+ request.done = done;+ sg_request = request;+ // SGSpclientHeaders can wait for Spotify's next request. A late header or metadata answer must+ // never queue an album after the user has already been told that loading failed.+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 25 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{+ if (!request.submitted) [request finish:0 error:@"Spotify took too long to load the album. Try again."];+ });+ __weak SGAlbumQueueRequest *weakRequest = request;+ SGSpclientHeaders(^(NSDictionary<NSString *, NSString *> *headers) {+ SGAlbumQueueRequest *request = weakRequest;+ if (!request || request.finished) return;+ NSString *address = [@"https://spclient.wg.spotify.com/context-resolve/v1/" stringByAppendingString:uri];+ NSMutableURLRequest *http = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:address]];+ http.timeoutInterval = 15;+ http.allHTTPHeaderFields = headers;+ [http setValue:@"application/json" forHTTPHeaderField:@"Accept"];+ [[NSURLSession.sharedSession dataTaskWithRequest:http completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {+ NSInteger status = [response isKindOfClass:NSHTTPURLResponse.class] ? ((NSHTTPURLResponse *)response).statusCode : 0;+ id context = status == 200 && data.length > 0 && data.length <= 2 * 1024 * 1024 ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;+ NSString *reason;+ NSArray *uris = SGAlbumQueueTrackURIs(context, uri, &reason);+ dispatch_async(dispatch_get_main_queue(), ^{+ if (request.finished) return;+ if (!uris) {+ if (error || status != 200) SGLog(@"album queue: context-resolve status %ld, %@", (long)status, error);+ [request finish:0 error:error || status != 200 ? @"Spotify could not load the album. Try again." : reason];+ return;+ }+ NSMutableArray *tracks = [NSMutableArray arrayWithCapacity:uris.count];+ for (NSString *trackURI in uris) {+ SPTPlayerTrack *item = [[track alloc] initWithURI:[NSURL URLWithString:trackURI] albumURI:[NSURL URLWithString:uri] artistURI:nil andUID:nil];+ if (!item) { [request finish:0 error:@"Spotify could not prepare the album."]; return; }+ [tracks addObject:item];+ }+ request.wrapper = [[wrapper alloc] initWithPlayer:request.player];+ SPTask *task = [request.wrapper queueMultipleTracks:tracks loggingParams:nil];+ if (![task respondsToSelector:@selector(addCallback:on:)] || ![task respondsToSelector:@selector(addErrorCallback:on:)]) {+ [request finish:0 error:@"Spotify did not return a queue result."]; return;+ }+ request.submitted = YES;+ request.task = task;+ // A task that never answers would otherwise hold sg_request and refuse every later album.+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 15 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{+ [request finish:0 error:@"Spotify did not confirm the album was queued. Check the queue before trying again."];+ });+ [task addCallback:^(id value) {+ SGLog(@"album queue: %lu tracks added", (unsigned long)uris.count);+ [request finish:uris.count error:nil];+ } on:dispatch_get_main_queue()];+ [task addErrorCallback:^(NSError *failure) {+ [request finish:0 error:@"Spotify could not add the album to the queue."];+ } on:dispatch_get_main_queue()];+ });+ }] resume];+ });+}diff --git a/tweak/Sources/Shared/AlbumQueue/AlbumQueueContext.m b/tweak/Sources/Shared/AlbumQueue/AlbumQueueContext.mnew file mode 100644index 00000000..f4af5952--- /dev/null+++ b/tweak/Sources/Shared/AlbumQueue/AlbumQueueContext.m@@ -0,0 +1,36 @@+#import "AlbumQueue.h"++static BOOL validURI(NSString *uri, NSString *prefix) {+ if (![uri isKindOfClass:NSString.class] || ![uri hasPrefix:prefix] || uri.length != prefix.length + 22) return NO;+ for (NSUInteger i = prefix.length; i < uri.length; i++) {+ unichar c = [uri characterAtIndex:i];+ if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) return NO;+ }+ return YES;+}++NSArray<NSString *> *SGAlbumQueueTrackURIs(id context, NSString *uri, NSString **error) {+ if (error) *error = @"Spotify did not return a complete album.";+ if (!validURI(uri, @"spotify:album:") || ![context isKindOfClass:NSDictionary.class] || ![context[@"uri"] isEqual:uri]) return nil;+ id pages = context[@"pages"];+ if (![pages isKindOfClass:NSArray.class] || ![pages count]) return nil;+ NSMutableArray *tracks = [NSMutableArray array];+ for (id page in pages) {+ if (![page isKindOfClass:NSDictionary.class]) return nil;+ // Do not queue just the first page of a large release. No queue command runs for a partial answer.+ id next = page[@"next_page_url"];+ if (next && next != NSNull.null && ![next isEqual:@""]) return nil;+ id entries = page[@"tracks"];+ if (![entries isKindOfClass:NSArray.class]) return nil;+ for (id entry in entries) {+ if (![entry isKindOfClass:NSDictionary.class] || !validURI(entry[@"uri"], @"spotify:track:")) return nil;+ [tracks addObject:entry[@"uri"]];+ if (tracks.count > 5000) return nil;+ }+ }+ if (!tracks.count) return nil;+ if (error) *error = nil;+ return tracks;+}++BOOL SGAlbumQueueIsAlbumURI(NSString *uri) { return validURI(uri, @"spotify:album:"); }diff --git a/tweak/Sources/Shared/AlbumQueue/AlbumQueueMenu.x b/tweak/Sources/Shared/AlbumQueue/AlbumQueueMenu.xnew file mode 100644index 00000000..149f7035--- /dev/null+++ b/tweak/Sources/Shared/AlbumQueue/AlbumQueueMenu.x@@ -0,0 +1,329 @@+#import "Core/SGCore.h"+#import "Shared/AdBlock/AdBlock.h"+#import "AlbumQueue.h"++@interface SGAlbumQueuePage : NSObject++ (NSString *)albumURI:(id)controller;+@end++static char kURIKey, kRowKey, kNativeKey, kSeenKey;+static NSString *sg_pending;+static CFTimeInterval sg_markedAt;+static NSString *const kPageClass = @"_TtC28CreativeWorkPlatform_PageKit24CreativeWorkTemplateView";++static NSString *SGAlbumQueueURIForView(UIView *view) {+ // The page model is the authority; a track's own ⋯ shares the page but has another identifier.+ static Class pageClass;+ if (!pageClass) pageClass = NSClassFromString(kPageClass);+ UIView *page = view;+ while (page && ![page isKindOfClass:pageClass]) page = page.superview;+ if (!page) return nil;+ NSString *uri;+ for (UIResponder *r = page.nextResponder; r; r = r.nextResponder) {+ if ([r isKindOfClass:UIViewController.class]) {+ uri = [SGAlbumQueuePage albumURI:r];+ if (uri) break;+ }+ }+ if (!SGAlbumQueueIsAlbumURI(uri)) return nil;+ NSString *identifier = [SGAlbumQueueButtonPrefix stringByAppendingString:[uri substringFromIndex:@"spotify:album:".length]];+ if (![view.accessibilityIdentifier isEqualToString:identifier]) return nil;+ for (UIView *v = view; v != page; v = v.superview) {+ if ([v.accessibilityIdentifier isEqualToString:@"CreativeWorkPlatform.Header"]) return uri;+ }+ // A pinned button lives outside the header. Find the original inside the header only.+ __block BOOL matches = NO;+ SGForEachView(page, ^(UIView *header) {+ if (![header.accessibilityIdentifier isEqualToString:@"CreativeWorkPlatform.Header"]) return;+ SGForEachView(header, ^(UIView *v) { if ([v.accessibilityIdentifier isEqualToString:identifier]) matches = YES; });+ });+ return matches ? uri : nil;+}++void SGAlbumQueueMarkSource(UIView *view) {+ sg_pending = SGAlbumQueueURIForView(view);+ sg_markedAt = CACurrentMediaTime();+}++static UITableView *tableIn(UIView *view, NSUInteger depth) {+ if ([view isKindOfClass:UITableView.class]) return (UITableView *)view;+ if (depth > 6) return nil;+ for (UIView *child in view.subviews) {+ UITableView *table = tableIn(child, depth + 1);+ if (table) return table;+ }+ return nil;+}++// Spotify's item number "11" first, so another language still matches, then the English title, as+// Redesigned/ContextMenu's quickItems() does for a sheet without the number.+static BOOL isNativeQueueView(UIView *view) {+ if ([view.accessibilityIdentifier isEqualToString:@"11"]) return YES;+ if (![view isKindOfClass:UILabel.class]) return NO;+ NSString *title = [((UILabel *)view).text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];+ return [title.lowercaseString isEqualToString:@"add to queue"];+}++static BOOL hasNativeQueueRow(UITableView *table) {+ for (NSInteger section = 0; section < table.numberOfSections; section++) {+ for (NSInteger index = 0; index < [table numberOfRowsInSection:section]; index++) {+ NSIndexPath *path = [NSIndexPath indexPathForRow:index inSection:section];+ UITableViewCell *cell = [table cellForRowAtIndexPath:path];+ cell = cell ?: [table.dataSource tableView:table cellForRowAtIndexPath:path];+ __block BOOL found = NO;+ SGForEachView(cell, ^(UIView *v) { if (isNativeQueueView(v)) found = YES; });+ if (found) return YES;+ }+ }+ return NO;+}++// The outcome as a glass capsule under the Dynamic Island, the way the system confirms an action.+// It materializes on a critically damped spring, leaves the way it came, and a tap or an upward+// swipe sends it off early. VoiceOver hears the same words.+@interface SGAlbumQueueNotice : UIView+@end+@implementation SGAlbumQueueNotice {+ UIVisualEffectView *_glass;+ CGFloat _restY;+ BOOL _leaving;+}+static __weak SGAlbumQueueNotice *sg_notice;+++ (void)showIn:(UIWindow *)window title:(NSString *)title detail:(NSString *)detail symbol:(NSString *)symbol {+ if (!window) return;+ [sg_notice leave:0];+ SGAlbumQueueNotice *notice = [[self alloc] initWithFrame:CGRectZero];+ notice.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;+ [notice buildIn:window title:title detail:detail symbol:symbol];+ sg_notice = notice;+ UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, notice.accessibilityLabel);+ // Long enough to read: a confirmation is glanced at, a problem is read.+ NSTimeInterval stay = detail ? 2.5 : 4;+ __weak SGAlbumQueueNotice *weakNotice = notice;+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(stay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [weakNotice leave:0]; });+}++- (void)buildIn:(UIWindow *)window title:(NSString *)title detail:(NSString *)detail symbol:(NSString *)symbol {+ UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage systemImageNamed:symbol]];+ icon.preferredSymbolConfiguration = [UIImageSymbolConfiguration configurationWithTextStyle:UIFontTextStyleBody scale:UIImageSymbolScaleMedium];+ icon.tintColor = UIColor.labelColor;+ icon.contentMode = UIViewContentModeCenter;+ UILabel *top = [UILabel new];+ top.text = title;+ UIFont *subheadline = [UIFont preferredFontForTextStyle:UIFontTextStyleSubheadline];+ top.font = [UIFont systemFontOfSize:subheadline.pointSize weight:UIFontWeightSemibold];+ top.textColor = UIColor.labelColor;+ top.numberOfLines = 0;+ top.textAlignment = detail ? NSTextAlignmentNatural : NSTextAlignmentCenter;+ UILabel *bottom = [UILabel new];+ bottom.text = detail;+ bottom.font = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];+ // secondaryLabelColor reads under 3:1 on the tinted glass; this reads about 5.7:1.+ bottom.textColor = [UIColor colorWithWhite:1 alpha:0.78];++ // Hugs its words, up to a width that keeps a line short enough to read at a glance.+ CGFloat maxWidth = MIN(window.bounds.size.width - 32, 380), iconSide = 28, pad = 18, gap = 10;+ CGFloat textMax = maxWidth - pad * 2 - iconSide - gap;+ CGSize topSize = [top sizeThatFits:CGSizeMake(textMax, CGFLOAT_MAX)];+ CGSize bottomSize = detail ? [bottom sizeThatFits:CGSizeMake(textMax, CGFLOAT_MAX)] : CGSizeZero;+ CGFloat textWidth = MIN(textMax, MAX(topSize.width, bottomSize.width));+ CGFloat textHeight = topSize.height + bottomSize.height;+ CGFloat height = MAX(50, textHeight + 24), width = pad * 2 + iconSide + gap + textWidth;+ _restY = window.safeAreaInsets.top + 6;+ self.frame = CGRectMake((window.bounds.size.width - width) / 2, _restY, width, height);+ self.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;++ _glass = [[UIVisualEffectView alloc] initWithEffect:nil];+ _glass.frame = self.bounds;+ _glass.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;+ [self addSubview:_glass];+ SGShapeGlass(_glass, 22, textHeight < 40);+ icon.frame = CGRectMake(pad, (height - iconSide) / 2, iconSide, iconSide);+ CGFloat y = (height - textHeight) / 2;+ top.frame = CGRectMake(pad + iconSide + gap, y, textWidth, topSize.height);+ bottom.frame = CGRectMake(pad + iconSide + gap, y + topSize.height, textWidth, bottomSize.height);+ for (UIView *v in @[icon, top, bottom]) [_glass.contentView addSubview:v];++ self.isAccessibilityElement = YES;+ self.accessibilityLabel = detail ? [NSString stringWithFormat:@"%@, %@", title, detail] : title;+ self.accessibilityHint = @"Double-tap to dismiss.";+ [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped)]];+ [self addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(dragged:)]];+ [window addSubview:self];++ // Reduce Motion keeps the fade and drops the travel.+ BOOL still = UIAccessibilityIsReduceMotionEnabled();+ self.alpha = 0;+ self.transform = still ? CGAffineTransformIdentity : CGAffineTransformScale(CGAffineTransformMakeTranslation(0, -height), 0.9, 0.9);+ // Glass turns light over a light cover; the tint keeps it dark enough for white words.+ UIVisualEffect *effect = SGGlassEffect();+ if ([effect respondsToSelector:@selector(setTintColor:)]) [(id)effect setTintColor:[UIColor colorWithWhite:0 alpha:0.55]];+ [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:1 initialSpringVelocity:0 options:UIViewAnimationOptionAllowUserInteraction animations:^{+ self.alpha = 1;+ self.transform = CGAffineTransformIdentity;+ self->_glass.effect = effect;+ } completion:nil];+}++- (void)tapped {+ [self leave:0];+}++// Follows the finger up, resists going down, and leaves on a flick or a short lift.+- (void)dragged:(UIPanGestureRecognizer *)pan {+ CGFloat dy = [pan translationInView:self.superview].y;+ if (pan.state == UIGestureRecognizerStateChanged) {+ self.transform = CGAffineTransformMakeTranslation(0, dy < 0 ? dy : dy / (1 + dy / 30));+ } else if (pan.state == UIGestureRecognizerStateEnded || pan.state == UIGestureRecognizerStateCancelled) {+ CGFloat velocity = [pan velocityInView:self.superview].y;+ if (dy < -16 || velocity < -300) {+ [self leave:velocity];+ } else {+ [UIView animateWithDuration:0.4 delay:0 usingSpringWithDamping:1 initialSpringVelocity:0 options:UIViewAnimationOptionAllowUserInteraction animations:^{+ self.transform = CGAffineTransformIdentity;+ } completion:nil];+ }+ }+}++- (void)leave:(CGFloat)velocity {+ if (_leaving) return;+ _leaving = YES;+ BOOL still = UIAccessibilityIsReduceMotionEnabled();+ CGFloat distance = self.frame.origin.y + self.bounds.size.height;+ CGFloat spring = distance > 0 && velocity < 0 ? -velocity / distance : 0;+ [UIView animateWithDuration:0.35 delay:0 usingSpringWithDamping:1 initialSpringVelocity:spring options:UIViewAnimationOptionBeginFromCurrentState animations:^{+ self.alpha = 0;+ if (!still) self.transform = CGAffineTransformScale(CGAffineTransformMakeTranslation(0, -distance), 0.9, 0.9);+ self->_glass.effect = nil;+ } completion:^(BOOL finished) {+ [self removeFromSuperview];+ }];+}+@end++@interface SGAlbumQueueRow : UIControl+@property (nonatomic, copy) NSString *uri;+@property (nonatomic, weak) UIViewController *menu;+@end+@implementation SGAlbumQueueRow {+ UILabel *_title;+ UIImageView *_icon;+}+- (instancetype)initWithFrame:(CGRect)frame {+ if (!(self = [super initWithFrame:frame])) return nil;+ self.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;+ _title = [UILabel new];+ _title.text = @"Add to Queue";+ _title.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];+ _title.adjustsFontForContentSizeCategory = YES;+ _title.textColor = UIColor.whiteColor;+ _icon = [[UIImageView alloc] initWithImage:[UIImage systemImageNamed:@"text.line.last.and.arrowtriangle.forward"]];+ _icon.tintColor = [UIColor colorWithWhite:1 alpha:0.65];+ _icon.contentMode = UIViewContentModeScaleAspectFit;+ for (UIView *v in @[_title, _icon]) { v.userInteractionEnabled = NO; [self addSubview:v]; }+ self.isAccessibilityElement = YES;+ self.accessibilityLabel = @"Add to Queue";+ self.accessibilityIdentifier = @"spotifyglass.albumQueue";+ self.accessibilityTraits = UIAccessibilityTraitButton;+ [self addTarget:self action:@selector(addAlbum) forControlEvents:UIControlEventTouchUpInside];+ return self;+}+- (void)layoutSubviews {+ [super layoutSubviews];+ CGFloat h = self.bounds.size.height, w = self.bounds.size.width;+ _icon.frame = CGRectMake(16, (h - 24) / 2, 24, 24);+ _title.frame = CGRectMake(56, 0, MAX(0, w - 72), h);+}+- (void)setHighlighted:(BOOL)highlighted {+ [super setHighlighted:highlighted];+ self.backgroundColor = [UIColor colorWithWhite:1 alpha:highlighted ? 0.08 : 0];+}+- (void)addAlbum {+ self.enabled = NO;+ UIViewController *menu = self.menu;+ // The app's own window: the redesign presents the menu from a window of the mod's that drops under the app's+ // once the menu is gone, which would hide the notice.+ UIWindow *window;+ for (UIWindow *w in menu.viewIfLoaded.window.windowScene.windows) {+ if (!w.hidden && w.windowLevel == UIWindowLevelNormal) { window = w; break; }+ }+ NSString *uri = self.uri;+ [menu dismissViewControllerAnimated:YES completion:nil];+ SGAlbumQueueAdd(uri, ^(NSUInteger count, NSString *error) {+ if (error) {+ [SGAlbumQueueNotice showIn:window title:error detail:nil symbol:@"exclamationmark.circle"];+ } else {+ NSString *songs = count == 1 ? @"1 song" : [NSString stringWithFormat:@"%lu songs", (unsigned long)count];+ [SGAlbumQueueNotice showIn:window title:@"Added to Queue" detail:songs symbol:@"text.line.last.and.arrowtriangle.forward"];+ }+ });+}+@end++void SGAlbumQueueInstall(UIViewController *menu) {+ NSString *uri = objc_getAssociatedObject(menu, &kURIKey);+ if (!uri) return;+ UITableView *table = tableIn(menu.viewIfLoaded, 0);+ if (table.bounds.size.width <= 0) return;+ NSInteger rows = 0;+ for (NSInteger section = 0; section < table.numberOfSections; section++) rows += [table numberOfRowsInSection:section];+ // Wait for Spotify's rows, so its own queue row wins whenever it is present. Decided once per menu,+ // because the scan asks the data source for cells it never shows.+ if (!rows) return;+ NSNumber *native = objc_getAssociatedObject(menu, &kNativeKey);+ if (!native) {+ native = @(hasNativeQueueRow(table));+ objc_setAssociatedObject(menu, &kNativeKey, native, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ }+ if (native.boolValue) return;+ SGAlbumQueueRow *row = objc_getAssociatedObject(menu, &kRowKey);+ if (table.tableFooterView && table.tableFooterView != row && table.tableFooterView.bounds.size.height > 0) return;+ if (!row) {+ row = [[SGAlbumQueueRow alloc] initWithFrame:CGRectZero];+ row.menu = menu;+ objc_setAssociatedObject(menu, &kRowKey, row, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ SGLog(@"album queue: row offered for %@", uri);+ }+ row.uri = uri;+ CGFloat height = MAX(56, [UIFont preferredFontForTextStyle:UIFontTextStyleBody].lineHeight + 24);+ CGSize size = CGSizeMake(table.bounds.size.width, height);+ // The table moves its footer to the end of the content, so only the size says whether it changed.+ if (table.tableFooterView != row || !CGSizeEqualToSize(row.bounds.size, size)) {+ // Outside the sheet's rise, or the row slides down over Spotify's rows from the table's top.+ [UIView performWithoutAnimation:^{+ row.frame = (CGRect){CGPointZero, size};+ table.tableFooterView = row;+ [table invalidateIntrinsicContentSize];+ [table layoutIfNeeded];+ }];+ }+}++%hook _TtC24ContextMenu_InternalImpl25ContextMenuViewController+- (void)viewWillAppear:(BOOL)animated {+ // Only the first appearance takes the marker; coming back from a page pushed in the sheet keeps the row.+ if (!objc_getAssociatedObject(self, &kSeenKey)) {+ objc_setAssociatedObject(self, &kSeenKey, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ NSString *uri = CACurrentMediaTime() - sg_markedAt <= 1.5 ? sg_pending : nil;+ sg_pending = nil;+ if (uri) {+ objc_setAssociatedObject(self, &kURIKey, uri, OBJC_ASSOCIATION_COPY_NONATOMIC);+ SGAlbumQueueInstall((UIViewController *)self);+ }+ }+ %orig;+}+- (void)viewDidLayoutSubviews {+ %orig;+ SGAlbumQueueInstall((UIViewController *)self);+}+%end+%ctor {+ if (!SGHidden(SGKeyFakePremium)) return;+ %init;+ SGRequireClasses(@[@"_TtC24ContextMenu_InternalImpl25ContextMenuViewController",+ kPageClass,+ @"SPTPlayerQueueWrapperImpl", @"SPTPlayerTrack"]);+}diff --git a/tweak/Sources/Shared/Player/PlayerState.h b/tweak/Sources/Shared/Player/PlayerState.hindex 8ff74543..c023db7e 100644--- a/tweak/Sources/Shared/Player/PlayerState.h+++ b/tweak/Sources/Shared/Player/PlayerState.h@@ -25,3 +25,5 @@ NSString *SGURIString(id uri);void SGAddPlayerStateObserver(id<SGPlayerStateObserver> observer);// The last state reported, nil before the player has reported one.SPTPlayerState *SGPlayerState(void);+// The SPTEsperantoPlayer the mod observes, nil until the app has added its first observer.+id SGPlayer(void);diff --git a/tweak/Sources/Shared/Player/PlayerState.x b/tweak/Sources/Shared/Player/PlayerState.xindex 93415daa..6a4cf9a1 100644--- a/tweak/Sources/Shared/Player/PlayerState.x+++ b/tweak/Sources/Shared/Player/PlayerState.x@@ -64,6 +64,11 @@ static void report(id state, BOOL platform) {@endstatic SGPlayerObserver *sg_ownObserver;+static __weak id sg_player;++id SGPlayer(void) {+ return sg_player;+}%hook _TtC23NowPlaying_PlatformImpl28StatefulPlayerImplementation- (void)player:(id)player stateDidChange:(id)state {@@ -85,6 +90,7 @@ static SGPlayerObserver *sg_ownObserver;static dispatch_once_t once;dispatch_once(&once, ^{dispatch_async(dispatch_get_main_queue(), ^{+ sg_player = player;sg_ownObserver = [SGPlayerObserver new];[(id<SPTPlayer>)player addPlayerObserver:sg_ownObserver];id state = [player respondsToSelector:@selector(state)] ? [(id<SPTPlayer>)player state] : nil;