Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.
C
feat: replace the glass tab bar with a system UITabBar
Vojtěch Škopek7b978e242cb4
diff --git a/tweak/Sources/Features/Navbar/TabBar.x b/tweak/Sources/Features/Navbar/TabBar.xindex 2da7f4fd..abb2fddc 100644--- a/tweak/Sources/Features/Navbar/TabBar.x+++ b/tweak/Sources/Features/Navbar/TabBar.x@@ -1,19 +1,33 @@-// Tab bar: gradient and labels go, icons centre, a glass capsule sits behind the tabs and a glass-// circle behind Create when Create is the last of them. Navbar/Navbar.x owns which items are on the-// bar and in what order; this file only paints whatever it left there.+// Tab bar: Spotify's own bar stays where it is but goes invisible, and a system UITabBar sits on top+// of it. On iOS 26+ with UIDesignRequiresCompatibility off, UIKit draws that bar as real Liquid Glass+// (selection bubble, lensing, light/dark adaptation) with no glass API of ours. Spotify's bar keeps+// its frame, so the page insets and the now playing bar stay where Spotify puts them.//-// Tree (trees/home.txt): NavigationUI_TabBarImpl.TabBarView > TabBarCompactView > TabBarGradientView-// + UIStackView 402x49 of four ElementContentView<TabBarItemElement> 100x49, each with an-// SPTEncoreIconView 24x24 and an SPTEncoreLabel.+// A tab picked on the system bar is passed on as a tap on the hidden Spotify item it mirrors, and the+// system bar's selection follows whichever Spotify label is painted white. Navbar/Navbar.x still+// composes the hidden row, so its order, hidden tabs and tabs of the mod's own carry over.+//+// Tree (trees/home.txt): NavigationUI_TabBarImpl.TabBarView > TabBarCompactView > UIStackView of+// ElementContentView<TabBarItemElement>, each with an SPTEncoreIconView and an SPTEncoreLabel.#import "Core/SGCore.h"#import "Navbar.h"+#import "Features/Appearance/Appearance.h"+#import "Headers/SPTEncoreIconView.h"+#import <objc/message.h>++static char kBarKey;+static __weak UIView *sg_stockBar;++@interface SGSystemTabBar : UITabBar <UITabBarDelegate>+@property (nonatomic, weak) UIView *stockBar;+@property (nonatomic, copy) NSArray<UIView *> *sources;+@end-static const CGFloat kPillHeight = 56;-static const CGFloat kCircleSize = 52;-static char kPillKey, kCircleKey;+static void syncBar(UIView *stockBar);-// The items the bar shows, left to right. Navbar/Navbar.x leaves the stack in Spotify's order and-// shifts the items across it, so the row reads by position on screen, not by arranged order.+#pragma mark - reading Spotify's items++// The items the bar shows, left to right as Navbar/Navbar.x placed them.static NSArray<UIView *> *tabItems(UIView *tabBar) {NSMutableArray<UIView *> *items = [NSMutableArray array];for (UIView *item in SGRowIn(tabBar).arrangedSubviews) {@@ -24,83 +38,271 @@ static NSArray<UIView *> *tabItems(UIView *tabBar) {}];}-static void styleTabBar(UIView *tabBar) {- if (!SGFlag(SGKeyTabBar, NO)) return;- sg_tabBarRoot = tabBar;- SGStripBackgrounds(tabBar);- tabBar.superview.layer.backgroundColor = NULL;+static UILabel *labelIn(UIView *item) {+ __block UILabel *label = nil;+ SGForEachView(item, ^(UIView *v) {+ if (!label && [v isKindOfClass:UILabel.class] && ((UILabel *)v).text.length) label = (UILabel *)v;+ });+ return label;+}++static UIView *iconIn(UIView *item) {+ __block UIView *icon = nil;+ SGForEachView(item, ^(UIView *v) {+ if (icon || v.bounds.size.width < 2) return;+ if ([v isKindOfClass:UIImageView.class] || [NSStringFromClass(v.class) containsString:@"IconView"]) icon = v;+ });+ return icon;+}++// Spotify paints the selected tab's label white and the rest #B3B3B3.+static BOOL isActive(UIView *item) {+ UIColor *color = labelIn(item).textColor;+ CGFloat white = 0, alpha = 0, r, g, b;+ if (![color getWhite:&white alpha:&alpha] && [color getRed:&r green:&g blue:&b alpha:&alpha]) white = MIN(r, MIN(g, b));+ return white > 0.95;+}++static BOOL hasInk(UIImage *image) {+ CGImageRef cg = image.CGImage;+ size_t width = CGImageGetWidth(cg), height = CGImageGetHeight(cg);+ if (!width || !height) return NO;+ NSMutableData *pixels = [NSMutableData dataWithLength:width * height];+ CGContextRef context = CGBitmapContextCreate(pixels.mutableBytes, width, height, 8, width, NULL, kCGImageAlphaOnly);+ CGContextDrawImage(context, CGRectMake(0, 0, width, height), cg);+ CGContextRelease(context);+ const uint8_t *alpha = pixels.bytes;+ for (size_t i = 0; i < pixels.length; i++) if (alpha[i] > 16) return YES;+ return NO;+}++static UIImage *renderLayer(CALayer *layer, CGSize size) {+ UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:size];+ UIImage *image = [renderer imageWithActions:^(UIGraphicsImageRendererContext *context) {+ [layer renderInContext:context.CGContext];+ }];+ return hasInk(image) ? [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] : nil;+}++// The SPTEncoreIcon an icon view was built with. Encore keeps it in a Swift ivar with no getter.+static id encoreIconOf(UIView *view) {+ Ivar ivar = class_getInstanceVariable(view.class, "icon");+ const char *type = ivar ? ivar_getTypeEncoding(ivar) : NULL;+ return type && type[0] == '@' ? object_getIvar(view, ivar) : nil;+}++// Encore draws a tab's icon from one SPTEncoreIcon in two states: isActive picks its filled variant.+// Both are drawn on an icon view of our own, off screen, so the images do not wait for Spotify's+// views to lay out and paint, and UITabBar swaps image and selectedImage itself.+static UIImage *glyphOf(UIView *item, BOOL active) {+ UIView *live = iconIn(item);+ if (!live) return nil;+ CGSize size = live.bounds.size;+ id icon = encoreIconOf(live);+ Class viewClass = NSClassFromString(@"SPTEncoreIconView");+ if (icon && viewClass) {+ static NSCache<NSString *, UIImage *> *cache;+ if (!cache) cache = [NSCache new];+ NSString *key = [NSString stringWithFormat:@"%@ %d %@", [icon respondsToSelector:@selector(name)] ? [icon name] : icon, active, NSStringFromCGSize(size)];+ UIImage *cached = [cache objectForKey:key];+ if (cached) return cached;+ SPTEncoreIconView *view = [[viewClass alloc] initWithIcon:icon];+ view.frame = (CGRect){CGPointZero, size};+ [view setForegroundColor:UIColor.whiteColor];+ if ([view respondsToSelector:@selector(setActiveForegroundColor:)]) [view setActiveForegroundColor:UIColor.whiteColor];+ if ([view respondsToSelector:@selector(setIsActive:)]) [view setIsActive:active];+ [view layoutIfNeeded];+ UIImage *image = renderLayer(view.layer, size);+ if (image) {+ [cache setObject:image forKey:key];+ return image;+ }+ }+ // Tabs of the mod's own draw a UIImageView, or an icon Encore would not draw off screen.+ return size.width >= 2 ? renderLayer(live.layer, size) : nil;+}++#pragma mark - passing a tap on++// NavigationUI_TabBarImpl's TabBarItemElementUI answers a tap recognizer (-handleTap), so the tap is+// replayed through the recognizer's own target-action pairs, the same call a real touch ends in.+static BOOL fireTapRecognizers(UIView *view) {+ Ivar targetsIvar = class_getInstanceVariable(UIGestureRecognizer.class, "_targets");+ if (!targetsIvar) return NO;+ BOOL fired = NO;+ for (UIGestureRecognizer *recognizer in view.gestureRecognizers) {+ if (![recognizer isKindOfClass:UITapGestureRecognizer.class] || !recognizer.enabled) continue;+ for (id pair in object_getIvar(recognizer, targetsIvar)) {+ Ivar targetIvar = class_getInstanceVariable([pair class], "_target");+ Ivar actionIvar = class_getInstanceVariable([pair class], "_action");+ if (!targetIvar || !actionIvar) continue;+ id target = object_getIvar(pair, targetIvar);+ SEL action = *(SEL *)((char *)(__bridge void *)pair + ivar_getOffset(actionIvar));+ if (!target || !action || ![target respondsToSelector:action]) continue;+ SGLog(@"tab bar: tap -> %@ %@", NSStringFromClass([target class]), NSStringFromSelector(action));+ ((void (*)(id, SEL, id))objc_msgSend)(target, action, recognizer);+ fired = YES;+ }+ }+ return fired;+}++static void forwardTap(UIView *item) {+ __block BOOL sent = NO;+ SGForEachView(item, ^(UIView *v) {+ if (!sent) sent = fireTapRecognizers(v);+ });+ SGForEachView(item, ^(UIView *v) {+ if (sent || ![v isKindOfClass:UIControl.class]) return;+ SGLog(@"tab bar: tap -> control %@", NSStringFromClass(v.class));+ [(UIControl *)v sendActionsForControlEvents:UIControlEventTouchUpInside];+ sent = YES;+ });+ if (!sent) {+ NSMutableString *out = [NSMutableString stringWithFormat:@"tab bar: nothing to tap in %@", NSStringFromClass(item.class)];+ SGForEachView(item, ^(UIView *v) {+ for (UIGestureRecognizer *r in v.gestureRecognizers) [out appendFormat:@"\n %@ on %@", r, NSStringFromClass(v.class)];+ });+ SGLogLong(@"navbar", out);+ }+}++#pragma mark - the system bar++@implementation SGSystemTabBar++- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {+ NSUInteger index = [self.items indexOfObject:item];+ if (index == NSNotFound || index >= self.sources.count) return;+ forwardTap(self.sources[index]);+ // Spotify repaints its labels a moment later; a tap it did not take snaps the selection back.+ UIView *stockBar = self.stockBar;+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ if (stockBar) syncBar(stockBar);+ });+}++@end++static void removeBar(UIView *stockBar) {+ UIView *bar = objc_getAssociatedObject(stockBar, &kBarKey);+ if (!bar) return;+ [bar removeFromSuperview];+ objc_setAssociatedObject(stockBar, &kBarKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ for (UIView *sub in stockBar.subviews) {+ sub.alpha = 1;+ sub.userInteractionEnabled = YES;+ }+}- NSArray<UIView *> *items = tabItems(tabBar);+static void logBarOnce(UITabBar *bar) {static dispatch_once_t once;- dispatch_once(&once, ^{ SGLog(@"tab bar %@ with %lu items", tabBar.class, (unsigned long)items.count); });- if (items.count < 2) return;-- // Create is a round button of its own, but only where Spotify puts it: last. Moved in among- // the others by Navbar/Navbar.x it joins them under the capsule instead.- BOOL circled = SGHasClass(items.lastObject, @"CreateMenu");- NSArray<UIView *> *capsuled = circled ? [items subarrayWithRange:NSMakeRange(0, items.count - 1)] : items;- CGRect first = SGFrameIn(items.firstObject, tabBar);- CGFloat midY = CGRectGetMidY(first);-- UIVisualEffectView *pill = SGGlassFor(tabBar, &kPillKey);- pill.hidden = capsuled.count == 0;- if (capsuled.count) {- CGFloat left = MAX(12, first.origin.x + 12);- pill.frame = CGRectMake(left, midY - kPillHeight / 2, CGRectGetMaxX(SGFrameIn(capsuled.lastObject, tabBar)) + 4 - left, kPillHeight);- SGShapeGlass(pill, kPillHeight / 2, YES);+ dispatch_once(&once, ^{+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ SGLogLong(@"navbar", [NSString stringWithFormat:@"system tab bar %@\n%@", NSStringFromCGRect(bar.frame), [bar recursiveDescription]]);+ });+ });+}++static void syncBar(UIView *stockBar) {+ if (!SGFlag(SGKeyTabBar, NO)) {+ removeBar(stockBar);+ return;+ }+ sg_stockBar = stockBar;++ SGSystemTabBar *bar = objc_getAssociatedObject(stockBar, &kBarKey);+ if (!bar) {+ bar = [[SGSystemTabBar alloc] initWithFrame:stockBar.bounds];+ bar.delegate = bar;+ bar.stockBar = stockBar;+ objc_setAssociatedObject(stockBar, &kBarKey, bar, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ }+ bar.tintColor = SGAccentColor() ?: [UIColor colorWithRed:0x1E / 255.0 green:0xD7 / 255.0 blue:0x60 / 255.0 alpha:1];++ for (UIView *sub in stockBar.subviews) {+ if (sub == bar) continue;+ sub.alpha = 0;+ sub.userInteractionEnabled = NO;+ }+ stockBar.superview.layer.backgroundColor = NULL;++ NSArray<UIView *> *sources = tabItems(stockBar);+ if (!sources.count) return;++ if (![sources isEqualToArray:bar.sources]) {+ NSMutableArray<UITabBarItem *> *items = [NSMutableArray array];+ for (UIView *source in sources) [items addObject:[[UITabBarItem alloc] initWithTitle:labelIn(source).text image:nil tag:items.count]];+ bar.sources = sources;+ [bar setItems:items animated:NO];+ NSMutableString *out = [NSMutableString stringWithString:@"tab bar icons"];+ for (UIView *source in sources) {+ UIView *live = iconIn(source);+ id icon = live ? encoreIconOf(live) : nil;+ id variant = [icon respondsToSelector:NSSelectorFromString(@"active")] ? ((id (*)(id, SEL))objc_msgSend)(icon, NSSelectorFromString(@"active")) : nil;+ [out appendFormat:@"\n %@: %@ icon %@ active-variant %@ live-isActive %d label-white %d", labelIn(source).text, NSStringFromClass(live.class),+ [icon respondsToSelector:@selector(name)] ? [icon name] : icon, [variant respondsToSelector:@selector(name)] ? [variant name] : variant,+ [live respondsToSelector:@selector(isActive)] ? [(SPTEncoreIconView *)live isActive] : -1, isActive(source)];+ }+ SGLogLong(@"navbar", out);}- UIVisualEffectView *circle = SGGlassFor(tabBar, &kCircleKey);- circle.hidden = !circled;- if (circled) {- CGRect last = SGFrameIn(items.lastObject, tabBar);- circle.frame = CGRectMake(CGRectGetMidX(last) - kCircleSize / 2, midY - kCircleSize / 2, kCircleSize, kCircleSize);- SGShapeGlass(circle, kCircleSize / 2, YES);+ UITabBarItem *selected = nil;+ BOOL missing = NO;+ for (NSUInteger i = 0; i < sources.count; i++) {+ UITabBarItem *item = bar.items[i];+ if (!item.image) item.image = glyphOf(sources[i], NO);+ if (!item.selectedImage || item.selectedImage == item.image) item.selectedImage = glyphOf(sources[i], YES);+ missing |= !item.image || !item.selectedImage;+ NSString *title = labelIn(sources[i]).text;+ if (title.length && ![title isEqualToString:item.title]) item.title = title;+ if (!selected && isActive(sources[i])) selected = item;}+ if (selected && bar.selectedItem != selected) bar.selectedItem = selected;+ // An icon view Spotify has not built yet is looked for again shortly, not on the next touch.+ static NSUInteger retries;+ if (missing && retries++ < 40) {+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ syncBar(stockBar);+ });+ }++ CGRect bounds = stockBar.bounds;+ CGFloat width = bounds.size.width;+ CGFloat height = MAX(bounds.size.height, [bar sizeThatFits:CGSizeMake(width, bounds.size.height)].height);+ CGRect frame = CGRectMake(0, CGRectGetMaxY(bounds) - height, width, height);+ if (!CGRectEqualToRect(bar.frame, frame)) bar.frame = frame;+ if (bar.superview != stockBar) [stockBar addSubview:bar];+ else if (stockBar.subviews.lastObject != bar) [stockBar bringSubviewToFront:bar];+ logBarOnce(bar);}+#pragma mark - hooks+static UIView *tabBarOf(UIView *item) {Class barClass = NSClassFromString(@"_TtC23NavigationUI_TabBarImpl10TabBarView");for (UIView *v = item.superview; v; v = v.superview) if ([v isKindOfClass:barClass]) return v;return nil;}-// Items lay out their own icon and label, after the bar; hide the label, centre the icon, then-// restyle the bar, whose own pass ran before the items had frames.-static void styleTabItem(UIView *item) {- if (!SGFlag(SGKeyTabBar, NO)) return;- CGFloat midY = CGRectGetMidY(item.bounds);- SGForEachView(item, ^(UIView *v) {- if ([v isKindOfClass:UILabel.class]) {- v.alpha = 0;- } else if ([NSStringFromClass(v.class) containsString:@"IconView"]) {- CGPoint target = [item convertPoint:CGPointMake(0, midY) toView:v.superview];- v.center = CGPointMake(v.center.x, target.y);- }- });- UIView *bar = tabBarOf(item);- if (bar) styleTabBar(bar);-}-%hook _TtC23NavigationUI_TabBarImpl10TabBarView- (void)layoutSubviews {%orig;- // After Spotify's own pass, so whatever it did to the row of items is undone before the glass- // is measured against it; the layoutIfNeeded below gives the moved items their frames.SGComposeTabBar((UIView *)self);- for (UIView *sub in ((UIView *)self).subviews) [sub layoutIfNeeded];- styleTabBar((UIView *)self);+ for (UIView *sub in ((UIView *)self).subviews) {+ if (![sub isKindOfClass:SGSystemTabBar.class]) [sub layoutIfNeeded];+ }+ syncBar((UIView *)self);SGLogTabBarRow((UIView *)self);}%end-// The bar's own pass runs once, before Spotify has filled the row, and does not run again until-// something touches it; the items lay out as they arrive, which is when the order is ours to set.+// The bar's own pass runs before Spotify has filled the row; the items lay out as they arrive.static void itemDidLayOut(UIView *item) {UIView *bar = tabBarOf(item);if (!bar) return;SGComposeTabBar(bar);- styleTabItem(item);+ syncBar(bar);SGLogTabBarRow(bar);}@@ -118,11 +320,23 @@ static void itemDidLayOut(UIView *item) {}%end+// A tab changed from elsewhere (a link, the side drawer) repaints the labels without a layout pass.+%hook _TtC23NavigationUI_TabBarImpl19TabBarContainerImpl+- (void)setSelectedViewController:(UIViewController *)controller {+ %orig;+ dispatch_async(dispatch_get_main_queue(), ^{+ UIView *bar = sg_stockBar;+ if (bar) syncBar(bar);+ });+}+%end+%ctor {%init;SGRequireClasses(@[@"_TtC23NavigationUI_TabBarImpl10TabBarView",@"_TtC23NavigationUI_TabBarImpl21TabBarItemElementView",@"_TtC25CreateMenu_TabBarItemImpl24CreateMenuTabBarItemView",+ @"_TtC23NavigationUI_TabBarImpl19TabBarContainerImpl",]);}diff --git a/tweak/Sources/Headers/SPTEncoreIconView.h b/tweak/Sources/Headers/SPTEncoreIconView.hindex f49f293b..14b09ff8 100644--- a/tweak/Sources/Headers/SPTEncoreIconView.h+++ b/tweak/Sources/Headers/SPTEncoreIconView.h@@ -5,4 +5,11 @@@interface SPTEncoreIconView : UIView- (instancetype)initWithIcon:(id)icon;- (void)setForegroundColor:(UIColor *)color;+- (void)setActiveForegroundColor:(UIColor *)color;+- (void)setIsActive:(BOOL)active;+- (BOOL)isActive;+@end++@interface NSObject (SPTEncoreIcon)+- (NSString *)name;@end