Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.
C
fix: the player's more menu opens on a finger's touch and runs each pick at once
My-Name-Is-Jeffef03e254777f
diff --git a/docs/tweaks.md b/docs/tweaks.mdindex 6623358e..276b442a 100644--- a/docs/tweaks.md+++ b/docs/tweaks.md@@ -370,15 +370,25 @@ Redesigned:(BarConnect.x, its own key and its own row on the Player page, apart from the native look's). In a Jam theglass stays on the track and Spotify's Jam strip gets a pane of its own above it (harness/tabbar/, jam)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/+ always (ContextMenu.h). The player's ⋯ is a pull-down button of the mod's over Spotify's: the menu+ opens on touch down with the quick row (Spotify's items 9, 19 and 11), the player's items and More,+ waiting on nothing of Spotify's (the button holds a stand-in menu from the start, since UIKit opens+ a button's menu on touch down only while it holds one, and the session's replaces it as the touch+ asks); Spotify's ⋯ action is then run from code and its sheet presented+ in a window of the mod's under the app's (the menu, a presentation of UIKit's from the player,+ leaves no room for another there), read, and used to run a pick. More shows the last complete set+ of rows stored for that kind of track (spotifyglass.redesign.player.menuRows.<kind>), or the+ system's loading row the first time, and is put right in place as the live rows come. A page's ⋯+ works the other way round: its tap opens Spotify's sheet, presented unanimated in a container hidden+ from the presented controller's viewWillAppear: on, and 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:). Spotify's rows, read off the sheet's+ cells (words, glyph, greyed out), and the mod's own rows in its header and footer (Sort, Mix, Edit+ info) are fired on the hidden sheet once the menu is gone, through the row's own control (scrolled+ to when it is below the fold); a row that pushes a page shows the sheet on that page, one that+ presents a sheet of its own (Sleep timer) leaves that sheet as Spotify's and the card goes unseen,+ and a close with no pick dismisses the hidden sheet. Checked in the simulator against+ harness/system-menu/Player/ the redesigned full screen player (Player.h lists its files); its more button opens the systemmenu (ContextMenu/), Spotify's rows and then Playback Speed, Pitch (with Pitch follows speed),Reverb and the backgrounds it can switch to (PlayerMenu.m), and a hold on either side of thediff --git a/harness/menu/main.m b/harness/menu/main.mindex c435ffff..01baa1f8 100644--- a/harness/menu/main.m+++ b/harness/menu/main.m@@ -348,6 +348,7 @@ static void tapRow(UIViewController *menu) {BOOL loading = argument(@"loading"), stuck = argument(@"stuck");// Spotify's ⋯ card, put up by a tap on the player's more button: the tap first, as a finger lifting off it.void (^present)(void) = ^{+ [player.header.more sendActionsForControlEvents:UIControlEventTouchDown];[player.header.more sendActionsForControlEvents:UIControlEventTouchUpInside];menu = [_TtC24ContextMenu_InternalImpl25ContextMenuViewController new];UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:menu];diff --git a/harness/system-menu/README.md b/harness/system-menu/README.mdindex 69cf1d04..6ed04a6f 100644--- a/harness/system-menu/README.md+++ b/harness/system-menu/README.md@@ -1,38 +1,58 @@# 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.+Spotify's player ⋯ and its context menu sheet (`ContextMenu_InternalImpl.ContextMenuViewController` under its+class name, inside a navigation controller): 15 rows, each an Encore-style ListRow control whose identifier is+Spotify's item number and which acts on touch up inside, no `didSelect`, Sleep timer last and below the sheet's+fold, as on the phone. Speed, pitch, reverb and Animated artwork are stubs that log.THEOS=$HOME/theos ./build.shxcrun simctl install <udid> build/SystemMenuHarness.appxcrun 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.+The header row is shaped like Spotify's (`trees/clean/player/01.txt`: a 402x48 row, the down arrow 48x48 at x 12+and the ⋯ 48x48 at the trailing edge), each button with a 44pt glass circle first among its subviews taking no+touches, as `PlayerHeader.x` leaves them. The player's ⋯ is the mod's own pull-down button over Spotify's ⋯, and+a tap on it is a finger's touch (`../tabbar/touch.m`), down and up at its middle: UIKit opens the button's menu+on the touch down. (Until 2026-10-06 the harness tapped with `-performPrimaryAction`, which opens a button's menu+whether or not the button holds one yet, and so missed that a finger's touch on the mod's button, holding none+until asked, was taken and opened nothing: the phone's ⋯ did nothing.) Each run taps at 1 s 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.+Every scenario but `timing` first checks the top level: the menu is on screen (within 1 s, the simulator's+first menu of a launch being slow), the mod's ⋯ takes touches, the quick row (Share, Add to Playlist, Add to+Queue), Speed, Pitch & Reverb, Show Animated Artwork and More are in it and none of Spotify's other rows are;+then that Spotify's ⋯ action ran once, from code, after the menu was up, that Speed and pitch was told the+sheet is the player's, and that the sheet is in the mod's window under the app's, unseen, with the menu still up.-- `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.+- `arrow`: the mod's ⋯ sits exactly over Spotify's in the window, above its glass circle and glyph, with the ⋯'s+ label for VoiceOver; a finger on the down arrow runs Spotify's arrow action, reaches nothing of the mod's and+ opens no menu; a finger on the ⋯ then sends the mod's button its touch down and opens the menu, and the press+ (what `PlayerHeader.x`'s circle listens to) holds while the menu is up and is let go as it ends.+- `timing`: ten taps, each closed again; logs the time from the touch down to the menu view in the hierarchy+ (UIKit presents it inside the touch's delivery, so 2 to 4 ms warm), and the median, best and worst of the last+ nine (the first pays for UIKit's menu classes loading).+- `rows`: More holds Go to album, the greyed-out Lyrics and Sleep timer (below the sheet's fold), not the rows+ the quick row has; picking Go to album taps Spotify's row and the sheet goes.+- `loading`: the first menu ever, its rows 1.5 s late: More shows the system's loading row, then the rows come+ into the open More, and Go to album fires.+- `stored`: a first menu reads and stores the rows and is closed with no pick (its sheet goes); a second menu's+ sheet holds its rows back: More shows the stored rows at once, a pick on them waits, and fires once the live+ rows come.+- `quick`: Add to Queue is picked at once; the rows come 1.2 s after the sheet, and the pick waits for them.+- `quicklate`: Add to Playlist is picked and the rows never come: after 4 s Spotify's sheet is shown.+- `podcast`: a sheet with no Add to playlist row: once its rows 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 takes the hidden sheet away within 1 s, and a second tap opens again.+- `subpage`: the quick Share taps Spotify's Share, which pushes a page inside the sheet: the sheet is shown over+ the player, on that page; closed, the mod's window goes back under the app's.+- `sleep`: More's Sleep timer pushes its options page 0.3 s later: the same.+- `sleeppresent`: More's Sleep timer presents a context menu sheet of its own from the player, as on the phone:+ that sheet shows as Spotify's, in the app's window, no menu comes up for it, Spotify's ⋯ action ran once, and+ the card it came from goes unseen.- `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.+- `wrapped`: Spotify presents a controller of its own that puts the sheet in only as it appears+ (NavigationUI_SheetImpl.ContainerViewController on the phone); More and a pick work the same.diff --git a/harness/system-menu/build.sh b/harness/system-menu/build.shindex 80a49d9f..873efb04 100755--- a/harness/system-menu/build.sh+++ b/harness/system-menu/build.sh@@ -10,9 +10,9 @@ rm -rf "$OUT"; mkdir -p "$OUT/gen" "$OUT/SystemMenuHarness.app"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 \+ "$(dirname "$0")/main.m" "$(dirname "$0")/../scene.m" "$(dirname "$0")/../tabbar/touch.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 \+ -framework UIKit -framework IOKit -framework QuartzCore -framework CoreGraphics -framework Foundation \-o "$OUT/SystemMenuHarness.app/SystemMenuHarness"cat > "$OUT/SystemMenuHarness.app/Info.plist" <<'PLIST'diff --git a/harness/system-menu/main.m b/harness/system-menu/main.mindex 13821f85..eb6c70d0 100644--- a/harness/system-menu/main.m+++ b/harness/system-menu/main.m@@ -1,12 +1,15 @@// 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.+// Spotify's player ⋯ and its context menu sheet (its class name, a table of rows that are Encore-style ListRow+// controls and no didSelect, as on the phone), 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+// The ⋯ is the mod's own pull-down button over Spotify's ⋯, and a tap on it is a finger's touch (../tabbar/touch.m),+// down and up, at its middle: UIKit opens the button's menu on the touch down. (Tapped with -performPrimaryAction+// before, the harness missed that a finger's touch on a button holding no menu yet opened nothing, 2026-10-06.)+// 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>@@ -14,6 +17,8 @@#import "Redesigned/ContextMenu/ContextMenu.h"void SGRPlayerMenuWatch(UIView *button);+// touch.m: a finger's touches, through UIKit's own recognizers.+extern void SGHarnessTap(UIWindow *window, CGPoint point);static NSString *scenario(void) {NSArray<NSString *> *arguments = NSProcessInfo.processInfo.arguments;@@ -24,11 +29,6 @@ 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);}@@ -37,13 +37,13 @@ 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.+// Runs `then` once `condition` holds, or after `limit` seconds whether or not it does; looks every 10 ms.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); });+ after(0.01, ^{ waitFor(condition, limit - 0.01, then); });}#pragma mark - what the menu's code calls@@ -51,6 +51,7 @@ static void waitFor(BOOL (^condition)(void), NSTimeInterval limit, dispatch_blocstatic double sg_speed = 1;static float sg_pitch, sg_reverb;static BOOL sg_follows = YES, sg_animated;+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); }@@ -64,11 +65,15 @@ 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.+static NSUInteger sg_marked;+void SGPlayerMenuMarkPlayers(void) { sg_marked++; }+// The player's background (Redesigned/Player/Player.h's SGRPlayerBackgroundKind): Fluid, so the menu offers+// Animated and the Visualiser; Show Animated Artwork switches it on.+NSInteger SGRPlayerBackground(void) { return sg_background; }+void SGRPlayerMenuSetBackground(NSInteger kind) { sg_background = kind; SGPlayerMenuSetAnimatedArtwork(kind == 3); }@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];@@ -90,14 +95,22 @@ static UIMenu *recordMenu(id self, SEL _cmd, NSString *title, UIImage *image, NS#pragma mark - Spotify's sheet+// The rows of 9.1.78's player sheet, with their item numbers; Sleep timer last, below what the sheet shows.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"]];+ if (is(@"podcast")) return @[@[@"text.badge.plus", @"Add to queue", @"11"], @[@"square.stack", @"Go to show", @"40"], @[@"square.and.arrow.up", @"Share", @"9"]];+ NSMutableArray *rows = [@[@[@"plus.circle", @"Add to playlist", @"19"], @[@"text.badge.plus", @"Add to queue", @"11"],+ @[@"square.and.arrow.up", @"Share", @"9"], @[@"square.stack", @"Go to album", @"1"],+ @[@"quote.bubble", @"Lyrics", @"28"]] mutableCopy];+ for (int i = 0; i < 9; i++) [rows addObject:@[@"circle", [NSString stringWithFormat:@"Row %d", i + 1], [NSString stringWithFormat:@"%d", 60 + i]]];+ [rows addObject:@[@"moon", @"Sleep timer", @"44"]];+ return rows;}static NSString *sg_selected;+static NSUInteger sg_spotifyTaps;+// The sheet waits for the harness to give it its rows (sg_rowsAfter seconds after it loads, or never).+static BOOL sg_rowsHeld, sg_rowsNever;+static NSTimeInterval sg_rowsAfter;// A row of the mod's own in the sheet's header, as Redesigned/Playlist/PlaylistMenu.x puts Sort there.@interface SGHarnessSortRow : UIControl@@ -112,19 +125,39 @@ static NSString *sg_selected;[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;}+ sg_selected = @"Sort";[sheet.presentingViewController dismissViewControllerAnimated:YES completion:^{ NSLog(@"[harness] sort fired"); }];}@end-@interface _TtC24ContextMenu_InternalImpl25ContextMenuViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>+// Spotify's row: an Encore ListRow, a control whose identifier is the item number, acting on touch up inside.+@interface SGHarnessListRow : UIControl+@property (nonatomic, copy) NSString *title;+@end+@implementation SGHarnessListRow+@end++@class SGHarnessPlayer;+static SGHarnessPlayer *sg_player;++@interface _TtC24ContextMenu_InternalImpl25ContextMenuViewController : UIViewController <UITableViewDataSource>@property (nonatomic, strong) UITableView *table;-@property (nonatomic) BOOL loaded;+@property (nonatomic) BOOL loaded, sleepOptions;+- (void)giveRows;+@end++@interface SGHarnessPlayer : UIViewController+@property (nonatomic, strong) UIButton *more, *arrow;+@property (nonatomic, strong) UIView *header;+@property (nonatomic) NSUInteger arrowTaps, frontDowns, frontUps, frontCancels;+@property (nonatomic, weak) UINavigationController *sheet;+@property (nonatomic, weak) UIViewController *sleepSheet;+- (void)presentSleepOptions;@end@implementation _TtC24ContextMenu_InternalImpl25ContextMenuViewController@@ -132,12 +165,12 @@ static NSString *sg_selected;- (void)viewDidLoad {[super viewDidLoad];self.view.backgroundColor = [UIColor colorWithWhite:0.07 alpha:1];- self.loaded = !rowsLate();+ self.loaded = self.sleepOptions || !sg_rowsHeld;self.table = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];self.table.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;- self.table.rowHeight = 56;+ self.table.rowHeight = 64;self.table.dataSource = self;- self.table.delegate = self;+ self.table.allowsSelection = NO;[self.table registerClass:UITableViewCell.class forCellReuseIdentifier:@"row"];if (is(@"sort")) {UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 56)];@@ -147,92 +180,95 @@ static NSString *sg_selected;self.table.tableHeaderView = header;}[self.view addSubview:self.table];+ if (!self.loaded && !sg_rowsNever && sg_rowsAfter > 0) {+ __weak typeof(self) weakSelf = self;+ after(sg_rowsAfter, ^{ [weakSelf giveRows]; });+ }}-// What Spotify does once its item factories are done.- (void)giveRows {+ if (self.loaded) return;self.loaded = YES;[self.table reloadData];NSLog(@"[harness] the sheet has its rows");}+- (NSArray<NSArray<NSString *> *> *)rows {+ if (self.sleepOptions) return @[@[@"timer", @"1 minute", @"s1"], @[@"timer", @"5 minutes", @"s5"]];+ return spotifyRows();+}+- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {- return self.loaded ? spotifyRows().count : 0;+ return self.loaded ? self.rows.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]];+ for (UIView *old in cell.contentView.subviews) [old removeFromSuperview];+ NSArray<NSString *> *row = self.rows[indexPath.row];+ SGHarnessListRow *control = [[SGHarnessListRow alloc] initWithFrame:cell.contentView.bounds];+ control.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;+ control.accessibilityIdentifier = row[2];+ control.title = row[1];+ [control addTarget:self action:@selector(rowTapped:) forControlEvents:UIControlEventTouchUpInside];+ UIImageView *glyph = [[UIImageView alloc] initWithImage:[UIImage systemImageNamed:row[0]]];+ glyph.frame = CGRectMake(16, 20, 24, 24);+ glyph.tintColor = UIColor.whiteColor;+ [control addSubview:glyph];+ UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(56, 0, 280, 64)];+ title.text = row[1];// 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;+ title.textColor = [row[1] isEqualToString:@"Lyrics"] ? [UIColor colorWithWhite:1 alpha:0.3] : UIColor.whiteColor;+ [control addSubview:title];+ [cell.contentView addSubview:control];+ cell.backgroundColor = UIColor.clearColor;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];+// Share opens a page of its own inside the sheet; Sleep timer opens its options, inside the sheet 0.3 s later+// (`sleep`) or as a context menu sheet of its own presented from the player (`sleeppresent`); every other row+// does its thing and closes the sheet.+- (void)rowTapped:(SGHarnessListRow *)row {+ sg_selected = row.title;+ NSLog(@"[harness] selected %@", row.title);+ UINavigationController *navigation = self.navigationController;+ if ([row.title isEqualToString:@"Share"] || ([row.title isEqualToString:@"Sleep timer"] && !is(@"sleeppresent"))) {+ after([row.title isEqualToString:@"Share"] ? 0 : 0.3, ^{+ UIViewController *page = [UIViewController new];+ page.title = [row.title stringByAppendingString:@" page"];+ page.view.backgroundColor = UIColor.darkGrayColor;+ [navigation pushViewController:page animated:YES];+ });+ return;+ }+ if ([row.title isEqualToString:@"Sleep timer"]) {+ // As on the phone: the card stays while Spotify presents the timer's own sheet from the player.+ after(0.3, ^{ [sg_player presentSleepOptions]; });return;}- [self.navigationController.presentingViewController dismissViewControllerAnimated:YES completion:nil];+ [navigation.presentingViewController dismissViewControllerAnimated:YES completion:nil];}@end-#pragma mark - the player--@interface SGHarnessPlayer : UIViewController-@property (nonatomic, strong) UIButton *more;-@property (nonatomic, weak) UINavigationController *sheet;+// A controller of Spotify's own presented in place of the sheet's navigation controller, which it puts the sheet+// into only as it appears (`wrapped`), as NavigationUI_SheetImpl.ContainerViewController does on the phone.+@interface SGHarnessWrapper : UIViewController+@property (nonatomic, strong) UINavigationController *inner;@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;+@implementation SGHarnessWrapper+- (void)viewWillAppear:(BOOL)animated {+ [super viewWillAppear:animated];+ if (self.inner.parentViewController) return;+ [self addChildViewController:self.inner];+ self.inner.view.frame = self.view.bounds;+ self.inner.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;+ [self.view addSubview:self.inner.view];+ [self.inner didMoveToParentViewController:self];}+@end-- (UIButton *)anchor {- for (UIView *view in self.more.subviews) if ([NSStringFromClass(view.class) isEqualToString:@"SGRMenuAnchor"]) return (UIButton *)view;- return nil;-}+#pragma mark - the playerstatic UIView *menuView(UIView *root) {if ([NSStringFromClass(root.class) isEqualToString:@"_UIContextMenuView"]) return root;@@ -253,8 +289,7 @@ static UIView *openMenu(void) {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).+// Whether a label in the open menu reads exactly `title`.static BOOL menuShows(NSString *title) {__block BOOL found = NO;UIView *menu = openMenu();@@ -278,7 +313,6 @@ static BOOL menuShowsAny(NSArray<NSString *> *titles) {return NO;}-// Picks an action, or opens a submenu.static void pick(NSString *title) {UIView *menu = openMenu();UIMenuElement *element = sg_elements[title];@@ -286,209 +320,422 @@ static void pick(NSString *title) {if (menu && element) ((void (*)(id, SEL, id))objc_msgSend)(menu, NSSelectorFromString(@"_handleSelectionForElement:"), element);}+@implementation SGHarnessPlayer++- (void)viewDidLoad {+ [super viewDidLoad];+ self.view.backgroundColor = [UIColor colorWithRed:0.25 green:0.1 blue:0.2 alpha:1];+ // Spotify's header row (trees/clean/player/01.txt: HeaderElementsUnit's view is a 402x48 row holding the+ // down arrow, 48x48 at x 12, and the ⋯, 48x48 at the trailing edge), each button with the redesign's 44pt+ // glass circle first among its subviews, taking no touches (PlayerHeader.x, SGRGlassInside).+ self.header = [[UIView alloc] initWithFrame:CGRectMake(0, 70, 402, 48)];+ [self.view addSubview:self.header];+ self.arrow = [self headerButton:@"chevron.down" at:12 identifier:@"now-playing-minimize-button" label:@"Minimize"];+ [self.arrow addTarget:self action:@selector(arrowTapped) forControlEvents:UIControlEventTouchUpInside];+ self.more = [self headerButton:@"ellipsis" at:342 identifier:@"Context menu" label:@"More options"];+ [self.more addTarget:self action:@selector(moreTapped) forControlEvents:UIControlEventTouchUpInside];+ SGRPlayerMenuWatch(self.more);+ // The press PlayerHeader.x's circle listens to: down, and up or drag out (not the cancel UIKit sends as the+ // menu comes up, which the mod's button turns into a touch up outside once the menu ends).+ [self.front addTarget:self action:@selector(frontDown) forControlEvents:UIControlEventTouchDown];+ [self.front addTarget:self action:@selector(frontUp) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside | UIControlEventTouchDragExit];+ [self.front addTarget:self action:@selector(frontCancel) forControlEvents:UIControlEventTouchCancel];+}++// As PlayerHeader.x does on every layout of Spotify's header unit.+- (void)viewDidLayoutSubviews {+ [super viewDidLayoutSubviews];+ SGRPlayerMenuWatch(self.more);+}++- (UIButton *)headerButton:(NSString *)symbol at:(CGFloat)x identifier:(NSString *)identifier label:(NSString *)label {+ UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];+ [button setImage:[UIImage systemImageNamed:symbol] forState:UIControlStateNormal];+ button.frame = CGRectMake(x, 0, 48, 48);+ button.accessibilityIdentifier = identifier;+ button.accessibilityLabel = label;+ UIVisualEffectView *circle = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleSystemThinMaterialDark]];+ circle.frame = CGRectMake(2, 2, 44, 44);+ circle.layer.cornerRadius = 22;+ circle.clipsToBounds = YES;+ circle.userInteractionEnabled = NO;+ [button insertSubview:circle atIndex:0];+ [self.header addSubview:button];+ return button;+}++- (void)arrowTapped {+ self.arrowTaps++;+ NSLog(@"[harness] Spotify's down arrow action ran");+}++- (void)frontDown {+ self.frontDowns++;+}++- (void)frontUp {+ self.frontUps++;+}++- (void)frontCancel {+ self.frontCancels++;+}++// A finger on `button`'s middle.+- (void)touch:(UIView *)button {+ CGPoint middle = [button convertPoint:CGPointMake(CGRectGetMidX(button.bounds), CGRectGetMidY(button.bounds)) toView:nil];+ NSLog(@"[harness] a finger taps %@ at %@ (hit view %@)", button.accessibilityIdentifier, NSStringFromCGPoint(middle),+ NSStringFromClass([button.window hitTest:middle withEvent:nil].class));+ SGHarnessTap(button.window, middle);+}++// What Spotify's ⋯ does: build its sheet and present it, animated.+- (void)moreTapped {+ sg_spotifyTaps++;+ NSLog(@"[harness] Spotify's ⋯ action ran");+ UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:[_TtC24ContextMenu_InternalImpl25ContextMenuViewController new]];+ self.sheet = navigation;+ if (is(@"wrapped")) {+ SGHarnessWrapper *wrapper = [SGHarnessWrapper new];+ wrapper.inner = navigation;+ [self presentViewController:wrapper animated:YES completion:nil];+ return;+ }+ [self presentViewController:navigation animated:YES completion:nil];+}++- (void)presentSleepOptions {+ _TtC24ContextMenu_InternalImpl25ContextMenuViewController *options = [_TtC24ContextMenu_InternalImpl25ContextMenuViewController new];+ options.sleepOptions = YES;+ UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:options];+ self.sleepSheet = navigation;+ NSLog(@"[harness] Spotify presents the sleep timer's own sheet");+ [self presentViewController:navigation animated:YES completion:nil];+}++- (UIButton *)front {+ for (UIView *view in self.more.subviews) if ([NSStringFromClass(view.class) isEqualToString:@"SGRMenuFront"]) return (UIButton *)view;+ return nil;+}++// A finger's tap on the ⋯, which the mod's button over it takes and opens its menu on, as UIKit opens any+// button's menu. The time from the touch down to the menu on screen, looked at every 10 ms.+- (void)tap:(void (^)(CFTimeInterval took))up {+ CFTimeInterval tapped = CACurrentMediaTime();+ [self touch:self.more];+ waitFor(^BOOL { return openMenu() != nil; }, 3, ^{+ CFTimeInterval took = CACurrentMediaTime() - tapped;+ NSLog(@"[harness] the menu view is on screen %.0f ms after the touch down", took * 1000);+ if (up) up(openMenu() ? took : -1);+ });+}++- (UIWindow *)sheetWindow {+ return self.sheet.viewIfLoaded.window;+}+- (CGFloat)sheetAlpha {- UIView *container = self.sheet.presentationController.containerView;+ UIViewController *outer = self.sheet;+ while (outer.parentViewController) outer = outer.parentViewController;+ UIView *container = outer.presentationController.containerView;return container ? container.alpha : -1;}+// Seen: in the app's window, or in the mod's window raised over it, its container opaque.+- (BOOL)sheetShown {+ UIWindow *window = self.sheetWindow;+ return window && self.sheetAlpha == 1 && (window == self.view.window || window.windowLevel > self.view.window.windowLevel);+}++- (BOOL)sheetGone {+ return !self.sheet.viewIfLoaded.window;+}+- (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);+ after(1, ^{ [self run:scenario()]; });}static NSArray<NSString *> *quickTitles(void) {return @[@"Share", @"Add to Playlist", @"Add to Queue"];}-- (void)runScenario:(NSString *)run {+- (_TtC24ContextMenu_InternalImpl25ContextMenuViewController *)mockSheet {+ return (id)self.sheet.viewControllers.firstObject;+}++- (void)run:(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);+ sg_rowsHeld = is(@"loading") || is(@"quick") || is(@"quicklate") || is(@"podcast") || is(@"stored");+ sg_rowsNever = is(@"quicklate");+ sg_rowsAfter = is(@"quick") ? 1.2 : is(@"loading") || is(@"podcast") ? 1.5 : 0;++ if ([run isEqualToString:@"arrow"]) {+ // The header's other button keeps its own touches: a finger on the down arrow runs Spotify's action and+ // opens no menu; one on the ⋯ then reaches the mod's button, whose touch down opens the menu.+ UIView *front = self.front;+ CGRect over = [front convertRect:front.bounds toView:nil], under = [self.more convertRect:self.more.bounds toView:nil];+ check(CGRectEqualToRect(over, under), [NSString stringWithFormat:@"the mod's ⋯ sits over Spotify's exactly (%@ over %@)", NSStringFromCGRect(over), NSStringFromCGRect(under)]);+ check(self.more.subviews.lastObject == front && self.more.subviews.firstObject != front, @"it is over the ⋯'s glass circle and glyph");+ check(!front.isAccessibilityElement || front.accessibilityLabel.length > 0, @"VoiceOver reaches it with the ⋯'s own label");+ check([self.arrow.window hitTest:CGPointMake(CGRectGetMidX([self.arrow convertRect:self.arrow.bounds toView:nil]), 94) withEvent:nil] != front, @"a touch on the arrow does not reach the mod's ⋯");+ [self touch:self.arrow];+ after(0.5, ^{+ check(self.arrowTaps == 1, [NSString stringWithFormat:@"Spotify's down arrow action ran (%lu)", (unsigned long)self.arrowTaps]);+ check(self.frontDowns == 0 && !openMenu() && sg_spotifyTaps == 0, @"the mod's ⋯ saw no touch, no menu came, Spotify's ⋯ action did not run");+ [self tap:^(CFTimeInterval took) {+ check(took >= 0, @"a finger on the ⋯ opens the menu");+ check(self.frontDowns == 1, [NSString stringWithFormat:@"the mod's ⋯ sent its touch down (%lu)", (unsigned long)self.frontDowns]);+ check(self.arrowTaps == 1, @"the arrow's action did not run again");+ // The finger lifted 0.08 s after the touch down; the press holds while the menu is up.+ after(0.5, ^{+ check(self.frontUps == 0, [NSString stringWithFormat:@"with the menu up the press holds: no touch up yet (cancelled %lu)", (unsigned long)self.frontCancels]);+ [self.front.contextMenuInteraction dismissMenu];+ waitFor(^BOOL { return self.frontUps > 0; }, 2, ^{+ check(self.frontUps == 1, [NSString stringWithFormat:@"the menu's end lets the press go (%lu)", (unsigned long)self.frontUps]);+ 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"); });++ if ([run isEqualToString:@"timing"]) {+ // Ten taps, each closed again, and each time to the menu on screen.+ __block int round = 0;+ NSMutableArray<NSNumber *> *times = [NSMutableArray array];+ // Kept by itself until the last round lets it go.+ __block void (^next)(void);+ next = ^{+ if (round++ == 10) {+ // The first tap of a launch pays for UIKit's menu classes loading; the other nine are the measure.+ NSArray *sorted = [[times subarrayWithRange:NSMakeRange(1, times.count - 1)] sortedArrayUsingSelector:@selector(compare:)];+ NSLog(@"[harness] tap to menu on screen over %lu taps: median %.0f ms, best %.0f ms, worst %.0f ms", (unsigned long)sorted.count,+ [sorted[sorted.count / 2] doubleValue] * 1000, [sorted.firstObject doubleValue] * 1000, [sorted.lastObject doubleValue] * 1000);+ check([sorted[sorted.count / 2] doubleValue] < 0.25, @"the median tap brings the menu up within 250 ms");+ next = nil;+ finish();+ return;+ }+ [self tap:^(CFTimeInterval took) {+ [times addObject:@(took)];+ after(0.5, ^{+ [self.front.contextMenuInteraction dismissMenu];+ after(1.5, ^{ next(); });+ });+ }];+ };+ next();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();+ [self tap:^(CFTimeInterval took) {+ // The simulator's first menu of a launch is slow (UIKit loading its menu classes); `timing` measures the rest.+ check(took >= 0 && took < 1, [NSString stringWithFormat:@"the menu is on screen %.0f ms after the tap", took * 1000]);+ check(self.front.userInteractionEnabled, @"the mod's ⋯ takes touches");+ 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", @"Lyrics", @"Sleep timer"]), @"Spotify's other rows are not at the top level");+ // Spotify's sheet is asked for once the menu is up, into the mod's window, under the app's.+ waitFor(^BOOL { return self.sheetWindow != nil; }, 2, ^{+ check(sg_spotifyTaps == 1, [NSString stringWithFormat:@"Spotify's ⋯ action ran once, from code (%lu)", (unsigned long)sg_spotifyTaps]);+ check(sg_marked == 1, @"Speed and pitch was told the sheet is the player's");+ check(self.sheetWindow && self.sheetWindow != self.view.window && self.sheetWindow.windowLevel < self.view.window.windowLevel,+ @"Spotify's sheet is in the mod's window, under the app's");+ check(!self.sheetShown, @"Spotify's sheet is not seen");+ check(openMenu() != nil, @"the menu is still up");+ [self run:run finish:finish];});- };+ }];+}- if ([run isEqualToString:@"rows"] || [run isEqualToString:@"sort"]) {- after(0.4, ^{+// Waits for the sheet and the menu to go, then reports.+- (void)gone:(NSString *)what selected:(NSString *)selected from:(CFTimeInterval)from finish:(dispatch_block_t)finish {+ waitFor(^BOOL { return self.sheetGone && !openMenu(); }, 6, ^{+ check(self.sheetGone, [NSString stringWithFormat:@"%@: Spotify's sheet went, %.2f s later", what, CACurrentMediaTime() - from]);+ if (selected) check([sg_selected isEqualToString:selected], [NSString stringWithFormat:@"Spotify's %@ was selected (%@)", selected, sg_selected]);+ check(self.front.userInteractionEnabled, @"the mod's ⋯ still takes touches");+ finish();+ });+}++- (void)run:(NSString *)run finish:(dispatch_block_t)finish {+ if ([run isEqualToString:@"rows"] || [run isEqualToString:@"sort"] || [run isEqualToString:@"wrapped"]) {+ after(0.3, ^{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(menuShowsAll(@[@"Go to album", @"Lyrics", @"Sleep timer"]), @"More holds the rest of Spotify's rows, Sleep timer below the sheet's fold too");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");+ after(0.3, ^{+ NSString *title = [run isEqualToString:@"sort"] ? @"Sort" : @"Go to album";+ pick(title);+ [self gone:[@"picked " stringByAppendingString:title] selected:title from:CACurrentMediaTime() finish:finish];});});});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"); });+ // The first menu ever: More shows the system's loading row until the rows come, 1.5 s after the sheet.+ pick(@"More");+ after(0.3, ^{+ check(openMenu() && !menuShows(@"Go to album"), @"More has no rows before the sheet has them");+ waitFor(^BOOL { return menuShows(@"Go to album"); }, 4, ^{+ check(menuShows(@"Go to album"), @"Spotify's rows came into the open More");+ after(0.3, ^{+ pick(@"Go to album");+ [self gone:@"picked Go to album" selected:@"Go to album" from:CACurrentMediaTime() finish:finish];});});});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.+ if ([run isEqualToString:@"stored"]) {+ // A second menu, its sheet's rows held back: More shows the first one's rows at once, and a pick on them+ // waits for the live ones.+ pick(@"More");+ after(0.6, ^{+ check(!menuShows(@"Go to album"), @"the first menu has no stored rows: More waits for the live ones");+ [self.mockSheet giveRows];+ waitFor(^BOOL { return menuShows(@"Go to album"); }, 3, ^{+ [self.front.contextMenuInteraction dismissMenu];+ waitFor(^BOOL { return self.sheetGone && !openMenu(); }, 3, ^{+ check(self.sheetGone, @"the first menu closed with no pick took its sheet with it");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();- });+ [self tap:^(CFTimeInterval took) {+ check(took >= 0 && took < 0.5, [NSString stringWithFormat:@"the second menu is on screen %.0f ms after the tap", took * 1000]);+ pick(@"More");+ after(0.15, ^{+ check(menuShowsAll(@[@"Go to album", @"Sleep timer"]), @"More shows the stored rows at once, the live ones not in yet");+ check(!self.mockSheet.loaded, @"(the live rows are not in)");+ pick(@"Go to album");+ after(0.8, ^{+ check(!self.sheetGone && ![sg_selected isEqualToString:@"Go to album"], @"the pick waits for the live rows");+ [self.mockSheet giveRows];+ [self gone:@"picked Go to album from the stored rows" selected:@"Go to album" from:CACurrentMediaTime() finish: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:@"quick"] || [run isEqualToString:@"quicklate"]) {+ BOOL late = [run isEqualToString:@"quicklate"];+ pick(late ? @"Add to Playlist" : @"Add to Queue");+ CFTimeInterval picked = CACurrentMediaTime();+ after(0.5, ^{ check(!self.sheetShown && !self.sheetGone, @"the sheet stays hidden while the pick waits for its row"); });+ if (!late) {+ [self gone:@"Add to Queue picked before the rows (they came 1.2 s after the sheet)" selected:@"Add to queue" from:picked finish:finish];+ return;+ }+ waitFor(^BOOL { return self.sheetShown; }, 6, ^{+ check(self.sheetShown, [NSString stringWithFormat:@"with no rows in 4 s Spotify's sheet is shown (%.1f s after the pick)", CACurrentMediaTime() - picked]);+ 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"); });+ waitFor(^BOOL { return !menuShows(@"Add to Playlist"); }, 4, ^{+ 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"), @"More holds the podcast's other rows");+ after(0.3, ^{+ pick(@"Go to show");+ [self gone:@"picked Go to show" selected:@"Go to show" from:CACurrentMediaTime() finish:finish];});});});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");+ after(0.3, ^{+ [self.front.contextMenuInteraction dismissMenu];+ CFTimeInterval closed = CACurrentMediaTime();+ // The sheet timed alone: the simulator's menu takes a second and more to fade out on its own.+ __block CFTimeInterval took = -1;+ waitFor(^BOOL { if (took < 0 && self.sheetGone) took = CACurrentMediaTime() - closed; return self.sheetGone && !openMenu(); }, 4, ^{+ check(self.sheetGone && took < 1, [NSString stringWithFormat:@"closing with no pick took the hidden sheet away, %.2f s later", took]);+ check(!sg_selected, @"nothing was selected");+ [self tap:^(CFTimeInterval took) {+ check(took >= 0 && took < 0.5, [NSString stringWithFormat:@"a second tap opens the menu again, %.0f ms after it", took * 1000]);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();+ if ([run isEqualToString:@"subpage"] || [run isEqualToString:@"sleep"]) {+ BOOL sleep = [run isEqualToString:@"sleep"];+ after(0.3, ^{+ if (sleep) pick(@"More");+ waitFor(^BOOL { return !sleep || menuShows(@"Sleep timer"); }, 3, ^{+ pick(sleep ? @"Sleep timer" : @"Share");+ waitFor(^BOOL { return self.sheetShown && [self.sheet.topViewController.title hasSuffix:@"page"]; }, 4, ^{+ check([sg_selected isEqualToString:sleep ? @"Sleep timer" : @"Share"], [NSString stringWithFormat:@"Spotify's row was tapped (%@)", sg_selected]);+ check(self.sheetShown, @"the sheet is shown, over the player");+ check([self.sheet.topViewController.title hasSuffix:@"page"], [NSString stringWithFormat:@"on the page the row pushed (%@)", self.sheet.topViewController.title]);+ waitFor(^BOOL { return !openMenu(); }, 3, ^{+ check(!openMenu(), @"the menu is gone");+ // Closed, the mod's window goes back under the app's.+ [self.sheet.presentingViewController dismissViewControllerAnimated:NO completion:nil];+ after(0.6, ^{+ check(self.view.window.windowLevel > [self.front.window windowLevel] - 1 && !self.sheetWindow, @"the sheet closed, nothing of the mod's stays over the player");+ UIWindow *host = nil;+ for (UIWindow *window in self.view.window.windowScene.windows) if ([NSStringFromClass(window.class) isEqualToString:@"SGRSheetWindow"]) host = window;+ check(host.windowLevel < self.view.window.windowLevel, [NSString stringWithFormat:@"the mod's window is back under the app's (level %.0f)", host.windowLevel]);+ 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();+ if ([run isEqualToString:@"sleeppresent"]) {+ after(0.3, ^{+ pick(@"More");+ waitFor(^BOOL { return menuShows(@"Sleep timer"); }, 3, ^{+ pick(@"Sleep timer");+ waitFor(^BOOL { return self.sleepSheet.viewIfLoaded.window && !self.sleepSheet.isBeingPresented; }, 4, ^{+ UIViewController *sleepSheet = self.sleepSheet;+ check(sleepSheet.viewIfLoaded.window == self.view.window && sleepSheet.presentingViewController == self,+ @"Spotify's sleep timer sheet is up, from the player, in the app's window");+ UIView *container = sleepSheet.presentationController.containerView;+ check(container.alpha == 1 && container.userInteractionEnabled, @"and it is seen and takes touches, as Spotify's");+ waitFor(^BOOL { return !openMenu(); }, 3, ^{+ check(!openMenu(), @"no menu came up for it (the picked one faded out)");+ check(sg_spotifyTaps == 1, @"Spotify's ⋯ action ran only once");+ after(1, ^{+ check(self.sheetGone, @"the card it came from is gone, unseen");+ check(sleepSheet.viewIfLoaded.window != nil, @"the sleep timer sheet is still up");+ finish();+ });+ });+ });});});return;}+ if ([run isEqualToString:@"animated"]) {+ pick(@"Show Animated Artwork");+ check(sg_animated, @"Show Animated Artwork switched it on");+ [self gone:@"picked Show Animated Artwork" selected:nil from:CACurrentMediaTime() finish:finish];+ return;+ }check(NO, [NSString stringWithFormat:@"no scenario %@", run]);finish();}@@ -502,28 +749,25 @@ static NSArray<NSString *> *quickTitles(void) {@implementation SGHarnessApp- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)options {self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];- self.window.rootViewController = [SGHarnessPlayer new];+ sg_player = [SGHarnessPlayer new];+ self.window.rootViewController = sg_player;[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.+// Before every %ctor, so the redesign's gate reads on; and no rows stored from an earlier run.__attribute__((constructor(101))) static void sgr_harnessDefaults(void) {- [NSUserDefaults.standardUserDefaults setBool:YES forKey:@"spotifyglass.redesign"];+ NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;+ [defaults setBool:YES forKey:@"spotifyglass.redesign"];+ for (NSString *key in defaults.dictionaryRepresentation.allKeys) {+ if ([key hasPrefix:@"spotifyglass.redesign.player.menuRows"]) [defaults removeObjectForKey:key];+ }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[]) {diff --git a/harness/tabbar/touch.m b/harness/tabbar/touch.mindex f8739f49..180fa4b6 100644--- a/harness/tabbar/touch.m+++ b/harness/tabbar/touch.m@@ -89,14 +89,19 @@ static void touchTo(UITouch *touch, CGPoint point, UITouchPhase phase) {deliver(touch);}-// A tap at `point`, down and up 0.08 s apart.-void SGHarnessTap(UIWindow *window, CGPoint point) {+// A finger held at `point` for `seconds`, then lifted.+void SGHarnessHold(UIWindow *window, CGPoint point, NSTimeInterval seconds) {UITouch *touch = touchDown(window, point);- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.08 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(seconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{touchTo(touch, point, UITouchPhaseEnded);});}+// A tap at `point`, down and up 0.08 s apart.+void SGHarnessTap(UIWindow *window, CGPoint point) {+ SGHarnessHold(window, point, 0.08);+}+// A finger from `from` to `to` over `seconds`, a move every 1/60 s, let go while still moving: a fling.void SGHarnessDrag(UIWindow *window, CGPoint from, CGPoint to, NSTimeInterval seconds) {UITouch *touch = touchDown(window, from);diff --git a/tweak/Sources/Redesigned/ContextMenu/ContextMenu.h b/tweak/Sources/Redesigned/ContextMenu/ContextMenu.hindex 33092964..e69168e1 100644--- a/tweak/Sources/Redesigned/ContextMenu/ContextMenu.h+++ b/tweak/Sources/Redesigned/ContextMenu/ContextMenu.h@@ -6,21 +6,29 @@// 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.+// the sheet is still Spotify's and still made, unseen.+//+// The player's ⋯ is a pull-down button of the mod's: a button over Spotify's ⋯ takes its touches and opens+// the menu on touch down, as UIKit opens any button's menu, so it waits on nothing of Spotify's. Share, Add to+// playlist and Add to queue (Spotify's items 9, 19 and 11, or found by title) are a row of three at its top, as+// the last sheet of this kind had them, then come the player's own items, then More, which holds the rest of+// Spotify's rows: the last complete set stored, at once, or the system's loading row the first time, put right+// in place as the live rows come. Once the menu is up, Spotify's ⋯ action is run from code; its sheet is+// presented in a window of the mod's under the app's (the menu, a presentation of UIKit's from the player,+// leaves no room for another there), read, and used to run a pick. A pick made before the live rows are in+// waits up to 4 s for them, else the sheet is shown.+//+// A page's ⋯ is the other way round: its tap opens Spotify's sheet, presented without animation in a container+// at alpha 0 from its first frame, and the menu opens over it from an invisible anchor button inside the ⋯, its+// rows a deferred element that waits for them.//// 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+// A page's 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.//@@ -33,9 +41,11 @@ typedef NSArray<UIMenuElement *> *(^SGRMenuItems)(void);// 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).+// Makes `button`, the player's ⋯ (a UIControl), open the system menu itself: the quick row, `items`, then More.+// `kind` may be nil. Called on every layout of the ⋯'s row: it keeps the mod's button on top and over the whole+// ⋯, and 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);++// The mod's button over `button`, which takes the ⋯'s touches once SGRSystemMenuWatch has been called; nil before.+UIControl *SGRSystemMenuFront(UIView *button);diff --git a/tweak/Sources/Redesigned/ContextMenu/ContextMenu.x b/tweak/Sources/Redesigned/ContextMenu/ContextMenu.xindex 2cd11cc6..4b3d3a3d 100644--- a/tweak/Sources/Redesigned/ContextMenu/ContextMenu.x+++ b/tweak/Sources/Redesigned/ContextMenu/ContextMenu.x@@ -1,5 +1,8 @@// The redesign's ⋯ as the system menu (ContextMenu.h says what and why).//+// The player's ⋯ is a pull-down button of the mod's (SGRMenuFront) and its sheet lives in a window of the+// mod's (SGRSheetWindow); everything below about opening the menu over a sheet already up is a page's ⋯.+//// 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@@ -10,8 +13,10 @@// 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+// comes up only some of the time (most of the time on a first showing, not on a second right after a first),+// and the presentation takes 0.2 s and more to end even unanimated, so the menu is asked for a turn after+// viewWillAppear: and, when that does not come, again from the presentation's completion, the sheet going up+// unanimated for that to be soon; -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@@ -23,34 +28,42 @@#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;+// After a pick of Spotify's, how long its sheet has to start going, or to push a page of its own (which shows+// it at once), before it is taken to have stayed up for some other reason and is shown.+static const NSTimeInterval kSettle = 1;// 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;+// How long a pick made before the sheet has its live rows waits for them before the sheet is shown.+static const NSTimeInterval kQuickWait = 4;+// How long the player's menu waits for Spotify's sheet once its ⋯ action has been run for it.+static const NSTimeInterval kRequestWindow = 3;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 NSString *const kMoreMenu = @"com.vitrine.systemmenu.more";+// The last complete set of Spotify's rows for each kind of sheet, for More to show before the live ones come.+static NSString *const kStoredRowsKey = @"spotifyglass.redesign.player.menuRows";++static char kAnchorKey, kFrontKey, kPlacedKey, kSessionKey;++@class SGRMenuSession;+// The session whose pick is being fired on its hidden sheet, for a page the row pushes inside the sheet.+static __weak SGRMenuSession *sg_firing;+// The player's menu asking Spotify for its sheet, and when: the next presentation is that sheet.+static __weak SGRMenuSession *sg_requesting;+static CFTimeInterval sg_requestedAt;+// The session whose sheet is in the mod's own window, and the presentation the mod is making itself.+static __weak SGRMenuSession *sg_hosted;+static BOOL sg_redirecting;++// The player's quick items: what the item says, its symbol, the title of Spotify's row it fires (compared+// without case) and that row's item number, the accessibility identifier of its Encore ListRow on 9.1.78. The+// number is matched first, so a sheet in another language still finds them; the title is the fallback.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"]];+ return @[@[@"Share", @"square.and.arrow.up", @"share", @"9"],+ @[@"Add to Playlist", @"text.badge.plus", @"add to playlist", @"19"],+ @[@"Add to Queue", @"text.line.last.and.arrowtriangle.forward", @"add to queue", @"11"]];}// Which quick items (their rows' titles) the last sheet of each kind had.@@ -58,12 +71,22 @@ 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.+// Spotify's ContextMenuViewController in what was presented: itself, the root of its navigation controller, or+// a child of a controller wrapped around either.+// Matched by class, not by name: NSStringFromClass gives a Swift class's readable name ("Module.Class") on+// iOS 27, never the mangled one kSheetClass holds.static UIViewController *sheetIn(UIViewController *presented) {- if ([NSStringFromClass(presented.class) isEqualToString:kSheetClass]) return presented;+ static Class sheetClass;+ if (!sheetClass) sheetClass = NSClassFromString(kSheetClass);+ if (!presented || !sheetClass) return nil;+ if ([presented isKindOfClass:sheetClass]) return presented;if ([presented isKindOfClass:UINavigationController.class]) {UIViewController *root = ((UINavigationController *)presented).viewControllers.firstObject;- if ([NSStringFromClass(root.class) isEqualToString:kSheetClass]) return root;+ if ([root isKindOfClass:sheetClass]) return root;+ }+ for (UIViewController *child in presented.childViewControllers) {+ UIViewController *sheet = sheetIn(child);+ if (sheet) return sheet;}return nil;}@@ -147,7 +170,32 @@ static BOOL rowEnabled(UITableView *table, NSIndexPath *path, UITableViewCell *creturn title.enabled && title.alpha * alpha >= 0.6;}+// Fires a control as a tap on it would: its primary action's handlers if it has any, else its touch up inside+// ones (the mod's own watchers left out of the count), else its accessibility activation. What it did, for the log.+static NSString *fireControl(UIControl *control) {+ if (!control) return @"nothing to fire";+ __block UIControlEvents events = 0;+ if ([control respondsToSelector:@selector(enumerateEventHandlers:)]) {+ [control enumerateEventHandlers:^(UIAction *action, id target, SEL selector, UIControlEvents handled, BOOL *stop) {+ // The mod's own watcher of the ⋯ (Shared/Player/SpeedPitchMenu.x) is not Spotify's action.+ if (!action && [NSStringFromClass([target class]) hasSuffix:@"TapWatcher"]) return;+ events |= handled;+ }];+ }+ if (events & UIControlEventPrimaryActionTriggered) {+ [control sendActionsForControlEvents:UIControlEventPrimaryActionTriggered];+ return [NSString stringWithFormat:@"%@'s primary action", NSStringFromClass(control.class)];+ }+ if (events & UIControlEventTouchUpInside) {+ [control sendActionsForControlEvents:UIControlEventTouchUpInside];+ return [NSString stringWithFormat:@"%@'s touch up inside", NSStringFromClass(control.class)];+ }+ BOOL done = [control accessibilityActivate];+ return [NSString stringWithFormat:@"%@'s accessibility activation (%@, events 0x%lx)", NSStringFromClass(control.class), done ? @"taken" : @"refused", (unsigned long)events];+}+// Picks the row as a tap would; a row that answers to no delegate is tapped through the first control in it.+// Only the cells on screen exist, so a row further down is scrolled to first (the table is hidden).static void selectRow(UITableView *table, NSIndexPath *path) {id<UITableViewDelegate> delegate = table.delegate;if ([delegate respondsToSelector:@selector(tableView:willSelectRowAtIndexPath:)]) path = [delegate tableView:table willSelectRowAtIndexPath:path];@@ -157,12 +205,17 @@ static void selectRow(UITableView *table, NSIndexPath *path) {[delegate tableView:table didSelectRowAtIndexPath:path];return;}+ UITableViewCell *cell = [table cellForRowAtIndexPath:path];+ if (!cell && path.section < table.numberOfSections && path.row < [table numberOfRowsInSection:path.section]) {+ [table scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionMiddle animated:NO];+ [table layoutIfNeeded];+ cell = [table cellForRowAtIndexPath:path];+ }__block UIControl *control = nil;- SGForEachView([table cellForRowAtIndexPath:path], ^(UIView *view) {- if (!control && [view isKindOfClass:UIControl.class]) control = (UIControl *)view;+ SGForEachView(cell, ^(UIView *view) {+ if (!control && [view isKindOfClass:UIControl.class] && view.userInteractionEnabled) 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];+ SGLog(@"system menu: the sheet's table has no didSelect, so %@ (row %ld%@)", fireControl(control), (long)path.row, cell ? @"" : @", no cell");}// The mod's own rows in the table's header or footer view: the view itself or its children, controls of the@@ -177,6 +230,8 @@ static NSArray<UIControl *> *modRowsIn(UIView *slot) {return rows;}+static NSString *controllersIn(UIViewController *presented);+static UIMenu *inlineGroup(NSArray<UIMenuElement *> *children) {return [UIMenu menuWithTitle:@"" image:nil identifier:nil options:UIMenuOptionsDisplayInline children:children];}@@ -199,16 +254,38 @@ static UIMenu *inlineGroup(NSArray<UIMenuElement *> *children) {@class SGRMenuAnchor;// One ⋯ tap: the sheet Spotify presented, the anchor the menu comes from, and what was picked.+//+// The player's ⋯ (`direct`) opens its menu itself, from a button of the mod's over Spotify's ⋯ (SGRMenuFront),+// before Spotify has done anything: Spotify's sheet is asked for (requestSheet, Spotify's ⋯ action run from+// code) once the menu is up, and presented in a window of the mod's own under the app's (adoptSheet), unseen,+// for its rows and to run them. A page's ⋯ is the other way round: Spotify's sheet comes first, from its tap,+// and the menu is opened over it, hidden (takeOver, open).@interface SGRMenuSession : NSObject+@property (nonatomic) BOOL direct;+// Spotify's ⋯ (direct), whose action brings its sheet up, and the controller Spotify presented that sheet from.+@property (nonatomic, weak) UIControl *spotify;+@property (nonatomic, weak) UIViewController *presenter;@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);+// When the ⋯ was touched (0 for a pinned ⋯, whose touch is the Kit's) and when the sheet was taken over, for+// the log of where the time to the menu goes.+@property (nonatomic) CFTimeInterval touchedAt, takenAt;- (void)open;+- (void)tryEarly;+- (void)present;+- (void)shown;- (void)reveal;+- (void)hide;- (void)menuEnded;+- (UIView *)container;+- (void)requestSheet;+- (void)adoptSheet:(UIViewController *)presented from:(UIViewController *)presenter completion:(void (^)(void))completion;+- (void)rowPresented;+- (UIMenu *)menu;@end// An invisible button over the ⋯ that only hosts the menu. It takes touches only while the menu is up@@ -217,12 +294,22 @@ static UIMenu *inlineGroup(NSArray<UIMenuElement *> *children) {@property (nonatomic, strong) SGRMenuSession *session;@end+// The player's ⋯ as a pull-down button of the mod's own (HIG, Pull-down buttons): an invisible button over+// Spotify's ⋯ that takes its touches and opens the menu on touch down, as UIKit opens any button's menu, so the+// menu waits for nothing of Spotify's and Spotify's ⋯ action does not run on the tap. Its menu is made afresh+// as it opens, with a session of its own.+@interface SGRMenuFront : SGRMenuAnchor+@property (nonatomic, weak) UIControl *spotify;+@property (nonatomic, copy) SGRMenuItems items;+@property (nonatomic, copy) SGRMenuKind kind;+@end+@implementation SGRMenuAnchor- (void)contextMenuInteraction:(UIContextMenuInteraction *)interaction willDisplayMenuForConfiguration:(UIContextMenuConfiguration *)configurationanimator:(id<UIContextMenuInteractionAnimating>)animator {[super contextMenuInteraction:interaction willDisplayMenuForConfiguration:configuration animator:animator];- self.session.displayed = YES;+ [self.session shown];}- (void)contextMenuInteraction:(UIContextMenuInteraction *)interaction willEndForConfiguration:(UIContextMenuConfiguration *)configuration@@ -230,21 +317,101 @@ static UIMenu *inlineGroup(NSArray<UIMenuElement *> *children) {[super contextMenuInteraction:interaction willEndForConfiguration:configuration animator:animator];SGRMenuSession *session = self.session;self.session = nil;- self.userInteractionEnabled = NO;- if (!animator) {- [session menuEnded];- return;+ self.userInteractionEnabled = [self isKindOfClass:SGRMenuFront.class];+ // At once, not at the end of the menu's dismissal: on the phone that end never came (the animator's+ // completion never ran), so every pick and close waited out a 3 s limit with the hidden sheet over the+ // player. The pick fires a turn later, which the sheet takes while the menu is still fading.+ [session menuEnded];+ // The player's ⋯ is pressed for as long as its menu is up (the touch that opened it was cancelled at once,+ // as the menu came): its targets for the press (PlayerHeader.x's circle) are told now that it is let go.+ if ([self isKindOfClass:SGRMenuFront.class]) [self sendActionsForControlEvents:UIControlEventTouchUpOutside];+}++@end++@implementation SGRMenuFront++- (UIContextMenuConfiguration *)contextMenuInteraction:(UIContextMenuInteraction *)interaction configurationForMenuAtLocation:(CGPoint)location {+ SGRMenuSession *session = [SGRMenuSession new];+ session.direct = YES;+ session.opened = YES;+ session.touchedAt = session.takenAt = CACurrentMediaTime();+ session.anchor = self;+ session.spotify = self.spotify;+ session.items = self.items;+ session.kind = self.kind ? self.kind() : nil;+ self.session = session;+ self.menu = [session menu];+ return [super contextMenuInteraction:interaction configurationForMenuAtLocation:location];+}++// One line per touch down, so the phone log says the finger reached the mod's button and what it held then.+- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {+ [super touchesBegan:touches withEvent:event];+ SGLog(@"system menu: touch down on the mod's ⋯ at %@ in the window (menu %@, %@)", NSStringFromCGRect([self convertRect:self.bounds toView:nil]),+ self.menu ? @"held" : @"none", self.enabled && self.userInteractionEnabled ? @"taking touches" : @"not taking touches");+}++// UIKit cancels the touch as the menu comes up, and the press holds until the menu ends (willEndForConfiguration:).+// A touch cancelled with no menu up is a touch let go.+- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {+ [super touchesCancelled:touches withEvent:event];+ if (!self.session) [self sendActionsForControlEvents:UIControlEventTouchUpOutside];+}++@end+++#pragma mark - the mod's window for Spotify's sheet++// The player's menu is a presentation of UIKit's own from the player, so while it is up nothing else can be+// presented there: Spotify's sheet, asked for once the menu is up, would be turned down (simulator, iOS 27). It is+// presented instead in a window of the mod's under the app's, where it lays out and gets its rows unseen. Shown,+// the window comes up over the app's until the sheet is gone. A touch that lands on nothing of the sheet's goes+// through it.+@interface SGRSheetWindow : UIWindow+@end+@implementation SGRSheetWindow+- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {+ UIView *hit = [super hitTest:point withEvent:event];+ return hit == self || hit == self.rootViewController.viewIfLoaded ? nil : hit;+}+@end++static SGRSheetWindow *sg_host;++static SGRSheetWindow *hostWindow(UIWindowScene *scene) {+ if (!scene) return nil;+ if (sg_host.windowScene != scene) {+ sg_host = [[SGRSheetWindow alloc] initWithWindowScene:scene];+ UIViewController *root = [UIViewController new];+ root.view.backgroundColor = UIColor.clearColor;+ sg_host.rootViewController = root;+ sg_host.backgroundColor = UIColor.clearColor;+ sg_host.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;}- [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];+ sg_host.windowLevel = UIWindowLevelNormal - 1;+ sg_host.hidden = NO;+ return sg_host;+}++// The mod's window over the app's while the sheet in it is shown, and back under once it is gone.+static void lowerWhenEmpty(void) {+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ if (sg_host.windowLevel < UIWindowLevelNormal) return;+ if (sg_host.rootViewController.presentedViewController) {+ lowerWhenEmpty();+ return;+ }+ sg_host.windowLevel = UIWindowLevelNormal - 1;});}-@end+static void raiseHost(UIWindow *window) {+ if (!window || window != sg_host || sg_host.windowLevel >= UIWindowLevelNormal) return;+ sg_host.windowLevel = UIWindowLevelNormal + 1;+ lowerWhenEmpty();+}@implementation SGRMenuSession {// The sheet's rows in its groups (the mod's header rows, each section, the mod's footer rows), nil until@@ -258,13 +425,29 @@ static UIMenu *inlineGroup(NSArray<UIMenuElement *> *children) {// The quick row as the menu shows it, to know whether the rows changed it.NSString *_quickShown;NSTimer *_poll;- CFTimeInterval _openedAt;+ CFTimeInterval _openedAt, _askedAt;+ // The menu is asked for while the sheet's presentation is still under way, which UIKit takes only some of+ // the time; if it does not come, it is asked for again once the sheet is up.+ BOOL _early, _wasEarly;+ // Direct: Spotify's sheet asked for, and when; it did not come; the menu closed with nothing for it to do,+ // so it goes as it comes; a row picked on it presented something of Spotify's.+ BOOL _requested, _failed, _dropOnArrival, _rowPresented;+ CFTimeInterval _requestedAt;}- (UIViewController *)sheet {return sheetIn(self.presented);}+// The presentation's container, which the sheet is hidden in. Asked of the controller UIKit presented: a+// controller inside it (the sheet, taken over as it appeared inside one of Spotify's) would answer with a+// presentation controller of its own, made then, holding nothing.+- (UIView *)container {+ UIViewController *outer = self.presented;+ while (outer.parentViewController) outer = outer.parentViewController;+ return outer.presentationController.containerView;+}+- (void)open {if (self.opened) return;self.opened = YES;@@ -275,8 +458,32 @@ static UIMenu *inlineGroup(NSArray<UIMenuElement *> *children) {return;}_openedAt = CACurrentMediaTime();- _whenRead = [NSMutableArray array];- if (![self readRows]) [self pollRows];+ // A turn later, so the menu never comes up in the same turn as the touch that opened Spotify's sheet.+ dispatch_async(dispatch_get_main_queue(), ^{ [self present]; });+}++// The first try, a turn after the sheet starts to appear, before its presentation is over: the wait for that is+// the most the mod adds between the touch and the menu (0.2 s and more in the simulator, even unanimated). UIKit+// brings a menu up then only some of the time, so a try that does not come is let go and open asks again once+// the sheet is up.+- (void)tryEarly {+ if (self.opened || self.displayed || self.ended || self.revealed) return;+ _early = _wasEarly = YES;+ [self present];+}++// The menu up from the anchor, at once, with what needs nothing of the sheet; Spotify's rows are read after it is+// asked for, so the time they take is not the menu's.+- (void)present {+ if (self.displayed || self.ended || self.revealed) return;+ if (!_whenRead) _whenRead = [NSMutableArray array];+ 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;+ }+ if (!_askedAt) _askedAt = CACurrentMediaTime();anchor.session = self;anchor.menu = [self menu];anchor.userInteractionEnabled = YES;@@ -295,14 +502,111 @@ static UIMenu *inlineGroup(NSArray<UIMenuElement *> *children) {}// 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];+ if (!self.displayed && !self.ended && self->_early) {+ self->_early = NO;+ anchor.userInteractionEnabled = NO;+ anchor.session = nil;+ static int logged;+ if (logged++ < 3) SGLog(@"system menu: the menu asked for while Spotify's sheet came up did not come, asked again once it is up");+ return;+ }+ self->_early = NO;+ if (!self.displayed && !self.ended) {+ SGLog(@"system menu: the menu did not come up, Spotify's sheet shown");+ anchor.userInteractionEnabled = NO;+ anchor.session = nil;+ [self reveal];+ return;+ }+ if (![self readRows]) [self pollRows];+ });+}++// Where the time from the ⋯ touch to the menu on screen went, in seconds after the touch (after the takeover for+// a pinned ⋯).+- (void)shown {+ if (self.displayed) return;+ self.displayed = YES;+ if (!_whenRead) _whenRead = [NSMutableArray array];+ if (self.direct) {+ SGLog(@"system menu: the player's menu is up %.3f s after the touch down on its ⋯ (Spotify's sheet not asked for yet)",+ CACurrentMediaTime() - self.touchedAt);+ // A turn later, so nothing of Spotify's stands in the way of the menu's first frames.+ dispatch_async(dispatch_get_main_queue(), ^{ [self requestSheet]; });+ return;+ }+ CFTimeInterval now = CACurrentMediaTime(), from = self.touchedAt ?: self.takenAt;+ SGLog(@"system menu: the menu is up %.2f s after the %@: Spotify's sheet taken over at %.2f, first asked for at %.2f%@, %@",+ now - from, self.touchedAt ? @"⋯ touch" : @"takeover", self.takenAt - from, _askedAt - from,+ _wasEarly ? @" while the sheet came up" : @"", _openedAt ? [NSString stringWithFormat:@"the sheet up at %.2f", _openedAt - from] : @"before the sheet was up");+}++#pragma mark Spotify's sheet, for the player's menu++// Runs Spotify's ⋯ action from code, as the tap the menu kept from it would have: its sheet comes up, is taken+// for this menu (the presentation hook) and goes into the mod's window.+- (void)requestSheet {+ if (!self.direct || self.presented || _requested) return;+ _requested = YES;+ _requestedAt = CACurrentMediaTime();+ sg_requesting = self;+ sg_requestedAt = _requestedAt;+ // Speed and pitch's sheet test (and Edit info's) counts the ⋯'s touch, which the menu kept from Spotify's ⋯.+ SGPlayerMenuMarkPlayers();+ NSString *how = fireControl(self.spotify);+ SGLog(@"system menu: Spotify's sheet asked for, %.3f s after the touch down, by %@", _requestedAt - self.touchedAt, how);+ __weak SGRMenuSession *weakSelf = self;+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kRequestWindow * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ SGRMenuSession *session = weakSelf;+ if (!session || session.presented) return;+ if (sg_requesting == session) sg_requesting = nil;+ session->_failed = YES;+ SGLog(@"system menu: Spotify's sheet did not come %.0f s after it was asked for", kRequestWindow);+ session->_waiting = NO;+ NSArray<dispatch_block_t> *waiting = session->_whenRead;+ session->_whenRead = [NSMutableArray array];+ for (dispatch_block_t block in waiting) block();});}+// Spotify's sheet, asked for, on its way up from `presenter`: presented in the mod's window instead, unseen.+- (void)adoptSheet:(UIViewController *)presented from:(UIViewController *)presenter completion:(void (^)(void))completion {+ self.presented = presented;+ self.presenter = presenter;+ self.takenAt = CACurrentMediaTime();+ objc_setAssociatedObject(presented, &kSessionKey, self, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ sg_hosted = self;+ SGRSheetWindow *host = hostWindow(presenter.viewIfLoaded.window.windowScene ?: self.anchor.window.windowScene);+ SGLog(@"system menu: Spotify's sheet (%@) came %.3f s after it was asked for, %.3f s after the touch down; kept in the mod's window",+ controllersIn(presented), self.takenAt - _requestedAt, self.takenAt - self.touchedAt);+ UIViewController *root = host.rootViewController;+ void (^present)(void) = ^{+ sg_redirecting = YES;+ [root presentViewController:presented animated:NO completion:^{+ if (completion) completion();+ [self sheetArrived];+ }];+ sg_redirecting = NO;+ [self hide];+ };+ // An earlier sheet still there (its menu closed while it came) goes first.+ if (root.presentedViewController) [root dismissViewControllerAnimated:NO completion:present];+ else present();+}++- (void)sheetArrived {+ if (_dropOnArrival && !_waiting) {+ [self.presented.presentingViewController dismissViewControllerAnimated:NO completion:nil];+ return;+ }+ if (![self readRows]) [self pollRows];+}++// Something of Spotify's was presented while a row picked on this sheet fired: the row's own sheet.+- (void)rowPresented {+ _rowPresented = YES;+}+#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@@ -314,7 +618,7 @@ static UIMenu *inlineGroup(NSArray<UIMenuElement *> *children) {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]]];+ UIMenu *more = [UIMenu menuWithTitle:@"More" image:[UIImage systemImageNamed:@"ellipsis.circle"] identifier:kMoreMenu options:0 children:@[[self deferredRows]]];[children addObject:inlineGroup(@[more])];return [UIMenu menuWithTitle:@"" image:nil identifier:kTopMenu options:0 children:children];}@@ -328,8 +632,22 @@ static UIMenu *inlineGroup(NSArray<UIMenuElement *> *children) {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] ?: @[]); }];+ // The player's: the rows the last sheet of this kind had, at once, the live ones put in when they come.+ NSArray<UIMenuElement *> *stored = session.direct ? [session storedElements] : nil;+ if (stored.count) {+ completion(stored);+ return;+ }+ if (session.direct) [session requestSheet];+ if (session->_failed) {+ completion([session unavailable]);+ return;+ }+ SGLog(@"system menu: Spotify's rows asked for before the sheet has them");+ [session->_whenRead addObject:^{+ SGRMenuSession *read = weakSelf;+ completion(read ? (read->_groups ? [read rowElements] : [read unavailable]) : @[]);+ }];}];}@@ -345,6 +663,75 @@ static UIMenu *inlineGroup(NSArray<UIMenuElement *> *children) {return groups;}+// Shown when Spotify's sheet never came, so More is not left loading.+- (NSArray<UIMenuElement *> *)unavailable {+ UIAction *none = [UIAction actionWithTitle:@"Spotify's options did not load" image:nil identifier:nil handler:^(UIAction *action) {}];+ none.attributes = UIMenuElementAttributesDisabled;+ return @[none];+}++static NSString *storedKey(NSString *kind) {+ return [NSString stringWithFormat:@"%@.%@", kStoredRowsKey, kind.length ? kind : @"track"];+}++// The rows the last sheet of this kind had, as stored: title, subtitle, enabled and glyph, but for the quick ones.+// Picking one waits for the live rows and fires the row of that title (fireTitle).+- (NSArray<UIMenuElement *> *)storedElements {+ NSArray<NSArray<NSDictionary *> *> *groups = [NSUserDefaults.standardUserDefaults arrayForKey:storedKey(self.kind)];+ if (![groups isKindOfClass:NSArray.class]) return nil;+ __weak SGRMenuSession *weakSelf = self;+ NSMutableArray<UIMenuElement *> *elements = [NSMutableArray array];+ for (NSArray<NSDictionary *> *group in groups) {+ if (![group isKindOfClass:NSArray.class]) continue;+ NSMutableArray<UIMenuElement *> *actions = [NSMutableArray array];+ for (NSDictionary *row in group) {+ NSString *title = [row isKindOfClass:NSDictionary.class] ? row[@"title"] : nil;+ if (![title isKindOfClass:NSString.class]) continue;+ NSData *glyph = row[@"image"];+ UIImage *image = [glyph isKindOfClass:NSData.class] ? [NSKeyedUnarchiver unarchivedObjectOfClass:UIImage.class fromData:glyph error:nil] : nil;+ UIAction *action = [UIAction actionWithTitle:title image:image identifier:nil handler:^(UIAction *picked) {+ weakSelf.pick = ^{ [weakSelf fireTitle:title]; };+ }];+ NSString *subtitle = row[@"subtitle"];+ if ([subtitle isKindOfClass:NSString.class]) action.subtitle = subtitle;+ if ([row[@"enabled"] isEqual:@NO]) action.attributes = UIMenuElementAttributesDisabled;+ [actions addObject:action];+ }+ if (actions.count) [elements addObject:inlineGroup(actions)];+ }+ return elements;+}++// Keeps a complete read of the rows (all but the quick ones) for the next menu of this kind, when it differs.+- (void)storeRows {+ NSMutableArray *groups = [NSMutableArray array];+ for (NSArray<SGRSheetRow *> *group in _groups) {+ NSMutableArray *rows = [NSMutableArray array];+ for (SGRSheetRow *row in group) {+ if (row.quick || !row.title.length) continue;+ NSMutableDictionary *stored = [@{@"title": row.title, @"enabled": @(row.enabled)} mutableCopy];+ if (row.subtitle.length) stored[@"subtitle"] = row.subtitle;+ NSData *glyph = row.image ? [NSKeyedArchiver archivedDataWithRootObject:row.image requiringSecureCoding:YES error:nil] : nil;+ if (glyph.length && glyph.length < 32 * 1024) stored[@"image"] = glyph;+ [rows addObject:stored];+ }+ if (rows.count) [groups addObject:rows];+ }+ NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;+ if (!groups.count || [[defaults arrayForKey:storedKey(self.kind)] isEqual:groups]) return;+ [defaults setObject:groups forKey:storedKey(self.kind)];+}++// The live rows came while More shows the stored ones or the loading row: More is put right in place.+- (void)refreshMore {+ if (!self.direct || !self.displayed || self.ended) return;+ NSArray<UIMenuElement *> *live = [self rowElements];+ [self.anchor.contextMenuInteraction updateVisibleMenuWithBlock:^UIMenu *(UIMenu *visible) {+ if (![visible.identifier isEqualToString:kMoreMenu]) return visible;+ return [visible menuByReplacingChildren:live];+ }];+}+- (UIAction *)actionFor:(SGRSheetRow *)row {__weak SGRMenuSession *weakSelf = self;UIAction *action = [UIAction actionWithTitle:row.title image:row.image identifier:nil handler:^(UIAction *picked) {@@ -431,6 +818,7 @@ static UIMenu *inlineGroup(NSArray<UIMenuElement *> *children) {if (_groups) return YES;UITableView *table = tableIn(self.sheet.viewIfLoaded, 0);if (!table || rowCount(table) == 0) return NO;+ CFTimeInterval started = CACurrentMediaTime();[table layoutIfNeeded];_table = table;NSMutableArray<NSArray<SGRSheetRow *> *> *groups = [NSMutableArray array];@@ -449,15 +837,17 @@ static UIMenu *inlineGroup(NSArray<UIMenuElement *> *children) {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] : @"");+ CFTimeInterval now = CACurrentMediaTime(), from = self.touchedAt ?: self.takenAt;+ SGLog(@"system menu: %lu of Spotify's rows and %lu of the mod's read in %.0f ms, %.2f s after the %@", (unsigned long)read,+ (unsigned long)(header.count + footer.count), (now - started) * 1000, now - from, self.touchedAt ? @"⋯ touch" : @"takeover");if (self.items) [self matchQuick];+ if (self.direct) [self storeRows];NSArray<dispatch_block_t> *waiting = _whenRead;_whenRead = [NSMutableArray array];for (dispatch_block_t block in waiting) block();[self refreshQuickRow];+ [self refreshMore];return YES;}@@ -501,7 +891,7 @@ static UIMenu *inlineGroup(NSArray<UIMenuElement *> *children) {[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;+ if (!([row.identifier isEqualToString:item[3]] || [title isEqualToString:item[2]]) || [found containsObject:item[2]]) continue;row.quick = item[2];[found addObject:item[2]];}@@ -514,7 +904,7 @@ static UIMenu *inlineGroup(NSArray<UIMenuElement *> *children) {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");+ SGLog(@"system menu: quick items matched by number or title: %@", found.count ? [found componentsJoinedByString:@", "] : @"none");}#pragma mark the pick@@ -529,8 +919,10 @@ static UIMenu *inlineGroup(NSArray<UIMenuElement *> *children) {SGLog(@"system menu: %@ picked before the sheet had its rows, waiting up to %.0f s", quick, kQuickWait);_waiting = YES;__weak SGRMenuSession *weakSelf = self;+ if (!_whenRead) _whenRead = [NSMutableArray array];[_whenRead addObject:^{ [weakSelf fireQuickNow:quick]; }];- [self pollRows];+ if (self.direct) [self requestSheet];+ if (self.presented) [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;@@ -540,6 +932,38 @@ static UIMenu *inlineGroup(NSArray<UIMenuElement *> *children) {});}+// A stored row picked: the live row of that title is fired once the rows are in.+- (void)fireTitle:(NSString *)title {+ if (!_groups) {+ SGLog(@"system menu: %@ picked from the stored rows, waiting up to %.0f s for Spotify's", title, kQuickWait);+ _waiting = YES;+ __weak SGRMenuSession *weakSelf = self;+ if (!_whenRead) _whenRead = [NSMutableArray array];+ [_whenRead addObject:^{ [weakSelf fireTitle:title]; }];+ [self requestSheet];+ if (self.presented) [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, title);+ [session reveal];+ });+ return;+ }+ _waiting = NO;+ for (NSArray<SGRSheetRow *> *group in _groups) {+ for (SGRSheetRow *row in group) {+ if ([row.title isEqualToString:title]) {+ [self fire:row];+ return;+ }+ }+ }+ SGLog(@"system menu: Spotify's rows no longer have %@, its sheet shown", title);+ [self reveal];+}+- (void)fireQuickNow:(NSString *)quick {_waiting = NO;SGRSheetRow *row = [self rowForQuick:quick];@@ -555,17 +979,31 @@ static UIMenu *inlineGroup(NSArray<UIMenuElement *> *children) {- (void)fire:(SGRSheetRow *)row {UIViewController *presented = self.presented;if (!presented.presentingViewController || self.revealed) return;+ sg_firing = self;+ _rowPresented = NO;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.+ // A row that pushes a page of its own inside the sheet shows it as it pushes (the push hook below); one that+ // leaves the sheet up some other way shows it after kSettle.dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kSettle * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ if (sg_firing == self) sg_firing = nil;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");+ if (self.revealed || !still.presentingViewController || still.isBeingDismissed || !still.viewIfLoaded.window) return;+ // Spotify put up a sheet of the row's own (Sleep timer's): that is what shows; the card it came from goes,+ // unseen, never over it.+ if (self->_rowPresented) {+ SGLog(@"system menu: the row picked (%@) put up a sheet of its own, Spotify's hidden card goes unseen", row.title);+ [still.presentingViewController dismissViewControllerAnimated:NO completion:nil];+ return;+ }+ UINavigationController *navigation = self.sheet.navigationController;+ SGLog(@"system menu: the row picked (%@) left Spotify's sheet up without pushing a page, so it is shown (it holds %@%@)", row.title,+ navigation ? [[navigation.viewControllers valueForKey:@"class"] componentsJoinedByString:@" > "] : NSStringFromClass(self.sheet.class),+ still.presentedViewController ? [NSString stringWithFormat:@", and presents %@", NSStringFromClass(still.presentedViewController.class)] : @"");[self reveal];});}@@ -579,9 +1017,24 @@ static UIMenu *inlineGroup(NSArray<UIMenuElement *> *children) {self.pick = nil;dispatch_async(dispatch_get_main_queue(), ^{UIViewController *presented = self.presented;- if (!presented.presentingViewController || self.revealed) return;+ if (self.revealed) return;+ // The player's menu with no sheet yet: a pick asks for it and waits for its rows; with no pick, a sheet+ // still on its way goes as it comes.+ if (self.direct && !presented) {+ if (pick) pick();+ else self->_dropOnArrival = YES;+ return;+ }+ if (!presented.presentingViewController) return;if (!pick) {[presented.presentingViewController dismissViewControllerAnimated:NO completion:nil];+ // Never a hidden sheet left behind: should UIKit have turned the dismissal down, it is asked again.+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ UIViewController *still = self.presented;+ if (!still.presentingViewController || still.isBeingDismissed || self.revealed) return;+ SGLog(@"system menu: Spotify's hidden sheet was still up after the menu closed, dismissed again");+ [still.presentingViewController dismissViewControllerAnimated:NO completion:nil];+ });return;}pick();@@ -590,75 +1043,97 @@ static UIMenu *inlineGroup(NSArray<UIMenuElement *> *children) {// 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).+// The sheet unseen and out of the way of touches, so one left up for any reason never stands between a finger+// and the player.+- (void)hide {+ UIView *container = self.container;+ container.alpha = 0;+ container.userInteractionEnabled = NO;+}+- (void)reveal {- if (self.revealed) return;+ if (self.revealed || !self.presented) return;self.revealed = YES;- UIView *container = self.presented.presentationController.containerView;+ UIView *container = self.container;+ raiseHost(container.window);+ container.userInteractionEnabled = YES;SGRAnimate(SGRMotionFade, ^{ container.alpha = 1; }, nil);[self.sheet.viewIfLoaded setNeedsLayout];}@end-static SGRMenuSession *sessionFor(UIViewController *controller) {+// The session on the sheet or a controller it is inside of. With `fresh`, as the sheet appears, a session whose+// menu has opened is an earlier showing's (a controller Spotify kept and shows again): it is let go, so this+// showing is looked at afresh rather than left to a session that is over.+static SGRMenuSession *sessionFor(UIViewController *controller, BOOL fresh) {for (UIViewController *vc = controller; vc; vc = vc.parentViewController) {SGRMenuSession *session = objc_getAssociatedObject(vc, &kSessionKey);- if (session) return session;+ if (!session) continue;+ if (!fresh || !session.opened || session.direct) return session;+ SGLog(@"system menu: a ⋯ sheet appears again holding an earlier showing's session (on %@), let go", NSStringFromClass(vc.class));+ objc_setAssociatedObject(vc, &kSessionKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);}return nil;}BOOL SGPlayerMenuReplaced(UIViewController *menu) {- SGRMenuSession *session = sessionFor(menu);+ SGRMenuSession *session = sessionFor(menu, NO);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();- static int logged;- if (logged++ < 3) SGLog(@"system menu: ⋯ pressed (%@)", NSStringFromClass(press.view.class));-}-- (void)touchedDown:(UIView *)control {- sg_claimButton = control;- sg_claimAt = CACurrentMediaTime();- static int logged;- if (logged++ < 3) SGLog(@"system menu: ⋯ touched down (%@)", NSStringFromClass(control.class));-}-- (BOOL)gestureRecognizer:(UIGestureRecognizer *)recognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)other {- return YES;+void SGRSystemMenuWatch(UIView *button, SGRMenuItems items, SGRMenuKind kind) {+ if (![button isKindOfClass:UIControl.class]) return;+ SGRMenuFront *front = objc_getAssociatedObject(button, &kFrontKey);+ if (!front) {+ front = [SGRMenuFront buttonWithType:UIButtonTypeCustom];+ front.showsMenuAsPrimaryAction = YES;+ // UIKit opens a button's menu on touch down only while the button holds one; a finger's touch on a+ // button with none is taken and opens nothing (phone, and harness/system-menu with a finger's touch,+ // 2026-10-06; -performPrimaryAction, which the harness tapped with before, opens the menu either way).+ // This one stands in until the touch down asks for the session's (configurationForMenuAtLocation:).+ front.menu = [UIMenu menuWithChildren:@[]];+ front.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;+ front.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;+ front.isAccessibilityElement = YES;+ front.accessibilityTraits = UIAccessibilityTraitButton;+ objc_setAssociatedObject(button, &kFrontKey, front, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ SGLog(@"system menu: the player's ⋯ (%@) opens the menu from a button of the mod's over it", NSStringFromClass(button.class));+ }+ front.spotify = (UIControl *)button;+ front.items = items;+ front.kind = kind;+ // VoiceOver reaches the mod's button rather than Spotify's ⋯, with the ⋯'s own words, so it opens the menu too.+ if (button.isAccessibilityElement) {+ if (button.accessibilityLabel.length) front.accessibilityLabel = button.accessibilityLabel;+ button.isAccessibilityElement = NO;+ }+ if (!front.accessibilityLabel.length) front.accessibilityLabel = @"More";+ if (front.superview != button) [button addSubview:front];+ else if (button.subviews.lastObject != front) [button bringSubviewToFront:front];+ if (!CGRectEqualToRect(front.frame, button.bounds)) front.frame = button.bounds;+ // Where the mod's button sits in the window next to the ⋯, and what a touch at the ⋯'s middle would reach,+ // so the phone log shows the placement: once per change of the one over the other, of the ⋯'s size or of+ // what the touch reaches, not of where the header is (the player's open and close move it every frame).+ if (!button.window || button.bounds.size.width <= 0) return;+ CGRect over = [front convertRect:front.bounds toView:nil], under = [button convertRect:button.bounds toView:nil];+ CGPoint middle = CGPointMake(CGRectGetMidX(under), CGRectGetMidY(under));+ UIView *hit = [button.window hitTest:middle withEvent:nil];+ NSString *reaches = hit == front ? @"it" : NSStringFromClass(hit.class);+ NSString *key = [NSString stringWithFormat:@"%@ %@ %@", NSStringFromCGPoint(CGPointMake(over.origin.x - under.origin.x, over.origin.y - under.origin.y)),+ NSStringFromCGSize(over.size), NSStringFromCGSize(under.size)];+ key = [key stringByAppendingFormat:@" %@", reaches];+ if (![key isEqualToString:objc_getAssociatedObject(front, &kPlacedKey)]) {+ objc_setAssociatedObject(front, &kPlacedKey, key, OBJC_ASSOCIATION_COPY_NONATOMIC);+ SGLog(@"system menu: the mod's ⋯ at %@ over Spotify's at %@ in the window; a touch at the ⋯'s middle reaches %@",+ NSStringFromCGRect(over), NSStringFromCGRect(under), reaches);+ }}-@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);- static int logged;- if (logged++ < 4) SGLog(@"system menu: watching a ⋯ (%@, %@ touches, in %@)", NSStringFromClass(button.class),- button.userInteractionEnabled ? @"takes" : @"takes no", NSStringFromClass(button.superview.class));- // 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];+UIControl *SGRSystemMenuFront(UIView *button) {+ return objc_getAssociatedObject(button, &kFrontKey);}static SGRMenuAnchor *anchorIn(UIView *host) {@@ -679,23 +1154,51 @@ static SGRMenuAnchor *anchorIn(UIView *host) {return anchor;}-// Whether this sheet is a watched ⋯'s, and if so its session, with the sheet's presentation now the menu's.-static void whyNot(NSString *reason) {+// A page's ⋯ was touched this recently: a context menu sheet that is not taken over now is worth a line saying why.+static BOOL claimRecent(void) {+ return SGRPinnedMoreRecentButton() != nil;+}++// Why a sheet was not taken over: every time while a ⋯ touch is recent, so the next log of a ⋯ that opened+// Spotify's sheet says why; a few times otherwise, since every other context menu in the app passes here too.+static void whyNot(NSString *via, BOOL recent, NSString *reason) {static int logged;- if (logged++ < 8) SGLog(@"system menu: not taken over: %@", reason);+ if (recent || logged++ < 4) SGLog(@"system menu: a sheet %@, not taken over: %@", via, reason);}-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();+// The controllers from `presented` down, for the log of a presentation that held no sheet.+static NSString *controllersIn(UIViewController *presented) {+ NSMutableArray<NSString *> *names = [NSMutableArray arrayWithObject:NSStringFromClass(presented.class)];+ if ([presented isKindOfClass:UINavigationController.class]) {+ for (UIViewController *vc in ((UINavigationController *)presented).viewControllers) [names addObject:NSStringFromClass(vc.class)];+ }+ for (UIViewController *child in presented.childViewControllers) [names addObject:NSStringFromClass(child.class)];+ return [names componentsJoinedByString:@" > "];+}++// Whether this sheet is a watched ⋯'s, and if so its session, with the sheet's presentation now the menu's.+// `via` says which way in asked, for the log.+static SGRMenuSession *takeOver(UIViewController *presented, NSString *via) {+ BOOL recent = claimRecent();+ if (!sheetIn(presented)) {+ if (recent) SGLog(@"system menu: %@ presented soon after a page's ⋯ touch holds no ⋯ sheet (%@)", NSStringFromClass(presented.class),+ controllersIn(presented));+ return nil;+ }+ // While a row picked on a menu's sheet fires, what comes up is that row's (Sleep timer's own sheet), never+ // a new ⋯ menu.+ if (sg_firing) {+ whyNot(via, YES, @"it came while a picked row fired, so it is the row's");+ return nil;+ }+ UIView *button = SGRPinnedMoreRecentButton();+ CFTimeInterval touchedAt = 0;+ if (!button) {+ whyNot(via, recent, @"no page's ⋯ was touched");+ return nil;}if (!button.window) {- whyNot(button ? @"the claimed ⋯ is off screen" : sg_claimButton ? [NSString stringWithFormat:@"the claim is %.1f s old", CACurrentMediaTime() - sg_claimAt] : @"no ⋯ was claimed");+ whyNot(via, YES, [NSString stringWithFormat:@"the ⋯ touched (%@) is off screen", NSStringFromClass(button.class)]);return nil;}static BOOL canPresent, checked;@@ -703,22 +1206,90 @@ static SGRMenuSession *takeOver(UIViewController *presented) {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;+ if (!canPresent) {+ whyNot(via, YES, @"this iOS has no way to open a button's menu from code");+ return nil;+ }SGRMenuSession *session = [SGRMenuSession new];+ session.touchedAt = touchedAt;+ session.takenAt = CACurrentMediaTime();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);+ SGLog(@"system menu: the ⋯ sheet taken over %@ (%@)", via, session.items ? @"the player's" : @"a page's");return session;}+// Should neither appearance call come to a sheet taken over as it laid out, its menu opens once its+// presentation is over all the same: looked at every tenth of a second for up to 3 s.+static void openWhenUp(SGRMenuSession *session, UIViewController *sheet, int tries) {+ __weak UIViewController *weakSheet = sheet;+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ UIViewController *up = weakSheet;+ if (session.opened || !up) return;+ UIViewController *outer = up;+ while (outer.parentViewController) outer = outer.parentViewController;+ if ((!up.viewIfLoaded.window || outer.isBeingPresented) && tries < 30) {+ openWhenUp(session, up, tries + 1);+ return;+ }+ SGLog(@"system menu: the ⋯ sheet taken over as it laid out did not say it appeared, its menu opened anyway");+ [session open];+ });+}++// A row picked on the hidden sheet that pushes a page inside it (Sleep timer's options): the page goes in without+// its slide, so the sheet is shown on that page rather than on the card it covers, and the sheet is shown.+%hook UINavigationController+- (void)pushViewController:(UIViewController *)page animated:(BOOL)animated {+ SGRMenuSession *session = sg_firing;+ UIView *container = session.container;+ if (!session || session.revealed || !container || ![self.viewIfLoaded isDescendantOfView:container]) {+ %orig;+ return;+ }+ sg_firing = nil;+ SGLog(@"system menu: the row picked pushed %@ inside Spotify's sheet, which is shown on it", NSStringFromClass(page.class));+ %orig(page, NO);+ [session reveal];+}+%end+%hook UIViewController- (void)presentViewController:(UIViewController *)presented animated:(BOOL)animated completion:(void (^)(void))completion {- SGRMenuSession *session = takeOver(presented);+ if (sg_redirecting) {+ %orig;+ return;+ }+ UIWindow *in = self.viewIfLoaded.window;+ // The sheet the player's menu asked Spotify for: into the mod's window, unseen.+ SGRMenuSession *requesting = sg_requesting;+ if (requesting && in != sg_host && CACurrentMediaTime() - sg_requestedAt <= kRequestWindow && ![presented isKindOfClass:UIAlertController.class]) {+ sg_requesting = nil;+ [requesting adoptSheet:presented from:self completion:completion];+ return;+ }+ SGRMenuSession *firing = sg_firing;+ if (firing) {+ SGLog(@"system menu: while a picked row fires, %@ presents %@", NSStringFromClass(self.class), NSStringFromClass(presented.class));+ [firing rowPresented];+ }+ // Spotify presenting from its sheet in the mod's window, or from under it, while that sheet is hidden: it goes+ // up from Spotify's own presenter instead, in Spotify's window, where it can be seen.+ SGRMenuSession *hosted = sg_hosted;+ if (in && in == sg_host && hosted && !hosted.revealed && presented != hosted.presented) {+ UIViewController *from = hosted.presenter;+ while (from.presentedViewController && !from.presentedViewController.isBeingDismissed) from = from.presentedViewController;+ if (from) {+ SGLog(@"system menu: %@ presented from Spotify's hidden sheet goes up from %@ instead", NSStringFromClass(presented.class), NSStringFromClass(from.class));+ sg_redirecting = YES;+ [from presentViewController:presented animated:animated completion:completion];+ sg_redirecting = NO;+ return;+ }+ }+ SGRMenuSession *session = takeOver(presented, @"as it is presented");if (!session) {%orig;return;@@ -731,25 +1302,40 @@ static SGRMenuSession *takeOver(UIViewController *presented) {%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 {+// A sheet Spotify puts up some other way than presentViewController: (the player's ⋯ on a phone), or inside a+// controller of its own that held no sheet yet when it was presented, is taken over as it first lays out or+// appears, from the same claim, and its menu opened once it has appeared.+//+// Its first layout can come before its presentation's container exists, so it is hidden at each layout and in+// viewWillAppear:, the first moment the container does exist, before it has drawn a frame; its dimming too, so+// the screen does not darken under the menu.+- (void)viewDidLayoutSubviews {%orig;- static int logged;- if (logged++ < 3) SGLog(@"system menu: a ⋯ sheet will appear (%@ session)", sessionFor((UIViewController *)self) ? @"with a" : @"without a");- 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");+ UIViewController *sheet = (UIViewController *)self;+ SGRMenuSession *session = sessionFor(sheet, NO);+ // Only a sheet on its way up, not one that was up before the ⋯ was touched laying out again.+ UIViewController *outer = sheet;+ while (outer.parentViewController) outer = outer.parentViewController;+ if (!session && claimRecent() && (!sheet.viewIfLoaded.window || outer.isBeingPresented)) {+ session = takeOver(sheet, @"as it lays out");+ if (session) openWhenUp(session, sheet, 0);}- if (session && !session.revealed) session.presented.presentationController.containerView.alpha = 0;+ // Until its menu opens: a session that has opened hides its sheet itself, or is an earlier showing's. The+ // player's sheet stays hidden at every layout until it is shown.+ if (session && (!session.opened || session.direct) && !session.revealed) [session hide];+}++- (void)viewWillAppear:(BOOL)animated {+ %orig;+ SGRMenuSession *session = sessionFor((UIViewController *)self, YES);+ if (!session) session = takeOver((UIViewController *)self, @"as it appears");+ if (session && !session.revealed) [session hide];+ if (session && !session.direct) dispatch_async(dispatch_get_main_queue(), ^{ [session tryEarly]; });}- (void)viewDidAppear:(BOOL)animated {%orig;- SGRMenuSession *session = sessionFor((UIViewController *)self);+ SGRMenuSession *session = sessionFor((UIViewController *)self, NO);if (session && !session.opened) [session open];}%enddiff --git a/tweak/Sources/Shared/Player/SpeedPitch.h b/tweak/Sources/Shared/Player/SpeedPitch.hindex d5304fdc..8ac35993 100644--- a/tweak/Sources/Shared/Player/SpeedPitch.h+++ b/tweak/Sources/Shared/Player/SpeedPitch.h@@ -16,6 +16,9 @@// Whether a context menu sheet is the player's ⋯ card: the first to come up within a few seconds of a tap on// the player's more button (SpeedPitchMenu.x watches it under either look); decided once per menu.BOOL SGPlayerMenuIsPlayers(UIViewController *menu);+// The next context menu sheet is the player's ⋯ card, as a tap on the ⋯ would make it: for the redesign's ⋯,+// whose menu runs Spotify's ⋯ action from code (Redesigned/ContextMenu) and keeps the touch from the ⋯.+void SGPlayerMenuMarkPlayers(void);// 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.diff --git a/tweak/Sources/Shared/Player/SpeedPitchMenu.x b/tweak/Sources/Shared/Player/SpeedPitchMenu.xindex 8e5d1ae7..0cdcbb90 100644--- a/tweak/Sources/Shared/Player/SpeedPitchMenu.x+++ b/tweak/Sources/Shared/Player/SpeedPitchMenu.x@@ -528,10 +528,14 @@ static void watchMoreButton(UIView *button) {static SGMoreTapWatcher *watcher;if (!watcher) watcher = [SGMoreTapWatcher 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.+ // A control (Spotify's ⋯ is an Encore button, a UIControl) is watched through its own events alone, from+ // the touch down on: a recognizer on it, even one that cancels and delays nothing, took part in its touches+ // (a ripple on the ⋯ on the phone).if ([button isKindOfClass:UIControl.class]) {- [(UIControl *)button addTarget:watcher action:@selector(tapped) forControlEvents:UIControlEventTouchUpInside | UIControlEventPrimaryActionTriggered];+ // Touch down alone: a touch up after the ⋯ card has used the tap up would count a second time, for the+ // next sheet (the card's Sleep timer took the block that way on the phone).+ [(UIControl *)button addTarget:watcher action:@selector(tapped) forControlEvents:UIControlEventTouchDown];+ return;}UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:watcher action:@selector(tapped)];tap.cancelsTouchesInView = NO;@@ -577,6 +581,10 @@ static BOOL isPlayerMenu(UIViewController *menu) {return ours;}+void SGPlayerMenuMarkPlayers(void) {+ sg_moreTappedAt = CACurrentMediaTime();+}+BOOL SGPlayerMenuIsPlayers(UIViewController *menu) {return isPlayerMenu(menu);}