Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.
C
perf: let the player open and close smoothly with the karaoke card under it
Vojtěch Škopek103cf886f6f3
diff --git a/tweak/Sources/Features/Karaoke/KaraokeView.m b/tweak/Sources/Features/Karaoke/KaraokeView.mindex adbf40b4..4ccfd6fd 100644--- a/tweak/Sources/Features/Karaoke/KaraokeView.m+++ b/tweak/Sources/Features/Karaoke/KaraokeView.m@@ -1,6 +1,7 @@#import "Core/SGCore.h"#import "Karaoke.h"#import "Features/LyricsSources/LyricsSources.h"+#import "Features/NowPlaying/NowPlaying.h"static const CGFloat kFontSize = 30, kMargin = 24, kLineGap = 24, kRowTighten = 2;// The card under the player is a seventh of the page's height, so it gets Spotify's own card type@@ -18,6 +19,13 @@ static const CGFloat kCreditSize = 12, kCreditAlpha = 0.4, kCreditBottom = 10;static const NSTimeInterval kBrowseHold = 3; // after scrolling by hand, how long until it follows the song againstatic const double kFloatMinMs = 700, kFloatLeadMs = 80; // a short word still floats up this slowlystatic const double kClockSnapMs = 250, kClockPull = 0.08;+// Lines get views this far outside the visible part, in screen heights: half a screen above it+// and below, and a quarter more before a view is let go. The card under the player is in the tree+// for every open and close of the player, and every view it holds is one more for the window to+// take in and let go; a line comes into view about once in three seconds, and a page flung by+// hand fills in at a few lines a frame.+static const CGFloat kSightBehind = 0.5, kSightAhead = 0.5, kSightSlack = 0.25;+static const NSTimeInterval kTransitionSlack = 0.05; // after the player's animation, before the link is backstatic NSString *const kBlurPath = @"filters.gaussianBlur.inputRadius";@interface CAFilter : NSObject@@ -406,9 +414,15 @@ static double secant(SGSweepKnot *knots, NSUInteger i) {// A tap on the card is Spotify's, and opens the full screen page; seeking by tap is the page's.if (compact) self.userInteractionEnabled = NO;else [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)]];+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(playerTransitionChanged:) name:SGPlayerTransitionNotification object:nil];+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(playerTransitionChanged:) name:SGPlayerTransitionEndedNotification object:nil];return self;}+- (void)dealloc {+ [NSNotificationCenter.defaultCenter removeObserver:self];+}+- (void)tapped:(UITapGestureRecognizer *)tap {CGPoint point = [tap locationInView:_scroll];for (SGKaraokeLineView *view in _shown.allValues) {@@ -453,20 +467,42 @@ static double secant(SGSweepKnot *knots, NSUInteger i) {- (void)didMoveToWindow {[super didMoveToWindow];- [_link invalidate];- _link = nil;if (!self.window) {[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(followSong) object:nil];_browsing = NO;- return;}+ [self scheduleLink];+}++// The player opens and closes in animations that run at 120 Hz, and while a display link asked+// for 30 to 60, the range Apple's ProMotion guide says Core Animation gives priority to, those+// animations ran rough; the player and the lyrics themselves were smooth throughout. The card's+// link now asks for 60 but takes 120, and is put down for as long as the player animates, which+// NowPlayingBar.x announces as each animation starts and again as it ends; the card holds still+// under it, where nobody sees it. The timer is for an end that is never announced.+- (void)scheduleLink {+ [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(startLink) object:nil];+ [_link invalidate];+ _link = nil;+ if (!self.window) return;+ NSTimeInterval wait = SGPlayerTransitionEnds() - CACurrentMediaTime();+ if (wait <= 0) [self startLink];+ else [self performSelector:@selector(startLink) withObject:nil afterDelay:wait + kTransitionSlack inModes:@[NSRunLoopCommonModes]];+}++- (void)startLink {+ if (!self.window || _link) return;_link = [CADisplayLink displayLinkWithTarget:self selector:@selector(tick)];// The card stays in the window behind the full screen page, so both sweep at once; the card is- // a few lines tall and gives up the high refresh rate the page keeps.- _link.preferredFrameRateRange = _compact ? CAFrameRateRangeMake(30, 60, 60) : CAFrameRateRangeMake(80, 120, 120);+ // a few lines tall and is content with 60, the page keeps the high refresh rate.+ _link.preferredFrameRateRange = _compact ? CAFrameRateRangeMake(30, 120, 60) : CAFrameRateRangeMake(80, 120, 120);[_link addToRunLoop:NSRunLoop.mainRunLoop forMode:NSRunLoopCommonModes];}+- (void)playerTransitionChanged:(NSNotification *)note {+ [self scheduleLink];+}+// The mask sits in the scroll view's own coordinates, which move with the content as it scrolls, so// it is put back over the visible part on every frame, where the presentation layer says the// content is: that holds through a drag and through the animated scroll home alike. Left where@@ -540,10 +576,10 @@ static double secant(SGSweepKnot *knots, NSUInteger i) {return view;}-// Views for the lines within a screen's height of the visible part, wherever that is: around the+// Views for the lines just outside the visible part as well as in it, wherever that is: around the// sung line while following the song, around wherever the page has been scrolled to while browsing.-// The ones a further screen away are let go, so a long song costs a few dozen line views rather-// than one for every line, and the lines in sight are the only ones the compositor has to draw.+// The ones further off are let go, so a long song costs a couple of dozen line views rather than+// one for every line, and the lines in sight are the only ones the compositor has to draw.- (void)showLinesInSight {if (!_tops.count) return;CGFloat offset = ((CALayer *)_scroll.layer.presentationLayer ?: _scroll.layer).bounds.origin.y;@@ -551,18 +587,19 @@ static double secant(SGSweepKnot *knots, NSUInteger i) {_sightOffset = offset;_sightFocus = _focusTop;_sightActive = _active;- CGFloat height = self.bounds.size.height, from = offset - height, to = offset + 2 * height;+ CGFloat height = self.bounds.size.height;+ CGFloat from = offset - kSightBehind * height, to = offset + (1 + kSightAhead) * height, slack = kSightSlack * height;NSMutableArray<NSNumber *> *gone = [NSMutableArray array];for (NSNumber *key in _shown) {NSInteger index = key.integerValue;CGFloat top = [self topOfLine:index], bottom = top + _shown[key].bounds.size.height;- if (index != _active && (bottom < from - height || top > to + height)) [gone addObject:key];+ if (index != _active && (bottom < from - slack || top > to + slack)) [gone addObject:key];}for (NSNumber *key in gone) {[_shown[key] removeFromSuperview];[_shown removeObjectForKey:key];}- NSInteger count = (NSInteger)_tops.count, focus = MAX(_active, 0);+ NSInteger count = (NSInteger)_tops.count;NSMutableArray<NSNumber *> *wanted = [NSMutableArray array];for (NSInteger index = 0; index < count; index++) {if (_shown[@(index)]) continue;@@ -571,9 +608,11 @@ static double secant(SGSweepKnot *knots, NSUInteger i) {if (bottom < from || top > to) continue;[wanted addObject:@(index)];}- // A few a frame, the nearest the sung line first; the next frame picks up where this one left off.+ // A few a frame, the nearest the middle of the visible part first, so a page scrolled by hand+ // fills in what is in view before what is not; the next frame picks up where this one left off.+ CGFloat middle = offset + height / 2;[wanted sortUsingComparator:^NSComparisonResult(NSNumber *a, NSNumber *b) {- NSInteger da = labs(a.integerValue - focus), db = labs(b.integerValue - focus);+ CGFloat da = fabs([self topOfLine:a.integerValue] - middle), db = fabs([self topOfLine:b.integerValue] - middle);return da < db ? NSOrderedAscending : da > db ? NSOrderedDescending : NSOrderedSame;}];NSUInteger made = 0;diff --git a/tweak/Sources/Features/NowPlaying/NowPlaying.h b/tweak/Sources/Features/NowPlaying/NowPlaying.hindex 333ac162..554daa97 100644--- a/tweak/Sources/Features/NowPlaying/NowPlaying.h+++ b/tweak/Sources/Features/NowPlaying/NowPlaying.h@@ -10,3 +10,10 @@#define SGHideBarConnect @"spotifyglass.hide.barConnect" // the device button in the now playing barUIViewController *SGNowPlayingSettingsPage(void); // the Player page++// Posted by NowPlayingBar.x as the full screen player starts to open or close, before the animation+// runs, and again once it is over; SGPlayerTransitionEnds says when it is expected to be over (as+// CACurrentMediaTime), 0 when none runs.+extern NSString *const SGPlayerTransitionNotification;+extern NSString *const SGPlayerTransitionEndedNotification;+CFTimeInterval SGPlayerTransitionEnds(void);diff --git a/tweak/Sources/Features/NowPlaying/NowPlayingBar.x b/tweak/Sources/Features/NowPlaying/NowPlayingBar.xindex 7e7e0449..39cb6df1 100644--- a/tweak/Sources/Features/NowPlaying/NowPlayingBar.x+++ b/tweak/Sources/Features/NowPlaying/NowPlayingBar.x@@ -22,6 +22,37 @@ static __weak UIView *sg_barGlassHost = nil;// Open and close tapped in quick succession overlap; only the newest animation takes the bar back.static NSUInteger sg_barTransition = 0;+// The karaoke card under the player puts its display link down while the player animates.+NSString *const SGPlayerTransitionNotification = @"spotifyglass.playerTransition";+NSString *const SGPlayerTransitionEndedNotification = @"spotifyglass.playerTransitionEnded";+static CFTimeInterval sg_transitionEnds;+static NSUInteger sg_transitionGeneration;++CFTimeInterval SGPlayerTransitionEnds(void) {+ return sg_transitionEnds > CACurrentMediaTime() ? sg_transitionEnds : 0;+}++// The two animators hooked below are what the bar was written against, but the player of this+// Spotify never runs through them (no log of theirs has ever shown up), so the announcement comes+// from the appearance callbacks of a controller inside the player, which UIKit sends as the+// presentation or the dismissal begins, whatever animates it; the transition coordinator says when+// it is over, a cancelled swipe included.+static void announceTransition(UIViewController *unit, BOOL animated, NSString *what) {+ id<UIViewControllerTransitionCoordinator> coordinator = unit.transitionCoordinator;+ if (!animated || !coordinator) return;+ NSTimeInterval duration = MAX(0.1, coordinator.transitionDuration);+ NSUInteger generation = ++sg_transitionGeneration;+ sg_transitionEnds = CACurrentMediaTime() + duration;+ [NSNotificationCenter.defaultCenter postNotificationName:SGPlayerTransitionNotification object:nil];+ [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {+ if (generation != sg_transitionGeneration) return;+ sg_transitionEnds = 0;+ [NSNotificationCenter.defaultCenter postNotificationName:SGPlayerTransitionEndedNotification object:nil];+ }];+ static dispatch_once_t once;+ dispatch_once(&once, ^{ SGLog(@"player %@ over %.2fs, by its appearance callbacks", what, duration); });+}+static UIView *detectColoredCard(UIView *bar) {__block UIView *best = nil;__block CGFloat bestArea = 0;@@ -170,6 +201,8 @@ static void barStock(BOOL stock, NSTimeInterval fade) {static void playerTransition(id<UIViewControllerAnimatedTransitioning> animator, id<UIViewControllerContextTransitioning> context) {NSTimeInterval duration = MAX(0.1, [animator transitionDuration:context]);NSUInteger generation = ++sg_barTransition;+ sg_transitionEnds = CACurrentMediaTime() + duration;+ [NSNotificationCenter.defaultCenter postNotificationName:SGPlayerTransitionNotification object:nil];barStock(YES, MIN(kFadeOut, duration / 3));dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{if (generation == sg_barTransition) barStock(NO, kFadeIn);@@ -194,6 +227,17 @@ static void playerTransition(id<UIViewControllerAnimatedTransitioning> animator,}%end+%hook _TtC21NowPlaying_ScrollImpl27NPVBackgroundViewController+- (void)viewWillAppear:(BOOL)animated {+ %orig;+ announceTransition((UIViewController *)self, animated, @"opens");+}+- (void)viewWillDisappear:(BOOL)animated {+ %orig;+ announceTransition((UIViewController *)self, animated, @"closes");+}+%end+%hook _TtC23NowPlaying_ViewPageImpl35ShowFullscreenAnimatedTransitioning- (void)animateTransition:(id<UIViewControllerContextTransitioning>)context {playerTransition((id)self, context);@@ -213,6 +257,7 @@ static void playerTransition(id<UIViewControllerAnimatedTransitioning> animator,SGRequireClasses(@[@"_TtC18NowPlaying_BarImpl36NowPlayingBarContainerViewController",@"_TtC18NowPlaying_BarImpl27NowPlayingBarViewController",+ @"_TtC21NowPlaying_ScrollImpl27NPVBackgroundViewController",@"_TtC23NowPlaying_ViewPageImpl35ShowFullscreenAnimatedTransitioning",@"_TtC23NowPlaying_ViewPageImpl36CloseFullScreenAnimatedTransitioning",]);