Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.
C
feat: the artist's Follow is a glyph that turns into a checkmark, as add to library does (#88)
Vojtěch Škopekf10bf8d88e7d
diff --git a/harness/artist/build.sh b/harness/artist/build.shindex 84c3a3cc..ef18810f 100755--- a/harness/artist/build.sh+++ b/harness/artist/build.sh@@ -4,7 +4,7 @@ SRC=$(cd "$(dirname "$0")/../../tweak/Sources" && pwd)OUT=$(dirname "$0")/buildrm -rf "$OUT"; mkdir -p "$OUT/gen" "$OUT/ArtistHarness.app"-for f in Redesigned/Artist/ArtistField.x Redesigned/Artist/ArtistHeader.x Redesigned/Artist/ArtistSections.x; do+for f in Redesigned/Artist/ArtistField.x Redesigned/Artist/ArtistHeader.x Redesigned/Artist/ArtistSections.x Redesigned/Artist/ArtistFollow.x; doname=$(basename "$f" .x)"$THEOS/bin/logos.pl" -c generator=internal "$SRC/$f" > "$OUT/gen/$name.m"donediff --git a/harness/artist/main.m b/harness/artist/main.mindex 83917afe..a67c6e85 100644--- a/harness/artist/main.m+++ b/harness/artist/main.m@@ -4,8 +4,8 @@// the Follow button's word and then the photo back, one after the other, the way a page opened for the first// time gets them -- each has to reach the redesign on its own (issue #52), and the artwork view carries// Encore's Swift class name so that it can only be watched the way the phone makes the Kit watch it.-// `relabel` builds Follow as Encore's Swift button with an empty content view, and adds the label with the-// word in it a second later rather than filling one that was there.+// The follow state comes from a mock of Spotify's collection platform under its real class and selector+// names: `none` at once, or in `late` a second in; Following, as saved, after the tap made at 2.5 s.#import <UIKit/UIKit.h>#pragma mark - Spotify's classes, by name@@ -50,9 +50,73 @@@interface MockButton : UIControl @end@implementation MockButton @end-// Encore's text button (trees/lyrics.txt:615): a Swift class, so only its plain content view can be watched.-@interface _TtCCE16Encore_ButtonKitO16EncoreFoundation6Encore6Button9Secondary : UIControl @end-@implementation _TtCCE16Encore_ButtonKitO16EncoreFoundation6Encore6Button9Secondary @end+// The collection platform as 9.1.78 has it: SPTCollectionPlatformState is an option set (saved 1, banned 2,+// none 4), and the provider answers subscribeCollectionStateForURL:completion: with a token to cancel.+@interface SPTCollectionPlatformState : NSObject+@property (nonatomic, readonly) NSInteger rawValue;+@end+@implementation SPTCollectionPlatformState+- (instancetype)initWithRawValue:(NSInteger)raw {+ if ((self = [super init])) _rawValue = raw;+ return self;+}++ (instancetype)saved { return [[self alloc] initWithRawValue:1]; }++ (instancetype)banned { return [[self alloc] initWithRawValue:2]; }++ (instancetype)none { return [[self alloc] initWithRawValue:4]; }+- (BOOL)contains:(SPTCollectionPlatformState *)other { return (_rawValue & other.rawValue) == other.rawValue; }+@end++@interface MockRequestToken : NSObject+@property (nonatomic, copy) void (^onCancel)(void);+@end+@implementation MockRequestToken+- (void)cancel {+ NSLog(@"[harness] collection subscription cancelled");+ if (self.onCancel) self.onCancel();+}+@end++@interface _TtC23Collection_PlatformImpl35CollectionPlatformStateProviderImpl : NSObject+@property (nonatomic) NSInteger raw;+@property (nonatomic, strong) NSMutableArray *subscribers;+- (void)push:(NSInteger)raw;+@end+@implementation _TtC23Collection_PlatformImpl35CollectionPlatformStateProviderImpl+- (id)subscribeCollectionStateForURL:(NSURL *)url completion:(void (^)(SPTCollectionPlatformState *, NSError *))completion {+ if (!self.subscribers) self.subscribers = [NSMutableArray array];+ void (^copied)(SPTCollectionPlatformState *, NSError *) = [completion copy];+ [self.subscribers addObject:copied];+ NSLog(@"[harness] subscribed for %@", url);+ if (self.raw) completion([[SPTCollectionPlatformState alloc] initWithRawValue:self.raw], nil);+ MockRequestToken *token = [MockRequestToken new];+ __weak typeof(self) weakSelf = self;+ token.onCancel = ^{ [weakSelf.subscribers removeObject:copied]; };+ return token;+}+// As the collection does it: off the main thread.+- (void)push:(NSInteger)raw {+ self.raw = raw;+ for (void (^completion)(SPTCollectionPlatformState *, NSError *) in [self.subscribers copy]) {+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{+ completion([[SPTCollectionPlatformState alloc] initWithRawValue:raw], nil);+ });+ }+}+@end+typedef _TtC23Collection_PlatformImpl35CollectionPlatformStateProviderImpl MockStateProvider;++@interface SPTCollectionPlatformImplementation : NSObject+@property (nonatomic, strong) MockStateProvider *stateProvider;+@end+@implementation SPTCollectionPlatformImplementation @end++static SPTCollectionPlatformImplementation *sgh_platform;++// The page's controller, which Spotify's answer spt_pageURI with the artist's URI.+@interface MockArtistPageController : UIViewController @end+@implementation MockArtistPageController+- (NSURL *)spt_pageURI { return [NSURL URLWithString:@"spotify:artist:7n2wHs1TKAczGzO7Dd2rGr"]; }+@end// Encore's image view, the one every picture Spotify loads arrives in (01.txt:48). Its name is the point of// the mock: a Swift one, which the Kit refuses to give an instance its own subclass of, so the harness@@ -193,9 +257,13 @@ static NSArray<NSArray *> *musicList(void) {CGFloat W = self.window.bounds.size.width, H = self.window.bounds.size.height;BOOL collapsed = [NSProcessInfo.processInfo.arguments containsObject:@"collapsed"];BOOL late = [NSProcessInfo.processInfo.arguments containsObject:@"late"];- BOOL relabel = [NSProcessInfo.processInfo.arguments containsObject:@"relabel"];+ sgh_platform = [SPTCollectionPlatformImplementation new];+ sgh_platform.stateProvider = [MockStateProvider new];+ if (!late) sgh_platform.stateProvider.raw = 4;+ // Some part of Spotify reaches for the provider before the page does.+ (void)sgh_platform.stateProvider;- UIViewController *root = [UIViewController new];+ UIViewController *root = [MockArtistPageController new];root.view.backgroundColor = [UIColor colorWithRed:0.07 green:0.07 blue:0.07 alpha:1];self.window.rootViewController = root;@@ -229,15 +297,13 @@ static NSArray<NSArray *> *musicList(void) {@"Components.Header.UI.Metadata");UIView *row = box(header, UIStackView.class, CGRectMake(4, 456, 394, 48), nil);- Class followClass = relabel ? _TtCCE16Encore_ButtonKitO16EncoreFoundation6Encore6Button9Secondary.class : MockButton.class;- UIView *follow = box(row, followClass, CGRectMake(70, 8, 66, 32), @"Curation.FollowButtonElementKit.FollowButton");+ UIView *follow = box(row, MockButton.class, CGRectMake(70, 8, 66, 32), @"Curation.FollowButtonElementKit.FollowButton");follow.accessibilityLabel = @"Follow";follow.layer.borderColor = UIColor.grayColor.CGColor;follow.layer.borderWidth = 1;follow.layer.cornerRadius = 16;- UIView *followContent = relabel ? box(follow, UIView.class, follow.bounds, nil) : nil;- UILabel *followWord = relabel ? nil : label(follow, CGRectMake(16, 8, 40, 16), late ? @"" : @"Follow", 11, UIColor.whiteColor, @"Encore.Label");- if (late || relabel) follow.accessibilityLabel = nil;+ UILabel *followWord = label(follow, CGRectMake(16, 8, 40, 16), late ? @"" : @"Follow", 11, UIColor.whiteColor, @"Encore.Label");+ if (late) follow.accessibilityLabel = nil;[(UIControl *)follow addTarget:self action:@selector(toggleFollow:) forControlEvents:UIControlEventTouchUpInside];glyph(box(row, MockButton.class, CGRectMake(148, 0, 48, 48), @"Components.UI.ContextMenuButton-7n2wHs1TKAczGzO7Dd2rGr"), @"ellipsis", 12);glyph(box(row, MockButton.class, CGRectMake(278, 0, 48, 48), @"Components.UI.ShuffleButton"), @"shuffle", 12);@@ -290,15 +356,8 @@ static NSArray<NSArray *> *musicList(void) {[self.window makeKeyAndVisible];- if (relabel) {- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{- label(followContent, CGRectMake(16, 8, 40, 16), @"Follow", 11, UIColor.whiteColor, @"Encore.Label");- follow.accessibilityLabel = @"Follow";- NSLog(@"[harness] relabel: a new label with \"Follow\" is in Spotify's button now");- });- }- // What the redesign's Follow draws: nothing before the word, the word after it.- // A tap on it at 2.5 s, which Spotify answers with Following.+ // What the redesign's Follow draws: nothing before the state, then the glyph for it. A tap on it at+ // 2.5 s, which Spotify answers with Following.for (NSNumber *when in @[@0.5, @1.5, @2.5, @3.0]) {dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(when.doubleValue * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{NSMutableArray *lines = [NSMutableArray array];@@ -315,11 +374,15 @@ static NSArray<NSArray *> *musicList(void) {if (sub.hidden || sub.alpha < 0.01) continue;NSString *what = NSStringFromClass(sub.class);if ([sub isKindOfClass:UILabel.class]) what = [NSString stringWithFormat:@"\"%@\"", ((UILabel *)sub).text];- else if ([sub isKindOfClass:UIImageView.class]) what = ((UIImageView *)sub).image ? @"glyph" : @"empty image view";+ else if ([sub isKindOfClass:UIImageView.class]) {+ NSString *symbol = [((UIImageView *)sub).image.description componentsSeparatedByString:@"symbol(system: "].lastObject;+ what = [NSString stringWithFormat:@"%@ in %@", [symbol componentsSeparatedByString:@")"].firstObject,+ ((UIImageView *)sub).tintColor];+ }[drawn addObject:what];}- [lines addObject:[NSString stringWithFormat:@"%@ touches %d draws %@", NSStringFromCGRect(v.frame),- v.userInteractionEnabled, [drawn componentsJoinedByString:@", "]]];+ [lines addObject:[NSString stringWithFormat:@"%@ touches %d a11y \"%@\" draws %@", NSStringFromCGRect(v.frame),+ v.userInteractionEnabled, v.accessibilityLabel, [drawn componentsJoinedByString:@", "]]];}NSLog(@"[harness] follow at %.1fs: %@", when.doubleValue, [lines componentsJoinedByString:@" | "]);if (when.doubleValue == 2.5) [tapped sendActionsForControlEvents:UIControlEventTouchUpInside];@@ -331,7 +394,8 @@ static NSArray<NSArray *> *musicList(void) {dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{followWord.text = @"Follow";follow.accessibilityLabel = @"Follow";- NSLog(@"[harness] late: \"Follow\" is in Spotify's header now");+ [sgh_platform.stateProvider push:4];+ NSLog(@"[harness] late: the follow state is in Spotify's collection now");});dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{picture.image = photo();@@ -379,6 +443,8 @@ static NSArray<NSArray *> *musicList(void) {[queue addObjectsFromArray:v.subviews];}word.text = [word.text isEqualToString:@"Follow"] ? @"Following" : @"Follow";+ follow.accessibilityLabel = word.text;+ [sgh_platform.stateProvider push:[word.text isEqualToString:@"Following"] ? 1 : 4];NSLog(@"[harness] Spotify's Follow fired, now \"%@\"", word.text);}diff --git a/tweak/Sources/Redesigned/Artist/Artist.h b/tweak/Sources/Redesigned/Artist/Artist.hindex 6501ce25..7fa384c1 100644--- a/tweak/Sources/Redesigned/Artist/Artist.h+++ b/tweak/Sources/Redesigned/Artist/Artist.h@@ -11,6 +11,7 @@// ArtistHeader.x the header: the photo full bleed dissolving into the field, and the Kit's// SGRHeaderInfo over it -- the name, the listeners, shuffle, a white Play and Follow// ArtistSections.x the sections the Music list carries that are not the artist's music: its videos+// ArtistFollow.x whether the artist is followed, from Spotify's collection, for Follow's glyph//// Every hook installs only while Redesigned UI is on (SGRedesignedUI); the native look's do not then.// Threading: main thread only.@@ -25,3 +26,8 @@ UIView *SGRArtistPageOf(UIView *view);UIColor *SGRArtistFieldColor(UIView *view);// The artist's photo, for the page's field to take its colour from. The same image again is a no-op.void SGRArtistSetArtwork(UIView *view, UIImage *image);++// ArtistFollow.x. YES once Spotify's collection has said whether the user follows the page's artist, with+// the answer; NO until then. The first call subscribes for the page's lifetime, and `changed` runs on the+// main thread whenever the answer changes.+BOOL SGRArtistFollowing(UIView *page, NSString *moreIdentifier, BOOL *following, void (^changed)(void));diff --git a/tweak/Sources/Redesigned/Artist/ArtistFollow.x b/tweak/Sources/Redesigned/Artist/ArtistFollow.xnew file mode 100644index 00000000..bf614554--- /dev/null+++ b/tweak/Sources/Redesigned/Artist/ArtistFollow.x@@ -0,0 +1,222 @@+// Whether the user follows the page's artist, read from Spotify's collection state (following saves the+// artist to the collection) rather than the Follow button, whose only state is its localized title.+// The provider is the one Spotify's own code uses, kept weakly.+#import "Core/SGCore.h"+#import "Artist.h"++@protocol SGRCollectionState <NSObject>++ (id)saved;+- (BOOL)contains:(id)state;+- (NSInteger)rawValue;+@end++@protocol SGRCollectionStateProvider <NSObject>+- (id)subscribeCollectionStateForURL:(NSURL *)url completion:(void (^)(id state, NSError *error))completion;+@end++static __weak id sg_provider;++// Called from wherever Spotify reaches for its provider, any thread.+static void keepProvider(id provider) {+ if (!provider || ![provider respondsToSelector:@selector(subscribeCollectionStateForURL:completion:)]) return;+ static NSMutableSet<NSString *> *logged;+ @synchronized (NSObject.class) {+ if (provider == sg_provider) return;+ sg_provider = provider;+ if (!logged) logged = [NSMutableSet set];+ NSString *name = NSStringFromClass([provider class]);+ if ([logged containsObject:name]) return;+ [logged addObject:name];+ }+ SGLog(@"redesign artist: collection state from %@", NSStringFromClass([provider class]));+}++static __weak id sg_platform;++static id currentProvider(void) {+ id provider;+ @synchronized (NSObject.class) {+ provider = sg_provider;+ }+ if (!provider && [sg_platform respondsToSelector:@selector(stateProvider)]) {+ provider = [sg_platform performSelector:@selector(stateProvider)];+ keepProvider(provider);+ }+ return provider;+}++%hook SPTCollectionPlatformImplementation+- (id)initWithCosmosDataLoader:(id)loader isGatedEntityRelationsEnabled:(BOOL)gated {+ id platform = %orig;+ sg_platform = platform;+ return platform;+}+- (id)stateProvider {+ id provider = %orig;+ keepProvider(provider);+ return provider;+}+%end++%hook _TtC23Collection_PlatformImpl22CollectionPlatformImpl+- (id)stateProvider {+ id provider = %orig;+ keepProvider(provider);+ return provider;+}+%end++%hook _TtC23Collection_PlatformImpl27CollectionPlatformMigration+- (id)stateProvider {+ id provider = %orig;+ keepProvider(provider);+ return provider;+}+%end++%hook _TtC26AlignedCuration_CommonImpl21ACUCollectionPlatform+- (id)stateProvider {+ id provider = %orig;+ keepProvider(provider);+ return provider;+}+%end++%hook _TtC23Collection_PlatformImpl35CollectionPlatformStateProviderImpl+- (id)subscribeCollectionStateForURL:(id)url completion:(id)completion {+ keepProvider(self);+ return %orig;+}+- (id)subscribeCollectionStateForURLs:(id)urls completion:(id)completion {+ keepProvider(self);+ return %orig;+}+- (id)subscribeCollectionStateForURL:(id)url inContextURL:(id)context completion:(id)completion {+ keepProvider(self);+ return %orig;+}+- (id)subscribeCollectionStateForURLs:(id)urls inContextURL:(id)context completion:(id)completion {+ keepProvider(self);+ return %orig;+}+%end++%hook _TtC26AlignedCuration_CommonImpl25ACUEsperantoStateProvider+- (id)subscribeCollectionStateForURL:(id)url completion:(id)completion {+ keepProvider(self);+ return %orig;+}+- (id)subscribeCollectionStateForURLs:(id)urls completion:(id)completion {+ keepProvider(self);+ return %orig;+}+- (id)subscribeCollectionStateForURL:(id)url inContextURL:(id)context completion:(id)completion {+ keepProvider(self);+ return %orig;+}+- (id)subscribeCollectionStateForURLs:(id)urls inContextURL:(id)context completion:(id)completion {+ keepProvider(self);+ return %orig;+}+%end++// The Follow element asks Curation's provider, which wraps the collection one.+%hook _TtC21Curation_PlatformImpl30CUPStateProviderImplementation+- (id)subscribeCollectionStateForURL:(id)url inContext:(id)context completion:(id)completion {+ Ivar ivar = class_getInstanceVariable(object_getClass(self), "collectionPlatformStateProvider");+ if (ivar) keepProvider(object_getIvar(self, ivar));+ return %orig;+}+%end++#pragma mark - one subscription per page++// Held by the page, so the subscription ends with it.+@interface SGRFollowWatch : NSObject+@property (nonatomic, copy) NSURL *uri;+@property (nonatomic, strong) id token;+@property (nonatomic) BOOL subscribed;+@property (nonatomic) NSInteger following; // -1 until the first state arrives+@property (nonatomic, copy) void (^changed)(void);+@end++@implementation SGRFollowWatch+- (void)dealloc {+ if ([_token respondsToSelector:@selector(cancel)]) [_token cancel];+}+@end++static char kWatchKey;++// The artist the page is for. The artist page's controllers carry no URI, but the header's ⋯ does:+// Components.UI.ContextMenuButton-<artist id>.+static NSURL *artistURI(UIView *page, NSString *moreIdentifier) {+ for (UIResponder *responder = page; responder; responder = responder.nextResponder) {+ if (![responder isKindOfClass:UIViewController.class] || ![responder respondsToSelector:@selector(spt_pageURI)]) continue;+ id uri = [(id)responder performSelector:@selector(spt_pageURI)];+ if ([uri isKindOfClass:NSURL.class] && [[uri absoluteString] hasPrefix:@"spotify:artist:"]) return uri;+ }+ NSString *prefix = @"Components.UI.ContextMenuButton-";+ if (![moreIdentifier hasPrefix:prefix]) return nil;+ NSString *identifier = [moreIdentifier substringFromIndex:prefix.length];+ NSCharacterSet *base62 = [NSCharacterSet alphanumericCharacterSet].invertedSet;+ if (identifier.length != 22 || [identifier rangeOfCharacterFromSet:base62].location != NSNotFound) return nil;+ return [NSURL URLWithString:[@"spotify:artist:" stringByAppendingString:identifier]];+}++static void subscribe(SGRFollowWatch *watch, id provider) {+ Class stateClass = NSClassFromString(@"SPTCollectionPlatformState");+ if (![stateClass respondsToSelector:@selector(saved)]) return;+ id saved = [(Class<SGRCollectionState>)stateClass saved];+ __weak SGRFollowWatch *weakWatch = watch;+ NSURL *uri = watch.uri;+ watch.subscribed = YES;+ SGLog(@"redesign artist: follow subscribes for %@ on %@", uri.absoluteString, NSStringFromClass([provider class]));+ watch.token = [(id<SGRCollectionStateProvider>)provider subscribeCollectionStateForURL:uri completion:^(id state, NSError *error) {+ if (error || ![state respondsToSelector:@selector(contains:)]) {+ SGLog(@"redesign artist: follow state for %@ unreadable: %@ %@", uri.absoluteString, [state class], error);+ return;+ }+ NSInteger raw = [state respondsToSelector:@selector(rawValue)] ? [(id<SGRCollectionState>)state rawValue] : -1;+ BOOL following = [(id<SGRCollectionState>)state contains:saved];+ dispatch_async(dispatch_get_main_queue(), ^{+ SGRFollowWatch *current = weakWatch;+ if (!current || current.following == following) return;+ SGLog(@"redesign kit: follow state %ld for %@", (long)raw, uri.absoluteString);+ current.following = following;+ if (current.changed) current.changed();+ });+ }];+}++BOOL SGRArtistFollowing(UIView *page, NSString *moreIdentifier, BOOL *following, void (^changed)(void)) {+ if (!page) return NO;+ SGRFollowWatch *watch = objc_getAssociatedObject(page, &kWatchKey);+ if (!watch) {+ NSURL *uri = artistURI(page, moreIdentifier);+ if (!uri) {+ static __weak UIView *loggedPage;+ if (loggedPage != page) {+ loggedPage = page;+ SGLog(@"redesign artist: follow has no artist URI, more is %@", moreIdentifier);+ }+ return NO;+ }+ watch = [SGRFollowWatch new];+ watch.uri = uri;+ watch.following = -1;+ objc_setAssociatedObject(page, &kWatchKey, watch, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ }+ watch.changed = changed;+ id provider = watch.subscribed ? nil : currentProvider();+ if (provider) subscribe(watch, provider);+ if (watch.following < 0) return NO;+ if (following) *following = watch.following == 1;+ return YES;+}++%ctor {+ if (!SGRedesignedUI()) return;+ %init;+ SGRequireClasses(@[@"SPTCollectionPlatformState", @"_TtC23Collection_PlatformImpl35CollectionPlatformStateProviderImpl"]);+}diff --git a/tweak/Sources/Redesigned/Artist/ArtistHeader.x b/tweak/Sources/Redesigned/Artist/ArtistHeader.xindex 12b266f5..4a3389e2 100644--- a/tweak/Sources/Redesigned/Artist/ArtistHeader.x+++ b/tweak/Sources/Redesigned/Artist/ArtistHeader.x@@ -24,8 +24,7 @@// Everything else of the ImageHeaderView is drawn by nothing (an empty mask) and takes no touches: the badge,// Explore, and the headline go with it -- the headline's pre-save is also the list's own Release Countdown// section. The Kit's SGRHeaderInfo reads the name and the listeners off Spotify's concealed labels and draws-// and fires Spotify's shuffle, play and Follow, whose word ("Follow", "Following") is its state in the app's-// language. More stays in Spotify's row, where the row needs it (ArtistField.x), and the Kit's pinned ⋯+// and fires Spotify's shuffle, play and Follow, Follow as a glyph from the collection (ArtistFollow.x). More stays in Spotify's row, where the row needs it (ArtistField.x), and the Kit's pinned ⋯// (SGRPinnedMore) draws and fires it from the top trailing corner of the page, level with the back button.#import "Core/SGCore.h"#import "Redesigned/Kit/SGRKit.h"@@ -256,7 +255,16 @@ static void applyHeader(UIView *header) {SGRHeaderInfo *info = objc_getAssociatedObject(container, &kInfoKey);if (!info) {info = [[SGRHeaderInfo alloc] initWithFrame:CGRectZero];- info.trailingShowsWord = YES;+ // Follow's only state is its title in the app's language, so the glyph takes it from the collection.+ __weak UIView *weakPage = SGRArtistPageOf(container);+ __weak SGRHeaderInfo *weakInfo = info;+ __weak UIView *weakHeader = header;+ info.trailingState = ^BOOL(BOOL *on) {+ UIView *more = SGRFindByIdentifier(weakHeader, @"Components.UI.ContextMenuButton*", &kMoreKey);+ return SGRArtistFollowing(weakPage, more.accessibilityIdentifier, on, ^{ [weakInfo trailingStateChanged]; });+ };+ info.trailingOffSymbol = @"person.badge.plus";+ info.trailingOnSymbol = @"person.fill.checkmark";objc_setAssociatedObject(container, &kInfoKey, info, OBJC_ASSOCIATION_RETAIN_NONATOMIC);}if (info.superview != container) [container addSubview:info];@@ -270,7 +278,6 @@ static void applyHeader(UIView *header) {UIView *shuffle = SGRFindByIdentifier(header, @"Components.UI.ShuffleButton", &kShuffleKey);UIView *play = SGRFindByIdentifier(header, @"header-play-button", &kPlayKey);UIView *follow = SGRFindByIdentifier(header, @"Curation.FollowButtonElementKit.FollowButton", &kFollowKey);- NSString *word = firstText(follow);[info showShuffle:shuffle play:play trailing:follow trailingFallback:nil playColor:SGRArtistFieldColor(container)];// More, in the top trailing corner of the page itself rather than of the container, which scrolls away@@ -309,7 +316,7 @@ static void applyHeader(UIView *header) {logged = YES;SGLog(@"redesign artist: own block \"%@\", \"%@\"; shuffle %@, play %@, follow %@, more %@", name,firstText(listeners) ?: @"no listeners", shuffle ? @"found" : @"missing", play ? @"found" : @"missing",- follow ? word ?: @"found, no word yet" : @"missing", more ? @"found" : @"missing");+ follow ? @"found" : @"missing", more ? @"found" : @"missing");}}diff --git a/tweak/Sources/Redesigned/Kit/SGRActionRow.h b/tweak/Sources/Redesigned/Kit/SGRActionRow.hindex 39a5c12c..12a251c9 100644--- a/tweak/Sources/Redesigned/Kit/SGRActionRow.h+++ b/tweak/Sources/Redesigned/Kit/SGRActionRow.h@@ -44,13 +44,13 @@// view, hidden while off). Spotify's own off grey read as a disabled button beside the white download// (issue #65). A button with no such dot keeps Spotify's colours. nil, the default, reads no dot.@property (nonatomic, copy) UIColor *onGlyphColor;-// The word on Spotify's button instead of a glyph, in a glass capsule as wide as the word asks for: for a-// text button such as the artist's Follow, whose word is its state ("Follow", "Following") in the app's-// language. Until Spotify's button has a word the button draws nothing and takes no touches. Set before the-// first -feedFrom:.-@property (nonatomic) BOOL showsWord;-// The width the button wants: SGRActionHeight for a glyph, the word and its padding for a word.-- (CGFloat)sgr_width;+// For a button that shows its state only as a word in the app's language (the artist's Follow): YES with+// whether it is on once the state is known, from wherever the page reads it. The button then draws+// stateOffSymbol, or stateOnSymbol in the accent colour, and nothing while it answers NO. Set before the+// first -feedFrom:; call -feedFrom: again when the state changes.+@property (nonatomic, copy) BOOL (^readState)(BOOL *on);+@property (nonatomic, copy) NSString *stateOffSymbol;+@property (nonatomic, copy) NSString *stateOnSymbol;// Takes the glyph, its colour and the label from `source`, and follows the glyph as Spotify swaps it// (shuffle turning on). Cheap to call again on every pass.//diff --git a/tweak/Sources/Redesigned/Kit/SGRActionRow.m b/tweak/Sources/Redesigned/Kit/SGRActionRow.mindex fadbea61..7c1e3aa0 100644--- a/tweak/Sources/Redesigned/Kit/SGRActionRow.m+++ b/tweak/Sources/Redesigned/Kit/SGRActionRow.m@@ -18,10 +18,7 @@ static const CGFloat kGlyphSide = 44, kCapsuleLead = 4, kCapsuleTrail = 20;// The mirrored glyph, the size Spotify draws one inside a 48pt round button.static const CGFloat kMirrorGlyph = 24;-static char kCapsuleGlassKey, kMirrorGlassKey, kWordGlassKey;--// A word button's padding either side of the word.-static const CGFloat kWordPadding = 18;+static char kCapsuleGlassKey, kMirrorGlassKey;// The glyph Spotify's button draws: an image view of the button's own size that nothing hidden is in the// way of. `side` is the size to match, 0 for any image view that is showing.@@ -159,15 +156,6 @@ static NSString *wordIn(UIView *button) {#pragma mark - a button standing in for Spotify's-// The label a button shows its word in, whether it has a word in it yet or not.-static UILabel *labelIn(UIView *button) {- __block UILabel *found = nil;- SGForEachView(button, ^(UIView *v) {- if (!found && [v isKindOfClass:UILabel.class]) found = (UILabel *)v;- });- return found;-}-// Whether a button that marks "on" with a small dot under its glyph (Encore's shuffle, a 4pt round view it// hides while off) is on. `found` says whether the button has such a dot at all.static BOOL indicatorOn(UIView *button, BOOL *found) {@@ -186,22 +174,8 @@ static BOOL indicatorOn(UIView *button, BOOL *found) {return dot != nil;}-// The text a button shows: the first label under it with something in it.-static NSString *labelTextIn(UIView *button) {- __block NSString *text = nil;- SGForEachView(button, ^(UIView *v) {- if (text || ![v isKindOfClass:UILabel.class]) return;- NSString *candidate = [((UILabel *)v).text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];- if (candidate.length) text = candidate;- });- return text;-}-@implementation SGRMirrorButton {UIImageView *_glyph;- UILabel *_word;- __weak UILabel *_watchedWord;- __weak UIView *_watchedContent;__weak UIImageView *_watchedGlyph;// Spotify's own image, as it was taken: what the copy is compared against, since a copy re-rendered as// a template is no longer the same object.@@ -209,8 +183,8 @@ static NSString *labelTextIn(UIView *button) {// Standing in for Spotify's download button: its state drawn, and read again while on screen.SGRDownloadGlyph *_download;NSTimer *_downloadTimer;- // Standing in for Spotify's add-to button: 1 saved, 0 not, -1 not one.- NSInteger _addedShown;+ // A two-state glyph drawn for Spotify (add-to, readState): 1 on, 0 off, -1 none drawn.+ NSInteger _stateShown;}- (instancetype)initWithFrame:(CGRect)frame {@@ -219,7 +193,7 @@ static NSString *labelTextIn(UIView *button) {_glyph.contentMode = UIViewContentModeScaleAspectFit;_glyph.userInteractionEnabled = NO;[self addSubview:_glyph];- _addedShown = -1;+ _stateShown = -1;self.isAccessibilityElement = YES;self.accessibilityTraits = UIAccessibilityTraitButton;@@ -229,36 +203,15 @@ static NSString *labelTextIn(UIView *button) {return self;}-- (CGFloat)sgr_width {- if (!self.showsWord || !_word.text.length) return SGRActionHeight;- [_word sizeToFit];- return MAX(SGRActionHeight, ceil(_word.bounds.size.width) + 2 * kWordPadding);-}-- (void)layoutSubviews {[super layoutSubviews];CGRect bounds = self.bounds;- // A word button draws nothing until its word is there, then the capsule: a glyph in its place first- // read as a different button. Only one shape is asked for on a pass, so the other is put away.- if (self.showsWord && !_word.text.length) {- ((UIView *)objc_getAssociatedObject(self, &kWordGlassKey)).hidden = YES;+ // Until its state is known the button draws nothing: a guess would flash the wrong glyph first.+ if (self.readState && _stateShown < 0) {((UIView *)objc_getAssociatedObject(self, &kMirrorGlassKey)).hidden = YES;return;}- if (self.showsWord) {- SGRGlassCapsuleInside(self, &kWordGlassKey, bounds.size, NO);- ((UIView *)objc_getAssociatedObject(self, &kMirrorGlassKey)).hidden = YES;- [_word sizeToFit];- CGSize text = _word.bounds.size;- // Given less width than the word asked for -- what is left of the row beside a wide Play -- the- // capsule spends its own padding on the word before it lets the word be cut ("Following").- CGFloat padding = MIN(kWordPadding, MAX(0, floor((bounds.size.width - text.width) / 2)));- _word.frame = CGRectMake(padding, round((bounds.size.height - text.height) / 2),- MAX(0, bounds.size.width - 2 * padding), text.height);- return;- }SGRGlassInside(self, &kMirrorGlassKey, SGRGlassCircleSize);- ((UIView *)objc_getAssociatedObject(self, &kWordGlassKey)).hidden = YES;_glyph.frame = CGRectMake(round((bounds.size.width - kMirrorGlyph) / 2), round((bounds.size.height - kMirrorGlyph) / 2),kMirrorGlyph, kMirrorGlyph);_download.frame = _glyph.frame;@@ -266,7 +219,7 @@ static NSString *labelTextIn(UIView *button) {- (void)didMoveToWindow {[super didMoveToWindow];- if (!_download && _addedShown < 0) return;+ if (!_download && _stateShown < 0 && !self.readState) return;// Read again on the way in -- the state may have moved on while the page was away -- and not at all// while out of the window.if (self.window && self.source) [self feedFrom:self.source];@@ -311,31 +264,39 @@ static NSString *labelTextIn(UIView *button) {return YES;}-// Shows whether Spotify's add-to button has its album or playlist saved; YES when `source` is one.-- (BOOL)sgr_feedAddToFrom:(UIView *)source {- BOOL added;- if (!SGRReadAddTo(source, &added)) {- _addedShown = -1;- return NO;- }- if (_addedShown != added) {- UIImage *image = [UIImage systemImageNamed:added ? @"checkmark" : @"plus"];- BOOL animated = _addedShown >= 0 && self.window && !SGRReduceMotion();- _addedShown = added;+// Draws `offSymbol`, or `onSymbol` in the accent colour, switching between them in place.+- (void)sgr_showOn:(BOOL)on off:(NSString *)offSymbol on:(NSString *)onSymbol source:(UIView *)source {+ if (_stateShown != on) {+ UIImage *image = [UIImage systemImageNamed:on ? onSymbol : offSymbol];+ BOOL animated = _stateShown >= 0 && self.window && !SGRReduceMotion();+ BOOL first = _stateShown < 0;+ _stateShown = on;_takenGlyph = nil;+ _glyph.hidden = NO;if (@available(iOS 17.0, *)) {if (animated) [_glyph setSymbolImage:image withContentTransition:[NSSymbolReplaceContentTransition replaceDownUpTransition]];else _glyph.image = image;} else {_glyph.image = image;}- // Saved is "on", in the accent colour, as downloaded is.- _glyph.tintColor = added ? SGRAccent() : SGRPrimary();+ // On is saved or followed, in the accent colour, as downloaded is.+ _glyph.tintColor = on ? SGRAccent() : SGRPrimary();+ if (first) [self setNeedsLayout];}NSString *word = source.accessibilityLabel ?: wordIn(source);if (word && ![self.accessibilityLabel isEqualToString:word]) self.accessibilityLabel = word;- // Nothing is laid out when it is saved from elsewhere (the ⋯ sheet), so it is read again as download is.+ // Nothing is laid out when it changes from elsewhere (the ⋯ sheet), so it is read again as download is.[self sgr_followDownload:self.window ? 2 : 0];+}++// Shows whether Spotify's add-to button has its album or playlist saved; YES when `source` is one.+- (BOOL)sgr_feedAddToFrom:(UIView *)source {+ BOOL added;+ if (!SGRReadAddTo(source, &added)) {+ _stateShown = -1;+ return NO;+ }+ [self sgr_showOn:added off:@"plus" on:@"checkmark" source:source];return YES;}@@ -366,49 +327,15 @@ static NSString *labelTextIn(UIView *button) {if (!source) return;_source = source;- if (self.showsWord) {- if (!_word) {- _word = [UILabel new];- _word.userInteractionEnabled = NO;- _word.textAlignment = NSTextAlignmentCenter;- _word.font = SGRFont(UIFontTextStyleSubheadline, UIFontWeightSemibold, UIContentSizeCategoryExtraLarge);- _word.textColor = SGRPrimary();- [self addSubview:_word];- }- NSString *text = labelTextIn(source);- if (text && ![_word.text isEqualToString:text]) {- _word.text = text;- self.accessibilityLabel = source.accessibilityLabel ?: text;- [self setNeedsLayout];- [self.superview setNeedsLayout];- }- // Spotify's word is its state, which it fills in a moment after the button itself is there and- // changes without laying out anything the page hears (the artist's Follow, issue #52). So the label- // it puts the word in is watched, and the button hears it land.- __weak SGRMirrorButton *weakSelf = self;- __weak UIView *weakSource = source;- UILabel *source_word = labelIn(source);- if (source_word && source_word != _watchedWord) {- _watchedWord = source_word;- SGRObserveText(source_word, ^(UILabel *label) {- if (weakSelf && weakSource) [weakSelf feedFrom:weakSource];- });- }- // A label added or swapped in later has no watch on it; the view it lands in lays out then. Encore's- // button is a Swift class, so its plain content view is watched when the button itself cannot be.- if (source != _watchedContent && source.subviews.firstObject != _watchedContent) {- void (^laidOut)(UIView *) = ^(UIView *view) {- if (weakSelf && weakSource) [weakSelf feedFrom:weakSource];- };- if (SGRObserveLayout(source, laidOut)) _watchedContent = source;- else if (SGRObserveLayout(source.subviews.firstObject, laidOut)) _watchedContent = source.subviews.firstObject;- }- BOOL hasWord = _word.text.length > 0;- if (!_glyph.hidden) _glyph.hidden = YES;- if (self.userInteractionEnabled != hasWord) {- self.userInteractionEnabled = hasWord;- self.isAccessibilityElement = hasWord;- [self setNeedsLayout];+ if (self.readState) {+ BOOL on = NO;+ if (self.readState(&on)) [self sgr_showOn:on off:self.stateOffSymbol on:self.stateOnSymbol source:source];+ else [self sgr_followDownload:self.window ? 2 : 0];+ BOOL known = _stateShown >= 0;+ if (_glyph.hidden == known) _glyph.hidden = !known;+ if (self.userInteractionEnabled != known) {+ self.userInteractionEnabled = known;+ self.isAccessibilityElement = known;}return;}diff --git a/tweak/Sources/Redesigned/Kit/SGRHeaderInfo.h b/tweak/Sources/Redesigned/Kit/SGRHeaderInfo.hindex e1311ae8..09ddcf57 100644--- a/tweak/Sources/Redesigned/Kit/SGRHeaderInfo.h+++ b/tweak/Sources/Redesigned/Kit/SGRHeaderInfo.h@@ -27,8 +27,12 @@ extern const CGFloat SGRHeaderInfoTitleRise; // 56, of the content over the pic// The line keeps its colour: it is the page's one piece of secondary text, not a link to be tinted. nil// leaves it as text.- (void)showCreatorLink:(UIView *)control;-// Spotify's own trailing control is a text button (the artist's Follow): drawn as its word in a capsule.-@property (nonatomic) BOOL trailingShowsWord;+// For a trailing control that shows its state only as a word (the artist's Follow): SGRMirrorButton's+// readState and its two symbols. Set before the first -showShuffle:...; -trailingStateChanged redraws it.+@property (nonatomic, copy) BOOL (^trailingState)(BOOL *on);+@property (nonatomic, copy) NSString *trailingOffSymbol;+@property (nonatomic, copy) NSString *trailingOnSymbol;+- (void)trailingStateChanged;// Spotify's controls, each drawn from and fired; nil hides that button. Play stays in the middle of the// page whether the other two are there or not. `trailingFallback` is drawn when Spotify's trailing control// has no image to copy. `playColor` is the colour of the capsule's glyph and word.diff --git a/tweak/Sources/Redesigned/Kit/SGRHeaderInfo.m b/tweak/Sources/Redesigned/Kit/SGRHeaderInfo.mindex fc785337..fc61b822 100644--- a/tweak/Sources/Redesigned/Kit/SGRHeaderInfo.m+++ b/tweak/Sources/Redesigned/Kit/SGRHeaderInfo.m@@ -116,7 +116,11 @@ static BOOL setText(UILabel *label, NSString *text) {- (void)showShuffle:(UIView *)shuffle play:(UIView *)play trailing:(UIView *)trailingtrailingFallback:(UIImage *)trailingFallback playColor:(UIColor *)playColor {_trailing.fallbackGlyph = trailingFallback;- _trailing.showsWord = self.trailingShowsWord;+ if (_trailing.readState != self.trailingState) {+ _trailing.readState = self.trailingState;+ _trailing.stateOffSymbol = self.trailingOffSymbol;+ _trailing.stateOnSymbol = self.trailingOnSymbol;+ }if (shuffle) [_shuffle feedFrom:shuffle];if (play) {if (playColor) _play.contentColor = playColor;@@ -137,6 +141,10 @@ static BOOL setText(UILabel *label, NSString *text) {if (changed) [self setNeedsLayout];}+- (void)trailingStateChanged {+ if (_trailing.source) [_trailing feedFrom:_trailing.source];+}+- (CGFloat)contentHeightForWidth:(CGFloat)width {CGFloat text = MAX(0, width - 2 * kSide), height = 0;UILabel *previous = nil;@@ -175,9 +183,7 @@ static BOOL setText(UILabel *label, NSString *text) {CGRect play = CGRectMake(round((width - playWidth) / 2), y, playWidth, side);_play.frame = play;_shuffle.frame = CGRectMake(CGRectGetMinX(play) - kRowSpacing - side, y, side, side);- // A word button is as wide as its word, up to what is left of the page after Play.- CGFloat trailing = MIN([_trailing sgr_width], MAX(side, width - CGRectGetMaxX(play) - kRowSpacing - kSide));- _trailing.frame = CGRectMake(CGRectGetMaxX(play) + kRowSpacing, y, trailing, side);+ _trailing.frame = CGRectMake(CGRectGetMaxX(play) + kRowSpacing, y, side, side);y += side;if (!_about.hidden) {diff --git a/tweak/Sources/Redesigned/Kit/SGRRestyle.h b/tweak/Sources/Redesigned/Kit/SGRRestyle.hindex cd9f2375..5479c1df 100644--- a/tweak/Sources/Redesigned/Kit/SGRRestyle.h+++ b/tweak/Sources/Redesigned/Kit/SGRRestyle.h@@ -32,10 +32,6 @@ void SGRMonospacedDigits(UILabel *label);// ancestor out, so nothing else tells the screen it is there.BOOL SGRObserveImage(UIImageView *view, void (^changed)(UIImageView *view));-// `changed` after every setText: and setAttributedText: on the label, the same way and with the same-// answer: for a word of Spotify's that is a state it fills in later, such as the artist's Follow.-BOOL SGRObserveText(UILabel *label, void (^changed)(UILabel *label));-// `laidOut` after every layoutSubviews of the view, Spotify's included, for as long as the view lives, by// a runtime subclass of the instance like SGRSuppress. A second call replaces the block, and a pass started// from inside the block is not reported again. NO when the view cannot be subclassed (one of Spotify's Swiftdiff --git a/tweak/Sources/Redesigned/Kit/SGRRestyle.m b/tweak/Sources/Redesigned/Kit/SGRRestyle.mindex d31ac5a9..48c37c7c 100644--- a/tweak/Sources/Redesigned/Kit/SGRRestyle.m+++ b/tweak/Sources/Redesigned/Kit/SGRRestyle.m@@ -4,7 +4,7 @@#import "SGRRestyle.h"#import "SGRTokens.h"-static char kPlateKey, kImageObserverKey, kLayoutObserverKey, kTextObserverKey;+static char kPlateKey, kImageObserverKey, kLayoutObserverKey;@interface SGRWeakBox : NSObject@property (nonatomic, weak) id value;@@ -217,42 +217,6 @@ BOOL SGRObserveImage(UIImageView *view, void (^changed)(UIImageView *view)) {return kept || onClass;}-static void reportText(UILabel *label) {- void (^block)(UILabel *) = objc_getAssociatedObject(label, &kTextObserverKey);- if (block) block(label);-}--BOOL SGRObserveText(UILabel *label, void (^changed)(UILabel *label)) {- if (![label isKindOfClass:UILabel.class]) return NO;- BOOL first = objc_getAssociatedObject(label, &kTextObserverKey) == nil;- objc_setAssociatedObject(label, &kTextObserverKey, changed, OBJC_ASSOCIATION_COPY_NONATOMIC);- BOOL kept = adopt(label, "SGRTextObserved_", ^(Class subclass, Class original) {- for (NSString *name in @[@"setText:", @"setAttributedText:"]) {- 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);- reportText(self);- });- }- });- BOOL onClass = NO;- if (!kept) {- Class cls = object_getClass(label);- for (NSString *name in @[@"setText:", @"setAttributedText:"]) {- SEL selector = NSSelectorFromString(name);- onClass |= overrideOnClass(cls, selector, ^id(IMP replaced) {- return ^(UILabel *self, id value) {- ((void (*)(id, SEL, id))replaced)(self, selector, value);- reportText(self);- };- });- }- }- if (first) logWatch(label, @selector(setText:), kept || onClass, onClass);- return kept || onClass;-}-// A pass the block itself sets off (a frame it moves) reaches layoutSubviews again before the block has// returned; one level is enough to settle, and re-entering would not end.static BOOL sg_reportingLayout = NO;