Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.
C
fix: stop idle wakeups and repeated layout work that cost battery (#165)
My-Name-Is-Jeff430766cdd170
diff --git a/AGENTS.md b/AGENTS.mdindex 9903d1c5..06a7e3cf 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -55,7 +55,8 @@ Rules:- Settings: each layer builds its own rows and sections. `App/Pages.m` and `App/ModSettings.x`decide what to show from `SGRedesignedUIStored()`, so native-only pages disappear in the redesign.- Keys start with `spotifyglass.` (redesign-only ones with `spotifyglass.redesign.`). Switches are- read at launch, so a change needs a restart.+ read live through the `Core/SGPrefs.m` memo, but Redesigned UI and any feature whose `%ctor` installs+ its hooks only when it is on take effect at the next launch.## Working on itdiff --git a/harness/genius-lyrics/check.m b/harness/genius-lyrics/check.mindex 442acf48..f1a3652a 100644--- a/harness/genius-lyrics/check.m+++ b/harness/genius-lyrics/check.m@@ -51,6 +51,9 @@ void SGLyricsGetText(NSURL *url, void (^done)(NSString *text)) {NSData *body = fetched(url);done(body ? [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding] : nil);}+void SGLyricsGetTextThen(NSURL *url, id (^parse)(NSString *text), void (^done)(id parsed)) {+ SGLyricsGetText(url, ^(NSString *text) { done(parse(text)); });+}// A search reply holding these hits, in this order: {id, title, primary artists, instrumental, artist_names}.static NSDictionary *reply(NSArray<NSArray *> *hits) {diff --git a/harness/prefs/check.m b/harness/prefs/check.mindex e83e3f64..34b180c0 100644--- a/harness/prefs/check.m+++ b/harness/prefs/check.m@@ -32,7 +32,65 @@ int main(void) {[store removeObjectForKey:choice];CHECK(SGInt(choice, 7) == 7);- for (NSString *key in @[flag, choice]) [store removeObjectForKey:key];+ // A write posts one change notification, before it returns, on the thread that wrote. dispatch_sync would run+ // its block on this thread, so the other thread is a real one, waited for.+ NSString *counter = @"spotifyglass.test.counter";+ __block NSUInteger posts = 0;+ __block NSThread *postedOn = nil, *writer = nil;+ dispatch_semaphore_t written = dispatch_semaphore_create(0);+ void (^elsewhere)(void (^)(void)) = ^(void (^write)(void)) {+ dispatch_async(dispatch_get_global_queue(0, 0), ^{+ writer = NSThread.currentThread;+ write();+ dispatch_semaphore_signal(written);+ });+ dispatch_semaphore_wait(written, DISPATCH_TIME_FOREVER);+ };+ [NSNotificationCenter.defaultCenter addObserverForName:NSUserDefaultsDidChangeNotification object:nil queue:nil+ usingBlock:^(NSNotification *note) { posts++; postedOn = NSThread.currentThread; }];+ [store setInteger:1 forKey:choice];+ CHECK(posts == 1 && postedOn == NSThread.currentThread);+ [store setObject:@{@"a": @1} forKey:counter];+ CHECK(posts == 2 && postedOn == NSThread.currentThread);+ elsewhere(^{ [store setInteger:2 forKey:choice]; });+ CHECK(posts == 3 && writer != NSThread.currentThread && postedOn == writer);+ CHECK(SGInt(choice, 7) == 2);++ // The memo itself: a write to the store that posts nothing stays unseen until the next change.+ CFPreferencesSetAppValue((__bridge CFStringRef)choice, (__bridge CFPropertyListRef)@4, kCFPreferencesCurrentApplication);+ CHECK(posts == 3 && [store integerForKey:choice] == 4 && SGInt(choice, 7) == 2);+ // A tagged write of a key the accessors never read leaves the memo in place.+ SGPrefsWriteUnmemoized(^{ [store setObject:@{@"a": @2} forKey:counter]; });+ CHECK(posts == 4 && SGInt(choice, 7) == 2);+ // The tag is this thread's: a write on another thread inside it still drops the memo.+ SGPrefsWriteUnmemoized(^{ elsewhere(^{ [store setObject:@{@"a": @3} forKey:counter]; }); });+ CHECK(posts == 5 && postedOn == writer && SGInt(choice, 7) == 4);+ // And an untagged write after the tagged one drops it too.+ CFPreferencesSetAppValue((__bridge CFStringRef)choice, (__bridge CFPropertyListRef)@5, kCFPreferencesCurrentApplication);+ CHECK(SGInt(choice, 7) == 4);+ [store setObject:@{@"a": @4} forKey:counter];+ CHECK(posts == 6 && SGInt(choice, 7) == 5);++ // SGString answers as -stringForKey: does, through the memo.+ NSString *text = @"spotifyglass.test.text";+ CHECK(SGString(text) == nil);+ [store setObject:@"Recents" forKey:text];+ CHECK([SGString(text) isEqualToString:@"Recents"] && SGString(text) == SGString(text));+ [store setInteger:12 forKey:text];+ CHECK([SGString(text) isEqualToString:@"12"]);+ [store setObject:@[@"a"] forKey:text];+ CHECK(SGString(text) == nil);++ // SGArray answers as -arrayForKey: does, through the memo, and a writer's SGPrefsChanged() shows the write.+ CHECK([SGArray(text) isEqualToArray:@[@"a"]] && SGArray(text) == SGArray(text));+ [store setObject:@"Recents" forKey:text];+ CHECK(SGArray(text) == nil);+ CFPreferencesSetAppValue((__bridge CFStringRef)text, (__bridge CFPropertyListRef)@[@"b"], kCFPreferencesCurrentApplication);+ CHECK(SGArray(text) == nil);+ SGPrefsChanged();+ CHECK([SGArray(text) isEqualToArray:@[@"b"]]);++ for (NSString *key in @[flag, choice, counter, text]) [store removeObjectForKey:key];puts("prefs: ok");}return 0;diff --git a/harness/sing/main.m b/harness/sing/main.mindex 8803fbd7..34f6fec9 100644--- a/harness/sing/main.m+++ b/harness/sing/main.m@@ -714,7 +714,7 @@ static void checkStarved(void) {SGSingEngineSetOn(engine, true);Source source = {tone, 0, true, 0}, *pulled = &source;__block double worst = 0, leadAt6 = 0, leastInStall = 100, leadAt12 = 0;- __block unsigned long long stopsAt6 = 0, stopsAt12 = 0;+ __block unsigned long long stopsAt6 = 0, stopsAt12 = 0, windowsAt8 = 0, windowsAt12 = 0;malloc_logger = countAllocation;Audio out = play(engine, tone, &source, 1024, 12.5, ^(double played) {// Decoded at 1.5 times what plays from a quarter second in, stalled from 6 s to 8 s.@@ -726,9 +726,11 @@ static void checkStarved(void) {stopsAt6 = SGSingEngineReadStats(engine).aheadStops;}if (played >= 6 && played < 8.1) leastInStall = fmin(leastInStall, SGSingEngineLead(engine));+ if (played >= 8 && !windowsAt8) windowsAt8 = SGSingEngineReadStats(engine).windows;if (played >= 12 && !leadAt12) {leadAt12 = SGSingEngineLead(engine);stopsAt12 = SGSingEngineReadStats(engine).aheadStops;+ windowsAt12 = SGSingEngineReadStats(engine).windows;}});malloc_logger = NULL;@@ -738,6 +740,8 @@ static void checkStarved(void) {"filling as the decoder let it (%.2f s at 6 s)", stopsAt6, leadAt6);CHECK(leastInStall > 0.5 && leastInStall < leadAt6 - 1, "a 2 s stall of the decoder at 6 s plays through on the lead (down to %.2f s)", leastInStall);CHECK(leadAt12 > 2 && stopsAt12 > stopsAt6, "after it the lead is read again (%.2f s at 12 s, %llu stops)", leadAt12, stopsAt12);+ CHECK(windowsAt12 > windowsAt8, "and the model runs windows again, the worker asleep through the stall woken (%llu by 8 s, %llu by 12 s)",+ windowsAt8, windowsAt12);double gap = 0;for (size_t i = 0; i < 12 * kSGSingRate; i++) gap = fmax(gap, fabsf(out.left[i] - tone.left[i]));CHECK(gap < 1e-6, "what plays is the song with no gap and every frame in order, the stall included (%.2g)", gap);diff --git a/harness/tokens/check.m b/harness/tokens/check.mnew file mode 100644index 00000000..3fee8d98--- /dev/null+++ b/harness/tokens/check.m@@ -0,0 +1,39 @@+// Host check for Redesigned/Kit/SGRTokens.m's SGRFont: the same inputs give the one kept font, each input is part+// of what tells fonts apart, and the kept font is the one the uncached computation gives.+#import <UIKit/UIKit.h>+#import "Redesigned/Kit/SGRTokens.h"++// SGRTokens.m's accent comes from SGRAccent.x, which this does not compile.+UIColor *SGRAccentColor(void) { return nil; }++#define CHECK(cond) do { if (!(cond)) { fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #cond); exit(1); } } while (0)++static UIFont *uncached(UIFontTextStyle style, UIFontWeight weight, UIContentSizeCategory largest) {+ UIContentSizeCategory current = UIApplication.sharedApplication.preferredContentSizeCategory;+ if (largest && UIContentSizeCategoryCompareToCategory(current, largest) == NSOrderedDescending) current = largest;+ UITraitCollection *traits = [UITraitCollection traitCollectionWithPreferredContentSizeCategory:current];+ return [UIFont systemFontOfSize:[UIFont preferredFontForTextStyle:style compatibleWithTraitCollection:traits].pointSize weight:weight];+}++int main(void) {+ @autoreleasepool {+ printf("current category: %s\n", UIApplication.sharedApplication.preferredContentSizeCategory.UTF8String ?: "(none)");+ UIFont *title = SGRFont(UIFontTextStyleTitle2, UIFontWeightBold, UIContentSizeCategoryLarge);+ CHECK(title == SGRFont(UIFontTextStyleTitle2, UIFontWeightBold, UIContentSizeCategoryLarge));+ CHECK([title isEqual:uncached(UIFontTextStyleTitle2, UIFontWeightBold, UIContentSizeCategoryLarge)]);++ // Mac Catalyst scales no text style by category, so only the style and the weight can be told apart here; the+ // cap and the live category are in the key by construction (SGRTokens.m).+ UIFont *body = SGRFont(UIFontTextStyleBody, UIFontWeightBold, UIContentSizeCategoryLarge);+ UIFont *regular = SGRFont(UIFontTextStyleTitle2, UIFontWeightRegular, UIContentSizeCategoryLarge);+ UIFont *capped = SGRFont(UIFontTextStyleTitle2, UIFontWeightBold, UIContentSizeCategoryExtraSmall);+ CHECK(![body isEqual:title] && ![regular isEqual:title]);+ CHECK(body == SGRFont(UIFontTextStyleBody, UIFontWeightBold, UIContentSizeCategoryLarge));+ CHECK([body isEqual:uncached(UIFontTextStyleBody, UIFontWeightBold, UIContentSizeCategoryLarge)]);+ CHECK([regular isEqual:uncached(UIFontTextStyleTitle2, UIFontWeightRegular, UIContentSizeCategoryLarge)]);+ CHECK([capped isEqual:uncached(UIFontTextStyleTitle2, UIFontWeightBold, UIContentSizeCategoryExtraSmall)]);+ printf("title %.1f, body %.1f, capped %.1f\n", title.pointSize, body.pointSize, capped.pointSize);+ puts("tokens: ok");+ }+ return 0;+}diff --git a/harness/tokens/check.sh b/harness/tokens/check.shnew file mode 100644index 00000000..e5dc34f1--- /dev/null+++ b/harness/tokens/check.sh@@ -0,0 +1,12 @@+#!/bin/sh+# Builds and runs the SGRTokens check for the Mac (Mac Catalyst, for UIKit), the way harness/palette builds.+set -eu+cd "$(dirname "$0")"+SRC=../../tweak/Sources+SDK=$(xcrun --sdk macosx --show-sdk-path)+mkdir -p build+xcrun clang -fobjc-arc -O0 -g -Wall -Wextra -Werror -Wno-unused-parameter -target arm64-apple-ios17.0-macabi -isysroot "$SDK" \+ -iframework "$SDK/System/iOSSupport/System/Library/Frameworks" -isystem "$SDK/System/iOSSupport/usr/include" \+ -I"$SRC" check.m "$SRC"/Redesigned/Kit/SGRTokens.m "$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m \+ -framework UIKit -framework CoreGraphics -framework QuartzCore -o build/check+build/checkdiff --git a/tweak/Sources/Core/SGGlass.m b/tweak/Sources/Core/SGGlass.mindex 44d5540a..b4fdc3ca 100644--- a/tweak/Sources/Core/SGGlass.m+++ b/tweak/Sources/Core/SGGlass.m@@ -50,13 +50,21 @@ void SGHideGlassFrom(UIView *host, NSUInteger count) {}void SGShapeGlass(UIView *glass, CGFloat radius, BOOL capsule) {- Class config = NSClassFromString(@"UICornerConfiguration");- Class cornerRadius = NSClassFromString(@"UICornerRadius");+ // The classes and what they answer to are fixed once loaded; whether this pane takes a configuration is asked each time.+ static Class config, cornerRadius;+ static BOOL capsules, uniform;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ config = NSClassFromString(@"UICornerConfiguration");+ cornerRadius = NSClassFromString(@"UICornerRadius");+ capsules = [config respondsToSelector:@selector(capsuleConfiguration)];+ uniform = [config respondsToSelector:@selector(configurationWithUniformRadius:)] && [cornerRadius respondsToSelector:@selector(fixedRadius:)];+ });id shape = nil;if (config && [glass respondsToSelector:@selector(setCornerConfiguration:)]) {- if (capsule && [config respondsToSelector:@selector(capsuleConfiguration)]) {+ if (capsule && capsules) {shape = [config capsuleConfiguration];- } else if ([config respondsToSelector:@selector(configurationWithUniformRadius:)] && [cornerRadius respondsToSelector:@selector(fixedRadius:)]) {+ } else if (uniform) {shape = [config configurationWithUniformRadius:[cornerRadius fixedRadius:radius]];}}diff --git a/tweak/Sources/Core/SGPrefs.h b/tweak/Sources/Core/SGPrefs.hindex 57969c6a..b3471f8b 100644--- a/tweak/Sources/Core/SGPrefs.h+++ b/tweak/Sources/Core/SGPrefs.h@@ -18,9 +18,19 @@ void SGSetEnabled(NSString *key, BOOL on);NSInteger SGInt(NSString *key, NSInteger fallback);void SGSetInt(NSString *key, NSInteger value);+// What -stringForKey: answers (a string as it is, a number as its stringValue, else nil), kept like the switches.+// A writer of such a key calls SGPrefsChanged() after its write, as SGSetInt does.+NSString *SGString(NSString *key);+// What -arrayForKey: answers (an array as it is, else nil), kept like the switches; same rule for its writers.+NSArray *SGArray(NSString *key);+// The accessors keep what they read until the defaults change. An observer of NSUserDefaultsDidChangeNotification// that reads them calls this first, as observers are not called in a set order.void SGPrefsChanged(void);+// Runs `write`, whose defaults writes go to keys the accessors never read (a counter, the last track), without+// dropping what they keep: the change notification such a write posts, on this thread before it returns, is+// passed over, as is any SGPrefsChanged() made inside. Nothing in `write` may change a key the accessors read.+void SGPrefsWriteUnmemoized(void (^write)(void));// Overrides of Spotify's remote-config flags, stored under SGFlagOverridePrefix + flag key;// nil keeps Spotify's value. Shared/Flags reads them, the All flags page and flag rows write them.diff --git a/tweak/Sources/Core/SGPrefs.m b/tweak/Sources/Core/SGPrefs.mindex 50e1655c..e142b869 100644--- a/tweak/Sources/Core/SGPrefs.m+++ b/tweak/Sources/Core/SGPrefs.m@@ -7,8 +7,11 @@static os_unfair_lock memoLock = OS_UNFAIR_LOCK_INIT;static NSMutableDictionary<NSString *, id> *memo;static NSUInteger memoGeneration;+// Set on the thread inside SGPrefsWriteUnmemoized, whose write changes nothing the memo holds.+static _Thread_local BOOL writingUnmemoized;void SGPrefsChanged(void) {+ if (writingUnmemoized) return;os_unfair_lock_lock(&memoLock);[memo removeAllObjects];memoGeneration++;@@ -36,6 +39,13 @@ static id stored(NSString *key) {return value;}+void SGPrefsWriteUnmemoized(void (^write)(void)) {+ BOOL was = writingUnmemoized;+ writingUnmemoized = YES;+ write();+ writingUnmemoized = was;+}+BOOL SGFlag(NSString *key, BOOL fallback) {id value = stored(key);if (value) return [value boolValue];@@ -60,6 +70,17 @@ NSInteger SGInt(NSString *key, NSInteger fallback) {return value ? [value integerValue] : fallback;}+NSString *SGString(NSString *key) {+ id value = stored(key);+ if ([value isKindOfClass:NSString.class]) return value;+ return [value isKindOfClass:NSNumber.class] ? [value stringValue] : nil;+}++NSArray *SGArray(NSString *key) {+ id value = stored(key);+ return [value isKindOfClass:NSArray.class] ? value : nil;+}+void SGSetInt(NSString *key, NSInteger value) {[NSUserDefaults.standardUserDefaults setInteger:value forKey:key];SGPrefsChanged();diff --git a/tweak/Sources/Core/SGViewTree.h b/tweak/Sources/Core/SGViewTree.hindex 4a2b4fee..97e16ee7 100644--- a/tweak/Sources/Core/SGViewTree.h+++ b/tweak/Sources/Core/SGViewTree.h@@ -19,8 +19,15 @@ BOOL SGHasClass(UIView *root, NSString *marker);// The first view under `root` (itself included) that `match` accepts, remembered weakly on `root` under// `key` and looked for again once it no longer matches or has left `root`. Nothing found is not remembered.UIView *SGFindRemembered(UIView *root, const void *key, BOOL (^match)(UIView *view));+// `count` SGFindRemembered lookups on `root` in one walk, for a caller that asks for several views back to back+// with nothing between the lookups that could change the tree. Each key's remembered view is kept by the same+// rule, the keys left are looked for together, each taking the first view `match` accepts for it, and only hits+// are remembered. `out[i]` is key i's view or nil: the same answers the lookups give one after another.+void SGFindRememberedAll(UIView *root, NSUInteger count, const void *const keys[], BOOL (^match)(NSUInteger i, UIView *view), UIView *__strong out[]);// SGFindRemembered for the first view whose accessibility identifier starts with `prefix`.UIView *SGFindIdentifier(UIView *root, NSString *prefix, const void *key);+// SGFindRememberedAll for `count` identifier prefixes.+void SGFindIdentifiers(UIView *root, NSUInteger count, NSString *const prefixes[], const void *const keys[], UIView *__strong out[]);// Artwork, glyphs, text and thin lines (progress bar) keep their color, everything else goes clear.BOOL SGKeepsColor(UIView *view);diff --git a/tweak/Sources/Core/SGViewTree.m b/tweak/Sources/Core/SGViewTree.mindex 191fbf9a..a5a292d4 100644--- a/tweak/Sources/Core/SGViewTree.m+++ b/tweak/Sources/Core/SGViewTree.m@@ -72,25 +72,66 @@ BOOL SGHasClass(UIView *root, NSString *marker) {@implementation SGWeakBox@end-UIView *SGFindRemembered(UIView *root, const void *key, BOOL (^match)(UIView *view)) {- if (!root) return nil;+// The view remembered on `root` under `key`, while it still matches and is still under `root`.+static UIView *remembered(UIView *root, const void *key, BOOL (^match)(UIView *view)) {SGWeakBox *box = objc_getAssociatedObject(root, key);UIView *cached = box.value;- if (cached && match(cached) && [cached isDescendantOfView:root]) return cached;- UIView *found = firstMatch(root, match);- if (!found) return nil;+ return cached && match(cached) && [cached isDescendantOfView:root] ? cached : nil;+}++static void remember(UIView *root, const void *key, UIView *found) {+ SGWeakBox *box = objc_getAssociatedObject(root, key);if (!box) {box = [SGWeakBox new];objc_setAssociatedObject(root, key, box, OBJC_ASSOCIATION_RETAIN_NONATOMIC);}box.value = found;+}++UIView *SGFindRemembered(UIView *root, const void *key, BOOL (^match)(UIView *view)) {+ if (!root) return nil;+ UIView *found = remembered(root, key, match);+ if (found) return found;+ found = firstMatch(root, match);+ if (found) remember(root, key, found);return found;}+// Depth first like firstMatch, testing every key still wanted at each view, so each takes the first view it+// accepts; done once every key has one.+static void matchAll(UIView *view, NSUInteger count, BOOL (^match)(NSUInteger i, UIView *view), UIView *__strong out[], NSUInteger *left) {+ for (NSUInteger i = 0; i < count; i++) {+ if (out[i] || !match(i, view)) continue;+ out[i] = view;+ if (!--*left) return;+ }+ for (UIView *sub in view.subviews) {+ matchAll(sub, count, match, out, left);+ if (!*left) return;+ }+}++void SGFindRememberedAll(UIView *root, NSUInteger count, const void *const keys[], BOOL (^match)(NSUInteger i, UIView *view), UIView *__strong out[]) {+ NSUInteger left = 0;+ for (NSUInteger i = 0; i < count; i++) {+ out[i] = root ? remembered(root, keys[i], ^BOOL(UIView *v) { return match(i, v); }) : nil;+ if (!out[i]) left++;+ }+ if (!root || !left) return;+ matchAll(root, count, match, out, &left);+ for (NSUInteger i = 0; i < count; i++) {+ if (out[i]) remember(root, keys[i], out[i]);+ }+}+UIView *SGFindIdentifier(UIView *root, NSString *prefix, const void *key) {return SGFindRemembered(root, key, ^BOOL(UIView *v) { return [v.accessibilityIdentifier hasPrefix:prefix]; });}+void SGFindIdentifiers(UIView *root, NSUInteger count, NSString *const prefixes[], const void *const keys[], UIView *__strong out[]) {+ SGFindRememberedAll(root, count, keys, ^BOOL(NSUInteger i, UIView *v) { return [v.accessibilityIdentifier hasPrefix:prefixes[i]]; }, out);+}+BOOL SGKeepsColor(UIView *view) {return [view isKindOfClass:UIImageView.class] || [view isKindOfClass:UILabel.class] || view.bounds.size.height <= 4;}diff --git a/tweak/Sources/Native/Album/Album.x b/tweak/Sources/Native/Album/Album.xindex bd6bcb0f..62ce0637 100644--- a/tweak/Sources/Native/Album/Album.x+++ b/tweak/Sources/Native/Album/Album.x@@ -43,10 +43,18 @@ static BOOL buttonHidden(UIView *action) {return key && SGHidden(key);}+static BOOL anyButtonSwitch(void) {+ for (size_t i = 0; i < sizeof(buttons) / sizeof(buttons[0]); i++) {+ if (SGHidden(buttons[i].key)) return YES;+ }+ return NO;+}+// The buttons arrive after the page has laid out, and a row that keeps its size lays nothing else out.%hook UIStackView- (void)layoutSubviews {%orig;+ if (!anyButtonSwitch()) return;BOOL any = NO;for (UIView *action in self.subviews) {if ((any = buttonHidden(action))) break;diff --git a/tweak/Sources/Native/Appearance/Repaint.x b/tweak/Sources/Native/Appearance/Repaint.xindex 3bfd7231..0d7a2550 100644--- a/tweak/Sources/Native/Appearance/Repaint.x+++ b/tweak/Sources/Native/Appearance/Repaint.x@@ -9,15 +9,25 @@ __weak UIView *sg_npvBackdropRoot = nil;%hook CALayer- (void)setBackgroundColor:(CGColorRef)color {- if (color && (sg_lyricsCardRoot || sg_lyricsPageRoot || sg_homeRoot || sg_npvBackdropRoot)) {+ if (!color) {+ %orig;+ return;+ }+ UIView *cardRoot = sg_lyricsCardRoot, *pageRoot = sg_lyricsPageRoot, *homeRoot = sg_homeRoot, *npvRoot = sg_npvBackdropRoot;+ if (cardRoot || pageRoot || homeRoot || npvRoot) {UIView *view = (UIView *)self.delegate;if ([view isKindOfClass:UIView.class] && view.layer == self && !SGKeepsColor(view)) {- if (SGIsInside(view, sg_lyricsCardRoot) || SGIsInside(view, sg_lyricsPageRoot)) {- color = NULL;- } else if (SGIsInside(view, sg_npvBackdropRoot)) {- // The album color arrives on the plane per track, outside any layout pass.+ // One walk answers SGIsInside for all four roots: each stops at the same first effect view.+ BOOL lyrics = NO, home = NO;+ for (UIView *v = view; v && !lyrics; v = v.superview) {+ if ([v isKindOfClass:UIVisualEffectView.class]) break;+ // The album color arrives on the backdrop plane per track, outside any layout pass.+ lyrics = v == cardRoot || v == pageRoot || v == npvRoot;+ home = home || v == homeRoot;+ }+ if (lyrics) {color = NULL;- } else if (SGIsBaseSurface(color) && SGIsInside(view, sg_homeRoot)) {+ } else if (home && SGIsBaseSurface(color)) {// Home keeps its cards and its placeholders; only the base surface the gradient// of Native/Home/HomeGradient.x sits behind goes.color = NULL;diff --git a/tweak/Sources/Native/Artist/Artist.x b/tweak/Sources/Native/Artist/Artist.xindex 6a0f66a7..12ebad3b 100644--- a/tweak/Sources/Native/Artist/Artist.x+++ b/tweak/Sources/Native/Artist/Artist.x@@ -45,13 +45,34 @@ static UIView *actionHolding(UIView *button, UIView *header) {}static void applyHeader(UIView *header) {- if (SGHidden(SGHideArtistVerified)) SGFindIdentifier(header, kBadge, &kBadgeKey).hidden = YES;- // Its AutoLayoutStackView traps like OverflowStackView below once the label goes hidden.- if (SGHidden(SGHideArtistListeners)) SGFindIdentifier(header, kMetadata, &kMetadataKey).alpha = 0;-+ // Every part with a switch on, looked for in one walk; hiding one changes no view's place or identifier.+ BOOL hideBadge = SGHidden(SGHideArtistVerified), hideListeners = SGHidden(SGHideArtistListeners);+ NSString *idents[kButtons + 2];+ const void *keys[kButtons + 2];+ NSUInteger count = 0;+ if (hideBadge) {+ idents[count] = kBadge;+ keys[count++] = &kBadgeKey;+ }+ if (hideListeners) {+ idents[count] = kMetadata;+ keys[count++] = &kMetadataKey;+ }for (size_t i = 0; i < kButtons; i++) {if (!SGHidden(buttons[i].key)) continue;- UIView *action = actionHolding(SGFindIdentifier(header, buttons[i].ident, &kButtonKeys[i]), header);+ idents[count] = buttons[i].ident;+ keys[count++] = &kButtonKeys[i];+ }+ if (!count) return;+ UIView *found[count];+ SGFindIdentifiers(header, count, idents, keys, found);++ NSUInteger at = 0;+ if (hideBadge) found[at++].hidden = YES;+ // Its AutoLayoutStackView traps like OverflowStackView below once the label goes hidden.+ if (hideListeners) found[at++].alpha = 0;+ for (; at < count; at++) {+ UIView *action = actionHolding(found[at], header);if (!action) continue;// OverflowStackView traps in updateConstraints once its views go hidden (crash 2026-09-15),// so those only turn invisible and keep their place.diff --git a/tweak/Sources/Native/Home/HomeGradient.x b/tweak/Sources/Native/Home/HomeGradient.xindex c7e4ac98..72f1d062 100644--- a/tweak/Sources/Native/Home/HomeGradient.x+++ b/tweak/Sources/Native/Home/HomeGradient.x@@ -169,7 +169,7 @@ static UIScrollView *pageList(UIView *view) {%orig;for (UIView *wrapper in ((UIViewController *)self).viewIfLoaded.subviews) {for (UIView *view in wrapper.subviews) {- if ([NSStringFromClass(view.class) containsString:@"GradientView"]) view.hidden = YES;+ if (SGClassNamed(view.class, @"GradientView")) view.hidden = YES;}}}diff --git a/tweak/Sources/Native/LocalFiles/LocalCover.x b/tweak/Sources/Native/LocalFiles/LocalCover.xindex 0da1fcec..bf3685f7 100644--- a/tweak/Sources/Native/LocalFiles/LocalCover.x+++ b/tweak/Sources/Native/LocalFiles/LocalCover.x@@ -15,6 +15,8 @@static const CGFloat kCoverMinWidth = 200;static char kImageKey, kTrackKey;static __weak UIScrollView *sg_list;+// The image views holding a picture of the mod's, weakly.+static NSHashTable<UIImageView *> *sg_filled;static BOOL isCoverCell(UIView *view) {static Class cell, legacy;@@ -49,14 +51,26 @@ static void fill(UIImageView *view) {view.image = cover;objc_setAssociatedObject(view, &kImageKey, cover, OBJC_ASSOCIATION_RETAIN_NONATOMIC);objc_setAssociatedObject(view, &kTrackKey, uri, OBJC_ASSOCIATION_COPY_NONATOMIC);+ if (!sg_filled) sg_filled = [NSHashTable weakObjectsHashTable];+ if (cover) [sg_filled addObject:view]; else [sg_filled removeObject:view];+}++// With no picture of the mod's on screen and no local file playing, fill changes nothing (no view is+// ours, and SGLocalFileFallbackCover answers nil for any other track before doing anything), so the+// walk for the image view is spared on every layout of the list.+static BOOL nothingToFill(void) {+ // A weak table's count can still include freed views; enumeration skips them.+ for (__unused UIView *view in sg_filled) return NO;+ return !SGLocalFileIs(SGURIString(SGPlayerState().track.URI));}static void fillFront(UIScrollView *list) {CGFloat middle = list.contentOffset.x + list.bounds.size.width / 2;+ BOOL idle = nothingToFill();for (UIView *cell in list.subviews) {if (!isCoverCell(cell) || middle < CGRectGetMinX(cell.frame) || middle > CGRectGetMaxX(cell.frame)) continue;sg_list = list;- fill(largestImageIn(cell));+ if (!idle) fill(largestImageIn(cell));}}@@ -94,7 +108,7 @@ static void fillFront(UIScrollView *list) {if (isCoverCell(view)) return;player = player || SGClassNamed(view.class, @"NowPlaying");}- if (player) fill(largestImageIn(tilt));+ if (player && !nothingToFill()) fill(largestImageIn(tilt));}%enddiff --git a/tweak/Sources/Native/Lyrics/LyricsPage.x b/tweak/Sources/Native/Lyrics/LyricsPage.xindex c93e6153..b2098551 100644--- a/tweak/Sources/Native/Lyrics/LyricsPage.x+++ b/tweak/Sources/Native/Lyrics/LyricsPage.x@@ -20,12 +20,20 @@static char kPageGlassKey;+// A class's name never changes, so its prefix test is answered once (main thread only, as the layout is).+static BOOL isTransitionClass(Class cls) {+ static NSMutableDictionary *answers;+ if (!answers) answers = [NSMutableDictionary dictionary];+ NSNumber *answer = answers[(id<NSCopying>)cls];+ if (!answer) answers[(id<NSCopying>)cls] = answer = @([NSStringFromClass(cls) hasPrefix:@"UITransition"]);+ return answer.boolValue;+}+// Up to the presentation: the template views in between paint themselves opaque once, at setup.// Only the chain is cleared, not the subtree -- nothing else on the page is painted.static UIView *clearAncestors(UIView *view) {UIView *top = view;- for (UIView *v = view; v && ![v isKindOfClass:UIWindow.class]- && ![NSStringFromClass(v.class) hasPrefix:@"UITransition"]; v = v.superview) {+ for (UIView *v = view; v && ![v isKindOfClass:UIWindow.class] && !isTransitionClass(v.class); v = v.superview) {v.layer.backgroundColor = NULL;top = v;}diff --git a/tweak/Sources/Native/Navbar/Navbar.x b/tweak/Sources/Native/Navbar/Navbar.xindex df913abc..f2f4efc0 100644--- a/tweak/Sources/Native/Navbar/Navbar.x+++ b/tweak/Sources/Native/Navbar/Navbar.x@@ -383,13 +383,12 @@ void SGLogTabBarRow(UIView *tabBar) {%hook _TtC28NavigationUI_TabBarItemsImpl29TabBarItemsNavigationListImpl- (NSArray *)items {NSArray *items = %orig;+ static BOOL logged;+ if (logged) return items;+ logged = YES;NSMutableString *out = [NSMutableString stringWithFormat:@"list read, %lu items", (unsigned long)items.count];for (id item in items) [out appendFormat:@"\n %@ · %@", [item valueForKey:@"title"], [item valueForKey:@"viewURI"]];- static NSString *last;- if (![out isEqualToString:last]) {- last = [out copy];- SGLogLong(@"navbar", out);- }+ SGLogLong(@"navbar", out);return items;}%enddiff --git a/tweak/Sources/Native/Navbar/NavbarLayout.m b/tweak/Sources/Native/Navbar/NavbarLayout.mindex 71bad609..510e7b8a 100644--- a/tweak/Sources/Native/Navbar/NavbarLayout.m+++ b/tweak/Sources/Native/Navbar/NavbarLayout.m@@ -1,4 +1,5 @@// The saved composition of the bar, as NSUserDefaults property lists.+#import "Core/SGPrefs.h"#import "Navbar.h"NSString *const SGNavbarID = @"id";@@ -14,7 +15,7 @@ static NSString *const kNavbarSplit = @"spotifyglass.navbar.split";// Only property list types go in, so a corrupt read cannot be anything but an array of dictionaries.static NSArray *listOfKind(NSString *key, Class kind) {- NSArray *list = [NSUserDefaults.standardUserDefaults arrayForKey:key];+ NSArray *list = SGArray(key);for (id item in list) if (![item isKindOfClass:kind]) return @[];return list ?: @[];}@@ -25,6 +26,7 @@ NSArray<NSDictionary *> *SGNavbarLayout(void) {void SGSetNavbarLayout(NSArray<NSDictionary *> *layout) {[NSUserDefaults.standardUserDefaults setObject:layout ?: @[] forKey:kNavbarLayout];+ SGPrefsChanged();}NSArray<NSString *> *SGNavbarSplit(void) {@@ -33,6 +35,7 @@ NSArray<NSString *> *SGNavbarSplit(void) {void SGSetNavbarSplit(NSArray<NSString *> *split) {[NSUserDefaults.standardUserDefaults setObject:split ?: @[] forKey:kNavbarSplit];+ SGPrefsChanged();}NSArray<NSString *> *SGNavbarStock(void) {@@ -41,4 +44,5 @@ NSArray<NSString *> *SGNavbarStock(void) {void SGSetNavbarStock(NSArray<NSString *> *stock) {[NSUserDefaults.standardUserDefaults setObject:stock ?: @[] forKey:kNavbarStock];+ SGPrefsChanged();}diff --git a/tweak/Sources/Native/NowPlayingBar/NowPlayingBar.x b/tweak/Sources/Native/NowPlayingBar/NowPlayingBar.xindex a5ac60c6..f01caf11 100644--- a/tweak/Sources/Native/NowPlayingBar/NowPlayingBar.x+++ b/tweak/Sources/Native/NowPlayingBar/NowPlayingBar.x@@ -6,15 +6,16 @@#import "Core/SGCore.h"#import "NowPlayingBar.h"+// `marker` is a literal: SGClassNamed keeps its answers by the marker's address.static BOOL insideClass(UIView *view, NSString *marker) {- for (UIView *v = view; v; v = v.superview) if ([NSStringFromClass(v.class) containsString:marker]) return YES;+ for (UIView *v = view; v; v = v.superview) if (SGClassNamed(v.class, marker)) return YES;return NO;}static void hideConnectButton(UIView *bar) {SGForEachView(bar, ^(UIView *v) {- NSString *name = NSStringFromClass(v.class);- if (![name containsString:@"ConnectButtonView"] && ![name containsString:@"ConnectStateView"]) return;+ Class cls = v.class;+ if (!SGClassNamed(cls, @"ConnectButtonView") && !SGClassNamed(cls, @"ConnectStateView")) return;if (insideClass(v, @"InformationContainer")) return;UIView *item = v;while (item.superview && ![item.superview isKindOfClass:UIStackView.class]) item = item.superview;diff --git a/tweak/Sources/Native/Playlist/Playlist.x b/tweak/Sources/Native/Playlist/Playlist.xindex 9765bcf6..1f90eb51 100644--- a/tweak/Sources/Native/Playlist/Playlist.x+++ b/tweak/Sources/Native/Playlist/Playlist.x@@ -82,9 +82,22 @@ static void applyColumn(UIView *header) {// the action rather than the button and the row closes up behind it.// An action already hidden is passed over.static void applyActions(UIView *row) {+ // The buttons with a switch on, looked for under each action in one walk.+ NSString *idents[kButtons];+ const void *keys[kButtons];+ NSUInteger count = 0;+ for (size_t i = 0; i < kButtons; i++) {+ if (!SGHidden(buttons[i].key)) continue;+ idents[count] = buttons[i].ident;+ keys[count++] = &kButtonKeys[i];+ }+ if (!count) return;for (UIView *action in row.subviews) {- for (size_t i = 0; i < kButtons && !action.hidden; i++) {- if (SGHidden(buttons[i].key) && SGFindIdentifier(action, buttons[i].ident, &kButtonKeys[i])) action.hidden = YES;+ if (action.hidden) continue;+ UIView *found[count];+ SGFindIdentifiers(action, count, idents, keys, found);+ for (NSUInteger i = 0; i < count && !action.hidden; i++) {+ if (found[i]) action.hidden = YES;}}}diff --git a/tweak/Sources/Redesigned/Album/AlbumHeader.x b/tweak/Sources/Redesigned/Album/AlbumHeader.xindex 94eb7416..764f436a 100644--- a/tweak/Sources/Redesigned/Album/AlbumHeader.x+++ b/tweak/Sources/Redesigned/Album/AlbumHeader.x@@ -143,9 +143,13 @@ static void watch(UIView *view, const void *key, void (^laidOut)(UIView *view))AVPlayerLayer *_motion;AVQueuePlayer *_player;AVPlayerLooper *_looper;+ BOOL _motionOn; // what the player was last asked, so a scroll's steps ask it nothing again+ BOOL _motionSeen; // whether the hero was on screen when the player was last asked+ __weak UIScrollView *_list; // the page's list, watched for the hero scrolling off the screen and back}static void *kReadyContext = &kReadyContext;+static void *kListContext = &kListContext;- (instancetype)initWithFrame:(CGRect)frame {if (!(self = [super initWithFrame:frame])) return nil;@@ -197,6 +201,7 @@ static void *kReadyContext = &kReadyContext;- (void)dealloc {[NSNotificationCenter.defaultCenter removeObserver:self];+ [_list removeObserver:self forKeyPath:@"contentOffset" context:kListContext];[self sgr_dropMotion];}@@ -295,6 +300,8 @@ static void *kReadyContext = &kReadyContext;_motion.opacity = 0;[self.layer addSublayer:_motion];[_motion addObserver:self forKeyPath:@"readyForDisplay" options:NSKeyValueObservingOptionInitial context:kReadyContext];+ _motionOn = NO;+ [self sgr_watchList];[self sgr_updateMotion];SGLog(@"redesign album: animated cover %@", file.lastPathComponent);}@@ -308,6 +315,13 @@ static void *kReadyContext = &kReadyContext;}- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {+ if (context == kListContext) {+ // Only whether the hero is on screen moves while the list scrolls.+ BOOL seen = [self sgr_seen];+ if (seen == _motionSeen) return;+ [self sgr_updateMotion];+ return;+ }if (context != kReadyContext) {[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];return;@@ -345,17 +359,41 @@ static void *kReadyContext = &kReadyContext;// The clip moves under the conditions the player's does (Player/PlayerMotion.x), and only with Auto-Play// Video Previews on; otherwise it holds its frame. Off screen it stops: an album page left on the-// navigation stack would otherwise keep decoding.+// navigation stack would otherwise keep decoding, and so would one scrolled down to its tracks, where the+// hero is above the top of the screen. Scrolled back, the clip goes on from the frame it stopped on.+- (BOOL)sgr_seen {+ UIWindow *window = self.window;+ return window && CGRectIntersectsRect([self convertRect:self.bounds toView:window], window.bounds);+}+- (void)sgr_updateMotion {BOOL front = UIApplication.sharedApplication.applicationState == UIApplicationStateActive;- BOOL may = self.window && front && !SGRReduceMotion() && !NSProcessInfo.processInfo.lowPowerModeEnabled+ BOOL seen = _motionSeen = [self sgr_seen];+ BOOL may = seen && front && !SGRReduceMotion() && !NSProcessInfo.processInfo.lowPowerModeEnabled&& UIAccessibilityIsVideoAutoplayEnabled();+ if (may == _motionOn) return;+ _motionOn = may;if (may) [_player play];else [_player pause];}+// The hero scrolls with the header, so the page's list is where its leaving the screen is heard: its offset,+// watched while the hero has a clip and is in a window, and let go when either goes. A hero with no clip, which+// every album page has, costs the scroll nothing.+- (void)sgr_watchList {+ UIScrollView *list = nil;+ for (UIView *v = _player && self.window ? self.superview : nil; v && !list; v = v.superview) {+ if ([v isKindOfClass:UIScrollView.class]) list = (UIScrollView *)v;+ }+ if (list == _list) return;+ [_list removeObserver:self forKeyPath:@"contentOffset" context:kListContext];+ _list = list;+ [list addObserver:self forKeyPath:@"contentOffset" options:0 context:kListContext];+}+- (void)didMoveToWindow {[super didMoveToWindow];+ [self sgr_watchList];[self sgr_updateMotion];}@@ -617,11 +655,11 @@ static UIColor *washColorOf(UIView *gradient) {// on Home, Search and Library.static void applyWash(UIView *page) {for (UIView *sub in page.subviews) {- NSString *name = NSStringFromClass(sub.class);- if (![name containsString:@"HeaderView"] && ![name containsString:@"HeaderNavigationBar"]) continue;- BOOL wash = ![name containsString:@"NavigationBar"];+ Class cls = sub.class;+ if (!SGClassNamed(cls, @"HeaderView") && !SGClassNamed(cls, @"HeaderNavigationBar")) continue;+ BOOL wash = !SGClassNamed(cls, @"NavigationBar");for (UIView *v in sub.subviews) {- if (![NSStringFromClass(v.class) containsString:@"GradientView"]) continue;+ if (!SGClassNamed(v.class, @"GradientView")) continue;if (wash) {UIColor *color = washColorOf(v);static BOOL logged;diff --git a/tweak/Sources/Redesigned/Artist/ArtistFollow.x b/tweak/Sources/Redesigned/Artist/ArtistFollow.xindex bf614554..af0082a0 100644--- a/tweak/Sources/Redesigned/Artist/ArtistFollow.x+++ b/tweak/Sources/Redesigned/Artist/ArtistFollow.x@@ -1,6 +1,7 @@// 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 <os/lock.h>#import "Core/SGCore.h"#import "Artist.h"@@ -15,29 +16,35 @@@endstatic __weak id sg_provider;+// Guards sg_provider and keepProvider's `logged`; a lock of this file's own, so Spotify's threads binding rows+// never queue behind another file's.+static os_unfair_lock sg_providerLock = OS_UNFAIR_LOCK_INIT;// Called from wherever Spotify reaches for its provider, any thread.static void keepProvider(id provider) {if (!provider || ![provider respondsToSelector:@selector(subscribeCollectionStateForURL:completion:)]) return;+ // Nearly every call brings the provider already kept; a weak load is atomic, and the lock below decides.+ if (provider == sg_provider) return;static NSMutableSet<NSString *> *logged;- @synchronized (NSObject.class) {- if (provider == sg_provider) return;+ NSString *name = nil;+ os_unfair_lock_lock(&sg_providerLock);+ if (provider != sg_provider) {sg_provider = provider;if (!logged) logged = [NSMutableSet set];- NSString *name = NSStringFromClass([provider class]);- if ([logged containsObject:name]) return;- [logged addObject:name];+ name = NSStringFromClass([provider class]);+ if ([logged containsObject:name]) name = nil;+ else [logged addObject:name];}- SGLog(@"redesign artist: collection state from %@", NSStringFromClass([provider class]));+ os_unfair_lock_unlock(&sg_providerLock);+ if (name) SGLog(@"redesign artist: collection state from %@", name);}static __weak id sg_platform;static id currentProvider(void) {- id provider;- @synchronized (NSObject.class) {- provider = sg_provider;- }+ os_unfair_lock_lock(&sg_providerLock);+ id provider = sg_provider;+ os_unfair_lock_unlock(&sg_providerLock);if (!provider && [sg_platform respondsToSelector:@selector(stateProvider)]) {provider = [sg_platform performSelector:@selector(stateProvider)];keepProvider(provider);diff --git a/tweak/Sources/Redesigned/Home/HomeSettings.m b/tweak/Sources/Redesigned/Home/HomeSettings.mindex a2cbac3d..3113dbb9 100644--- a/tweak/Sources/Redesigned/Home/HomeSettings.m+++ b/tweak/Sources/Redesigned/Home/HomeSettings.m@@ -13,6 +13,7 @@ UIViewController *SGRHomeSettingsPage(void) {SGModRow *from = SGMenuRow(@"Cards from", sources, ^NSString *{ return SGRHomeTopPicksFrom() ?: kFirstShelf; }, ^(NSInteger index) {if (index == 0) [NSUserDefaults.standardUserDefaults removeObjectForKey:SGRKeyHomeTopPicksFrom];else [NSUserDefaults.standardUserDefaults setObject:sources[(NSUInteger)index] forKey:SGRKeyHomeTopPicksFrom];+ SGPrefsChanged();});SGModRow *look = SGSwitchRow(@"Home look", @"Top picks, the tinted shortcut pills and the title's glass pill; off, Home as the redesign had it", SGRKeyHomeLook);SGModRow *topPicks = SGRHomeTopPicksRow();diff --git a/tweak/Sources/Redesigned/Home/HomeShelves.m b/tweak/Sources/Redesigned/Home/HomeShelves.mindex 4629b0c4..c51d0a3b 100644--- a/tweak/Sources/Redesigned/Home/HomeShelves.m+++ b/tweak/Sources/Redesigned/Home/HomeShelves.m@@ -141,6 +141,6 @@ BOOL SGRHomeLook(void) {}NSString *SGRHomeTopPicksFrom(void) {- NSString *from = [NSUserDefaults.standardUserDefaults stringForKey:SGRKeyHomeTopPicksFrom];+ NSString *from = SGString(SGRKeyHomeTopPicksFrom);return from.length ? from : nil;}diff --git a/tweak/Sources/Redesigned/Kit/SGRActionRow.m b/tweak/Sources/Redesigned/Kit/SGRActionRow.mindex eddb8a4e..d3424308 100644--- a/tweak/Sources/Redesigned/Kit/SGRActionRow.m+++ b/tweak/Sources/Redesigned/Kit/SGRActionRow.m@@ -215,6 +215,11 @@ static BOOL indicatorOn(UIView *button, BOOL *found) {[self addTarget:self action:@selector(sgr_down) forControlEvents:UIControlEventTouchDown];[self addTarget:self action:@selector(sgr_up) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside | UIControlEventTouchCancel];[self addTarget:self action:@selector(sgr_tap) forControlEvents:UIControlEventTouchUpInside];+ // Spotify in the background plays on with the page in its window, so the state is not read there: the+ // poll goes with the app and the way back in reads again, as the way into the window does.+ NSNotificationCenter *center = NSNotificationCenter.defaultCenter;+ [center addObserver:self selector:@selector(sgr_stopFollowing) name:UIApplicationWillResignActiveNotification object:nil];+ [center addObserver:self selector:@selector(sgr_readAgain) name:UIApplicationDidBecomeActiveNotification object:nil];return self;}@@ -234,14 +239,23 @@ static BOOL indicatorOn(UIView *button, BOOL *found) {- (void)didMoveToWindow {[super didMoveToWindow];+ [self sgr_readAgain];+}++// 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.+- (void)sgr_readAgain {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];else [self sgr_followDownload:0];}+- (void)sgr_stopFollowing {+ [self sgr_followDownload:0];+}+- (void)dealloc {+ [NSNotificationCenter.defaultCenter removeObserver:self];[_downloadTimer invalidate];}@@ -273,7 +287,7 @@ static BOOL indicatorOn(UIView *button, BOOL *found) {// Spotify lays nothing out that the page hears as a download moves on, so the state is read again:// twice a second while one runs, for the ring, and now and then otherwise, for one started or removed- // from elsewhere (the ⋯ sheet). Only while the button is on screen.+ // from elsewhere (the ⋯ sheet). Only while the button is on screen and the app is active.BOOL running = state == SGRDownloadWaiting || state == SGRDownloadDownloading;[self sgr_followDownload:self.window ? (running ? 0.5 : 2) : 0];return YES;@@ -317,7 +331,8 @@ static BOOL indicatorOn(UIView *button, BOOL *found) {// Reads the state again every `interval` seconds; 0 stops.- (void)sgr_followDownload:(NSTimeInterval)interval {- if (interval <= 0) {+ // A layout while Spotify plays in the background feeds the button too; becoming active reads it again.+ if (interval <= 0 || UIApplication.sharedApplication.applicationState != UIApplicationStateActive) {[_downloadTimer invalidate];_downloadTimer = nil;return;diff --git a/tweak/Sources/Redesigned/Kit/SGRAmoled.x b/tweak/Sources/Redesigned/Kit/SGRAmoled.xindex cb469b96..3c1130eb 100644--- a/tweak/Sources/Redesigned/Kit/SGRAmoled.x+++ b/tweak/Sources/Redesigned/Kit/SGRAmoled.x@@ -36,18 +36,22 @@ static CGColorRef copyBlack(CGColorRef color) {%hook CAGradientLayer- (void)setColors:(NSArray *)colors {- NSMutableArray *mapped = [[NSMutableArray alloc] initWithCapacity:colors.count];+ // Most gradients hold no base gray: those go through as they are, and a copy is made only from the first gray on.+ NSMutableArray *mapped = nil;+ NSUInteger index = 0;for (id entry in colors) {CGColorRef color = (__bridge CGColorRef)entry;- if (!isBaseGrey(color)) {+ if (isBaseGrey(color)) {+ if (!mapped) mapped = [[colors subarrayWithRange:NSMakeRange(0, index)] mutableCopy];+ CGColorRef black = copyBlack(color);+ [mapped addObject:(__bridge id)black];+ CGColorRelease(black);+ } else if (mapped) {[mapped addObject:entry];- continue;}- CGColorRef black = copyBlack(color);- [mapped addObject:(__bridge id)black];- CGColorRelease(black);+ index++;}- %orig(colors ? mapped : nil);+ %orig(mapped ?: colors);}%enddiff --git a/tweak/Sources/Redesigned/Kit/SGRDownload.m b/tweak/Sources/Redesigned/Kit/SGRDownload.mindex 72d85b67..506160d4 100644--- a/tweak/Sources/Redesigned/Kit/SGRDownload.m+++ b/tweak/Sources/Redesigned/Kit/SGRDownload.m@@ -99,24 +99,34 @@ BOOL SGRReadDownload(UIView *source, SGRDownloadState *state, CGFloat *progress)// Downloading with nothing to show how far is the ring turning, as while waiting.if (result == SGRDownloadDownloading && value < 0) result = SGRDownloadWaiting;- // Said once for each combination read, so the first device run shows which of the two signals moved.- static NSMutableSet<NSString *> *logged;- if (!logged) logged = [NSMutableSet set];- NSString *mark = [NSString stringWithFormat:@"%@ %d %d", button.accessibilityIdentifier, current ? *current : -1, stored != NULL];- if (![logged containsObject:mark]) {- [logged addObject:mark];- SGLog(@"redesign kit: download %@, model %@ state %d progress %@, label \"%@\" value \"%@\"",- button.accessibilityIdentifier, owner ? NSStringFromClass(object_getClass(owner)) : @"missing",- current ? *current : -1, stored ? (stored[8] == 0 ? @"set" : @"none") : @"unreadable",- button.accessibilityLabel, button.accessibilityValue);- }- if (modelled && named && modelState != said && !(modelState == SGRDownloadWaiting && said == SGRDownloadDownloading)) {- static NSMutableSet<NSString *> *disagreed;- if (!disagreed) disagreed = [NSMutableSet set];- if (![disagreed containsObject:mark]) {- [disagreed addObject:mark];- SGLog(@"redesign kit: download model says %d where the identifier says %@, the model wins", *current,- button.accessibilityIdentifier);+ // Said once for each combination read, so the first device run shows which of the two signals moved. The+ // combination read last was said already, so the timers' reads of a button at rest build no mark.+ static NSString *lastIdentifier;+ static int lastCurrent = -2;+ static BOOL lastStored;+ NSString *identifier = button.accessibilityIdentifier;+ int currentValue = current ? *current : -1;+ if (currentValue != lastCurrent || (stored != NULL) != lastStored || ![identifier isEqualToString:lastIdentifier]) {+ lastIdentifier = identifier;+ lastCurrent = currentValue;+ lastStored = stored != NULL;+ static NSMutableSet<NSString *> *logged;+ if (!logged) logged = [NSMutableSet set];+ NSString *mark = [NSString stringWithFormat:@"%@ %d %d", identifier, currentValue, stored != NULL];+ if (![logged containsObject:mark]) {+ [logged addObject:mark];+ SGLog(@"redesign kit: download %@, model %@ state %d progress %@, label \"%@\" value \"%@\"",+ identifier, owner ? NSStringFromClass(object_getClass(owner)) : @"missing",+ currentValue, stored ? (stored[8] == 0 ? @"set" : @"none") : @"unreadable",+ button.accessibilityLabel, button.accessibilityValue);+ }+ if (modelled && named && modelState != said && !(modelState == SGRDownloadWaiting && said == SGRDownloadDownloading)) {+ static NSMutableSet<NSString *> *disagreed;+ if (!disagreed) disagreed = [NSMutableSet set];+ if (![disagreed containsObject:mark]) {+ [disagreed addObject:mark];+ SGLog(@"redesign kit: download model says %d where the identifier says %@, the model wins", *current, identifier);+ }}}if (state) *state = result;diff --git a/tweak/Sources/Redesigned/Kit/SGRRepaint.x b/tweak/Sources/Redesigned/Kit/SGRRepaint.xindex 126f3b63..2d9bce97 100644--- a/tweak/Sources/Redesigned/Kit/SGRRepaint.x+++ b/tweak/Sources/Redesigned/Kit/SGRRepaint.x@@ -36,9 +36,19 @@ enum { kInNowPlaying = 1, kInLyrics = 2, kInPage = 4 };}if (inside & kInNowPlaying) {// Its size is judged when the bar picks its card: Spotify can paint a card before it sizes it.- if (SGIsVisibleColor(color) && ![sgr_nowPlayingPainted containsObject:view]) {- [sgr_nowPlayingPainted addObject:view];- dispatch_async(dispatch_get_main_queue(), ^{ [nowPlaying.superview setNeedsLayout]; });+ if (SGIsVisibleColor(color)) {+ // The bar reads the table on main, and Spotify also paints layers off main.+ void (^learn)(UIView *) = ^(UIView *painted) {+ if (!painted || [sgr_nowPlayingPainted containsObject:painted]) return;+ [sgr_nowPlayingPainted addObject:painted];+ dispatch_async(dispatch_get_main_queue(), ^{ [nowPlaying.superview setNeedsLayout]; });+ };+ if (NSThread.isMainThread) {+ learn(view);+ } else {+ __weak UIView *weakView = view;+ dispatch_async(dispatch_get_main_queue(), ^{ learn(weakView); });+ }}color = NULL;} else if (inside & (kInLyrics | kInPage)) {diff --git a/tweak/Sources/Redesigned/Kit/SGRRestyle.h b/tweak/Sources/Redesigned/Kit/SGRRestyle.hindex c11cccb8..586267f0 100644--- a/tweak/Sources/Redesigned/Kit/SGRRestyle.h+++ b/tweak/Sources/Redesigned/Kit/SGRRestyle.h@@ -47,6 +47,9 @@ BOOL SGRObserveLayout(UIView *view, void (^laidOut)(UIView *view));// 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);+// SGRFindByIdentifier for every identifier at once, in one walk (Core's SGFindRememberedAll): `found[i]` is+// identifiers[i]'s view or nil. For lookups made back to back with nothing between them that changes the tree.+void SGRFindByIdentifiers(UIView *root, NSArray<NSString *> *identifiers, const void *const cacheKeys[], UIView *__strong found[]);// Whether `view` is the profile avatar that opens the side drawer, in the Home, Search and Library headers. Known by// its identifier, which every version gives it: 9.1.88 draws it in an AdaptiveFaceContainer, 9.1.90 in an Encorediff --git a/tweak/Sources/Redesigned/Kit/SGRRestyle.m b/tweak/Sources/Redesigned/Kit/SGRRestyle.mindex f61f9ee3..67bd959a 100644--- a/tweak/Sources/Redesigned/Kit/SGRRestyle.m+++ b/tweak/Sources/Redesigned/Kit/SGRRestyle.m@@ -277,6 +277,12 @@ UIView *SGRFindByIdentifier(UIView *root, NSString *identifier, const void *cachreturn SGFindRemembered(root, cacheKey, ^BOOL(UIView *v) { return identifierMatches(v.accessibilityIdentifier, identifier); });}+void SGRFindByIdentifiers(UIView *root, NSArray<NSString *> *identifiers, const void *const cacheKeys[], UIView *__strong found[]) {+ SGFindRememberedAll(root, identifiers.count, cacheKeys, ^BOOL(NSUInteger i, UIView *v) {+ return identifierMatches(v.accessibilityIdentifier, identifiers[i]);+ }, found);+}+@implementation SGRShadowPlate {CGRect _pathBounds;}@@ -349,7 +355,7 @@ static const CGFloat kPaintedShare = 0.75;// same way, and its photo is not to fade (device 2026-10-08).static char kRowFadeKey;static BOOL isFooter(UIView *view) {- return [NSStringFromClass(view.class) containsString:@"ListSectionFooter"];+ return SGClassNamed(view.class, @"ListSectionFooter");}static void fadeRowsAbove(UIView *gradient) {diff --git a/tweak/Sources/Redesigned/Kit/SGRTokens.m b/tweak/Sources/Redesigned/Kit/SGRTokens.mindex 15aab681..512dd8a0 100644--- a/tweak/Sources/Redesigned/Kit/SGRTokens.m+++ b/tweak/Sources/Redesigned/Kit/SGRTokens.m@@ -66,9 +66,20 @@ UIColor *SGRElevated(UIColor *field) {UIFont *SGRFont(UIFontTextStyle style, UIFontWeight weight, UIContentSizeCategory largest) {UIContentSizeCategory current = UIApplication.sharedApplication.preferredContentSizeCategory;if (largest && UIContentSizeCategoryCompareToCategory(current, largest) == NSOrderedDescending) current = largest;+ // Asked for on every layout pass of the Search and Library headers. A font is immutable and the same inputs+ // give the same one, so each is kept per input; the live category above and Bold Text are read on every call,+ // so a Dynamic Type change is a new key at once.+ // A string key: an array's hash is its count, so array keys would all collide.+ static NSMutableDictionary<NSString *, UIFont *> *fonts;+ if (!fonts) fonts = [NSMutableDictionary dictionary];+ NSString *key = [NSString stringWithFormat:@"%@|%g|%@|%@|%d", style, weight, largest ?: @"", current ?: @"", UIAccessibilityIsBoldTextEnabled()];+ UIFont *font = fonts[key];+ if (font) return font;UITraitCollection *traits = [UITraitCollection traitCollectionWithPreferredContentSizeCategory:current];CGFloat size = [UIFont preferredFontForTextStyle:style compatibleWithTraitCollection:traits].pointSize;- return [UIFont systemFontOfSize:size weight:weight];+ font = [UIFont systemFontOfSize:size weight:weight];+ fonts[key] = font;+ return font;}UIFont *SGRMonospacedDigitsFont(UIFont *font) {diff --git a/tweak/Sources/Redesigned/Library/LibraryHeader.x b/tweak/Sources/Redesigned/Library/LibraryHeader.xindex bf5124e5..62ef90b1 100644--- a/tweak/Sources/Redesigned/Library/LibraryHeader.x+++ b/tweak/Sources/Redesigned/Library/LibraryHeader.x@@ -78,10 +78,12 @@ void SGRLibraryClearScrim(UIView *header) {// The header's controls, in the order they are to read from the leading edge, leaving out what this build does// not have, what Spotify has hidden (a folder shows play or pause, never both) and what has not been laid out.-static NSMutableArray<UIView *> *controlsIn(UIView *header, NSArray<NSString *> *identifiers, const void **keys) {+static NSMutableArray<UIView *> *controlsIn(UIView *header, NSArray<NSString *> *identifiers, const void *const keys[]) {+ UIView *controls[identifiers.count];+ SGRFindByIdentifiers(header, identifiers, keys, controls);NSMutableArray<UIView *> *found = [NSMutableArray array];for (NSUInteger i = 0; i < identifiers.count; i++) {- UIView *control = SGRFindByIdentifier(header, identifiers[i], keys[i]);+ UIView *control = controls[i];if (control && !control.hidden && control.alpha > 0.01 && control.bounds.size.width > 1) [found addObject:control];}return found;diff --git a/tweak/Sources/Redesigned/NowPlayingBar/BarConnect.x b/tweak/Sources/Redesigned/NowPlayingBar/BarConnect.xindex c69c7d80..af66bd6a 100644--- a/tweak/Sources/Redesigned/NowPlayingBar/BarConnect.x+++ b/tweak/Sources/Redesigned/NowPlayingBar/BarConnect.x@@ -7,15 +7,16 @@#import "Core/SGCore.h"#import "NowPlayingBar.h"+// `marker` is a literal: SGClassNamed keeps its answers by the marker's address.static BOOL insideClass(UIView *view, NSString *marker) {- for (UIView *v = view; v; v = v.superview) if ([NSStringFromClass(v.class) containsString:marker]) return YES;+ for (UIView *v = view; v; v = v.superview) if (SGClassNamed(v.class, marker)) return YES;return NO;}static void hideConnectButton(UIView *bar) {SGForEachView(bar, ^(UIView *v) {- NSString *name = NSStringFromClass(v.class);- if (![name containsString:@"ConnectButtonView"] && ![name containsString:@"ConnectStateView"]) return;+ Class cls = v.class;+ if (!SGClassNamed(cls, @"ConnectButtonView") && !SGClassNamed(cls, @"ConnectStateView")) return;if (insideClass(v, @"InformationContainer")) return;UIView *item = v;while (item.superview && ![item.superview isKindOfClass:UIStackView.class]) item = item.superview;diff --git a/tweak/Sources/Redesigned/NowPlayingBar/NowPlayingBar.x b/tweak/Sources/Redesigned/NowPlayingBar/NowPlayingBar.xindex b5f7b0e4..65583d2b 100644--- a/tweak/Sources/Redesigned/NowPlayingBar/NowPlayingBar.x+++ b/tweak/Sources/Redesigned/NowPlayingBar/NowPlayingBar.x@@ -90,7 +90,7 @@ static UIView *trackMarker(UIView *bar) {__block UIView *info = nil, *artwork = nil;SGForEachView(bar, ^(UIView *v) {if (info || inStrip(v, bar)) return;- if ([NSStringFromClass(v.class) containsString:@"InformationContainer"]) info = v;+ if (SGClassNamed(v.class, @"InformationContainer")) info = v;CGSize size = v.bounds.size;BOOL square = size.width >= 36 && size.width <= 48 && fabs(size.width - size.height) < 1;if (!artwork && square && ![v isKindOfClass:UIControl.class]) artwork = v;@@ -523,7 +523,7 @@ void SGRNowPlayingBarMoving(BOOL moving) {// frame from those.static BOOL inSheet(UIView *view) {for (UIView *v = view.superview; v; v = v.superview) {- if ([v.accessibilityIdentifier isEqualToString:@"sheet-view"] || [NSStringFromClass(v.class) containsString:@"SheetImpl"]) return YES;+ if ([v.accessibilityIdentifier isEqualToString:@"sheet-view"] || SGClassNamed(v.class, @"SheetImpl")) return YES;}return NO;}@@ -689,7 +689,7 @@ static void styleNowPlayingBar(UIViewController *container) {- (void)viewDidLayoutSubviews {%orig;UIViewController *parent = ((UIViewController *)self).parentViewController;- if ([NSStringFromClass(parent.class) containsString:@"NowPlayingBarContainer"]) styleNowPlayingBar(parent);+ if (SGClassNamed(parent.class, @"NowPlayingBarContainer")) styleNowPlayingBar(parent);}%enddiff --git a/tweak/Sources/Redesigned/Player/PlayerArtwork.x b/tweak/Sources/Redesigned/Player/PlayerArtwork.xindex 066d6a54..51e558aa 100644--- a/tweak/Sources/Redesigned/Player/PlayerArtwork.x+++ b/tweak/Sources/Redesigned/Player/PlayerArtwork.x@@ -253,9 +253,9 @@ static void watchHold(UIView *tilt) {%hook _TtC35CreativeWorkCommons_CoverArtTiltKit16CoverArtTiltView- (void)layoutSubviews {UIView *tilt = (UIView *)self;- BOOL player = inCoverCell(tilt);%orig;- if (tilt.bounds.size.width < kCoverMinWidth || !player) return;+ // The width first: the bar's and the pages' small tilt views skip the walk up to the cell.+ if (tilt.bounds.size.width < kCoverMinWidth || !inCoverCell(tilt)) return;UIView *cover = coverIn(tilt);if (!cover) return;[sg_tilts addObject:tilt];diff --git a/tweak/Sources/Redesigned/Player/PlayerCoverAccent.x b/tweak/Sources/Redesigned/Player/PlayerCoverAccent.xindex 8e4c0ce9..a4bae100 100644--- a/tweak/Sources/Redesigned/Player/PlayerCoverAccent.x+++ b/tweak/Sources/Redesigned/Player/PlayerCoverAccent.x@@ -321,7 +321,8 @@ void SGRPlayerSetCoverAccent(UIColor *cover) {%orig;if (sg_cover < 0 && !objc_getAssociatedObject(self, &kTintedKey)) return;UIView *stack = sg_stack, *bar = sgr_nowPlayingRoot, *button = (UIView *)self;- if (stack && [button isDescendantOfView:stack]) SGRPlayerPaintCover(button);+ // A descendant shares the stack's window, so a button in another (or the stack off screen) skips the walk up.+ if (stack && button.window == stack.window && [button isDescendantOfView:stack]) SGRPlayerPaintCover(button);else if (bar && (isBarButton(button) || isBarButton(button.superview)) && [button isDescendantOfView:bar]) paintTree(button);}%enddiff --git a/tweak/Sources/Redesigned/Player/PlayerFooter.x b/tweak/Sources/Redesigned/Player/PlayerFooter.xindex 840a68ed..58b99fb3 100644--- a/tweak/Sources/Redesigned/Player/PlayerFooter.x+++ b/tweak/Sources/Redesigned/Player/PlayerFooter.x@@ -296,7 +296,7 @@ UIView *SGRPlayerConnectGlyphIn(UIView *host, UIView *connect) {dispatch_async(dispatch_get_main_queue(), ^{ [weakHost setNeedsLayout]; });}SGForEachView(connect, ^(UIView *view) {- if ([view isKindOfClass:UILabel.class] || [NSStringFromClass(view.class) containsString:@"MarqueeLabel"]) SGRPlayerVanish(view);+ if ([view isKindOfClass:UILabel.class] || SGClassNamed(view.class, @"MarqueeLabel")) SGRPlayerVanish(view);});if (glyph) standInForConnect((UIImageView *)glyph);return glyph;@@ -360,8 +360,8 @@ void SGRPlayerLowerRow(UIView *row) {// Only the controls, and only straight above: a volume row between them keeps its place and theirs.UIView *above = rowAbove(row);// The ordinary player's controls unit, or the AI DJ's head unit (DJPlayer.x), which holds the same buttons.- NSString *unit = NSStringFromClass(unitOf(above).class);- BOOL controls = [unit containsString:@"PlaybackControlsElementsUnit"] || [unit containsString:@"DJMHeadUnitViewController"];+ Class unit = unitOf(above).class;+ BOOL controls = SGClassNamed(unit, @"PlaybackControlsElementsUnit") || SGClassNamed(unit, @"DJMHeadUnitViewController");// With the volume row, the controls stay where Spotify put them and the row takes the room the footer leaves.// The volume row is placed against the controls where they would stand for it; one that does not show leaves them// following the footer as they do without it.@@ -408,19 +408,20 @@ void SGRPlayerLowerRow(UIView *row) {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));- // "From <friend>" on a track a friend shared sits in the middle of the row, over Connect, which the- // row moves there; the Music app has no such chip.- UIView *sharedBy = SGRFindByIdentifier(host, @"Components.UI.SharedByChip", &kSharedByKey);- SGRPlayerVanish(sharedBy);- SGRPlayerVanish(arrangedAround(sharedBy, host));+ // Share; Spotify's clip button, hidden in every clean tree, which would turn up where the queue moves to; and+ // "From <friend>" on a track a friend shared, which sits in the middle of the row, over Connect, which the row+ // moves there (the Music app has no such chip). Found in one walk: nothing between them touches the tree.+ static const void *const goneKeys[] = {&kShareKey, &kTrimmerKey, &kSharedByKey};+ UIView *gone[3];+ static NSArray<NSString *> *goneIdentifiers;+ if (!goneIdentifiers) goneIdentifiers = @[@"ShareButtonNowPlayingView", @"nowplaying-npv-media-trimmer-navigation-button", @"Components.UI.SharedByChip"];+ SGRFindByIdentifiers(host, goneIdentifiers, goneKeys, gone);+ UIView *share = gone[0];+ for (NSUInteger i = 0; i < 3; i++) {+ SGRPlayerVanish(gone[i]);+ // The arranged view goes too: a view that takes touches swallows them even with nothing on it.+ SGRPlayerVanish(arrangedAround(gone[i], host));+ }SGRGlyphButton *lyrics = SGRPlayerLyricsGlyphIn(host);lyrics.bounds = CGRectMake(0, 0, 44, 44);diff --git a/tweak/Sources/Redesigned/Player/PlayerLyrics.x b/tweak/Sources/Redesigned/Player/PlayerLyrics.xindex 798e4b51..a0c0d536 100644--- a/tweak/Sources/Redesigned/Player/PlayerLyrics.x+++ b/tweak/Sources/Redesigned/Player/PlayerLyrics.x@@ -695,7 +695,8 @@ void SGRPlayerToggleLyrics(void) {static void replace(void) {UIView *host = sg_host;if (!host || sg_moving) return; // a pass in the middle of the transition would cut it short- SGRLyricsLayout l = layoutIn(host);+ // Closed, placeTitleRow reads nothing of the layout, so the cover is not measured for it.+ SGRLyricsLayout l = sg_open ? layoutIn(host) : (SGRLyricsLayout){0};if (sg_open && !l.ok) return;placeTitleRow(l);sg_floating.viewIfLoaded.alpha = sg_open ? 0 : 1;diff --git a/tweak/Sources/Redesigned/Player/PlayerScroll.x b/tweak/Sources/Redesigned/Player/PlayerScroll.xindex a15ff264..43903d8e 100644--- a/tweak/Sources/Redesigned/Player/PlayerScroll.x+++ b/tweak/Sources/Redesigned/Player/PlayerScroll.x@@ -22,7 +22,7 @@ static __weak UIScrollView *sg_loggedList;// list's own layout, since the first scroll waits for a finger.static void hideTopEdge(UIScrollView *list) {if (@available(iOS 26.0, *)) {- if (!list.topEdgeEffect.hidden && [list.accessibilityIdentifier isEqualToString:kListIdentifier]) list.topEdgeEffect.hidden = YES;+ if ([list.accessibilityIdentifier isEqualToString:kListIdentifier] && !list.topEdgeEffect.hidden) list.topEdgeEffect.hidden = YES;}}diff --git a/tweak/Sources/Redesigned/Player/PlayerVisualiser.m b/tweak/Sources/Redesigned/Player/PlayerVisualiser.mindex 0a93868b..891d1772 100644--- a/tweak/Sources/Redesigned/Player/PlayerVisualiser.m+++ b/tweak/Sources/Redesigned/Player/PlayerVisualiser.m@@ -119,6 +119,9 @@ static NSDictionary *noActions(void) {uint64_t _generation;CFTimeInterval _fresh, _last;NSUInteger _palette;+ // What draw last drew from: the same again sets the same paths and opacity, so a hill at rest hands the render+ // server nothing. The pulse is kept as the opacity it rounds to, since it decays on long after that stands still.+ struct { CGRect bounds; CGFloat baseline, screenHeight; float front[kBands], back[kBands], opacity; } _drawn;}// As PlayerMotion.x: what fades is the effect view's effect, never its alpha or an ancestor's.@@ -433,6 +436,15 @@ static void shape(CAShapeLayer *layer, const float *bands, CGFloat width, CGFloa- (void)draw {CGRect bounds = self.bounds;if (bounds.size.width <= 0 || bounds.size.height <= 0) return;+ float opacity = kPulseFloor + (1 - kPulseFloor) * _pulse;+ if (CGRectEqualToRect(bounds, _drawn.bounds) && _baseline == _drawn.baseline && _screenHeight == _drawn.screenHeight+ && opacity == _drawn.opacity && !memcmp(_front, _drawn.front, sizeof _front) && !memcmp(_back, _drawn.back, sizeof _back)) return;+ _drawn.bounds = bounds;+ _drawn.baseline = _baseline;+ _drawn.screenHeight = _screenHeight;+ _drawn.opacity = opacity;+ memcpy(_drawn.front, _front, sizeof _front);+ memcpy(_drawn.back, _back, sizeof _back);CGFloat baseline = _baseline > 0 ? _baseline : bounds.size.height;CGFloat screen = _screenHeight > 0 ? _screenHeight : bounds.size.height;CGFloat foot = MAX(baseline, bounds.size.height), rest = round(screen * kRestHeight);@@ -440,7 +452,7 @@ static void shape(CAShapeLayer *layer, const float *bands, CGFloat width, CGFloa[CATransaction setDisableActions:YES];shape(_backShape, _back, bounds.size.width, baseline, foot, screen * kBackHeight, rest * 1.5);shape(_frontShape, _front, bounds.size.width, baseline, foot, screen * kFrontHeight, rest);- _frontFill.opacity = kPulseFloor + (1 - kPulseFloor) * _pulse;+ _frontFill.opacity = opacity;_crestFade.startPoint = CGPointMake(0.5, (baseline - screen * kFadeTop) / bounds.size.height);_crestFade.endPoint = CGPointMake(0.5, (baseline - screen * kFadeFoot) / bounds.size.height);[CATransaction commit];diff --git a/tweak/Sources/Redesigned/Playlist/PlaylistHeader.x b/tweak/Sources/Redesigned/Playlist/PlaylistHeader.xindex 86e1d12e..2672718a 100644--- a/tweak/Sources/Redesigned/Playlist/PlaylistHeader.x+++ b/tweak/Sources/Redesigned/Playlist/PlaylistHeader.x@@ -275,6 +275,9 @@ static BOOL modelFlag(id model, NSString *name, BOOL fallback) {// A description is HTML: links to other playlists as <a> and entities for quotes and ampersands.static NSString *plainText(NSString *html) {if (!html.length) return nil;+ // The header's passes hand the same description over on every step of the collapse.+ static NSString *lastHTML, *lastText;+ if ([html isEqualToString:lastHTML]) return lastText;static NSRegularExpression *tags;if (!tags) tags = [NSRegularExpression regularExpressionWithPattern:@"<[^>]+>" options:0 error:NULL];NSMutableString *text = [[tags stringByReplacingMatchesInString:html options:0 range:NSMakeRange(0, html.length)@@ -285,7 +288,9 @@ static NSString *plainText(NSString *html) {[text replaceOccurrencesOfString:entity withString:entities[entity] options:0 range:NSMakeRange(0, text.length)];}NSString *trimmed = [text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];- return trimmed.length ? trimmed : nil;+ lastHTML = [html copy];+ lastText = trimmed.length ? trimmed : nil;+ return lastText;}static NSString *firstText(UIView *root, UIView *skip) {@@ -305,7 +310,7 @@ static NSString *firstText(UIView *root, UIView *skip) {static NSString *creatorIn(UIView *block) {__block UIView *facepile = nil;SGForEachView(block, ^(UIView *v) {- if (!facepile && [NSStringFromClass(v.class) containsString:@"FacepileView"]) facepile = v;+ if (!facepile && SGClassNamed(v.class, @"FacepileView")) facepile = v;});UIView *row = facepile.superview;for (NSUInteger level = 0; row && row != block && level < 3; level++, row = row.superview) {@@ -486,7 +491,7 @@ static void applyScrims(UIView *headerRoot) {if (!bar) bar = NSClassFromString(@"_TtC28EncoreConsumerMobile_BaseKit19HeaderNavigationBar");UIView *navigation = firstOfClass(headerRoot, bar);for (UIView *sub in navigation.subviews) {- if (![NSStringFromClass(sub.class) containsString:@"GradientView"]) continue;+ if (!SGClassNamed(sub.class, @"GradientView")) continue;conceal(sub);objc_setAssociatedObject(headerRoot, &kBarScrimKey, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC);}@@ -512,7 +517,7 @@ static UIView *applyBackground(UIView *layout) {SGRPlaylistHero *hero = objc_getAssociatedObject(plane, &kHeroKey);SGForEachView(container, ^(UIView *v) {if (hero && (v == hero || [v isDescendantOfView:hero])) return;- if ([NSStringFromClass(v.class) containsString:@"GradientView"]) {+ if (SGClassNamed(v.class, @"GradientView")) {conceal(v);return;}diff --git a/tweak/Sources/Redesigned/Search/SearchPage.x b/tweak/Sources/Redesigned/Search/SearchPage.xindex b065d426..1fd547a2 100644--- a/tweak/Sources/Redesigned/Search/SearchPage.x+++ b/tweak/Sources/Redesigned/Search/SearchPage.x@@ -32,12 +32,13 @@ static void vanish(UIView *view) {if (!view) return;if (view.alpha != 0) view.alpha = 0;if (view.userInteractionEnabled) view.userInteractionEnabled = NO;- view.accessibilityElementsHidden = YES;+ if (!view.accessibilityElementsHidden) view.accessibilityElementsHidden = YES;}+// `marker` is a literal (SGClassNamed).static UIView *childNamed(UIView *host, NSString *marker) {for (UIView *sub in host.subviews) {- if ([NSStringFromClass(sub.class) containsString:marker]) return sub;+ if (SGClassNamed(sub.class, marker)) return sub;}return nil;}diff --git a/tweak/Sources/Redesigned/Search/SearchSections.x b/tweak/Sources/Redesigned/Search/SearchSections.xindex 093e1096..c4d34e13 100644--- a/tweak/Sources/Redesigned/Search/SearchSections.x+++ b/tweak/Sources/Redesigned/Search/SearchSections.x@@ -173,8 +173,9 @@ static void measureSoon(void) {if (!collapsed) {sg_changes++;measureSoon();+ // Described on the first drop only: a cell measured again while collapsed holds the same content.+ logOnce([@"dropped " stringByAppendingString:describe(root)]);}- logOnce([@"dropped " stringByAppendingString:describe(root)]);} else if (kind == SGRSearchKindKeep && collapsed) {// Cells are reused across kinds: one collapsed before holds a card now.expand(cell);diff --git a/tweak/Sources/Settings/SGGlowSwitch.m b/tweak/Sources/Settings/SGGlowSwitch.mindex 5ba2065e..a17e7259 100644--- a/tweak/Sources/Settings/SGGlowSwitch.m+++ b/tweak/Sources/Settings/SGGlowSwitch.m@@ -186,6 +186,9 @@ static CAShapeLayer *newStroke(CGFloat width) {turn.duration = kTurn;turn.repeatCount = HUGE_VALF;turn.removedOnCompletion = NO;+ // A turn this slow needs no more than the display's base rate (SGMarquee does the same): each frame of it+ // is the blur and three masks drawn again.+ turn.preferredFrameRateRange = CAFrameRateRangeMake(30, 60, 60);[colors addAnimation:turn forKey:kTurnKey];}}diff --git a/tweak/Sources/Shared/AdBlock/AdBlock.m b/tweak/Sources/Shared/AdBlock/AdBlock.mindex 2219b7ec..7430e6b7 100644--- a/tweak/Sources/Shared/AdBlock/AdBlock.m+++ b/tweak/Sources/Shared/AdBlock/AdBlock.m@@ -163,7 +163,7 @@ static NSMutableDictionary<NSString *, NSNumber *> *countsLocked(void) {if (sg_counts.count && !sg_counts[checkedKey(@"Requests")]) {[sg_counts removeAllObjects];sg_counts[checkedKey(@"Requests")] = @0;- [NSUserDefaults.standardUserDefaults setObject:sg_counts forKey:kCounts];+ SGPrefsWriteUnmemoized(^{ [NSUserDefaults.standardUserDefaults setObject:sg_counts forKey:kCounts]; });}}return sg_counts;@@ -174,7 +174,7 @@ static NSMutableDictionary<NSString *, NSNumber *> *countsLocked(void) {// half a minute at most. Called under the lock.static void saveLocked(BOOL now) {if (!sg_unsaved || (!now && CFAbsoluteTimeGetCurrent() - sg_savedAt < 30)) return;- [NSUserDefaults.standardUserDefaults setObject:countsLocked() forKey:kCounts];+ SGPrefsWriteUnmemoized(^{ [NSUserDefaults.standardUserDefaults setObject:countsLocked() forKey:kCounts]; });sg_unsaved = NO;sg_savedAt = CFAbsoluteTimeGetCurrent();}diff --git a/tweak/Sources/Shared/AdBlock/AdHubs.x b/tweak/Sources/Shared/AdBlock/AdHubs.xindex c2353a4c..808f5429 100644--- a/tweak/Sources/Shared/AdBlock/AdHubs.x+++ b/tweak/Sources/Shared/AdBlock/AdHubs.x@@ -51,7 +51,11 @@ static BOOL isAd(NSDictionary *component) {id kind = component[@"component"];if ([kind isKindOfClass:NSDictionary.class]) {NSString *ns = kind[@"namespace"], *name = kind[@"name"];- if (adWord(ns) || adWord(name) || adWord([NSString stringWithFormat:@"%@:%@", ns, name])) return YES;+ if (adWord(ns) || adWord(name)) return YES;+ // No ad word has a ':', so in two strings the joined form only adds an intent word in one next to a+ // surface word in the other; a part that is not a string is matched on its description, as before.+ BOOL strings = (!ns || [ns isKindOfClass:NSString.class]) && (!name || [name isKindOfClass:NSString.class]);+ if ((upsells || !strings) && adWord([NSString stringWithFormat:@"%@:%@", ns, name])) return YES;} else if (adWord(kind)) {return YES;}diff --git a/tweak/Sources/Shared/AdBlock/AdNetwork.x b/tweak/Sources/Shared/AdBlock/AdNetwork.xindex 5599cdab..a831bde0 100644--- a/tweak/Sources/Shared/AdBlock/AdNetwork.x+++ b/tweak/Sources/Shared/AdBlock/AdNetwork.x@@ -284,10 +284,12 @@ static void complete(id<NSURLSessionDataDelegate> delegate, NSURLSession *sessio%hook NSURLSessionTask- (void)resume {NSURL *url = self.currentRequest.URL ?: self.originalRequest.URL;- NSString *host = url.host.lowercaseString ?: @"", *path = url.path.lowercaseString ?: @"";+ NSString *host = url.host.lowercaseString ?: @"";BOOL spotify = has(host, @"spotify") || has(host, @"spclient");- if (spotify && elapsed() > 30 && (has(path, @"deletetoken") || has(path, @"signup/public") || has(path, @"pses/screenconfig")- || isCustomize(path) || has(host, @"apresolve"))) {+ // The path is lowercased only for the requests the tests below can cancel.+ NSString *path = spotify && elapsed() > 30 ? url.path.lowercaseString ?: @"" : nil;+ if (path && (has(path, @"deletetoken") || has(path, @"signup/public") || has(path, @"pses/screenconfig")+ || isCustomize(path) || has(host, @"apresolve"))) {SGAdBlockSawOne(@"Requests");SGAdBlockCountOne(@"Requests");SGLog(@"canceled %@%@ before it left", host, path);diff --git a/tweak/Sources/Shared/AdBlock/Premium.m b/tweak/Sources/Shared/AdBlock/Premium.mindex 77fccbeb..f517799e 100644--- a/tweak/Sources/Shared/AdBlock/Premium.m+++ b/tweak/Sources/Shared/AdBlock/Premium.m@@ -372,10 +372,22 @@ static const SGRule rules[] = {{"core-player", "disable_smart_shuffle_when_in_jam", SGRuleForce, NO, NULL},};static const size_t ruleCount = sizeof(rules) / sizeof(rules[0]);+// The rules' scope and name as NSStrings, made once: every rule is tried against every entry of a config.+static NSString *ruleScopes[sizeof(rules) / sizeof(rules[0])], *ruleNames[sizeof(rules) / sizeof(rules[0])];-static BOOL ruleMatches(const SGRule *rule, NSString *scope, NSString *name) {- if (rule->scope && ![scope isEqualToString:@(rule->scope)]) return NO;- return !rule->name || [name isEqualToString:@(rule->name)];+static void boxRules(void) {+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ for (size_t i = 0; i < ruleCount; i++) {+ ruleScopes[i] = rules[i].scope ? @(rules[i].scope) : nil;+ ruleNames[i] = rules[i].name ? @(rules[i].name) : nil;+ }+ });+}++static BOOL ruleMatches(size_t i, NSString *scope, NSString *name) {+ if (ruleScopes[i] && ![scope isEqualToString:ruleScopes[i]]) return NO;+ return !ruleNames[i] || [name isEqualToString:ruleNames[i]];}// A false BoolValue is an empty message, as protobuf writes it.@@ -424,6 +436,7 @@ static NSData *patchConfiguration(NSData *configuration) {NSMutableArray<SGPBField *> *fields = SGPBParse(configuration);if (!fields) return nil;keepLiveConfiguration(fields);+ boxRules();NSMutableArray<SGPBField *> *out = [NSMutableArray array];NSMutableSet<NSString *> *present = [NSMutableSet set];for (SGPBField *field in fields) {@@ -437,7 +450,7 @@ static NSData *patchConfiguration(NSData *configuration) {NSString *scope = SGPBText(SGPBFirst(parts, 1)) ?: @"", *name = SGPBText(SGPBFirst(parts, 2)) ?: @"";BOOL removed = NO;for (size_t i = 0; i < ruleCount && !removed; i++) {- if (!ruleMatches(&rules[i], scope, name)) continue;+ if (!ruleMatches(i, scope, name)) continue;switch (rules[i].kind) {case SGRuleRemove: removed = YES; break;case SGRuleSet:diff --git a/tweak/Sources/Shared/AnimatedArtwork/SGMotionFollower.m b/tweak/Sources/Shared/AnimatedArtwork/SGMotionFollower.mindex b5e50aba..6c29ef37 100644--- a/tweak/Sources/Shared/AnimatedArtwork/SGMotionFollower.m+++ b/tweak/Sources/Shared/AnimatedArtwork/SGMotionFollower.m@@ -57,8 +57,11 @@});}-// The next track's clip, fetched into the store once, so a skip finds it there.+// The next track's clip, fetched into the store once, so a skip finds it there. Not in Low Power Mode: the+// skip then downloads it, and the plain cover shows until it lands. Every found clip asks again, so no+// observer is needed for the mode ending.- (void)fetchAhead {+ if (NSProcessInfo.processInfo.lowPowerModeEnabled) return;SPTPlayerState *state = SGPlayerState();id future = [state respondsToSelector:@selector(future)] ? state.future : nil;id next = [future isKindOfClass:NSArray.class] ? [(NSArray *)future firstObject] : nil;diff --git a/tweak/Sources/Shared/AnimatedArtwork/SGMotionStore.m b/tweak/Sources/Shared/AnimatedArtwork/SGMotionStore.mindex 721d2417..3fd1ca01 100644--- a/tweak/Sources/Shared/AnimatedArtwork/SGMotionStore.m+++ b/tweak/Sources/Shared/AnimatedArtwork/SGMotionStore.m@@ -28,6 +28,8 @@ static void trim(void) {NSArray<NSURLResourceKey> *keys = @[NSURLContentModificationDateKey];NSArray<NSURL *> *files = [NSFileManager.defaultManager contentsOfDirectoryAtURL:folder() includingPropertiesForKeys:keysoptions:NSDirectoryEnumerationSkipsHiddenFiles error:nil];+ // The catalog keeps its album answers in this folder too (SGMotionCatalog.m), and they are not videos to trim.+ files = [files filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"pathExtension != 'plist'"]];if (files.count <= kFiles) return;NSArray<NSURL *> *oldestFirst = [files sortedArrayUsingComparator:^NSComparisonResult(NSURL *a, NSURL *b) {NSDate *left = nil, *right = nil;diff --git a/tweak/Sources/Shared/ArtistBlock/ArtistSkip.x b/tweak/Sources/Shared/ArtistBlock/ArtistSkip.xindex 79555fbc..c6d965ce 100644--- a/tweak/Sources/Shared/ArtistBlock/ArtistSkip.x+++ b/tweak/Sources/Shared/ArtistBlock/ArtistSkip.x@@ -44,8 +44,10 @@ static NSString *trackKey(SPTPlayerTrack *track) {static NSDictionary *blockedArtistOf(SPTPlayerTrack *track) {NSArray<NSDictionary *> *artists = SGArtistsOfTrack(track);if (!SGFlag(SGKeyArtistBlockFeatured, NO) && artists.count > 1) artists = @[artists.firstObject];+ // The list is read from defaults once for the track, not once per credited artist.+ NSArray<NSString *> *blocked = [SGBlockedArtists() valueForKey:SGArtistURI];for (NSDictionary *artist in artists) {- if (SGArtistBlocked(artist[SGArtistURI])) return artist;+ if ([blocked containsObject:artist[SGArtistURI]]) return artist;}return nil;}diff --git a/tweak/Sources/Shared/AudioEffects/AudioEffects.x b/tweak/Sources/Shared/AudioEffects/AudioEffects.xindex aedaa63b..2be6f0c2 100644--- a/tweak/Sources/Shared/AudioEffects/AudioEffects.x+++ b/tweak/Sources/Shared/AudioEffects/AudioEffects.x@@ -250,14 +250,20 @@ static BOOL readFormat(AudioUnit unit) {// Spotify starts its output again after every pause; the format is logged when it is not the last one.// Spotify's thread and a format change's may both be here.static os_unfair_lock lock = OS_UNFAIR_LOCK_INIT;- static NSString *logged;- NSString *text = [NSString stringWithFormat:@"dsp: Spotify's output renders %@, from %@ Spotify hands it%@", formatText(format),- formatText(client), takes ? @"" : [NSString stringWithFormat:@"; not a format the engine takes (status %d), its sound passes as it is", (int)status]];+ static AudioStreamBasicDescription lastFormat, lastClient;+ static OSStatus lastStatus;+ static BOOL seen;os_unfair_lock_lock(&lock);- BOOL changed = ![text isEqualToString:logged];- logged = text;+ BOOL changed = !seen || status != lastStatus || memcmp(&format, &lastFormat, sizeof format) || memcmp(&client, &lastClient, sizeof client);+ lastFormat = format;+ lastClient = client;+ lastStatus = status;+ seen = YES;os_unfair_lock_unlock(&lock);- if (changed) SGLog(@"%@", text);+ if (changed) {+ SGLog(@"dsp: Spotify's output renders %@, from %@ Spotify hands it%@", formatText(format), formatText(client),+ takes ? @"" : [NSString stringWithFormat:@"; not a format the engine takes (status %d), its sound passes as it is", (int)status]);+ }if (!takes) {atomic_store(&sg_layout, 0);atomic_store(&sg_outputState, SGOutputUnsupported);diff --git a/tweak/Sources/Shared/Haptics/MusicHaptics.x b/tweak/Sources/Shared/Haptics/MusicHaptics.xindex 876d6634..74360b7f 100644--- a/tweak/Sources/Shared/Haptics/MusicHaptics.x+++ b/tweak/Sources/Shared/Haptics/MusicHaptics.x@@ -207,14 +207,20 @@ static void readFormat(AudioUnit unit) {// Spotify starts its output again after every pause; the format is logged when it is not the last one.// Spotify's thread and a format change's may both be here.static os_unfair_lock lock = OS_UNFAIR_LOCK_INIT;- static NSString *logged;- NSString *text = [NSString stringWithFormat:@"music haptics: listening to Spotify's output at %@, from %@ Spotify hands it%@", formatText(format),- formatText(client), takes ? @"" : [NSString stringWithFormat:@"; not a format the analyzer reads (status %d), nothing plays", (int)status]];+ static AudioStreamBasicDescription lastFormat, lastClient;+ static OSStatus lastStatus;+ static BOOL seen;os_unfair_lock_lock(&lock);- BOOL changed = ![text isEqualToString:logged];- logged = text;+ BOOL changed = !seen || status != lastStatus || memcmp(&format, &lastFormat, sizeof format) || memcmp(&client, &lastClient, sizeof client);+ lastFormat = format;+ lastClient = client;+ lastStatus = status;+ seen = YES;os_unfair_lock_unlock(&lock);- if (changed) SGLog(@"%@", text);+ if (changed) {+ SGLog(@"music haptics: listening to Spotify's output at %@, from %@ Spotify hands it%@", formatText(format), formatText(client),+ takes ? @"" : [NSString stringWithFormat:@"; not a format the analyzer reads (status %d), nothing plays", (int)status]);+ }if (!takes) {atomic_store(&sg_layout, 0);return;diff --git a/tweak/Sources/Shared/HeadGestures/HeadGesturesTeach.m b/tweak/Sources/Shared/HeadGestures/HeadGesturesTeach.mindex 593d6bfb..00b30d6d 100644--- a/tweak/Sources/Shared/HeadGestures/HeadGesturesTeach.m+++ b/tweak/Sources/Shared/HeadGestures/HeadGesturesTeach.m@@ -9,7 +9,7 @@//// The sheet holds the motion open while it is up (SGHeadGesturesHold), so the system's Motion & Fitness prompt,// the first time, comes over it before Start, and no gesture does anything to the song meanwhile. The ring-// reads the motion through SGHeadMotionListen and draws at 60 fps at most, only while the sheet shows.+// reads the motion through SGHeadMotionListen and draws only while the sheet shows, at up to 120 fps.#import <QuartzCore/QuartzCore.h>#import <os/lock.h>#import "Core/SGCore.h"@@ -33,7 +33,7 @@ static const CGFloat kTickLength = 10, kTickWidth = 3, kDotSize = 18;static const double kPitchReach = 0.3, kYawReach = 0.22;// Where the head rests follows it this slowly, so a gesture moves the dot and a new posture does not.static const double kRestSeconds = 1.2;-// The dot follows the motion's 25 samples a second this closely, so it glides between them at 60 fps.+// The dot follows the motion's 25 samples a second this closely, so it glides between them at any frame rate.static const double kFollowSeconds = 0.05;// A lit tick fades back this slowly; the light spreads this far either side of the head's direction.static const double kTickFadeSeconds = 0.45, kTickSpread = M_PI / 7;@@ -191,7 +191,7 @@ static BOOL headOffset(double *pitch, double *yaw) {SGHeadMotionListen(@"teaching", ^(CMDeviceMotion *motion) { headMoved(motion); });_lastFrame = 0;_link = [CADisplayLink displayLinkWithTarget:self selector:@selector(frame:)];- _link.preferredFrameRateRange = CAFrameRateRangeMake(30, 60, 60);+ _link.preferredFrameRateRange = CAFrameRateRangeMake(30, 120, 60); // a 60 Hz cap would hold other 120 Hz motion on screen to 60[_link addToRunLoop:NSRunLoop.mainRunLoop forMode:NSRunLoopCommonModes];}diff --git a/tweak/Sources/Shared/LiveActivity/LiveActivity.x b/tweak/Sources/Shared/LiveActivity/LiveActivity.xindex 62fabe4b..66a1029b 100644--- a/tweak/Sources/Shared/LiveActivity/LiveActivity.x+++ b/tweak/Sources/Shared/LiveActivity/LiveActivity.x@@ -85,6 +85,7 @@ static const double kAccentLuminance = 0.48;static NSTimer *sg_timer;static NSTimeInterval sg_tickEvery;static NSString *sg_shown;+static NSArray *sg_shownFields; // the fields sg_shown was built from, as readstatic NSString *sg_missingLyrics;// The tracks whose look for lyrics ended (SGKaraokeLinesKeptNotification), with lines or without: a set, since// the track up next is looked up too, ahead of the one playing.@@ -114,7 +115,7 @@ static void startTimer(NSTimeInterval every) API_AVAILABLE(ios(17.0)) {// Sends `shown`, what the activity is to show as one string, unless it is showing that already and was// sent within kRefresh; starts the activity when there is none and the app is in front.-static void send(NSString *shown, void (^show)(void)) API_AVAILABLE(ios(17.0)) {+static void send(NSString *shown, NSArray *fields, void (^show)(void)) API_AVAILABLE(ios(17.0)) {// ActivityKit is asked only when there is something to send: each question is a round trip to the system,// and this runs four times a second. An activity ended from outside is started again within kRefresh.if ([shown isEqualToString:sg_shown] && -sg_lastSent.timeIntervalSinceNow < kRefresh) return;@@ -143,6 +144,7 @@ static void send(NSString *shown, void (^show)(void)) API_AVAILABLE(ios(17.0)) {sg_lastStart = [NSDate date];}sg_shown = shown;+ sg_shownFields = fields;sg_lastSent = [NSDate date];show();}@@ -351,6 +353,17 @@ static void tick(void) API_AVAILABLE(ios(17.0)) {SGSleepTimerMode sleepMode = SGSleepTimerCurrentMode();NSDate *sleepEnd = SGSleepTimerEnd();+ // The fields as read, before the string below is built from them: equal fields give an equal string, which+ // send would set aside, so the string and its two dozen pieces are built only once a field moved or kRefresh+ // has passed. The string stays what send compares, as two fields with a line break between them could read as+ // one. The small numbers are tagged pointers, so this is one array a tick.+ NSArray *fields = @[@(view), @(paused), line, next, @(tab), title, artist, @(shuffle), @(repeatMode),+ @((long long)sleepEnd.timeIntervalSince1970), @(sleepMode), tint ?: @"", translation ?: @"",+ paused ? @0 : @((long long)trackStart.timeIntervalSince1970), paused ? @(round(pausedAt.doubleValue * 100)) : @0,+ cover ? sg_artTrack : @"", @(textSize), @(alignment), @(noLyrics), @(withoutLyrics), @(colors), accent ?: @"", @(progressBar),+ titles, artists, uris];+ if ([fields isEqualToArray:sg_shownFields] && -sg_lastSent.timeIntervalSinceNow < kRefresh) return;+NSMutableArray<NSString *> *parts = [NSMutableArray arrayWithObjects:@(view).stringValue, paused ? @"1" : @"0", line, next,@(tab).stringValue, title, artist, shuffle ? @"1" : @"0", @(repeatMode).stringValue,@((long long)sleepEnd.timeIntervalSince1970).stringValue, @(sleepMode).stringValue, tint ?: @"", translation ?: @"",@@ -358,7 +371,7 @@ static void tick(void) API_AVAILABLE(ios(17.0)) {cover ? sg_artTrack : @"", @(textSize).stringValue, @(alignment).stringValue, noLyrics ? @"1" : @"0",@(withoutLyrics).stringValue, @(colors).stringValue, accent ?: @"", progressBar ? @"1" : @"0", nil];for (NSUInteger i = 0; i < titles.count; i++) [parts addObject:[NSString stringWithFormat:@"%@\t%@\t%@", titles[i], artists[i], uris[i]]];- send([parts componentsJoinedByString:@"\n"], ^{+ send([parts componentsJoinedByString:@"\n"], fields, ^{[SGLiveActivityBridge showWithView:view paused:paused line:line nextLine:next titles:titles artists:artists uris:uristab:tab title:title artist:artist shuffle:shuffle repeatMode:repeatModetimerEnd:sleepEnd timerEndOfTrack:sleepMode == SGSleepTimerEndOfTrack@@ -481,6 +494,7 @@ void SGSetLiveActivityEnabled(BOOL on) {[sg_timer invalidate];sg_timer = nil;sg_shown = nil;+ sg_shownFields = nil;sg_lastStart = nil;// A sleep timer runs on its own clock (SleepTimer.m) and stays set: the shortcut and the control set it// with the card off, and a card switched back on shows it from its first tick.diff --git a/tweak/Sources/Shared/Lossless/SGLosslessEngine.m b/tweak/Sources/Shared/Lossless/SGLosslessEngine.mindex 21553fd6..fd685dcc 100644--- a/tweak/Sources/Shared/Lossless/SGLosslessEngine.m+++ b/tweak/Sources/Shared/Lossless/SGLosslessEngine.m@@ -285,8 +285,9 @@ static BOOL record(double seconds, NSString **error) {#pragma mark - the writer-// Fills the ring from where the render thread reads until the generation changes or the file ends.-static void fill(NSString *path, double rate, uint64_t from, uint64_t generation) {+// Fills the ring from where the render thread reads until the generation or the source epoch changes or the file ends.+// Past the epoch the selector never reads this ring again (the epoch only grows), so there is nothing left to fill.+static void fill(NSString *path, double rate, uint64_t from, uint64_t generation, uint64_t epoch) {Reader reader = {0};NSString *error;if (!openReader(&reader, path, rate, &error)) {@@ -297,7 +298,7 @@ static void fill(NSString *path, double rate, uint64_t from, uint64_t generationfloat *l = malloc(kChunk * sizeof(float)), *r = malloc(kChunk * sizeof(float));uint64_t end = from;BOOL seek = YES;- while (atomic_load(&sg_generation) == generation) {+ while (atomic_load(&sg_generation) == generation && SGPlayerSourceEpoch() == epoch) {uint64_t reading = MAX(atomic_load_explicit(&sg_readAt, memory_order_relaxed), atomic_load(&sg_ringStart));if (reading > end + (uint64_t)rate) {// Spotify plays ahead of what the ring holds: start again where it plays.@@ -372,10 +373,10 @@ static NSDictionary *anchor(NSString *path, double hint, NSString **error) {atomic_store(&sg_ringStart, now);atomic_store(&sg_ringEnd, now);atomic_store(&sg_readAt, now);- uint64_t generation = atomic_load(&sg_generation);+ uint64_t generation = atomic_load(&sg_generation), epoch = sg_playEpoch;atomic_fetch_add(&sg_writers, 1);// Its own thread: it runs for the rest of the song, which would hold a shared queue's thread that long.- NSThread *writer = [[NSThread alloc] initWithBlock:^{ fill(path, rate, now, generation); }];+ NSThread *writer = [[NSThread alloc] initWithBlock:^{ fill(path, rate, now, generation, epoch); }];writer.qualityOfService = NSQualityOfServiceUserInitiated;writer.name = @"spotifyglass.lossless.writer";[writer start];diff --git a/tweak/Sources/Shared/Lossless/SGLosslessStore.m b/tweak/Sources/Shared/Lossless/SGLosslessStore.mindex 3e5c00bf..7a89ba4e 100644--- a/tweak/Sources/Shared/Lossless/SGLosslessStore.m+++ b/tweak/Sources/Shared/Lossless/SGLosslessStore.m@@ -4,8 +4,13 @@static NSString *const kIndex = @".index.plist"; // track URI -> file nameNSString *SGLosslessStoreDirectory(void) {- NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;- NSString *directory = [documents stringByAppendingPathComponent:@"Lossless"];+ static NSString *directory;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;+ directory = [documents stringByAppendingPathComponent:@"Lossless"];+ });+ // Made again on every call: a folder the user deletes in Files comes back, and its date is read each second.[NSFileManager.defaultManager createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:NULL];return directory;}diff --git a/tweak/Sources/Shared/LyricsMeanings/Meanings.m b/tweak/Sources/Shared/LyricsMeanings/Meanings.mindex a7c5d6cf..3d726f23 100644--- a/tweak/Sources/Shared/LyricsMeanings/Meanings.m+++ b/tweak/Sources/Shared/LyricsMeanings/Meanings.m@@ -27,11 +27,15 @@ SGModRow *SGLyricsMeaningsRow(void) {#pragma mark - text-static BOOL sameLine(NSString *a, NSString *b) {+static NSArray<NSString *> *wordsOf(NSString *text) {+ return [text componentsSeparatedByString:@" "];+}++// `wordsA` and `wordsB` are wordsOf(a) and wordsOf(b), split once by the caller rather than for every pair.+static BOOL sameLine(NSString *a, NSArray<NSString *> *wordsA, NSString *b, NSArray<NSString *> *wordsB) {if (!a.length || !b.length) return NO;if ([a isEqualToString:b]) return YES;if (MIN(a.length, b.length) >= kLeastContained && ([a containsString:b] || [b containsString:a])) return YES;- NSArray<NSString *> *wordsA = [a componentsSeparatedByString:@" "], *wordsB = [b componentsSeparatedByString:@" "];if (MIN(wordsA.count, wordsB.count) < 4) return NO;NSCountedSet *left = [[NSCountedSet alloc] initWithArray:wordsA];NSUInteger shared = 0;@@ -190,16 +194,22 @@ static NSDictionary<NSNumber *, NSArray<SGLyricsMeaning *> *> *matched(NSArray<SNSArray<SGKaraokeLine *> *lines,SGLyricsMeaningsLevel level) {NSMutableArray<NSString *> *texts = [NSMutableArray arrayWithCapacity:lines.count];- for (SGKaraokeLine *line in lines) [texts addObject:SGLyricsFoldedText(SGKaraokeLineText(line))];+ NSMutableArray<NSArray<NSString *> *> *words = [NSMutableArray arrayWithCapacity:lines.count];+ for (SGKaraokeLine *line in lines) {+ NSString *text = SGLyricsFoldedText(SGKaraokeLineText(line));+ [texts addObject:text];+ [words addObject:wordsOf(text)];+ }SGLyricsMeaningAuthor furthest = level == SGLyricsMeaningsArtist ? SGLyricsMeaningByArtist: level == SGLyricsMeaningsEditors ? SGLyricsMeaningByEditors : SGLyricsMeaningByCommunity;NSMutableDictionary<NSNumber *, NSMutableArray<SGLyricsMeaning *> *> *byLine = [NSMutableDictionary dictionary];for (SGLyricsMeaning *meaning in meanings) {if (meaning.author > furthest) continue;for (NSString *wanted in fragmentLines(meaning.fragment)) {+ NSArray<NSString *> *wantedWords = wordsOf(wanted);BOOL found = NO;for (NSUInteger i = 0; i < texts.count; i++) {- if (!sameLine(wanted, texts[i])) continue;+ if (!sameLine(wanted, wantedWords, texts[i], words[i])) continue;found = YES;NSMutableArray<SGLyricsMeaning *> *list = byLine[@(i)] ?: (byLine[@(i)] = [NSMutableArray array]);// A chorus annotated at each of its places carries the same words at every one.diff --git a/tweak/Sources/Shared/LyricsSources/BiniLyrics.m b/tweak/Sources/Shared/LyricsSources/BiniLyrics.mindex e9718b40..d456c5cc 100644--- a/tweak/Sources/Shared/LyricsSources/BiniLyrics.m+++ b/tweak/Sources/Shared/LyricsSources/BiniLyrics.m@@ -68,8 +68,9 @@ static void search(SGLyricsQuery *query, void (^done)(SGLyricsResult *result)) {done(nil);return;}- SGLyricsGetText([NSURL URLWithString:found[@"lyricsUrl"]], ^(NSString *ttml) {- SGLyricsResult *result = resultFor(ttml, [found[@"timing_type"] isEqual:@"word"]);+ SGLyricsGetTextThen([NSURL URLWithString:found[@"lyricsUrl"]], ^id(NSString *ttml) {+ return resultFor(ttml, [found[@"timing_type"] isEqual:@"word"]);+ }, ^(SGLyricsResult *result) {if (!result) SGLog(@"binilyrics: %@ gave nothing the page could show", found[@"lyricsUrl"]);else SGLog(@"binilyrics: %@ by %@ has %lu %@ lines", query.title, query.artist,(unsigned long)result.karaokeLines.count, result.wordTimed ? @"word timed" : @"line timed");@@ -89,8 +90,9 @@ SGLyricsAsk SGBiniLyricsAsk = ^(SGLyricsQuery *query, void (^done)(SGLyricsResulsearch(query, done);return;}- SGLyricsGetText([NSURL URLWithString:[NSString stringWithFormat:kByISRC, isrc]], ^(NSString *ttml) {- SGLyricsResult *result = resultFor(ttml, [ttml containsString:@"timing=\"Word\""]);+ SGLyricsGetTextThen([NSURL URLWithString:[NSString stringWithFormat:kByISRC, isrc]], ^id(NSString *ttml) {+ return resultFor(ttml, [ttml containsString:@"timing=\"Word\""]);+ }, ^(SGLyricsResult *result) {if (!result) {SGLog(@"binilyrics: nothing filed under %@, searched by name", isrc);search(query, done);diff --git a/tweak/Sources/Shared/LyricsSources/Genius.m b/tweak/Sources/Shared/LyricsSources/Genius.mindex 06e16051..e01a90e2 100644--- a/tweak/Sources/Shared/LyricsSources/Genius.m+++ b/tweak/Sources/Shared/LyricsSources/Genius.m@@ -103,8 +103,7 @@ SGLyricsAsk SGGeniusAsk = ^(SGLyricsQuery *query, void (^done)(SGLyricsResult *rreturn;}NSURL *embed = [NSURL URLWithString:[NSString stringWithFormat:@"https://genius.com/songs/%@/embed.js", song]];- SGLyricsGetText(embed, ^(NSString *js) {- NSArray<NSString *> *rows = SGGeniusEmbedRows(js);+ SGLyricsGetTextThen(embed, ^id(NSString *js) { return SGGeniusEmbedRows(js); }, ^(NSArray<NSString *> *rows) {if (!rows) {SGLog(@"genius: %@ by %@ is song %@, no lines in its embed", query.title, query.artist, song);done(nil);diff --git a/tweak/Sources/Shared/LyricsSources/LyricsSources.h b/tweak/Sources/Shared/LyricsSources/LyricsSources.hindex fc417156..60816549 100644--- a/tweak/Sources/Shared/LyricsSources/LyricsSources.h+++ b/tweak/Sources/Shared/LyricsSources/LyricsSources.h@@ -129,6 +129,11 @@ void SGLyricsGetJSON(NSURL *url, NSDictionary<NSString *, NSString *> *headers,// body says why. response is nil when the request never got an answer.void SGLyricsGetJSONReply(NSURL *url, NSDictionary<NSString *, NSString *> *headers, void (^done)(id root, NSHTTPURLResponse *response));void SGLyricsGetText(NSURL *url, void (^done)(NSString *text));+// The same two with a `parse` that reads the reply on the session's queue, so a TTML or an embed page is+// read off the main queue; `done` gets what it returns, on the main queue. `parse` must touch no state of+// the main queue's.+void SGLyricsGetJSONThen(NSURL *url, NSDictionary<NSString *, NSString *> *headers, id (^parse)(id root), void (^done)(id parsed));+void SGLyricsGetTextThen(NSURL *url, id (^parse)(NSString *text), void (^done)(id parsed));// For the one source that is asked a question rather than sent to an address. body is anything// NSJSONSerialization writes; nothing is sent at all when it is not.void SGLyricsPostJSON(NSURL *url, NSDictionary<NSString *, NSString *> *headers, id body, void (^done)(id root));diff --git a/tweak/Sources/Shared/LyricsSources/LyricsSources.m b/tweak/Sources/Shared/LyricsSources/LyricsSources.mindex 47e4af8a..47d86664 100644--- a/tweak/Sources/Shared/LyricsSources/LyricsSources.m+++ b/tweak/Sources/Shared/LyricsSources/LyricsSources.m@@ -72,7 +72,8 @@ static NSMutableURLRequest *requestFor(NSURL *url, NSDictionary<NSString *, NSStreturn request;}-// The body whatever the status, and the reply it came with; nil for both when there was none.+// The body whatever the status, and the reply it came with, on the session's own queue so the callers+// below can read it there before they hand the result to the main queue; nil for both when there was none.static void sendForReply(NSURLRequest *request, void (^done)(NSData *body, NSHTTPURLResponse *response)) {if (!request) {dispatch_async(dispatch_get_main_queue(), ^{ done(nil, nil); });@@ -83,7 +84,7 @@ static void sendForReply(NSURLRequest *request, void (^done)(NSData *body, NSHTTNSHTTPURLResponse *reply = [response isKindOfClass:NSHTTPURLResponse.class] ? (NSHTTPURLResponse *)response : nil;SGLyricsNoteReply(response, error);if (error || reply.statusCode >= 400) SGLog(@"lyrics: %@ answered %ld, error %@", url.host, (long)reply.statusCode, error);- dispatch_async(dispatch_get_main_queue(), ^{ done(data, reply); });+ done(data, reply);}] resume];}@@ -97,24 +98,41 @@ static id jsonIn(NSData *body) {return body.length ? [NSJSONSerialization JSONObjectWithData:body options:0 error:nil] : nil;}-void SGLyricsGetJSON(NSURL *url, NSDictionary<NSString *, NSString *> *headers, void (^done)(id root)) {+static NSString *textIn(NSData *body) {+ return body.length ? [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding] : nil;+}++static void onMain(void (^done)(id), id parsed) {+ dispatch_async(dispatch_get_main_queue(), ^{ done(parsed); });+}++void SGLyricsGetJSONThen(NSURL *url, NSDictionary<NSString *, NSString *> *headers, id (^parse)(id root), void (^done)(id parsed)) {send(requestFor(url, headers), ^(NSData *body) {- done(jsonIn(body));+ onMain(done, parse(jsonIn(body)));});}+void SGLyricsGetJSON(NSURL *url, NSDictionary<NSString *, NSString *> *headers, void (^done)(id root)) {+ SGLyricsGetJSONThen(url, headers, ^id(id root) { return root; }, done);+}+void SGLyricsGetJSONReply(NSURL *url, NSDictionary<NSString *, NSString *> *headers, void (^done)(id root, NSHTTPURLResponse *response)) {sendForReply(requestFor(url, headers), ^(NSData *body, NSHTTPURLResponse *reply) {- done(jsonIn(body), reply);+ id root = jsonIn(body);+ dispatch_async(dispatch_get_main_queue(), ^{ done(root, reply); });});}-void SGLyricsGetText(NSURL *url, void (^done)(NSString *text)) {+void SGLyricsGetTextThen(NSURL *url, id (^parse)(NSString *text), void (^done)(id parsed)) {send(requestFor(url, nil), ^(NSData *body) {- done(body.length ? [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding] : nil);+ onMain(done, parse(textIn(body)));});}+void SGLyricsGetText(NSURL *url, void (^done)(NSString *text)) {+ SGLyricsGetTextThen(url, ^id(NSString *text) { return text; }, done);+}+void SGLyricsPostJSON(NSURL *url, NSDictionary<NSString *, NSString *> *headers, id body, void (^done)(id root)) {NSData *written = [NSJSONSerialization isValidJSONObject:body]? [NSJSONSerialization dataWithJSONObject:body options:0 error:nil] : nil;@@ -123,7 +141,7 @@ void SGLyricsPostJSON(NSURL *url, NSDictionary<NSString *, NSString *> *headers,request.HTTPBody = written;[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];send(request, ^(NSData *answer) {- done(jsonIn(answer));+ onMain(done, jsonIn(answer));});}diff --git a/tweak/Sources/Shared/LyricsSources/Unison.m b/tweak/Sources/Shared/LyricsSources/Unison.mindex ac6ebb1d..bf857bd1 100644--- a/tweak/Sources/Shared/LyricsSources/Unison.m+++ b/tweak/Sources/Shared/LyricsSources/Unison.m@@ -23,30 +23,25 @@ SGLyricsAsk SGUnisonAsk = ^(SGLyricsQuery *query, void (^done)(SGLyricsResult *r}];if (query.seconds > 0) search[@"duration"] = @(query.seconds).stringValue;if (query.album.length) search[@"album"] = query.album;- SGLyricsGetJSON(SGLyricsURL(kAPI, search), nil, ^(id root) {+ // Read on the session's queue: the TTML is the walk's longest parse. The query is read, never written, here.+ SGLyricsGetJSONThen(SGLyricsURL(kAPI, search), nil, ^id(id root) {id data = [root isKindOfClass:NSDictionary.class] ? root[@"data"] : nil;if (![data isKindOfClass:NSDictionary.class]) {SGLog(@"unison: no lyrics for %@ by %@", query.title, query.artist);- done(nil);- return;+ return nil;}// Unison also keeps LRC and plain text, which carry nothing the other sources do not.if (![data[@"format"] isEqual:@"ttml"]) {SGLog(@"unison: %@ by %@ is %@, not ttml", query.title, query.artist, data[@"format"]);- done(nil);- return;+ return nil;}NSInteger length = [data[@"duration"] integerValue];if (query.seconds > 0 && length > 0 && labs(length - query.seconds) > kLengthSlack) {SGLog(@"unison: %@ is %lds against the track's %lds", query.title, (long)length, (long)query.seconds);- done(nil);- return;+ return nil;}NSArray<SGKaraokeLine *> *lines = SGTTMLLines(data[@"lyrics"]);- if (!lines) {- done(nil);- return;- }+ if (!lines) return nil;SGLyricsResult *result = [SGLyricsResult new];result.synced = YES;result.wordTimed = [data[@"syncType"] isEqual:@"richsync"];@@ -58,6 +53,6 @@ SGLyricsAsk SGUnisonAsk = ^(SGLyricsQuery *query, void (^done)(SGLyricsResult *rresult.texts = texts;SGLog(@"unison: %@ by %@ has %lu %@ lines (%@ confidence)", query.title, query.artist,(unsigned long)lines.count, result.wordTimed ? @"word timed" : @"line timed", data[@"confidence"]);- done(result);- });+ return result;+ }, done);};diff --git a/tweak/Sources/Shared/Player/PlayerState.x b/tweak/Sources/Shared/Player/PlayerState.xindex 6a4cf9a1..3a513cec 100644--- a/tweak/Sources/Shared/Player/PlayerState.x+++ b/tweak/Sources/Shared/Player/PlayerState.x@@ -10,7 +10,10 @@ NSString *SGURIString(id uri) {static NSHashTable<id<SGPlayerStateObserver>> *sg_stateObservers;static SPTPlayerState *sg_playerState;-static NSString *sg_stateKey;+// What the last change was told from, so a report that moved none of them tells observers nothing.+static BOOL sg_stateSeen;+static NSString *sg_stateTrack, *sg_stateContext;+static int sg_stateBits;// Set once the now playing platform has reported; the mod's own observer on the player stands down.static BOOL sg_platformReported = NO;@@ -24,22 +27,27 @@ SPTPlayerState *SGPlayerState(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", SGURIString(state.track.URI), SGURIString(state.contextURI),- state.isPaused, state.isPlaying, [state respondsToSelector:@selector(isLoading)] && state.isLoading, shuffling];+static BOOL sameURI(NSString *a, NSString *b) {+ return a == b || [a isEqualToString:b];}+// What an observer is told about; the state object itself is new with every position report.static void publish(SPTPlayerState *state) {sg_playerState = state;for (id<SGPlayerStateObserver> observer in sg_stateObservers.allObjects) {if ([observer respondsToSelector:@selector(playerStateDidReport:)]) [observer playerStateDidReport:state];}- NSString *key = keyOf(state);- if ([key isEqualToString:sg_stateKey]) return;- sg_stateKey = key;+ NSString *track = SGURIString(state.track.URI), *context = SGURIString(state.contextURI);+ SPTPlayerOptions *options = [state respondsToSelector:@selector(options)] ? state.options : nil;+ BOOL paused = state.isPaused, playing = state.isPlaying;+ BOOL loading = [state respondsToSelector:@selector(isLoading)] && state.isLoading;+ BOOL shuffling = [options respondsToSelector:@selector(shufflingContext)] && options.shufflingContext;+ int bits = paused | playing << 1 | loading << 2 | shuffling << 3;+ if (sg_stateSeen && bits == sg_stateBits && sameURI(track, sg_stateTrack) && sameURI(context, sg_stateContext)) return;+ sg_stateSeen = YES;+ sg_stateTrack = track;+ sg_stateContext = context;+ sg_stateBits = bits;for (id<SGPlayerStateObserver> observer in sg_stateObservers.allObjects) [observer playerStateDidChange:state];}diff --git a/tweak/Sources/Shared/Player/SGLastTrack.m b/tweak/Sources/Shared/Player/SGLastTrack.mindex c3a90cfa..8615d153 100644--- a/tweak/Sources/Shared/Player/SGLastTrack.m+++ b/tweak/Sources/Shared/Player/SGLastTrack.m@@ -76,7 +76,7 @@ SGShownTrack *SGShownTrackNow(void) {NSDictionary *track = describe(state.track);if (!track[@"title"] || [track isEqualToDictionary:_last ?: stored()]) return;_last = track;- [NSUserDefaults.standardUserDefaults setObject:track forKey:SGKeyLastTrack];+ SGPrefsWriteUnmemoized(^{ [NSUserDefaults.standardUserDefaults setObject:track forKey:SGKeyLastTrack]; });}@enddiff --git a/tweak/Sources/Shared/Player/SpeedPitch.x b/tweak/Sources/Shared/Player/SpeedPitch.xindex 5640f6ed..92ff60d6 100644--- a/tweak/Sources/Shared/Player/SpeedPitch.x+++ b/tweak/Sources/Shared/Player/SpeedPitch.x@@ -1315,7 +1315,9 @@ BOOL SGPlayerWatchMusicOutput(SGPlayerOutputWatcher watcher) {- (void)playerStateDidChange:(SPTPlayerState *)state {}- (void)playerStateDidReport:(SPTPlayerState *)state {if (loadFloat(&sg_speedBits) == 1 || !state.isPlaying || state.isPaused) return;- BOOL buffering = [state respondsToSelector:NSSelectorFromString(@"isBuffering")] && [[state valueForKey:@"isBuffering"] boolValue];+ static SEL isBuffering;+ if (!isBuffering) isBuffering = NSSelectorFromString(@"isBuffering");+ BOOL buffering = [state respondsToSelector:isBuffering] && [[state valueForKey:@"isBuffering"] boolValue];if (buffering || state.playbackSpeed == 0) rearmClock();}@enddiff --git a/tweak/Sources/Shared/Player/VideoSwitch.x b/tweak/Sources/Shared/Player/VideoSwitch.xindex 7852be56..2a0a0990 100644--- a/tweak/Sources/Shared/Player/VideoSwitch.x+++ b/tweak/Sources/Shared/Player/VideoSwitch.x@@ -32,9 +32,9 @@ static UIView *switchIn(UIView *root, int depth) {logged = YES;SGLog(@"player: Switch to video hidden, %@ %@", NSStringFromClass(videoSwitch.class), NSStringFromCGRect(videoSwitch.frame));}- videoSwitch.alpha = 0;- videoSwitch.userInteractionEnabled = NO;- videoSwitch.accessibilityElementsHidden = YES;+ if (videoSwitch.alpha != 0) videoSwitch.alpha = 0;+ if (videoSwitch.userInteractionEnabled) videoSwitch.userInteractionEnabled = NO;+ if (!videoSwitch.accessibilityElementsHidden) videoSwitch.accessibilityElementsHidden = YES;}%enddiff --git a/tweak/Sources/Shared/Privacy/Privacy.x b/tweak/Sources/Shared/Privacy/Privacy.xindex cede5e84..ce390e88 100644--- a/tweak/Sources/Shared/Privacy/Privacy.x+++ b/tweak/Sources/Shared/Privacy/Privacy.x@@ -31,9 +31,26 @@ static const SGBlockRule kRules[] = {{"doubleclick.net", NULL, "Google"},};static const size_t kRuleCount = sizeof(kRules) / sizeof(kRules[0]);+// The rules as NSStrings, made once: the protocol is asked about nearly every request the app sends.+static NSString *sg_domains[sizeof(kRules) / sizeof(kRules[0])], *sg_dotted[sizeof(kRules) / sizeof(kRules[0])],+ *sg_paths[sizeof(kRules) / sizeof(kRules[0])], *sg_labels[sizeof(kRules) / sizeof(kRules[0])];++static void boxRules(void) {+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ for (size_t i = 0; i < kRuleCount; i++) {+ sg_domains[i] = @(kRules[i].host);+ sg_dotted[i] = [@"." stringByAppendingString:sg_domains[i]];+ sg_paths[i] = kRules[i].path ? @(kRules[i].path) : nil;+ sg_labels[i] = @(kRules[i].label);+ }+ });+}static NSString *const kCounts = @"spotifyglass.privacy.counts";static NSMutableDictionary<NSString *, NSNumber *> *sg_counts;+static BOOL sg_unsaved; // blocks counted since the counts were last written+static CFAbsoluteTime sg_savedAt;@interface SGBlockProtocol : NSURLProtocol@end@@ -52,32 +69,47 @@ static NSMutableDictionary<NSString *, NSNumber *> *countsLocked(void) {return sg_counts;}+// Counted in memory and written as AdBlock.m writes its counts: when Spotify leaves the screen and at most+// every 30 s while counting goes on, so a kill in the background (no notification comes) loses half a+// minute at most. Each write also wakes every defaults observer and empties the prefs memo. Called under+// the lock.+static void saveLocked(BOOL now) {+ if (!sg_unsaved || (!now && CFAbsoluteTimeGetCurrent() - sg_savedAt < 30)) return;+ SGPrefsWriteUnmemoized(^{ [NSUserDefaults.standardUserDefaults setObject:countsLocked() forKey:kCounts]; });+ sg_unsaved = NO;+ sg_savedAt = CFAbsoluteTimeGetCurrent();+}+static void countOne(NSString *label) {@synchronized (SGBlockProtocol.class) {NSMutableDictionary<NSString *, NSNumber *> *counts = countsLocked();counts[label] = @(counts[label].unsignedIntegerValue + 1);- [NSUserDefaults.standardUserDefaults setObject:counts forKey:kCounts];+ sg_unsaved = YES;+ saveLocked(NO);}}static NSString *labelFor(NSURL *url) {NSString *host = url.host.lowercaseString;if (!host) return nil;- NSString *path = url.path ?: @"";+ boxRules();+ NSString *path = nil;for (size_t i = 0; i < kRuleCount; i++) {- NSString *domain = @(kRules[i].host);- if (![host isEqualToString:domain] && ![host hasSuffix:[@"." stringByAppendingString:domain]]) continue;- if (kRules[i].path && ![path containsString:@(kRules[i].path)]) continue;- return @(kRules[i].label);+ if (![host isEqualToString:sg_domains[i]] && ![host hasSuffix:sg_dotted[i]]) continue;+ if (sg_paths[i]) {+ if (!path) path = url.path ?: @"";+ if (![path containsString:sg_paths[i]]) continue;+ }+ return sg_labels[i];}return nil;}NSArray<NSString *> *SGBlockedLabels(void) {+ boxRules();NSMutableArray<NSString *> *labels = [NSMutableArray array];for (size_t i = 0; i < kRuleCount; i++) {- NSString *label = @(kRules[i].label);- if (![labels containsObject:label]) [labels addObject:label];+ if (![labels containsObject:sg_labels[i]]) [labels addObject:sg_labels[i]];}return labels;}@@ -95,6 +127,7 @@ NSUInteger SGBlockedCount(NSString *label) {void SGResetBlocked(void) {@synchronized (SGBlockProtocol.class) {sg_counts = [NSMutableDictionary dictionary];+ sg_unsaved = NO;[NSUserDefaults.standardUserDefaults removeObjectForKey:kCounts];}}@@ -149,5 +182,10 @@ static NSURLSessionConfiguration *carryingProtocol(NSURLSessionConfiguration *coif (SGEnabled(SGKeyBlockTelemetry)) {[NSURLProtocol registerClass:SGBlockProtocol.class];%init;+ // Spotify leaving the screen writes what was counted since the last write.+ [NSNotificationCenter.defaultCenter addObserverForName:UIApplicationWillResignActiveNotification object:nil queue:nil+ usingBlock:^(NSNotification *note) {+ @synchronized (SGBlockProtocol.class) { saveLocked(YES); }+ }];}}diff --git a/tweak/Sources/Shared/Sing/SGSingCard.m b/tweak/Sources/Shared/Sing/SGSingCard.mindex 2a6c17ed..15d8565f 100644--- a/tweak/Sources/Shared/Sing/SGSingCard.m+++ b/tweak/Sources/Shared/Sing/SGSingCard.m@@ -13,8 +13,8 @@// Reading the lines is how Sing knows the page shows ("the lines" in its log are these two, not the lyrics' lines):// at As sung with Spatial voice off, where Sing otherwise rests, it separates the playing song while they are read,// so the lines move and the slider and the three stops are heard at once, and rests again a second after the last-// read. The timer stops with the page off screen (popped, or covered by another page) and reads nothing while-// Spotify is in the background. At any other level Sing separates whether the page shows or not. Every other gate+// read. The timer stops with the page off screen (popped, or covered by another page) and while Spotify is in the+// background. At any other level Sing separates whether the page shows or not. Every other gate// (the switch, the model, the heat, memory, Runs on, the model kept a minute after resting) stays Sing.x's.//// Threading: main thread.@@ -237,10 +237,19 @@ static CGFloat height(float rms) {_card.accessibilityElements = @[_song, _play, _column];UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(stateTapped:)];[_card addGestureRecognizer:tap];+ // Spotify in the background plays on, and tick reads nothing there: the timer goes with the app and comes back with it.+ NSNotificationCenter *center = NSNotificationCenter.defaultCenter;+ [center addObserver:self selector:@selector(stopTimer) name:UIApplicationDidEnterBackgroundNotification object:nil];+ [center addObserver:self selector:@selector(startTimer) name:UIApplicationWillEnterForegroundNotification object:nil];[self refresh];return self;}+- (void)dealloc {+ [NSNotificationCenter.defaultCenter removeObserver:self];+ [_timer invalidate];+}+- (CGSize)sizeThatFits:(CGSize)size {CGFloat stops = MAX(36, [_stops sizeThatFits:CGSizeMake(size.width, 0)].height);CGFloat text = _title.font.lineHeight + _artist.font.lineHeight + _state.font.lineHeight;@@ -272,15 +281,25 @@ static CGFloat height(float rms) {- (void)didMoveToWindow {[super didMoveToWindow];- [_timer invalidate];- _timer = nil;+ [self stopTimer];if (!self.window) return;+ // Pushed while in the background, the timer waits for WillEnterForeground.+ if (UIApplication.sharedApplication.applicationState != UIApplicationStateBackground) [self startTimer];+ _track = nil;+ [self refresh];+}++- (void)startTimer {+ if (_timer || !self.window) return;__weak typeof(self) weakSelf = self;// In the common modes, so the lines go on while the page is scrolled._timer = [NSTimer timerWithTimeInterval:kPoll repeats:YES block:^(NSTimer *timer) { [weakSelf tick]; }];[NSRunLoop.mainRunLoop addTimer:_timer forMode:NSRunLoopCommonModes];- _track = nil;- [self refresh];+}++- (void)stopTimer {+ [_timer invalidate];+ _timer = nil;}#pragma mark - what it shows@@ -330,7 +349,8 @@ static CGFloat height(float rms) {}- (void)tick {- // Spotify in the background plays on and so runs this timer: no reads then, so Sing rests as with the page gone.+ // A tick before the background notification stops the timer, or from a page put in a window there: no reads+ // then, so Sing rests as with the page gone.if (UIApplication.sharedApplication.applicationState == UIApplicationStateBackground) return;// The words ten times a second, the lines at every read.if (_ticks++ % 3 == 0) [self refresh];diff --git a/tweak/Sources/Shared/Sing/SGSingEngine.m b/tweak/Sources/Shared/Sing/SGSingEngine.mindex aed667c0..06f7275b 100644--- a/tweak/Sources/Shared/Sing/SGSingEngine.m+++ b/tweak/Sources/Shared/Sing/SGSingEngine.m@@ -30,8 +30,10 @@ static const uint64_t kReturn = kSGSingEngineHop;static const uint64_t kBudget = kSGSingRate * 8;// The loudness the Sing page draws: per tenth of a second of the song, kept for the last kLevelSlots of them.enum { kLevelBlock = kSGSingRate / 10, kLevelSlots = 128 };-// How often the worker looks for a new window.+// How often the worker looks for a new window; and after this many looks at a `written` that has not moved (0.5 s,+// longer than any IO buffer: Spotify paused, or its decoder stalled) it sleeps until a render moves it.static const useconds_t kPoll = 10000;+static const unsigned kStillPolls = 500000 / kPoll;// Spatial voice: at 90 degrees the pan goes this far of the way to one ear, the far ear hears the voice this// many frames late (0.65 ms, sound's way around a head) and through a one-pole low-pass of this coefficient// (about 3 kHz); the angle glides to where it is set over this long.@@ -91,6 +93,8 @@ struct SGSingEngine {// The worker's.pthread_t worker;atomic_bool alive;+ dispatch_semaphore_t wake; // slept on while off, held or without a model; the setters and Destroy signal it+ atomic_bool sleeping; // asleep on `wake` until `written` moves: the one render that moves it signalsos_unfair_lock lock; // the separator, the error and `asked`void *separator; // retainedNSString *error;@@ -236,7 +240,10 @@ OSStatus SGSingEngineRender(SGSingEngine *engine, UInt32 frames, float *left, flreturn status;}written += need + ahead;- atomic_store_explicit(&engine->written, written, memory_order_release);+ // Sequentially consistent, with the worker's store of `sleeping` and its re-read of `written`: one of the two+ // threads sees the other's write, so a worker going to sleep as this moves `written` is never left asleep.+ atomic_store(&engine->written, written);+ if (need + ahead && atomic_load(&engine->sleeping) && atomic_exchange(&engine->sleeping, false)) dispatch_semaphore_signal(engine->wake);}uint64_t ready = atomic_load_explicit(&engine->ready, memory_order_acquire);@@ -409,8 +416,8 @@ static void measureLevels(SGSingEngine *engine, uint64_t start, uint64_t ready)static void *work(void *argument) {SGSingEngine *engine = argument;pthread_setname_np("spotifyglass.sing");- unsigned generation = UINT_MAX;- uint64_t start = 0, previousEnd = 0;+ unsigned generation = UINT_MAX, still = 0;+ uint64_t start = 0, previousEnd = 0, lastWritten = 0;while (atomic_load(&engine->alive)) {unsigned now = atomic_load(&engine->generation);if (now != generation) {@@ -422,7 +429,21 @@ static void *work(void *argument) {SGSingSeparator *separator = currentSeparator(engine);uint64_t written = atomic_load_explicit(&engine->written, memory_order_acquire);uint64_t played = atomic_load_explicit(&engine->played, memory_order_relaxed);- if (!separator || !atomic_load(&engine->on) || atomic_load(&engine->paused) || written < start + kSGSingWindowFrames) {+ if (!separator || !atomic_load(&engine->on) || atomic_load(&engine->paused)) {+ dispatch_semaphore_wait(engine->wake, DISPATCH_TIME_FOREVER);+ continue;+ }+ if (written < start + kSGSingWindowFrames) {+ if (written != lastWritten) {+ lastWritten = written;+ still = 0;+ } else if (++still >= kStillPolls) {+ // Woken with `written` as it was (a setter, a stray signal), it comes straight back here and sleeps on.+ atomic_store(&engine->sleeping, true);+ if (atomic_load(&engine->written) == written) dispatch_semaphore_wait(engine->wake, DISPATCH_TIME_FOREVER);+ atomic_store(&engine->sleeping, false);+ continue;+ }usleep(kPoll);continue;}@@ -483,6 +504,7 @@ SGSingEngine *SGSingEngineCreate(void) {SGSingEngine *engine = calloc(1, sizeof *engine);if (!engine) return NULL;engine->lock = OS_UNFAIR_LOCK_INIT;+ engine->wake = dispatch_semaphore_create(0);engine->left = calloc(kRing, sizeof(float));engine->right = calloc(kRing, sizeof(float));engine->vocalsLeft = calloc(kRing, sizeof(float));@@ -521,7 +543,11 @@ SGSingEngine *SGSingEngineCreate(void) {void SGSingEngineDestroy(SGSingEngine *engine) {if (!engine) return;atomic_store(&engine->alive, false);- if (engine->worker) pthread_join(engine->worker, NULL);+ if (engine->worker) {+ dispatch_semaphore_signal(engine->wake);+ pthread_join(engine->worker, NULL);+ }+ engine->wake = nil;if (engine->separator) CFRelease(engine->separator);engine->error = nil;for (int c = 0; c < 2; c++) {@@ -545,17 +571,19 @@ void SGSingEngineSetSeparator(SGSingEngine *engine, SGSingSeparator *separator)engine->separator = retained;os_unfair_lock_unlock(&engine->lock);atomic_store(&engine->hasSeparator, retained != NULL);+ if ((old != NULL) != (retained != NULL)) dispatch_semaphore_signal(engine->wake);// Released outside the lock; the worker holds its own reference while it runs one.if (old) CFRelease(old);}void SGSingEngineSetOn(SGSingEngine *engine, bool on) {+ bool was = atomic_exchange(&engine->on, on);// Switched on again, it tries again with a full budget.- if (on && !atomic_exchange(&engine->on, true)) {+ if (on && !was) {atomic_store(&engine->freshBudget, true);atomic_store(&engine->gaveUp, false);}- atomic_store(&engine->on, on);+ if (was != on) dispatch_semaphore_signal(engine->wake);}void SGSingEngineHoldBudget(SGSingEngine *engine, bool held) {@@ -590,7 +618,7 @@ void SGSingEngineSetVoiceAngle(SGSingEngine *engine, float radians) {}void SGSingEngineSetPaused(SGSingEngine *engine, bool paused) {- atomic_store(&engine->paused, paused);+ if (atomic_exchange(&engine->paused, paused) != paused) dispatch_semaphore_signal(engine->wake);}void SGSingEngineSetLeadCap(SGSingEngine *engine, double seconds) {