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 player's and pinned pages' more button opens the system menu

My-Name-Is-Jeff8464e29634b3
diff --git a/docs/tweaks.md b/docs/tweaks.md
index 8f8457d2..4423b19b 100644
--- a/docs/tweaks.md
+++ b/docs/tweaks.md
@@ -163,7 +163,11 @@ Shared:
and is drawn from its own measures, not the Kit's, so it sits there under either look. Tested on the
Mac against harness/pitch/ and in the simulator against harness/speed/ and harness/menu/. Under the
redesign, with the player's background Fluid or Animated, a row under the block switches Animated
- artwork at once, through functions the redesign's PlayerMotion.x defines
+ artwork at once, through functions the redesign's PlayerMotion.x defines. The redesign shows that
+ sheet as the system menu (Redesigned/ContextMenu), whose own items stand in for the block, so the
+ block stays out of it unless the sheet itself is shown (SGPlayerMenuReplaced). Switch to video,
+ the chip over the title of a song with a music video, is hidden under either look on request
+ (VideoSwitch.x, spotifyglass.hide.videoSwitch), by its identifier in FloatingElementsUnit
AudioEffects/ the audio effects on Spotify's sound (AudioEffects.h has the keys and the page's calls): Spotify's
import of AudioOutputUnitStart is rebound, as Music Haptics does, and a render notify on its RemoteIO
unit runs each finished buffer through the mod's own engine, re-blocked to 1024 frames one block late,
@@ -289,8 +293,19 @@ Redesigned:
NowPlayingBar/ the glass now playing bar (NowPlayingBar.x), with Spotify's device button on it hidden on request
(BarConnect.x, its own key and its own Now playing page, apart from the native look's). In a Jam the
glass stays on the track and Spotify's Jam strip gets a pane of its own above it (harness/tabbar/, jam)
- Player/ the redesigned full screen player (Player.h lists its files); its more button is handed to
- Shared/Player's Speed and pitch, which draws in the menu it opens, and a hold on either side of the
+ ContextMenu/ the ⋯ of the player and the ⋯ pinned over the playlist, album and artist pages open the system menu,
+ always (ContextMenu.h): Spotify's sheet is still made, presented unanimated in a container hidden from
+ the presented controller's viewWillAppear: on, so nothing darkens; the menu comes from an invisible
+ button inside the ⋯ that takes touches only while it is up, opened with -performPrimaryAction (else
+ UIContextMenuInteraction's private _presentMenuAtLocation:, checked with respondsToSelector:).
+ Spotify's rows, read off the sheet's cells (words, glyph, greyed out), are a deferred element that
+ waits for them as long as the menu is up; the mod's own rows in the sheet's header and footer (Sort,
+ Mix, Edit info) come with them. A pick selects the row on the sheet once the menu is gone; a pick
+ that leaves the sheet up, or a menu that does not come up, shows the sheet; a close with no pick
+ dismisses it. Checked in the simulator against harness/system-menu/
+ Player/ the redesigned full screen player (Player.h lists its files); its more button opens the system
+ menu (ContextMenu/), Spotify's rows and then Playback Speed, Pitch (with Pitch follows speed),
+ Reverb and Animated artwork (PlayerMenu.m), and a hold on either side of the
cover plays at 2x until the finger lifts (PlayerArtwork.x), an octave higher while Pitch follows
speed is on. Animated artwork (PlayerMotion.x)
runs the clip edge to edge from the top over its own last rows drawn on down, with a blur coming in
diff --git a/harness/menu/main.m b/harness/menu/main.m
index 9f979a3b..2add6ac8 100644
--- a/harness/menu/main.m
+++ b/harness/menu/main.m
@@ -35,6 +35,8 @@ static BOOL sg_animated;
BOOL SGPlayerMenuOffersAnimatedArtwork(void) { return [NSProcessInfo.processInfo.arguments containsObject:@"animated"]; }
BOOL SGPlayerMenuAnimatedArtwork(void) { return sg_animated; }
void SGPlayerMenuSetAnimatedArtwork(BOOL on) { sg_animated = on; NSLog(@"[harness] animated artwork %d", on); }
+// The redesign's system menu, which never takes this sheet over here (harness/system-menu has it).
+BOOL SGPlayerMenuReplaced(UIViewController *menu) { return NO; }
// The audio effects' settings, kept in a dictionary: the reverb slider reads and writes them.
static NSMutableDictionary *sg_dsp;
BOOL SGDSPSwitch(NSString *key) { return [sg_dsp[key] boolValue]; }
diff --git a/harness/system-menu/README.md b/harness/system-menu/README.md
new file mode 100644
index 00000000..69cf1d04
--- /dev/null
+++ b/harness/system-menu/README.md
@@ -0,0 +1,38 @@
+# System menu harness
+
+`Redesigned/ContextMenu/ContextMenu.x` and `Redesigned/Player/PlayerMenu.m` run for real against a mock of
+Spotify's context menu sheet (`ContextMenu_InternalImpl.ContextMenuViewController` under its class name,
+a table of rows with a delegate, inside a navigation controller), presented by a ⋯ button the way
+Spotify's is. Speed, pitch, reverb and Animated artwork are stubs that log.
+
+ THEOS=$HOME/theos ./build.sh
+ xcrun simctl install <udid> build/SystemMenuHarness.app
+ xcrun simctl launch --console-pty <udid> com.vitrine.systemmenuharness <scenario>
+
+Each run taps ⋯ at 1 s, waits for the sheet's presentation to end (the simulator takes a second or more
+over the first one), and prints `PASS` or `FAIL` lines, then `done`. A pick, or opening a submenu, goes
+through the menu view's own selection (`_UIContextMenuView`'s `_handleSelectionForElement:`), the harness's
+only private call; the mod's own lines (`SGLog`) go to the unified log.
+
+Every scenario but `fallback` first checks the top level: the sheet is hidden (its container at alpha 0),
+the system menu is up with the quick row (Share, Add to Playlist, Add to Queue), Speed, Pitch & Reverb, Show
+Animated Artwork and More, none of Spotify's other rows at the top, and the anchor takes touches.
+
+- `rows`: More holds Go to album and the greyed-out, disabled Lyrics, and not the rows the quick row has;
+ picking Go to album selects it on the sheet, which goes, and the anchor gives its touches back.
+- `loading`: the sheet has no rows when the menu comes up; More opened then shows none, the rows come into
+ the open More once the sheet has them, and Go to album fires.
+- `quick`: Add to Queue is picked before the sheet has its rows, which come 1 s after the menu has gone; the
+ pick waits for them and selects Spotify's Add to queue.
+- `quicklate`: Add to Playlist is picked and the rows never come: after 2 s Spotify's sheet is shown.
+- `podcast`: a sheet with no Add to playlist row, its rows late: once they are in, the quick row drops Add to
+ Playlist while the menu is up, and More holds Go to show.
+- `close`: closing the menu with no pick dismisses the sheet, and a second tap opens it again.
+- `subpage`: the quick Share selects Spotify's Share, which pushes a page inside the sheet instead of
+ closing it, so the sheet is shown.
+- `sort`: a row of the mod's own in the sheet's header (as the playlist's Sort) is in More and fires.
+- `animated`: Show Animated Artwork switches it on and the sheet goes.
+- `fallback`: neither `performPrimaryAction` nor `_presentMenuAtLocation:` does anything, so the sheet
+ shows at once and the anchor takes no touches.
+- `show`, `showmore`, `showsound`: the menu, More or Speed, Pitch & Reverb held open, for a screenshot
+ (`xcrun simctl io <udid> screenshot`); these never exit.
diff --git a/harness/system-menu/build.sh b/harness/system-menu/build.sh
new file mode 100755
index 00000000..80a49d9f
--- /dev/null
+++ b/harness/system-menu/build.sh
@@ -0,0 +1,40 @@
+#!/bin/sh
+# Builds the system menu harness for the simulator: ContextMenu.x's hooks and PlayerMenu.m run for real
+# on a mock of Spotify's context menu sheet.
+set -e
+SRC=$(cd "$(dirname "$0")/../../tweak/Sources" && pwd)
+OUT=$(dirname "$0")/build
+rm -rf "$OUT"; mkdir -p "$OUT/gen" "$OUT/SystemMenuHarness.app"
+"$THEOS/bin/logos.pl" -c generator=internal "$SRC/Redesigned/ContextMenu/ContextMenu.x" > "$OUT/gen/ContextMenu.m"
+
+SDK=$(xcrun --sdk iphonesimulator --show-sdk-path)
+xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.4-simulator -fobjc-arc -g -O0 \
+ -I"$SRC" -I"$SRC/Redesigned/ContextMenu" -isysroot "$SDK" -Wno-deprecated-declarations \
+ "$(dirname "$0")/main.m" "$(dirname "$0")/../scene.m" "$OUT"/gen/*.m "$SRC"/Redesigned/Player/PlayerMenu.m \
+ "$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGViewTree.m "$SRC"/Core/SGUIMode.m \
+ -framework UIKit -framework QuartzCore -framework CoreGraphics -framework Foundation \
+ -o "$OUT/SystemMenuHarness.app/SystemMenuHarness"
+
+cat > "$OUT/SystemMenuHarness.app/Info.plist" <<'PLIST'
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0"><dict>
+<key>CFBundleExecutable</key><string>SystemMenuHarness</string>
+<key>CFBundleIdentifier</key><string>com.vitrine.systemmenuharness</string>
+<key>CFBundleName</key><string>SystemMenuHarness</string>
+<key>CFBundleVersion</key><string>1</string>
+<key>CFBundleShortVersionString</key><string>1.0</string>
+<key>UIUserInterfaceStyle</key><string>Dark</string>
+<key>UILaunchScreen</key><dict/>
+<key>UIApplicationSceneManifest</key><dict>
+ <key>UIApplicationSupportsMultipleScenes</key><false/>
+ <key>UISceneConfigurations</key><dict>
+ <key>UIWindowSceneSessionRoleApplication</key><array><dict>
+ <key>UISceneConfigurationName</key><string>Default</string>
+ <key>UISceneDelegateClassName</key><string>SGRHarnessScene</string>
+ </dict></array>
+ </dict>
+</dict>
+</dict></plist>
+PLIST
+echo "built $OUT/SystemMenuHarness.app"
diff --git a/harness/system-menu/main.m b/harness/system-menu/main.m
new file mode 100644
index 00000000..13821f85
--- /dev/null
+++ b/harness/system-menu/main.m
@@ -0,0 +1,533 @@
+// Redesigned/ContextMenu/ContextMenu.x and Redesigned/Player/PlayerMenu.m run for real against a mock of
+// Spotify's context menu sheet (its class name, a table of rows with a delegate, a navigation controller
+// around it), presented by a ⋯ button the way Spotify's is, and the system menu checked as it comes up.
+//
+// THEOS=$HOME/theos ./build.sh && xcrun simctl install <udid> build/SystemMenuHarness.app
+// xcrun simctl launch --console-pty <udid> com.vitrine.systemmenuharness <scenario>
+//
+// Every scenario taps ⋯ at 1 s and prints PASS or FAIL lines, then `done` (README.md lists them). A pick or
+// a submenu is opened the way a finger on the menu does it, through the menu view's own selection
+// (_UIContextMenuView's _handleSelectionForElement:, the harness's only private call).
+#import <UIKit/UIKit.h>
+#import <objc/message.h>
+#import <objc/runtime.h>
+#import "Redesigned/ContextMenu/ContextMenu.h"
+
+void SGRPlayerMenuWatch(UIView *button);
+
+static NSString *scenario(void) {
+ NSArray<NSString *> *arguments = NSProcessInfo.processInfo.arguments;
+ return arguments.count > 1 ? arguments.lastObject : @"rows";
+}
+
+static BOOL is(NSString *run) {
+ return [scenario() isEqualToString:run];
+}
+
+// The scenarios whose sheet gets its rows only when the harness gives them.
+static BOOL rowsLate(void) {
+ return is(@"loading") || is(@"quick") || is(@"quicklate") || is(@"podcast");
+}
+
+static void check(BOOL ok, NSString *what) {
+ NSLog(@"[harness] %@ %@", ok ? @"PASS" : @"FAIL", what);
+}
+
+static void after(NSTimeInterval seconds, dispatch_block_t block) {
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(seconds * NSEC_PER_SEC)), dispatch_get_main_queue(), block);
+}
+
+// Runs `then` once `condition` holds, or after `limit` seconds whether or not it does.
+static void waitFor(BOOL (^condition)(void), NSTimeInterval limit, dispatch_block_t then) {
+ if (condition() || limit <= 0) {
+ then();
+ return;
+ }
+ after(0.1, ^{ waitFor(condition, limit - 0.1, then); });
+}
+
+#pragma mark - what the menu's code calls
+
+static double sg_speed = 1;
+static float sg_pitch, sg_reverb;
+static BOOL sg_follows = YES, sg_animated;
+double SGPlayerSpeed(void) { return sg_speed; }
+BOOL SGPlayerSpeedAllowed(void) { return YES; }
+void SGSetPlayerSpeed(double speed) { sg_speed = speed; NSLog(@"[harness] speed %.2f", speed); }
+float SGPlayerPitch(void) { return sg_pitch; }
+void SGSetPlayerPitch(float semitones) { sg_pitch = semitones; NSLog(@"[harness] pitch %.0f", semitones); }
+BOOL SGPlayerPitchAvailable(void) { return YES; }
+BOOL SGPlayerPitchFollowsSpeed(void) { return sg_follows; }
+void SGSetPlayerPitchFollowsSpeed(BOOL follows) { sg_follows = follows; }
+float SGPlayerReverb(void) { return sg_reverb; }
+void SGPlayerSetReverb(float amount) { sg_reverb = amount; }
+BOOL SGPlayerMenuOffersAnimatedArtwork(void) { return YES; }
+BOOL SGPlayerMenuAnimatedArtwork(void) { return sg_animated; }
+void SGPlayerMenuSetAnimatedArtwork(BOOL on) { sg_animated = on; NSLog(@"[harness] animated artwork %d", on); }
+// The player's state, which the harness does not have: every sheet is of one kind.
+@class SPTPlayerState;
+SPTPlayerState *SGPlayerState(void) { return nil; }
+NSString *SGURIString(id uri) { return nil; }
+// The Kit's, which the harness does not build.
+UIView *SGRPinnedMoreRecentButton(void) { return nil; }
+void SGRAnimate(NSInteger motion, void (^animations)(void), void (^completion)(BOOL finished)) {
+ [UIView animateWithDuration:0.2 animations:animations completion:completion];
+}
+
+// Every action and submenu the menu makes, by its title, so the harness can pick or open one.
+static NSMutableDictionary<NSString *, UIMenuElement *> *sg_elements;
+static IMP sg_actionWithTitle, sg_menuWithTitle;
+static UIAction *recordAction(id self, SEL _cmd, NSString *title, UIImage *image, NSString *identifier, UIActionHandler handler) {
+ UIAction *action = ((UIAction *(*)(id, SEL, NSString *, UIImage *, NSString *, UIActionHandler))sg_actionWithTitle)(self, _cmd, title, image, identifier, handler);
+ if (title) sg_elements[title] = action;
+ return action;
+}
+static UIMenu *recordMenu(id self, SEL _cmd, NSString *title, UIImage *image, NSString *identifier, UIMenuOptions options, NSArray *children) {
+ UIMenu *menu = ((UIMenu *(*)(id, SEL, NSString *, UIImage *, NSString *, UIMenuOptions, NSArray *))sg_menuWithTitle)(self, _cmd, title, image, identifier, options, children);
+ if (title.length) sg_elements[title] = menu;
+ return menu;
+}
+
+#pragma mark - Spotify's sheet
+
+static NSArray<NSArray<NSString *> *> *spotifyRows(void) {
+ // A podcast's sheet, with no Add to playlist.
+ if (is(@"podcast")) return @[@[@"text.badge.plus", @"Add to queue"], @[@"square.stack", @"Go to show"], @[@"square.and.arrow.up", @"Share"]];
+ return @[@[@"plus.circle", @"Add to playlist"], @[@"text.badge.plus", @"Add to queue"], @[@"square.stack", @"Go to album"],
+ @[@"square.and.arrow.up", @"Share"], @[@"quote.bubble", @"Lyrics"]];
+}
+
+static NSString *sg_selected;
+
+// A row of the mod's own in the sheet's header, as Redesigned/Playlist/PlaylistMenu.x puts Sort there.
+@interface SGHarnessSortRow : UIControl
+@end
+@implementation SGHarnessSortRow
+- (instancetype)initWithFrame:(CGRect)frame {
+ if (!(self = [super initWithFrame:frame])) return nil;
+ UIImageView *glyph = [[UIImageView alloc] initWithImage:[UIImage systemImageNamed:@"arrow.up.arrow.down"]];
+ glyph.frame = CGRectMake(16, 16, 24, 24);
+ [self addSubview:glyph];
+ self.accessibilityLabel = @"Sort";
+ [self addTarget:self action:@selector(fired) forControlEvents:UIControlEventTouchUpInside];
+ return self;
+}
+// As the playlist's row does: the sheet goes first, then Spotify's own Sort is fired.
+- (void)fired {
+ UIViewController *sheet = nil;
+ for (UIResponder *responder = self; responder && !sheet; responder = responder.nextResponder) {
+ if ([responder isKindOfClass:UINavigationController.class]) sheet = (UIViewController *)responder;
+ }
+ [sheet.presentingViewController dismissViewControllerAnimated:YES completion:^{ NSLog(@"[harness] sort fired"); }];
+}
+@end
+
+@interface _TtC24ContextMenu_InternalImpl25ContextMenuViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
+@property (nonatomic, strong) UITableView *table;
+@property (nonatomic) BOOL loaded;
+@end
+
+@implementation _TtC24ContextMenu_InternalImpl25ContextMenuViewController
+
+- (void)viewDidLoad {
+ [super viewDidLoad];
+ self.view.backgroundColor = [UIColor colorWithWhite:0.07 alpha:1];
+ self.loaded = !rowsLate();
+ self.table = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
+ self.table.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
+ self.table.rowHeight = 56;
+ self.table.dataSource = self;
+ self.table.delegate = self;
+ [self.table registerClass:UITableViewCell.class forCellReuseIdentifier:@"row"];
+ if (is(@"sort")) {
+ UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 56)];
+ SGHarnessSortRow *sort = [[SGHarnessSortRow alloc] initWithFrame:header.bounds];
+ sort.autoresizingMask = UIViewAutoresizingFlexibleWidth;
+ [header addSubview:sort];
+ self.table.tableHeaderView = header;
+ }
+ [self.view addSubview:self.table];
+}
+
+// What Spotify does once its item factories are done.
+- (void)giveRows {
+ self.loaded = YES;
+ [self.table reloadData];
+ NSLog(@"[harness] the sheet has its rows");
+}
+
+- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
+ return self.loaded ? spotifyRows().count : 0;
+}
+
+- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
+ UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"row" forIndexPath:indexPath];
+ UIListContentConfiguration *content = cell.defaultContentConfiguration;
+ NSString *title = spotifyRows()[indexPath.row][1];
+ content.text = title;
+ content.image = [UIImage systemImageNamed:spotifyRows()[indexPath.row][0]];
+ // Lyrics greyed out, as for a track no source has them for.
+ content.textProperties.color = [title isEqualToString:@"Lyrics"] ? [UIColor colorWithWhite:1 alpha:0.3] : UIColor.whiteColor;
+ cell.contentConfiguration = content;
+ return cell;
+}
+
+- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
+ return ![spotifyRows()[indexPath.row][1] isEqualToString:@"Lyrics"];
+}
+
+// Share opens a page of its own inside the sheet; every other row does its thing and closes the sheet.
+- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
+ NSString *row = spotifyRows()[indexPath.row][1];
+ sg_selected = row;
+ NSLog(@"[harness] selected %@", row);
+ if ([row isEqualToString:@"Share"]) {
+ UIViewController *page = [UIViewController new];
+ page.view.backgroundColor = UIColor.darkGrayColor;
+ [self.navigationController pushViewController:page animated:YES];
+ return;
+ }
+ [self.navigationController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
+}
+
+@end
+
+#pragma mark - the player
+
+@interface SGHarnessPlayer : UIViewController
+@property (nonatomic, strong) UIButton *more;
+@property (nonatomic, weak) UINavigationController *sheet;
+@end
+
+@implementation SGHarnessPlayer
+
+- (void)viewDidLoad {
+ [super viewDidLoad];
+ self.view.backgroundColor = [UIColor colorWithRed:0.25 green:0.1 blue:0.2 alpha:1];
+ self.more = [UIButton buttonWithType:UIButtonTypeSystem];
+ [self.more setImage:[UIImage systemImageNamed:@"ellipsis"] forState:UIControlStateNormal];
+ self.more.frame = CGRectMake(330, 70, 48, 48);
+ self.more.accessibilityIdentifier = @"Context menu";
+ [self.more addTarget:self action:@selector(moreTapped) forControlEvents:UIControlEventTouchUpInside];
+ [self.view addSubview:self.more];
+ SGRPlayerMenuWatch(self.more);
+}
+
+// What Spotify's ⋯ does: build its sheet and present it, animated.
+- (void)moreTapped {
+ UINavigationController *sheet = [[UINavigationController alloc] initWithRootViewController:[_TtC24ContextMenu_InternalImpl25ContextMenuViewController new]];
+ self.sheet = sheet;
+ [self presentViewController:sheet animated:YES completion:nil];
+}
+
+- (void)tapMore {
+ [self.more sendActionsForControlEvents:UIControlEventTouchDown];
+ [self.more sendActionsForControlEvents:UIControlEventTouchUpInside];
+}
+
+- (_TtC24ContextMenu_InternalImpl25ContextMenuViewController *)mockSheet {
+ return (id)self.sheet.viewControllers.firstObject;
+}
+
+- (UIButton *)anchor {
+ for (UIView *view in self.more.subviews) if ([NSStringFromClass(view.class) isEqualToString:@"SGRMenuAnchor"]) return (UIButton *)view;
+ return nil;
+}
+
+static UIView *menuView(UIView *root) {
+ if ([NSStringFromClass(root.class) isEqualToString:@"_UIContextMenuView"]) return root;
+ for (UIView *child in root.subviews) {
+ UIView *found = menuView(child);
+ if (found) return found;
+ }
+ return nil;
+}
+
+static UIView *openMenu(void) {
+ for (UIWindowScene *scene in UIApplication.sharedApplication.connectedScenes) {
+ for (UIWindow *window in scene.windows) {
+ UIView *found = menuView(window);
+ if (found) return found;
+ }
+ }
+ return nil;
+}
+
+// Whether a label in the open menu reads exactly `title` (case and all, so Spotify's "Add to queue" and the
+// quick "Add to Queue" are told apart).
+static BOOL menuShows(NSString *title) {
+ __block BOOL found = NO;
+ UIView *menu = openMenu();
+ void (^walk)(UIView *);
+ __block __weak void (^weakWalk)(UIView *);
+ weakWalk = walk = ^(UIView *view) {
+ if ([view isKindOfClass:UILabel.class] && !view.hidden && view.window && [((UILabel *)view).text isEqualToString:title]) found = YES;
+ for (UIView *child in view.subviews) weakWalk(child);
+ };
+ if (menu) walk(menu);
+ return found;
+}
+
+static BOOL menuShowsAll(NSArray<NSString *> *titles) {
+ for (NSString *title in titles) if (!menuShows(title)) return NO;
+ return YES;
+}
+
+static BOOL menuShowsAny(NSArray<NSString *> *titles) {
+ for (NSString *title in titles) if (menuShows(title)) return YES;
+ return NO;
+}
+
+// Picks an action, or opens a submenu.
+static void pick(NSString *title) {
+ UIView *menu = openMenu();
+ UIMenuElement *element = sg_elements[title];
+ NSLog(@"[harness] picking %@ (%@)", title, element ? @"made" : @"never made");
+ if (menu && element) ((void (*)(id, SEL, id))objc_msgSend)(menu, NSSelectorFromString(@"_handleSelectionForElement:"), element);
+}
+
+- (CGFloat)sheetAlpha {
+ UIView *container = self.sheet.presentationController.containerView;
+ return container ? container.alpha : -1;
+}
+
+- (void)viewDidAppear:(BOOL)animated {
+ [super viewDidAppear:animated];
+ static BOOL started;
+ if (started) return;
+ started = YES;
+ NSString *run = scenario();
+ after(1, ^{ [self tapMore]; });
+ // The simulator takes a second or more over the first sheet it presents, so what follows is timed from
+ // the presentation's end (the sheet's view in a window) rather than from the tap.
+ [self whenSheetUp:^{ [self runScenario:run]; }];
+}
+
+- (void)whenSheetUp:(dispatch_block_t)then {
+ __block int tries = 0;
+ __block __weak void (^weakPoll)(void);
+ void (^poll)(void) = ^{
+ if (self.sheet.viewIfLoaded.window && !self.sheet.isBeingPresented) {
+ after(0.4, then);
+ return;
+ }
+ if (++tries > 100) {
+ check(NO, @"Spotify's sheet came up within 10 s");
+ exit(0);
+ }
+ after(0.1, weakPoll);
+ };
+ weakPoll = poll;
+ after(1.1, poll);
+}
+
+static NSArray<NSString *> *quickTitles(void) {
+ return @[@"Share", @"Add to Playlist", @"Add to Queue"];
+}
+
+- (void)runScenario:(NSString *)run {
+ void (^finish)(void) = ^{
+ NSLog(@"[harness] done");
+ exit(0);
+ };
+ check(self.sheet.presentingViewController == self, @"Spotify's sheet is presented");
+ if ([run isEqualToString:@"fallback"]) {
+ check(self.sheetAlpha == 1, [NSString stringWithFormat:@"with no way to open the menu the sheet shows at once (container alpha %.2f)", self.sheetAlpha]);
+ check(!openMenu(), @"no menu came up");
+ check(!self.anchor.userInteractionEnabled, @"the anchor takes no touches");
+ after(1.2, finish);
+ return;
+ }
+ check(self.sheetAlpha == 0, [NSString stringWithFormat:@"the sheet is hidden (container alpha %.2f)", self.sheetAlpha]);
+ check(openMenu() != nil, @"the system menu is up");
+ check(self.anchor.userInteractionEnabled, @"the anchor takes touches while its menu is up");
+ if (rowsLate()) check(openMenu() && !self.mockSheet.loaded, @"the menu came up before the sheet had its rows");
+ check(menuShowsAll(@[@"Speed, Pitch & Reverb", @"Show Animated Artwork", @"More"]), @"the player's own items and More are in it");
+ check(menuShowsAll(quickTitles()), @"the quick row has Share, Add to Playlist and Add to Queue");
+ check(!menuShowsAny(@[@"Go to album", @"Go to show", @"Playback Speed", @"Lyrics"]), @"Spotify's other rows and the speed steps are not at the top level");
+
+ // Held open for a screenshot.
+ if ([run isEqualToString:@"show"]) return;
+ if ([run isEqualToString:@"showmore"] || [run isEqualToString:@"showsound"]) {
+ after(0.4, ^{ pick([run isEqualToString:@"showmore"] ? @"More" : @"Speed, Pitch & Reverb"); });
+ return;
+ }
+
+ // The simulator takes up to a second or two over the menu's own dismissal, so the checks after a pick
+ // wait for what they look for, up to a limit, and report what they then find.
+ BOOL (^gone)(void) = ^BOOL { return !openMenu() && !self.sheet; };
+ void (^pickAndGo)(NSString *, NSString *) = ^(NSString *title, NSString *selected) {
+ pick(title);
+ waitFor(gone, 5, ^{
+ check(!self.sheet, @"the sheet went with the row's action");
+ check(!self.anchor.userInteractionEnabled, @"the anchor gave its touches back");
+ if (selected) check([sg_selected isEqualToString:selected], [NSString stringWithFormat:@"Spotify's %@ was selected (%@)", selected, sg_selected]);
+ finish();
+ });
+ };
+
+ if ([run isEqualToString:@"rows"] || [run isEqualToString:@"sort"]) {
+ after(0.4, ^{
+ pick(@"More");
+ waitFor(^BOOL { return menuShows(@"Go to album"); }, 3, ^{
+ check(menuShowsAll(@[@"Go to album", @"Lyrics"]), @"More holds the rest of Spotify's rows");
+ check(!menuShowsAny(@[@"Add to playlist", @"Add to queue"]), @"More leaves out the rows the quick row has");
+ UIMenuElement *lyrics = sg_elements[@"Lyrics"];
+ check([lyrics isKindOfClass:UIAction.class] && (((UIAction *)lyrics).attributes & UIMenuElementAttributesDisabled), @"the row Spotify greys out is disabled");
+ if ([run isEqualToString:@"sort"]) check(menuShows(@"Sort"), @"the mod's row in the sheet's header is in More");
+ after(0.4, ^{
+ if ([run isEqualToString:@"sort"]) {
+ pick(@"Sort");
+ waitFor(gone, 5, ^{
+ check(!self.sheet, @"the sheet went with Sort's action");
+ finish();
+ });
+ return;
+ }
+ pickAndGo(@"Go to album", @"Go to album");
+ });
+ });
+ });
+ return;
+ }
+ if ([run isEqualToString:@"loading"]) {
+ after(0.4, ^{
+ pick(@"More");
+ after(0.6, ^{
+ check(openMenu() && !menuShows(@"Go to album"), @"More has no rows before the sheet has them");
+ [self.mockSheet giveRows];
+ waitFor(^BOOL { return menuShows(@"Go to album"); }, 5, ^{
+ check(openMenu() != nil, @"the menu waited for the rows, still up");
+ check(menuShows(@"Go to album"), @"Spotify's rows came into the open More");
+ after(0.4, ^{ pickAndGo(@"Go to album", @"Go to album"); });
+ });
+ });
+ });
+ return;
+ }
+ if ([run isEqualToString:@"quick"] || [run isEqualToString:@"quicklate"]) {
+ BOOL late = [run isEqualToString:@"quicklate"];
+ after(0.4, ^{
+ pick(late ? @"Add to Playlist" : @"Add to Queue");
+ waitFor(^BOOL { return !openMenu(); }, 5, ^{
+ check(!openMenu(), @"the menu closed on the pick");
+ check(self.sheet.presentingViewController && self.sheetAlpha == 0, @"the sheet stays hidden while the pick waits for its row");
+ if (!late) {
+ // The rows come only after the menu has gone, so the pick has to wait for them.
+ after(1, ^{
+ [self.mockSheet giveRows];
+ waitFor(gone, 5, ^{
+ check(!self.sheet, @"the sheet went with the row's action");
+ check([sg_selected isEqualToString:@"Add to queue"], [NSString stringWithFormat:@"the late row Add to queue was selected (%@)", sg_selected]);
+ check(!self.anchor.userInteractionEnabled, @"the anchor gave its touches back");
+ finish();
+ });
+ });
+ return;
+ }
+ waitFor(^BOOL { return self.sheetAlpha == 1; }, 4, ^{
+ check(self.sheet.presentingViewController && self.sheetAlpha == 1, [NSString stringWithFormat:@"with no rows in 2 s Spotify's sheet is shown (container alpha %.2f)", self.sheetAlpha]);
+ check(!sg_selected, @"nothing was selected");
+ finish();
+ });
+ });
+ });
+ return;
+ }
+ if ([run isEqualToString:@"podcast"]) {
+ after(0.4, ^{
+ [self.mockSheet giveRows];
+ waitFor(^BOOL { return !menuShows(@"Add to Playlist"); }, 3, ^{
+ check(!menuShows(@"Add to Playlist"), @"once the rows are in, the quick item this sheet has no row for is gone");
+ check(menuShowsAll(@[@"Share", @"Add to Queue", @"More"]), @"the other quick items and More are still there");
+ pick(@"More");
+ waitFor(^BOOL { return menuShows(@"Go to show"); }, 3, ^{
+ check(menuShows(@"Go to show") && !menuShowsAny(@[@"Add to queue"]), @"More holds the podcast's other rows");
+ after(0.4, ^{ pickAndGo(@"Go to show", @"Go to show"); });
+ });
+ });
+ });
+ return;
+ }
+ if ([run isEqualToString:@"close"]) {
+ after(0.4, ^{
+ [self.anchor.contextMenuInteraction dismissMenu];
+ waitFor(gone, 5, ^{
+ check(!self.sheet, @"closing the menu with no pick dismissed the sheet");
+ check(!self.anchor.userInteractionEnabled, @"the anchor gave its touches back");
+ [self tapMore];
+ waitFor(^BOOL { return openMenu() && self.sheet && !self.sheet.isBeingPresented; }, 5, ^{
+ check(openMenu() != nil && self.sheetAlpha == 0, @"a second tap opens the menu again over a hidden sheet");
+ finish();
+ });
+ });
+ });
+ return;
+ }
+ if ([run isEqualToString:@"subpage"]) {
+ after(0.4, ^{
+ pick(@"Share");
+ waitFor(^BOOL { return !openMenu() && self.sheetAlpha == 1; }, 5, ^{
+ check(!openMenu(), @"the menu closed on the pick");
+ check(!self.anchor.userInteractionEnabled, @"the anchor gave its touches back");
+ check([sg_selected isEqualToString:@"Share"], @"the quick Share selected Spotify's Share");
+ check(self.sheet.presentingViewController && self.sheetAlpha == 1, [NSString stringWithFormat:@"a row that keeps the sheet up shows it (container alpha %.2f)", self.sheetAlpha]);
+ finish();
+ });
+ });
+ return;
+ }
+ if ([run isEqualToString:@"animated"]) {
+ after(0.4, ^{
+ pick(@"Show Animated Artwork");
+ waitFor(gone, 5, ^{
+ check(!openMenu(), @"the menu closed on the pick");
+ check(sg_animated, @"Show Animated Artwork switched it on");
+ check(!self.sheet, @"the sheet went with the menu");
+ finish();
+ });
+ });
+ return;
+ }
+ check(NO, [NSString stringWithFormat:@"no scenario %@", run]);
+ finish();
+}
+
+@end
+
+@interface SGHarnessApp : UIResponder <UIApplicationDelegate>
+@property (nonatomic, strong) UIWindow *window;
+@end
+
+@implementation SGHarnessApp
+- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)options {
+ self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
+ self.window.rootViewController = [SGHarnessPlayer new];
+ [self.window makeKeyAndVisible];
+ return YES;
+}
+@end
+
+static void nothing(id self, SEL _cmd) {}
+static void nothingAt(id self, SEL _cmd, CGPoint location) {}
+
+// Before every %ctor, so the redesign's gate reads on.
+__attribute__((constructor(101))) static void sgr_harnessDefaults(void) {
+ [NSUserDefaults.standardUserDefaults setBool:YES forKey:@"spotifyglass.redesign"];
+ sg_elements = [NSMutableDictionary dictionary];
+ Method make = class_getClassMethod(UIAction.class, @selector(actionWithTitle:image:identifier:handler:));
+ sg_actionWithTitle = method_setImplementation(make, (IMP)recordAction);
+ Method menu = class_getClassMethod(UIMenu.class, @selector(menuWithTitle:image:identifier:options:children:));
+ sg_menuWithTitle = method_setImplementation(menu, (IMP)recordMenu);
+ // An OS where neither way of opening a button's menu from code does anything.
+ if (is(@"fallback")) {
+ class_replaceMethod(UIButton.class, NSSelectorFromString(@"performPrimaryAction"), (IMP)nothing, "v@:");
+ class_replaceMethod(UIContextMenuInteraction.class, NSSelectorFromString(@"_presentMenuAtLocation:"), (IMP)nothingAt, "v@:{CGPoint=dd}");
+ }
+}
+
+int main(int argc, char *argv[]) {
+ @autoreleasepool {
+ return UIApplicationMain(argc, argv, nil, NSStringFromClass(SGHarnessApp.class));
+ }
+}
diff --git a/tweak/Sources/Redesigned/ContextMenu/ContextMenu.h b/tweak/Sources/Redesigned/ContextMenu/ContextMenu.h
new file mode 100644
index 00000000..33092964
--- /dev/null
+++ b/tweak/Sources/Redesigned/ContextMenu/ContextMenu.h
@@ -0,0 +1,41 @@
+// The redesign's ⋯ opens the system menu instead of Spotify's sheet, the way the Music app's does: the
+// player's ⋯ and the ⋯ every redesigned entity page pins to its corner (playlist, album, artist and the
+// pages that share their templates). Always on in the redesign; no setting.
+//
+// ContextMenu.x the takeover: Spotify's sheet presented unseen, its rows read into a UIMenu shown from
+// the ⋯, a pick fired on the sheet, and the sheet itself as the fallback
+//
+// Spotify's rows come from Swift item factories with nothing to read them from but the cells they fill, so
+// the sheet is still Spotify's and still made: it is presented without animation inside a container at alpha
+// 0, from its first frame (no dark flash), and the menu opens at once over it from an invisible anchor button
+// inside the ⋯. On a page's ⋯, Spotify's rows are a deferred element of the menu, which shows the system's
+// loading row until the sheet has them, however long that is. The player's menu waits on nothing: Share, Add
+// to playlist and Add to queue, found among Spotify's rows by title, are a row of three at its top, then come
+// the player's own items, then More, a submenu holding the rest of Spotify's rows and the only deferred element.
+// A quick item picked before the sheet has its rows waits up to 2 s for them, else the sheet is shown.
+//
+// A pick closes the menu and then selects that row on the sheet, so what it does stays Spotify's; a pick that
+// leaves the sheet up (a row opening a page of its own) shows the sheet. Rows the mod puts in the sheet's
+// header or footer (Sort and Mix on a playlist, Edit info for a local file) are read the same way and fired the
+// same way. Closing the menu without a pick dismisses the sheet.
+//
+// The anchor takes touches only while its menu is up, so every other tap reaches the ⋯ under it, and the menu
+// is opened with -[UIControl performPrimaryAction] (iOS 17.4), else UIContextMenuInteraction's private
+// _presentMenuAtLocation:, each checked with respondsToSelector:. When neither is there, or the menu does not
+// come up, Spotify's sheet shows at once instead, with nothing waited out.
+//
+// Threading: main thread only.
+#import <UIKit/UIKit.h>
+
+// Items of the mod's own for the menu `button` opens, built afresh every time it opens.
+typedef NSArray<UIMenuElement *> *(^SGRMenuItems)(void);
+// What the sheet the ⋯ opens now is for ("track", "episode"...). The menu remembers which quick items the last
+// sheet of each kind had, so the quick row is right before this sheet has its rows.
+typedef NSString *(^SGRMenuKind)(void);
+
+// Marks the next context menu sheet Spotify presents within a few seconds of a touch on `button` as this
+// button's: it is shown as the system menu from `button`. With `items` (the player's ⋯), the menu is the quick
+// row, `items`, then More; with nil it is Spotify's rows alone. `kind` may be nil. Watching the same button
+// again only replaces `items` and `kind`. The pinned ⋯ of the entity pages needs no call: the Kit records its
+// taps (SGRPinnedMoreRecentButton).
+void SGRSystemMenuWatch(UIView *button, SGRMenuItems items, SGRMenuKind kind);
diff --git a/tweak/Sources/Redesigned/ContextMenu/ContextMenu.x b/tweak/Sources/Redesigned/ContextMenu/ContextMenu.x
new file mode 100644
index 00000000..782c0c5f
--- /dev/null
+++ b/tweak/Sources/Redesigned/ContextMenu/ContextMenu.x
@@ -0,0 +1,744 @@
+// The redesign's ⋯ as the system menu (ContextMenu.h says what and why).
+//
+// The sheet is ContextMenu_InternalImpl.ContextMenuViewController, presented on its own or as the root of
+// ContextMenuNativeNavigationController; its rows are a table sized to its content (Shared/Player/
+// SpeedPitchMenu.x and harness/menu say more), each a ContextMenuTableViewCell whose only ivar is the
+// containedView Spotify draws the row in (nm on 9.1.78). So a row is read off the cell it fills -- its words
+// from its labels, its glyph from its image view or else drawn off the small view at its leading edge -- and
+// picked through the table's own delegate, as a tap on it would be.
+//
+// What UIKit does was checked in the simulator against harness/system-menu/ (iOS 27): a presentation's
+// container exists from the presented controller's viewWillAppear: on, not when presentViewController: returns,
+// so that is where the sheet is hidden; a menu asked for while the sheet's presentation is still under way
+// never comes up, so it is asked for from the presentation's completion, and the sheet goes up unanimated for
+// that to be at once; -performPrimaryAction brings the menu up over the hidden sheet and calls
+// willDisplayMenuForConfiguration: before it returns; a pick runs the action's handler before
+// willEndForConfiguration:, so by the end of the menu's dismissal it is known whether there was one; a deferred
+// element in a submenu is asked for its items when that submenu opens, not with the menu, so More's rows are
+// not kept from one menu to the next: by the time More is opened the sheet has nearly always read them.
+#import <objc/message.h>
+#import <objc/runtime.h>
+#import "Core/SGCore.h"
+#import "Redesigned/Kit/SGRKit.h"
+#import "Shared/Player/SpeedPitch.h"
+#import "ContextMenu.h"
+
+// A sheet this soon after a touch on a watched ⋯ is that ⋯'s menu, as SGRPinnedMoreWindow has it for pages.
+static const NSTimeInterval kClaimWindow = 3;
+// After a pick of Spotify's, how long its sheet has to start going before it is taken to have opened a page
+// of its own and is shown.
+static const NSTimeInterval kSettle = 0.5;
+// How often the sheet is asked for its rows until it has them.
+static const NSTimeInterval kRowsPoll = 0.1;
+// How long the menu's dismissal may take before it is taken to be over without having said so.
+static const NSTimeInterval kEndedLimit = 3;
+// How long a quick item picked before the sheet has its rows waits for them before the sheet is shown.
+static const NSTimeInterval kQuickWait = 2;
+
+static NSString *const kSheetClass = @"_TtC24ContextMenu_InternalImpl25ContextMenuViewController";
+static NSString *const kTopMenu = @"com.vitrine.systemmenu.top";
+static NSString *const kQuickMenu = @"com.vitrine.systemmenu.quick";
+
+static char kAnchorKey, kItemsKey, kKindKey, kWatchedKey, kSessionKey;
+
+static __weak UIView *sg_claimButton;
+static NSTimeInterval sg_claimAt;
+
+// The player's quick items: what the item says, its symbol, and the title of Spotify's row it fires, compared
+// without case. Spotify's rows carry no identifier known to be stable (the first read logs what they have), so
+// the title is what is matched; a sheet in another language matches none, and the row is left out.
+static NSArray<NSArray<NSString *> *> *quickItems(void) {
+ return @[@[@"Share", @"square.and.arrow.up", @"share"],
+ @[@"Add to Playlist", @"text.badge.plus", @"add to playlist"],
+ @[@"Add to Queue", @"text.line.last.and.arrowtriangle.forward", @"add to queue"]];
+}
+
+// Which quick items (their rows' titles) the last sheet of each kind had.
+static NSMutableDictionary<NSString *, NSArray<NSString *> *> *sg_quickSeen;
+
+#pragma mark - the sheet
+
+// Spotify's ContextMenuViewController in what was presented: itself, or the root of its navigation controller.
+static UIViewController *sheetIn(UIViewController *presented) {
+ if ([NSStringFromClass(presented.class) isEqualToString:kSheetClass]) return presented;
+ if ([presented isKindOfClass:UINavigationController.class]) {
+ UIViewController *root = ((UINavigationController *)presented).viewControllers.firstObject;
+ if ([NSStringFromClass(root.class) isEqualToString:kSheetClass]) return root;
+ }
+ return nil;
+}
+
+static UITableView *tableIn(UIView *root, int depth) {
+ if ([root isKindOfClass:UITableView.class]) return (UITableView *)root;
+ if (!root || depth > 5) return nil;
+ for (UIView *child in root.subviews) {
+ UITableView *table = tableIn(child, depth + 1);
+ if (table) return table;
+ }
+ return nil;
+}
+
+static NSInteger rowCount(UITableView *table) {
+ NSInteger rows = 0;
+ for (NSInteger section = 0; section < table.numberOfSections; section++) rows += [table numberOfRowsInSection:section];
+ return rows;
+}
+
+static BOOL shows(UIView *view) {
+ return !view.hidden && view.alpha > 0.01;
+}
+
+// The visible labels' words in reading order: the row's title first, a line under it second.
+static NSArray<UILabel *> *labelsIn(UIView *root) {
+ NSMutableArray<UILabel *> *labels = [NSMutableArray array];
+ SGForEachView(root, ^(UIView *view) {
+ if ([view isKindOfClass:UILabel.class] && shows(view) && ((UILabel *)view).text.length) [labels addObject:(UILabel *)view];
+ });
+ [labels sortUsingComparator:^NSComparisonResult(UILabel *a, UILabel *b) {
+ CGRect ra = [a convertRect:a.bounds toView:root], rb = [b convertRect:b.bounds toView:root];
+ if (fabs(CGRectGetMinY(ra) - CGRectGetMinY(rb)) > 4) return CGRectGetMinY(ra) < CGRectGetMinY(rb) ? NSOrderedAscending : NSOrderedDescending;
+ return CGRectGetMinX(ra) < CGRectGetMinX(rb) ? NSOrderedAscending : NSOrderedDescending;
+ }];
+ return labels;
+}
+
+// The first accessibility identifier in the row, for the log.
+static NSString *identifierIn(UIView *root) {
+ __block NSString *found = nil;
+ SGForEachView(root, ^(UIView *view) {
+ if (!found && view.accessibilityIdentifier.length) found = view.accessibilityIdentifier;
+ });
+ return found;
+}
+
+// The row's glyph as a template, for the menu to draw in its own colour: an image view's picture, else the
+// small view at the row's leading edge drawn into one (Encore draws its icons into a view of its own,
+// Redesigned/Playlist/PlaylistMenu.x).
+static UIImage *glyphIn(UIView *root) {
+ __block UIImageView *image = nil;
+ __block UIView *drawn = nil;
+ __block CGFloat drawnX = CGFLOAT_MAX;
+ SGForEachView(root, ^(UIView *view) {
+ if (view == root || !shows(view)) return;
+ CGSize size = view.bounds.size;
+ if (size.width < 12 || size.width > 40 || size.height < 12 || size.height > 40) return;
+ if (!image && [view isKindOfClass:UIImageView.class] && ((UIImageView *)view).image) image = (UIImageView *)view;
+ CGFloat x = [view convertRect:view.bounds toView:root].origin.x;
+ if (![view isKindOfClass:UILabel.class] && !view.subviews.count && x < drawnX) {
+ drawn = view;
+ drawnX = x;
+ }
+ });
+ if (image) return [image.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
+ if (!drawn || drawnX > root.bounds.size.width / 3) return nil;
+ UIImage *picture = [[[UIGraphicsImageRenderer alloc] initWithSize:drawn.bounds.size] imageWithActions:^(UIGraphicsImageRendererContext *context) {
+ [drawn.layer renderInContext:context.CGContext];
+ }];
+ return [picture imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
+}
+
+// Spotify greys a row out (lyrics for a track no source has them for) rather than leaving it out.
+static BOOL rowEnabled(UITableView *table, NSIndexPath *path, UITableViewCell *cell, UILabel *title) {
+ if (!cell.userInteractionEnabled) return NO;
+ id<UITableViewDelegate> delegate = table.delegate;
+ if ([delegate respondsToSelector:@selector(tableView:shouldHighlightRowAtIndexPath:)] && ![delegate tableView:table shouldHighlightRowAtIndexPath:path]) return NO;
+ CGFloat alpha = 1;
+ [title.textColor getRed:NULL green:NULL blue:NULL alpha:&alpha];
+ return title.enabled && title.alpha * alpha >= 0.6;
+}
+
+// Picks the row as a tap would; a row that answers to no delegate is tapped through the first control in it.
+static void selectRow(UITableView *table, NSIndexPath *path) {
+ id<UITableViewDelegate> delegate = table.delegate;
+ if ([delegate respondsToSelector:@selector(tableView:willSelectRowAtIndexPath:)]) path = [delegate tableView:table willSelectRowAtIndexPath:path];
+ if (!path) return;
+ if ([delegate respondsToSelector:@selector(tableView:didSelectRowAtIndexPath:)]) {
+ [table selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
+ [delegate tableView:table didSelectRowAtIndexPath:path];
+ return;
+ }
+ __block UIControl *control = nil;
+ SGForEachView([table cellForRowAtIndexPath:path], ^(UIView *view) {
+ if (!control && [view isKindOfClass:UIControl.class]) control = (UIControl *)view;
+ });
+ SGLog(@"system menu: the sheet's table has no didSelect, the row's %@ is tapped instead", control ? NSStringFromClass(control.class) : @"nothing");
+ [control sendActionsForControlEvents:UIControlEventTouchUpInside];
+}
+
+// The mod's own rows in the table's header or footer view: the view itself or its children, controls of the
+// mod's (SG…) with a label. Spotify's own header (the track it is for) is not one.
+static NSArray<UIControl *> *modRowsIn(UIView *slot) {
+ if (!slot || slot.bounds.size.height < 1) return @[];
+ NSMutableArray<UIControl *> *rows = [NSMutableArray array];
+ for (UIView *view in [slot isKindOfClass:UIControl.class] ? @[slot] : slot.subviews) {
+ if ([view isKindOfClass:UIControl.class] && shows(view) && view.accessibilityLabel.length
+ && [NSStringFromClass(view.class) hasPrefix:@"SG"]) [rows addObject:(UIControl *)view];
+ }
+ return rows;
+}
+
+static UIMenu *inlineGroup(NSArray<UIMenuElement *> *children) {
+ return [UIMenu menuWithTitle:@"" image:nil identifier:nil options:UIMenuOptionsDisplayInline children:children];
+}
+
+#pragma mark - one menu
+
+// One row of the sheet as read: a row of Spotify's table (`path`) or a control of the mod's (`control`).
+@interface SGRSheetRow : NSObject
+@property (nonatomic, strong) NSIndexPath *path;
+@property (nonatomic, weak) UIControl *control;
+@property (nonatomic, copy) NSString *title, *subtitle, *identifier;
+@property (nonatomic, strong) UIImage *image;
+@property (nonatomic) BOOL enabled;
+// The quick item this row is, by its row title in quickItems(); nil for none.
+@property (nonatomic, copy) NSString *quick;
+@end
+@implementation SGRSheetRow
+@end
+
+@class SGRMenuAnchor;
+
+// One ⋯ tap: the sheet Spotify presented, the anchor the menu comes from, and what was picked.
+@interface SGRMenuSession : NSObject
+@property (nonatomic, weak) UIViewController *presented;
+@property (nonatomic, weak) SGRMenuAnchor *anchor;
+@property (nonatomic, copy) SGRMenuItems items;
+@property (nonatomic, copy) NSString *kind;
+@property (nonatomic) BOOL displayed, revealed, ended, opened;
+@property (nonatomic, copy) void (^pick)(void);
+- (void)open;
+- (void)reveal;
+- (void)menuEnded;
+@end
+
+// An invisible button over the ⋯ that only hosts the menu. It takes touches only while the menu is up
+// (UIKit will not present a menu from a view that takes none), so a tap on the ⋯ reaches the ⋯.
+@interface SGRMenuAnchor : UIButton
+@property (nonatomic, strong) SGRMenuSession *session;
+@end
+
+@implementation SGRMenuAnchor
+
+- (void)contextMenuInteraction:(UIContextMenuInteraction *)interaction willDisplayMenuForConfiguration:(UIContextMenuConfiguration *)configuration
+ animator:(id<UIContextMenuInteractionAnimating>)animator {
+ [super contextMenuInteraction:interaction willDisplayMenuForConfiguration:configuration animator:animator];
+ self.session.displayed = YES;
+}
+
+- (void)contextMenuInteraction:(UIContextMenuInteraction *)interaction willEndForConfiguration:(UIContextMenuConfiguration *)configuration
+ animator:(id<UIContextMenuInteractionAnimating>)animator {
+ [super contextMenuInteraction:interaction willEndForConfiguration:configuration animator:animator];
+ SGRMenuSession *session = self.session;
+ self.session = nil;
+ self.userInteractionEnabled = NO;
+ if (!animator) {
+ [session menuEnded];
+ return;
+ }
+ [animator addCompletion:^{ [session menuEnded]; }];
+ // Should the dismissal never report its end, the hidden sheet is not left over the screen taking its touches.
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kEndedLimit * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
+ if (session.ended) return;
+ SGLog(@"system menu: the menu's dismissal did not end within %.0f s, the pick goes ahead", kEndedLimit);
+ [session menuEnded];
+ });
+}
+
+@end
+
+@implementation SGRMenuSession {
+ // The sheet's rows in its groups (the mod's header rows, each section, the mod's footer rows), nil until
+ // the sheet has them; read once.
+ NSArray<NSArray<SGRSheetRow *> *> *_groups;
+ __weak UITableView *_table;
+ // Run once the rows are read: More's items, a quick pick waiting for its row.
+ NSMutableArray<dispatch_block_t> *_whenRead;
+ // A quick pick is waiting for the rows, which keeps the poll going after the menu has gone.
+ BOOL _waiting;
+ // The quick row as the menu shows it, to know whether the rows changed it.
+ NSString *_quickShown;
+ NSTimer *_poll;
+ CFTimeInterval _openedAt;
+}
+
+- (UIViewController *)sheet {
+ return sheetIn(self.presented);
+}
+
+- (void)open {
+ if (self.opened) return;
+ self.opened = YES;
+ SGRMenuAnchor *anchor = self.anchor;
+ if (!anchor.window || !self.presented.presentingViewController) {
+ SGLog(@"system menu: the ⋯ left the screen before its menu could open, Spotify's sheet shown");
+ [self reveal];
+ return;
+ }
+ _openedAt = CACurrentMediaTime();
+ _whenRead = [NSMutableArray array];
+ if (![self readRows]) [self pollRows];
+ anchor.session = self;
+ anchor.menu = [self menu];
+ anchor.userInteractionEnabled = YES;
+ SEL perform = NSSelectorFromString(@"performPrimaryAction");
+ if ([anchor respondsToSelector:perform]) ((void (*)(id, SEL))objc_msgSend)(anchor, perform);
+ if (!self.displayed) {
+ UIContextMenuInteraction *interaction = anchor.contextMenuInteraction;
+ for (id<UIInteraction> each in anchor.interactions) {
+ if (!interaction && [(id)each isKindOfClass:UIContextMenuInteraction.class]) interaction = (UIContextMenuInteraction *)each;
+ }
+ SEL present = NSSelectorFromString(@"_presentMenuAtLocation:");
+ if ([interaction respondsToSelector:present]) {
+ CGPoint middle = CGPointMake(CGRectGetMidX(anchor.bounds), CGRectGetMidY(anchor.bounds));
+ ((void (*)(id, SEL, CGPoint))objc_msgSend)(interaction, present, middle);
+ }
+ }
+ // Both ways answer before they return; one more turn is given for an OS that answers a moment later.
+ dispatch_async(dispatch_get_main_queue(), ^{
+ if (self.displayed || self.ended) return;
+ SGLog(@"system menu: the menu did not come up, Spotify's sheet shown");
+ anchor.userInteractionEnabled = NO;
+ anchor.session = nil;
+ [self reveal];
+ });
+}
+
+#pragma mark the menu
+
+// A page's ⋯: Spotify's rows, waited for. The player's: the quick row, the player's items and More, none of
+// them waited for; More's rows are, when More is opened before the sheet has them.
+- (UIMenu *)menu {
+ if (!self.items) return [UIMenu menuWithChildren:@[[self deferredRows]]];
+ NSMutableArray<UIMenuElement *> *children = [NSMutableArray array];
+ UIMenu *quick = [self quickRow];
+ if (quick) [children addObject:quick];
+ NSArray<UIMenuElement *> *ours = self.items();
+ if (ours.count) [children addObject:inlineGroup(ours)];
+ UIMenu *more = [UIMenu menuWithTitle:@"More" image:[UIImage systemImageNamed:@"ellipsis.circle"] identifier:nil options:0 children:@[[self deferredRows]]];
+ [children addObject:inlineGroup(@[more])];
+ return [UIMenu menuWithTitle:@"" image:nil identifier:kTopMenu options:0 children:children];
+}
+
+// The sheet's rows as menu items, but for the quick ones. Uncached: every menu reads the sheet it was opened with.
+- (UIDeferredMenuElement *)deferredRows {
+ __weak SGRMenuSession *weakSelf = self;
+ return [UIDeferredMenuElement elementWithUncachedProvider:^(void (^completion)(NSArray<UIMenuElement *> *)) {
+ SGRMenuSession *session = weakSelf;
+ if (!session || session->_groups) {
+ completion(session ? [session rowElements] : @[]);
+ return;
+ }
+ SGLog(@"system menu: Spotify's rows asked for %.1f s after the menu opened, before the sheet has them", CACurrentMediaTime() - session->_openedAt);
+ [session->_whenRead addObject:^{ completion([weakSelf rowElements] ?: @[]); }];
+ }];
+}
+
+- (NSArray<UIMenuElement *> *)rowElements {
+ NSMutableArray<UIMenuElement *> *groups = [NSMutableArray array];
+ for (NSArray<SGRSheetRow *> *group in _groups) {
+ NSMutableArray<UIMenuElement *> *actions = [NSMutableArray array];
+ for (SGRSheetRow *row in group) {
+ if (!row.quick) [actions addObject:[self actionFor:row]];
+ }
+ if (actions.count) [groups addObject:inlineGroup(actions)];
+ }
+ return groups;
+}
+
+- (UIAction *)actionFor:(SGRSheetRow *)row {
+ __weak SGRMenuSession *weakSelf = self;
+ UIAction *action = [UIAction actionWithTitle:row.title image:row.image identifier:nil handler:^(UIAction *picked) {
+ weakSelf.pick = ^{ [weakSelf fire:row]; };
+ }];
+ action.subtitle = row.subtitle;
+ if (!row.enabled) action.attributes = UIMenuElementAttributesDisabled;
+ return action;
+}
+
+- (SGRSheetRow *)rowForQuick:(NSString *)quick {
+ for (NSArray<SGRSheetRow *> *group in _groups) {
+ for (SGRSheetRow *row in group) if ([row.quick isEqualToString:quick]) return row;
+ }
+ return nil;
+}
+
+// Share, Add to playlist and Add to queue as a row of three, those this sheet has: once it has its rows, the
+// ones found in them; before, the ones the last sheet of this kind had, or all three.
+- (UIMenu *)quickRow {
+ NSArray<NSString *> *seen = sg_quickSeen[self.kind ?: @""];
+ NSMutableArray<UIMenuElement *> *actions = [NSMutableArray array];
+ NSMutableString *shown = [NSMutableString string];
+ __weak SGRMenuSession *weakSelf = self;
+ for (NSArray<NSString *> *item in quickItems()) {
+ NSString *quick = item[2];
+ SGRSheetRow *row = [self rowForQuick:quick];
+ if (_groups ? !row : (seen && ![seen containsObject:quick])) continue;
+ UIAction *action = [UIAction actionWithTitle:item[0] image:[UIImage systemImageNamed:item[1]] identifier:nil handler:^(UIAction *picked) {
+ weakSelf.pick = ^{ [weakSelf fireQuick:quick]; };
+ }];
+ if (row && !row.enabled) action.attributes = UIMenuElementAttributesDisabled;
+ [actions addObject:action];
+ [shown appendFormat:@"%@%@; ", quick, row && !row.enabled ? @" (greyed out)" : @""];
+ }
+ _quickShown = shown;
+ if (!actions.count) return nil;
+ UIMenu *row = [UIMenu menuWithTitle:@"" image:nil identifier:kQuickMenu options:UIMenuOptionsDisplayInline children:actions];
+ // Medium, a symbol over a short label: the HIG keeps small, symbols alone, for actions as closely related
+ // as Bold and Italic, and gives medium to three important ones, which these are.
+ row.preferredElementSize = UIMenuElementSizeMedium;
+ return row;
+}
+
+// The rows came in while the menu is up: the quick row is put right if they changed it.
+- (void)refreshQuickRow {
+ if (!self.items || !self.displayed || self.ended) return;
+ NSString *before = _quickShown;
+ UIMenu *quick = [self quickRow];
+ if ([before isEqualToString:_quickShown]) return;
+ SGLog(@"system menu: the quick row is now %@(was %@)", _quickShown.length ? _quickShown : @"empty ", before.length ? before : @"empty");
+ [self.anchor.contextMenuInteraction updateVisibleMenuWithBlock:^UIMenu *(UIMenu *visible) {
+ // Only the top level, never a submenu that happens to be showing.
+ if (![visible.identifier isEqualToString:kTopMenu]) return visible;
+ NSMutableArray<UIMenuElement *> *children = [visible.children mutableCopy];
+ NSUInteger at = [children indexOfObjectPassingTest:^BOOL(UIMenuElement *child, NSUInteger index, BOOL *stop) {
+ return [child isKindOfClass:UIMenu.class] && [((UIMenu *)child).identifier isEqualToString:kQuickMenu];
+ }];
+ if (at != NSNotFound && quick) children[at] = quick;
+ else if (at != NSNotFound) [children removeObjectAtIndex:at];
+ else if (quick) [children insertObject:quick atIndex:0];
+ return [visible menuByReplacingChildren:children];
+ }];
+}
+
+#pragma mark the rows
+
+- (void)pollRows {
+ if (_poll) return;
+ __weak SGRMenuSession *weakSelf = self;
+ // In the common modes, so a scroll through the menu does not hold the rows back.
+ _poll = [NSTimer timerWithTimeInterval:kRowsPoll repeats:YES block:^(NSTimer *timer) {
+ SGRMenuSession *session = weakSelf;
+ if (!session || (session.ended && !session->_waiting) || [session readRows]) {
+ [timer invalidate];
+ if (session) session->_poll = nil;
+ }
+ }];
+ [NSRunLoop.mainRunLoop addTimer:_poll forMode:NSRunLoopCommonModes];
+}
+
+// Reads the sheet's rows once it has them, and runs what waited for them. Whether they are read.
+- (BOOL)readRows {
+ if (_groups) return YES;
+ UITableView *table = tableIn(self.sheet.viewIfLoaded, 0);
+ if (!table || rowCount(table) == 0) return NO;
+ [table layoutIfNeeded];
+ _table = table;
+ NSMutableArray<NSArray<SGRSheetRow *> *> *groups = [NSMutableArray array];
+ NSArray<SGRSheetRow *> *header = [self modRows:modRowsIn(table.tableHeaderView)];
+ if (header.count) [groups addObject:header];
+ NSUInteger read = 0;
+ for (NSInteger section = 0; section < table.numberOfSections; section++) {
+ NSMutableArray<SGRSheetRow *> *rows = [NSMutableArray array];
+ for (NSInteger index = 0; index < [table numberOfRowsInSection:section]; index++) {
+ SGRSheetRow *row = [self rowAt:[NSIndexPath indexPathForRow:index inSection:section] inTable:table];
+ if (row) [rows addObject:row];
+ }
+ read += rows.count;
+ if (rows.count) [groups addObject:rows];
+ }
+ NSArray<SGRSheetRow *> *footer = [self modRows:modRowsIn(table.tableFooterView)];
+ if (footer.count) [groups addObject:footer];
+ _groups = groups;
+ CFTimeInterval after = CACurrentMediaTime() - _openedAt;
+ SGLog(@"system menu: %lu of Spotify's rows and %lu of the mod's read%@", (unsigned long)read, (unsigned long)(header.count + footer.count),
+ after > 0.5 ? [NSString stringWithFormat:@", %.1f s after the menu opened", after] : @"");
+ if (self.items) [self matchQuick];
+
+ NSArray<dispatch_block_t> *waiting = _whenRead;
+ _whenRead = [NSMutableArray array];
+ for (dispatch_block_t block in waiting) block();
+ [self refreshQuickRow];
+ return YES;
+}
+
+- (SGRSheetRow *)rowAt:(NSIndexPath *)path inTable:(UITableView *)table {
+ UITableViewCell *cell = [table cellForRowAtIndexPath:path];
+ if (!cell && [table.dataSource respondsToSelector:@selector(tableView:cellForRowAtIndexPath:)]) cell = [table.dataSource tableView:table cellForRowAtIndexPath:path];
+ NSArray<UILabel *> *labels = labelsIn(cell);
+ if (!labels.count) return nil;
+ SGRSheetRow *row = [SGRSheetRow new];
+ row.path = path;
+ row.title = labels[0].text;
+ if (labels.count > 1) row.subtitle = labels[1].text;
+ row.image = glyphIn(cell);
+ row.identifier = identifierIn(cell);
+ row.enabled = rowEnabled(table, path, cell, labels[0]);
+ return row;
+}
+
+- (NSArray<SGRSheetRow *> *)modRows:(NSArray<UIControl *> *)controls {
+ NSMutableArray<SGRSheetRow *> *rows = [NSMutableArray array];
+ for (UIControl *control in controls) {
+ SGRSheetRow *row = [SGRSheetRow new];
+ row.control = control;
+ row.title = control.accessibilityLabel;
+ row.image = glyphIn(control);
+ row.enabled = YES;
+ [rows addObject:row];
+ }
+ return rows;
+}
+
+// Marks Spotify's rows that are quick items, remembers which this kind of sheet has, and says so in the log,
+// once a kind.
+- (void)matchQuick {
+ NSString *kind = self.kind ?: @"";
+ NSMutableArray<NSString *> *found = [NSMutableArray array];
+ NSMutableArray<NSString *> *every = [NSMutableArray array];
+ for (NSArray<SGRSheetRow *> *group in _groups) {
+ for (SGRSheetRow *row in group) {
+ if (!row.path) continue;
+ [every addObject:[NSString stringWithFormat:@"%@ (%@)", row.title, row.identifier ?: @"no id"]];
+ NSString *title = [row.title.lowercaseString stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
+ for (NSArray<NSString *> *item in quickItems()) {
+ if (![title isEqualToString:item[2]] || [found containsObject:item[2]]) continue;
+ row.quick = item[2];
+ [found addObject:item[2]];
+ }
+ }
+ }
+ if (!sg_quickSeen) sg_quickSeen = [NSMutableDictionary dictionary];
+ sg_quickSeen[kind] = found;
+ static NSMutableSet<NSString *> *logged;
+ if (!logged) logged = [NSMutableSet set];
+ if ([logged containsObject:kind] || logged.count >= 4) return;
+ [logged addObject:kind];
+ SGLog(@"system menu: the rows of a %@ sheet: %@", kind.length ? kind : @"player", [every componentsJoinedByString:@", "]);
+ SGLog(@"system menu: quick items matched by title: %@", found.count ? [found componentsJoinedByString:@", "] : @"none");
+}
+
+#pragma mark the pick
+
+// A quick item picked: its row fired, after the rows come in if they are not in yet, for up to kQuickWait;
+// with no such row, or none in time, Spotify's sheet is shown, so the pick is never lost.
+- (void)fireQuick:(NSString *)quick {
+ if (_groups) {
+ [self fireQuickNow:quick];
+ return;
+ }
+ SGLog(@"system menu: %@ picked before the sheet had its rows, waiting up to %.0f s", quick, kQuickWait);
+ _waiting = YES;
+ __weak SGRMenuSession *weakSelf = self;
+ [_whenRead addObject:^{ [weakSelf fireQuickNow:quick]; }];
+ [self pollRows];
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kQuickWait * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
+ SGRMenuSession *session = weakSelf;
+ if (!session || !session->_waiting) return;
+ session->_waiting = NO;
+ SGLog(@"system menu: the sheet had no rows %.0f s after %@ was picked, Spotify's sheet shown", kQuickWait, quick);
+ [session reveal];
+ });
+}
+
+- (void)fireQuickNow:(NSString *)quick {
+ _waiting = NO;
+ SGRSheetRow *row = [self rowForQuick:quick];
+ if (row) {
+ [self fire:row];
+ return;
+ }
+ SGLog(@"system menu: this sheet has no %@ row, Spotify's sheet shown", quick);
+ [self reveal];
+}
+
+// A row of the sheet's fired, on the sheet still hidden under where the menu was.
+- (void)fire:(SGRSheetRow *)row {
+ UIViewController *presented = self.presented;
+ if (!presented.presentingViewController || self.revealed) return;
+ if (row.control) {
+ [row.control sendActionsForControlEvents:UIControlEventTouchUpInside];
+ } else {
+ UITableView *table = _table;
+ if (table.window) selectRow(table, row.path);
+ }
+ // A row that opens a page of its own inside the sheet leaves the sheet up: it is shown.
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kSettle * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
+ UIViewController *still = self.presented;
+ if (!still.presentingViewController || still.isBeingDismissed || !still.viewIfLoaded.window) return;
+ SGLog(@"system menu: the row picked left Spotify's sheet up, so it is shown");
+ [self reveal];
+ });
+}
+
+// The menu is gone. A pick is fired now, on the sheet still hidden under it; anything else leaves the sheet
+// nothing to do, so it goes. Done a turn later, once the menu's own presentation is off the sheet.
+- (void)menuEnded {
+ if (self.ended) return;
+ self.ended = YES;
+ void (^pick)(void) = self.pick;
+ self.pick = nil;
+ dispatch_async(dispatch_get_main_queue(), ^{
+ UIViewController *presented = self.presented;
+ if (!presented.presentingViewController || self.revealed) return;
+ if (!pick) {
+ [presented.presentingViewController dismissViewControllerAnimated:NO completion:nil];
+ return;
+ }
+ pick();
+ });
+}
+
+// Spotify's sheet as it would have been: what the menu falls back to, and what a row that opens a page of
+// the sheet's own leads to. Speed and pitch's block comes back into it (SGPlayerMenuReplaced).
+- (void)reveal {
+ if (self.revealed) return;
+ self.revealed = YES;
+ UIView *container = self.presented.presentationController.containerView;
+ SGRAnimate(SGRMotionFade, ^{ container.alpha = 1; }, nil);
+ [self.sheet.viewIfLoaded setNeedsLayout];
+}
+
+@end
+
+static SGRMenuSession *sessionFor(UIViewController *controller) {
+ for (UIViewController *vc = controller; vc; vc = vc.parentViewController) {
+ SGRMenuSession *session = objc_getAssociatedObject(vc, &kSessionKey);
+ if (session) return session;
+ }
+ return nil;
+}
+
+BOOL SGPlayerMenuReplaced(UIViewController *menu) {
+ SGRMenuSession *session = sessionFor(menu);
+ return session && !session.revealed;
+}
+
+#pragma mark - the ⋯
+
+@interface SGRMenuTapWatcher : NSObject <UIGestureRecognizerDelegate>
+@end
+
+@implementation SGRMenuTapWatcher
+// On touch down, not up: Spotify's own action may present the sheet from the same touch before a target
+// added after it has run (Kit/SGRActionRow.m records the pinned ⋯ the same way).
+- (void)pressed:(UIGestureRecognizer *)press {
+ if (press.state != UIGestureRecognizerStateBegan) return;
+ sg_claimButton = press.view;
+ sg_claimAt = CACurrentMediaTime();
+}
+- (void)touchedDown:(UIView *)control {
+ sg_claimButton = control;
+ sg_claimAt = CACurrentMediaTime();
+}
+- (BOOL)gestureRecognizer:(UIGestureRecognizer *)recognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)other {
+ return YES;
+}
+@end
+
+void SGRSystemMenuWatch(UIView *button, SGRMenuItems items, SGRMenuKind kind) {
+ if (!button) return;
+ objc_setAssociatedObject(button, &kItemsKey, items, OBJC_ASSOCIATION_COPY_NONATOMIC);
+ objc_setAssociatedObject(button, &kKindKey, kind, OBJC_ASSOCIATION_COPY_NONATOMIC);
+ if (objc_getAssociatedObject(button, &kWatchedKey)) return;
+ static SGRMenuTapWatcher *watcher;
+ if (!watcher) watcher = [SGRMenuTapWatcher new];
+ objc_setAssociatedObject(button, &kWatchedKey, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ // An Encore button may read its touches through a gesture recognizer rather than as a control, so both
+ // are watched.
+ if ([button isKindOfClass:UIControl.class]) [(UIControl *)button addTarget:watcher action:@selector(touchedDown:) forControlEvents:UIControlEventTouchDown];
+ UILongPressGestureRecognizer *press = [[UILongPressGestureRecognizer alloc] initWithTarget:watcher action:@selector(pressed:)];
+ press.minimumPressDuration = 0;
+ press.cancelsTouchesInView = NO;
+ press.delaysTouchesEnded = NO;
+ press.delegate = watcher;
+ [button addGestureRecognizer:press];
+}
+
+static SGRMenuAnchor *anchorIn(UIView *host) {
+ SGRMenuAnchor *anchor = objc_getAssociatedObject(host, &kAnchorKey);
+ if (!anchor) {
+ anchor = [SGRMenuAnchor buttonWithType:UIButtonTypeCustom];
+ anchor.showsMenuAsPrimaryAction = YES;
+ anchor.userInteractionEnabled = NO;
+ // VoiceOver reaches the ⋯ itself, whose tap brings the menu up the same way.
+ anchor.isAccessibilityElement = NO;
+ anchor.accessibilityElementsHidden = YES;
+ anchor.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;
+ anchor.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
+ objc_setAssociatedObject(host, &kAnchorKey, anchor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ }
+ if (anchor.superview != host) [host addSubview:anchor];
+ anchor.frame = host.bounds;
+ return anchor;
+}
+
+// Whether this sheet is a watched ⋯'s, and if so its session, with the sheet's presentation now the menu's.
+static SGRMenuSession *takeOver(UIViewController *presented) {
+ if (!sheetIn(presented)) return nil;
+ UIView *button = nil;
+ if (sg_claimButton && CACurrentMediaTime() - sg_claimAt <= kClaimWindow) {
+ button = sg_claimButton;
+ sg_claimAt = 0;
+ } else {
+ button = SGRPinnedMoreRecentButton();
+ }
+ if (!button.window) return nil;
+ static BOOL canPresent, checked;
+ if (!checked) {
+ checked = YES;
+ canPresent = [UIControl instancesRespondToSelector:NSSelectorFromString(@"performPrimaryAction")]
+ || [UIContextMenuInteraction instancesRespondToSelector:NSSelectorFromString(@"_presentMenuAtLocation:")];
+ if (!canPresent) SGLog(@"system menu: this iOS has no way to open a button's menu from code, Spotify's sheets stay");
+ }
+ if (!canPresent) return nil;
+ SGRMenuSession *session = [SGRMenuSession new];
+ session.presented = presented;
+ session.anchor = anchorIn(button);
+ session.items = objc_getAssociatedObject(button, &kItemsKey);
+ SGRMenuKind kind = objc_getAssociatedObject(button, &kKindKey);
+ session.kind = kind ? kind() : nil;
+ objc_setAssociatedObject(presented, &kSessionKey, session, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ return session;
+}
+
+%hook UIViewController
+- (void)presentViewController:(UIViewController *)presented animated:(BOOL)animated completion:(void (^)(void))completion {
+ SGRMenuSession *session = takeOver(presented);
+ if (!session) {
+ %orig;
+ return;
+ }
+ %orig(presented, NO, ^{
+ if (completion) completion();
+ [session open];
+ });
+}
+%end
+
+%hook _TtC24ContextMenu_InternalImpl25ContextMenuViewController
+// The first moment the presentation's container exists, before it has drawn a frame: hidden from here, its
+// dimming too, so the screen does not darken under the menu.
+// A sheet Spotify puts up some other way than presentViewController: (the player's ⋯ on a phone) is
+// taken over here instead, from the same claim, and its menu opened once it has appeared.
+- (void)viewWillAppear:(BOOL)animated {
+ %orig;
+ SGRMenuSession *session = sessionFor((UIViewController *)self);
+ if (!session && (session = takeOver((UIViewController *)self))) {
+ static int logged;
+ if (logged++ < 3) SGLog(@"system menu: a ⋯ sheet came up without presentViewController:, taken over as it appears");
+ }
+ if (session && !session.revealed) session.presented.presentationController.containerView.alpha = 0;
+}
+
+- (void)viewDidAppear:(BOOL)animated {
+ %orig;
+ SGRMenuSession *session = sessionFor((UIViewController *)self);
+ if (session && !session.opened) [session open];
+}
+%end
+
+%ctor {
+ if (!SGRedesignedUI()) return;
+ %init;
+ SGRequireClasses(@[kSheetClass]);
+}
diff --git a/tweak/Sources/Redesigned/Kit/SGRActionRow.h b/tweak/Sources/Redesigned/Kit/SGRActionRow.h
index 12a251c9..25380bdc 100644
--- a/tweak/Sources/Redesigned/Kit/SGRActionRow.h
+++ b/tweak/Sources/Redesigned/Kit/SGRActionRow.h
@@ -76,3 +76,6 @@ static const NSTimeInterval SGRPinnedMoreWindow = 3;
// The page whose pinned ⋯ was tapped within that window, or nil: for a screen that puts rows of its own on
// Spotify's context menu sheet and has to know which page the sheet belongs to.
UIView *SGRPinnedMoreRecentPage(void);
+// The pinned ⋯ itself, tapped within that window, or nil: what the redesign's system menu opens from
+// (Redesigned/ContextMenu).
+SGRMirrorButton *SGRPinnedMoreRecentButton(void);
diff --git a/tweak/Sources/Redesigned/Kit/SGRActionRow.m b/tweak/Sources/Redesigned/Kit/SGRActionRow.m
index 7c1e3aa0..d87e466d 100644
--- a/tweak/Sources/Redesigned/Kit/SGRActionRow.m
+++ b/tweak/Sources/Redesigned/Kit/SGRActionRow.m
@@ -424,6 +424,7 @@ static const CGFloat kCornerSide = 16;
// Spotify's ⋯ from the same event, so a sheet Spotify puts up in that same turn would ask which page it
// belonged to before a target added after -sgr_tap had answered.
static __weak UIView *sg_morePage;
+static __weak SGRMirrorButton *sg_moreButton;
static NSTimeInterval sg_moreTappedAt;
static char kRecorderKey;
@@ -432,11 +433,17 @@ UIView *SGRPinnedMoreRecentPage(void) {
return sg_morePage;
}
+SGRMirrorButton *SGRPinnedMoreRecentButton(void) {
+ if (!sg_moreButton || CACurrentMediaTime() - sg_moreTappedAt > SGRPinnedMoreWindow) return nil;
+ return sg_moreButton;
+}
+
@interface SGRPinnedMoreRecorder : NSObject
@end
@implementation SGRPinnedMoreRecorder
- (void)sgr_moreTapped:(SGRMirrorButton *)button {
sg_morePage = button.superview;
+ sg_moreButton = button;
sg_moreTappedAt = CACurrentMediaTime();
}
@end
diff --git a/tweak/Sources/Redesigned/Player/Player.h b/tweak/Sources/Redesigned/Player/Player.h
index 4bdf9f7f..79fec28d 100644
--- a/tweak/Sources/Redesigned/Player/Player.h
+++ b/tweak/Sources/Redesigned/Player/Player.h
@@ -18,9 +18,12 @@
// PlayerGestures.x the gestures' hookup
// PlayerMorph.x the open and close grown out of the now playing bar's card, the cover flown
// PlayerMotion.x Animated artwork: the Canvas or Apple Music's animated cover behind the player
+// PlayerMenu.m the more button's system menu: Spotify's rows, then speed, pitch, reverb and
+// Animated artwork (Redesigned/ContextMenu)
//
// Speed and pitch, once the redesign's own, are Shared/Player/SpeedPitch.h's; PlayerHeader.x still hands
-// the more button over, so a menu opened from it is taken for the player's.
+// the more button over, so a menu opened from it is taken for the player's, and hands it to PlayerMenu.m,
+// which opens it as the system menu.
//
// Every hook installs only while Redesigned UI is on (SGRedesignedUI); the native look's do not then.
// Threading: main thread only.
@@ -92,3 +95,7 @@ BOOL SGRPlayerMotionShowing(void);
// Alpha 0, no touches, hidden from accessibility, set again on every call: for Spotify's Swift views,
// which SGRSuppress cannot keep (PlayerControls.x).
void SGRPlayerVanish(UIView *view);
+
+// The more button's menu opens as the system menu with the player's own items (PlayerMenu.m). Called from
+// PlayerHeader.x with Spotify's more button on every pass; watching it again changes nothing.
+void SGRPlayerMenuWatch(UIView *button);
diff --git a/tweak/Sources/Redesigned/Player/PlayerHeader.x b/tweak/Sources/Redesigned/Player/PlayerHeader.x
index 4596a8f7..ca24a2f7 100644
--- a/tweak/Sources/Redesigned/Player/PlayerHeader.x
+++ b/tweak/Sources/Redesigned/Player/PlayerHeader.x
@@ -39,7 +39,10 @@ static void glassInside(UIViewController *unit, NSArray<NSString *> *identifiers
continue;
}
SGRGlassInside(button, &kGlassKey, SGRGlassCircleSize);
- if ([identifiers[i] isEqualToString:@"Context menu"]) SGPlayerMenuWatchMoreButton(button);
+ if ([identifiers[i] isEqualToString:@"Context menu"]) {
+ SGPlayerMenuWatchMoreButton(button);
+ SGRPlayerMenuWatch(button);
+ }
found++;
}
diff --git a/tweak/Sources/Redesigned/Player/PlayerMenu.m b/tweak/Sources/Redesigned/Player/PlayerMenu.m
new file mode 100644
index 00000000..9c8983c0
--- /dev/null
+++ b/tweak/Sources/Redesigned/Player/PlayerMenu.m
@@ -0,0 +1,141 @@
+// Player redesign: the ⋯ opens the system menu (Redesigned/ContextMenu): Share, Add to playlist and Add to
+// queue in a row at its top, then the player's own items here, then More with the rest of Spotify's rows. The
+// player's items take over what Speed and pitch's block is on Spotify's sheet:
+//
+// Speed, Pitch & Reverb a submenu of three:
+// Playback Speed 0.5× to 2× in the steps Podcasts offers, the current one checked
+// Pitch Pitch Follows Speed, then three semitones down to three up, Original between them
+// Reverb Off and a quarter at a time up to 100%, the audio effects' reverb
+// Show Animated Artwork or Show Fluid Artwork: a button that switches the background between the two,
+// while it is one of them, named for what it switches to
+//
+// Each submenu says what it is set to under its name, so the menu reads as a settings summary without opening
+// anything. A public menu has no sliders, so the steps stand in for them: the sheet's block, with its finer
+// steps, is still what shows when the menu cannot open (ContextMenu.h). What the speed or the pitch is set to
+// outside the steps (from that block) is kept, said under the name, and checked nowhere.
+#import "Core/SGCore.h"
+#import "Redesigned/ContextMenu/ContextMenu.h"
+#import "Shared/Player/PlayerState.h"
+#import "Shared/Player/SpeedPitch.h"
+#import "Player.h"
+
+static const float kSemitonesShown = 3;
+
+static UIImage *symbol(NSString *name) {
+ return [UIImage systemImageNamed:name];
+}
+
+static NSString *speedText(double speed) {
+ NSString *text = [NSString stringWithFormat:@"%.2f", speed];
+ while ([text hasSuffix:@"0"]) text = [text substringToIndex:text.length - 1];
+ if ([text hasSuffix:@"."]) text = [text substringToIndex:text.length - 1];
+ return [text stringByAppendingString:@"×"];
+}
+
+static NSString *semitonesText(float semitones) {
+ if (semitones == 0) return @"Original";
+ return [NSString stringWithFormat:@"%@%.0f %@", semitones > 0 ? @"+" : @"−", fabsf(semitones), fabsf(semitones) == 1 ? @"Semitone" : @"Semitones"];
+}
+
+// While pitch follows a speed that is not normal, the speed sets the pitch and the semitones are not played
+// (SGTimePitch.h), so they stand aside, as on the sheet.
+static BOOL pitchFollowing(void) {
+ return SGPlayerSpeedAllowed() && SGPlayerPitchFollowsSpeed() && SGPlayerSpeed() != 1;
+}
+
+static UIMenu *speedMenu(void) {
+ BOOL allowed = SGPlayerSpeedAllowed();
+ double current = SGPlayerSpeed();
+ NSMutableArray<UIMenuElement *> *choices = [NSMutableArray array];
+ for (NSNumber *step in @[@0.5, @0.75, @1, @1.25, @1.5, @1.75, @2]) {
+ UIAction *choice = [UIAction actionWithTitle:speedText(step.doubleValue) image:nil identifier:nil handler:^(UIAction *action) {
+ SGSetPlayerSpeed(step.doubleValue);
+ }];
+ choice.state = fabs(current - step.doubleValue) < 0.01 ? UIMenuElementStateOn : UIMenuElementStateOff;
+ if (!allowed) choice.attributes = UIMenuElementAttributesDisabled;
+ [choices addObject:choice];
+ }
+ UIMenu *menu = [UIMenu menuWithTitle:@"Playback Speed" image:symbol(@"gauge.with.dots.needle.67percent") identifier:nil options:0 children:choices];
+ menu.subtitle = allowed ? speedText(current) : @"Unavailable";
+ return menu;
+}
+
+static UIMenu *pitchMenu(void) {
+ BOOL available = SGPlayerPitchAvailable(), speedAllowed = SGPlayerSpeedAllowed(), follows = SGPlayerPitchFollowsSpeed();
+ BOOL following = pitchFollowing();
+ float current = SGPlayerPitch();
+
+ UIAction *follow = [UIAction actionWithTitle:@"Pitch Follows Speed" image:nil identifier:nil handler:^(UIAction *action) {
+ SGSetPlayerPitchFollowsSpeed(!follows);
+ }];
+ follow.state = follows ? UIMenuElementStateOn : UIMenuElementStateOff;
+ // Following needs the speed's unit, which the in place fallback does not have.
+ if (!speedAllowed) follow.attributes = UIMenuElementAttributesDisabled;
+
+ NSMutableArray<UIMenuElement *> *steps = [NSMutableArray array];
+ for (float semitones = kSemitonesShown; semitones >= -kSemitonesShown; semitones--) {
+ float chosen = semitones;
+ UIAction *step = [UIAction actionWithTitle:semitonesText(chosen) image:nil identifier:nil handler:^(UIAction *action) {
+ SGSetPlayerPitch(chosen);
+ }];
+ step.state = !following && current == chosen ? UIMenuElementStateOn : UIMenuElementStateOff;
+ if (!available || following) step.attributes = UIMenuElementAttributesDisabled;
+ [steps addObject:step];
+ }
+ UIMenu *menu = [UIMenu menuWithTitle:@"Pitch" image:symbol(@"tuningfork") identifier:nil options:0 children:@[
+ [UIMenu menuWithTitle:@"" image:nil identifier:nil options:UIMenuOptionsDisplayInline children:@[follow]],
+ [UIMenu menuWithTitle:@"" image:nil identifier:nil options:UIMenuOptionsDisplayInline children:steps],
+ ]];
+ menu.subtitle = !available ? @"Unavailable" : following ? @"Follows Speed" : semitonesText(current);
+ return menu;
+}
+
+static UIMenu *reverbMenu(void) {
+ float current = SGPlayerReverb();
+ NSMutableArray<UIMenuElement *> *choices = [NSMutableArray array];
+ for (NSNumber *amount in @[@0, @25, @50, @75, @100]) {
+ UIAction *choice = [UIAction actionWithTitle:amount.floatValue ? [NSString stringWithFormat:@"%@%%", amount] : @"Off" image:nil identifier:nil
+ handler:^(UIAction *action) { SGPlayerSetReverb(amount.floatValue); }];
+ choice.state = current == amount.floatValue ? UIMenuElementStateOn : UIMenuElementStateOff;
+ [choices addObject:choice];
+ }
+ UIMenu *menu = [UIMenu menuWithTitle:@"Reverb" image:symbol(@"building.columns") identifier:nil options:0 children:choices];
+ menu.subtitle = current > 0 ? [NSString stringWithFormat:@"%.0f%%", current] : @"Off";
+ return menu;
+}
+
+// The three under one item, which says what is not as Spotify plays it, or Normal.
+static UIMenu *soundMenu(void) {
+ NSMutableArray<NSString *> *changed = [NSMutableArray array];
+ if (SGPlayerSpeedAllowed() && fabs(SGPlayerSpeed() - 1) >= 0.01) [changed addObject:speedText(SGPlayerSpeed())];
+ if (SGPlayerPitchAvailable() && !pitchFollowing() && SGPlayerPitch() != 0) [changed addObject:semitonesText(SGPlayerPitch())];
+ if (SGPlayerReverb() > 0) [changed addObject:[NSString stringWithFormat:@"Reverb %.0f%%", SGPlayerReverb()]];
+ UIMenu *menu = [UIMenu menuWithTitle:@"Speed, Pitch & Reverb" image:symbol(@"slider.horizontal.3") identifier:nil options:0
+ children:@[speedMenu(), pitchMenu(), reverbMenu()]];
+ menu.subtitle = changed.count ? [changed componentsJoinedByString:@", "] : @"Normal";
+ return menu;
+}
+
+static NSArray<UIMenuElement *> *playerItems(void) {
+ NSMutableArray<UIMenuElement *> *items = [NSMutableArray arrayWithObject:soundMenu()];
+ if (SGPlayerMenuOffersAnimatedArtwork()) {
+ // A button named for what it does, not a checkmark: the HIG's changeable label for a toggled item.
+ BOOL on = SGPlayerMenuAnimatedArtwork();
+ UIAction *animated = [UIAction actionWithTitle:on ? @"Show Fluid Artwork" : @"Show Animated Artwork"
+ image:symbol(on ? @"drop" : @"play.rectangle.on.rectangle") identifier:nil
+ handler:^(UIAction *action) { SGPlayerMenuSetAnimatedArtwork(!on); }];
+ [items addObject:animated];
+ }
+ return items;
+}
+
+// What the player is playing, from its URI (spotify:track:…, spotify:episode:…, spotify:local:…): a podcast's
+// sheet has other rows than a song's.
+static NSString *sheetKind(void) {
+ NSArray<NSString *> *parts = [SGURIString(SGPlayerState().track.URI) componentsSeparatedByString:@":"];
+ return parts.count > 2 ? parts[1] : @"";
+}
+
+void SGRPlayerMenuWatch(UIView *button) {
+ SGRSystemMenuWatch(button, ^NSArray<UIMenuElement *> *{ return playerItems(); }, ^NSString *{ return sheetKind(); });
+}
diff --git a/tweak/Sources/Shared/Player/SpeedPitch.h b/tweak/Sources/Shared/Player/SpeedPitch.h
index 8968e5cf..f862f55d 100644
--- a/tweak/Sources/Shared/Player/SpeedPitch.h
+++ b/tweak/Sources/Shared/Player/SpeedPitch.h
@@ -19,6 +19,10 @@
void SGPlayerMenuWatchMoreButton(UIView *button);
// Whether a context menu sheet is the player's, by the same test; decided once per menu.
BOOL SGPlayerMenuIsPlayers(UIViewController *menu);
+// Whether the sheet is shown as the system menu instead, unseen under it (Redesigned/ContextMenu), whose own
+// items then stand in for the block, which stays out of it. Defined by the redesign; NO under the native look
+// and once the sheet itself is shown.
+BOOL SGPlayerMenuReplaced(UIViewController *menu);
// The speed Spotify's sound plays at, 1 when normal.
double SGPlayerSpeed(void);
// Whether speed can apply: Spotify's output was taken over when it wired it.
@@ -34,6 +38,10 @@ BOOL SGPlayerPitchFollowsSpeed(void);
void SGSetPlayerPitchFollowsSpeed(BOOL follows);
// Whether the output could be reached to change its pitch.
BOOL SGPlayerPitchAvailable(void);
+// The audio effects' reverb as the menu sets it, 0 to 100, 0 while it is off. Any amount turns the effects and
+// the reverb on with it; 0 turns the reverb off and leaves the rest of the effects as they were.
+float SGPlayerReverb(void);
+void SGPlayerSetReverb(float amount);
// The redesign's Animated artwork, switched in the same block: whether the player offers the switch (the
// redesign is running and its background is Fluid or Animated, the two that share a field), whether it is
diff --git a/tweak/Sources/Shared/Player/SpeedPitchMenu.x b/tweak/Sources/Shared/Player/SpeedPitchMenu.x
index e385bc77..25c334a5 100644
--- a/tweak/Sources/Shared/Player/SpeedPitchMenu.x
+++ b/tweak/Sources/Shared/Player/SpeedPitchMenu.x
@@ -24,6 +24,10 @@
//
// Under the redesign, with the player's background Fluid or Animated, a row under the block switches
// Animated artwork (SpeedPitch.h), which the redesign's PlayerMotion.x defines.
+//
+// The redesign shows the player's sheet as the system menu, with speed, pitch, reverb and Animated artwork
+// as items of its own (Redesigned/Player/PlayerMenu.m), so the block stays out of a sheet shown that way
+// and comes in only if the sheet itself is shown after all (SGPlayerMenuReplaced).
#import <CoreText/SFNTLayoutTypes.h>
#import <objc/runtime.h>
#import "Core/SGCore.h"
@@ -299,9 +303,11 @@ static void placeTick(UISlider *slider) {
#pragma mark state
-// The audio effects' reverb, from the menu: any amount turns the effects and the reverb on, none turns the
-// reverb off and leaves the rest of the effects as they were.
-static void setReverb(float amount) {
+float SGPlayerReverb(void) {
+ return SGDSPSwitch(SGKeyDSP) && SGDSPSwitch(SGKeyDSPReverb) ? roundf(SGDSPNumber(SGKeyDSPReverbAmount)) : 0;
+}
+
+void SGPlayerSetReverb(float amount) {
if (amount > 0) {
SGDSPSetNumber(SGKeyDSPReverbAmount, amount);
if (!SGDSPSwitch(SGKeyDSPReverb)) SGDSPSetSwitch(SGKeyDSPReverb, YES);
@@ -330,7 +336,7 @@ static NSString *pitchText(float pitch) {
BOOL speedAllowed = SGPlayerSpeedAllowed(), pitchAvailable = SGPlayerPitchAvailable();
if (!_speed.tracking) _shownSpeed = snappedSpeed(SGPlayerSpeed());
if (!_pitch.tracking) _shownPitch = SGPlayerPitch();
- if (!_reverb.tracking) _shownReverb = SGDSPSwitch(SGKeyDSP) && SGDSPSwitch(SGKeyDSPReverb) ? roundf(SGDSPNumber(SGKeyDSPReverbAmount)) : 0;
+ if (!_reverb.tracking) _shownReverb = SGPlayerReverb();
_reverb.value = _shownReverb;
_speed.value = _shownSpeed;
_pitch.value = _shownPitch;
@@ -446,7 +452,7 @@ static NSString *pitchText(float pitch) {
if (amount == _shownReverb) return;
if (amount == 0 || _shownReverb == 0) SGPlayFeedback(SGFeedbackDetent);
_shownReverb = amount;
- setReverb(amount);
+ SGPlayerSetReverb(amount);
} else {
float pitch = roundf(slider.value);
if (pitch == _shownPitch) return;
@@ -470,7 +476,7 @@ static NSString *pitchText(float pitch) {
- (void)resetReverb {
_shownReverb = 0;
- setReverb(0);
+ SGPlayerSetReverb(0);
[_reverb setValue:0 animated:YES];
[self showValues];
}
@@ -645,6 +651,8 @@ static void watchRows(UIViewController *menu) {
static void install(UIViewController *menu) {
UIView *root = menu.viewIfLoaded;
if (!root || !isPlayerMenu(menu)) return;
+ // Shown as the system menu, whose own items are speed, pitch and reverb.
+ if (SGPlayerMenuReplaced(menu)) return;
UITableView *table = findTable(root, 0);
SGSpeedPitchView *block = objc_getAssociatedObject(menu, &kBlockKey);
if (!table) {