Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.
C
feat: redesigned Home, decluttered to music on black, and a hang sampler for FLEX builds
Vojtěch Škopek7168f76919b6
diff --git a/AGENTS.md b/AGENTS.mdindex f8993dcb..70086409 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -11,7 +11,7 @@ A Theos tweak (Objective-C + Logos) injected into the decrypted Spotify iOS app.Home gradient, AMOLED switch, accent colour...).- **Redesigned**: the mod's own Liquid Glass look, from a clean sheet. It includes the glass tab bar,search field and now playing bar, the redesigned player and lyrics page with Apple Music style lyrics- always on, black throughout, and its own accent colour. No native tweak runs.+ always on, a decluttered Home, black throughout, and its own accent colour. No native tweak runs.Anything that doesn't draw on Spotify's screens works the same under both: ads, privacy, lyricssources, gestures, blocked artists, flags.diff --git a/docs/tweaks.md b/docs/tweaks.mdindex 8394a32e..7644df8e 100644--- a/docs/tweaks.md+++ b/docs/tweaks.md@@ -13,7 +13,7 @@tweak/Sources/Redesigned/ the redesign, running only while Redesigned UI is ontweak/Sources/App/ what brings the layers together: Mod Settings' root and composed pages, the Mod page,backup and signing, the welcome tour- tweak/Sources/Diagnostics/ screen dumps and the tree server of FLEX builds+ tweak/Sources/Diagnostics/ screen dumps, the tree server and the main thread hang sampler of FLEX buildsscripts/ pipeline.sh (build + inject), install.sh (sign + install), record-trees.py,record-session.py, dump-log.sh, extract-flags.py, publish.sh (release: version bump,site release.json)@@ -108,6 +108,11 @@ Redesigned:Player/ the redesigned full screen player (Player.h lists its files)Lyrics/ the full screen lyrics page on glass with Apple Music style lyrics over it, always on (SGRKaraokeView,also over the card under the player, Player/KaraokeCard.x)+ Home/ Home decluttered to music on black (an allow list of its sections: shortcuts, the DJ without its heading and+ transcript, the shelves of cards), a large title where the filter pills were with the avatar at the trailing+ edge, the shelves' headings at the Music app's size, each shortcut tile's cover run across it blurred+ (SGRPalette's extension), continuous corners on the covers, and in FLEX builds a meter of each scroll's+ frames and the hooks' time (Home.h lists its files)App:diff --git a/tweak/Sources/Diagnostics/SGHangSampler.h b/tweak/Sources/Diagnostics/SGHangSampler.hnew file mode 100644index 00000000..22a26f73--- /dev/null+++ b/tweak/Sources/Diagnostics/SGHangSampler.h@@ -0,0 +1,13 @@+// FLEX builds: what the main thread is doing while it is stuck. While a watch is running, a background+// thread pings the main queue every 10 ms; once a ping has waited `kThreshold` (120 ms) the main thread+// is suspended for an instant, its stack walked by frame pointers, resumed, and the frames logged as+// "hang <reason> <n>/<m>" with the image and symbol of each, or the address in Spotify's own binary for+// scripts to symbolicate against its symbol table. A long stall is sampled again every 80 ms, up to 12+// samples a stall.+//+// Threading: start and stop on the main thread. Watches nest; the sampler runs while any is open.+#import <Foundation/Foundation.h>++// Runs the sampler until the matching stop, or for `seconds` when that is above 0 (no stop then).+void SGHangSamplerStart(NSString *reason, NSTimeInterval seconds);+void SGHangSamplerStop(void);diff --git a/tweak/Sources/Diagnostics/SGHangSampler.m b/tweak/Sources/Diagnostics/SGHangSampler.mnew file mode 100644index 00000000..18d8111b--- /dev/null+++ b/tweak/Sources/Diagnostics/SGHangSampler.m@@ -0,0 +1,139 @@+#import <mach/mach.h>+#import <mach/mach_time.h>+#import <pthread.h>+#import <dlfcn.h>+#import <mach-o/dyld.h>+#import <stdatomic.h>+#import "Core/SGCore.h"+#import "SGHangSampler.h"++static const double kThreshold = 0.12, kInterval = 0.08;+static const useconds_t kTick = 10000;+enum { kMaxFrames = 40, kMaxSamplesPerStall = 12 };+// Return addresses signed by pointer authentication keep their address in the low bits.+static const uintptr_t kAddressMask = 0x0000007FFFFFFFFFull;++static mach_port_t sg_main;+static uintptr_t sg_stackLow, sg_stackHigh;+static atomic_int sg_watches;+static atomic_uint_fast64_t sg_pending; // mach time of the ping not answered yet, 0 when none+static atomic_bool sg_running;+static NSString *sg_reason;++static double seconds(uint64_t mach) {+ static mach_timebase_info_data_t base;+ if (!base.denom) mach_timebase_info(&base);+ return (double)mach * base.numer / base.denom / 1e9;+}++// Nothing here may allocate or lock: the main thread is suspended and may hold either.+static int walk(uintptr_t frames[kMaxFrames]) {+ int n = 0;+ if (thread_suspend(sg_main) != KERN_SUCCESS) return 0;+ arm_thread_state64_t state;+ mach_msg_type_number_t count = ARM_THREAD_STATE64_COUNT;+ if (thread_get_state(sg_main, ARM_THREAD_STATE64, (thread_state_t)&state, &count) == KERN_SUCCESS) {+ frames[n++] = (uintptr_t)arm_thread_state64_get_pc(state) & kAddressMask;+ frames[n++] = (uintptr_t)arm_thread_state64_get_lr(state) & kAddressMask;+ uintptr_t fp = (uintptr_t)arm_thread_state64_get_fp(state);+ while (fp && n < kMaxFrames && fp >= sg_stackLow && fp + 2 * sizeof(uintptr_t) <= sg_stackHigh && !(fp & 0x7)) {+ uintptr_t next = ((uintptr_t *)fp)[0];+ uintptr_t ret = ((uintptr_t *)fp)[1] & kAddressMask;+ if (ret) frames[n++] = ret;+ if (next <= fp) break;+ fp = next;+ }+ }+ thread_resume(sg_main);+ return n;+}++static NSString *describe(uintptr_t address) {+ Dl_info info;+ if (!dladdr((void *)address, &info) || !info.dli_fname) return [NSString stringWithFormat:@"? 0x%lx", (unsigned long)address];+ const char *slash = strrchr(info.dli_fname, '/');+ NSString *image = @(slash ? slash + 1 : info.dli_fname);+ if ([image isEqualToString:@"Spotify"]) {+ intptr_t slide = 0;+ for (uint32_t i = 0; i < _dyld_image_count(); i++) {+ if (strcmp(_dyld_get_image_name(i), info.dli_fname) == 0) {+ slide = _dyld_get_image_vmaddr_slide(i);+ break;+ }+ }+ return [NSString stringWithFormat:@"Spotify 0x%lx", (unsigned long)(address - slide)];+ }+ if (info.dli_sname && strcmp(info.dli_sname, "<redacted>") != 0) {+ return [NSString stringWithFormat:@"%@ %s+%lu", image, info.dli_sname, (unsigned long)(address - (uintptr_t)info.dli_saddr)];+ }+ return [NSString stringWithFormat:@"%@ +0x%lx", image, (unsigned long)(address - (uintptr_t)info.dli_saddr)];+}++static void logSample(uintptr_t frames[kMaxFrames], int count, double stalled, int index, NSString *reason) {+ NSMutableString *text = [NSMutableString stringWithFormat:@"stalled %.0f ms, sample %d\n", stalled * 1000, index];+ for (int i = 0; i < count; i++) [text appendFormat:@"%@\n", describe(frames[i])];+ SGLogLong([NSString stringWithFormat:@"hang %@", reason], text);+}++static void *watch(void *unused) {+ uint64_t sampledStall = 0;+ int samples = 0;+ double lastSample = 0;+ for (;;) {+ while (atomic_load(&sg_watches) > 0) {+ uint64_t pending = atomic_load(&sg_pending);+ uint64_t now = mach_absolute_time();+ if (!pending) {+ atomic_store(&sg_pending, now);+ dispatch_async(dispatch_get_main_queue(), ^{ atomic_store(&sg_pending, 0); });+ } else {+ double stalled = seconds(now - pending);+ if (stalled >= kThreshold) {+ if (sampledStall != pending) {+ sampledStall = pending;+ samples = 0;+ lastSample = 0;+ }+ if (samples < kMaxSamplesPerStall && stalled - lastSample >= kInterval) {+ uintptr_t frames[kMaxFrames];+ int count = walk(frames);+ samples++;+ lastSample = stalled;+ if (count) logSample(frames, count, stalled, samples, sg_reason);+ }+ }+ }+ usleep(kTick);+ }+ atomic_store(&sg_running, false);+ // A watch opened while this thread was on its way out finds it still marked running and starts none.+ if (atomic_load(&sg_watches) > 0 && !atomic_exchange(&sg_running, true)) continue;+ break;+ }+ return NULL;+}++void SGHangSamplerStart(NSString *reason, NSTimeInterval duration) {+ if (!NSThread.isMainThread) return;+ if (!sg_main) {+ sg_main = mach_thread_self();+ pthread_t main = pthread_self();+ sg_stackHigh = (uintptr_t)pthread_get_stackaddr_np(main);+ sg_stackLow = sg_stackHigh - pthread_get_stacksize_np(main);+ }+ sg_reason = [reason copy];+ atomic_fetch_add(&sg_watches, 1);+ if (!atomic_exchange(&sg_running, true)) {+ pthread_t thread;+ if (pthread_create(&thread, NULL, watch, NULL) == 0) pthread_detach(thread);+ else atomic_store(&sg_running, false);+ SGLog(@"hang: sampling the main thread (%@)", reason);+ }+ if (duration > 0) {+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ SGHangSamplerStop(); });+ }+}++void SGHangSamplerStop(void) {+ if (atomic_load(&sg_watches) > 0) atomic_fetch_sub(&sg_watches, 1);+}diff --git a/tweak/Sources/Redesigned/Home/Home.h b/tweak/Sources/Redesigned/Home/Home.hnew file mode 100644index 00000000..93b0bf45--- /dev/null+++ b/tweak/Sources/Redesigned/Home/Home.h@@ -0,0 +1,35 @@+// The Home redesign: Spotify's Home page kept, with its controllers, lists and cards, decluttered to a+// music app on black and restyled from the Kit. No settings of its own.+//+// HomeSections.x an allow list of the feed's sections: the shortcuts grid, the DJ and the shelves of+// cards stay; video and episode previews, episode cards and any new kind collapse. The+// DJ loses its heading, and the flags the redesign forces on Home+// HomeHeader.x a large title where the filter pills were, the avatar at the trailing edge, no scrim+// HomeHeadings.x the shelves' headings in the Music app's size, drawn over Spotify's+// HomeCards.x the Encore button every card is: shortcut tiles (HomeTiles.m), continuous corners on the+// shelf covers, the DJ card at the card radius without its talking transcript+// HomeTiles.m a shortcut tile's picture run across the tile, blurred behind its title+// HomePerf.x FLEX builds: the frames of each scroll of Home and the time the hooks above took+//+// Every hook installs only while Redesigned UI is on (SGRedesignedUI).+// Threading: main thread only.+#import <UIKit/UIKit.h>++// Whether HomeSections.x has collapsed the section in this cell.+BOOL SGRHomeSectionCollapsed(UIView *cell);++// Styles a shortcut tile (id=Shortcut.Card.Home) and keeps its picture in step with its cover (HomeTiles.m).+void SGRHomeStyleTile(UIView *tile);++// FLEX builds only (HomePerf.x): a hook takes the time as it starts and hands it back as it ends; outside+// a FLEX build Begin returns 0 and End does nothing.+typedef NS_ENUM(NSUInteger, SGRHomeProbe) {+ SGRHomeProbeSections,+ SGRHomeProbeHeader,+ SGRHomeProbeHeadings,+ SGRHomeProbeCards,+ SGRHomeProbeTiles,+ SGRHomeProbeCount,+};+CFTimeInterval SGRHomeProbeBegin(void);+void SGRHomeProbeEnd(SGRHomeProbe probe, CFTimeInterval began);diff --git a/tweak/Sources/Redesigned/Home/HomeCards.x b/tweak/Sources/Redesigned/Home/HomeCards.xnew file mode 100644index 00000000..824ac3e4--- /dev/null+++ b/tweak/Sources/Redesigned/Home/HomeCards.x@@ -0,0 +1,88 @@+// Home redesign: every card Home keeps is the same Encore button, told apart where it lays out:+// id=Shortcut.Card.Home a shortcut tile 181x48 r=4 that clips, in a ConfigurableUIEventObservingView+// r=4 (trees/clean/home/01.txt:36-37): the cover radius, continuous, and its+// picture run across it (HomeTiles.m)+// id=Components.UI.HomeCard a shelf card, its picture Encore.ImageView 149x149 > UIImageView with no radius+// of its own (10.txt:2280-2286): cut at the cover radius, continuous, over the+// 4pt Spotify bakes into the picture (an artist's round one sits inside it)+// in Discovery_MediumDensityCardKit.DJMDCView the DJ card 370x192 r=8 that clips (01.txt:477-478): the card+// radius, and without the transcript Spotify's DJ talks through+// (Discovery_MediumDensityCardKit.TranscriptView, :500) or the Beta badge (:503)+#import "Core/SGCore.h"+#import "Redesigned/Kit/SGRKit.h"+#import "Home.h"++// Below this a card's picture is a glyph or a placeholder, not a cover.+static const CGFloat kCoverMinWidth = 80;++static char kImageKey;++static void roundCorners(UIView *view, CGFloat radius) {+ CALayer *layer = view.layer;+ if (layer.cornerRadius != radius) layer.cornerRadius = radius;+ if (layer.cornerCurve != kCACornerCurveContinuous) layer.cornerCurve = kCACornerCurveContinuous;+}++static void roundCover(UIView *card) {+ UIView *holder = SGRFindByIdentifier(card, @"Encore.ImageView", &kImageKey);+ if (holder.bounds.size.width < kCoverMinWidth) return;+ for (UIView *sub in holder.subviews) {+ if (![sub isKindOfClass:UIImageView.class]) continue;+ roundCorners(sub, SGRRadiusCover);+ if (!sub.layer.masksToBounds) sub.layer.masksToBounds = YES;+ }+}++// The transcript's own labels are plain UILabels the Kit keeps transparent; the Swift views around them+// take their alpha again on every pass.+static void calmDJ(UIView *card) {+ for (UIView *sub in card.subviews) {+ NSString *name = NSStringFromClass(sub.class);+ if (![name containsString:@"TranscriptView"] && ![name containsString:@"BetaBadge"]) continue;+ if (sub.alpha != 0) sub.alpha = 0;+ sub.accessibilityElementsHidden = YES;+ SGForEachView(sub, ^(UIView *v) {+ if ([v isKindOfClass:UILabel.class]) SGRSuppress(v);+ });+ }+}++static void style(UIView *button) {+ NSString *identifier = button.accessibilityIdentifier;+ if ([identifier isEqualToString:@"Shortcut.Card.Home"]) {+ roundCorners(button, SGRRadiusCover);+ if (button.superview.layer.cornerRadius > 0) roundCorners(button.superview, SGRRadiusCover);+ SGRHomeStyleTile(button);+ return;+ }+ if ([identifier isEqualToString:@"Components.UI.HomeCard"]) {+ roundCover(button);+ return;+ }+ static Class dj;+ if (!dj) dj = NSClassFromString(@"_TtC30Discovery_MediumDensityCardKit9DJMDCView");+ if (dj && [button.superview isKindOfClass:dj]) {+ roundCorners(button, SGRRadiusCard);+ calmDJ(button);+ static dispatch_once_t once;+ dispatch_once(&once, ^{ SGLog(@"redesign home: DJ card at the card radius, transcript gone"); });+ }+}++%hook _TtC19LegacyUI_ECMCoreKit31InteractableLayoutBackingButton+- (void)layoutSubviews {+ %orig;+ CFTimeInterval began = SGRHomeProbeBegin();+ style((UIView *)self);+ SGRHomeProbeEnd(SGRHomeProbeCards, began);+}+%end++%ctor {+ if (!SGRedesignedUI()) return;+ %init;+ SGRequireClasses(@[+ @"_TtC19LegacyUI_ECMCoreKit31InteractableLayoutBackingButton",+ @"_TtC30Discovery_MediumDensityCardKit9DJMDCView",+ ]);+}diff --git a/tweak/Sources/Redesigned/Home/HomeHeader.x b/tweak/Sources/Redesigned/Home/HomeHeader.xnew file mode 100644index 00000000..4f43f87d--- /dev/null+++ b/tweak/Sources/Redesigned/Home/HomeHeader.x@@ -0,0 +1,164 @@+// Home redesign: the header the way the Music app has it. The filter pills (All, Music, Podcasts) go and+// a large title takes their place at the leading edge; the avatar that opens the side drawer moves to the+// trailing edge; the scrim Spotify lays behind the header goes too, the soft scroll edge (Kit/SGREdgeEffect.x)+// being what keeps the title clear of the page scrolling under it, as on every other redesigned page.+//+// Tree (trees/clean/home/10.txt:3018-3051): FunkisViewController's view holds a 402x112 UIView around+// Reprise_LiquidGlassKit LiquidGlass.GradientView (the scrim) and, at {0, 62}, an+// ElementView<HomeHeaderElement> 402x50 holding HomeHeaderView > UIStackView {0, 8} 402x34 of two arranged+// views: ListeningActivity_ElementsKit.AdaptiveFaceContainer {16, 0} 32x34 (the avatar,+// id=Components.UI.SideDrawerButton) and LiquidGlass.LeadingFadeMaskView {48, 1} 354x32 around+// Home_PillUIKit.PillScrollView.+//+// The avatar moves by the stack's layout direction rather than by a frame of ours. Right to left, the stack+// lays its first view out at the trailing edge itself on every pass, whatever width the face container+// takes when friends listening show beside the avatar; its leading margin, 16pt, is the one Spotify gives+// the header in a right to left language. The pills stay in the stack with no alpha rather than hidden,+// the way the redesign takes any view out of a stack Spotify arranges (Kit/SGRRestyle.h).+//+// The title is Spotify's own name for the tab, read off its tab bar item (id=TabBar.Item.Home, 10.txt:3100),+// so it follows the app's language.+#import "Core/SGCore.h"+#import "Redesigned/Kit/SGRKit.h"+#import "Home.h"++// Tries at finding the tab's name before settling for the English one: a miss walks the window.+static const NSUInteger kTitleTries = 8;++static char kTitleKey, kTabKey;+static NSString *sg_tabName;++static void vanish(UIView *view) {+ if (!view) return;+ if (view.alpha != 0) view.alpha = 0;+ view.userInteractionEnabled = NO;+ view.accessibilityElementsHidden = YES;+}++static UIView *childNamed(UIView *host, NSString *marker) {+ for (UIView *sub in host.subviews) {+ if ([NSStringFromClass(sub.class) containsString:marker]) return sub;+ }+ return nil;+}++static NSString *tabName(UIWindow *window) {+ if (sg_tabName || !window) return sg_tabName ?: @"Home";+ static NSUInteger tries;+ if (tries >= kTitleTries) return @"Home";+ tries++;+ UIView *item = SGRFindByIdentifier(window, @"TabBar.Item.Home", &kTabKey);+ __block NSString *name = nil;+ if (item) SGForEachView(item, ^(UIView *v) {+ if (!name && [v isKindOfClass:UILabel.class] && ((UILabel *)v).text.length) name = ((UILabel *)v).text;+ });+ if (!name) {+ if (tries == kTitleTries) SGLog(@"redesign home: the Home tab's name not found, the title stays English");+ return @"Home";+ }+ sg_tabName = [name copy];+ SGLog(@"redesign home: title \"%@\" from the tab bar", sg_tabName);+ return sg_tabName;+}++static UILabel *titleIn(UIView *header) {+ UILabel *title = objc_getAssociatedObject(header, &kTitleKey);+ if (!title) {+ title = [UILabel new];+ title.textColor = SGRPrimary();+ title.accessibilityTraits = UIAccessibilityTraitHeader;+ title.adjustsFontSizeToFitWidth = YES;+ title.minimumScaleFactor = 0.6;+ title.userInteractionEnabled = NO;+ objc_setAssociatedObject(header, &kTitleKey, title, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ }+ if (title.superview != header) [header addSubview:title];+ return title;+}++// The header's views, found once: the page lays out again as it appears, and the walk names classes.+static __weak UIView *sg_header;+static __weak UIStackView *sg_stack;+static __weak UIView *sg_scrim;++static BOOL findHeader(UIView *view) {+ if (sg_stack && [sg_stack isDescendantOfView:view]) return YES;+ for (UIView *wrapper in view.subviews) {+ UIView *scrim = childNamed(wrapper, @"GradientView");+ if (scrim) sg_scrim = scrim;+ }+ UIView *header = childNamed(childNamed(view, @"HomeHeaderElement"), @"HomeHeaderView");+ for (UIView *sub in header.subviews) {+ if ([sub isKindOfClass:UIStackView.class]) sg_stack = (UIStackView *)sub;+ }+ sg_header = header;+ if (sg_stack) return YES;+ static dispatch_once_t once;+ dispatch_once(&once, ^{ SGLog(@"redesign home: header stack not found, header left as Spotify's"); });+ return NO;+}++static void layoutHeader(UIViewController *page) {+ UIView *view = page.viewIfLoaded;+ if (!view || !findHeader(view)) return;+ UIView *header = sg_header;+ UIStackView *stack = sg_stack;+ vanish(sg_scrim);++ static Class faceClass;+ if (!faceClass) faceClass = NSClassFromString(@"_TtC29ListeningActivity_ElementsKit21AdaptiveFaceContainer");+ UIView *face = nil;+ for (UIView *part in stack.arrangedSubviews) {+ if (faceClass && [part isKindOfClass:faceClass]) face = part;+ else vanish(part);+ }+ if (stack.semanticContentAttribute != UISemanticContentAttributeForceRightToLeft) {+ stack.semanticContentAttribute = UISemanticContentAttributeForceRightToLeft;+ [stack setNeedsLayout];+ }+ [stack layoutIfNeeded];++ UILabel *title = titleIn(header);+ NSString *text = tabName(header.window);+ if (![title.text isEqualToString:text]) {+ title.text = text;+ title.accessibilityLabel = text;+ }+ UIFont *font = SGRFont(UIFontTextStyleLargeTitle, UIFontWeightBold, UIContentSizeCategoryLarge);+ if (![title.font isEqual:font]) title.font = font;++ CGFloat trailing = face ? CGRectGetMinX([stack convertRect:face.frame toView:header]) - SGRGrid : header.bounds.size.width - SGRSideMargin;+ CGFloat height = ceil(font.lineHeight);+ CGRect frame = CGRectMake(SGRSideMargin, round(CGRectGetMidY(stack.frame) - height / 2), MAX(0, trailing - SGRSideMargin), height);+ if (!CGRectEqualToRect(title.frame, frame)) title.frame = frame;++ static dispatch_once_t once;+ dispatch_once(&once, ^{+ SGLog(@"redesign home: header %@, avatar %@ in the stack %@, title %@, scrim %@", NSStringFromCGRect(header.frame),+ face ? NSStringFromCGRect(face.frame) : @"not found", NSStringFromCGRect(stack.frame), NSStringFromCGRect(frame),+ sg_scrim ? @"found" : @"not found");+ });+}++%hook _TtC19Home_FunkisPageImpl20FunkisViewController+- (void)viewDidLayoutSubviews {+ %orig;+ CFTimeInterval began = SGRHomeProbeBegin();+ layoutHeader((UIViewController *)self);+ SGRHomeProbeEnd(SGRHomeProbeHeader, began);+}++- (void)traitCollectionDidChange:(UITraitCollection *)previous {+ %orig;+ [((UIViewController *)self).viewIfLoaded setNeedsLayout];+}+%end++%ctor {+ if (!SGRedesignedUI()) return;+ %init;+ SGRequireClasses(@[+ @"_TtC19Home_FunkisPageImpl20FunkisViewController",+ @"_TtC29ListeningActivity_ElementsKit21AdaptiveFaceContainer",+ ]);+}diff --git a/tweak/Sources/Redesigned/Home/HomeHeadings.x b/tweak/Sources/Redesigned/Home/HomeHeadings.xnew file mode 100644index 00000000..5dc09e76--- /dev/null+++ b/tweak/Sources/Redesigned/Home/HomeHeadings.x@@ -0,0 +1,101 @@+// Home redesign: a shelf's heading at the Music app's size, the title 2 style in bold (22pt at the default+// text size) over Spotify's 17pt. The title is a label of the Kit's own on the same baseline, drawn over+// Spotify's, which goes transparent: Spotify's label measures the heading, so the shelf keeps its layout,+// and the heading button keeps its touch and its accessibility label. The larger title reaches a few+// points up into the gap above the shelf. A small line over the title ("For fans of") and the artist's+// picture beside it stay Spotify's.+//+// Tree (trees/continuous/1.txt:2289-2312, 2026-09-17): Element_List.SupplementaryItemView 370x48 >+// ... > UIView id=Components.UI.SectionHeadingHome > AutoLayoutStackView > UIView > NoIntrinsicContentSizeButton+// (a11y "For fans of Yzomandias"), under which an ImageViewHolder 48x48 and a stack of SPTEncoreLabels:+// "For fans of " 11pt #B3B3B3, "Yzomandias" 17pt #FFFFFF at {0, 19.3} 91x20.7, and a hidden one. A heading+// of a title alone is 20.7 tall (10.txt:2363). "Show all" is Components.UI.NavigationButtonHome, a sibling+// of the button's stack, 0 wide while it is not offered.+#import "Core/SGCore.h"+#import "Redesigned/Kit/SGRKit.h"+#import "Home.h"++static char kTitleKey, kShowAllKey;++static UIView *headingAround(UIView *button) {+ NSUInteger depth = 0;+ for (UIView *v = button.superview; v && depth < 4; v = v.superview, depth++) {+ if ([v.accessibilityIdentifier isEqualToString:@"Components.UI.SectionHeadingHome"]) return v;+ }+ return nil;+}++static BOOL shown(UIView *view, UIView *root) {+ for (UIView *v = view; v && v != root; v = v.superview) {+ if (v.hidden) return NO;+ }+ return YES;+}++// The label that is the title: the largest text showing under the button, its own label aside.+static UILabel *titleLabelIn(UIView *button, UILabel *mine) {+ __block UILabel *title = nil;+ SGForEachView(button, ^(UIView *v) {+ if (v == mine || ![v isKindOfClass:UILabel.class]) return;+ UILabel *label = (UILabel *)v;+ if (!label.text.length || label.bounds.size.height < 1 || !shown(label, button)) return;+ if (!title || label.font.pointSize > title.font.pointSize) title = label;+ });+ return title;+}++static void restyle(UIView *button) {+ UIView *heading = headingAround(button);+ if (!heading) return;+ UILabel *mine = objc_getAssociatedObject(button, &kTitleKey);+ UILabel *theirs = titleLabelIn(button, mine);+ if (!theirs) {+ mine.hidden = YES;+ return;+ }+ if (!mine) {+ mine = [UILabel new];+ mine.userInteractionEnabled = NO;+ mine.accessibilityElementsHidden = YES;+ mine.lineBreakMode = NSLineBreakByTruncatingTail;+ objc_setAssociatedObject(button, &kTitleKey, mine, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ }+ if (mine.superview != button) [button addSubview:mine];+ mine.hidden = NO;++ UIFont *font = SGRFont(UIFontTextStyleTitle2, UIFontWeightBold, UIContentSizeCategoryLarge);+ if (![mine.font isEqual:font]) mine.font = font;+ if (![mine.text isEqualToString:theirs.text]) mine.text = theirs.text;+ if (![mine.textColor isEqual:theirs.textColor]) mine.textColor = theirs.textColor;+ if (theirs.alpha != 0) theirs.alpha = 0;++ // Spotify's label centres its one line in its bounds.+ CGRect frame = [theirs convertRect:theirs.bounds toView:button];+ UIFont *spotify = theirs.font;+ CGFloat baseline = CGRectGetMinY(frame) + (frame.size.height - spotify.lineHeight) / 2 + spotify.ascender;+ CGFloat x = CGRectGetMinX(frame);+ CGFloat available = heading.bounds.size.width - [button convertPoint:CGPointMake(x, 0) toView:heading].x;+ UIView *showAll = SGRFindByIdentifier(heading, @"Components.UI.NavigationButtonHome", &kShowAllKey);+ if (showAll.bounds.size.width > 1 && shown(showAll, heading)) available -= showAll.bounds.size.width + SGRGrid;+ CGFloat width = MIN(ceil([mine sizeThatFits:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX)].width), MAX(0, available));+ CGRect target = CGRectMake(x, round(baseline - font.ascender), width, ceil(font.lineHeight));+ if (!CGRectEqualToRect(mine.frame, target)) mine.frame = target;++ static dispatch_once_t once;+ dispatch_once(&once, ^{ SGLog(@"redesign home: heading \"%@\" %.0fpt drawn at %.0fpt, %@", theirs.text, spotify.pointSize, font.pointSize, NSStringFromCGRect(target)); });+}++%hook _TtCOOOE11Home_ECMKitO19LegacyUI_ECMCoreKit10Components18SectionHeadingHome2UI7Private28NoIntrinsicContentSizeButton+- (void)layoutSubviews {+ %orig;+ CFTimeInterval began = SGRHomeProbeBegin();+ restyle((UIView *)self);+ SGRHomeProbeEnd(SGRHomeProbeHeadings, began);+}+%end++%ctor {+ if (!SGRedesignedUI()) return;+ %init;+ SGRequireClasses(@[@"_TtCOOOE11Home_ECMKitO19LegacyUI_ECMCoreKit10Components18SectionHeadingHome2UI7Private28NoIntrinsicContentSizeButton"]);+}diff --git a/tweak/Sources/Redesigned/Home/HomePerf.x b/tweak/Sources/Redesigned/Home/HomePerf.xnew file mode 100644index 00000000..c86dbe00--- /dev/null+++ b/tweak/Sources/Redesigned/Home/HomePerf.x@@ -0,0 +1,192 @@+// Home redesign, FLEX builds only: what a scroll of Home costs. While Home's list is dragged or+// decelerating, a display link at the screen's own rate times each frame, and the Home hooks add up+// the calls and the time spent in them (SGRHomeProbeBegin/End). When the list settles, one log line+// says the scroll's frames, its hitches (a frame late by half a frame or more), the worst frame and+// each hook's share. A hitch the hooks do not account for is Spotify's main thread; lag with no+// hitches here is the render server (masks, clipping), which a display link does not see.+//+// Main thread stalls over 120 ms are sampled too (Diagnostics/SGHangSampler.h): for 90 s once Home is+// up, and during every scroll.+//+// The hooks install with the rest of the redesign and return at once outside a FLEX build: FLEX is+// injected after the tweak, so whether it is there is only known once the app runs.+#import <QuartzCore/QuartzCore.h>+#import "Core/SGCore.h"+#import "Diagnostics/Diagnostics.h"+#import "Diagnostics/SGHangSampler.h"+#import "Home.h"++// Frames with nothing moving before a scroll counts as over.+static const NSUInteger kSettledFrames = 10;+// A frame this long is described, the first few of each scroll.+static const CFTimeInterval kLongFrame = 0.1;+static const NSUInteger kLongFramesDescribed = 5;++// Section sizing includes Spotify's own measuring of the cell, which the hook calls through.+static const char *const kProbeNames[SGRHomeProbeCount] = {"section sizing", "header", "headings", "cards", "tiles"};+static NSUInteger sg_calls[SGRHomeProbeCount];+static CFTimeInterval sg_time[SGRHomeProbeCount];+static __weak UIScrollView *sg_list;+static char kHomeTabKey;++static BOOL probing(void) {+ static int state = -1;+ if (state < 0) state = SGIsDebugBuild() ? 1 : 0;+ return state == 1;+}++CFTimeInterval SGRHomeProbeBegin(void) {+ return probing() ? CACurrentMediaTime() : 0;+}++void SGRHomeProbeEnd(SGRHomeProbe probe, CFTimeInterval began) {+ if (began <= 0 || probe >= SGRHomeProbeCount) return;+ sg_calls[probe]++;+ sg_time[probe] += CACurrentMediaTime() - began;+}++@interface SGRHomeScrollMeter : NSObject+- (void)watch:(UIScrollView *)list;+@end++@implementation SGRHomeScrollMeter {+ CADisplayLink *_link;+ __weak UIScrollView *_list;+ CFTimeInterval _start, _last, _worst, _frameSum;+ NSUInteger _frames, _hitches, _dropped, _settled, _layouts, _described;+ NSUInteger _calls[SGRHomeProbeCount];+ CFTimeInterval _time[SGRHomeProbeCount];+}++- (void)watch:(UIScrollView *)list {+ _layouts++;+ if (_link || !(list.isDragging || list.isDecelerating)) return;+ _list = list;+ _start = CACurrentMediaTime();+ _last = _worst = _frameSum = 0;+ _frames = _hitches = _dropped = _settled = _described = 0;+ _layouts = 1;+ SGHangSamplerStart(@"home scroll", 0);+ memcpy(_calls, sg_calls, sizeof(_calls));+ memcpy(_time, sg_time, sizeof(_time));+ _link = [CADisplayLink displayLinkWithTarget:self selector:@selector(tick:)];+ // A link left at its default rate holds the whole app to 60 Hz while it runs (CLAUDE.md).+ if (@available(iOS 15.0, *)) _link.preferredFrameRateRange = CAFrameRateRangeMake(80, 120, 120);+ [_link addToRunLoop:NSRunLoop.mainRunLoop forMode:NSRunLoopCommonModes];+}++- (void)tick:(CADisplayLink *)link {+ CFTimeInterval expected = link.targetTimestamp - link.timestamp;+ if (_last > 0 && expected > 0) {+ CFTimeInterval gap = link.timestamp - _last;+ _frames++;+ _frameSum += expected;+ _worst = MAX(_worst, gap);+ if (gap > expected * 1.5) {+ _hitches++;+ _dropped += (NSUInteger)MAX(1, round(gap / expected) - 1);+ if (gap > kLongFrame && _described < kLongFramesDescribed) {+ _described++;+ [self describeLongFrame:gap];+ }+ }+ }+ _last = link.timestamp;+ UIScrollView *list = _list;+ if (list && (list.isDragging || list.isDecelerating || list.isTracking)) {+ _settled = 0;+ return;+ }+ if (++_settled >= kSettledFrames) [self finish];+}++// What was on screen around a long frame: each section in sight, top down, by the class of its root, and+// whether HomeSections.x collapsed it.+- (void)describeLongFrame:(CFTimeInterval)gap {+ UICollectionView *list = (UICollectionView *)_list;+ if (![list isKindOfClass:UICollectionView.class]) return;+ NSArray<UICollectionViewCell *> *cells = [list.visibleCells sortedArrayUsingComparator:^NSComparisonResult(UIView *a, UIView *b) {+ return a.frame.origin.y < b.frame.origin.y ? NSOrderedAscending : a.frame.origin.y > b.frame.origin.y ? NSOrderedDescending : NSOrderedSame;+ }];+ NSMutableArray<NSString *> *parts = [NSMutableArray array];+ for (UICollectionViewCell *cell in cells) {+ UIView *root = cell.contentView.subviews.firstObject.subviews.firstObject;+ NSString *name = root ? NSStringFromClass(root.class) : @"empty";+ NSRange dot = [name rangeOfString:@"." options:NSBackwardsSearch];+ if (dot.location != NSNotFound) name = [name substringFromIndex:dot.location + 1];+ [parts addObject:[NSString stringWithFormat:@"%@%@ %.0f", name, SGRHomeSectionCollapsed(cell) ? @" (collapsed)" : @"", cell.bounds.size.height]];+ }+ SGLog(@"home perf: %.0f ms frame at offset %.0f over %@", gap * 1000, list.contentOffset.y, [parts componentsJoinedByString:@", "]);+}++- (void)finish {+ [_link invalidate];+ _link = nil;+ SGHangSamplerStop();+ CFTimeInterval duration = CACurrentMediaTime() - _start;+ NSMutableString *hooks = [NSMutableString string];+ CFTimeInterval ours = 0;+ for (NSUInteger i = 0; i < SGRHomeProbeCount; i++) {+ NSUInteger calls = sg_calls[i] - _calls[i];+ CFTimeInterval time = sg_time[i] - _time[i];+ ours += time;+ if (calls) [hooks appendFormat:@", %s %lu in %.1f ms", kProbeNames[i], (unsigned long)calls, time * 1000];+ }+ double rate = _frames && _frameSum > 0 ? _frames / _frameSum : 0;+ SGLog(@"home perf: scroll %.1f s, %lu frames at %.0f Hz, %lu hitches (%lu frames dropped), worst frame %.0f ms, list laid out %lu times; hooks %.1f ms in all%@",+ duration, (unsigned long)_frames, rate, (unsigned long)_hitches, (unsigned long)_dropped, _worst * 1000,+ (unsigned long)_layouts, ours * 1000, hooks.length ? hooks : @", none called");+}++@end++static SGRHomeScrollMeter *sg_meter;++static BOOL isHomeTab(UIViewController *page) {+ NSNumber *answer = objc_getAssociatedObject(page, &kHomeTabKey);+ if (answer) return answer.boolValue;+ static Class funkis;+ if (!funkis) funkis = NSClassFromString(@"_TtC19Home_FunkisPageImpl20FunkisViewController");+ BOOL home = NO;+ for (UIViewController *parent = page.parentViewController; parent && !home; parent = parent.parentViewController) {+ home = [parent isKindOfClass:funkis];+ }+ if (page.parentViewController) objc_setAssociatedObject(page, &kHomeTabKey, @(home), OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ return home;+}++%hook _TtC16Home_EvoPageImpl33EvoLoadableResourceViewController+- (void)viewDidLayoutSubviews {+ %orig;+ if (!probing() || sg_list) return;+ UIViewController *page = (UIViewController *)self;+ if (!isHomeTab(page)) return;+ for (UIView *sub in page.viewIfLoaded.subviews) {+ if ([sub isKindOfClass:UICollectionView.class]) sg_list = (UIScrollView *)sub;+ }+ if (!sg_list) return;+ SGLog(@"home perf: measuring the scrolls of %@", NSStringFromClass(sg_list.class));+ // The lag reported came in the first half minute after launch, scrolling or not.+ static dispatch_once_t once;+ dispatch_once(&once, ^{ SGHangSamplerStart(@"after launch", 90); });+}+%end++// The list lays out on every frame it moves, which is when a scroll is noticed.+%hook _TtC16Home_CarouselKit29TouchCancellingCollectionView+- (void)layoutSubviews {+ %orig;+ if ((UIView *)self != sg_list) return;+ if (!sg_meter) sg_meter = [SGRHomeScrollMeter new];+ [sg_meter watch:(UIScrollView *)self];+}+%end++%ctor {+ if (!SGRedesignedUI()) return;+ %init;+ SGRequireClasses(@[+ @"_TtC16Home_EvoPageImpl33EvoLoadableResourceViewController",+ @"_TtC16Home_CarouselKit29TouchCancellingCollectionView",+ ]);+}diff --git a/tweak/Sources/Redesigned/Home/HomeSections.x b/tweak/Sources/Redesigned/Home/HomeSections.xnew file mode 100644index 00000000..b195c228--- /dev/null+++ b/tweak/Sources/Redesigned/Home/HomeSections.x@@ -0,0 +1,192 @@+// Home redesign: of the sections the feed sends, only the music ones stay: the grid of shortcuts, the+// DJ and the shelves of cards (Recents, Jump back in, Your playlists, New releases, the mixes, For fans+// of...). Every other section reports no height, so the list closes up around it: the medium density+// previews (a video or an episode playing muted under Unmute and Watch full episode, or a playlist to+// Preview), a heading over one of those (Fitness for you, Videos from your top artists), the episode+// cards, and any kind the server adds later.+//+// An allow list, as for the cards under the player (Redesigned/Player/PlayerCards.x): the feed is the+// server's, and a new kind should not turn up on a redesigned Home.+//+// Tree (trees/clean/home/10.txt): a section is an Element_List.CollectionViewCell of the page's list whose+// first subview is an ElementContentView over Home_EvoPageImpl.HomeStructure, then an+// ElementView<HomeStructure>, then the section's own root, which names its kind:+// Home_CarouselKit.TouchCancellingCollectionView a shelf of SimpleCards under a heading (:2274)+// UICollectionView with no identifier the shortcuts grid, Home_AnchorsAndShortcutsKit cells (01.txt:33)+// UICollectionView id=ActionCardCarouselElement episode cards (:696)+// UIStackView a heading over the DJ card's LazyElementView (01.txt:460),+// or over a medium density card (:973, :1443)+// Discovery_MediumDensityCardKit.MediumCardAnimatingLayout a preview card (:1300, :1746, :1882)+//+// The DJ stays without its heading ("Your own personal DJ" over a card that says DJ): the stack is a plain+// UIStackView, so the heading's LazyElementView is hidden before the cell is measured and the stack closes up.+//+// A dropped section still leaves the list's 24pt gap on either side of it (the shortcuts end at 216, the+// next section starts at 240, 01.txt:30, :325): the spacing is the list layout's, which a cell's height+// does not reach. Taking the sections out of the casita feed itself is what would close it.+#import "Core/SGCore.h"+#import "Redesigned/Kit/SGRKit.h"+#import "Home.h"++typedef NS_ENUM(NSInteger, SGRHomeKind) {+ SGRHomeKindPending, // the section's root is not in the cell yet: left as it is+ SGRHomeKindKeep,+ SGRHomeKindDrop,+};++static char kCollapsedKey;++static BOOL classNames(Class cls, NSString *marker, NSMutableDictionary<NSString *, NSMutableDictionary *> *cache) {+ if (!cls || !marker) return NO;+ NSMutableDictionary *answers = cache[marker];+ if (!answers) answers = cache[marker] = [NSMutableDictionary dictionary];+ NSNumber *answer = answers[(id<NSCopying>)cls];+ if (!answer) {+ answer = @([NSStringFromClass(cls) containsString:marker]);+ answers[(id<NSCopying>)cls] = answer;+ }+ return answer.boolValue;+}++static BOOL contentNames(UIView *content, NSString *marker) {+ static NSMutableDictionary<NSString *, NSMutableDictionary *> *cache;+ if (!cache) cache = [NSMutableDictionary dictionary];+ return content && classNames(object_getClass(content), marker, cache);+}++static BOOL isSection(UIView *content) {+ return contentNames(content, @"Home_EvoPageImpl13HomeStructure");+}++static void logOnce(NSString *what) {+ static NSMutableSet<NSString *> *logged;+ if (!logged) logged = [NSMutableSet set];+ if ([logged containsObject:what]) return;+ [logged addObject:what];+ SGLog(@"redesign home: %@", what);+}++// The shortcuts grid names no identifier; episode cards and whatever else comes as a bare list do.+static SGRHomeKind gridKind(UICollectionView *grid) {+ if (grid.accessibilityIdentifier.length) return SGRHomeKindDrop;+ UIView *cell = grid.visibleCells.firstObject;+ // A grid the list sized before it laid its own cells out: nothing but the shortcuts has come as one.+ if (!cell) return SGRHomeKindKeep;+ return contentNames(cell.subviews.firstObject, @"Home_AnchorsAndShortcutsKit") ? SGRHomeKindKeep : SGRHomeKindDrop;+}++// A LazyElementView names the element it will hold before it holds it.+static SGRHomeKind stackKind(UIStackView *stack) {+ for (UIView *part in stack.arrangedSubviews) {+ if ([NSStringFromClass(part.class) containsString:@"Discovery_DJElementKit"]) return SGRHomeKindKeep;+ }+ return stack.arrangedSubviews.count >= 2 ? SGRHomeKindDrop : SGRHomeKindPending;+}++// Before the cell is measured, so the height it reports is without the heading.+static void dropDJHeading(UIView *content) {+ UIStackView *stack = (UIStackView *)content.subviews.firstObject.subviews.firstObject;+ if (![stack isKindOfClass:UIStackView.class] || stackKind(stack) != SGRHomeKindKeep) return;+ for (UIView *part in stack.arrangedSubviews) {+ if (part.hidden || ![NSStringFromClass(part.class) containsString:@"Home_HeadingElementKit"]) continue;+ part.hidden = YES;+ logOnce(@"DJ heading hidden");+ }+}++static SGRHomeKind kindOf(UIView *content, NSString **rootName) {+ UIView *root = content.subviews.firstObject.subviews.firstObject;+ if (!root) return SGRHomeKindPending;+ *rootName = NSStringFromClass(root.class);+ static Class shelf;+ if (!shelf) shelf = NSClassFromString(@"_TtC16Home_CarouselKit29TouchCancellingCollectionView");+ if (shelf && [root isKindOfClass:shelf]) return SGRHomeKindKeep;+ if ([root isKindOfClass:UICollectionView.class]) return gridKind((UICollectionView *)root);+ if ([root isKindOfClass:UIStackView.class]) return stackKind((UIStackView *)root);+ return SGRHomeKindDrop;+}++// A dropped section's cell is 0 tall, but what it holds keeps the height it measured at, hidden and cut off+// by the cell. Spotify's content squeezed to 0 with the cell (trees/continuous/1.txt:375-381, every stack,+// heading and card at {402, 0}) breaks its required constraints on every layout pass of the cell, which+// held the main thread for up to 1.5 s at a time where dropped sections scrolled in (home perf, 2026-09-17).+static void collapse(UICollectionViewCell *cell, CGFloat natural) {+ UIView *content = cell.contentView;+ objc_setAssociatedObject(cell, &kCollapsedKey, @(natural), OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ if (content.autoresizingMask & UIViewAutoresizingFlexibleHeight) content.autoresizingMask &= ~UIViewAutoresizingFlexibleHeight;+ CGRect frame = CGRectMake(0, 0, cell.bounds.size.width, natural);+ if (!CGRectEqualToRect(content.frame, frame)) content.frame = frame;+ if (!content.hidden) content.hidden = YES;+ if (!cell.clipsToBounds) cell.clipsToBounds = YES;+ cell.accessibilityElementsHidden = YES;+}++static void expand(UICollectionViewCell *cell) {+ UIView *content = cell.contentView;+ objc_setAssociatedObject(cell, &kCollapsedKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ content.autoresizingMask |= UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;+ content.frame = cell.bounds;+ content.hidden = NO;+ cell.clipsToBounds = NO;+ cell.accessibilityElementsHidden = NO;+}++%hook _TtC12Element_List18CollectionViewCell+- (UICollectionViewLayoutAttributes *)preferredLayoutAttributesFittingAttributes:(UICollectionViewLayoutAttributes *)attributes {+ UICollectionViewCell *cell = (UICollectionViewCell *)self;+ UIView *content = cell.contentView;+ if (!isSection(content)) return %orig;+ CFTimeInterval began = SGRHomeProbeBegin();+ dropDJHeading(content);+ UICollectionViewLayoutAttributes *result = %orig;++ NSString *rootName = nil;+ SGRHomeKind kind = kindOf(content, &rootName);+ BOOL collapsed = objc_getAssociatedObject(cell, &kCollapsedKey) != nil;+ if (kind == SGRHomeKindDrop) {+ collapse(cell, MAX(1, result.size.height));+ result.size = CGSizeMake(result.size.width, 0);+ logOnce([@"dropped a section of " stringByAppendingString:rootName]);+ } else if (kind == SGRHomeKindKeep) {+ // Cells are reused across kinds: one collapsed before holds a section to keep now.+ if (collapsed) expand(cell);+ logOnce([@"kept a section of " stringByAppendingString:rootName]);+ } else {+ logOnce([@"sized a section before its root was in, left as it is: " stringByAppendingString:rootName ?: @"no root"]);+ }+ SGRHomeProbeEnd(SGRHomeProbeSections, began);+ return result;+}++// The cell's own passes may size the content to the cell again.+- (void)layoutSubviews {+ %orig;+ NSNumber *natural = objc_getAssociatedObject(self, &kCollapsedKey);+ if (natural) collapse((UICollectionViewCell *)self, natural.doubleValue);+}++- (void)prepareForReuse {+ %orig;+ if (objc_getAssociatedObject(self, &kCollapsedKey)) expand((UICollectionViewCell *)self);+}+%end++BOOL SGRHomeSectionCollapsed(UIView *cell) {+ return objc_getAssociatedObject(cell, &kCollapsedKey) != nil;+}++%ctor {+ // Registered whatever the switch says: the flag rows elsewhere lock to these while it is on.+ SGRedesignForceFlags(@"home", @{+ // The badge on the DJ card.+ @"ios-home-evopage-impl.dj_mdc_beta_badge_enabled": @NO,+ // The prompt field for Spotify's AI on Home.+ @"ios-home-evopage-impl.interactive_entrypoint_enabled": @NO,+ });+ if (!SGRedesignedUI()) return;+ %init;+ SGRequireClasses(@[+ @"_TtC12Element_List18CollectionViewCell",+ @"_TtC16Home_CarouselKit29TouchCancellingCollectionView",+ ]);+}diff --git a/tweak/Sources/Redesigned/Home/HomeTiles.m b/tweak/Sources/Redesigned/Home/HomeTiles.mnew file mode 100644index 00000000..aa1a7530--- /dev/null+++ b/tweak/Sources/Redesigned/Home/HomeTiles.m@@ -0,0 +1,162 @@+// Home redesign: a shortcut tile runs its own picture across itself. The sharp cover keeps its place at the+// leading edge and fades, from 40% of its width, into the same picture blurred, which carries on to the+// trailing edge as its own edge stretched out and dims under the title until white text on it passes WCAG AA+// (Kit/SGRPalette.h, +extensionForImage:). Until the picture has loaded, the tile is Spotify's grey.+//+// The picture sits behind Spotify's stack, over the tile's own fill, so the title, the playing indicator and+// the button's touches stay Spotify's. It is made off the main thread once per picture and follows the cover+// as Spotify sets it (SGRObserveImage), since a cover lands after the tile has laid out.+//+// Tree (trees/continuous/1.txt:3454-3465, 2026-09-17): InteractableLayoutBackingButton id=Shortcut.Card.Home+// 181x48 clips > UIView 181x48 bg=#[email protected] (the fill), then Encore.StackView > AutoLayoutStackView >+// UIView > UIView {0, 0} 48x48 bg=#[email protected] r=4 (the cover's square) > Encore.ImageView > UIImageView 48x48+// and the PlaceholderView; the title's stack starts at x 56.+#import <QuartzCore/QuartzCore.h>+#import "Core/SGCore.h"+#import "Redesigned/Kit/SGRKit.h"+#import "Home.h"++// Where the sharp cover starts to fade, as a share of its width.+static const CGFloat kFadeFrom = 0.4;++static char kBackdropKey, kImageKey, kMaskKey, kShownKey;++// Pictures already worked out, by the image object while it lives (main thread only).+static NSMapTable<UIImage *, UIImage *> *extensions(void) {+ static NSMapTable *table;+ if (!table) table = [NSMapTable weakToStrongObjectsMapTable];+ return table;+}++@interface SGRTileParts : NSObject+@property (nonatomic, weak) UIView *fill;+@property (nonatomic, weak) UIView *square;+@property (nonatomic, weak) UIImageView *cover;+@end++@implementation SGRTileParts+@end++static SGRTileParts *partsOf(UIView *tile) {+ UIView *holder = SGRFindByIdentifier(tile, @"Encore.ImageView", &kImageKey);+ SGRTileParts *parts = [SGRTileParts new];+ for (UIView *sub in holder.subviews) {+ if ([sub isKindOfClass:UIImageView.class]) parts.cover = (UIImageView *)sub;+ }+ parts.square = holder.superview;+ UIView *first = tile.subviews.firstObject;+ if (object_getClass(first) == UIView.class && CGRectEqualToRect(first.frame, tile.bounds)) parts.fill = first;+ return parts;+}++static UIView *backdropIn(UIView *tile, UIView *fill) {+ UIView *backdrop = objc_getAssociatedObject(tile, &kBackdropKey);+ if (!backdrop) {+ backdrop = [UIView new];+ backdrop.userInteractionEnabled = NO;+ backdrop.accessibilityElementsHidden = YES;+ backdrop.layer.contentsGravity = kCAGravityResize;+ backdrop.hidden = YES;+ objc_setAssociatedObject(tile, &kBackdropKey, backdrop, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ }+ if (backdrop.superview != tile) {+ if (fill) [tile insertSubview:backdrop aboveSubview:fill];+ else [tile insertSubview:backdrop atIndex:0];+ }+ if (!CGRectEqualToRect(backdrop.frame, tile.bounds)) backdrop.frame = tile.bounds;+ return backdrop;+}++static void fadeCover(UIView *square, BOOL on) {+ if (!square) return;+ if (!on) {+ if (square.layer.mask) square.layer.mask = nil;+ return;+ }+ CAGradientLayer *mask = objc_getAssociatedObject(square, &kMaskKey);+ if (!mask) {+ mask = [CAGradientLayer layer];+ mask.startPoint = CGPointMake(0, 0.5);+ mask.endPoint = CGPointMake(1, 0.5);+ mask.colors = @[(id)UIColor.blackColor.CGColor, (id)UIColor.clearColor.CGColor];+ mask.locations = @[@(kFadeFrom), @1];+ mask.actions = @{@"bounds": NSNull.null, @"position": NSNull.null};+ objc_setAssociatedObject(square, &kMaskKey, mask, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ }+ if (!CGRectEqualToRect(mask.frame, square.bounds)) mask.frame = square.bounds;+ if (square.layer.mask != mask) square.layer.mask = mask;+}++static void show(UIView *tile, UIView *backdrop, UIView *square, UIImage *extension, BOOL animated) {+ if (!extension) {+ backdrop.hidden = YES;+ backdrop.layer.contents = nil;+ fadeCover(square, NO);+ return;+ }+ if (backdrop.layer.contents == (__bridge id)extension.CGImage && !backdrop.hidden) {+ fadeCover(square, YES);+ return;+ }+ [CATransaction begin];+ [CATransaction setDisableActions:YES];+ if (animated && tile.window && !backdrop.hidden) {+ CATransition *fade = [CATransition animation];+ fade.type = kCATransitionFade;+ fade.duration = SGRCrossfade;+ [backdrop.layer addAnimation:fade forKey:@"contents"];+ }+ backdrop.layer.contents = (__bridge id)extension.CGImage;+ backdrop.hidden = NO;+ [CATransaction commit];+ fadeCover(square, YES);+}++static void refresh(UIView *tile) {+ SGRTileParts *parts = partsOf(tile);+ UIImageView *cover = parts.cover;+ UIView *square = parts.square;+ if (!cover || !square || square.bounds.size.width < 20 || tile.bounds.size.width <= square.bounds.size.width) return;+ UIView *backdrop = backdropIn(tile, parts.fill);++ UIImage *image = cover.image;+ // The cover's placeholder shows while there is no picture, over Spotify's grey.+ if (!image) {+ objc_setAssociatedObject(tile, &kShownKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ show(tile, backdrop, square, nil, NO);+ return;+ }+ UIImage *known = [extensions() objectForKey:image];+ if (known && CGSizeEqualToSize(known.size, CGSizeMake(ceil(tile.bounds.size.width), ceil(tile.bounds.size.height)))) {+ objc_setAssociatedObject(tile, &kShownKey, image, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ show(tile, backdrop, square, known, YES);+ return;+ }+ if (objc_getAssociatedObject(tile, &kShownKey) == image) return;+ objc_setAssociatedObject(tile, &kShownKey, image, OBJC_ASSOCIATION_RETAIN_NONATOMIC);++ CGFloat art = CGRectGetMaxX([square convertRect:square.bounds toView:tile]);+ __weak UIView *weakTile = tile;+ [SGRPalette extensionForImage:image size:tile.bounds.size artWidth:art completion:^(UIImage *extension) {+ UIView *strongTile = weakTile;+ if (extension) [extensions() setObject:extension forKey:image];+ // A tile reused for another cover in the meantime has asked for that one.+ if (!strongTile || objc_getAssociatedObject(strongTile, &kShownKey) != image) return;+ SGRTileParts *now = partsOf(strongTile);+ show(strongTile, backdropIn(strongTile, now.fill), now.square, extension, YES);+ }];+}++void SGRHomeStyleTile(UIView *tile) {+ CFTimeInterval began = SGRHomeProbeBegin();+ UIImageView *cover = partsOf(tile).cover;+ if (!cover) return;+ __weak UIView *weakTile = tile;+ // The block is replaced on every pass, so a cover taken into another tile tells the tile it is in now.+ SGRObserveImage(cover, ^(UIImageView *view) {+ UIView *strongTile = weakTile;+ if (strongTile && [view isDescendantOfView:strongTile]) refresh(strongTile);+ });+ refresh(tile);+ SGRHomeProbeEnd(SGRHomeProbeTiles, began);+}diff --git a/tweak/Sources/Redesigned/Kit/SGRPalette.h b/tweak/Sources/Redesigned/Kit/SGRPalette.hindex 2a7d5f33..207d2cff 100644--- a/tweak/Sources/Redesigned/Kit/SGRPalette.h+++ b/tweak/Sources/Redesigned/Kit/SGRPalette.h@@ -29,6 +29,15 @@ typedef struct {@property (nonatomic, readonly) UIImage *dissolve; // nil unless asked for, 96px wide// nil to the completion when the image has no bitmap to read (a symbol, a CIImage).+ (void)paletteForImage:(UIImage *)image request:(SGRPaletteRequest)request completion:(void (^)(SGRPalette *palette))completion;++// A strip `size` points across with the artwork `artWidth` wide at its leading edge, carried on to the+// trailing edge by the artwork's own trailing edge stretched out, the way a background extension continues+// a picture, and blurred. From the artwork's trailing edge on it is dimmed until white text on it passes+// WCAG AA (its 90th percentile luminance at 0.16, 0.08 with Increase Contrast, and never less than a+// 15% dim), so a row can run its picture on behind its text; under the artwork itself it is the same+// picture blurred, for the sharp one to fade into. One pixel a point, since it is blurred. nil to the+// completion when the image has no bitmap to read.++ (void)extensionForImage:(UIImage *)image size:(CGSize)size artWidth:(CGFloat)artWidth completion:(void (^)(UIImage *extension))completion;@end// Any colour made fit to be a field, the same way the edge colour is: for a colour Spotify hands overdiff --git a/tweak/Sources/Redesigned/Kit/SGRPalette.m b/tweak/Sources/Redesigned/Kit/SGRPalette.mindex 2b4ae45f..6d5a55ce 100644--- a/tweak/Sources/Redesigned/Kit/SGRPalette.m+++ b/tweak/Sources/Redesigned/Kit/SGRPalette.m@@ -10,6 +10,11 @@ static const CGFloat kMaxLuminance = 0.07, kMaxLuminanceContrast = 0.04;static const CGFloat kBackdropWidth = 160, kBackdropMaxHeight = 400, kBackdropSigma = 12;static const CGFloat kDissolveWidth = 96, kDissolveSigma = 5;static const CGFloat kFadeFrom = 0.55, kDissolveOpaque = 0.85;+static const CGFloat kExtensionSigma = 8, kExtensionLuminance = 0.16, kExtensionLuminanceContrast = 0.08, kExtensionMinDim = 0.15;+// The share of the artwork's width, at its trailing edge, stretched over the rest of the strip.+static const CGFloat kExtensionEdge = 0.04;+// The dim starts at this share of the artwork's width and is full this far past it, where a row's text begins.+static const CGFloat kExtensionRampFrom = 0.4, kExtensionRampOut = 8;@interface SGRPalette ()@property (nonatomic, readwrite) UIColor *edgeColor;@@ -155,6 +160,99 @@ static UIImage *finished(CGImageRef blurred, BOOL dim, CGFloat dimBottom, CGFloareturn image;}+#pragma mark - extension++// The artwork filling `rect` and clipped to it.+static void drawFillingRect(CGContextRef context, CGImageRef image, CGRect rect) {+ CGFloat iw = CGImageGetWidth(image), ih = CGImageGetHeight(image);+ CGFloat scale = MAX(rect.size.width / iw, rect.size.height / ih);+ CGContextSaveGState(context);+ CGContextClipToRect(context, rect);+ CGContextDrawImage(context, CGRectMake(CGRectGetMidX(rect) - iw * scale / 2, CGRectGetMidY(rect) - ih * scale / 2, iw * scale, ih * scale), image);+ CGContextRestoreGState(context);+}++// The luminance under which 90% of the pixels right of `fromX` fall, read off a histogram.+static CGFloat upperLuminance(const uint8_t *px, size_t width, size_t height, size_t fromX) {+ static CGFloat linear[256];+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ for (int i = 0; i < 256; i++) linear[i] = toLinear(i / 255.0);+ });+ enum { kBins = 64 };+ size_t bins[kBins] = {0}, total = 0;+ for (size_t y = 0; y < height; y++) {+ for (size_t x = fromX; x < width; x++) {+ const uint8_t *p = px + (y * width + x) * 4;+ CGFloat luminance = 0.2126 * linear[p[0]] + 0.7152 * linear[p[1]] + 0.0722 * linear[p[2]];+ bins[MIN(kBins - 1, (size_t)(luminance * kBins))]++;+ total++;+ }+ }+ size_t seen = 0;+ for (size_t i = 0; i < kBins; i++) {+ seen += bins[i];+ if (seen * 10 >= total * 9) return (CGFloat)(i + 1) / kBins;+ }+ return 1;+}++static UIImage *extensionOf(CGImageRef image, CGSize size, CGFloat artWidth, CGFloat ceiling) {+ size_t width = (size_t)ceil(size.width), height = (size_t)ceil(size.height);+ CGFloat art = MIN(MAX(1, round(artWidth)), width);+ CGContextRef context = newBitmap(width, height);+ if (!context) return nil;+ CGContextSetInterpolationQuality(context, kCGInterpolationMedium);+ drawFillingRect(context, image, CGRectMake(0, 0, art, height));+ if (art < width) {+ // The part of the picture that shows once it fills the artwork's place, and the strip at its trailing+ // edge; copies laid side by side instead repeat whatever stands out in the picture along the row.+ CGFloat iw = CGImageGetWidth(image), ih = CGImageGetHeight(image);+ CGFloat scale = MAX(art / iw, height / ih);+ CGFloat shownWidth = art / scale, shownHeight = height / scale;+ CGFloat edge = MAX(2, round(shownWidth * kExtensionEdge));+ CGRect strip = CGRectMake(floor((iw + shownWidth) / 2 - edge), floor((ih - shownHeight) / 2), edge, floor(shownHeight));+ CGImageRef column = CGImageCreateWithImageInRect(image, strip);+ if (column) CGContextDrawImage(context, CGRectMake(art, 0, width - art, height), column);+ CGImageRelease(column);+ }+ CGImageRef tiled = CGBitmapContextCreateImage(context);+ CGContextRelease(context);+ if (!tiled) return nil;+ CIImage *input = [CIImage imageWithCGImage:tiled];+ CGImageRelease(tiled);+ CIImage *output = [[input imageByClampingToExtent] imageByApplyingGaussianBlurWithSigma:kExtensionSigma];+ CGImageRef blurred = [blurContext() createCGImage:output fromRect:input.extent format:kCIFormatRGBA8 colorSpace:sRGB()];+ if (!blurred) return nil;++ context = newBitmap(width, height);+ if (!context) {+ CGImageRelease(blurred);+ return nil;+ }+ CGContextDrawImage(context, CGRectMake(0, 0, width, height), blurred);+ CGImageRelease(blurred);+ const uint8_t *px = CGBitmapContextGetData(context);+ size_t textFrom = (size_t)MIN(width - 1, art + kExtensionRampOut);+ CGFloat upper = px ? upperLuminance(px, width, height, textFrom) : 1;+ // A black over sRGB takes the encoded channels down linearly, the luminance by about that to the 2.4.+ CGFloat keep = MIN(1, ceiling / MAX(upper, 0.0001));+ CGFloat dim = MAX(kExtensionMinDim, 1 - pow(keep, 1 / 2.4));+ CGFloat components[] = {0, 0, 0, 0, 0, 0, 0, dim};+ CGFloat locations[] = {0, 1};+ CGGradientRef gradient = CGGradientCreateWithColorComponents(sRGB(), components, locations, 2);+ CGContextDrawLinearGradient(context, gradient, CGPointMake(art * kExtensionRampFrom, 0), CGPointMake(art + kExtensionRampOut, 0), kCGGradientDrawsAfterEndLocation);+ CGGradientRelease(gradient);+ CGImageRef result = CGBitmapContextCreateImage(context);+ CGContextRelease(context);+ UIImage *extension = result ? [UIImage imageWithCGImage:result scale:1 orientation:UIImageOrientationUp] : nil;+ CGImageRelease(result);++ static dispatch_once_t once;+ dispatch_once(&once, ^{ SGLog(@"redesign kit: first extension %zux%zu, luminance p90 %.3f, dim %.2f", width, height, upper, dim); });+ return extension;+}+@implementation SGRPalette+ (void)paletteForImage:(UIImage *)image request:(SGRPaletteRequest)request completion:(void (^)(SGRPalette *palette))completion {@@ -191,4 +289,17 @@ static UIImage *finished(CGImageRef blurred, BOOL dim, CGFloat dimBottom, CGFloa});}++ (void)extensionForImage:(UIImage *)image size:(CGSize)size artWidth:(CGFloat)artWidth completion:(void (^)(UIImage *extension))completion {+ if (!completion) return;+ CGFloat ceiling = SGRIncreaseContrast() ? kExtensionLuminanceContrast : kExtensionLuminance;+ dispatch_async(paletteQueue(), ^{+ CGImageRef cg = image.CGImage;+ UIImage *extension = nil;+ if (cg && CGImageGetWidth(cg) && CGImageGetHeight(cg) && size.width >= 1 && size.height >= 1 && artWidth >= 1) {+ extension = extensionOf(cg, size, artWidth, ceiling);+ }+ dispatch_async(dispatch_get_main_queue(), ^{ completion(extension); });+ });+}+@enddiff --git a/tweak/Sources/Redesigned/Kit/SGRRestyle.h b/tweak/Sources/Redesigned/Kit/SGRRestyle.hindex e861b412..14af977e 100644--- a/tweak/Sources/Redesigned/Kit/SGRRestyle.h+++ b/tweak/Sources/Redesigned/Kit/SGRRestyle.h@@ -22,6 +22,11 @@ void SGRSuppress(UIView *view);// setFont: by a runtime subclass of the instance, like SGRSuppress. Idempotent.void SGRMonospacedDigits(UILabel *label);+// `changed` after every setImage: on the image view, Spotify's included, for as long as the view lives, by a+// runtime subclass of the instance like SGRSuppress. A second call replaces the block. NO when the view+// cannot be subclassed (a KVO-observed instance): the caller then only sees what its own passes read.+BOOL SGRObserveImage(UIImageView *view, void (^changed)(UIImageView *view));+// The first view under `root` (itself included) with the accessibility identifier, depth first. The// answer is kept weakly on `root` under `cacheKey` and searched for again only when it is gone, has// left `root` or changed its identifier. nil when there is none; a miss is not cached.diff --git a/tweak/Sources/Redesigned/Kit/SGRRestyle.m b/tweak/Sources/Redesigned/Kit/SGRRestyle.mindex 7c291cb0..342418b0 100644--- a/tweak/Sources/Redesigned/Kit/SGRRestyle.m+++ b/tweak/Sources/Redesigned/Kit/SGRRestyle.m@@ -4,7 +4,7 @@#import "SGRRestyle.h"#import "SGRTokens.h"-static char kPlateKey;+static char kPlateKey, kImageObserverKey;@interface SGRWeakBox : NSObject@property (nonatomic, weak) id value;@@ -135,6 +135,29 @@ void SGRMonospacedDigits(UILabel *label) {keepMonospaced(label, original);}+BOOL SGRObserveImage(UIImageView *view, void (^changed)(UIImageView *view)) {+ if (![view isKindOfClass:UIImageView.class]) return NO;+ objc_setAssociatedObject(view, &kImageObserverKey, changed, OBJC_ASSOCIATION_COPY_NONATOMIC);+ BOOL kept = adopt(view, "SGRImageObserved_", ^(Class subclass, Class original) {+ addOverride(subclass, original, @selector(setImage:), ^(UIImageView *self, UIImage *image) {+ struct objc_super parent = {self, original};+ ((void (*)(struct objc_super *, SEL, id))objc_msgSendSuper)(&parent, @selector(setImage:), image);+ void (^block)(UIImageView *) = objc_getAssociatedObject(self, &kImageObserverKey);+ if (block) block(self);+ });+ });+ if (!kept) {+ static NSMutableSet<NSString *> *logged;+ if (!logged) logged = [NSMutableSet set];+ NSString *name = NSStringFromClass(object_getClass(view));+ if (![logged containsObject:name]) {+ [logged addObject:name];+ SGLog(@"redesign kit: %@ cannot be watched for its image", name);+ }+ }+ return kept;+}+// An identifier ending in * matches by prefix, for Spotify's ids that carry an entity after a dash.static BOOL identifierMatches(NSString *identifier, NSString *wanted) {if (!identifier) return NO;