Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.
C
feat: redesigned player and artist page behind their own switches (work in progress)
Vojtěch Škopekbacc0df4be3a
diff --git a/tweak/Sources/Core/SGGlass.h b/tweak/Sources/Core/SGGlass.hindex cb97969c..c1ebee35 100644--- a/tweak/Sources/Core/SGGlass.h+++ b/tweak/Sources/Core/SGGlass.h@@ -1,6 +1,8 @@// Glass panes: one UIVisualEffectView per host, kept behind the host's own content.#import <UIKit/UIKit.h>+// UIGlassEffect made the only way that resolves its material, or a dark chrome blur before iOS 26.+UIVisualEffect *SGGlassEffect(void);UIVisualEffectView *SGGlassFor(UIView *host, const void *key);// Several panes on one host, addressed by index; panes past `count` are hidden by SGHideGlassFrom.UIVisualEffectView *SGGlassAt(UIView *host, NSUInteger index);diff --git a/tweak/Sources/Core/SGGlass.m b/tweak/Sources/Core/SGGlass.mindex 647763b8..5023d9bf 100644--- a/tweak/Sources/Core/SGGlass.m+++ b/tweak/Sources/Core/SGGlass.m@@ -23,14 +23,14 @@ void SGRememberCardColor(CGColorRef color) {// +effectWithStyle: is the only initialiser UIGlassEffect has; a bare -init leaves the material// unresolved and the pane renders as a plain blur, while the capsule shape, which is the view's// own property, still comes out right. Spotify's own Reprise glass builds its effect the same way.-static UIVisualEffect *glassEffect(void) {+UIVisualEffect *SGGlassEffect(void) {Class glass = NSClassFromString(@"UIGlassEffect");if ([glass respondsToSelector:@selector(effectWithStyle:)]) return [glass effectWithStyle:0];return [UIBlurEffect effectWithStyle:UIBlurEffectStyleSystemChromeMaterialDark];}static UIVisualEffectView *newPane(void) {- UIVisualEffectView *glass = [[UIVisualEffectView alloc] initWithEffect:glassEffect()];+ UIVisualEffectView *glass = [[UIVisualEffectView alloc] initWithEffect:SGGlassEffect()];glass.userInteractionEnabled = NO;// A pane goes in at index 0, but a host that rebuilds its content puts that in at index 0 too// and the pane would end up over it. Depth keeps a pane behind whatever the host draws.diff --git a/tweak/Sources/Features/Appearance/Repaint.x b/tweak/Sources/Features/Appearance/Repaint.xindex bbb8c205..95d2f218 100644--- a/tweak/Sources/Features/Appearance/Repaint.x+++ b/tweak/Sources/Features/Appearance/Repaint.x@@ -2,10 +2,12 @@// view is the now playing card from the album-colour paint.#import "Core/SGCore.h"#import "Appearance.h"+#import "Redesign/Kit/SGRRestyle.h"%hook CALayer- (void)setBackgroundColor:(CGColorRef)color {- if (color && (sg_nowPlayingRoot || sg_tabBarRoot || sg_lyricsCardRoot || sg_lyricsPageRoot || sg_homeRoot || sg_npvBackdropRoot)) {+ if (color && (sg_nowPlayingRoot || sg_tabBarRoot || sg_lyricsCardRoot || sg_lyricsPageRoot || sg_homeRoot || sg_npvBackdropRoot+ || SGRHasClearRoots())) {UIView *view = (UIView *)self.delegate;if ([view isKindOfClass:UIView.class] && view.layer == self && !SGKeepsColor(view)) {if (SGIsInside(view, sg_nowPlayingRoot)) {@@ -27,6 +29,9 @@// Home keeps its cards and its placeholders; only the base surface the gradient// of Home/HomeGradient.x sits behind goes.color = NULL;+ } else if (SGRHasClearRoots() && SGIsBaseSurface(color) && SGRInsideClearRoot(view)) {+ // A redesigned page paints its own field behind Spotify's surfaces (Redesign/Kit/SGRRestyle.h).+ color = NULL;}}}diff --git a/tweak/Sources/Features/Artist/Artist.x b/tweak/Sources/Features/Artist/Artist.xindex aa9af478..b24518bc 100644--- a/tweak/Sources/Features/Artist/Artist.x+++ b/tweak/Sources/Features/Artist/Artist.x@@ -9,9 +9,13 @@// Only the heading names the section, so the list remembers the heading above every cell it sizes// and a hidden section's cells all answer height 0, down to the next heading. The headings are// told apart by their English titles.+//+// While the artist page is redesigned (Redesign/Artist/) none of these hooks is installed, so the two+// never fight over the same views; with the redesign off they behave as they always did.#import <objc/runtime.h>#import <CoreImage/CoreImage.h>#import "Core/SGCore.h"+#import "Redesign/Kit/SGRedesign.h"#import "Artist.h"static BOOL onArtistPage(UIView *view) {@@ -177,6 +181,8 @@ static void applyPhotoFade(UIView *header) {[CATransaction commit];}+%group SGArtistLegacy+%hook _TtC35CreativeWorkPlatform_ImageHeaderKit15ImageHeaderView- (void)layoutSubviews {%orig;@@ -328,8 +334,11 @@ static BOOL collapsed(UICollectionViewCell *cell, NSIndexPath *path) {}%end+%end+%ctor {- %init;+ if (SGRedesignOn(@"artist")) return;+ %init(SGArtistLegacy);SGRequireClasses(@[@"_TtC35CreativeWorkPlatform_ImageHeaderKit15ImageHeaderView",@"_TtC12Element_List18CollectionViewCell",diff --git a/tweak/Sources/Features/Artist/ArtistSettings.m b/tweak/Sources/Features/Artist/ArtistSettings.mindex 0991cede..72570074 100644--- a/tweak/Sources/Features/Artist/ArtistSettings.m+++ b/tweak/Sources/Features/Artist/ArtistSettings.m@@ -1,5 +1,6 @@#import "Core/SGCore.h"#import "Settings/SGModPage.h"+#import "Redesign/Kit/SGRedesign.h"#import "Artist.h"UIViewController *SGArtistSettingsPage(void) {@@ -37,5 +38,8 @@ UIViewController *SGArtistSettingsPage(void) {SGFlagRow(@"Top collaborators", @"ios-creator-impl.is_top_collaborators_enabled"),SGFlagRow(@"Artist facts", @"ios-creator-impl.is_artist_facts_enabled"), ]),];+ // While the redesign has the page, these switches stand aside; the note says so and opens its page.+ SGModSection *note = SGRedesignNoteSection(@"artist");+ if (note) sections = [@[note] arrayByAddingObjectsFromArray:sections];return [[SGModPage alloc] initWithTitle:@"Artist" intro:nil sections:sections footer:nil];}diff --git a/tweak/Sources/Features/Declutter/Declutter.x b/tweak/Sources/Features/Declutter/Declutter.xindex 9b77a378..b6c51af8 100644--- a/tweak/Sources/Features/Declutter/Declutter.x+++ b/tweak/Sources/Features/Declutter/Declutter.x@@ -10,6 +10,7 @@// and the queue; track info ends with the add-to button.#import "Core/SGCore.h"#import "Declutter.h"+#import "Redesign/Kit/SGRedesign.h"#pragma mark - cards and sections@@ -47,8 +48,11 @@ static NSString *hiddenKeyFor(UICollectionViewCell *cell) {if ([v isKindOfClass:cell.class]) return nil;}NSString *names = nil;+ // The cards under a redesigned player are Redesign/Player/PlayerCards.x's.+ BOOL playerRedesigned = SGRedesignOn(@"player");for (size_t i = 0; i < sizeof(cards) / sizeof(cards[0]); i++) {if (!SGHidden(cards[i].key)) continue;+ if (playerRedesigned && [cards[i].page isEqualToString:@"NowPlaying_ScrollAPI"]) continue;if (!names) names = classNamesIn(cell);if ([names containsString:cards[i].page] && [names containsString:cards[i].marker]) return cards[i].key;}@@ -68,7 +72,7 @@ static NSString *hiddenKeyFor(UICollectionViewCell *cell) {}%end-#pragma mark - player buttons+#pragma mark - player buttons, lyrics under the artworkstatic BOOL vanish(UIView *view) {if (!view || view.alpha == 0) return NO;@@ -82,6 +86,10 @@ static void finish(UIViewController *unit, BOOL changed) {if (changed) [unit.viewIfLoaded setNeedsLayout];}+// The player's buttons and the lyric preview under the artwork, left to the player redesign+// (Redesign/Player/) while it is on.+%group PlayerButtons+%hook _TtC20NowPlaying_ModesImpl28PlaybackControlsElementsUnit- (void)viewDidLayoutSubviews {%orig;@@ -124,8 +132,6 @@ static void finish(UIViewController *unit, BOOL changed) {}%end-#pragma mark - lyrics under the artwork, Home filter pills-%hook _TtC22Lyrics_NPVContainerKit19LyricsContainerView- (void)setHidden:(BOOL)hidden {%orig(SGHidden(SGHideLyricsInline) ? YES : hidden);@@ -136,6 +142,10 @@ static void finish(UIViewController *unit, BOOL changed) {}%end+%end++#pragma mark - Home filter pills+%hook _TtC14Home_PillUIKit14PillScrollView- (void)didMoveToWindow {%orig;@@ -152,6 +162,7 @@ void SGSetPlayerLyricsOnly(BOOL on) {%ctor {%init;+ if (!SGRedesignOn(@"player")) %init(PlayerButtons);SGRequireClasses(@[@"_TtC12Element_List18CollectionViewCell",@"_TtC20NowPlaying_ModesImpl28PlaybackControlsElementsUnit",diff --git a/tweak/Sources/Features/Flags/Flags.x b/tweak/Sources/Features/Flags/Flags.xindex 53ce9b41..8fc0b5c3 100644--- a/tweak/Sources/Features/Flags/Flags.x+++ b/tweak/Sources/Features/Flags/Flags.x@@ -1,10 +1,12 @@// Spotify reads every remote-config flag once at startup through the configuration provider,-// keyed "component.property". An override from the Flags page wins; the Spotify's own Liquid-// Glass switch then forces the flags of Spotify's own newer design, which it ships switched off.+// keyed "component.property". An override from the Flags page wins; a redesigned screen then forces+// the flags its redesign is built on (Redesign/Kit/SGRedesign.h), and the Spotify's own Liquid+// Glass switch the flags of Spotify's own newer design, which it ships switched off.#import "Core/SGCore.h"#import "Flags.h"#import "Features/AdBlock/AdBlock.h"#import "Features/LyricsSources/LyricsSources.h"+#import "Redesign/Kit/SGRedesign.h"BOOL SGGlassOwnsFlag(NSString *key) {static NSSet<NSString *> *owned;@@ -26,6 +28,7 @@ BOOL SGGlassOwnsFlag(NSString *key) {static id forced(NSString *key) {id value = SGFlagOverride(key);+ if (!value) value = SGRedesignForcedFlag(key);if (!value && SGFlag(SGKeySpotifyGlass, NO) && SGGlassOwnsFlag(key)) value = @YES;if (!value && SGAdBlockForcesFlagOff(key)) value = @NO;if (!value) value = SGLyricsForcedFlag(key);diff --git a/tweak/Sources/Features/Navbar/Navbar.x b/tweak/Sources/Features/Navbar/Navbar.xindex 08734db2..23cfc945 100644--- a/tweak/Sources/Features/Navbar/Navbar.x+++ b/tweak/Sources/Features/Navbar/Navbar.x@@ -16,7 +16,7 @@#import "Core/SGCore.h"#import "Navbar.h"#import "Headers/SPTEncoreIconView.h"-#import "Headers/SPTLinkDispatcherImplementation.h"+#import "Redesign/Kit/SGRBridges.h"#import <objc/message.h>static const CGFloat kIconSize = 24;@@ -31,7 +31,6 @@ static char kCustomKey, kOrderKey;static CGRect sg_iconBox = {{0, kIconTop}, {kIconSize, kIconSize}};static CGRect sg_labelBox = {{0, kLabelTop}, {0, kLabelHeight}};-static __weak SPTLinkDispatcherImplementation *sg_linkDispatcher;static __weak UIView *sg_navbarRoot;// The bar's row of items, given its frames by placeRow after each of its own passes.static __weak UIStackView *sg_row;@@ -126,14 +125,10 @@ static UIView *iconView(NSString *name) {self.alpha = highlighted ? 0.5 : 1;}+// Through the link dispatcher the Kit keeps (Redesign/Kit/SGRBridges.x).- (void)open {NSURL *url = self.uri.length ? [NSURL URLWithString:self.uri] : nil;- SPTLinkDispatcherImplementation *dispatcher = sg_linkDispatcher;- if (!url || ![dispatcher respondsToSelector:@selector(navigateToURI:options:interactionID:)]) {- SGLog(@"navbar: cannot open %@, dispatcher %@", self.uri, dispatcher);- return;- }- [dispatcher navigateToURI:url options:0 interactionID:nil];+ if (!SGROpenURI(url)) SGLog(@"navbar: cannot open %@, dispatcher %@", self.uri, SGRLinkDispatcher());}@end@@ -367,18 +362,9 @@ void SGLogTabBarRow(UIView *tabBar) {}%end-// The dispatcher is a singleton the app builds at startup; this is the last call of its setup.-%hook SPTLinkDispatcherImplementation-- (void)setMainUILoaded:(BOOL)loaded {- %orig;- sg_linkDispatcher = (SPTLinkDispatcherImplementation *)self;-}-%end-%ctor {%init;SGRequireClasses(@[- @"SPTLinkDispatcherImplementation",@"SPTEncoreIcon",@"SPTEncoreIconView",@"SPTEncoreLabel",diff --git a/tweak/Sources/Features/NowPlaying/Lyrics.x b/tweak/Sources/Features/NowPlaying/Lyrics.xindex 4def5d32..605e3c00 100644--- a/tweak/Sources/Features/NowPlaying/Lyrics.x+++ b/tweak/Sources/Features/NowPlaying/Lyrics.x@@ -16,6 +16,7 @@// front of whatever that view still fills itself with, rather than behind the whole page.#import "Core/SGCore.h"#import "NowPlaying.h"+#import "Redesign/Kit/SGRedesign.h"static const CGFloat kCardRadius = 16;static char kCardGlassKey, kPageGlassKey;@@ -31,6 +32,10 @@ static UIView *cellAround(UIView *view) {return nil;}+// The card is a content surface of the player redesign's own (Redesign/Player/PlayerCards.x) while it+// is on, so its glass stands aside; the page below is not the player's and keeps it.+%group Card+%hook _TtC22Lyrics_CardElementImpl8CardView- (void)layoutSubviews {%orig;@@ -49,6 +54,8 @@ static UIView *cellAround(UIView *view) {}%end+%end+#pragma mark - the expanded page// Up to the presentation: the template views in between paint themselves opaque once, at setup.@@ -90,6 +97,7 @@ static UIView *clearAncestors(UIView *view) {%ctor {%init;+ if (!SGRedesignOn(@"player")) %init(Card);SGRequireClasses(@[@"_TtC22Lyrics_CardElementImpl8CardView",@"_TtC12Element_List18CollectionViewCell",diff --git a/tweak/Sources/Features/NowPlaying/NowPlayingSettings.m b/tweak/Sources/Features/NowPlaying/NowPlayingSettings.mindex 272ee29c..4b556110 100644--- a/tweak/Sources/Features/NowPlaying/NowPlayingSettings.m+++ b/tweak/Sources/Features/NowPlaying/NowPlayingSettings.m@@ -7,6 +7,7 @@#import "Features/Karaoke/Karaoke.h"#import "Features/LockScreenLyrics/LockScreenLyrics.h"#import "Features/LyricsSources/LyricsSources.h"+#import "Redesign/Kit/SGRedesign.h"static UIViewController *nowPlayingBarPage(void) {return [[SGModPage alloc] initWithTitle:@"Now playing bar" intro:SGRestartNote sections:@[@@ -105,7 +106,7 @@ UIViewController *SGNowPlayingSettingsPage(void) {return SGFlag(SGKeyArtistBlock, NO) ? @(SGBlockedArtists().count).stringValue : @"Off";};- return [[SGModPage alloc] initWithTitle:@"Player" intro:@"Changes apply after you restart Spotify. Gestures and Blocked artists apply straight away." sections:@[+ NSArray<SGModSection *> *sections = @[SGSection(nil, @[SGWithSymbol(SGPageRow(@"Gestures", ^UIViewController *{ return SGGesturesSettingsPage(); }), @"hand.tap"),SGWithSymbol(SGPageRow(@"Lyrics", ^UIViewController *{ return lyricsPage(); }), @"quote.bubble"),@@ -143,5 +144,9 @@ UIViewController *SGNowPlayingSettingsPage(void) {SGHideRow(@"Share", nil, SGHideShare),SGHideRow(@"Connect to a device", nil, SGHideConnect),]),- ] footer:nil];+ ];+ // While the player is redesigned the player screen, card and button rows below don't apply.+ SGModSection *note = SGRedesignNoteSection(@"player");+ if (note) sections = [@[note] arrayByAddingObjectsFromArray:sections];+ return [[SGModPage alloc] initWithTitle:@"Player" intro:@"Changes apply after you restart Spotify. Gestures and Blocked artists apply straight away." sections:sections footer:nil];}diff --git a/tweak/Sources/Features/NowPlaying/Player.x b/tweak/Sources/Features/NowPlaying/Player.xindex 86db38e9..84c044a8 100644--- a/tweak/Sources/Features/NowPlaying/Player.x+++ b/tweak/Sources/Features/NowPlaying/Player.x@@ -23,6 +23,7 @@#import "Core/SGCore.h"#import "NowPlaying.h"#import "Features/Appearance/Appearance.h"+#import "Redesign/Kit/SGRedesign.h"static const CGFloat kButtonMin = 36, kButtonMax = 48;static const CGFloat kArtRadius = 12;@@ -192,6 +193,8 @@ static UIFont *timeFont(void) {%end%ctor {+ // The player redesign (Redesign/Player/) owns this screen while it is on.+ if (SGRedesignOn(@"player")) return;%init;SGRequireClasses(@[@"_TtC20NowPlaying_ModesImpl18HeaderElementsUnit",diff --git a/tweak/Sources/Headers/SPTPlayer.h b/tweak/Sources/Headers/SPTPlayer.hindex e8fd214a..42eb0d69 100644--- a/tweak/Sources/Headers/SPTPlayer.h+++ b/tweak/Sources/Headers/SPTPlayer.h@@ -11,9 +11,17 @@@property (nonatomic, readonly) NSDictionary<NSString *, NSString *> *metadata;@end+@interface SPTPlayerOptions : NSObject+@property (nonatomic, readonly) BOOL shufflingContext;+@end+@interface SPTPlayerState : NSObject@property (nonatomic, readonly) SPTPlayerTrack *track;+@property (nonatomic, readonly) id contextURI;+@property (nonatomic, readonly) SPTPlayerOptions *options;@property (nonatomic, readonly) BOOL isPaused;+@property (nonatomic, readonly) BOOL isPlaying;+@property (nonatomic, readonly) BOOL isLoading;// Seconds. position runs on from positionAsOfTimestamp by the time elapsed since the state was made.@property (nonatomic, readonly) double position;@property (nonatomic, readonly) double positionAsOfTimestamp;@@ -24,6 +32,7 @@@protocol SPTPlayer <NSObject>@property (nonatomic, readonly) SPTPlayerState *state;+- (void)addPlayerObserver:(id)observer;- (void)skipToNextTrack;- (void)seekTo:(double)seconds;@enddiff --git a/tweak/Sources/Redesign/Artist/ArtistList.x b/tweak/Sources/Redesign/Artist/ArtistList.xnew file mode 100644index 00000000..8d0c9ab7--- /dev/null+++ b/tweak/Sources/Redesign/Artist/ArtistList.x@@ -0,0 +1,485 @@+// Artist page redesign, the Music list (RedesignArtist.h): Spotify's own list with only the music left on+// it, under the Kit's section headers, its rows restyled for the field.+//+// Trees (trees/clean/artist/01-13.txt): every row of the Music list is an Element_List CollectionViewCell+// holding a Creator_CreatorPageImpl LCR_Structure element, NoData or NeedsData by its content view's class.+// Spotify's own accessibility identifiers say what a cell is, in any language:+// Components.UI.SectionHeadingHome a section's heading+// Components.UI.LikedSongs.Row songs you liked (and its 0pt twin, songs available offline)+// Components.UI.RetrievalRowElementUI_Loaded a popular track, the sixth with the See more footer, or a+// popular release+// Components.UI.ListSectionFooter.Button See discography+// Components.UI.UpcomingReleaseRow the release countdown+// Components.UI.RetrievalRowLoadingElementUI the loading row standing in for one of those+// Components.UI.PinnedItem*, CreatorBiographyCard*, MusicVideoShelfHeader*, Music-Videos.*, HomeCard+// artist pick, about, music videos, and the carousels of+// featuring, artist playlists, fans also like and appears on+// and a NoData cell with no identifier and nothing in it is the spacer between two sections. What is not+// music answers height 0 from preferredLayoutAttributesFittingAttributes:, as Features/Artist/Artist.x+// proved, and a section no rule knows is left out.+//+// A heading comes right before the cell of its section (01.txt: Artist pick at 468.7, its card at 505.3) but+// is sized before that cell exists. So a heading stays when it is the list's first (Popular) or the cell+// under it is already known to be music, and otherwise waits collapsed; sizing the cell under it settles+// the heading, which is sized again when the answer changed. What a heading's section turned out to be is+// remembered by its title for the rest of the launch, so the next artist page in the same language has+// the answer before the cell under it is sized. The answer still comes from the cells, never from the words.+#import <objc/runtime.h>+#import "Core/SGCore.h"+#import "Redesign/Kit/SGRKit.h"+#import "RedesignArtist.h"++typedef NS_ENUM(NSInteger, SGArtistCell) {+ SGArtistCellPending, // a NeedsData cell with nothing in it yet: Spotify's height until it fills+ SGArtistCellHeading,+ SGArtistCellMusic,+ SGArtistCellLiked,+ SGArtistCellLoading,+ SGArtistCellSpacer,+ SGArtistCellOther, // everything else, collapsed+};++static Class sg_listViewClass, sg_headingButtonClass, sg_gradientClass;+static BOOL sg_hideLiked;+static NSMutableDictionary<NSString *, NSNumber *> *sg_learntHeadings; // title: kept or not+static char kListKey, kFadedRowKey, kHiddenGradientKey;++// A cell's walk ends at its first telling identifier, a few views down; this bounds one that has none.+static const NSUInteger kWalkLimit = 160;+static NSString *const kFadeName = @"spotifyglass.artistFooterFade";++@interface SGArtistWeak : NSObject+@property (nonatomic, weak) UIView *view;+@end+@implementation SGArtistWeak+@end++static UIView *weakGet(id object, const void *key) {+ return ((SGArtistWeak *)objc_getAssociatedObject(object, key)).view;+}++static void weakSet(id object, const void *key, UIView *view) {+ SGArtistWeak *box = nil;+ if (view) {+ box = [SGArtistWeak new];+ box.view = view;+ }+ objc_setAssociatedObject(object, key, box, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+}++#pragma mark - what a cell is++static SGArtistCell kindOfIdentifier(NSString *identifier) {+ static NSSet<NSString *> *music;+ static NSArray<NSString *> *other;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ // EmptyReleasesSectionElement is in the binary's strings only, for an artist with no releases.+ music = [NSSet setWithArray:@[@"Components.UI.RetrievalRowElementUI_Loaded", @"Components.UI.ListSectionFooter.Button",+ @"Components.UI.UpcomingReleaseRow", @"Components.UI.EmptyReleasesSectionElement"]];+ other = @[@"Components.UI.PinnedItem", @"Components.UI.CreatorBiographyCard", @"Components.UI.MusicVideoShelfHeader",+ @"Music-Videos.", @"Components.UI.HomeCard", @"Merch."];+ });+ if ([identifier isEqualToString:@"Components.UI.SectionHeadingHome"]) return SGArtistCellHeading;+ if ([identifier isEqualToString:@"Components.UI.LikedSongs.Row"]) return SGArtistCellLiked;+ if ([music containsObject:identifier]) return SGArtistCellMusic;+ if ([identifier isEqualToString:@"Components.UI.RetrievalRowLoadingElementUI"]) return SGArtistCellLoading;+ for (NSString *prefix in other) {+ if ([identifier hasPrefix:prefix]) return SGArtistCellOther;+ }+ return SGArtistCellPending;+}++// Identifiers every kind of cell carries, which say nothing about the section.+static BOOL isGeneric(NSString *identifier) {+ return [identifier hasPrefix:@"Encore."] || [identifier hasPrefix:@"EncoreConsumerMobile.View."] || [identifier hasSuffix:@"-internal"];+}++// Depth first, stopping at the first identifier with a rule; `unknown` gets the first other identifier of a+// cell no rule decided.+static SGArtistCell classify(UICollectionViewCell *cell, NSString **unknown) {+ UIView *content = cell.contentView;+ // The state is in the element content view's class (01.txt: ElementContentView<…9NeedsData>), which is+ // the cell's only child and so its content view (a content configuration's view); its first child+ // too, should UIKit keep a content view of its own around it.+ BOOL needsData = [NSStringFromClass(content.class) containsString:@"9NeedsData"]+ || [NSStringFromClass(content.subviews.firstObject.class) containsString:@"9NeedsData"];+ NSMutableArray<UIView *> *stack = [NSMutableArray arrayWithObject:content];+ NSUInteger visited = 0;+ BOOL nested = NO;+ NSString *first = nil;+ while (stack.count && visited < kWalkLimit) {+ UIView *view = stack.lastObject;+ [stack removeLastObject];+ // The Kit's own header, left in a heading cell Spotify reuses for another row.+ if ([view isKindOfClass:SGRSectionHeader.class]) continue;+ visited++;+ NSString *identifier = view.accessibilityIdentifier;+ if (identifier.length) {+ SGArtistCell kind = kindOfIdentifier(identifier);+ if (kind != SGArtistCellPending) return kind;+ if (!first && !isGeneric(identifier)) first = identifier;+ }+ // A carousel's cards are a list of their own, and the carousel is not music.+ if ([view isKindOfClass:UICollectionView.class]) {+ nested = YES;+ continue;+ }+ for (UIView *sub in view.subviews.reverseObjectEnumerator) [stack addObject:sub];+ }+ if (unknown) *unknown = first;+ if (nested || first) return SGArtistCellOther;+ if (needsData) return SGArtistCellPending;+ // Element content view > element view > one bare UIView (01.txt: the 16pt cells), and one more level+ // should the content view wrap the element content view.+ return visited <= 4 ? SGArtistCellSpacer : SGArtistCellOther;+}++// Trees (01.txt): the title is the accessibility label of the heading's NoIntrinsicContentSizeButton.+static NSString *headingTitleIn(UIView *root) {+ __block NSString *title = nil;+ if (!root || !sg_headingButtonClass) return nil;+ SGForEachView(root, ^(UIView *view) {+ if (!title && [view isKindOfClass:sg_headingButtonClass] && view.accessibilityLabel.length) title = view.accessibilityLabel;+ });+ return title;+}++static BOOL settles(SGArtistCell kind) {+ return kind != SGArtistCellPending && kind != SGArtistCellLoading;+}++// The Kit's header draws its title 24pt down in title 2 bold (capped at XXXL); the heading gets that and+// a little room under it, never less than 56.+static CGFloat headingHeight(void) {+ UIFont *font = SGRFont(UIFontTextStyleTitle2, UIFontWeightBold, UIContentSizeCategoryExtraExtraExtraLarge);+ return MAX(56, ceil(24 + font.lineHeight + SGRGrid / 2));+}++static void logUnknown(NSString *identifier, CGFloat height) {+ static NSMutableSet<NSString *> *seen;+ if (!seen) seen = [NSMutableSet set];+ if (seen.count >= 12 || [seen containsObject:identifier]) return;+ [seen addObject:identifier];+ SGLog(@"artist: collapsed a cell no rule knows, first identifier %@, %.0f tall", identifier, height);+}++#pragma mark - the list++@interface SGArtistList : NSObject+@property (nonatomic, weak) UICollectionView *view;+- (CGFloat)heightOf:(UICollectionViewCell *)cell at:(NSIndexPath *)path fitting:(CGFloat)height;+- (void)willDisplay:(UICollectionViewCell *)cell at:(NSIndexPath *)path;+@end++@implementation SGArtistList {+ NSMutableDictionary<NSIndexPath *, NSNumber *> *_kinds; // what each cell sized so far is+ NSMutableDictionary<NSIndexPath *, NSNumber *> *_settled; // heading: kept or not, by the cell under it+ NSMutableDictionary<NSIndexPath *, NSNumber *> *_answered; // heading: kept or not, as last sized+ NSMutableDictionary<NSIndexPath *, NSString *> *_titles; // heading: its title+ NSUInteger _corrections;+}++- (instancetype)init {+ if (!(self = [super init])) return nil;+ _kinds = [NSMutableDictionary dictionary];+ _settled = [NSMutableDictionary dictionary];+ _answered = [NSMutableDictionary dictionary];+ _titles = [NSMutableDictionary dictionary];+ return self;+}++- (CGFloat)heightOf:(UICollectionViewCell *)cell at:(NSIndexPath *)path fitting:(CGFloat)height {+ NSString *unknown = nil;+ SGArtistCell kind = classify(cell, &unknown);+ [self record:kind at:path];+ // See more reconfigures its cell in place (the footer goes, the row stays), which sizes the cell again+ // but need not display it again.+ [self fadeFooterOf:cell music:kind == SGArtistCellMusic retry:NO];+ switch (kind) {+ case SGArtistCellHeading: {+ NSString *title = headingTitleIn(cell.contentView);+ _titles[path] = title;+ BOOL kept = [self headingKeptAt:path title:title];+ _answered[path] = @(kept);+ return kept ? headingHeight() : 0;+ }+ case SGArtistCellMusic:+ [self settleHeadingAbove:path kept:YES];+ return height;+ case SGArtistCellLiked:+ return sg_hideLiked ? 0 : height;+ case SGArtistCellOther:+ [self settleHeadingAbove:path kept:NO];+ if (unknown) logUnknown(unknown, height);+ return 0;+ case SGArtistCellSpacer:+ return 0;+ case SGArtistCellPending:+ case SGArtistCellLoading:+ return height;+ }+ return height;+}++- (void)record:(SGArtistCell)kind at:(NSIndexPath *)path {+ NSNumber *before = _kinds[path];+ _kinds[path] = @(kind);+ if (!before || before.integerValue == kind || !settles(before.integerValue) || !settles(kind)) return;+ // Something else sits at this index now (See more put five tracks in): what was learnt about it and+ // below it is stale.+ for (NSMutableDictionary<NSIndexPath *, id> *map in @[_kinds, _settled, _titles]) {+ NSMutableArray<NSIndexPath *> *stale = [NSMutableArray array];+ for (NSIndexPath *key in map) {+ if (key.section == path.section && (key.item > path.item || (map != (id)_kinds && key.item == path.item))) [stale addObject:key];+ }+ [map removeObjectsForKeys:stale];+ }+}++- (BOOL)headingKeptAt:(NSIndexPath *)path title:(NSString *)title {+ NSNumber *settled = _settled[path];+ if (settled) return settled.boolValue;+ NSNumber *below = _kinds[[NSIndexPath indexPathForItem:path.item + 1 inSection:path.section]];+ if (below && below.integerValue == SGArtistCellMusic) return YES;+ if (below && below.integerValue == SGArtistCellOther) return NO;+ NSNumber *learnt = title ? sg_learntHeadings[title] : nil;+ if (learnt) return learnt.boolValue;+ for (NSIndexPath *key in _kinds) {+ if (key.section == path.section && key.item < path.item && _kinds[key].integerValue == SGArtistCellHeading) return NO;+ }+ return YES;+}++- (void)settleHeadingAbove:(NSIndexPath *)path kept:(BOOL)kept {+ if (path.item == 0) return;+ NSIndexPath *above = [NSIndexPath indexPathForItem:path.item - 1 inSection:path.section];+ NSNumber *kind = _kinds[above];+ if (!kind || kind.integerValue != SGArtistCellHeading) return;+ _settled[above] = @(kept);+ NSString *title = _titles[above];+ if (title) sg_learntHeadings[title] = @(kept);+ NSNumber *answered = _answered[above];+ if (!answered || answered.boolValue == kept) return;+ [self resizeItemAt:above kept:kept];+}++// Self-sizing invalidation (iOS 16) sizes a shown cell again; a heading off screen is sized again when it+// scrolls in, and its layout item is invalidated meanwhile. After the current layout pass, not inside it.+- (void)resizeItemAt:(NSIndexPath *)path kept:(BOOL)kept {+ __weak UICollectionView *weakView = self.view;+ BOOL logged = _corrections++ < 3;+ dispatch_async(dispatch_get_main_queue(), ^{+ UICollectionView *view = weakView;+ if (!view || path.section >= view.numberOfSections || path.item >= [view numberOfItemsInSection:path.section]) return;+ UICollectionViewCell *cell = [view cellForItemAtIndexPath:path];+ if (logged) SGLog(@"artist: heading %ld %@ by the cell under it, %@", (long)path.item, kept ? @"kept" : @"collapsed", cell ? @"on screen" : @"off screen");+ if (cell && view.selfSizingInvalidation != UICollectionViewSelfSizingInvalidationDisabled) {+ [cell invalidateIntrinsicContentSize];+ return;+ }+ UICollectionViewLayout *layout = view.collectionViewLayout;+ UICollectionViewLayoutInvalidationContext *context = [[layout.class invalidationContextClass] new];+ [context invalidateItemsAtIndexPaths:@[path]];+ [layout invalidateLayoutWithContext:context];+ });+}++- (void)logSummarySoon {+ __weak SGArtistList *weakSelf = self;+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ SGArtistList *list = weakSelf;+ if (!list) return;+ NSUInteger counts[SGArtistCellOther + 1] = {0}, kept = 0;+ for (NSNumber *kind in list->_kinds.allValues) {+ if (kind.integerValue >= 0 && kind.integerValue <= SGArtistCellOther) counts[kind.integerValue]++;+ }+ for (NSNumber *answer in list->_answered.allValues) kept += answer.boolValue;+ SGLog(@"artist: list after 2 s: heading %lu (kept %lu), music %lu, liked %lu, loading %lu, pending %lu, spacer %lu, collapsed %lu, corrections %lu",+ (unsigned long)counts[SGArtistCellHeading], (unsigned long)kept, (unsigned long)counts[SGArtistCellMusic],+ (unsigned long)counts[SGArtistCellLiked], (unsigned long)counts[SGArtistCellLoading], (unsigned long)counts[SGArtistCellPending],+ (unsigned long)counts[SGArtistCellSpacer], (unsigned long)counts[SGArtistCellOther], (unsigned long)list->_corrections);+ });+}++#pragma mark - restyle++- (void)willDisplay:(UICollectionViewCell *)cell at:(NSIndexPath *)path {+ UICollectionView *view = self.view;+ if (SGIsBaseSurface(view.layer.backgroundColor)) view.layer.backgroundColor = NULL;+ SGArtistCell kind = classify(cell, NULL);+ if (kind == SGArtistCellHeading) {+ [self dressHeading:cell];+ // A heading settled while it had no visible cell (sized ahead of the scroll, then the row under it)+ // keeps its old size in the layout; the cell it finally shows in is sized again.+ NSNumber *settled = path ? _settled[path] : nil, *answered = path ? _answered[path] : nil;+ if (settled && answered && settled.boolValue != answered.boolValue) [self resizeItemAt:path kept:settled.boolValue];+ } else {+ for (UIView *sub in cell.contentView.subviews) {+ if ([sub isKindOfClass:SGRSectionHeader.class]) sub.hidden = YES;+ }+ if (kind != SGArtistCellSpacer && kind != SGArtistCellOther) SGRStyleSpotifyCell(cell.contentView);+ }+ [self fadeFooterOf:cell music:kind == SGArtistCellMusic retry:YES];+}++static BOOL shownIn(UIView *view, UIView *root) {+ if (CGRectGetWidth(view.bounds) <= 0) return NO;+ for (UIView *v = view; v && v != root; v = v.superview) {+ if (v.hidden) return NO;+ }+ return YES;+}++// Trees (01.txt): a section with somewhere to go shows Show all (id=Components.UI.NavigationButtonHome, an Encore tertiary+// button) in a passthrough view that is hidden otherwise (Popular).+- (void)dressHeading:(UICollectionViewCell *)cell {+ static char headingKey, showAllKey;+ UIView *spotify = SGRFindByIdentifier(cell.contentView, @"Components.UI.SectionHeadingHome", &headingKey);+ NSString *title = headingTitleIn(spotify);+ UIView *showAll = SGRFindByIdentifier(cell.contentView, @"Components.UI.NavigationButtonHome", &showAllKey);+ UIControl *target = [showAll isKindOfClass:UIControl.class] && shownIn(showAll, cell) ? (UIControl *)showAll : nil;+ if (spotify.alpha != 0) spotify.alpha = 0;+ if (spotify && !spotify.accessibilityElementsHidden) spotify.accessibilityElementsHidden = YES;+ SGRSectionHeader *header = [SGRSectionHeader headerInCell:cell title:title ?: @"" target:target];+ header.hidden = NO;+ static dispatch_once_t once;+ dispatch_once(&once, ^{ SGLog(@"artist: section header \"%@\", show all %@", title, target ? NSStringFromClass(target.class) : @"none"); });+}++// The See more cell's gradient, found by level (01.txt, 08.txt: element content view > element view >+// clipping view > view > [the row element, GradientView, the footer element], four levels down); no+// other cell of the Music list carries one that high up, the biography card's is lower and collapsed.+static UIView *footerGradientIn(UIView *content) {+ NSArray<UIView *> *level = content ? @[content] : @[];+ for (NSUInteger depth = 0; depth <= 5 && level.count; depth++) {+ NSMutableArray<UIView *> *next = [NSMutableArray array];+ for (UIView *view in level) {+ if ([view isKindOfClass:sg_gradientClass]) return view;+ [next addObjectsFromArray:view.subviews];+ }+ level = next;+ }+ return nil;+}++// See more closes Popular with the sixth track fading out under the button (01.txt: the 88pt cell, the row+// element, a GradientView over all of it, then the footer element). The gradient is Spotify's base grey,+// a band on the field, so it goes and the row fades through a mask instead; both are put back when the+// cell comes back as anything else. A cell not laid out yet has a row of no size, so the mask is sized+// once more after the layout pass.+- (void)fadeFooterOf:(UICollectionViewCell *)cell music:(BOOL)music retry:(BOOL)retry {+ UIView *row = nil, *gradient = music && sg_gradientClass ? footerGradientIn(cell.contentView) : nil;+ NSArray<UIView *> *siblings = gradient.superview.subviews;+ NSUInteger index = gradient ? [siblings indexOfObjectIdenticalTo:gradient] : NSNotFound;+ if (index != NSNotFound && index > 0) row = siblings[index - 1];+ if (!row) gradient = nil;+ UIView *fadedRow = weakGet(cell, &kFadedRowKey), *hiddenGradient = weakGet(cell, &kHiddenGradientKey);+ if (fadedRow && fadedRow != row && [fadedRow.layer.mask.name isEqualToString:kFadeName]) fadedRow.layer.mask = nil;+ if (hiddenGradient && hiddenGradient != gradient && hiddenGradient.alpha == 0) hiddenGradient.alpha = 1;+ if (!row || !gradient) {+ if (fadedRow) weakSet(cell, &kFadedRowKey, nil);+ if (hiddenGradient) weakSet(cell, &kHiddenGradientKey, nil);+ return;+ }+ if (gradient.alpha != 0) gradient.alpha = 0;+ if (hiddenGradient != gradient) weakSet(cell, &kHiddenGradientKey, gradient);+ if (CGRectGetHeight(row.bounds) <= 0) {+ if (!retry) return;+ __weak SGArtistList *weakSelf = self;+ __weak UICollectionViewCell *weakCell = cell;+ dispatch_async(dispatch_get_main_queue(), ^{+ UICollectionViewCell *later = weakCell;+ if (later) [weakSelf fadeFooterOf:later music:classify(later, NULL) == SGArtistCellMusic retry:NO];+ });+ return;+ }+ CAGradientLayer *mask = [row.layer.mask.name isEqualToString:kFadeName] ? (CAGradientLayer *)row.layer.mask : nil;+ [CATransaction begin];+ [CATransaction setDisableActions:YES];+ if (!mask) {+ mask = [CAGradientLayer layer];+ mask.name = kFadeName;+ mask.colors = @[(id)UIColor.blackColor.CGColor, (id)UIColor.clearColor.CGColor];+ mask.locations = @[@0.2, @1];+ row.layer.mask = mask;+ }+ mask.frame = row.layer.bounds;+ [CATransaction commit];+ if (fadedRow != row) weakSet(cell, &kFadedRowKey, row);+ static dispatch_once_t once;+ dispatch_once(&once, ^{ SGLog(@"artist: See more row faded, Spotify's gradient hidden"); });+}++@end++// The list of a redesigned artist page's Music tab, kept on its collection view; NSNull for any other list.+static SGArtistList *listOf(UICollectionView *view) {+ if (![view isKindOfClass:UICollectionView.class]) return nil;+ id known = objc_getAssociatedObject(view, &kListKey);+ if (known) return known == NSNull.null ? nil : known;+ UIView *listView = view.superview;+ // Not in its list view yet: asked again, not written off.+ if (!listView) return nil;+ // Only the first page of the tabs is Music (01.txt); a carousel inside a cell and the other tabs are left alone.+ if (![listView isKindOfClass:sg_listViewClass]) {+ objc_setAssociatedObject(view, &kListKey, NSNull.null, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ return nil;+ }+ BOOL pending = NO;+ SGArtistPage *page = SGArtistPageOf(listView, &pending);+ if (!page || listView.superview.subviews.firstObject != listView) {+ if (!pending && view.window) objc_setAssociatedObject(view, &kListKey, NSNull.null, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ return nil;+ }+ SGArtistList *list = [SGArtistList new];+ list.view = view;+ objc_setAssociatedObject(view, &kListKey, list, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ if (SGIsBaseSurface(view.layer.backgroundColor)) view.layer.backgroundColor = NULL;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ SGLog(@"artist: Music list found, %lu pages beside it", (unsigned long)listView.superview.subviews.count);+ [list logSummarySoon];+ });+ return list;+}++%hook _TtC12Element_List18CollectionViewCell+- (UICollectionViewLayoutAttributes *)preferredLayoutAttributesFittingAttributes:(UICollectionViewLayoutAttributes *)attributes {+ UICollectionViewLayoutAttributes *result = %orig;+ UICollectionViewCell *cell = (UICollectionViewCell *)self;+ NSIndexPath *path = attributes.indexPath;+ SGArtistList *list = path ? listOf((UICollectionView *)cell.superview) : nil;+ if (!list) return result;+ CGFloat height = [list heightOf:cell at:path fitting:result.size.height];+ if (height == result.size.height) return result;+ result.size = CGSizeMake(result.size.width, height);+ if (height == 0) cell.clipsToBounds = YES;+ static dispatch_once_t once;+ dispatch_once(&once, ^{ SGLog(@"artist: first cell resized, %.0f tall", height); });+ return result;+}+%end++%hook _TtC32CreativeWorkPlatform_TemplateKit28CreativeWorkTemplateListView+- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {+ %orig;+ [listOf(collectionView) willDisplay:cell at:indexPath];+}+%end++%ctor {+ if (!SGRedesignOn(@"artist")) return;+ sg_listViewClass = NSClassFromString(@"_TtC32CreativeWorkPlatform_TemplateKit28CreativeWorkTemplateListView");+ sg_headingButtonClass = NSClassFromString(@"_TtCOOOE11Home_ECMKitO19LegacyUI_ECMCoreKit10Components18SectionHeadingHome2UI7Private28NoIntrinsicContentSizeButton");+ sg_gradientClass = NSClassFromString(@"_TtC19LegacyUI_ECMCoreKit12GradientView");+ sg_hideLiked = SGHidden(SGKeyRedesignArtistHideLikedSongs);+ sg_learntHeadings = [NSMutableDictionary dictionary];+ %init;+ SGRequireClasses(@[+ @"_TtC12Element_List18CollectionViewCell",+ @"_TtC32CreativeWorkPlatform_TemplateKit28CreativeWorkTemplateListView",+ @"_TtCOOOE11Home_ECMKitO19LegacyUI_ECMCoreKit10Components18SectionHeadingHome2UI7Private28NoIntrinsicContentSizeButton",+ @"_TtC19LegacyUI_ECMCoreKit12GradientView",+ ]);+}diff --git a/tweak/Sources/Redesign/Artist/ArtistPage.x b/tweak/Sources/Redesign/Artist/ArtistPage.xnew file mode 100644index 00000000..f304f467--- /dev/null+++ b/tweak/Sources/Redesign/Artist/ArtistPage.x@@ -0,0 +1,534 @@+// Artist page redesign, the page (RedesignArtist.h): finds a redesigned artist page, lays the Kit's field+// behind it, puts the Kit's hero over Spotify's header and takes the tab strip away.+//+// Trees (trees/clean/artist/01.txt): LoadableTemplateViewController's view holds TemplateView+// (id=creator-page), and TemplateView the tab layout: an overlay scroll view that takes the pan+// (id=PCFFTabLayoutViewController.overlayScrollView) and over it the container scroll view+// (id=PCFFTabLayoutViewController.containerScrollView), whose stack holds the HeaderContainer (504 tall,+// 568 with a pre-save row under the buttons) and the tabs: the strip (id=Components.UI.TabsSectionHeading,+// 44 tall) over a paging scroll view of one list per tab. Scrolling down, the container stops at the+// header's height less 100 (02.txt: 468 of 568, 09.txt: 404 of 504) and Spotify keeps a 100pt band of+// its header pinned under the navigation bar while the list scrolls on.+//+// The page's URI comes from its hosting controller, MusicAppPageHostingViewController, a subclass of+// IdentifiedPageHostingViewController (objc-meta-Spotify.txt:1406777), whose spt_pageURI+// (objc-methods.txt:74510) SGRPageURI reads; an author's page is the same template with another URI.+//+// Spotify's header is ImageHeaderView: the photo (id=Components.Header.UI.ArtworkImage.ImageView holding an+// EncoreImageView, a UIImageView), the name (id=Encore.AdaptiveTitle around a CoreLabel), the listeners+// (id=Components.Header.UI.Metadata-internal), the explore deck of videos, and the buttons: Follow+// (id=Curation.FollowButtonElementKit.FollowButton, an Encore button), Shuffle (id=Components.UI.ShuffleButton,+// a UIButton whose 4pt green dot shows while shuffle is on) and Play (id=header-play-button, a PlayButtonView+// whose uiButtonTapped is its own action, objc-methods.txt:68122). It turns invisible and the hero lies over+// it in the HeaderContainer, so the hero scrolls with the page and Spotify's controls keep working under+// the glass buttons that fire them.+#import <objc/runtime.h>+#import "Core/SGCore.h"+#import "Settings/SGModPage.h"+#import "Redesign/Kit/SGRKit.h"+#import "RedesignArtist.h"++// The band of Spotify's header left pinned under the navigation bar (02.txt, 09.txt).+static const CGFloat kPinnedHeader = 100;++static Class sg_templateClass, sg_imageHeaderClass;+static char kPageKey, kArtworkContext;++@protocol SGArtistPlayButton+- (void)uiButtonTapped;+@end++static NSString *labelTextIn(UIView *root) {+ __block NSString *text = nil;+ if (!root) return nil;+ SGForEachView(root, ^(UIView *view) {+ if (!text && [view isKindOfClass:UILabel.class] && ((UILabel *)view).text.length) text = ((UILabel *)view).text;+ });+ return text;+}++static UIButton *buttonIn(UIView *root) {+ __block UIButton *button = nil;+ if (!root) return nil;+ SGForEachView(root, ^(UIView *view) {+ if (!button && [view isKindOfClass:UIButton.class]) button = (UIButton *)view;+ });+ return button;+}++// The shuffle button's dot (01.txt: a 4x4 UIView, hidden while shuffle is off).+static BOOL shuffleDotShown(UIView *shuffle) {+ for (UIView *view in shuffle.subviews) {+ CGFloat width = CGRectGetWidth(view.bounds);+ if (width > 0 && width <= 6 && ![view isKindOfClass:UIImageView.class]) return !view.hidden && view.alpha > 0.01;+ }+ return NO;+}++// A tap on one of Spotify's controls: its registered action, else its own VoiceOver activation, which an+// Encore control that reads touches through a gesture recognizer still answers.+static BOOL fire(UIControl *control) {+ if (!control) return NO;+ return SGRFire(control) || [control accessibilityActivate];+}++@interface SGArtistPage () <SGRPlayerStateObserver>+- (instancetype)initWithURI:(NSString *)uri template:(UIView *)template;+- (void)templateDidLayout:(UIView *)template;+- (void)headerContainerDidLayout:(UIView *)container;+- (void)stockHeaderDidLayout:(UIView *)header;+- (BOOL)hideTabsIn:(UIView *)root;+@end++@implementation SGArtistPage {+ SGRArtworkField *_field;+ SGRHeroHeader *_hero;+ SGRGlassButton *_shuffle, *_play, *_follow;+ __weak UIScrollView *_container, *_overlay;+ __weak UIImageView *_artworkView;+ __weak UIView *_stockHeader, *_playControl;+ __weak UIControl *_shuffleControl, *_followControl;+ UIImage *_image;+ CGFloat _containerY, _overlayY;+ CFTimeInterval _lastMirror;+ NSUInteger _missedReads;+ BOOL _observing, _tabsHidden, _mirrorScheduled;+}++- (instancetype)initWithURI:(NSString *)uri template:(UIView *)template {+ if (!(self = [super init])) return nil;+ _uri = [uri copy];+ _field = [[SGRArtworkField alloc] initWithFrame:template.bounds];+ _field.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;+ _field.userInteractionEnabled = NO;+ [template insertSubview:_field atIndex:0];+ // Spotify paints the page, its lists and its rows in its base grey (#121212); inside the template it+ // is cleared now and whenever it is painted again, so the field shows through.+ SGRRegisterClearRoot(template);+ SGRAddPlayerStateObserver(self);+ static dispatch_once_t once;+ dispatch_once(&once, ^{ SGLog(@"artist: page %@, field and clear root in %@", uri, NSStringFromClass(template.class)); });+ return self;+}++- (void)dealloc {+ [self watchArtwork:nil];+}++#pragma mark - page++- (void)templateDidLayout:(UIView *)template {+ if (template.subviews.firstObject != _field) [template insertSubview:_field atIndex:0];+ if (!CGRectEqualToRect(_field.frame, template.bounds)) _field.frame = template.bounds;+ if (!_observing) [self observeScrollIn:template];+ if (!_tabsHidden) [self hideTabsIn:template];+}++- (void)observeScrollIn:(UIView *)template {+ static char containerKey, overlayKey;+ UIScrollView *container = (UIScrollView *)SGRFindByIdentifier(template, @"PCFFTabLayoutViewController.containerScrollView", &containerKey);+ if (![container isKindOfClass:UIScrollView.class]) return;+ UIScrollView *overlay = (UIScrollView *)SGRFindByIdentifier(template, @"PCFFTabLayoutViewController.overlayScrollView", &overlayKey);+ _observing = YES;+ _container = container;+ SGRObserveOffset(container, self, ^(id owner, CGPoint offset) { [(SGArtistPage *)owner containerMoved:offset]; });+ // The overlay takes the pan, so an overscroll may show there only; the container is where the header is.+ if ([overlay isKindOfClass:UIScrollView.class]) {+ _overlay = overlay;+ SGRObserveOffset(overlay, self, ^(id owner, CGPoint offset) { [(SGArtistPage *)owner overlayMoved:offset]; });+ }+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ SGLog(@"artist: scroll observed, container inset %.0f, overlay %@", container.adjustedContentInset.top, overlay ? @"found" : @"missing");+ });+}++- (void)containerMoved:(CGPoint)offset {+ _containerY = offset.y + _container.adjustedContentInset.top;+ [self applyScroll];+}++- (void)overlayMoved:(CGPoint)offset {+ _overlayY = offset.y + _overlay.adjustedContentInset.top;+ if (_overlayY < 0 || _containerY <= 0) [self applyScroll];+}++// The hero's own scroll response: stretch on overscroll (from whichever scroll view shows it), drift, and+// the texts and buttons fading before the navigation bar. Only transforms and alphas change here.+- (void)applyScroll {+ if (!_hero) return;+ CGFloat y = _containerY;+ if (y <= 0 && _overlayY < y) y = _overlayY;+ CGFloat distance = MAX(0, CGRectGetHeight(_hero.bounds) - kPinnedHeader);+ [_hero applyScrollOffset:y collapseDistance:distance];+ if (y < -1) {+ static dispatch_once_t once;+ dispatch_once(&once, ^{ SGLog(@"artist: overscroll, container %.0f overlay %.0f", self->_containerY, self->_overlayY); });+ } else if (distance > 0 && y >= distance) {+ static dispatch_once_t once;+ dispatch_once(&once, ^{ SGLog(@"artist: header pinned at %.0f, container %.0f overlay %.0f", distance, self->_containerY, self->_overlayY); });+ }+}++// Trees (01.txt): the strip lives in a LegacyUI AutoLayoutStackView, so it goes invisible rather than+// hidden; the paging scroll view beside it moves up into its place and stops swiping, which leaves the+// Music list, the way Features/Artist/Artist.x hides it.+- (BOOL)hideTabsIn:(UIView *)root {+ static char stripKey;+ UIView *strip = SGRFindByIdentifier(root, @"Components.UI.TabsSectionHeading", &stripKey);+ if (!strip.superview) return NO;+ _tabsHidden = YES;+ if (strip.alpha != 0) strip.alpha = 0;+ if (strip.userInteractionEnabled) strip.userInteractionEnabled = NO;+ if (!strip.accessibilityElementsHidden) strip.accessibilityElementsHidden = YES;+ CGFloat lift = -CGRectGetHeight(strip.bounds);+ NSUInteger pages = 0;+ for (UIView *view in strip.superview.subviews) {+ if (view == strip || ![view isKindOfClass:UIScrollView.class]) continue;+ UIScrollView *paging = (UIScrollView *)view;+ if (paging.scrollEnabled) paging.scrollEnabled = NO;+ if (paging.transform.ty != lift) paging.transform = CGAffineTransformMakeTranslation(0, lift);+ pages++;+ }+ if (lift == 0 || !pages) return YES;+ static dispatch_once_t once;+ dispatch_once(&once, ^{ SGLog(@"artist: tab strip hidden, %lu paging view moved up %.0f and not swiping", (unsigned long)pages, -lift); });+ return YES;+}++#pragma mark - hero++- (SGRHeroHeader *)heroFor:(UIView *)container {+ if (_hero) return _hero;+ _hero = [[SGRHeroHeader alloc] initWithFrame:container.bounds];+ [_hero bindToField:_field];+ // English until Spotify's own words are read from its header (mirror:), a moment later.+ _shuffle = [SGRGlassButton circleWithSymbol:@"shuffle" accessibilityLabel:@"Shuffle"];+ _play = [SGRGlassButton capsuleWithSymbol:@"play.fill" title:@"Play" prominent:YES];+ _follow = [SGRGlassButton capsuleWithSymbol:nil title:@"Follow" prominent:NO];+ __weak SGArtistPage *weakSelf = self;+ _shuffle.onTap = ^{ [weakSelf tapShuffle]; };+ _play.onTap = ^{ [weakSelf tapPlay]; };+ _follow.onTap = ^{ [weakSelf tapFollow]; };+ SGRActionRow *row = [[SGRActionRow alloc] initWithFrame:_hero.actionSlot.bounds];+ row.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;+ row.buttons = @[_shuffle, _play, _follow];+ [_hero.actionSlot addSubview:row];+ [self updatePlay];+ static dispatch_once_t once;+ dispatch_once(&once, ^{ SGLog(@"artist: hero in the header container, %.0f tall", CGRectGetHeight(container.bounds)); });+ return _hero;+}++- (void)headerContainerDidLayout:(UIView *)container {+ SGRHeroHeader *hero = [self heroFor:container];+ if (container.subviews.lastObject != hero) [container addSubview:hero];+ if (!CGRectEqualToRect(hero.frame, container.bounds)) {+ hero.frame = container.bounds;+ [self applyScroll];+ }+ for (UIView *element in container.subviews) {+ for (UIView *header in element.subviews) {+ if ([header isKindOfClass:sg_imageHeaderClass]) [self stockHeaderDidLayout:header];+ }+ }+}++- (void)stockHeaderDidLayout:(UIView *)header {+ if (header.alpha != 0 || header.userInteractionEnabled || !header.accessibilityElementsHidden) {+ SGRSuppress(header);+ static dispatch_once_t once;+ dispatch_once(&once, ^{ SGLog(@"artist: Spotify's header hidden"); });+ }+ _stockHeader = header;+ // Spotify shrinks its header into the pinned band while the page scrolls, laying it out every frame;+ // what it shows does not change then, so it is read at full height only, and at most every 0.3 s with+ // one more read after a burst of layouts.+ UIView *container = header.superview.superview;+ if (!_hero || CGRectGetHeight(header.bounds) < CGRectGetHeight(container.bounds) - 1 || _mirrorScheduled) return;+ CFTimeInterval now = CACurrentMediaTime();+ if (now - _lastMirror >= 0.3) {+ _lastMirror = now;+ [self mirror:header];+ return;+ }+ [self mirrorLater:header];+}++- (void)mirrorLater:(UIView *)header {+ if (_mirrorScheduled) return;+ _mirrorScheduled = YES;+ __weak SGArtistPage *weakSelf = self;+ __weak UIView *weakHeader = header;+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ SGArtistPage *page = weakSelf;+ if (!page) return;+ page->_mirrorScheduled = NO;+ page->_lastMirror = CACurrentMediaTime();+ UIView *later = weakHeader;+ if (later) [page mirror:later];+ });+}++// Spotify's controls, looked for inside its header only: the music videos shelf has a header-play-button+// and the biography card a follow button of their own (10.txt).+- (void)findControlsIn:(UIView *)header {+ static char playKey, shuffleKey, followKey;+ _playControl = SGRFindByIdentifier(header, @"header-play-button", &playKey);+ UIView *shuffle = SGRFindByIdentifier(header, @"Components.UI.ShuffleButton", &shuffleKey);+ _shuffleControl = [shuffle isKindOfClass:UIControl.class] ? (UIControl *)shuffle : nil;+ UIView *follow = SGRFindByIdentifier(header, @"Curation.FollowButtonElementKit.FollowButton", &followKey);+ _followControl = [follow isKindOfClass:UIControl.class] ? (UIControl *)follow : nil;+}++- (void)mirror:(UIView *)header {+ static char titleKey, metaKey, artworkKey, exploreKey;+ NSString *title = labelTextIn(SGRFindByIdentifier(header, @"Encore.AdaptiveTitle", &titleKey));+ if (title.length) _hero.title = title;+ UILabel *meta = (UILabel *)SGRFindByIdentifier(header, @"Components.Header.UI.Metadata-internal", &metaKey);+ if ([meta isKindOfClass:UILabel.class]) _hero.meta = meta.text;++ UIImageView *artwork = nil;+ for (UIView *view in SGRFindByIdentifier(header, @"Components.Header.UI.ArtworkImage.ImageView", &artworkKey).subviews) {+ if ([view isKindOfClass:UIImageView.class]) {+ artwork = (UIImageView *)view;+ break;+ }+ }+ if (artwork != _artworkView) [self watchArtwork:artwork];++ [self findControlsIn:header];+ UIView *shuffle = _shuffleControl, *follow = _followControl;++ // The explore deck plays short videos in the header (01.txt: SPTVideoSurfaceImpl under+ // Components.UI.WatchFeedEntityExplorerButton). It goes transparent, never hidden: hiding it, though it+ // is no arranged view itself, changes the size of the button the header's Reprise OverflowStackView+ // arranges, and that stack traps in updateConstraints (crash 2026-09-17 09:30, the same trap as+ // Features/Artist/Artist.x on 2026-09-15). Spotify's whole header is transparent already.+ UIView *deck = SGRFindByIdentifier(header, @"Components.UI.WatchFeedEntityExplorerButton", &exploreKey).subviews.firstObject;+ if (deck.alpha != 0) deck.alpha = 0;++ [self mirrorControls];+ // The buttons and the photo can arrive after the header's last layout at full height (Features/Artist/+ // Artist.x watches the button row's stack for that), so a read that missed one is repeated, for a while.+ if (!(title.length && artwork && _playControl && shuffle && follow) && _missedReads < 10) {+ _missedReads++;+ [self mirrorLater:header];+ }+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ SGLog(@"artist: header read, title %@, meta %@, artwork %@, play %@, shuffle %@, follow %@, explore deck %@",+ title.length ? @"yes" : @"no", meta.text.length ? @"yes" : @"no", artwork ? @"yes" : @"no",+ NSStringFromClass(self->_playControl.class) ?: @"missing", NSStringFromClass(shuffle.class) ?: @"missing",+ NSStringFromClass(follow.class) ?: @"missing", deck ? @"hidden" : @"missing");+ });+}++// The photo arrives after the header is built, and setting it lays nothing out, so the image view is watched.+- (void)watchArtwork:(UIImageView *)view {+ UIImageView *watched = _artworkView;+ _artworkView = nil;+ if (watched) {+ @try {+ [watched removeObserver:self forKeyPath:@"image" context:&kArtworkContext];+ } @catch (NSException *exception) {+ SGLog(@"artist: artwork observation was already gone (%@)", exception.reason);+ }+ }+ if (!view) return;+ _artworkView = view;+ [view addObserver:self forKeyPath:@"image" options:NSKeyValueObservingOptionInitial context:&kArtworkContext];+}++- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {+ if (context != &kArtworkContext) {+ [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];+ return;+ }+ UIImage *image = [object isKindOfClass:UIImageView.class] ? ((UIImageView *)object).image : nil;+ if (!image || image == _image) return;+ _image = image;+ [_hero setImage:image animated:YES];+ [_field setArtwork:image identity:nil animated:YES];+ static dispatch_once_t once;+ dispatch_once(&once, ^{ SGLog(@"artist: hero image %.0fx%.0f@%.0f", image.size.width, image.size.height, image.scale); });+}++#pragma mark - actions++- (void)mirrorControls {+ // Spotify builds a control anew when its state changes (a follow), which lets go of the old one.+ UIView *header = _stockHeader;+ if (header && (!_playControl || !_shuffleControl || !_followControl)) [self findControlsIn:header];+ UIControl *shuffle = _shuffleControl, *follow = _followControl;+ _shuffle.enabled = shuffle != nil;+ _follow.enabled = follow != nil;+ _play.enabled = _playControl != nil;+ if (shuffle) {+ _shuffle.on = shuffleDotShown(shuffle);+ if (shuffle.accessibilityLabel.length) _shuffle.accessibilityLabel = shuffle.accessibilityLabel;+ }+ NSString *followTitle = labelTextIn(follow) ?: follow.accessibilityLabel;+ if (followTitle.length) [_follow setTitle:followTitle animated:YES];+ [self updatePlay];+}++// Playing means this artist's context is the player's and it is not paused; the glyph follows the+// player, the title is Spotify's own for its play button.+- (void)updatePlay {+ SPTPlayerState *state = SGRPlayerState();+ BOOL playing = state.isPlaying && !state.isPaused && [SGRURIString(state.contextURI) isEqualToString:_uri];+ [_play setSymbol:playing ? @"pause.fill" : @"play.fill" animated:YES];+ NSString *title = buttonIn(_playControl).accessibilityLabel;+ [_play setTitle:title.length ? title : playing ? @"Pause" : @"Play" animated:YES];+}++- (void)playerStateDidChange:(SPTPlayerState *)state {+ if (!_hero) return;+ [self mirrorControls];+ [self refreshSoon];+}++// Spotify's controls change their look a moment after the tap, once the player or the follow state answers.+- (void)refreshSoon {+ __weak SGArtistPage *weakSelf = self;+ for (NSNumber *delay in @[@0.35, @1.2]) {+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay.doubleValue * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ [weakSelf mirrorControls];+ });+ }+}++- (void)tapPlay {+ UIView *control = _playControl;+ BOOL direct = [control respondsToSelector:@selector(uiButtonTapped)];+ BOOL fired = direct;+ if (direct) [(id<SGArtistPlayButton>)control uiButtonTapped];+ else fired = fire(buttonIn(control));+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ SPTPlayerState *state = SGRPlayerState();+ SGLog(@"artist: play %@ (%@), player context %@ paused %d", fired ? @"fired" : @"fired nothing", direct ? @"uiButtonTapped" : @"its button",+ SGRURIString(state.contextURI), state.isPaused);+ });+ [self refreshSoon];+}++- (void)tapShuffle {+ UIControl *control = _shuffleControl;+ BOOL before = control ? shuffleDotShown(control) : NO;+ BOOL fired = fire(control);+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ __weak UIControl *weakControl = control;+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ UIControl *later = weakControl;+ SGLog(@"artist: shuffle %@, dot %d then %d", fired ? @"fired" : @"fired nothing", before, later ? shuffleDotShown(later) : -1);+ });+ });+ [self refreshSoon];+}++- (void)tapFollow {+ UIControl *control = _followControl;+ NSString *before = labelTextIn(control);+ BOOL fired = fire(control);+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ __weak UIControl *weakControl = control;+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ UIControl *later = weakControl;+ SGLog(@"artist: follow %@, label \"%@\" then \"%@\", selected %d", fired ? @"fired" : @"fired nothing", before, labelTextIn(later), later.isSelected);+ });+ });+ [self refreshSoon];+}++@end++SGArtistPage *SGArtistPageOf(UIView *view, BOOL *pending) {+ if (pending) *pending = NO;+ UIView *template = view;+ while (template && ![template isKindOfClass:sg_templateClass]) template = template.superview;+ if (!template) {+ if (pending) *pending = view.window == nil;+ return nil;+ }+ id known = objc_getAssociatedObject(template, &kPageKey);+ if (known) return known == NSNull.null ? nil : known;+ NSString *uri = SGRURIString(SGRPageURI(template));+ if (!uri) {+ if (pending) *pending = YES;+ static dispatch_once_t once;+ dispatch_once(&once, ^{ SGLog(@"artist: a creator page has no URI yet, asked again on its next layout"); });+ return nil;+ }+ if (![uri hasPrefix:@"spotify:artist:"]) {+ objc_setAssociatedObject(template, &kPageKey, NSNull.null, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ return nil;+ }+ SGArtistPage *page = [[SGArtistPage alloc] initWithURI:uri template:template];+ objc_setAssociatedObject(template, &kPageKey, page, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ return page;+}++%hook _TtC32CreativeWorkPlatform_TemplateKit12TemplateView+- (void)layoutSubviews {+ %orig;+ [SGArtistPageOf((UIView *)self, NULL) templateDidLayout:(UIView *)self];+}+%end++%hook _TtC32CreativeWorkPlatform_TemplateKitP33_07D2BCE376DED6F379FF5AAB5402E56315HeaderContainer+- (void)layoutSubviews {+ %orig;+ [SGArtistPageOf((UIView *)self, NULL) headerContainerDidLayout:(UIView *)self];+}+%end++// Hidden from its first moment in the window, before its first layout could show Spotify's own header.+%hook _TtC35CreativeWorkPlatform_ImageHeaderKit15ImageHeaderView+- (void)didMoveToWindow {+ %orig;+ UIView *header = (UIView *)self;+ if (header.window) [SGArtistPageOf(header, NULL) stockHeaderDidLayout:header];+}++- (void)layoutSubviews {+ %orig;+ [SGArtistPageOf((UIView *)self, NULL) stockHeaderDidLayout:(UIView *)self];+}+%end++// The strip is laid out with the tabs' controller view, which holds it (01.txt: tabsViewAccessibilityID).+%hook _TtC28CreativeWorkPlatform_TabsKit16TabBarController+- (void)viewDidLayoutSubviews {+ %orig;+ UIView *view = ((UIViewController *)self).view;+ SGArtistPage *page = SGArtistPageOf(view, NULL);+ if (!page) return;+ if (![page hideTabsIn:view] && view.superview) [page hideTabsIn:view.superview];+}+%end++%ctor {+ // No remote-config flags are forced for this page. Forcing the creator flags (the Video tab, the video,+ // collaborator and facts sections off, the context menu moved into the navigation bar) built a header+ // the clean trees never showed, and the header's Reprise OverflowStackView trapped in updateConstraints+ // on every artist page (crashes 2026-09-17 09:30, 09:44, 09:48, from the header's didMoveToWindow and+ // layoutSubviews). The list's allowlist removes those sections as Spotify builds them.+ SGRedesignRegisterRows(@"artist", ^NSArray<SGModRow *> *{+ return @[SGHideRow(@"Hide songs you liked", @"The row of this artist's songs in your Liked Songs", SGKeyRedesignArtistHideLikedSongs)];+ });+ if (!SGRedesignOn(@"artist")) return;+ sg_templateClass = NSClassFromString(@"_TtC32CreativeWorkPlatform_TemplateKit12TemplateView");+ sg_imageHeaderClass = NSClassFromString(@"_TtC35CreativeWorkPlatform_ImageHeaderKit15ImageHeaderView");+ %init;+ SGRequireClasses(@[+ @"_TtC32CreativeWorkPlatform_TemplateKit12TemplateView",+ @"_TtC32CreativeWorkPlatform_TemplateKitP33_07D2BCE376DED6F379FF5AAB5402E56315HeaderContainer",+ @"_TtC35CreativeWorkPlatform_ImageHeaderKit15ImageHeaderView",+ @"_TtC28CreativeWorkPlatform_TabsKit16TabBarController",+ @"_TtC28EncoreConsumerMobile_BaseKit14PlayButtonView",+ ]);+}diff --git a/tweak/Sources/Redesign/Artist/RedesignArtist.h b/tweak/Sources/Redesign/Artist/RedesignArtist.hnew file mode 100644index 00000000..5acf2b3f--- /dev/null+++ b/tweak/Sources/Redesign/Artist/RedesignArtist.h@@ -0,0 +1,25 @@+// The artist page redesigned (Mod Settings > Redesign > Artist): Spotify's own page and its Music list+// stay, for the data, the rows and every row interaction, while the chrome is the Kit's: one field+// colour behind the whole page, the hero with the photo dissolving into it, the glass Shuffle, Play and+// Follow firing Spotify's own controls, and the Kit's section headers. Everything on the list that is+// not music collapses, told apart by accessibility identifiers, so it works in any language.+//+// ArtistPage.x the page: finding it by its URI, the field, the hero in Spotify's header, the tabs+// ArtistList.x the Music list: which cells stay, the section headers, the rows restyled+//+// Trees: trees/clean/artist/01-07.txt (Shawn Mendes, with an artist pick and a release countdown) and+// 08-13.txt (The Weeknd, with a liked songs row), recorded stock on 9.1.78.+#import <UIKit/UIKit.h>++// Off until switched on: the row of this artist's songs in Liked Songs collapses with the rest.+#define SGKeyRedesignArtistHideLikedSongs @"spotifyglass.redesign.artist.hideLikedSongs"++// The state of one redesigned artist page, kept on its TemplateView.+@interface SGArtistPage : NSObject+@property (nonatomic, readonly, copy) NSString *uri;+@end++// The redesigned artist page `view` is on, found up its superviews. nil on any other page (an author's+// page shares the template and the creator-page identifier, so the URI decides), and nil with+// `pending` set while the page's URI cannot be read yet, so the caller asks again later.+SGArtistPage *SGArtistPageOf(UIView *view, BOOL *pending);diff --git a/tweak/Sources/Redesign/Kit/SGRBridges.h b/tweak/Sources/Redesign/Kit/SGRBridges.hnew file mode 100644index 00000000..c284a635--- /dev/null+++ b/tweak/Sources/Redesign/Kit/SGRBridges.h@@ -0,0 +1,59 @@+// What the redesigned screens read from Spotify and ask of it, through one hook each, so no screen+// hooks the player or the link dispatcher a second time.+//+// Player state: -[_TtC23NowPlaying_PlatformImpl28StatefulPlayerImplementation player:stateDidChange:]+// (objc-methods.txt:60654), the now playing platform's own player observer, and until that has reported,+// an observer of the Kit's added to the first SPTEsperantoPlayer the app adds one to+// (-[SPTEsperantoPlayer addPlayerObserver:], :35729). Installed while any screen is redesigned.+// Artwork: the now playing bar's 40pt cover (trees/clean/artist/01.txt: id=SPTNowPlayingBar > Encore.ImageView >+// UIImageView 40x40), read after the bar's layout and after a track change; installed while the player+// is redesigned. Screens publish better copies of their own (the player's cover).+// Links: -[SPTLinkDispatcherImplementation setMainUILoaded:] (:38809), the last call of the singleton's+// setup, always installed: the Navbar's own tabs open through it too.+//+// Threading: everything here is main thread only; the player's reports are moved onto it.+#import <UIKit/UIKit.h>+#import "Headers/SPTPlayer.h"++// A URI Spotify types as id (NSURL or NSString) as a string; nil for anything else.+NSString *SGRURIString(id uri);++#pragma mark - player state++@protocol SGRPlayerStateObserver <NSObject>+// Called when the track, the context, paused, playing, loading or shuffle changed, not for position.+- (void)playerStateDidChange:(SPTPlayerState *)state;+@end+// Observers are held weakly and need no removal.+void SGRAddPlayerStateObserver(id<SGRPlayerStateObserver> observer);+// The last state reported, nil before the player has reported one.+SPTPlayerState *SGRPlayerState(void);++#pragma mark - now playing artwork++typedef NS_ENUM(NSInteger, SGRArtworkQuality) {+ SGRArtworkQualityLow, // the now playing bar's 40pt cover+ SGRArtworkQualityHigh, // the player's own cover+};+// Posted when the artwork changes, object nil, userInfo image, trackURI and quality.+extern NSNotificationName const SGRNowPlayingArtworkDidChangeNotification;+// A lower quality image for the track already published is ignored, as is the same image again.+void SGRSetNowPlayingArtwork(UIImage *image, NSString *trackURI, SGRArtworkQuality quality);+// The last artwork published; `trackURI` and `identity` (URI and quality, for+// -[SGRArtworkField setArtwork:identity:animated:]) are filled when asked for.+UIImage *SGRNowPlayingArtwork(NSString **trackURI, NSString **identity);++#pragma mark - links++// Opens a spotify: URI the way the app opens a link of its own. NO before the dispatcher is set up or+// for a nil URI.+BOOL SGROpenURI(NSURL *uri);+id SGRLinkDispatcher(void); // SPTLinkDispatcherImplementation, nil until it is set up++#pragma mark - the player's open and close++// While the full screen player opens or closes (NowPlaying/NowPlayingBar.x announces it).+BOOL SGRPlayerIsTransitioning(void);+// SGPlayerTransitionNotification and SGPlayerTransitionEndedNotification as blocks, for as long as+// `owner` lives. The blocks are handed the owner so they need not capture it.+void SGRObservePlayerTransition(id owner, void (^began)(id owner), void (^ended)(id owner));diff --git a/tweak/Sources/Redesign/Kit/SGRBridges.x b/tweak/Sources/Redesign/Kit/SGRBridges.xnew file mode 100644index 00000000..ddd1c505--- /dev/null+++ b/tweak/Sources/Redesign/Kit/SGRBridges.x@@ -0,0 +1,271 @@+// The Kit's bridges into Spotify: the player's state, the now playing artwork and the link dispatcher.+// SGRBridges.h names the hooks and why they are the ones.+#import "Core/SGCore.h"+#import "Headers/SPTLinkDispatcherImplementation.h"+#import "Features/NowPlaying/NowPlaying.h"+#import "SGRBridges.h"+#import "SGRedesign.h"+#import "SGRRestyle.h"++NSString *SGRURIString(id uri) {+ if ([uri isKindOfClass:NSString.class]) return uri;+ if ([uri isKindOfClass:NSURL.class]) return ((NSURL *)uri).absoluteString;+ return nil;+}++#pragma mark - player state++static NSHashTable<id<SGRPlayerStateObserver>> *sg_stateObservers;+static SPTPlayerState *sg_playerState;+static NSString *sg_stateKey;+// Set once the now playing platform has reported; the Kit's own observer on the player stands down.+static BOOL sg_platformReported = NO;++void SGRAddPlayerStateObserver(id<SGRPlayerStateObserver> observer) {+ if (!observer) return;+ if (!sg_stateObservers) sg_stateObservers = [NSHashTable weakObjectsHashTable];+ [sg_stateObservers addObject:observer];+}++SPTPlayerState *SGRPlayerState(void) {+ return sg_playerState;+}++// What an observer is told about; the state object itself is new with every position report.+static NSString *keyOf(SPTPlayerState *state) {+ SPTPlayerOptions *options = [state respondsToSelector:@selector(options)] ? state.options : nil;+ BOOL shuffling = [options respondsToSelector:@selector(shufflingContext)] && options.shufflingContext;+ return [NSString stringWithFormat:@"%@|%@|%d%d%d%d", SGRURIString(state.track.URI), SGRURIString(state.contextURI),+ state.isPaused, state.isPlaying, [state respondsToSelector:@selector(isLoading)] && state.isLoading, shuffling];+}++static void publish(SPTPlayerState *state) {+ sg_playerState = state;+ NSString *key = keyOf(state);+ if ([key isEqualToString:sg_stateKey]) return;+ sg_stateKey = key;+ for (id<SGRPlayerStateObserver> observer in sg_stateObservers.allObjects) [observer playerStateDidChange:state];+}++static void report(id state, BOOL platform) {+ if (![state isKindOfClass:objc_getClass("SPTPlayerState")]) return;+ dispatch_block_t apply = ^{+ if (platform) sg_platformReported = YES;+ else if (sg_platformReported) return;+ publish(state);+ };+ if (NSThread.isMainThread) apply();+ else dispatch_async(dispatch_get_main_queue(), apply);+}++@interface SGRPlayerObserver : NSObject+@end++@implementation SGRPlayerObserver+- (void)player:(id)player stateDidChange:(id)state {+ report(state, NO);+}+@end++static SGRPlayerObserver *sg_kitObserver;++%group SGRPlayerStateHooks+%hook _TtC23NowPlaying_PlatformImpl28StatefulPlayerImplementation+- (void)player:(id)player stateDidChange:(id)state {+ %orig;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ SGLog(@"redesign kit: player state from %@, a %@, on the main thread %d", [player class], [state class], NSThread.isMainThread);+ });+ report(state, YES);+}+%end++// Observers are added from several threads as the app starts; the first player seen is the one+// watched, the way KaraokeSource.x takes the first player the app asks.+%hook SPTEsperantoPlayer+- (void)addPlayerObserver:(id)observer {+ %orig;+ id player = self;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ dispatch_async(dispatch_get_main_queue(), ^{+ sg_kitObserver = [SGRPlayerObserver new];+ [(id<SPTPlayer>)player addPlayerObserver:sg_kitObserver];+ id state = [player respondsToSelector:@selector(state)] ? [(id<SPTPlayer>)player state] : nil;+ if (state) report(state, NO);+ });+ });+}+%end+%end++#pragma mark - now playing artwork++NSNotificationName const SGRNowPlayingArtworkDidChangeNotification = @"spotifyglass.redesign.nowPlayingArtworkDidChange";++static UIImage *sg_artwork;+static NSString *sg_artworkURI;+static SGRArtworkQuality sg_artworkQuality;++void SGRSetNowPlayingArtwork(UIImage *image, NSString *trackURI, SGRArtworkQuality quality) {+ if (!image) return;+ BOOL sameTrack = trackURI ? [trackURI isEqualToString:sg_artworkURI] : !sg_artworkURI;+ if (sameTrack && (image == sg_artwork || quality < sg_artworkQuality)) return;+ sg_artwork = image;+ sg_artworkURI = [trackURI copy];+ sg_artworkQuality = quality;+ [NSNotificationCenter.defaultCenter postNotificationName:SGRNowPlayingArtworkDidChangeNotification object:nil userInfo:@{+ @"image": image,+ @"trackURI": trackURI ?: @"",+ @"quality": @(quality),+ }];+}++UIImage *SGRNowPlayingArtwork(NSString **trackURI, NSString **identity) {+ if (trackURI) *trackURI = sg_artworkURI;+ if (identity) *identity = sg_artwork ? [NSString stringWithFormat:@"%@#%ld", sg_artworkURI ?: @"", (long)sg_artworkQuality] : nil;+ return sg_artwork;+}++static const CFTimeInterval kBarLead = 0.5;+static char kBarCardKey, kBarImageKey;+static __weak UIView *sg_barView;+// The bar's picture and when it appeared, and when the track last changed: a picture that was there+// well before the change is the last track's cover still, while one that turned up just before it+// was set by the same state the Kit is told about a moment later.+static __weak UIImage *sg_barImage;+static CFTimeInterval sg_barImageSince, sg_trackChangedAt;++static void publishBarArtwork(void) {+ UIView *card = SGRFindByIdentifier(sg_barView, @"SPTNowPlayingBar", &kBarCardKey);+ UIView *holder = SGRFindByIdentifier(card, @"Encore.ImageView", &kBarImageKey);+ UIImageView *cover = nil;+ for (UIView *sub in holder.subviews) {+ if ([sub isKindOfClass:UIImageView.class]) cover = (UIImageView *)sub;+ }+ UIImage *image = cover.image;+ NSString *uri = SGRURIString(SGRPlayerState().track.URI);+ if (!image || !uri) return;+ if (image != sg_barImage) {+ sg_barImage = image;+ sg_barImageSince = CACurrentMediaTime();+ }+ if (sg_barImageSince < sg_trackChangedAt - kBarLead) return;+ SGRSetNowPlayingArtwork(image, uri, SGRArtworkQualityLow);+}++// The bar sets its picture when the image has loaded, which lays nothing out, so a track change looks+// again a few times while the picture comes in.+@interface SGRBarArtworkWatcher : NSObject <SGRPlayerStateObserver>+@end++@implementation SGRBarArtworkWatcher {+ NSString *_track;+}++- (void)playerStateDidChange:(SPTPlayerState *)state {+ NSString *track = SGRURIString(state.track.URI);+ if (!track || [track isEqualToString:_track]) return;+ // The first track of the launch has no last cover to mistake for its own.+ if (_track) sg_trackChangedAt = CACurrentMediaTime();+ _track = track;+ for (NSNumber *delay in @[@0, @0.3, @1, @2.5]) {+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay.doubleValue * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ publishBarArtwork(); });+ }+}++@end++static SGRBarArtworkWatcher *sg_barWatcher;++%group SGRBarArtworkHooks+%hook _TtC18NowPlaying_BarImpl27NowPlayingBarViewController+- (void)viewDidLayoutSubviews {+ %orig;+ sg_barView = ((UIViewController *)self).viewIfLoaded;+ publishBarArtwork();+}+%end+%end++#pragma mark - links++static __weak SPTLinkDispatcherImplementation *sg_linkDispatcher;++id SGRLinkDispatcher(void) {+ return sg_linkDispatcher;+}++BOOL SGROpenURI(NSURL *uri) {+ SPTLinkDispatcherImplementation *dispatcher = sg_linkDispatcher;+ if (!uri || ![dispatcher respondsToSelector:@selector(navigateToURI:options:interactionID:)]) return NO;+ [dispatcher navigateToURI:uri options:0 interactionID:nil];+ return YES;+}++// The dispatcher is a singleton the app builds at startup; this is the last call of its setup.+%hook SPTLinkDispatcherImplementation+- (void)setMainUILoaded:(BOOL)loaded {+ %orig;+ sg_linkDispatcher = (SPTLinkDispatcherImplementation *)self;+}+%end++#pragma mark - the player's open and close++BOOL SGRPlayerIsTransitioning(void) {+ return SGPlayerTransitionEnds() > 0;+}++@interface SGRTransitionObservation : NSObject+@property (nonatomic, strong) NSArray *tokens;+@end++@implementation SGRTransitionObservation+- (void)dealloc {+ for (id token in self.tokens) [NSNotificationCenter.defaultCenter removeObserver:token];+}+@end++static char kTransitionKey;++void SGRObservePlayerTransition(id owner, void (^began)(id owner), void (^ended)(id owner)) {+ if (!owner) return;+ __weak id weakOwner = owner;+ NSNotificationCenter *center = NSNotificationCenter.defaultCenter;+ NSMutableArray *tokens = [NSMutableArray array];+ if (began) {+ [tokens addObject:[center addObserverForName:SGPlayerTransitionNotification object:nil queue:nil usingBlock:^(NSNotification *note) {+ id strongOwner = weakOwner;+ if (strongOwner) began(strongOwner);+ }]];+ }+ if (ended) {+ [tokens addObject:[center addObserverForName:SGPlayerTransitionEndedNotification object:nil queue:nil usingBlock:^(NSNotification *note) {+ id strongOwner = weakOwner;+ if (strongOwner) ended(strongOwner);+ }]];+ }+ SGRTransitionObservation *observation = [SGRTransitionObservation new];+ observation.tokens = tokens;+ NSMutableArray *kept = objc_getAssociatedObject(owner, &kTransitionKey);+ if (!kept) {+ kept = [NSMutableArray array];+ objc_setAssociatedObject(owner, &kTransitionKey, kept, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ }+ [kept addObject:observation];+}++%ctor {+ %init;+ SGRequireClasses(@[@"SPTLinkDispatcherImplementation"]);+ if (!SGRedesignAnyOn()) return;+ %init(SGRPlayerStateHooks);+ SGRequireClasses(@[@"_TtC23NowPlaying_PlatformImpl28StatefulPlayerImplementation", @"SPTEsperantoPlayer", @"SPTPlayerState"]);+ if (!SGRedesignOn(@"player")) return;+ sg_barWatcher = [SGRBarArtworkWatcher new];+ SGRAddPlayerStateObserver(sg_barWatcher);+ %init(SGRBarArtworkHooks);+ SGRequireClasses(@[@"_TtC18NowPlaying_BarImpl27NowPlayingBarViewController"]);+}diff --git a/tweak/Sources/Redesign/Kit/SGRField.h b/tweak/Sources/Redesign/Kit/SGRField.hnew file mode 100644index 00000000..afc09e87--- /dev/null+++ b/tweak/Sources/Redesign/Kit/SGRField.h@@ -0,0 +1,46 @@+// The artwork field: one continuous colour taken from the artwork's bottom edge (SGRPalette.h) behind+// a whole redesigned page, with no card and no seam anywhere. The player's field also carries the+// artwork itself at the top, blurred and dimmed and dissolving into the colour (showsBackdrop); the+// artist page's hero draws its own photo (SGRHero.h), so its field is the colour alone.+//+// Nothing is blurred live and nothing is masked: the view draws a solid colour layer, a black+// gradient layer under AMOLED and at most one bitmap layer rendered off the main thread, so it costs+// one composited layer or two while the page moves. A new colour or bitmap crossfades over+// SGRCrossfade; the same image again is a no-op.+//+// Ownership: the screen that installs a field owns it (usually retained by its superview and an+// associated object). The field retains its last image and palette only.+// Threading: main thread only; the palette work it starts runs off it.+#import <UIKit/UIKit.h>++// Posted on the main thread by a field whose colour changed, with the field as the object and the+// new colour under "color".+extern NSNotificationName const SGRFieldColorDidChangeNotification;++@interface SGRArtworkField : UIView+// Where the colour, the AMOLED fade and the backdrop reach past the bounds (overscroll, a plane+// that does not clip): positive values draw outside. The field never clips.+@property (nonatomic) UIEdgeInsets bleed;+@property (nonatomic) BOOL showsBackdrop;+// The backdrop's height in points from the top of the bounds; 0 is the window's height.+@property (nonatomic) CGFloat backdropHeight;+// With AMOLED on: where the colour starts fading to black and where it is black, in points from the+// top of the bounds; 0 is 55% and 100% of the window's height.+@property (nonatomic) CGFloat amoledFadeFrom, amoledFadeTo;+// SGRNeutralField until a colour arrives.+@property (nonatomic, readonly) UIColor *fieldColor;++// A colour Spotify already has for the page (the player's background colour), made fit to be a field+// and shown until the first artwork has been read; ignored after that.+- (void)setProvisionalColor:(UIColor *)color;+// Reads the artwork off the main thread and crossfades the result in (without animation when+// `animated` is NO or the field is not in a window). The same image, or the same non-nil identity,+// as the last call is a no-op, and a result that lands after a newer call is dropped. nil keeps+// what the field shows.+- (void)setArtwork:(UIImage *)image identity:(NSString *)identity animated:(BOOL)animated;+@end++// A content surface (a card, not glass) filling `host` behind its content, rounded SGRRadiusCard, in+// SGRElevated of the field's colour and following it. `field` nil follows whichever field posts.+// Created once per host and returned again after; main thread.+UIView *SGRCardSurface(UIView *host, SGRArtworkField *field);diff --git a/tweak/Sources/Redesign/Kit/SGRField.m b/tweak/Sources/Redesign/Kit/SGRField.mnew file mode 100644index 00000000..7727fc14--- /dev/null+++ b/tweak/Sources/Redesign/Kit/SGRField.m@@ -0,0 +1,245 @@+#import "Core/SGCore.h"+#import "Features/Appearance/Appearance.h"+#import "SGRField.h"+#import "SGRPalette.h"+#import "SGRTokens.h"++NSNotificationName const SGRFieldColorDidChangeNotification = @"spotifyglass.redesign.fieldColorDidChange";++static const CGFloat kAmoledFrom = 0.55;+static const CGFloat kFallbackHeight = 874; // a window-less field sizes for an iPhone 17 Pro++// The colour the last field took, for a card surface that follows whichever field posts.+static UIColor *sg_lastFieldColor;++static CGFloat windowHeight(UIView *view) {+ CGFloat height = view.window.bounds.size.height;+ return height > 0 ? height : kFallbackHeight;+}++// The field paints on sublayers of its own rather than on the view's layer: Appearance/Repaint.x only+// clears the paint of a view's own layer, so the neutral colour cannot be taken for Spotify's base+// surface inside a page registered as a clear root.+static NSDictionary *noActions(void) {+ static NSDictionary *none;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ NSNull *off = NSNull.null;+ none = @{@"bounds": off, @"position": off, @"frame": off, @"contents": off, @"backgroundColor": off, @"hidden": off, @"locations": off};+ });+ return none;+}++@implementation SGRArtworkField {+ CALayer *_solid;+ CAGradientLayer *_amoled;+ CALayer *_backdrop;+ UIColor *_color;+ UIImage *_image;+ NSString *_identity;+ NSUInteger _generation;+ BOOL _read;+}++- (instancetype)initWithFrame:(CGRect)frame {+ if (!(self = [super initWithFrame:frame])) return nil;+ self.userInteractionEnabled = NO;+ self.clipsToBounds = NO;+ self.accessibilityElementsHidden = YES;+ _color = SGRNeutralField();++ _solid = [CALayer layer];+ _solid.actions = noActions();+ _solid.backgroundColor = _color.CGColor;+ [self.layer addSublayer:_solid];++ if (SGFlag(SGKeyAmoled, NO)) {+ _amoled = [CAGradientLayer layer];+ _amoled.actions = noActions();+ _amoled.colors = @[(id)[UIColor colorWithWhite:0 alpha:0].CGColor, (id)UIColor.blackColor.CGColor];+ [self.layer addSublayer:_amoled];+ }++ _backdrop = [CALayer layer];+ _backdrop.actions = noActions();+ _backdrop.contentsGravity = kCAGravityResize;+ _backdrop.hidden = YES;+ [self.layer addSublayer:_backdrop];+ return self;+}++- (UIColor *)fieldColor {+ return _color;+}++- (CGFloat)backdropHeightNow {+ return _backdropHeight > 0 ? _backdropHeight : windowHeight(self);+}++- (void)setBleed:(UIEdgeInsets)bleed {+ _bleed = bleed;+ [self setNeedsLayout];+}++- (void)setBackdropHeight:(CGFloat)height {+ _backdropHeight = height;+ [self setNeedsLayout];+}++- (void)layoutSubviews {+ [super layoutSubviews];+ CGRect bounds = self.bounds;+ UIEdgeInsets bleed = _bleed;+ CGRect painted = CGRectMake(-bleed.left, -bleed.top, bounds.size.width + bleed.left + bleed.right, bounds.size.height + bleed.top + bleed.bottom);+ [CATransaction begin];+ [CATransaction setDisableActions:YES];+ _solid.frame = painted;+ if (_amoled) {+ CGFloat height = windowHeight(self), total = MAX(1, painted.size.height);+ CGFloat from = (_amoledFadeFrom > 0 ? _amoledFadeFrom : height * kAmoledFrom) + bleed.top;+ CGFloat to = MAX(from + 1, (_amoledFadeTo > 0 ? _amoledFadeTo : height) + bleed.top);+ _amoled.frame = painted;+ _amoled.locations = @[@(MIN(1, from / total)), @(MIN(1, to / total))];+ }+ _backdrop.frame = CGRectMake(0, 0, bounds.size.width, [self backdropHeightNow]);+ [CATransaction commit];+}++- (void)applyColor:(UIColor *)color animated:(BOOL)animated {+ if (!color || CGColorEqualToColor(color.CGColor, _color.CGColor)) return;+ CALayer *shown = _solid.presentationLayer ?: _solid;+ id from = (__bridge id)shown.backgroundColor;+ _color = color;+ sg_lastFieldColor = color;+ [CATransaction begin];+ [CATransaction setDisableActions:YES];+ _solid.backgroundColor = color.CGColor;+ [CATransaction commit];+ if (animated && from) {+ CABasicAnimation *fade = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];+ fade.fromValue = from;+ // Read back rather than the colour asked for: Appearance/Amoled.x may have swapped it for black.+ fade.toValue = (__bridge id)_solid.backgroundColor;+ fade.duration = SGRCrossfade;+ fade.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];+ [_solid addAnimation:fade forKey:@"backgroundColor"];+ }+ [NSNotificationCenter.defaultCenter postNotificationName:SGRFieldColorDidChangeNotification object:self userInfo:@{@"color": color}];+}++- (void)setProvisionalColor:(UIColor *)color {+ if (_read || !color) return;+ [self applyColor:SGRFieldColorFor(color) animated:self.window != nil];+}++- (void)setArtwork:(UIImage *)image identity:(NSString *)identity animated:(BOOL)animated {+ if (!image || image == _image || (identity && [identity isEqualToString:_identity])) return;+ _image = image;+ _identity = [identity copy];+ NSUInteger generation = ++_generation;+ SGRPaletteRequest request = {CGSizeZero, NO, _amoled != nil};+ if (_showsBackdrop) request.backdropSize = CGSizeMake(self.bounds.size.width > 0 ? self.bounds.size.width : 402, [self backdropHeightNow]);+ __weak SGRArtworkField *weakSelf = self;+ [SGRPalette paletteForImage:image request:request completion:^(SGRPalette *palette) {+ SGRArtworkField *field = weakSelf;+ if (!field || !palette || generation != field->_generation) return;+ [field applyPalette:palette animated:animated && field.window != nil];+ }];+}++- (void)applyPalette:(SGRPalette *)palette animated:(BOOL)animated {+ _read = YES;+ if (_showsBackdrop && palette.backdrop) {+ [CATransaction begin];+ [CATransaction setDisableActions:YES];+ if (animated) {+ CATransition *fade = [CATransition animation];+ fade.type = kCATransitionFade;+ fade.duration = SGRCrossfade;+ [_backdrop addAnimation:fade forKey:@"contents"];+ }+ _backdrop.contents = (__bridge id)palette.backdrop.CGImage;+ _backdrop.hidden = NO;+ [CATransaction commit];+ }+ [self applyColor:palette.fieldColor animated:animated];+}++@end++#pragma mark - card surface++static char kSurfaceKey;++@interface SGRCardSurfaceView : UIView+@property (nonatomic, weak) SGRArtworkField *field;+@end++@implementation SGRCardSurfaceView {+ CALayer *_paint;+}++- (instancetype)initWithFrame:(CGRect)frame {+ if (!(self = [super initWithFrame:frame])) return nil;+ self.userInteractionEnabled = NO;+ self.accessibilityElementsHidden = YES;+ self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;+ self.layer.zPosition = -1;+ _paint = [CALayer layer];+ _paint.actions = noActions();+ _paint.cornerRadius = SGRRadiusCard;+ _paint.cornerCurve = kCACornerCurveContinuous;+ [self.layer addSublayer:_paint];+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(fieldColorChanged:) name:SGRFieldColorDidChangeNotification object:nil];+ return self;+}++- (void)dealloc {+ [NSNotificationCenter.defaultCenter removeObserver:self];+}++- (void)layoutSubviews {+ [super layoutSubviews];+ [CATransaction begin];+ [CATransaction setDisableActions:YES];+ _paint.frame = self.bounds;+ [CATransaction commit];+}++- (void)paintWith:(UIColor *)field animated:(BOOL)animated {+ CGColorRef color = SGRElevated(field ?: SGRNeutralField()).CGColor;+ if (!animated) {+ [CATransaction begin];+ [CATransaction setDisableActions:YES];+ _paint.backgroundColor = color;+ [CATransaction commit];+ return;+ }+ [CATransaction begin];+ [CATransaction setAnimationDuration:SGRCrossfade];+ _paint.actions = nil;+ _paint.backgroundColor = color;+ _paint.actions = noActions();+ [CATransaction commit];+}++- (void)fieldColorChanged:(NSNotification *)note {+ SGRArtworkField *field = self.field;+ if (field && note.object != field) return;+ [self paintWith:note.userInfo[@"color"] animated:self.window != nil];+}++@end++UIView *SGRCardSurface(UIView *host, SGRArtworkField *field) {+ if (!host) return nil;+ SGRCardSurfaceView *surface = objc_getAssociatedObject(host, &kSurfaceKey);+ if (!surface) {+ surface = [[SGRCardSurfaceView alloc] initWithFrame:host.bounds];+ surface.field = field;+ [surface paintWith:field ? field.fieldColor : sg_lastFieldColor animated:NO];+ objc_setAssociatedObject(host, &kSurfaceKey, surface, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ }+ if (surface.superview != host) [host insertSubview:surface atIndex:0];+ return surface;+}diff --git a/tweak/Sources/Redesign/Kit/SGRGlass.h b/tweak/Sources/Redesign/Kit/SGRGlass.hnew file mode 100644index 00000000..ed51e45d--- /dev/null+++ b/tweak/Sources/Redesign/Kit/SGRGlass.h@@ -0,0 +1,58 @@+// Glass for the redesign's control layer, and only for it: never behind rows, cards or text. Adjacent+// glass shares one UIGlassContainerEffect, since glass cannot sample glass, and glass that takes a+// touch is interactive. Built on Core/SGGlass.m (the effect made through +effectWithStyle:).+//+// Two stand-ins, chosen as a piece is laid out: under Reduce Transparency every shape and button is a+// solid SGRSolidGlassFill (a light fill for a prominent button), on any OS; before iOS 26 without it,+// a dark thin material blur with no container. Nothing touches a glass class on an OS without them.+//+// Ownership: a backing belongs to its host (associated with it under the caller's key); buttons and+// the action row belong to whoever adds them.+// Threading: main thread only.+#import <UIKit/UIKit.h>++typedef NS_ENUM(NSInteger, SGRGlassShape) {+ SGRGlassCircle, // round, from the frame's shorter side+ SGRGlassCapsule,+};++// Glass behind someone else's controls: one container spanning the host, behind everything the host+// draws (zPosition -1), holding a shape per frame, taking no touches, so Spotify's own buttons keep+// their actions, state and accessibility on top of it.+@interface SGRGlassBacking : UIView+// The host's backing under `key`, made on first use and put back at the bottom of the host whenever+// something moved it.++ (instancetype)backingInHost:(UIView *)host key:(const void *)key;+// Frames in the host's coordinates; shapes are reused, and those past the count are hidden.+- (void)setShapes:(NSArray<NSValue *> *)framesInHost shape:(SGRGlassShape)shape;+@end++// A glass circle inside someone else's round control, `side` across, behind everything the control+// draws (zPosition -1) and kept at its middle by the autoresizing mask. Being the control's own+// subview it goes wherever the control goes: a frame worked out from outside goes stale when Spotify+// lays a row out after the unit that holds it (the player's header circles sat 24pt off until a tap+// laid the unit out again, trees/continuous/1.txt 2026-09-17). Takes no touches; made once per control+// under `key`, and made again when Reduce Transparency changes the kind of shape.+UIView *SGRGlassInside(UIView *control, const void *key, CGFloat side);++// A glass button of the redesign's own: a circle with a symbol, or a capsule with a symbol and a+// title, prominent (light glass, dark content) for the one main action of a screen. UIKit's glass+// button configuration on iOS 26, with its own press response; a spring to 0.96 on the stand-ins.+@interface SGRGlassButton : UIButton++ (instancetype)circleWithSymbol:(NSString *)symbol accessibilityLabel:(NSString *)label;++ (instancetype)capsuleWithSymbol:(NSString *)symbol title:(NSString *)title prominent:(BOOL)prominent;+@property (nonatomic, copy) void (^onTap)(void);+// On tints the symbol with SGRAccent (shuffle on, following); it is also the accessibility value.+@property (nonatomic, getter=isOn) BOOL on;+// A symbol swap replaces the glyph with UIKit's symbol transition (none under Reduce Motion); a title+// swap crossfades. The same symbol or title again is a no-op.+- (void)setSymbol:(NSString *)symbol animated:(BOOL)animated;+- (void)setTitle:(NSString *)title animated:(BOOL)animated;+@end++// A centred row of glass buttons in one container, SGRActionSpacing apart and SGRActionHeight tall:+// circles SGRActionHeight wide, a prominent capsule at least 132, other capsules 96 to 140. Its+// own touches pass through; only the buttons take them.+@interface SGRActionRow : UIView+@property (nonatomic, copy) NSArray<UIButton *> *buttons;+@enddiff --git a/tweak/Sources/Redesign/Kit/SGRGlass.m b/tweak/Sources/Redesign/Kit/SGRGlass.mnew file mode 100644index 00000000..59907295--- /dev/null+++ b/tweak/Sources/Redesign/Kit/SGRGlass.m@@ -0,0 +1,393 @@+#import "Core/SGCore.h"+#import "SGRGlass.h"+#import "SGRTokens.h"++static const CGFloat kSymbolSize = 17, kPressScale = 0.96;+static const CGFloat kProminentMinWidth = 132, kCapsuleMinWidth = 96, kCapsuleMaxWidth = 140, kCapsulePadding = 20;+static const NSTimeInterval kTitleFade = 0.2;++typedef NS_ENUM(NSInteger, SGRGlassMode) {+ SGRGlassModeGlass,+ SGRGlassModeBlur,+ SGRGlassModeSolid,+};++static SGRGlassMode glassMode(void) {+ if (SGRReduceTransparency()) return SGRGlassModeSolid;+ if (@available(iOS 26.0, *)) return SGRGlassModeGlass;+ return SGRGlassModeBlur;+}++// The container glass shapes merge in, or a plain view where there is no glass to merge.+static UIView *newContainer(SGRGlassMode mode, CGFloat spacing) {+ if (mode == SGRGlassModeGlass) {+ if (@available(iOS 26.0, *)) {+ UIGlassContainerEffect *effect = [UIGlassContainerEffect new];+ effect.spacing = spacing;+ return [[UIVisualEffectView alloc] initWithEffect:effect];+ }+ }+ return [UIView new];+}++static UIView *contentOf(UIView *container) {+ return [container isKindOfClass:UIVisualEffectView.class] ? ((UIVisualEffectView *)container).contentView : container;+}++static UIView *newShape(SGRGlassMode mode) {+ UIView *shape;+ switch (mode) {+ case SGRGlassModeGlass:+ shape = [[UIVisualEffectView alloc] initWithEffect:SGGlassEffect()];+ break;+ case SGRGlassModeBlur:+ shape = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleSystemThinMaterialDark]];+ break;+ case SGRGlassModeSolid:+ shape = [UIView new];+ shape.backgroundColor = SGRSolidGlassFill();+ break;+ }+ shape.userInteractionEnabled = NO;+ return shape;+}++#pragma mark - inside a control++static char kInsideModeKey;++UIView *SGRGlassInside(UIView *control, const void *key, CGFloat side) {+ if (!control || !key) return nil;+ SGRGlassMode mode = glassMode();+ UIView *shape = objc_getAssociatedObject(control, key);+ if (shape && [objc_getAssociatedObject(shape, &kInsideModeKey) integerValue] != mode) {+ [shape removeFromSuperview];+ shape = nil;+ }+ if (!shape) {+ shape = newShape(mode);+ shape.accessibilityElementsHidden = YES;+ // Last among the control's subviews, so code of Spotify's reading its first subview still finds+ // its own; the depth puts it behind them all the same.+ shape.layer.zPosition = -1;+ shape.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin+ | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;+ objc_setAssociatedObject(shape, &kInsideModeKey, @(mode), OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ objc_setAssociatedObject(control, key, shape, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ }+ if (shape.superview != control) [control addSubview:shape];+ shape.hidden = side <= 0;+ CGRect bounds = CGRectMake(0, 0, side, side);+ if (!CGRectEqualToRect(shape.bounds, bounds)) {+ shape.bounds = bounds;+ SGShapeGlass(shape, side / 2, YES);+ }+ CGPoint middle = CGPointMake(CGRectGetMidX(control.bounds), CGRectGetMidY(control.bounds));+ if (!CGPointEqualToPoint(shape.center, middle)) shape.center = middle;+ return shape;+}++#pragma mark - backing++@implementation SGRGlassBacking {+ UIView *_container;+ NSMutableArray<UIView *> *_shapes;+ SGRGlassMode _mode;+}+++ (instancetype)backingInHost:(UIView *)host key:(const void *)key {+ if (!host || !key) return nil;+ SGRGlassBacking *backing = objc_getAssociatedObject(host, key);+ if (!backing) {+ backing = [[self alloc] initWithFrame:host.bounds];+ objc_setAssociatedObject(host, key, backing, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ }+ if (backing.superview != host) [host insertSubview:backing atIndex:0];+ if (!CGRectEqualToRect(backing.frame, host.bounds)) backing.frame = host.bounds;+ return backing;+}++- (instancetype)initWithFrame:(CGRect)frame {+ if (!(self = [super initWithFrame:frame])) return nil;+ self.userInteractionEnabled = NO;+ self.accessibilityElementsHidden = YES;+ // Behind whatever the host puts in at index 0 after it, as the panes of Core/SGGlass.m are.+ self.layer.zPosition = -1;+ _shapes = [NSMutableArray array];+ _mode = -1;+ return self;+}++- (void)layoutSubviews {+ [super layoutSubviews];+ _container.frame = self.bounds;+}++// Reduce Transparency can change while the page is open; the shapes are made again for it.+- (void)rebuildIfNeeded {+ SGRGlassMode mode = glassMode();+ if (mode == _mode) return;+ _mode = mode;+ [_shapes makeObjectsPerformSelector:@selector(removeFromSuperview)];+ [_shapes removeAllObjects];+ [_container removeFromSuperview];+ _container = newContainer(mode, SGRGlassSpacing);+ _container.userInteractionEnabled = NO;+ _container.frame = self.bounds;+ [self addSubview:_container];+}++- (UIView *)newShape {+ return newShape(_mode);+}++- (void)setShapes:(NSArray<NSValue *> *)framesInHost shape:(SGRGlassShape)kind {+ [self rebuildIfNeeded];+ NSUInteger count = 0;+ for (NSValue *value in framesInHost) {+ CGRect frame = [self convertRect:value.CGRectValue fromView:self.superview];+ if (CGRectIsEmpty(frame) || CGRectIsNull(frame)) continue;+ if (kind == SGRGlassCircle) {+ CGFloat side = MIN(frame.size.width, frame.size.height);+ frame = CGRectMake(CGRectGetMidX(frame) - side / 2, CGRectGetMidY(frame) - side / 2, side, side);+ }+ while (_shapes.count <= count) {+ UIView *shape = [self newShape];+ [contentOf(_container) addSubview:shape];+ [_shapes addObject:shape];+ }+ UIView *shape = _shapes[count++];+ shape.hidden = NO;+ if (!CGRectEqualToRect(shape.frame, frame)) {+ shape.frame = frame;+ SGShapeGlass(shape, frame.size.height / 2, YES);+ }+ }+ for (NSUInteger i = count; i < _shapes.count; i++) _shapes[i].hidden = YES;+}++@end++#pragma mark - buttons++@interface SGRGlassButton ()+- (CGFloat)rowWidth;+@end++@implementation SGRGlassButton {+ NSString *_symbol;+ NSString *_title;+ BOOL _prominent;+ BOOL _circle;+ SGRGlassMode _mode;+}+++ (instancetype)circleWithSymbol:(NSString *)symbol accessibilityLabel:(NSString *)label {+ SGRGlassButton *button = [[self alloc] initWithFrame:CGRectMake(0, 0, SGRActionHeight, SGRActionHeight)];+ button->_circle = YES;+ button->_symbol = [symbol copy];+ button.accessibilityLabel = label;+ [button configure];+ return button;+}+++ (instancetype)capsuleWithSymbol:(NSString *)symbol title:(NSString *)title prominent:(BOOL)prominent {+ SGRGlassButton *button = [[self alloc] initWithFrame:CGRectMake(0, 0, kCapsuleMinWidth, SGRActionHeight)];+ button->_symbol = [symbol copy];+ button->_title = [title copy];+ button->_prominent = prominent;+ [button configure];+ return button;+}++- (instancetype)initWithFrame:(CGRect)frame {+ if (!(self = [super initWithFrame:frame])) return nil;+ _mode = -1;+ [self addTarget:self action:@selector(tapped) forControlEvents:UIControlEventPrimaryActionTriggered];+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(settingsChanged:) name:UIAccessibilityReduceTransparencyStatusDidChangeNotification object:nil];+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(settingsChanged:) name:UIContentSizeCategoryDidChangeNotification object:nil];+ return self;+}++- (void)dealloc {+ [NSNotificationCenter.defaultCenter removeObserver:self];+}++- (void)tapped {+ if (self.onTap) self.onTap();+}++- (void)settingsChanged:(NSNotification *)note {+ [self configure];+}++// Above the Large content size the title would outgrow the 48pt button, so only the symbol is shown+// and the title stays the accessibility label.+static BOOL titleFits(void) {+ UIContentSizeCategory current = UIApplication.sharedApplication.preferredContentSizeCategory;+ return UIContentSizeCategoryCompareToCategory(current, UIContentSizeCategoryLarge) != NSOrderedDescending;+}++- (UIColor *)contentColor {+ if (_on) return SGRAccent();+ return _prominent ? UIColor.blackColor : SGRPrimary();+}++- (void)configure {+ SGRGlassMode mode = glassMode();+ UIButtonConfiguration *config = nil;+ if (mode == SGRGlassModeGlass) {+ if (@available(iOS 26.0, *)) {+ config = _prominent ? [UIButtonConfiguration prominentGlassButtonConfiguration] : [UIButtonConfiguration glassButtonConfiguration];+ if (_prominent) config.baseBackgroundColor = [UIColor colorWithWhite:0.96 alpha:1];+ }+ }+ if (!config) {+ config = [UIButtonConfiguration filledButtonConfiguration];+ config.baseBackgroundColor = _prominent ? [UIColor colorWithWhite:0.96 alpha:1] : (mode == SGRGlassModeBlur ? [UIColor colorWithWhite:1 alpha:0.12] : SGRSolidGlassFill());+ if (mode == SGRGlassModeBlur && !_prominent) {+ config.background.customView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleSystemThinMaterialDark]];+ }+ }+ _mode = mode;+ config.cornerStyle = UIButtonConfigurationCornerStyleCapsule;+ config.baseForegroundColor = [self contentColor];+ config.image = _symbol ? [UIImage systemImageNamed:_symbol] : nil;+ config.preferredSymbolConfigurationForImage = [UIImageSymbolConfiguration configurationWithPointSize:kSymbolSize weight:UIImageSymbolWeightSemibold];+ config.imagePadding = 6;+ if (_circle) {+ config.contentInsets = NSDirectionalEdgeInsetsZero;+ } else {+ config.contentInsets = NSDirectionalEdgeInsetsMake(0, kCapsulePadding, 0, kCapsulePadding);+ BOOL showTitle = _title.length && (titleFits() || !_symbol);+ UIFont *font = SGRFont(UIFontTextStyleBody, UIFontWeightSemibold, UIContentSizeCategoryLarge);+ config.attributedTitle = showTitle ? [[NSAttributedString alloc] initWithString:_title attributes:@{NSFontAttributeName: font}] : nil;+ self.accessibilityLabel = _title;+ }+ self.showsLargeContentViewer = YES;+ self.largeContentTitle = _title ?: self.accessibilityLabel;+ self.largeContentImage = config.image;+ self.configuration = config;+}++- (void)setOn:(BOOL)on {+ self.accessibilityValue = on ? @"On" : @"Off";+ if (on == _on) return;+ _on = on;+ [self configure];+}++- (void)setSymbol:(NSString *)symbol animated:(BOOL)animated {+ if (!symbol || [symbol isEqualToString:_symbol]) return;+ _symbol = [symbol copy];+ if (@available(iOS 17.0, *)) self.symbolAnimationEnabled = animated && !SGRReduceMotion() && self.window;+ [self configure];+}++- (void)setTitle:(NSString *)title animated:(BOOL)animated {+ if (!title || [title isEqualToString:_title]) return;+ _title = [title copy];+ if (!animated || !self.window) {+ [self configure];+ return;+ }+ [UIView transitionWithView:self duration:kTitleFade options:UIViewAnimationOptionTransitionCrossDissolve | UIViewAnimationOptionAllowUserInteraction animations:^{+ [self configure];+ } completion:nil];+}++// UIKit's glass buttons answer a press themselves; the stand-ins get the Kit's press spring.+- (void)setHighlighted:(BOOL)highlighted {+ [super setHighlighted:highlighted];+ if (_mode == SGRGlassModeGlass) return;+ SGRAnimate(SGRMotionPress, ^{+ self.transform = highlighted ? CGAffineTransformMakeScale(kPressScale, kPressScale) : CGAffineTransformIdentity;+ }, nil);+}++// The width the action row gives the button.+- (CGFloat)rowWidth {+ if (_circle) return SGRActionHeight;+ CGFloat natural = ceil([self sizeThatFits:CGSizeMake(CGFLOAT_MAX, SGRActionHeight)].width);+ if (_prominent) return MAX(kProminentMinWidth, natural);+ return MIN(kCapsuleMaxWidth, MAX(kCapsuleMinWidth, natural));+}++@end++#pragma mark - action row++@implementation SGRActionRow {+ UIView *_container;+ SGRGlassMode _mode;+}++- (instancetype)initWithFrame:(CGRect)frame {+ if (!(self = [super initWithFrame:frame])) return nil;+ _mode = -1;+ [self rebuildIfNeeded];+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(transparencyChanged:) name:UIAccessibilityReduceTransparencyStatusDidChangeNotification object:nil];+ return self;+}++- (void)dealloc {+ [NSNotificationCenter.defaultCenter removeObserver:self];+}++- (void)transparencyChanged:(NSNotification *)note {+ [self rebuildIfNeeded];+ [self setNeedsLayout];+}++- (void)rebuildIfNeeded {+ SGRGlassMode mode = glassMode();+ if (mode == _mode) return;+ _mode = mode;+ [_container removeFromSuperview];+ _container = newContainer(mode, SGRActionSpacing);+ [self addSubview:_container];+ for (UIButton *button in _buttons) [contentOf(_container) addSubview:button];+}++- (void)setButtons:(NSArray<UIButton *> *)buttons {+ for (UIButton *button in _buttons) {+ if (![buttons containsObject:button]) [button removeFromSuperview];+ }+ _buttons = [buttons copy];+ for (UIButton *button in _buttons) [contentOf(_container) addSubview:button];+ [self setNeedsLayout];+}++static CGFloat widthInRow(UIButton *button) {+ if ([button isKindOfClass:SGRGlassButton.class]) return [(SGRGlassButton *)button rowWidth];+ CGFloat natural = ceil([button sizeThatFits:CGSizeMake(CGFLOAT_MAX, SGRActionHeight)].width);+ return MIN(kCapsuleMaxWidth, MAX(kCapsuleMinWidth, natural));+}++- (CGSize)sizeThatFits:(CGSize)size {+ CGFloat total = 0;+ for (UIButton *button in _buttons) total += widthInRow(button);+ if (_buttons.count > 1) total += SGRActionSpacing * (_buttons.count - 1);+ return CGSizeMake(total, SGRActionHeight);+}++- (void)layoutSubviews {+ [super layoutSubviews];+ CGSize row = [self sizeThatFits:self.bounds.size];+ CGSize bounds = self.bounds.size;+ _container.frame = CGRectMake(floor((bounds.width - row.width) / 2), floor((bounds.height - row.height) / 2), row.width, row.height);+ CGFloat x = 0;+ for (UIButton *button in _buttons) {+ CGFloat width = widthInRow(button);+ button.bounds = CGRectMake(0, 0, width, SGRActionHeight);+ button.center = CGPointMake(x + width / 2, SGRActionHeight / 2);+ x += width + SGRActionSpacing;+ }+}++- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {+ UIView *hit = [super hitTest:point withEvent:event];+ return (hit == self || hit == _container || hit == contentOf(_container)) ? nil : hit;+}++@enddiff --git a/tweak/Sources/Redesign/Kit/SGRGlyph.h b/tweak/Sources/Redesign/Kit/SGRGlyph.hnew file mode 100644index 00000000..b5c407ff--- /dev/null+++ b/tweak/Sources/Redesign/Kit/SGRGlyph.h@@ -0,0 +1,26 @@+// Bare glyphs: an SF Symbol drawn over or instead of one of Spotify's own glyphs (the player's previous,+// play and next), and a glyph button of the Kit's own where Spotify has no control (the lyrics glyph in+// the player's footer). No glass: these sit in rows of controls, where a pane each would turn the row+// into glass sampling glass.+//+// Ownership: whoever adds them. Threading: main thread only.+#import <UIKit/UIKit.h>++// Takes no touches and is hidden from accessibility, so the Spotify control under it keeps both; put+// inside that control, it follows the control's own alpha when disabled or highlighted.+@interface SGRGlyphView : UIImageView+- (instancetype)initWithSymbol:(NSString *)symbol pointSize:(CGFloat)size weight:(UIImageSymbolWeight)weight;+@property (nonatomic, readonly) NSString *symbol;+// A swap replaces the glyph with the symbol transition on iOS 17 (none under Reduce Motion); the same+// symbol again is a no-op.+- (void)setSymbol:(NSString *)symbol animated:(BOOL)animated;+@end++// A glyph that is a button: at least 44pt to touch whatever the glyph's size, dims and springs back+// when pressed, 0.35 alpha and "dimmed" to VoiceOver when disabled, and shows the large content+// viewer with its title when held at accessibility text sizes.+@interface SGRGlyphButton : UIControl++ (instancetype)buttonWithSymbol:(NSString *)symbol pointSize:(CGFloat)size title:(NSString *)accessibilityTitle;+@property (nonatomic, readonly) SGRGlyphView *glyph;+@property (nonatomic, copy) void (^onTap)(void);+@enddiff --git a/tweak/Sources/Redesign/Kit/SGRGlyph.m b/tweak/Sources/Redesign/Kit/SGRGlyph.mnew file mode 100644index 00000000..fd4423fb--- /dev/null+++ b/tweak/Sources/Redesign/Kit/SGRGlyph.m@@ -0,0 +1,108 @@+#import "Core/SGCore.h"+#import "SGRGlyph.h"+#import "SGRTokens.h"++static const CGFloat kMinTouch = 44, kPressAlpha = 0.5, kPressScale = 0.9, kDisabledAlpha = 0.35;++@implementation SGRGlyphView {+ NSString *_symbol;+}++- (instancetype)initWithSymbol:(NSString *)symbol pointSize:(CGFloat)size weight:(UIImageSymbolWeight)weight {+ if (!(self = [super initWithFrame:CGRectZero])) return nil;+ _symbol = [symbol copy];+ self.preferredSymbolConfiguration = [UIImageSymbolConfiguration configurationWithPointSize:size weight:weight];+ self.image = symbol ? [UIImage systemImageNamed:symbol] : nil;+ self.tintColor = SGRPrimary();+ self.contentMode = UIViewContentModeCenter;+ self.userInteractionEnabled = NO;+ self.isAccessibilityElement = NO;+ self.accessibilityElementsHidden = YES;+ [self sizeToFit];+ return self;+}++- (NSString *)symbol {+ return _symbol;+}++- (void)setSymbol:(NSString *)symbol animated:(BOOL)animated {+ if (!symbol || [symbol isEqualToString:_symbol]) return;+ _symbol = [symbol copy];+ UIImage *image = [UIImage systemImageNamed:symbol];+ if (@available(iOS 17.0, *)) {+ if (animated && image && self.window && !SGRReduceMotion()) {+ [self setSymbolImage:image withContentTransition:[NSSymbolReplaceContentTransition transition]];+ return;+ }+ }+ self.image = image;+}++@end++@implementation SGRGlyphButton {+ SGRGlyphView *_glyph;+}+++ (instancetype)buttonWithSymbol:(NSString *)symbol pointSize:(CGFloat)size title:(NSString *)accessibilityTitle {+ SGRGlyphButton *button = [[self alloc] initWithFrame:CGRectMake(0, 0, kMinTouch, kMinTouch)];+ button->_glyph = [[SGRGlyphView alloc] initWithSymbol:symbol pointSize:size weight:UIImageSymbolWeightRegular];+ [button addSubview:button->_glyph];+ button.isAccessibilityElement = YES;+ button.accessibilityLabel = accessibilityTitle;+ button.accessibilityTraits = UIAccessibilityTraitButton;+ button.showsLargeContentViewer = YES;+ button.largeContentTitle = accessibilityTitle;+ button.largeContentImage = button->_glyph.image;+ [button addInteraction:[UILargeContentViewerInteraction new]];+ [button addTarget:button action:@selector(tapped) forControlEvents:UIControlEventPrimaryActionTriggered];+ return button;+}++- (SGRGlyphView *)glyph {+ return _glyph;+}++- (void)tapped {+ if (self.onTap) self.onTap();+}++- (CGSize)intrinsicContentSize {+ CGSize glyph = _glyph.intrinsicContentSize;+ return CGSizeMake(MAX(kMinTouch, glyph.width), MAX(kMinTouch, glyph.height));+}++- (CGSize)sizeThatFits:(CGSize)size {+ return self.intrinsicContentSize;+}++- (void)layoutSubviews {+ [super layoutSubviews];+ _glyph.bounds = (CGRect){CGPointZero, _glyph.intrinsicContentSize};+ _glyph.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));+}++// However small the frame it is given, a touch 44pt around its centre counts.+- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {+ CGRect bounds = self.bounds;+ CGFloat dx = MAX(0, (kMinTouch - bounds.size.width) / 2), dy = MAX(0, (kMinTouch - bounds.size.height) / 2);+ return CGRectContainsPoint(CGRectInset(bounds, -dx, -dy), point);+}++- (void)setHighlighted:(BOOL)highlighted {+ [super setHighlighted:highlighted];+ SGRGlyphView *glyph = _glyph;+ SGRAnimate(SGRMotionPress, ^{+ glyph.alpha = highlighted ? kPressAlpha : 1;+ glyph.transform = highlighted ? CGAffineTransformMakeScale(kPressScale, kPressScale) : CGAffineTransformIdentity;+ }, nil);+}++- (void)setEnabled:(BOOL)enabled {+ [super setEnabled:enabled];+ self.alpha = enabled ? 1 : kDisabledAlpha;+ self.accessibilityTraits = enabled ? UIAccessibilityTraitButton : UIAccessibilityTraitButton | UIAccessibilityTraitNotEnabled;+}++@enddiff --git a/tweak/Sources/Redesign/Kit/SGRHero.h b/tweak/Sources/Redesign/Kit/SGRHero.hnew file mode 100644index 00000000..764b44f4--- /dev/null+++ b/tweak/Sources/Redesign/Kit/SGRHero.h@@ -0,0 +1,36 @@+// The hero header of a redesigned page (the artist page first): the picture across the full width+// under the status bar, its lower part going soft through a blurred copy and dissolving into the+// field colour, the title and a meta line over the dissolved part, and a slot for the action row+// (SGRGlass.h) under them. Laid out for whatever height it is given, measured from its bottom edge:+//+// title bottom at H - 98, large title bold, up to 2 lines, centred, scales down to 0.7+// meta H - 94, 18 tall, footnote in SGRSecondary, hidden while empty+// actionSlot H - 64, 48 tall, full width+// dissolve field colour from transparent at 0.45 H to opaque at H+//+// Scrolling moves only transforms and alphas (applyScrollOffset:), never frames or layout: the picture+// stretches from its bottom edge on overscroll, drifts at 0.3 of the scroll speed after that, and the+// texts and actions fade before they reach the top bar. Under Reduce Motion only the fade is left.+//+// Ownership: the screen owns the hero and puts it in its page. The hero keeps a weak reference to the+// field it is bound to and the images it was given.+// Threading: main thread only; the blurred copy is made off it.+#import <UIKit/UIKit.h>++@class SGRArtworkField;++@interface SGRHeroHeader : UIView+@property (nonatomic, copy) NSString *title;+@property (nonatomic, copy) NSString *meta;+// Where the action row goes; the hero lays out nothing inside it.+@property (nonatomic, readonly) UIView *actionSlot;++// The picture fades in over 0.25s and its blurred copy follows when it is ready; the same image+// again is a no-op, nil leaves the picture as it is.+- (void)setImage:(UIImage *)image animated:(BOOL)animated;+// The dissolve takes the field's colour now and crossfades with it from then on.+- (void)bindToField:(SGRArtworkField *)field;+// `offset` is the page's vertical scroll offset with 0 at rest (negative on overscroll), `distance`+// how far the page scrolls before the header is pinned under the top bar.+- (void)applyScrollOffset:(CGFloat)offset collapseDistance:(CGFloat)distance;+@enddiff --git a/tweak/Sources/Redesign/Kit/SGRHero.m b/tweak/Sources/Redesign/Kit/SGRHero.mnew file mode 100644index 00000000..a4843de1--- /dev/null+++ b/tweak/Sources/Redesign/Kit/SGRHero.m@@ -0,0 +1,275 @@+#import "Core/SGCore.h"+#import "SGRHero.h"+#import "SGRField.h"+#import "SGRPalette.h"+#import "SGRTokens.h"++static const CGFloat kTitleBottom = 98, kMetaTop = 94, kMetaHeight = 18, kActionTop = 64;+static const CGFloat kScrimHeight = 140, kScrimAlpha = 0.3;+static const CGFloat kDissolveFrom = 0.45, kDissolveMid = 0.72, kDissolveMidAlpha = 0.55;+static const CGFloat kParallax = 0.3;+static const CGFloat kFadeStart = 300, kFadeLength = 120; // above the hero's bottom edge, in points of scroll+// The picture's clip reaches this far above the hero so an overscroll stretch can grow upwards; it+// clips the sides and the bottom only.+static const CGFloat kStretchRoom = 1000;+static const NSTimeInterval kImageFade = 0.25;++@interface SGRGradientView : UIView+@end++@implementation SGRGradientView++ (Class)layerClass {+ return CAGradientLayer.class;+}+@end++@implementation SGRHeroHeader {+ UIView *_clip;+ UIImageView *_photo;+ UIImageView *_blurred;+ SGRGradientView *_dissolve;+ UILabel *_titleLabel;+ UILabel *_metaLabel;+ UIView *_actionSlot;+ __weak SGRArtworkField *_field;+ UIImage *_image;+ NSUInteger _generation;+ CGFloat _lastPictureOffset, _lastFade;+}++- (instancetype)initWithFrame:(CGRect)frame {+ if (!(self = [super initWithFrame:frame])) return nil;+ _lastPictureOffset = NAN;+ _lastFade = NAN;++ _clip = [UIView new];+ _clip.clipsToBounds = YES;+ _clip.userInteractionEnabled = NO;+ _clip.accessibilityElementsHidden = YES;+ [self addSubview:_clip];++ _photo = [UIImageView new];+ _photo.contentMode = UIViewContentModeScaleAspectFill;+ CAGradientLayer *scrim = [CAGradientLayer layer];+ scrim.colors = @[(id)[UIColor colorWithWhite:0 alpha:kScrimAlpha].CGColor, (id)[UIColor colorWithWhite:0 alpha:0].CGColor];+ [_photo.layer addSublayer:scrim];+ [_clip addSubview:_photo];++ _blurred = [UIImageView new];+ _blurred.contentMode = UIViewContentModeScaleAspectFill;+ _blurred.alpha = 0;+ [_clip addSubview:_blurred];++ _dissolve = [SGRGradientView new];+ [self paintDissolve:SGRNeutralField() animated:NO];+ [_clip addSubview:_dissolve];++ _titleLabel = [UILabel new];+ _titleLabel.textColor = SGRPrimary();+ _titleLabel.textAlignment = NSTextAlignmentCenter;+ _titleLabel.numberOfLines = 2;+ _titleLabel.adjustsFontSizeToFitWidth = YES;+ _titleLabel.minimumScaleFactor = 0.7;+ _titleLabel.accessibilityTraits = UIAccessibilityTraitHeader;+ [self addSubview:_titleLabel];++ _metaLabel = [UILabel new];+ _metaLabel.textColor = SGRSecondary();+ _metaLabel.textAlignment = NSTextAlignmentCenter;+ _metaLabel.isAccessibilityElement = NO;+ [self addSubview:_metaLabel];++ _actionSlot = [UIView new];+ [self addSubview:_actionSlot];++ [self applyFonts];+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(contentSizeChanged:) name:UIContentSizeCategoryDidChangeNotification object:nil];+ return self;+}++- (void)dealloc {+ [NSNotificationCenter.defaultCenter removeObserver:self];+}++- (UIView *)actionSlot {+ return _actionSlot;+}++- (void)applyFonts {+ // The header keeps Spotify's height, so at the largest sizes the title shrinks rather than grows.+ _titleLabel.font = SGRFont(UIFontTextStyleLargeTitle, UIFontWeightBold, UIContentSizeCategoryAccessibilityMedium);+ _metaLabel.font = SGRFont(UIFontTextStyleFootnote, UIFontWeightRegular, UIContentSizeCategoryExtraExtraExtraLarge);+}++- (void)contentSizeChanged:(NSNotification *)note {+ [self applyFonts];+ [self setNeedsLayout];+}++#pragma mark - content++- (NSString *)title {+ return _titleLabel.text;+}++- (void)setTitle:(NSString *)title {+ if ([title isEqualToString:_titleLabel.text] || (!title && !_titleLabel.text)) return;+ _titleLabel.text = title;+ [self updateAccessibility];+ [self setNeedsLayout];+}++- (NSString *)meta {+ return _metaLabel.text;+}++- (void)setMeta:(NSString *)meta {+ if ([meta isEqualToString:_metaLabel.text] || (!meta && !_metaLabel.text)) return;+ _metaLabel.text = meta;+ _metaLabel.hidden = meta.length == 0;+ [self updateAccessibility];+}++// The meta line is read with the title, as one element.+- (void)updateAccessibility {+ NSString *title = _titleLabel.text ?: @"";+ _titleLabel.accessibilityLabel = _metaLabel.text.length ? [NSString stringWithFormat:@"%@, %@", title, _metaLabel.text] : title;+}++- (void)setImage:(UIImage *)image animated:(BOOL)animated {+ if (!image || image == _image) return;+ _image = image;+ animated = animated && self.window;+ UIImageView *photo = _photo;+ if (animated) {+ [UIView transitionWithView:photo duration:kImageFade options:UIViewAnimationOptionTransitionCrossDissolve | UIViewAnimationOptionAllowUserInteraction animations:^{+ photo.image = image;+ } completion:nil];+ } else {+ photo.image = image;+ }++ NSUInteger generation = ++_generation;+ SGRPaletteRequest request = {CGSizeZero, YES, NO};+ __weak SGRHeroHeader *weakSelf = self;+ [SGRPalette paletteForImage:image request:request completion:^(SGRPalette *palette) {+ SGRHeroHeader *hero = weakSelf;+ if (!hero || !palette.dissolve || generation != hero->_generation) return;+ [hero showBlurred:palette.dissolve];+ }];+}++- (void)showBlurred:(UIImage *)image {+ UIImageView *blurred = _blurred;+ if (!self.window) {+ blurred.image = image;+ blurred.alpha = 1;+ return;+ }+ if (blurred.alpha > 0) {+ [UIView transitionWithView:blurred duration:SGRCrossfade options:UIViewAnimationOptionTransitionCrossDissolve | UIViewAnimationOptionAllowUserInteraction animations:^{+ blurred.image = image;+ } completion:nil];+ return;+ }+ blurred.image = image;+ SGRAnimate(SGRMotionFade, ^{ blurred.alpha = 1; }, nil);+}++- (void)bindToField:(SGRArtworkField *)field {+ if (_field) [NSNotificationCenter.defaultCenter removeObserver:self name:SGRFieldColorDidChangeNotification object:_field];+ _field = field;+ if (!field) return;+ [self paintDissolve:field.fieldColor animated:NO];+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(fieldColorChanged:) name:SGRFieldColorDidChangeNotification object:field];+}++- (void)fieldColorChanged:(NSNotification *)note {+ UIColor *color = note.userInfo[@"color"];+ if (color) [self paintDissolve:color animated:self.window != nil];+}++// Started in the same transaction as the field's own colour animation, so the two stay one colour.+- (void)paintDissolve:(UIColor *)color animated:(BOOL)animated {+ CAGradientLayer *layer = (CAGradientLayer *)_dissolve.layer;+ NSArray *from = ((CAGradientLayer *)layer.presentationLayer ?: layer).colors;+ NSArray *to = @[(id)[color colorWithAlphaComponent:0].CGColor, (id)[color colorWithAlphaComponent:kDissolveMidAlpha].CGColor, (id)color.CGColor];+ [CATransaction begin];+ [CATransaction setDisableActions:YES];+ layer.colors = to;+ layer.locations = @[@0, @((kDissolveMid - kDissolveFrom) / (1 - kDissolveFrom)), @1];+ [CATransaction commit];+ if (!animated || !from) return;+ CABasicAnimation *fade = [CABasicAnimation animationWithKeyPath:@"colors"];+ fade.fromValue = from;+ fade.toValue = layer.colors;+ fade.duration = SGRCrossfade;+ fade.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];+ [layer addAnimation:fade forKey:@"colors"];+}++#pragma mark - layout and scroll++// Only the action row takes touches; anywhere else the touch belongs to the page under the hero.+- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {+ UIView *hit = [super hitTest:point withEvent:event];+ return hit == self ? nil : hit;+}++- (void)layoutSubviews {+ [super layoutSubviews];+ CGFloat width = self.bounds.size.width, height = self.bounds.size.height;+ CGRect picture = CGRectMake(0, kStretchRoom, width, height);+ [UIView performWithoutAnimation:^{+ CGAffineTransform photoTransform = _photo.transform, blurredTransform = _blurred.transform;+ _photo.transform = CGAffineTransformIdentity;+ _blurred.transform = CGAffineTransformIdentity;+ _clip.frame = CGRectMake(0, -kStretchRoom, width, height + kStretchRoom);+ _photo.frame = picture;+ _blurred.frame = picture;+ _photo.transform = photoTransform;+ _blurred.transform = blurredTransform;+ _dissolve.frame = CGRectMake(0, kStretchRoom + height * kDissolveFrom, width, height * (1 - kDissolveFrom));+ [CATransaction begin];+ [CATransaction setDisableActions:YES];+ _photo.layer.sublayers.firstObject.frame = CGRectMake(0, 0, width, kScrimHeight);+ [CATransaction commit];++ CGFloat textWidth = MAX(0, width - 2 * SGRSideMargin);+ CGFloat twoLines = ceil(_titleLabel.font.lineHeight * 2);+ CGFloat titleHeight = MIN(twoLines, ceil([_titleLabel sizeThatFits:CGSizeMake(textWidth, CGFLOAT_MAX)].height));+ _titleLabel.frame = CGRectMake(SGRSideMargin, height - kTitleBottom - titleHeight, textWidth, titleHeight);+ _metaLabel.frame = CGRectMake(SGRSideMargin, height - kMetaTop, textWidth, MAX(kMetaHeight, ceil(_metaLabel.font.lineHeight)));+ _actionSlot.frame = CGRectMake(0, height - kActionTop, width, SGRActionHeight);+ }];+}++- (void)applyScrollOffset:(CGFloat)offset collapseDistance:(CGFloat)distance {+ CGFloat height = self.bounds.size.height;+ if (height <= 0) return;+ CGFloat pictureOffset = SGRReduceMotion() ? 0 : MIN(offset, MAX(0, distance));+ if (pictureOffset != _lastPictureOffset) {+ _lastPictureOffset = pictureOffset;+ CGAffineTransform transform = CGAffineTransformIdentity;+ if (pictureOffset < 0) {+ // Scaled about the centre, then moved so the bottom edge stays where it is.+ CGFloat scale = (height - pictureOffset) / height;+ transform = CGAffineTransformMake(scale, 0, 0, scale, 0, height / 2 * (1 - scale));+ } else if (pictureOffset > 0) {+ transform = CGAffineTransformMakeTranslation(0, kParallax * pictureOffset);+ }+ _photo.transform = transform;+ _blurred.transform = transform;+ }+ CGFloat fade = MIN(1, MAX(0, (offset - (height - kFadeStart)) / kFadeLength));+ if (fade != _lastFade) {+ _lastFade = fade;+ CGFloat alpha = 1 - fade;+ _titleLabel.alpha = alpha;+ _metaLabel.alpha = alpha;+ _actionSlot.alpha = alpha;+ _actionSlot.userInteractionEnabled = alpha > 0.1;+ }+}++@enddiff --git a/tweak/Sources/Redesign/Kit/SGRKit.h b/tweak/Sources/Redesign/Kit/SGRKit.hnew file mode 100644index 00000000..06585bab--- /dev/null+++ b/tweak/Sources/Redesign/Kit/SGRKit.h@@ -0,0 +1,26 @@+// The Redesign Kit: what every redesigned screen (Redesign/<Screen>/) builds on, so the screens share+// one look and nothing is hand-rolled per screen. A screen imports this and Core/SGCore.h.+//+// SGRedesign.h the switch per screen, the flags a screen forces, the Redesign page+// SGRTokens.h colours, type, spacing, radii, motion, the accessibility settings+// SGRPalette.h the artwork's edge colour, the field colour and the pre-blurred bitmaps+// SGRField.h the artwork field behind a page, and content cards on it+// SGRHero.h the full-width hero header with title, meta and the action slot+// SGRGlass.h glass behind Spotify's controls, glass buttons, the action row+// SGRGlyph.h bare glyph overlays and glyph buttons+// SGRRestyle.h keeping Spotify's views restyled: suppress, digits, lookups, cells, repaint roots+// SGRBridges.h player state, now playing artwork, links, the player's open and close+//+// A screen's hooks install only while its switch is on: every .x of a screen ends with+// %ctor { if (!SGRedesignOn(@"<screen>")) return; %init; SGRequireClasses(@[...]); }+// and the legacy hooks of that screen stand aside with the same test, so with every switch off the mod+// behaves exactly as it did before the Kit.+#import "SGRedesign.h"+#import "SGRTokens.h"+#import "SGRPalette.h"+#import "SGRField.h"+#import "SGRHero.h"+#import "SGRGlass.h"+#import "SGRGlyph.h"+#import "SGRRestyle.h"+#import "SGRBridges.h"diff --git a/tweak/Sources/Redesign/Kit/SGRPalette.h b/tweak/Sources/Redesign/Kit/SGRPalette.hnew file mode 100644index 00000000..56192698--- /dev/null+++ b/tweak/Sources/Redesign/Kit/SGRPalette.h@@ -0,0 +1,36 @@+// What a redesigned page takes from its artwork, worked out off the main thread in one pass: the+// colour along the artwork's bottom edge, the field colour made from it, and the blurred bitmaps the+// field (SGRField.h) and the hero (SGRHero.h) draw instead of a live blur.+//+// The field colour is the edge colour with its saturation held to 0.55 and its relative luminance to+// 0.07 (0.04 with Increase Contrast). On anything that dark white text is past 8:1 and SGRSecondary+// (white 65%) past 4.5:1, WCAG AA, whatever the hue.+//+// Threading: +paletteForImage: may be called from the main thread only and calls back on it. The work+// runs on one serial background queue; UIImage and CoreImage are read there, UIKit views are not.+#import <UIKit/UIKit.h>++typedef struct {+ // The area a backdrop bitmap covers, in points; CGSizeZero when none is wanted. The bitmap is the+ // artwork filling that area, blurred, dimmed from 0.25 black at the top to 0.45 (0.55 with+ // AMOLED) at 55% of the height, and transparent from 55% down to the bottom, so the field colour+ // under it shows through with no edge.+ CGSize backdropSize;+ // A blurred copy at the artwork's own aspect, transparent down to 55% of its height and opaque+ // from 85%, to lay over the sharp picture with the same aspect fill.+ BOOL dissolve;+ BOOL amoled;+} SGRPaletteRequest;++@interface SGRPalette : NSObject+@property (nonatomic, readonly) UIColor *edgeColor;+@property (nonatomic, readonly) UIColor *fieldColor;+@property (nonatomic, readonly) UIImage *backdrop; // nil unless asked for, at most 160px wide+@property (nonatomic, readonly) UIImage *dissolve; // nil unless asked for, 96px wide+// nil to the completion when the image has no bitmap to read (a symbol, a CIImage).++ (void)paletteForImage:(UIImage *)image request:(SGRPaletteRequest)request completion:(void (^)(SGRPalette *palette))completion;+@end++// Any colour made fit to be a field, the same way the edge colour is: for a colour Spotify hands over+// before the artwork is read. Main thread.+UIColor *SGRFieldColorFor(UIColor *color);diff --git a/tweak/Sources/Redesign/Kit/SGRPalette.m b/tweak/Sources/Redesign/Kit/SGRPalette.mnew file mode 100644index 00000000..2b4ae45f--- /dev/null+++ b/tweak/Sources/Redesign/Kit/SGRPalette.m@@ -0,0 +1,194 @@+#import <CoreImage/CoreImage.h>+#import "Core/SGCore.h"+#import "SGRPalette.h"+#import "SGRTokens.h"++static const size_t kSample = 64; // the artwork shrunk to this square before its colours are read+static const size_t kEdgeRows = 10; // the bottom rows of it averaged into the edge colour+static const CGFloat kMaxSaturation = 0.55;+static const CGFloat kMaxLuminance = 0.07, kMaxLuminanceContrast = 0.04;+static const CGFloat kBackdropWidth = 160, kBackdropMaxHeight = 400, kBackdropSigma = 12;+static const CGFloat kDissolveWidth = 96, kDissolveSigma = 5;+static const CGFloat kFadeFrom = 0.55, kDissolveOpaque = 0.85;++@interface SGRPalette ()+@property (nonatomic, readwrite) UIColor *edgeColor;+@property (nonatomic, readwrite) UIColor *fieldColor;+@property (nonatomic, readwrite) UIImage *backdrop;+@property (nonatomic, readwrite) UIImage *dissolve;+@end++static dispatch_queue_t paletteQueue(void) {+ static dispatch_queue_t queue;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ queue = dispatch_queue_create("spotifyglass.redesign.palette", dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INITIATED, 0));+ });+ return queue;+}++static CGColorSpaceRef sRGB(void) {+ static CGColorSpaceRef space;+ static dispatch_once_t once;+ dispatch_once(&once, ^{ space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB); });+ return space;+}++// One context for the whole launch; CIContext is safe to share and costly to make.+static CIContext *blurContext(void) {+ static CIContext *context;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ context = [CIContext contextWithOptions:@{kCIContextCacheIntermediates: @NO, kCIContextWorkingColorSpace: (__bridge id)sRGB()}];+ });+ return context;+}++static CGContextRef newBitmap(size_t width, size_t height) {+ return CGBitmapContextCreate(NULL, width, height, 8, width * 4, sRGB(), (CGBitmapInfo)kCGImageAlphaPremultipliedLast);+}++static void drawFilling(CGContextRef context, CGImageRef image, size_t width, size_t height) {+ CGFloat iw = CGImageGetWidth(image), ih = CGImageGetHeight(image);+ CGFloat scale = MAX(width / iw, height / ih);+ CGContextSetInterpolationQuality(context, kCGInterpolationMedium);+ CGContextDrawImage(context, CGRectMake((width - iw * scale) / 2, (height - ih * scale) / 2, iw * scale, ih * scale), image);+}++#pragma mark - colour++static CGFloat toLinear(CGFloat c) {+ return c <= 0.04045 ? c / 12.92 : pow((c + 0.055) / 1.055, 2.4);+}++static CGFloat toEncoded(CGFloat c) {+ return c <= 0.0031308 ? c * 12.92 : 1.055 * pow(c, 1 / 2.4) - 0.055;+}++static UIColor *fieldColorFor(UIColor *color, CGFloat ceiling) {+ CGFloat r = 0, g = 0, b = 0, a = 1, h = 0, s = 0, v = 0;+ if (![color getRed:&r green:&g blue:&b alpha:&a]) {+ CGFloat white = 0;+ if (![color getWhite:&white alpha:&a]) return SGRNeutralField();+ r = g = b = white;+ }+ UIColor *clamped = [UIColor colorWithRed:MIN(1, MAX(0, r)) green:MIN(1, MAX(0, g)) blue:MIN(1, MAX(0, b)) alpha:1];+ [clamped getHue:&h saturation:&s brightness:&v alpha:&a];+ [[UIColor colorWithHue:h saturation:MIN(s, kMaxSaturation) brightness:v alpha:1] getRed:&r green:&g blue:&b alpha:&a];+ CGFloat lr = toLinear(r), lg = toLinear(g), lb = toLinear(b);+ CGFloat luminance = 0.2126 * lr + 0.7152 * lg + 0.0722 * lb;+ if (luminance > ceiling) {+ CGFloat k = ceiling / luminance;+ lr *= k, lg *= k, lb *= k;+ }+ return [UIColor colorWithRed:toEncoded(lr) green:toEncoded(lg) blue:toEncoded(lb) alpha:1];+}++UIColor *SGRFieldColorFor(UIColor *color) {+ return color ? fieldColorFor(color, SGRIncreaseContrast() ? kMaxLuminanceContrast : kMaxLuminance) : SGRNeutralField();+}++// The artwork squeezed into a small square, whatever its aspect, and the bottom rows of that averaged+// by coverage. A bitmap context keeps its rows top to bottom, so the last rows are the bottom edge.+static UIColor *edgeColorOf(CGImageRef image) {+ CGContextRef context = newBitmap(kSample, kSample);+ if (!context) return nil;+ CGContextSetInterpolationQuality(context, kCGInterpolationMedium);+ CGContextDrawImage(context, CGRectMake(0, 0, kSample, kSample), image);+ const uint8_t *px = CGBitmapContextGetData(context);+ double r = 0, g = 0, b = 0, coverage = 0;+ for (size_t y = kSample - kEdgeRows; px && y < kSample; y++) {+ for (size_t x = 0; x < kSample; x++) {+ const uint8_t *p = px + (y * kSample + x) * 4;+ r += p[0], g += p[1], b += p[2], coverage += p[3];+ }+ }+ CGContextRelease(context);+ // Premultiplied, so the sums over the summed alpha are the average of what is actually there.+ if (coverage < 1) return nil;+ return [UIColor colorWithRed:r / coverage green:g / coverage blue:b / coverage alpha:1];+}++#pragma mark - bitmaps++// The artwork drawn to fill the size, then blurred with its edges clamped so the border does not+// darken. Returned retained.+static CGImageRef newBlurred(CGImageRef image, size_t width, size_t height, CGFloat sigma) {+ CGContextRef context = newBitmap(width, height);+ if (!context) return NULL;+ drawFilling(context, image, width, height);+ CGImageRef small = CGBitmapContextCreateImage(context);+ CGContextRelease(context);+ if (!small) return NULL;+ CIImage *input = [CIImage imageWithCGImage:small];+ CGImageRelease(small);+ CIImage *output = [[input imageByClampingToExtent] imageByApplyingGaussianBlurWithSigma:sigma];+ return [blurContext() createCGImage:output fromRect:input.extent format:kCIFormatRGBA8 colorSpace:sRGB()];+}++// A black gradient from `a0` at `y0` to `a1` at `y1` (shares of the height, top down), extended+// past both ends; with kCGBlendModeDestinationIn it becomes an alpha ramp instead of a dim.+static void drawRamp(CGContextRef context, size_t height, CGFloat y0, CGFloat a0, CGFloat y1, CGFloat a1, CGBlendMode mode) {+ CGFloat components[] = {0, 0, 0, a0, 0, 0, 0, a1};+ CGFloat locations[] = {0, 1};+ CGGradientRef gradient = CGGradientCreateWithColorComponents(sRGB(), components, locations, 2);+ CGContextSetBlendMode(context, mode);+ CGContextDrawLinearGradient(context, gradient, CGPointMake(0, y0 * height), CGPointMake(0, y1 * height),+ kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);+ CGGradientRelease(gradient);+}++static UIImage *finished(CGImageRef blurred, BOOL dim, CGFloat dimBottom, CGFloat rampFrom, CGFloat alphaFrom, CGFloat rampTo, CGFloat alphaTo) {+ size_t width = CGImageGetWidth(blurred), height = CGImageGetHeight(blurred);+ CGContextRef context = newBitmap(width, height);+ if (!context) return nil;+ CGContextDrawImage(context, CGRectMake(0, 0, width, height), blurred);+ // Top down from here on.+ CGContextTranslateCTM(context, 0, height);+ CGContextScaleCTM(context, 1, -1);+ if (dim) drawRamp(context, height, 0, 0.25, kFadeFrom, dimBottom, kCGBlendModeNormal);+ drawRamp(context, height, rampFrom, alphaFrom, rampTo, alphaTo, kCGBlendModeDestinationIn);+ CGImageRef result = CGBitmapContextCreateImage(context);+ CGContextRelease(context);+ UIImage *image = result ? [UIImage imageWithCGImage:result scale:1 orientation:UIImageOrientationUp] : nil;+ CGImageRelease(result);+ return image;+}++@implementation SGRPalette+++ (void)paletteForImage:(UIImage *)image request:(SGRPaletteRequest)request completion:(void (^)(SGRPalette *palette))completion {+ if (!completion) return;+ CGFloat ceiling = SGRIncreaseContrast() ? kMaxLuminanceContrast : kMaxLuminance;+ dispatch_async(paletteQueue(), ^{+ SGRPalette *palette = nil;+ CGImageRef cg = image.CGImage;+ UIColor *edge = cg && CGImageGetWidth(cg) && CGImageGetHeight(cg) ? edgeColorOf(cg) : nil;+ if (edge) {+ CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();+ palette = [SGRPalette new];+ palette.edgeColor = edge;+ palette.fieldColor = fieldColorFor(edge, ceiling);+ CGSize area = request.backdropSize;+ if (area.width > 0 && area.height > 0) {+ size_t width = (size_t)kBackdropWidth, height = (size_t)MIN(kBackdropMaxHeight, round(kBackdropWidth * area.height / area.width));+ CGImageRef blurred = newBlurred(cg, width, MAX(height, 1), kBackdropSigma);+ if (blurred) palette.backdrop = finished(blurred, YES, request.amoled ? 0.55 : 0.45, kFadeFrom, 1, 1, 0);+ CGImageRelease(blurred);+ }+ if (request.dissolve) {+ CGFloat aspect = (CGFloat)CGImageGetHeight(cg) / CGImageGetWidth(cg);+ size_t height = (size_t)MIN(kDissolveWidth * 2, MAX(kDissolveWidth / 2, round(kDissolveWidth * aspect)));+ CGImageRef blurred = newBlurred(cg, (size_t)kDissolveWidth, height, kDissolveSigma);+ if (blurred) palette.dissolve = finished(blurred, NO, 0, kFadeFrom, 0, kDissolveOpaque, 1);+ CGImageRelease(blurred);+ }+ static dispatch_once_t once;+ double ms = (CFAbsoluteTimeGetCurrent() - start) * 1000;+ dispatch_once(&once, ^{ SGLog(@"redesign kit: first palette %@ from %zux%zu in %.1f ms", palette.fieldColor, CGImageGetWidth(cg), CGImageGetHeight(cg), ms); });+ }+ dispatch_async(dispatch_get_main_queue(), ^{ completion(palette); });+ });+}++@enddiff --git a/tweak/Sources/Redesign/Kit/SGRRestyle.h b/tweak/Sources/Redesign/Kit/SGRRestyle.hnew file mode 100644index 00000000..87780924--- /dev/null+++ b/tweak/Sources/Redesign/Kit/SGRRestyle.h@@ -0,0 +1,83 @@+// Keeping Spotify's views the way a redesigned screen set them: Spotify re-applies its own look on+// reuse, on state changes and on every layout pass, so each helper here either survives that or is+// cheap enough to run again on every pass. Nothing here uses `hidden` on a view Spotify arranges in a+// stack: OverflowStackView and some Encore stacks trap in updateConstraints when an arranged view+// hides, so a view goes away by alpha, touches and accessibility instead.+//+// Ownership: what a helper creates belongs to the view it was made for (associated objects), and a+// helper keeps only weak references to Spotify's views.+// Threading: main thread only, except SGRInsideClearRoot, which Appearance/Repaint.x calls from+// wherever a layer is painted.+#import <UIKit/UIKit.h>++#pragma mark - views++// Alpha 0, no touches, hidden from accessibility, and kept so: the instance becomes a runtime subclass+// of its own class (the way KVO does it, `class` still answers the original) whose setAlpha: and+// setUserInteractionEnabled: hold those values. For plain UIKit views (a UIImageView, a UILabel); a+// Swift class, or an instance already observed with KVO, gets the values once instead, re-applied on+// the next call, and a log line says so once.+void SGRSuppress(UIView *view);++// Digits of one width in the label, kept through Spotify's own setText:, setAttributedText: and+// setFont: by a runtime subclass of the instance, like SGRSuppress. Idempotent.+void SGRMonospacedDigits(UILabel *label);++// The first view under `root` (itself included) with the accessibility identifier, depth first. The+// answer is kept weakly on `root` under `cacheKey` and searched for again only when it is gone, has+// left `root` or changed its identifier. nil when there is none; a miss is not cached.+UIView *SGRFindByIdentifier(UIView *root, NSString *identifier, const void *cacheKey);++// A view that draws only a shadow, for a view whose own layer clips (rounded artwork): made once per+// host under `key`, inserted at the bottom of `host`. The caller gives it its frame and transform; its+// shadowPath follows its bounds and cornerRadius.+@interface SGRShadowPlate : UIView+@property (nonatomic) CGFloat cornerRadius; // SGRRadiusArtwork unless set+@end+SGRShadowPlate *SGRShadowPlateIn(UIView *host, const void *key);++// A Spotify list cell's content restyled for the field: base backgrounds (#121212, or the black AMOLED+// makes of it) cleared, white text to SGRPrimary and #B3B3B3 text to SGRSecondary (the now playing+// tint and other colours are left), Encore list row dividers at alpha 0, and image views of 40pt and+// more rounded (SGRRadiusThumb up to 64pt, SGRRadiusCover above). Idempotent; one walk of the subtree.+void SGRStyleSpotifyCell(UIView *content);++// A section header of the redesign's own over a Spotify heading cell: the title in title 2 bold, 24pt+// from the top and SGRSideMargin from the sides, and a chevron when there is somewhere to go, which+// fires `target` (Spotify's own "show all") with SGRFire. One per cell, updated on every call; the+// caller makes Spotify's heading invisible under it.+@interface SGRSectionHeader : UIView++ (instancetype)headerInCell:(UICollectionViewCell *)cell title:(NSString *)title target:(UIControl *)target;+@end++#pragma mark - Spotify's controls and pages++// Fires a control's action the way a tap would: the actions registered for primary action triggered,+// else those for touch up inside. NO when the control has neither (an Encore control that reads its+// touches through a gesture recognizer); what was found is logged once per class.+BOOL SGRFire(UIControl *control);++// The scroll view's contentOffset through KVO, on the main thread, until `owner` or the scroll view goes+// away or the observation is invalidated. The block is handed the owner so it need not capture it+// (the owner keeps the observation, so a captured owner would never be freed).+@interface SGROffsetObservation : NSObject+- (void)invalidate;+@end+SGROffsetObservation *SGRObserveOffset(UIScrollView *scrollView, id owner, void (^changed)(id owner, CGPoint offset));++// The URI of the page `view` is in (spotify:artist:…), from the first controller up its responder+// chain that answers spt_pageURI (IdentifiedPageHostingViewController and the other page wrappers);+// kept on the view once found.+NSURL *SGRPageURI(UIView *view);++#pragma mark - repaint++// A redesigned page that paints its own field registers the view that holds Spotify's surfaces:+// Appearance/Repaint.x then clears every base surface colour (SGIsBaseSurface) set on a view inside it,+// now and whenever Spotify repaints. Registering sweeps what is already painted once. The mark lives+// on the view, so it goes with it.+void SGRRegisterClearRoot(UIView *root);+// For Repaint.x: whether any root has been registered this launch, and whether `view` is inside one+// (stopping at a visual effect view, as SGIsInside does).+BOOL SGRHasClearRoots(void);+BOOL SGRInsideClearRoot(UIView *view);diff --git a/tweak/Sources/Redesign/Kit/SGRRestyle.m b/tweak/Sources/Redesign/Kit/SGRRestyle.mnew file mode 100644index 00000000..b2e3fd6c--- /dev/null+++ b/tweak/Sources/Redesign/Kit/SGRRestyle.m@@ -0,0 +1,455 @@+#import <objc/message.h>+#import <CoreText/SFNTLayoutTypes.h>+#import "Core/SGCore.h"+#import "SGRRestyle.h"+#import "SGRTokens.h"++static char kPlateKey, kHeaderKey, kObservationsKey, kPageURIKey, kClearRootKey;++@interface SGRWeakBox : NSObject+@property (nonatomic, weak) id value;+@end++@implementation SGRWeakBox+@end++#pragma mark - instance subclasses++// A Swift class can lose its metadata when the runtime makes a subclass of it, and an instance KVO+// already swapped the class of would be swapped back when its last observer goes; neither is subclassed.+static BOOL subclassable(Class cls) {+ const char *name = class_getName(cls);+ return strncmp(name, "_Tt", 3) != 0 && !strchr(name, '.') && strncmp(name, "NSKVONotifying_", 15) != 0;+}++// The class `prefix` + the instance's class, made once, answering `class` with the original so+// isKindOfClass:, NSStringFromClass and the tree dumps see what Spotify made.+static Class instanceSubclass(Class original, const char *prefix, void (^install)(Class subclass, Class original)) {+ NSString *name = [NSString stringWithFormat:@"%s%s", prefix, class_getName(original)];+ Class subclass = objc_getClass(name.UTF8String);+ if (subclass) return subclass;+ subclass = objc_allocateClassPair(original, name.UTF8String, 0);+ if (!subclass) return Nil;+ install(subclass, original);+ class_addMethod(subclass, @selector(class), imp_implementationWithBlock(^Class(id self) { return original; }), "#@:");+ objc_registerClassPair(subclass);+ return subclass;+}++// Moves the view into the subclass unless it is already in it; NO when the view cannot be subclassed.+static BOOL adopt(UIView *view, const char *prefix, void (^install)(Class subclass, Class original)) {+ Class current = object_getClass(view);+ if (strncmp(class_getName(current), prefix, strlen(prefix)) == 0) return YES;+ if (!subclassable(current)) return NO;+ Class subclass = instanceSubclass(current, prefix, install);+ if (!subclass) return NO;+ object_setClass(view, subclass);+ return YES;+}++static void addOverride(Class subclass, Class original, SEL selector, id block) {+ Method method = class_getInstanceMethod(original, selector);+ if (method) class_addMethod(subclass, selector, imp_implementationWithBlock(block), method_getTypeEncoding(method));+}++#pragma mark - views++void SGRSuppress(UIView *view) {+ if (!view) return;+ BOOL kept = adopt(view, "SGRSuppressed_", ^(Class subclass, Class original) {+ addOverride(subclass, original, @selector(setAlpha:), ^(UIView *self, CGFloat alpha) {+ struct objc_super parent = {self, original};+ ((void (*)(struct objc_super *, SEL, CGFloat))objc_msgSendSuper)(&parent, @selector(setAlpha:), 0);+ });+ addOverride(subclass, original, @selector(setUserInteractionEnabled:), ^(UIView *self, BOOL enabled) {+ struct objc_super parent = {self, original};+ ((void (*)(struct objc_super *, SEL, BOOL))objc_msgSendSuper)(&parent, @selector(setUserInteractionEnabled:), NO);+ });+ });+ if (!kept) {+ static NSMutableSet<NSString *> *logged;+ if (!logged) logged = [NSMutableSet set];+ NSString *name = NSStringFromClass(object_getClass(view));+ if (![logged containsObject:name]) {+ [logged addObject:name];+ SGLog(@"redesign kit: %@ cannot keep being suppressed, set once per call", name);+ }+ }+ view.alpha = 0;+ view.userInteractionEnabled = NO;+ view.accessibilityElementsHidden = YES;+}++static BOOL hasMonospacedDigits(UIFont *font) {+ for (NSDictionary *setting in font.fontDescriptor.fontAttributes[UIFontDescriptorFeatureSettingsAttribute]) {+ if ([setting[UIFontFeatureTypeIdentifierKey] integerValue] == kNumberSpacingType+ && [setting[UIFontFeatureSelectorIdentifierKey] integerValue] == kMonospacedNumbersSelector) return YES;+ }+ return NO;+}++static void applyMonospaced(UILabel *label, Class original) {+ NSAttributedString *text = label.attributedText;+ struct objc_super parent = {label, original};+ if (!text.length) {+ UIFont *font = label.font;+ if (font && !hasMonospacedDigits(font)) {+ ((void (*)(struct objc_super *, SEL, id))objc_msgSendSuper)(&parent, @selector(setFont:), SGRMonospacedDigitsFont(font));+ }+ return;+ }+ __block NSMutableAttributedString *mapped = nil;+ [text enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, text.length) options:0 usingBlock:^(UIFont *font, NSRange range, BOOL *stop) {+ if (!font || hasMonospacedDigits(font)) return;+ if (!mapped) mapped = [text mutableCopy];+ [mapped addAttribute:NSFontAttributeName value:SGRMonospacedDigitsFont(font) range:range];+ }];+ if (mapped) ((void (*)(struct objc_super *, SEL, id))objc_msgSendSuper)(&parent, @selector(setAttributedText:), mapped);+}++// Spotify's setters run first; what they left is then given the feature through the original class's+// own setters. UILabel may set one property through another, so a pass started inside a pass is+// skipped rather than trusted to settle.+static BOOL sg_keepingMonospaced = NO;++static void keepMonospaced(UILabel *label, Class original) {+ if (sg_keepingMonospaced) return;+ sg_keepingMonospaced = YES;+ applyMonospaced(label, original);+ sg_keepingMonospaced = NO;+}++void SGRMonospacedDigits(UILabel *label) {+ if (![label isKindOfClass:UILabel.class]) return;+ BOOL kept = adopt(label, "SGRMonospaced_", ^(Class subclass, Class original) {+ for (NSString *name in @[@"setText:", @"setAttributedText:", @"setFont:"]) {+ SEL selector = NSSelectorFromString(name);+ addOverride(subclass, original, selector, ^(UILabel *self, id value) {+ struct objc_super parent = {self, original};+ ((void (*)(struct objc_super *, SEL, id))objc_msgSendSuper)(&parent, selector, value);+ keepMonospaced(self, original);+ });+ }+ });+ Class original = kept ? class_getSuperclass(object_getClass(label)) : object_getClass(label);+ keepMonospaced(label, original);+}++// An identifier ending in * matches by prefix, for Spotify's ids that carry an entity after a dash.+static BOOL identifierMatches(NSString *identifier, NSString *wanted) {+ if (!identifier) return NO;+ if ([wanted hasSuffix:@"*"]) return [identifier hasPrefix:[wanted substringToIndex:wanted.length - 1]];+ return [identifier isEqualToString:wanted];+}++static UIView *findIdentifier(UIView *view, NSString *identifier) {+ if (identifierMatches(view.accessibilityIdentifier, identifier)) return view;+ for (UIView *sub in view.subviews) {+ UIView *found = findIdentifier(sub, identifier);+ if (found) return found;+ }+ return nil;+}++UIView *SGRFindByIdentifier(UIView *root, NSString *identifier, const void *cacheKey) {+ if (!root || !identifier.length) return nil;+ SGRWeakBox *box = cacheKey ? objc_getAssociatedObject(root, cacheKey) : nil;+ UIView *cached = box.value;+ if (cached && identifierMatches(cached.accessibilityIdentifier, identifier) && [cached isDescendantOfView:root]) return cached;+ UIView *found = findIdentifier(root, identifier);+ if (found && cacheKey) {+ if (!box) {+ box = [SGRWeakBox new];+ objc_setAssociatedObject(root, cacheKey, box, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ }+ box.value = found;+ }+ return found;+}++@implementation SGRShadowPlate {+ CGRect _pathBounds;+}++- (instancetype)initWithFrame:(CGRect)frame {+ if (!(self = [super initWithFrame:frame])) return nil;+ self.userInteractionEnabled = NO;+ self.accessibilityElementsHidden = YES;+ _cornerRadius = SGRRadiusArtwork;+ _pathBounds = CGRectNull;+ CALayer *layer = self.layer;+ layer.shadowColor = UIColor.blackColor.CGColor;+ layer.shadowOpacity = 0.45;+ layer.shadowRadius = 32;+ layer.shadowOffset = CGSizeMake(0, 12);+ return self;+}++- (void)setCornerRadius:(CGFloat)radius {+ _cornerRadius = radius;+ _pathBounds = CGRectNull;+ [self setNeedsLayout];+}++- (void)layoutSubviews {+ [super layoutSubviews];+ CGRect bounds = self.bounds;+ if (CGRectEqualToRect(bounds, _pathBounds)) return;+ _pathBounds = bounds;+ [CATransaction begin];+ [CATransaction setDisableActions:YES];+ self.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:bounds cornerRadius:_cornerRadius].CGPath;+ [CATransaction commit];+}++@end++SGRShadowPlate *SGRShadowPlateIn(UIView *host, const void *key) {+ if (!host) return nil;+ const void *slot = key ?: &kPlateKey;+ SGRShadowPlate *plate = objc_getAssociatedObject(host, slot);+ if (!plate) {+ plate = [[SGRShadowPlate alloc] initWithFrame:host.bounds];+ objc_setAssociatedObject(host, slot, plate, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ }+ if (plate.superview != host) [host insertSubview:plate atIndex:0];+ return plate;+}++static BOOL isOpaqueRGB(UIColor *color, CGFloat red, CGFloat green, CGFloat blue) {+ CGFloat r = 0, g = 0, b = 0, a = 0;+ if (![color getRed:&r green:&g blue:&b alpha:&a]) return NO;+ return a > 0.99 && fabs(r - red) < 0.01 && fabs(g - green) < 0.01 && fabs(b - blue) < 0.01;+}++void SGRStyleSpotifyCell(UIView *content) {+ if (!content) return;+ static Class divider;+ static dispatch_once_t once;+ dispatch_once(&once, ^{ divider = NSClassFromString(@"_TtCCE16Encore_LayoutKitO16EncoreFoundation6Encore7ListRow7Divider"); });+ UIColor *secondary = SGRSecondary();+ const CGFloat grey = 0xB3 / 255.0;+ SGForEachView(content, ^(UIView *view) {+ if (SGIsBaseSurface(view.layer.backgroundColor)) view.layer.backgroundColor = NULL;+ if ([view isKindOfClass:UILabel.class]) {+ UILabel *label = (UILabel *)view;+ if (isOpaqueRGB(label.textColor, grey, grey, grey)) label.textColor = secondary;+ } else if (divider && [view isKindOfClass:divider]) {+ if (view.alpha != 0) view.alpha = 0;+ } else if ([view isKindOfClass:UIImageView.class]) {+ CGSize size = view.bounds.size;+ if (size.width < 40 || fabs(size.width - size.height) > 1) return;+ CGFloat radius = size.width <= 64 ? SGRRadiusThumb : SGRRadiusCover;+ if (view.layer.cornerRadius == radius) return;+ view.layer.cornerRadius = radius;+ view.layer.cornerCurve = kCACornerCurveContinuous;+ view.clipsToBounds = YES;+ }+ });+}++@implementation SGRSectionHeader {+ UILabel *_label;+ UIImageView *_chevron;+ __weak UIControl *_target;+}+++ (instancetype)headerInCell:(UICollectionViewCell *)cell title:(NSString *)title target:(UIControl *)target {+ UIView *content = cell.contentView;+ if (!content) return nil;+ SGRSectionHeader *header = objc_getAssociatedObject(cell, &kHeaderKey);+ if (!header) {+ header = [[SGRSectionHeader alloc] initWithFrame:content.bounds];+ objc_setAssociatedObject(cell, &kHeaderKey, header, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ }+ if (content.subviews.lastObject != header) [content addSubview:header];+ header.frame = content.bounds;+ [header setTitle:title target:target];+ return header;+}++- (instancetype)initWithFrame:(CGRect)frame {+ if (!(self = [super initWithFrame:frame])) return nil;+ self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;+ _label = [UILabel new];+ _label.textColor = SGRPrimary();+ [self addSubview:_label];+ _chevron = [[UIImageView alloc] initWithImage:[UIImage systemImageNamed:@"chevron.right"]];+ _chevron.preferredSymbolConfiguration = [UIImageSymbolConfiguration configurationWithPointSize:15 weight:UIImageSymbolWeightSemibold];+ _chevron.tintColor = SGRSecondary();+ [_chevron sizeToFit];+ [self addSubview:_chevron];+ self.isAccessibilityElement = YES;+ [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped)]];+ [self applyFont];+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(contentSizeChanged:) name:UIContentSizeCategoryDidChangeNotification object:nil];+ return self;+}++- (void)dealloc {+ [NSNotificationCenter.defaultCenter removeObserver:self];+}++- (void)applyFont {+ _label.font = SGRFont(UIFontTextStyleTitle2, UIFontWeightBold, UIContentSizeCategoryExtraExtraExtraLarge);+}++- (void)contentSizeChanged:(NSNotification *)note {+ [self applyFont];+ [self setNeedsLayout];+}++- (void)setTitle:(NSString *)title target:(UIControl *)target {+ _target = target;+ // Without a target the touches go to Spotify's cell as they would without the header.+ self.userInteractionEnabled = target != nil;+ _chevron.hidden = target == nil;+ self.accessibilityLabel = title;+ self.accessibilityTraits = target ? UIAccessibilityTraitHeader | UIAccessibilityTraitButton : UIAccessibilityTraitHeader;+ if (![title isEqualToString:_label.text]) {+ _label.text = title;+ [self setNeedsLayout];+ }+}++- (void)layoutSubviews {+ [super layoutSubviews];+ CGFloat width = self.bounds.size.width, lineHeight = ceil(_label.font.lineHeight);+ CGFloat room = MAX(0, width - 2 * SGRSideMargin - (_chevron.hidden ? 0 : _chevron.bounds.size.width + 6));+ CGFloat textWidth = MIN(room, ceil([_label sizeThatFits:CGSizeMake(CGFLOAT_MAX, lineHeight)].width));+ _label.frame = CGRectMake(SGRSideMargin, 24, textWidth, lineHeight);+ _chevron.center = CGPointMake(SGRSideMargin + textWidth + 6 + _chevron.bounds.size.width / 2, CGRectGetMidY(_label.frame));+}++- (void)tapped {+ UIControl *target = _target;+ if (target) SGRFire(target);+}++- (BOOL)accessibilityActivate {+ UIControl *target = _target;+ return target && SGRFire(target);+}++@end++#pragma mark - Spotify's controls and pages++BOOL SGRFire(UIControl *control) {+ if (![control isKindOfClass:UIControl.class]) return NO;+ __block UIControlEvents registered = control.allControlEvents;+ [control enumerateEventHandlers:^(UIAction *action, id target, SEL selector, UIControlEvents events, BOOL *stop) {+ registered |= events;+ }];+ UIControlEvents fire = (registered & UIControlEventPrimaryActionTriggered) ? UIControlEventPrimaryActionTriggered+ : (registered & UIControlEventTouchUpInside) ? UIControlEventTouchUpInside : 0;+ static NSMutableSet<NSString *> *logged;+ if (!logged) logged = [NSMutableSet set];+ NSString *name = NSStringFromClass(control.class);+ if (![logged containsObject:name]) {+ [logged addObject:name];+ SGLog(@"redesign kit: %@ fires %@ (events 0x%lx)", name, fire == UIControlEventPrimaryActionTriggered ? @"its primary action" : fire ? @"touch up inside" : @"nothing", (unsigned long)registered);+ }+ if (!fire) return NO;+ [control sendActionsForControlEvents:fire];+ return YES;+}++@interface SGROffsetObservation ()+@property (nonatomic, weak) UIScrollView *scrollView;+@property (nonatomic, weak) id owner;+@property (nonatomic, copy) void (^changed)(id owner, CGPoint offset);+@end++@implementation SGROffsetObservation++- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {+ id owner = self.owner;+ UIScrollView *scrollView = self.scrollView;+ if (!owner || !scrollView) {+ [self invalidate];+ return;+ }+ if (self.changed) self.changed(owner, scrollView.contentOffset);+}++// A scroll view that went first took its observers with it (KVO lets go at the end of dealloc for a+// property it notifies about itself, iOS 11 on), so only a live one is asked to remove this.+- (void)invalidate {+ UIScrollView *scrollView = self.scrollView;+ self.scrollView = nil;+ self.changed = nil;+ if (!scrollView) return;+ @try {+ [scrollView removeObserver:self forKeyPath:@"contentOffset" context:&kObservationsKey];+ } @catch (NSException *exception) {+ SGLog(@"redesign kit: offset observation was already gone (%@)", exception.reason);+ }+}++- (void)dealloc {+ [self invalidate];+}++@end++SGROffsetObservation *SGRObserveOffset(UIScrollView *scrollView, id owner, void (^changed)(id owner, CGPoint offset)) {+ if (!scrollView || !owner || !changed) return nil;+ SGROffsetObservation *observation = [SGROffsetObservation new];+ observation.scrollView = scrollView;+ observation.owner = owner;+ observation.changed = changed;+ NSMutableArray *kept = objc_getAssociatedObject(owner, &kObservationsKey);+ if (!kept) {+ kept = [NSMutableArray array];+ objc_setAssociatedObject(owner, &kObservationsKey, kept, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ }+ [kept addObject:observation];+ [scrollView addObserver:observation forKeyPath:@"contentOffset" options:0 context:&kObservationsKey];+ return observation;+}++@protocol SGRPageController+- (id)spt_pageURI;+@end++NSURL *SGRPageURI(UIView *view) {+ if (!view) return nil;+ NSURL *cached = objc_getAssociatedObject(view, &kPageURIKey);+ if (cached) return cached;+ for (UIResponder *responder = view; responder; responder = responder.nextResponder) {+ if (![responder isKindOfClass:UIViewController.class] || ![responder respondsToSelector:@selector(spt_pageURI)]) continue;+ id uri = [(id<SGRPageController>)responder spt_pageURI];+ NSURL *url = [uri isKindOfClass:NSURL.class] ? uri : [uri isKindOfClass:NSString.class] ? [NSURL URLWithString:uri] : nil;+ if (!url) continue;+ objc_setAssociatedObject(view, &kPageURIKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ return url;+ }+ return nil;+}++#pragma mark - repaint++static BOOL sg_clearRoots = NO;++void SGRRegisterClearRoot(UIView *root) {+ if (!root || objc_getAssociatedObject(root, &kClearRootKey)) return;+ objc_setAssociatedObject(root, &kClearRootKey, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ sg_clearRoots = YES;+ SGForEachView(root, ^(UIView *view) {+ if (!SGKeepsColor(view) && SGIsBaseSurface(view.layer.backgroundColor) && SGRInsideClearRoot(view)) view.layer.backgroundColor = NULL;+ });+}++BOOL SGRHasClearRoots(void) {+ return sg_clearRoots;+}++BOOL SGRInsideClearRoot(UIView *view) {+ if (!sg_clearRoots) return NO;+ for (UIView *v = view; v; v = v.superview) {+ if ([v isKindOfClass:UIVisualEffectView.class]) return NO;+ if (objc_getAssociatedObject(v, &kClearRootKey)) return YES;+ }+ return NO;+}diff --git a/tweak/Sources/Redesign/Kit/SGRTokens.h b/tweak/Sources/Redesign/Kit/SGRTokens.hnew file mode 100644index 00000000..abf3c4a8--- /dev/null+++ b/tweak/Sources/Redesign/Kit/SGRTokens.h@@ -0,0 +1,53 @@+// The redesign's design tokens: every redesigned screen takes its colours, type, spacing, radii and+// motion from here, so the screens read as one app and nothing is tuned per screen by hand.+//+// Colours are white over the artwork field (SGRField.h), whose colour is kept dark enough that+// SGRPrimary and SGRSecondary both pass WCAG AA on it. Type is the system font (SF Pro) sized by the+// text style and capped, since Spotify's pages lay out for a fixed header height. Motion is springs,+// critically damped for layout and a little bounce for press feedback; under Reduce Motion both+// become instant, while crossfades stay, a fade not being motion.+//+// Threading: the constants and the colours are safe anywhere; fonts, SGRAnimate and the+// accessibility reads are main thread only.+#import <UIKit/UIKit.h>++extern const CGFloat SGRSideMargin; // 16, the page's side margin+extern const CGFloat SGRGrid; // 8, every gap is a multiple of it+extern const CGFloat SGRRadiusArtwork; // 12, the player's cover+extern const CGFloat SGRRadiusCard; // 16, a content card (the lyrics card under the player)+extern const CGFloat SGRRadiusCover; // 8, a release cover in a list+extern const CGFloat SGRRadiusThumb; // 6, a row's thumbnail up to 64pt+extern const CGFloat SGRGlassCircleSize; // 44, a round glass behind a top bar button+extern const CGFloat SGRActionHeight; // 48, a button of the action row under a hero+extern const CGFloat SGRActionSpacing; // 12, between the buttons of an action row+extern const CGFloat SGRGlassSpacing; // 16, how near two glass shapes merge in one container+extern const NSTimeInterval SGRCrossfade; // 0.35, a new image or field colour fading in++UIColor *SGRPrimary(void); // white+UIColor *SGRSecondary(void); // white 65%, 80% with Increase Contrast+UIColor *SGRTertiary(void); // white 40%, 60% with Increase Contrast+UIColor *SGRAccent(void); // the accent colour of Appearance, else Spotify's green+UIColor *SGRNeutralField(void); // #121212, the field before a colour arrives; AMOLED turns it black+// Where glass cannot be (Reduce Transparency), the shape it would have had: white 16% over the field.+UIColor *SGRSolidGlassFill(void);+// A content surface on the field (a card), a step lighter than the field it sits on.+UIColor *SGRElevated(UIColor *field);++// The system font at the size `style` has for the current content size category, but never larger+// than it has at `largest`, in `weight`. Callers re-ask on traitCollectionDidChange:.+UIFont *SGRFont(UIFontTextStyle style, UIFontWeight weight, UIContentSizeCategory largest);+// The same font with digits of one width, so a time or a count does not twitch as it changes.+UIFont *SGRMonospacedDigitsFont(UIFont *font);++BOOL SGRReduceMotion(void);+BOOL SGRReduceTransparency(void);+BOOL SGRIncreaseContrast(void);++typedef NS_ENUM(NSInteger, SGRMotion) {+ SGRMotionLayout, // a spring with no overshoot, for anything moving or resizing+ SGRMotionPress, // a spring with a little bounce, for press feedback+ SGRMotionFade, // an ease in and out over SGRCrossfade, kept under Reduce Motion+};+// Runs `animations` with the motion's timing, or at once under Reduce Motion (except a fade), and+// always calls `completion`. Only transform, alpha and colour belong in it while a page scrolls.+void SGRAnimate(SGRMotion motion, void (^animations)(void), void (^completion)(BOOL finished));diff --git a/tweak/Sources/Redesign/Kit/SGRTokens.m b/tweak/Sources/Redesign/Kit/SGRTokens.mnew file mode 100644index 00000000..26436937--- /dev/null+++ b/tweak/Sources/Redesign/Kit/SGRTokens.m@@ -0,0 +1,101 @@+#import <CoreText/SFNTLayoutTypes.h>+#import "Core/SGCore.h"+#import "Features/Appearance/Appearance.h"+#import "SGRTokens.h"++const CGFloat SGRSideMargin = 16;+const CGFloat SGRGrid = 8;+const CGFloat SGRRadiusArtwork = 12;+const CGFloat SGRRadiusCard = 16;+const CGFloat SGRRadiusCover = 8;+const CGFloat SGRRadiusThumb = 6;+const CGFloat SGRGlassCircleSize = 44;+const CGFloat SGRActionHeight = 48;+const CGFloat SGRActionSpacing = 12;+const CGFloat SGRGlassSpacing = 16;+const NSTimeInterval SGRCrossfade = 0.35;++// A layout spring settles in about this long without overshooting; a press gives a little back.+static const NSTimeInterval kLayoutDuration = 0.45, kPressDuration = 0.32;+static const CGFloat kPressDamping = 0.62;++UIColor *SGRPrimary(void) {+ return UIColor.whiteColor;+}++UIColor *SGRSecondary(void) {+ return [UIColor colorWithWhite:1 alpha:SGRIncreaseContrast() ? 0.80 : 0.65];+}++UIColor *SGRTertiary(void) {+ return [UIColor colorWithWhite:1 alpha:SGRIncreaseContrast() ? 0.60 : 0.40];+}++// Read per call: the accent is stored as it is picked, and the colour row reads it the same way.+UIColor *SGRAccent(void) {+ return SGAccentColor() ?: [UIColor colorWithRed:0x1E / 255.0 green:0xD7 / 255.0 blue:0x60 / 255.0 alpha:1];+}++UIColor *SGRNeutralField(void) {+ return [UIColor colorWithRed:0x12 / 255.0 green:0x12 / 255.0 blue:0x12 / 255.0 alpha:1];+}++UIColor *SGRSolidGlassFill(void) {+ return [UIColor colorWithWhite:1 alpha:0.16];+}++UIColor *SGRElevated(UIColor *field) {+ CGFloat r = 0, g = 0, b = 0, a = 1;+ if (![field getRed:&r green:&g blue:&b alpha:&a]) return [UIColor colorWithWhite:1 alpha:0.08];+ // 12% towards white keeps a card on a black AMOLED field clear of the greys Amoled.x turns black.+ CGFloat lift = 0.12;+ return [UIColor colorWithRed:r + (1 - r) * lift green:g + (1 - g) * lift blue:b + (1 - b) * lift alpha:1];+}++UIFont *SGRFont(UIFontTextStyle style, UIFontWeight weight, UIContentSizeCategory largest) {+ UIContentSizeCategory current = UIApplication.sharedApplication.preferredContentSizeCategory;+ if (largest && UIContentSizeCategoryCompareToCategory(current, largest) == NSOrderedDescending) current = largest;+ UITraitCollection *traits = [UITraitCollection traitCollectionWithPreferredContentSizeCategory:current];+ CGFloat size = [UIFont preferredFontForTextStyle:style compatibleWithTraitCollection:traits].pointSize;+ return [UIFont systemFontOfSize:size weight:weight];+}++UIFont *SGRMonospacedDigitsFont(UIFont *font) {+ if (!font) return nil;+ NSArray *features = @[@{UIFontFeatureTypeIdentifierKey: @(kNumberSpacingType), UIFontFeatureSelectorIdentifierKey: @(kMonospacedNumbersSelector)}];+ UIFontDescriptor *descriptor = [font.fontDescriptor fontDescriptorByAddingAttributes:@{UIFontDescriptorFeatureSettingsAttribute: features}];+ return [UIFont fontWithDescriptor:descriptor size:font.pointSize];+}++BOOL SGRReduceMotion(void) {+ return UIAccessibilityIsReduceMotionEnabled();+}++BOOL SGRReduceTransparency(void) {+ return UIAccessibilityIsReduceTransparencyEnabled();+}++BOOL SGRIncreaseContrast(void) {+ return UIAccessibilityDarkerSystemColorsEnabled();+}++void SGRAnimate(SGRMotion motion, void (^animations)(void), void (^completion)(BOOL finished)) {+ if (!animations) return;+ if (motion != SGRMotionFade && SGRReduceMotion()) {+ [UIView performWithoutAnimation:animations];+ if (completion) completion(YES);+ return;+ }+ UIViewAnimationOptions options = UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionBeginFromCurrentState;+ switch (motion) {+ case SGRMotionLayout:+ [UIView animateWithDuration:kLayoutDuration delay:0 usingSpringWithDamping:1 initialSpringVelocity:0 options:options animations:animations completion:completion];+ break;+ case SGRMotionPress:+ [UIView animateWithDuration:kPressDuration delay:0 usingSpringWithDamping:kPressDamping initialSpringVelocity:0 options:options animations:animations completion:completion];+ break;+ case SGRMotionFade:+ [UIView animateWithDuration:SGRCrossfade delay:0 options:options | UIViewAnimationOptionCurveEaseInOut animations:animations completion:completion];+ break;+ }+}diff --git a/tweak/Sources/Redesign/Kit/SGRedesign.h b/tweak/Sources/Redesign/Kit/SGRedesign.hnew file mode 100644index 00000000..48b977b5--- /dev/null+++ b/tweak/Sources/Redesign/Kit/SGRedesign.h@@ -0,0 +1,49 @@+// Redesign: per screen, either Spotify's own layout with the legacy tweaks on it, or the screen+// redesigned from the Kit (Redesign/<Screen>/). One switch per screen, off until asked for and read+// once per launch like every other switch, so a screen never changes hands while it is on screen.+// While a screen's switch is on, the legacy hooks of that screen stand aside (each gates itself with+// SGRedesignOn) and the redesign may force some of Spotify's remote-config flags, which the flag+// rows elsewhere then show locked, the way Liquid Glass UI locks the flags it owns.+//+// Threading: SGRedesignOn, SGRedesignAnyOn and SGRedesignForcedFlag are safe from any thread (the+// configuration provider asks from several). Registration happens in a %ctor, before Spotify reads a+// flag. Everything that builds settings rows is main thread only.+#import <UIKit/UIKit.h>++// spotifyglass.redesign.<screen>; the screens with a redesign are listed in SGRedesign.m.+#define SGKeyRedesignPrefix @"spotifyglass.redesign."+#define SGKeyRedesignPlayer @"spotifyglass.redesign.player"+#define SGKeyRedesignArtist @"spotifyglass.redesign.artist"++// Whether the screen ("player", "artist") was redesigned when Spotify started. A screen without a+// redesign yet reads off whatever is stored for it.+BOOL SGRedesignOn(NSString *screen);+BOOL SGRedesignAnyOn(void);+// The screens with a redesign, in the order the Redesign page lists them.+NSArray<NSString *> *SGRedesignScreens(void);++// The flags a screen's redesign forces, flag key to @YES/@NO/number/string, registered from the+// screen's %ctor whether or not the screen is on: the settings rows need the list to lock theirs.+// Only the screens on at launch force anything; an override from the All flags page still wins.+void SGRedesignForceFlags(NSString *screen, NSDictionary<NSString *, id> *flags);+// For Features/Flags/Flags.x, right after SGFlagOverride: the value a screen on at launch forces, or nil.+id SGRedesignForcedFlag(NSString *key);+// For the flag rows of Settings/SGModPage.m: the value a screen whose switch is on now forces, or+// nil. It follows the stored switch rather than the launch, as the Liquid Glass UI lock does.+id SGRedesignOwnedFlag(NSString *key);++@class SGModRow, SGModSection;+// Extra rows a screen shows under its switch on the Redesign page, asked for each time the page+// opens. Register from the screen's %ctor whether or not the screen is on.+void SGRedesignRegisterRows(NSString *screen, NSArray<SGModRow *> *(^rows)(void));++// The card under Appearance on the root page of Mod Settings: one row opening the Redesign page,+// reading out how many screens are redesigned ("1 of 2").+SGModSection *SGRedesignSection(void);+UIViewController *SGRedesignSettingsPage(void);+// The first section of a legacy page (Player, Artist) while that screen's switch is on: it says the+// switches of that page for the screen don't apply and opens the Redesign page. nil while the switch+// is off, so a page adds it only when there is one:+// SGModSection *note = SGRedesignNoteSection(@"artist");+// if (note) sections = [@[note] arrayByAddingObjectsFromArray:sections];+SGModSection *SGRedesignNoteSection(NSString *screen);diff --git a/tweak/Sources/Redesign/Kit/SGRedesign.m b/tweak/Sources/Redesign/Kit/SGRedesign.mnew file mode 100644index 00000000..9214bb5a--- /dev/null+++ b/tweak/Sources/Redesign/Kit/SGRedesign.m@@ -0,0 +1,89 @@+// The switches of the redesigned screens and the flags they force. The rows of the Redesign page are+// in SGRedesignSettings.m.+#import <os/lock.h>+#import "Core/SGCore.h"+#import "SGRedesign.h"++// A screen added later needs its name here and its title in SGRedesignSettings.m.+NSArray<NSString *> *SGRedesignScreens(void) {+ return @[@"player", @"artist"];+}++static NSString *keyFor(NSString *screen) {+ return [SGKeyRedesignPrefix stringByAppendingString:screen];+}++#pragma mark - switches++// Read once, the first time anything asks, so a switch flipped in Mod Settings waits for the restart+// like every other; the hooks, the flags and the pages all see the same answer for the whole launch.+static NSSet<NSString *> *onAtLaunch(void) {+ static NSSet<NSString *> *on;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ NSMutableSet *found = [NSMutableSet set];+ for (NSString *screen in SGRedesignScreens()) {+ if (SGFlag(keyFor(screen), NO)) [found addObject:screen];+ }+ on = [found copy];+ if (on.count) SGLog(@"redesign: on for %@", [on.allObjects componentsJoinedByString:@", "]);+ });+ return on;+}++BOOL SGRedesignOn(NSString *screen) {+ return screen && [onAtLaunch() containsObject:screen];+}++BOOL SGRedesignAnyOn(void) {+ return onAtLaunch().count > 0;+}++#pragma mark - forced flags++// Written from the screens' constructors, read by the configuration provider on whatever thread it+// asks from; the lock only guards the swap of the immutable tables.+static os_unfair_lock sg_flagsLock = OS_UNFAIR_LOCK_INIT;+static NSDictionary<NSString *, NSDictionary<NSString *, id> *> *sg_flagsByScreen;+static NSDictionary<NSString *, id> *sg_forcedNow;++void SGRedesignForceFlags(NSString *screen, NSDictionary<NSString *, id> *flags) {+ if (!screen.length || !flags.count) return;+ BOOL on = SGRedesignOn(screen);+ os_unfair_lock_lock(&sg_flagsLock);+ NSMutableDictionary *byScreen = [sg_flagsByScreen mutableCopy] ?: [NSMutableDictionary dictionary];+ byScreen[screen] = [flags copy];+ sg_flagsByScreen = [byScreen copy];+ if (on) {+ NSMutableDictionary *forced = [sg_forcedNow mutableCopy] ?: [NSMutableDictionary dictionary];+ [forced addEntriesFromDictionary:flags];+ sg_forcedNow = [forced copy];+ }+ os_unfair_lock_unlock(&sg_flagsLock);+ if (!on) return;+ SGLog(@"redesign %@: forcing %lu flags", screen, (unsigned long)flags.count);+ [flags enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) {+ id override = SGFlagOverride(key);+ if (override) SGLog(@"redesign %@: flag %@ forced %@, the All flags override %@ wins", screen, key, value, override);+ }];+}++id SGRedesignForcedFlag(NSString *key) {+ if (!key || !SGRedesignAnyOn()) return nil;+ os_unfair_lock_lock(&sg_flagsLock);+ id value = sg_forcedNow[key];+ os_unfair_lock_unlock(&sg_flagsLock);+ return value;+}++id SGRedesignOwnedFlag(NSString *key) {+ if (!key) return nil;+ os_unfair_lock_lock(&sg_flagsLock);+ NSDictionary<NSString *, NSDictionary<NSString *, id> *> *byScreen = sg_flagsByScreen;+ os_unfair_lock_unlock(&sg_flagsLock);+ for (NSString *screen in SGRedesignScreens()) {+ id value = byScreen[screen][key];+ if (value && SGFlag(keyFor(screen), NO)) return value;+ }+ return nil;+}diff --git a/tweak/Sources/Redesign/Kit/SGRedesignSettings.m b/tweak/Sources/Redesign/Kit/SGRedesignSettings.mnew file mode 100644index 00000000..95fe17ff--- /dev/null+++ b/tweak/Sources/Redesign/Kit/SGRedesignSettings.m@@ -0,0 +1,77 @@+// The Redesign page: a switch per redesigned screen and whatever rows a screen registers under it,+// the row on the root page of Mod Settings that opens it, and the note the legacy pages lead with+// while their screen is redesigned. Main thread only.+#import "Core/SGCore.h"+#import "Settings/SGModPage.h"+#import "SGRedesign.h"++typedef struct {+ __unsafe_unretained NSString *screen;+ __unsafe_unretained NSString *title;+ __unsafe_unretained NSString *subtitle;+ __unsafe_unretained NSString *symbol;+} SGRScreenRow;++// Spelled out in full rather than built from the screen's name: the page reads like the rest of Mod+// Settings, and a screen without a line here has no switch to show yet.+static const SGRScreenRow kRows[] = {+ {@"player", @"Player", @"The cover's own colour behind the whole player, glass behind the header buttons, and only the lyrics card below it", @"play.circle"},+ {@"artist", @"Artist", @"The photo across the full width fading into its colour, glass Play, Shuffle and Follow, and only the music below", @"music.mic"},+};++static const SGRScreenRow *rowFor(NSString *screen) {+ for (size_t i = 0; i < sizeof(kRows) / sizeof(kRows[0]); i++) {+ if ([kRows[i].screen isEqualToString:screen]) return &kRows[i];+ }+ return NULL;+}++static NSMutableDictionary<NSString *, NSArray<SGModRow *> *(^)(void)> *sg_extraRows;++void SGRedesignRegisterRows(NSString *screen, NSArray<SGModRow *> *(^rows)(void)) {+ if (!screen || !rows) return;+ if (!sg_extraRows) sg_extraRows = [NSMutableDictionary dictionary];+ sg_extraRows[screen] = [rows copy];+}++static NSUInteger countOn(void) {+ NSUInteger on = 0;+ for (NSString *screen in SGRedesignScreens()) {+ if (SGFlag([SGKeyRedesignPrefix stringByAppendingString:screen], NO)) on++;+ }+ return on;+}++UIViewController *SGRedesignSettingsPage(void) {+ NSMutableArray<SGModRow *> *switches = [NSMutableArray array];+ NSMutableArray<SGModSection *> *extras = [NSMutableArray array];+ for (NSString *screen in SGRedesignScreens()) {+ const SGRScreenRow *row = rowFor(screen);+ if (!row) continue;+ [switches addObject:SGWithSymbol(SGOptionRow(row->title, row->subtitle, [SGKeyRedesignPrefix stringByAppendingString:screen]), row->symbol)];+ NSArray<SGModRow *> *(^rows)(void) = sg_extraRows[screen];+ NSArray<SGModRow *> *more = rows ? rows() : nil;+ if (more.count) [extras addObject:SGSection(row->title, more)];+ }+ NSArray<SGModSection *> *sections = [@[+ SGNotedSection(@"Screens", switches, @"A redesigned screen replaces Spotify's own layout, so the switches for it on its part's page stop applying until it is off again."),+ ] arrayByAddingObjectsFromArray:extras];+ return [[SGModPage alloc] initWithTitle:@"Redesign" intro:SGRestartNote sections:sections footer:nil];+}++SGModSection *SGRedesignSection(void) {+ SGModRow *row = SGWithSymbol(SGPageRow(@"Redesign", ^UIViewController *{ return SGRedesignSettingsPage(); }), @"sparkles");+ row.value = ^NSString *{+ NSUInteger on = countOn();+ return on ? [NSString stringWithFormat:@"%lu of %lu", (unsigned long)on, (unsigned long)SGRedesignScreens().count] : @"Off";+ };+ return SGSection(nil, @[row]);+}++SGModSection *SGRedesignNoteSection(NSString *screen) {+ const SGRScreenRow *screenRow = rowFor(screen);+ if (!screenRow || !SGFlag([SGKeyRedesignPrefix stringByAppendingString:screen], NO)) return nil;+ SGModRow *row = SGPageRow([NSString stringWithFormat:@"%@ redesign is on", screenRow->title], ^UIViewController *{ return SGRedesignSettingsPage(); });+ row.subtitle = @"Its own layout replaces Spotify's, so the switches below that change this screen don't apply";+ return SGSection(nil, @[SGWithSymbol(row, @"sparkles")]);+}diff --git a/tweak/Sources/Redesign/Player/Player.h b/tweak/Sources/Redesign/Player/Player.hnew file mode 100644index 00000000..1c605efd--- /dev/null+++ b/tweak/Sources/Redesign/Player/Player.h@@ -0,0 +1,34 @@+// The player redesign (screen key "player"): Spotify's full screen player kept, with its controller,+// units, controls and card list, and restyled from the Kit. Every control stays Spotify's own, so its+// action, state and accessibility do too; the redesign adds the artwork field behind it, glass behind+// the header buttons and the add button, bare glyphs for previous, play and next, a lyrics glyph in the+// footer, and collapses every card under the player except lyrics.+//+// PlayerField.x the switch's flags and rows, the field in the background plane, the cover it reads+// PlayerArtwork.x the cover's corners, shadow and paused shrink, the lyric preview under it hidden+// PlayerHeader.x glass behind the close and more buttons, and behind add+// PlayerControls.x previous, play and next as bare glyphs, monospaced times+// PlayerFooter.x share gone, lyrics, Connect and queue as one row of three glyphs+// PlayerCards.x the lyrics card kept on a content surface, every other card collapsed+//+// Every hook installs only while SGRedesignOn(@"player"); the legacy player hooks stand aside then.+// Threading: main thread only.+#import <UIKit/UIKit.h>++@class SGRArtworkField;++// Whether the lyrics card stays under the player; on until switched off. Off collapses it with the+// rest, and the lyrics glyph still opens the full screen page.+#define SGKeyRedesignPlayerLyricsCard @"spotifyglass.redesign.player.lyricsCard"++// The field behind the player, nil until the player has laid out once (PlayerField.x).+SGRArtworkField *SGRPlayerField(void);++// The lyrics card under the player while it is in a window, else nil (PlayerCards.x).+UIView *SGRPlayerLyricsCard(void);+// Called by PlayerCards.x when the card comes or goes, so the footer's lyrics glyph follows (PlayerFooter.x).+void SGRPlayerLyricsCardChanged(void);++// Alpha 0, no touches, hidden from accessibility, set again on every call: for Spotify's Swift views,+// which SGRSuppress cannot keep (PlayerControls.x).+void SGRPlayerVanish(UIView *view);diff --git a/tweak/Sources/Redesign/Player/PlayerArtwork.x b/tweak/Sources/Redesign/Player/PlayerArtwork.xnew file mode 100644index 00000000..9e0567dc--- /dev/null+++ b/tweak/Sources/Redesign/Player/PlayerArtwork.x@@ -0,0 +1,159 @@+// Player redesign: the cover sits on the field with continuous corners and a soft shadow, and shrinks+// back while playback is paused, the way the Music app's does; the lyric preview under it is gone.+//+// Tree (trees/clean/player/01.txt:36-43): CoverArtCellImpl > ... > CoverArtTiltView 354x354 > an+// ElementView the same size > ImageViewProxy > Encore.ImageView (clips) > UIImageView, with+// Lyrics_NPVContainerKit.LyricsContainerView under the tilt view. The ElementView is what gets the+// corners and the scale: the tilt view's own transform is left to the tilt Spotify gives it when the+// cover is inspected. The image clips, so the shadow is a plate of the Kit's behind it.+//+// The scale is identity while the player opens or closes: the bar morphs into a 354pt stand-in+// (NowPlaying_ECMKit.MaskView, 01.txt:86) and the cover under it has to match where it lands. Once+// the transition is over a paused cover springs down.+#import "Core/SGCore.h"+#import "Redesign/Kit/SGRKit.h"+#import "Player.h"++static const CGFloat kPausedScale = 0.84, kPausedScaleReduceMotion = 0.92;+// The bar's 40pt cover lives in a tilt view of its own; the player's is 354.+static const CGFloat kCoverMinWidth = 200;++static char kPlateKey;+static NSHashTable<UIView *> *sg_tilts;+// The cover of each tilt view once found. A frame Spotify sets on a scaled view becomes its scaled+// size, leaving bounds that no longer match the tilt view's, so the cover is not looked for by size again.+static NSMapTable<UIView *, UIView *> *sg_covers;++static CGFloat currentScale(void) {+ SPTPlayerState *state = SGRPlayerState();+ if (!state.isPaused || SGRPlayerIsTransitioning()) return 1;+ return SGRReduceMotion() ? kPausedScaleReduceMotion : kPausedScale;+}++// The child of the tilt view the size of the cover.+static UIView *coverIn(UIView *tilt) {+ UIView *cover = [sg_covers objectForKey:tilt];+ if (cover.superview == tilt) return cover;+ for (UIView *sub in tilt.subviews) {+ if (![sub isKindOfClass:SGRShadowPlate.class] && CGSizeEqualToSize(sub.bounds.size, tilt.bounds.size)) {+ [sg_covers setObject:sub forKey:tilt];+ return sub;+ }+ }+ return nil;+}++static BOOL inCoverCell(UIView *tilt) {+ static Class cell;+ if (!cell) cell = NSClassFromString(@"_TtC28NowPlaying_ContentLayersImpl16CoverArtCellImpl");+ for (UIView *v = tilt.superview; v; v = v.superview) {+ if ([v isKindOfClass:cell]) return YES;+ }+ return NO;+}++static void scaleCover(UIView *tilt, CGFloat scale) {+ UIView *cover = coverIn(tilt);+ if (!cover) return;+ SGRShadowPlate *plate = SGRShadowPlateIn(tilt, &kPlateKey);+ CGAffineTransform transform = CGAffineTransformMakeScale(scale, scale);+ cover.transform = transform;+ plate.transform = transform;+}++static void scaleEveryCover(BOOL animated) {+ CGFloat scale = currentScale();+ NSArray<UIView *> *tilts = sg_tilts.allObjects;+ void (^apply)(void) = ^{+ for (UIView *tilt in tilts) scaleCover(tilt, scale);+ };+ if (animated) SGRAnimate(SGRMotionLayout, apply, nil);+ else apply();+}++%hook _TtC35CreativeWorkCommons_CoverArtTiltKit16CoverArtTiltView+- (void)layoutSubviews {+ %orig;+ UIView *tilt = (UIView *)self;+ if (tilt.bounds.size.width < kCoverMinWidth || !inCoverCell(tilt)) return;+ UIView *cover = coverIn(tilt);+ if (!cover) return;+ [sg_tilts addObject:tilt];+ // The cover fills the tilt view (01.txt:37); bounds and center, unlike a frame, hold under the scale.+ CGRect bounds = tilt.bounds;+ CGPoint middle = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds));+ if (!CGSizeEqualToSize(cover.bounds.size, bounds.size)) cover.bounds = (CGRect){cover.bounds.origin, bounds.size};+ if (!CGPointEqualToPoint(cover.center, middle)) cover.center = middle;++ cover.layer.cornerRadius = SGRRadiusArtwork;+ cover.layer.cornerCurve = kCACornerCurveContinuous;+ cover.clipsToBounds = YES;+ SGRShadowPlate *plate = SGRShadowPlateIn(tilt, &kPlateKey);+ plate.bounds = cover.bounds;+ plate.center = cover.center;+ // The same value an animation in flight is heading to, so a layout pass never cuts one short.+ scaleCover(tilt, currentScale());++ static dispatch_once_t once;+ dispatch_once(&once, ^{ SGLog(@"redesign player: cover %@ rounded %.0f with a shadow plate, scale %.2f", NSStringFromClass(cover.class), SGRRadiusArtwork, currentScale()); });+}+%end++// Spotify shows and hides the preview as lyrics come and go; it stays hidden, the way+// Declutter/Declutter.x has shipped it (its parent is a plain view, 01.txt:35, not a stack).+%hook _TtC22Lyrics_NPVContainerKit19LyricsContainerView+- (void)setHidden:(BOOL)hidden {+ %orig(YES);+}+- (void)didMoveToWindow {+ %orig;+ ((UIView *)self).hidden = YES;+}+%end++@interface SGRPlayerArtworkWatcher : NSObject <SGRPlayerStateObserver>+@end++@implementation SGRPlayerArtworkWatcher {+ NSInteger _paused;+}++- (instancetype)init {+ if (!(self = [super init])) return nil;+ _paused = -1;+ return self;+}++- (void)playerStateDidChange:(SPTPlayerState *)state {+ NSInteger paused = state.isPaused ? 1 : 0;+ if (paused == _paused) return;+ _paused = paused;+ scaleEveryCover(YES);+ static NSUInteger logged;+ if (logged++ < 3) SGLog(@"redesign player: state paused=%d loading=%d, %lu covers scaled", state.isPaused, state.isLoading, (unsigned long)sg_tilts.count);+}++@end++static SGRPlayerArtworkWatcher *sg_artworkWatcher;++%ctor {+ if (!SGRedesignOn(@"player")) return;+ %init;+ sg_tilts = [NSHashTable weakObjectsHashTable];+ sg_covers = [NSMapTable weakToWeakObjectsMapTable];+ sg_artworkWatcher = [SGRPlayerArtworkWatcher new];+ SGRAddPlayerStateObserver(sg_artworkWatcher);+ SGRObservePlayerTransition(sg_artworkWatcher, ^(id owner) {+ scaleEveryCover(YES);+ }, ^(id owner) {+ scaleEveryCover(YES);+ static dispatch_once_t once;+ dispatch_once(&once, ^{ SGLog(@"redesign player: transition over, cover scale %.2f", currentScale()); });+ });+ SGRequireClasses(@[+ @"_TtC35CreativeWorkCommons_CoverArtTiltKit16CoverArtTiltView",+ @"_TtC28NowPlaying_ContentLayersImpl16CoverArtCellImpl",+ @"_TtC22Lyrics_NPVContainerKit19LyricsContainerView",+ ]);+}diff --git a/tweak/Sources/Redesign/Player/PlayerCards.x b/tweak/Sources/Redesign/Player/PlayerCards.xnew file mode 100644index 00000000..d6343f22--- /dev/null+++ b/tweak/Sources/Redesign/Player/PlayerCards.x@@ -0,0 +1,185 @@+// Player redesign: of the cards under the player only lyrics is kept, on a content surface in the field's+// colour when Apple Music style lyrics draw it; every other card (about the artist, videos, SongDNA, events, explore, credits, merch, anything+// Spotify adds later) reports no height, so the list closes up around it.+//+// An allow list rather than Declutter's block list: the server decides which cards a track gets, and a+// new kind should not turn up under a redesigned player. The collapse is the one Declutter/Declutter.x+// has shipped (the 24pt gaps between cards stay until the card list is filtered at the network, phase 2).+//+// Tree (trees/clean/player/01.txt:385, lyrics/01.txt:996-999): every card is an Element_List.CollectionViewCell+// whose first subview is an ElementContentView naming NowPlaying_ScrollAPI, then an ElementView, then+// the card's own root: Lyrics_CardElementImpl.CardView id=lyrics-card-view for lyrics,+// CreatorBiographyCardLayout, song-dna-npv-card and so on for the rest (all ten player snapshots). The+// cells of lists inside a card (WatchFeed's) name WatchFeed_ComponentAPI instead, so they are left to+// their card. The card's share button is id=lyrics-share-button (lyrics/01.txt:1009).+#import "Core/SGCore.h"+#import "Redesign/Kit/SGRKit.h"+#import "Features/Karaoke/Karaoke.h"+#import "Player.h"++// Below this a cell is collapsed, or still being laid out.+static const CGFloat kLivingHeight = 40;++static char kShareKey, kRevalidatedKey;+static __weak UIView *sg_lyricsCard;++// Read once, like the switch: every card is sized through here.+static BOOL lyricsAllowed(void) {+ static BOOL allowed;+ static dispatch_once_t once;+ dispatch_once(&once, ^{ allowed = SGEnabled(SGKeyRedesignPlayerLyricsCard); });+ return allowed;+}++// Spotify draws the lines still to come in black, for its card in the album colour (lyrics/01.txt:1054),+// so they read on the field's dark surface only with Apple Music style lyrics drawn over them; without+// those the card keeps Spotify's own colour.+static BOOL surfaceWanted(void) {+ static BOOL wanted;+ static dispatch_once_t once;+ dispatch_once(&once, ^{ wanted = SGFlag(SGKeyKaraokeLyrics, NO); });+ return wanted;+}++// In a window and not in a hidden cell: the list keeps the cells it has put aside for reuse in it, hidden+// (player/02.txt:521), each with the card it last held.+static BOOL showing(UIView *card) {+ if (!card.window) return NO;+ for (UIView *v = card; v; v = v.superview) {+ if (v.hidden) return NO;+ if ([v isKindOfClass:UICollectionView.class]) break;+ }+ return YES;+}++UIView *SGRPlayerLyricsCard(void) {+ UIView *card = sg_lyricsCard;+ return showing(card) ? card : nil;+}++// Whether the cell's content is the player's card list, remembered per content class.+static BOOL isPlayerCard(UIView *content) {+ static NSMutableSet<Class> *yes, *no;+ if (!yes) {+ yes = [NSMutableSet set];+ no = [NSMutableSet set];+ }+ Class cls = object_getClass(content);+ if (!cls || [no containsObject:cls]) return NO;+ if ([yes containsObject:cls]) return YES;+ BOOL player = [NSStringFromClass(cls) containsString:@"NowPlaying_ScrollAPI"];+ [(player ? yes : no) addObject:cls];+ return player;+}++static Class cardViewClass(void) {+ static Class cls;+ if (!cls) cls = NSClassFromString(@"_TtC22Lyrics_CardElementImpl8CardView");+ return cls;+}++static UIView *cellAround(UIView *view) {+ static Class cell;+ if (!cell) cell = NSClassFromString(@"_TtC12Element_List18CollectionViewCell");+ for (UIView *v = view.superview; v; v = v.superview) {+ if ([v isKindOfClass:cell]) return v;+ }+ return nil;+}++%hook _TtC12Element_List18CollectionViewCell+- (UICollectionViewLayoutAttributes *)preferredLayoutAttributesFittingAttributes:(UICollectionViewLayoutAttributes *)attributes {+ UICollectionViewLayoutAttributes *result = %orig;+ UIView *cell = (UIView *)self;+ UIView *content = cell.subviews.firstObject;+ if (!content || !isPlayerCard(content)) return result;+ UIView *root = content.subviews.firstObject.subviews.firstObject;+ if ([root isKindOfClass:cardViewClass()] && lyricsAllowed()) return result;+ result.size = CGSizeMake(result.size.width, 0);+ cell.clipsToBounds = YES;++ static NSMutableSet<NSString *> *logged;+ if (!logged) logged = [NSMutableSet set];+ NSString *name = root ? NSStringFromClass(root.class) : @"nothing yet";+ if (![logged containsObject:name]) {+ [logged addObject:name];+ SGLog(@"redesign player: collapsed card root %@ (%lu kinds so far)", name, (unsigned long)logged.count);+ }+ return result;+}+%end++%hook _TtC22Lyrics_CardElementImpl8CardView+- (void)layoutSubviews {+ %orig;+ UIView *card = (UIView *)self;+ UIView *cell = cellAround(card);+ if (!cell || !isPlayerCard(cell.subviews.firstObject)) return;+ // A card in a cell put aside never replaces one showing; a cell taken back from reuse keeps its card,+ // so the glyph is told on every pass (it returns at once when nothing changed).+ if (sg_lyricsCard != card && (showing(card) || !showing(sg_lyricsCard))) sg_lyricsCard = card;+ SGRPlayerLyricsCardChanged();++ UIView *share = SGRFindByIdentifier(card, @"lyrics-share-button", &kShareKey);+ SGRPlayerVanish(share);++ if (!lyricsAllowed()) return;+ if (cell.bounds.size.height >= kLivingHeight) {+ objc_setAssociatedObject(cell, &kRevalidatedKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ SGRArtworkField *field = SGRPlayerField();+ // Made only with the player's own field to follow; the artist page has a field of its own.+ if (field && surfaceWanted()) SGRCardSurface(cell, field);+ return;+ }+ // Sized before its card was in it, so it was collapsed as an unknown card: the list is asked once to+ // size it again, and not again until it has been seen at its height.+ if (objc_getAssociatedObject(cell, &kRevalidatedKey)) return;+ UICollectionView *list = (UICollectionView *)cell.superview;+ NSIndexPath *path = [list isKindOfClass:UICollectionView.class] ? [list indexPathForCell:(UICollectionViewCell *)cell] : nil;+ if (!path) return;+ objc_setAssociatedObject(cell, &kRevalidatedKey, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ UICollectionViewLayoutInvalidationContext *context = [[list.collectionViewLayout.class invalidationContextClass] new];+ [context invalidateItemsAtIndexPaths:@[path]];+ [list.collectionViewLayout invalidateLayoutWithContext:context];+ SGLog(@"redesign player: lyrics cell sized again at %@", path);+}++- (void)didMoveToWindow {+ %orig;+ if ((UIView *)self == sg_lyricsCard) SGRPlayerLyricsCardChanged();+}+%end++// A track without lyrics puts the card's cell aside without laying the card out or taking it out of+// the window, so the footer's glyph looks again while the next track's cards come in (the player+// waits up to 5 s for them).+@interface SGRPlayerCardsWatcher : NSObject <SGRPlayerStateObserver>+@end++@implementation SGRPlayerCardsWatcher {+ NSString *_track;+}++- (void)playerStateDidChange:(SPTPlayerState *)state {+ NSString *track = SGRURIString(state.track.URI);+ if (!track || [track isEqualToString:_track]) return;+ _track = track;+ for (NSNumber *delay in @[@1, @3, @6]) {+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay.doubleValue * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ SGRPlayerLyricsCardChanged(); });+ }+}++@end++static SGRPlayerCardsWatcher *sg_cardsWatcher;++%ctor {+ if (!SGRedesignOn(@"player")) return;+ %init;+ sg_cardsWatcher = [SGRPlayerCardsWatcher new];+ SGRAddPlayerStateObserver(sg_cardsWatcher);+ SGRequireClasses(@[+ @"_TtC12Element_List18CollectionViewCell",+ @"_TtC22Lyrics_CardElementImpl8CardView",+ ]);+}diff --git a/tweak/Sources/Redesign/Player/PlayerControls.x b/tweak/Sources/Redesign/Player/PlayerControls.xnew file mode 100644index 00000000..6ec13530--- /dev/null+++ b/tweak/Sources/Redesign/Player/PlayerControls.x@@ -0,0 +1,214 @@+// Player redesign: previous, play and next as bare glyphs, the way the Music app draws them, and the+// timestamps under the slider in digits of one width, so they stop twitching every second.+//+// The glyphs are drawn over Spotify's controls rather than instead of them: each button keeps its+// action, its enabled state, its accessibility and the Gestures zones around it, and the glyph takes no+// touches. Previous and next get theirs inside the button's content view, so the button's own press+// and disabled look carry over; Spotify's icon under it goes transparent on every pass (SPTEncoreIconView+// is a Swift class, which SGRSuppress cannot keep). Play loses its white disc, a plain UIImageView the+// size of the button, which SGRSuppress keeps transparent, and the glyph over it follows the player's state.+//+// Tree (trees/clean/player/01.txt): PlaybackControlsElementsUnit's view holds+// id=SPTNowPlayingPreviousTrackButton 56x56 > UIView > StackView > StackView > SPTEncoreIconView (:257),+// id=SPTNowPlayingPlayButton (PlayButtonView 64x64, :266) > CondensedButton (a UIButton,+// objc-meta-Spotify.txt:207312) > UIImageView 64x64 and a hidden SpinnerView, next to a hidden UIView+// holding a UIImageView (:277), and id=SPTNowPlayingNextTrackButton. DurationElementUnit's view holds+// id=now-playing-time-take-label and id=now-playing-time-remaning-label, SPTEncoreLabels whose UILabel+// is id=...-internal (:227). The sticky header has a play button of its own (:492), which a search+// inside the unit's view never reaches.+#import "Core/SGCore.h"+#import "Redesign/Kit/SGRKit.h"+#import "Player.h"++static const CGFloat kSkipGlyphSize = 32, kPlayGlyphSize = 44;+// A spinner that is still up this long after a state change is buffering, not a track starting.+static const NSTimeInterval kSpinnerCheck = 0.6;++static char kPreviousKey, kNextKey, kPlayKey, kGlyphKey, kTakeKey, kRemainingKey;+static __weak UIButton *sg_playButton;+static __weak SGRGlyphView *sg_playGlyph;+static __weak UIView *sg_controlsHost;++void SGRPlayerVanish(UIView *view) {+ if (!view) return;+ if (view.alpha != 0) view.alpha = 0;+ view.userInteractionEnabled = NO;+ view.accessibilityElementsHidden = YES;+}++static void logMissing(NSString *what) {+ static NSMutableSet<NSString *> *logged;+ if (!logged) logged = [NSMutableSet set];+ if ([logged containsObject:what]) return;+ [logged addObject:what];+ SGLog(@"redesign player: %@ not found, left as Spotify's", what);+}++static SGRGlyphView *glyphFor(UIView *owner, NSString *symbol, CGFloat size) {+ SGRGlyphView *glyph = objc_getAssociatedObject(owner, &kGlyphKey);+ if (!glyph) {+ glyph = [[SGRGlyphView alloc] initWithSymbol:symbol pointSize:size weight:UIImageSymbolWeightRegular];+ objc_setAssociatedObject(owner, &kGlyphKey, glyph, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ }+ return glyph;+}++// Centred by the autoresizing mask as well as here: the unit lays out before the buttons in its row+// have a size, so a centre set then is the middle of nothing, (0, 0), and no later pass of the unit's+// comes to move it (trees/continuous/1.txt, 2026-09-17: glyphs at {-23.7, -14.7} in 56pt buttons).+static void keepOnTop(UIView *view, UIView *host) {+ if (view.superview != host) {+ view.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin+ | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;+ [host addSubview:view];+ } else if (host.subviews.lastObject != view) {+ [host bringSubviewToFront:view];+ }+ view.center = CGPointMake(CGRectGetMidX(host.bounds), CGRectGetMidY(host.bounds));+}++#pragma mark - previous and next++static void skipGlyph(UIView *host, NSString *identifier, const void *findKey, NSString *symbol) {+ UIView *button = SGRFindByIdentifier(host, identifier, findKey);+ UIView *content = button.subviews.firstObject;+ if (!content) {+ logMissing(identifier);+ return;+ }+ static Class icon;+ if (!icon) icon = NSClassFromString(@"SPTEncoreIconView");+ SGRGlyphView *glyph = glyphFor(button, symbol, kSkipGlyphSize);+ SGForEachView(content, ^(UIView *view) {+ if (view != glyph && [view isKindOfClass:icon]) SGRPlayerVanish(view);+ });+ keepOnTop(glyph, content);+}++#pragma mark - play++static BOOL spinnerShowing(UIButton *button) {+ for (UIView *sub in button.subviews) {+ if (!sub.hidden && sub.alpha > 0.01 && [NSStringFromClass(sub.class) containsString:@"SpinnerView"]) return YES;+ }+ return NO;+}++static void refreshPlayGlyph(BOOL animated) {+ SGRGlyphView *glyph = sg_playGlyph;+ SPTPlayerState *state = SGRPlayerState();+ if (!glyph || !state) return;+ [glyph setSymbol:state.isPaused ? @"play.fill" : @"pause.fill" animated:animated];+ glyph.alpha = spinnerShowing(sg_playButton) ? 0 : 1;+}++static void playGlyph(UIView *host) {+ UIView *play = SGRFindByIdentifier(host, @"SPTNowPlayingPlayButton", &kPlayKey);+ if (!play) {+ logMissing(@"SPTNowPlayingPlayButton");+ return;+ }+ // Before the player has reported a state the glyph could only guess, so the disc stays.+ SPTPlayerState *state = SGRPlayerState();+ if (!state) return;+ UIButton *button = nil;+ for (UIView *sub in play.subviews) {+ if ([sub isKindOfClass:UIButton.class]) button = (UIButton *)sub;+ }+ UIImageView *disc = nil;+ for (UIView *sub in button.subviews) {+ if ([sub isKindOfClass:UIImageView.class] && CGSizeEqualToSize(sub.bounds.size, button.bounds.size)) disc = (UIImageView *)sub;+ }+ if (!disc) {+ logMissing(@"the play button's disc");+ return;+ }+ SGRSuppress(disc);+ // The holder Spotify crossfades a snapshot of the disc in when play turns to pause.+ for (UIView *sub in play.subviews) {+ if (object_getClass(sub) != UIView.class) continue;+ for (UIView *image in sub.subviews) {+ if ([image isKindOfClass:UIImageView.class]) SGRSuppress(image);+ }+ }++ // Inside the button, over the disc it replaces, so it follows the button's own press.+ SGRGlyphView *glyph = glyphFor(play, state.isPaused ? @"play.fill" : @"pause.fill", kPlayGlyphSize);+ keepOnTop(glyph, button);+ sg_playButton = button;+ sg_playGlyph = glyph;+ refreshPlayGlyph(NO);++ static dispatch_once_t once;+ dispatch_once(&once, ^{ SGLog(@"redesign player: play glyph over %@ (disc %@ suppressed), spinner %@", NSStringFromClass(play.class), NSStringFromClass(disc.class), spinnerShowing(button) ? @"showing" : @"hidden"); });+}++%hook _TtC20NowPlaying_ModesImpl28PlaybackControlsElementsUnit+- (void)viewDidLayoutSubviews {+ %orig;+ UIView *host = ((UIViewController *)self).viewIfLoaded;+ if (!host) return;+ // The unit lays out before its row does, and the glyphs are centred on the buttons in it.+ [SGRowIn(host) layoutIfNeeded];+ sg_controlsHost = host;+ skipGlyph(host, @"SPTNowPlayingPreviousTrackButton", &kPreviousKey, @"backward.fill");+ skipGlyph(host, @"SPTNowPlayingNextTrackButton", &kNextKey, @"forward.fill");+ playGlyph(host);+}+%end++@interface SGRPlayerControlsWatcher : NSObject <SGRPlayerStateObserver>+@end++@implementation SGRPlayerControlsWatcher++- (void)playerStateDidChange:(SPTPlayerState *)state {+ // The first state can land after the controls laid out, which left the disc for want of one.+ if (!sg_playGlyph) [sg_controlsHost setNeedsLayout];+ refreshPlayGlyph(YES);+ // Spotify raises its spinner a moment after a state says loading, and drops it a moment after.+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kSpinnerCheck * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ refreshPlayGlyph(YES); });+}++@end++static SGRPlayerControlsWatcher *sg_controlsWatcher;++#pragma mark - times++static UILabel *monospaced(UIView *host, NSString *identifier, const void *findKey) {+ UILabel *label = (UILabel *)SGRFindByIdentifier(host, identifier, findKey);+ if (![label isKindOfClass:UILabel.class]) {+ logMissing(identifier);+ return nil;+ }+ SGRMonospacedDigits(label);+ return label;+}++%hook _TtC20NowPlaying_ModesImpl19DurationElementUnit+- (void)viewDidLayoutSubviews {+ %orig;+ UIView *host = ((UIViewController *)self).viewIfLoaded;+ if (!host) return;+ UILabel *taken = monospaced(host, @"now-playing-time-take-label-internal", &kTakeKey);+ monospaced(host, @"now-playing-time-remaning-label-internal", &kRemainingKey);+ // Whether Spotify's font has digits of one width shows in the descriptor's feature settings.+ if (!taken) return;+ static dispatch_once_t once;+ dispatch_once(&once, ^{ SGLog(@"redesign player: monospaced times in %@ %.0fpt, features %@", taken.font.fontName, taken.font.pointSize, taken.font.fontDescriptor.fontAttributes[UIFontDescriptorFeatureSettingsAttribute]); });+}+%end++%ctor {+ if (!SGRedesignOn(@"player")) return;+ %init;+ sg_controlsWatcher = [SGRPlayerControlsWatcher new];+ SGRAddPlayerStateObserver(sg_controlsWatcher);+ SGRequireClasses(@[+ @"_TtC20NowPlaying_ModesImpl28PlaybackControlsElementsUnit",+ @"_TtC20NowPlaying_ModesImpl19DurationElementUnit",+ @"_TtC28EncoreConsumerMobile_BaseKit14PlayButtonView",+ @"SPTEncoreIconView",+ ]);+}diff --git a/tweak/Sources/Redesign/Player/PlayerField.x b/tweak/Sources/Redesign/Player/PlayerField.xnew file mode 100644index 00000000..05f1bd57--- /dev/null+++ b/tweak/Sources/Redesign/Player/PlayerField.x@@ -0,0 +1,188 @@+// Player redesign: the artwork field behind the full screen player, and what the switch forces.+//+// Tree (trees/clean/player/01.txt:449): NPVBackgroundViewController's view is a plane inside the NPV's+// own list (scrolling_npv_collection_view), painted the album colour with Spotify's gradients+// (NPVGradientView) stacked on it. Its top stays at the top of the content and it grows as the list+// scrolls (874 at rest, 1495 and 2144 further down, 02.txt:757, 03.txt:861), so a field inside it+// scrolls with the cards and is laid out again on every scroll frame: the hook only compares a frame.+// The field goes on top of the plane's own subviews, so Spotify's gradients are covered rather than+// fought over, and nothing depends on Appearance/Repaint.x.+//+// The picture comes from the Kit's now playing artwork: the now playing bar's 40pt cover, published by+// the Kit, and the player's own 354pt cover, published here from the cell in the middle of the+// sideways list of covers (AccessibleCollectionView, 01.txt:28, one CoverArtCellImpl per queued track,+// the ones out of view hidden). Until the first picture has been read the field takes the colour+// Spotify already has for the player, from -[NPVBackgroundViewController+// backgroundViewModel:didChangeColor:playerState:] (objc-methods.txt:57949).+#import "Core/SGCore.h"+#import "Settings/SGModPage.h"+#import "Redesign/Kit/SGRKit.h"+#import "Player.h"++// Past the plane's edges: above for the pull that dismisses the player, below for the bounce at the end+// of the cards.+static const UIEdgeInsets kBleed = {200, 0, 600, 0};+// A cover this narrow is a placeholder glyph or the bar's, not the player's.+static const CGFloat kCoverMinWidth = 200;++static char kFieldKey, kCoverImageKey;+static __weak SGRArtworkField *sg_field;+static __weak UIScrollView *sg_coverList;+static __weak UIImage *sg_lastCover;+static NSString *sg_lastCoverURI;+// Spotify's colour for the player, which can arrive before the plane has laid out once.+static UIColor *sg_spotifyColor;++SGRArtworkField *SGRPlayerField(void) {+ return sg_field;+}++#pragma mark - the field++static void showArtwork(SGRArtworkField *field, BOOL animated) {+ NSString *identity = nil;+ UIImage *image = SGRNowPlayingArtwork(NULL, &identity);+ if (field && image) [field setArtwork:image identity:identity animated:animated];+}++static SGRArtworkField *fieldIn(UIView *plane) {+ SGRArtworkField *field = objc_getAssociatedObject(plane, &kFieldKey);+ if (field) return field;+ field = [[SGRArtworkField alloc] initWithFrame:plane.bounds];+ field.showsBackdrop = YES;+ field.bleed = kBleed;+ objc_setAssociatedObject(plane, &kFieldKey, field, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ sg_field = field;+ [field setProvisionalColor:sg_spotifyColor];+ // Made while the player is about to open: whatever is read lands in the first frames of the+ // animation, where a crossfade would only add work.+ showArtwork(field, NO);+ SGLog(@"redesign player: field in the background plane %.0fx%.0f, artwork %@", plane.bounds.size.width, plane.bounds.size.height, SGRNowPlayingArtwork(NULL, NULL) ? @"ready" : @"not read yet");+ return field;+}++%hook _TtC21NowPlaying_ScrollImpl27NPVBackgroundViewController+- (void)viewDidLayoutSubviews {+ %orig;+ UIView *plane = ((UIViewController *)self).viewIfLoaded;+ if (!plane || plane.bounds.size.height < 200) return;+ SGRArtworkField *field = fieldIn(plane);+ sg_field = field;+ if (field.superview != plane) [plane addSubview:field];+ else if (plane.subviews.lastObject != field) [plane bringSubviewToFront:field];+ if (!CGRectEqualToRect(field.frame, plane.bounds)) field.frame = plane.bounds;+}++- (void)backgroundViewModel:(id)model didChangeColor:(id)color playerState:(id)state {+ %orig;+ static dispatch_once_t once;+ dispatch_once(&once, ^{ SGLog(@"redesign player: Spotify's colour %@ (%@), state %@", color, [color class], [state class]); });+ if (![color isKindOfClass:UIColor.class]) return;+ sg_spotifyColor = color;+ UIView *plane = ((UIViewController *)self).viewIfLoaded;+ SGRArtworkField *field = plane ? objc_getAssociatedObject(plane, &kFieldKey) : nil;+ [field setProvisionalColor:color];+}+%end++#pragma mark - the player's own cover++// The picture of the cell under the middle of the list once it has settled: mid swipe the middle is+// between two tracks.+static UIImage *settledCover(UIScrollView *list) {+ if (!list.window || list.isDragging || list.isDecelerating) return nil;+ CGFloat middle = CGRectGetMidX(list.bounds);+ for (UIView *cell in list.subviews) {+ if (cell.hidden || ![cell isKindOfClass:UICollectionViewCell.class] || fabs(CGRectGetMidX(cell.frame) - middle) > 1) continue;+ UIView *holder = SGRFindByIdentifier(cell, @"Encore.ImageView", &kCoverImageKey);+ if (holder.bounds.size.width < kCoverMinWidth) return nil;+ for (UIView *sub in holder.subviews) {+ UIImageView *image = (UIImageView *)sub;+ if ([sub isKindOfClass:UIImageView.class] && image.image && image.alpha > 0) return image.image;+ }+ return nil;+ }+ return nil;+}++static void publishCover(void) {+ UIImage *cover = settledCover(sg_coverList);+ if (!cover) return;+ NSString *uri = SGRURIString(SGRPlayerState().track.URI);+ if (!uri || (cover == sg_lastCover && [uri isEqualToString:sg_lastCoverURI])) return;+ sg_lastCover = cover;+ sg_lastCoverURI = uri;+ SGRSetNowPlayingArtwork(cover, uri, SGRArtworkQualityHigh);+ static NSUInteger logged;+ if (logged++ < 3) SGLog(@"redesign player: cover %.0fx%.0f published for %@", cover.size.width, cover.size.height, uri);+}++%hook _TtC35NowPlaying_ContentLayerPlatformImpl24AccessibleCollectionView+- (void)layoutSubviews {+ %orig;+ sg_coverList = (UIScrollView *)self;+ publishCover();+}+%end++// A cover that loads after the track changed sets an image and lays nothing out, so the list is looked+// at again a few times while it comes in, as the Kit does for the bar.+@interface SGRPlayerCoverWatcher : NSObject <SGRPlayerStateObserver>+@end++@implementation SGRPlayerCoverWatcher {+ NSString *_track;+}++- (void)playerStateDidChange:(SPTPlayerState *)state {+ NSString *track = SGRURIString(state.track.URI);+ if (!track || [track isEqualToString:_track]) return;+ _track = track;+ for (NSNumber *delay in @[@0.3, @1, @2.5]) {+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay.doubleValue * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ publishCover(); });+ }+}++@end++static SGRPlayerCoverWatcher *sg_coverWatcher;++%ctor {+ // Registered whatever the switch says: the flag rows elsewhere lock to these while it is on.+ NSMutableDictionary<NSString *, id> *flags = [@{+ // The artwork is the picture; Canvas video would cover the field and the corners.+ @"ios-feature-canvas.canvas_enabled": @NO,+ // The header, slider and sheets the trees were recorded with (trees/clean/player/01.txt:122+ // id=Context menu, :216 SPTNowPlayingSliderV2).+ @"ios-feature-nowplaying.new_redesign_header_with_context_menu_enabled": @YES,+ @"ios-feature-encoreexperiments.new_npv_slider_enabled": @YES,+ @"ios-feature-nowplaying.bottom_sheet_queue_enabled": @YES,+ @"ios-feature-nowplaying-elements.enable_connect_bottom_sheet": @YES,+ @"ios-feature-nowplaying.sheet_style_npv": @YES,+ // Art around the play disc would sit under a bare glyph.+ @"ios-feature-nowplaying-elements.mixing_play_button": @NO,+ } mutableCopy];+ for (NSString *egg in @[@"ariana_petal_play_button_easter_egg", @"attack_on_titan_easter_egg_enabled", @"barbie_easter_egg_enabled",+ @"black_panther_easter_egg_enabled", @"demogorgon_easter_egg", @"harry_potter_play_button_surround_easter_egg",+ @"luma_easter_egg", @"pokemon_easter_egg_enabled", @"sanremo_easter_egg_enabled", @"sanrio_easter_egg_enabled",+ @"spiderman_easter_egg_enabled", @"star_easter_egg", @"wednesday_easter_egg", @"wicked_easter_egg_enabled",+ @"world_cup_easter_egg"]) {+ flags[[@"ios-feature-nowplaying." stringByAppendingString:egg]] = @NO;+ }+ SGRedesignForceFlags(@"player", flags);+ SGRedesignRegisterRows(@"player", ^NSArray<SGModRow *> *{+ return @[SGSwitchRow(@"Lyrics under the player", @"The lyrics card below the player; every other card is left out", SGKeyRedesignPlayerLyricsCard)];+ });++ if (!SGRedesignOn(@"player")) return;+ %init;+ sg_coverWatcher = [SGRPlayerCoverWatcher new];+ SGRAddPlayerStateObserver(sg_coverWatcher);+ [NSNotificationCenter.defaultCenter addObserverForName:SGRNowPlayingArtworkDidChangeNotification object:nil queue:nil usingBlock:^(NSNotification *note) {+ showArtwork(sg_field, YES);+ }];+ SGRequireClasses(@[+ @"_TtC21NowPlaying_ScrollImpl27NPVBackgroundViewController",+ @"_TtC35NowPlaying_ContentLayerPlatformImpl24AccessibleCollectionView",+ ]);+}diff --git a/tweak/Sources/Redesign/Player/PlayerFooter.x b/tweak/Sources/Redesign/Player/PlayerFooter.xnew file mode 100644index 00000000..954f73ff--- /dev/null+++ b/tweak/Sources/Redesign/Player/PlayerFooter.x@@ -0,0 +1,146 @@+// Player redesign: the footer as the Music app's row of three glyphs, lyrics, devices and queue, spread+// evenly across the player, and no share button.+//+// Spotify's footer is Connect with the device's name at the leading edge, share, and the queue at the+// trailing edge. Connect and the queue stay Spotify's controls (the device sheet, the remote device+// tint, the Jam avatars) and are only moved, by a translation of the arranged view that holds each: a+// transform survives the stack view laying them out again, and moving the holder keeps its touches+// inside its own bounds. The device name goes transparent, since the glyph alone sits in the middle.+// Spotify has no lyrics control down here, so that one is the Kit's glyph button, which fires the+// lyrics card's own expand button, or opens spotify:lyrics:fullscreen when there is no card.+//+// Tree (trees/clean/player/01.txt:295-320): FooterElementsUnit's view 402x44 > UIStackView 382x44 >+// ElementView > ConnectButtonOutputSwitcherViewHolder id=Components.ConnectButtonOutputSwitcher 153x36+// (a 19x19 UIImageView glyph and a MarqueeLabel with the device name), a spacer, a hidden media trimmer,+// ElementView > EncoreButton id=ShareButtonNowPlayingView 44x44, ElementView > Queue control+// id=QueueButtonNowPlaying 47x32. The card's button is id=lyrics-expand-button, an EncoreButton, which+// is a UIButton (trees/clean/lyrics/01.txt:1013, objc-meta-Spotify.txt:216095).+#import "Core/SGCore.h"+#import "Redesign/Kit/SGRKit.h"+#import "Player.h"++static const CGFloat kLyricsGlyphSize = 20;+// Where the three glyphs sit, as parts of the footer's width.+static const CGFloat kLeading = 0.2, kMiddle = 0.5, kTrailing = 0.8;+static const CGFloat kGlyphMaxWidth = 30;++static char kConnectKey, kShareKey, kTrimmerKey, kQueueKey, kLyricsGlyphKey, kExpandKey;+static __weak SGRGlyphButton *sg_lyricsGlyph;++// The view the footer's stack view arranges around `view`.+static UIView *arrangedAround(UIView *view, UIView *host) {+ for (UIView *v = view; v && v != host; v = v.superview) {+ if ([v.superview isKindOfClass:UIStackView.class]) return v;+ }+ return nil;+}++// Where `point` of `view` is in the host with the arranged view's own transform left out.+static CGFloat untransformedX(UIView *arranged, UIView *view, CGPoint point, UIView *host) {+ CGPoint local = [view convertPoint:point toView:arranged];+ CGPoint inRow = CGPointMake(arranged.center.x + local.x - CGRectGetMidX(arranged.bounds), arranged.center.y);+ return [arranged.superview convertPoint:inRow toView:host].x;+}++static CGFloat moveTo(UIView *arranged, UIView *view, CGPoint point, UIView *host, CGFloat x) {+ if (!arranged) return -1;+ CGFloat from = untransformedX(arranged, view, point, host);+ CGAffineTransform transform = CGAffineTransformMakeTranslation(round(x - from), 0);+ if (!CGAffineTransformEqualToTransform(arranged.transform, transform)) arranged.transform = transform;+ return from;+}++#pragma mark - lyrics++static void openLyrics(void) {+ UIView *card = SGRPlayerLyricsCard();+ UIControl *expand = (UIControl *)SGRFindByIdentifier(card, @"lyrics-expand-button", &kExpandKey);+ NSString *how = @"nothing";+ if ([expand isKindOfClass:UIControl.class] && SGRFire(expand)) how = @"the card's expand button";+ else if (SGROpenURI([NSURL URLWithString:@"spotify:lyrics:fullscreen"])) how = @"spotify:lyrics:fullscreen";+ SGLog(@"redesign player: lyrics glyph opened the page by %@", how);+}++void SGRPlayerLyricsCardChanged(void) {+ SGRGlyphButton *glyph = sg_lyricsGlyph;+ BOOL enabled = SGRPlayerLyricsCard() != nil;+ if (!glyph || glyph.enabled == enabled) return;+ // The card turns up once the player has fetched it, well after the footer laid out: a fade, not a+ // pop. While the player opens or closes the two come and go together, so nothing is animated then.+ if (!glyph.window || SGRPlayerIsTransitioning()) glyph.enabled = enabled;+ else SGRAnimate(SGRMotionFade, ^{ glyph.enabled = enabled; }, nil);+}++static SGRGlyphButton *lyricsGlyphIn(UIView *host) {+ SGRGlyphButton *glyph = objc_getAssociatedObject(host, &kLyricsGlyphKey);+ if (!glyph) {+ glyph = [SGRGlyphButton buttonWithSymbol:@"quote.bubble" pointSize:kLyricsGlyphSize title:@"Lyrics"];+ glyph.glyph.tintColor = SGRSecondary();+ glyph.onTap = ^{ openLyrics(); };+ objc_setAssociatedObject(host, &kLyricsGlyphKey, glyph, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ }+ if (glyph.superview != host) [host addSubview:glyph];+ sg_lyricsGlyph = glyph;+ return glyph;+}++#pragma mark - the row++static UIView *connectGlyphIn(UIView *holder) {+ __block UIView *glyph = nil;+ SGForEachView(holder, ^(UIView *view) {+ if (!glyph && [view isKindOfClass:UIImageView.class] && view.bounds.size.width > 0 && view.bounds.size.width <= kGlyphMaxWidth) glyph = view;+ });+ return glyph;+}++%hook _TtC20NowPlaying_ModesImpl18FooterElementsUnit+- (void)viewDidLayoutSubviews {+ %orig;+ UIView *host = ((UIViewController *)self).viewIfLoaded;+ if (!host) return;+ // The unit lays out before its row does, and the moves are measured from where the row put things.+ [SGRowIn(host) layoutIfNeeded];+ CGFloat width = host.bounds.size.width, middleY = CGRectGetMidY(host.bounds);+ BOOL rtl = host.effectiveUserInterfaceLayoutDirection == UIUserInterfaceLayoutDirectionRightToLeft;++ UIView *share = SGRFindByIdentifier(host, @"ShareButtonNowPlayingView", &kShareKey);+ // The arranged view goes too: a view that takes touches swallows them even with nothing on it.+ SGRPlayerVanish(share);+ SGRPlayerVanish(arrangedAround(share, host));+ // Spotify's clip button, hidden in every clean tree, would turn up where the queue moves to.+ UIView *trimmer = SGRFindByIdentifier(host, @"nowplaying-npv-media-trimmer-navigation-button", &kTrimmerKey);+ SGRPlayerVanish(trimmer);+ SGRPlayerVanish(arrangedAround(trimmer, host));++ SGRGlyphButton *lyrics = lyricsGlyphIn(host);+ lyrics.bounds = CGRectMake(0, 0, 44, 44);+ lyrics.center = CGPointMake(round(width * (rtl ? kTrailing : kLeading)), middleY);+ SGRPlayerLyricsCardChanged();++ UIView *connect = SGRFindByIdentifier(host, @"Components.ConnectButtonOutputSwitcher", &kConnectKey);+ UIView *glyph = connectGlyphIn(connect);+ for (UIView *view = glyph.superview; view && view != connect; view = view.superview) {+ for (UIView *sibling in view.subviews) {+ if ([NSStringFromClass(sibling.class) containsString:@"MarqueeLabel"]) SGRPlayerVanish(sibling);+ }+ }+ UIView *pinned = glyph ?: connect;+ CGFloat connectFrom = moveTo(arrangedAround(connect, host), pinned, CGPointMake(CGRectGetMidX(pinned.bounds), CGRectGetMidY(pinned.bounds)), host, round(width * kMiddle));++ UIView *queue = SGRFindByIdentifier(host, @"QueueButtonNowPlaying", &kQueueKey);+ CGFloat queueFrom = moveTo(arrangedAround(queue, host), queue, CGPointMake(CGRectGetMidX(queue.bounds), CGRectGetMidY(queue.bounds)), host, round(width * (rtl ? kLeading : kTrailing)));++ static dispatch_once_t once;+ dispatch_once(&once, ^{+ SGLog(@"redesign player: footer lyrics at %.0f, connect %.0f (%@) to %.0f, queue %.0f to %.0f, share %@", lyrics.center.x,+ connectFrom, glyph ? @"glyph" : @"button", round(width * kMiddle), queueFrom, round(width * (rtl ? kLeading : kTrailing)), share ? @"gone" : @"not found");+ });+}+%end++%ctor {+ if (!SGRedesignOn(@"player")) return;+ %init;+ SGRequireClasses(@[@"_TtC20NowPlaying_ModesImpl18FooterElementsUnit"]);+}diff --git a/tweak/Sources/Redesign/Player/PlayerHeader.x b/tweak/Sources/Redesign/Player/PlayerHeader.xnew file mode 100644index 00000000..b5241982--- /dev/null+++ b/tweak/Sources/Redesign/Player/PlayerHeader.x@@ -0,0 +1,65 @@+// Player redesign: glass circles behind the header's close and more buttons.+//+// Glass is the control layer floating over the field, so it goes behind the round buttons only: the+// playlist name between them stays a label, and the row of playback controls stays bare glyphs+// (PlayerControls.x). Each circle is a subview of the button it sits behind (SGRGlassInside), below+// what the button draws and taking no touches, so the buttons stay Spotify's, with their actions, state+// and accessibility, and the circle follows the button wherever Spotify's row puts it. Circles placed+// from the unit's layout pass instead (a backing across the unit's view) were read before the row had+// laid the buttons out and sat 24pt up and to the side until a tap laid the unit out again+// (trees/continuous/1.txt, 2026-09-17: shapes at {-10, -22} and {320, -22}; the close button is at {12, 0}+// in the unit's view, so its circle belonged at {14, 2}).+//+// The add button keeps no circle: its glyph is a circle of its own, green and filled once the track is+// saved, and on glass it read as a disc on a disc (device test, 2026-09-17).+//+// Tree (trees/clean/player/01.txt): HeaderElementsUnit's view is a 402x48 row holding+// id=now-playing-minimize-button 48x48 (:103) and id=Context menu 48x48 (:122), the playlist name+// between them.+#import "Core/SGCore.h"+#import "Redesign/Kit/SGRKit.h"+#import "Player.h"++static char kGlassKey, kCloseKey, kMoreKey;++static void glassInside(UIViewController *unit, NSArray<NSString *> *identifiers, const void **findKeys) {+ UIView *host = unit.viewIfLoaded;+ if (!host) return;+ NSUInteger found = 0;+ for (NSUInteger i = 0; i < identifiers.count; i++) {+ UIView *button = SGRFindByIdentifier(host, identifiers[i], findKeys[i]);+ if (!button) {+ static NSMutableSet<NSString *> *missing;+ if (!missing) missing = [NSMutableSet set];+ if (![missing containsObject:identifiers[i]]) {+ [missing addObject:identifiers[i]];+ SGLog(@"redesign player: %@ not found in %@, left as Spotify's", identifiers[i], NSStringFromClass(host.class));+ }+ continue;+ }+ SGRGlassInside(button, &kGlassKey, SGRGlassCircleSize);+ found++;+ }++ static NSMutableSet<NSString *> *logged;+ if (!logged) logged = [NSMutableSet set];+ NSString *unitName = NSStringFromClass(unit.class);+ if (![logged containsObject:unitName]) {+ [logged addObject:unitName];+ SGLog(@"redesign player: glass inside %lu of %lu buttons in %@", (unsigned long)found, (unsigned long)identifiers.count, unitName);+ }+}++%hook _TtC20NowPlaying_ModesImpl18HeaderElementsUnit+- (void)viewDidLayoutSubviews {+ %orig;+ static const void *keys[] = {&kCloseKey, &kMoreKey};+ glassInside((UIViewController *)self, @[@"now-playing-minimize-button", @"Context menu"], keys);+}+%end++%ctor {+ if (!SGRedesignOn(@"player")) return;+ %init;+ SGRequireClasses(@[@"_TtC20NowPlaying_ModesImpl18HeaderElementsUnit"]);+}diff --git a/tweak/Sources/Settings/SGModPage.m b/tweak/Sources/Settings/SGModPage.mindex c4501c79..a038af05 100644--- a/tweak/Sources/Settings/SGModPage.m+++ b/tweak/Sources/Settings/SGModPage.m@@ -4,6 +4,7 @@#import "Features/Flags/Flags.h"#import "Features/About/About.h"#import "Features/AdBlock/AdBlock.h"+#import "Redesign/Kit/SGRedesign.h"NSString *const SGRestartNote = @"Changes apply after you restart Spotify.";@@ -223,11 +224,20 @@ static BOOL flagRowOn(SGModRow *row) {return value && [value boolValue] != row.forceOff;}-// A flag the Liquid Glass UI switch owns: its row shows what that switch forces and-// takes no touch, so the flag has one place to change. An override from All flags still wins.+// A flag the Liquid Glass UI switch or a redesigned screen owns: its row shows what that switch+// forces and takes no touch, so the flag has one place to change. An override from All flags still wins.static BOOL flagRowLocked(SGModRow *row) {if (!row.flag) return NO;- return (SGGlassOwnsFlag(row.key) && SGFlag(SGKeySpotifyGlass, NO)) || (row.forceOff && SGAdBlockForcesFlagOff(row.key));+ return (SGGlassOwnsFlag(row.key) && SGFlag(SGKeySpotifyGlass, NO)) || (row.forceOff && SGAdBlockForcesFlagOff(row.key))+ || SGRedesignOwnedFlag(row.key);+}++// What a locked row shows: the value its owner forces, read the row's way, so a Disable Canvas row+// reads on while a redesign forces Canvas off. Liquid Glass UI and the ad blocking only ever force a+// flag the way its row would.+static BOOL lockedRowOn(SGModRow *row) {+ id owned = SGRedesignOwnedFlag(row.key);+ return owned ? [owned boolValue] != row.forceOff : YES;}@implementation SGModPage {@@ -343,7 +353,7 @@ static BOOL flagRowLocked(SGModRow *row) {UISwitch *toggle = [UISwitch new];toggle.onTintColor = SGGreen();BOOL locked = flagRowLocked(row);- toggle.on = row.flag ? (locked && !SGFlagOverride(row.key) ? YES : flagRowOn(row)) : SGFlag(row.key, row.defaultOn);+ toggle.on = row.flag ? (locked && !SGFlagOverride(row.key) ? lockedRowOn(row) : flagRowOn(row)) : SGFlag(row.key, row.defaultOn);toggle.enabled = !locked;// A disabled switch would swallow the tap; letting it through is what gets the row asked.toggle.userInteractionEnabled = !locked;diff --git a/tweak/Sources/Settings/SGModSettings.x b/tweak/Sources/Settings/SGModSettings.xindex 9e08eea7..5c848f07 100644--- a/tweak/Sources/Settings/SGModSettings.x+++ b/tweak/Sources/Settings/SGModSettings.x@@ -1,5 +1,5 @@// Settings: a Mod Settings row at the end of Spotify's settings list opens the mod's own page: the-// Appearance card that styles the whole app, then a page per part of Spotify, each holding that+// Appearance card that styles the whole app, the Redesign row under it (Redesign/Kit), then a page per part of Spotify, each holding that// part's glass, hide switches and flags (Navbar, Player, Home & Library), Premium, ads & privacy// and Labs, All flags, a searchable list of every flag with an override per flag, and Mod, the// build, its updates and links. The same row leads the side drawer's list (trees/test6.txt), above@@ -22,6 +22,7 @@#import "Features/AdBlock/AdBlock.h"#import "Features/Flags/Flags.h"#import "Features/About/About.h"+#import "Redesign/Kit/SGRedesign.h"static const CGFloat kRowHeight = 56;static char kRowKey, kInsetKey;@@ -42,6 +43,7 @@ static UIViewController *modSettingsPage(void) {mod.value = ^NSString *{ return @(SG_VERSION); };[sections addObjectsFromArray:@[SGAppearanceSection(),+ SGRedesignSection(),SGSection(nil, @[pageRow(@"Navbar", @"dock.rectangle", ^UIViewController *{ return SGNavbarSettingsPage(); }),pageRow(@"Player", @"play.circle", ^UIViewController *{ return SGNowPlayingSettingsPage(); }),