Skip to content

Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.

C

feat: the Player preview remembers the last song while nothing plays

My-Name-Is-Jeff044d51369c11
diff --git a/docs/tweaks.md b/docs/tweaks.md
index 1f368ac3..5aa808f7 100644
--- a/docs/tweaks.md
+++ b/docs/tweaks.md
@@ -165,7 +165,8 @@ Shared:
Add a Tab sheet (AddTabSheet.m) with the icons a tab can wear, Encore's glyphs or SF Symbols
(TabIcons.m). The sheet runs in the simulator in harness/addtab/
Player/ the player's open and close announced (PlayerEvents.x), what the player is doing read through
- one hook for every feature that wants it (PlayerState.x), the lock screen widget's flags, and in the
+ one hook for every feature that wants it (PlayerState.x), the last track played for the settings
+ pages' previews to show when nothing plays (SGLastTrack.m), the lock screen widget's flags, and in the
more button's menu Speed and pitch: both done to Spotify's audio by Apple's time and pitch unit, put
between its mixer and its RemoteIO unit by taking over the connection Spotify makes between them
(SpeedPitchMenu.x, SpeedPitch.x, SGTimePitch.m). Spotify runs a chain per sample rate, so a local
diff --git a/harness/player/README.md b/harness/player/README.md
index 5ca7ebf6..3ecac667 100644
--- a/harness/player/README.md
+++ b/harness/player/README.md
@@ -82,6 +82,11 @@ come late, out of order, or not at all.
it without asking the server again. Fluid and then Animated again bring it back at once. The clip's address is
the run's own, so the store never has it from a run before. The log ends with
`preview checks: n of 7 right -- PASS` or `FAIL`; on the sources before the fix it read 5 of 7.
+- `card` plays nothing and opens the Player page at 1 s, then logs the card's title, artist and cover size: with
+ no track ever played, Not Playing over the accent's gradient; with `HARNESS_LAST=1`, a last track played with a
+ long title (gliding), its cover from the picture server and a Canvas of the run's own (`HARNESS_CANVAS_FILE`).
+ `HARNESS_BACKGROUND` is the background's index, Fluid if unset. For screenshots: 2026-10-06 on an iPhone 17 Pro,
+ iOS 27.0, the card read Not Playing over a dim green field, and Holocene with its cover over Fluid.
- `visualiser` plays the Visualiser background, fed by `stubs.m`'s stand-in for the audio effects' reader: a song
of its own at 120 beats a minute, handed over in buffers of 1024 at 48 kHz. It checks the hills stand on the
Fluid field held still with the reader on and the link at up to 60 fps, blur behind the lyrics with the link at
diff --git a/harness/player/build.sh b/harness/player/build.sh
index 1dbbeac3..a6cd06ad 100755
--- a/harness/player/build.sh
+++ b/harness/player/build.sh
@@ -20,7 +20,7 @@ xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-ar
"$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGViewTree.m "$SRC"/Core/SGGlass.m \
"$SRC"/Core/SGBackdrop.m "$SRC"/Core/SGFlagForce.m "$SRC"/Core/SGUIMode.m \
"$SRC"/Redesigned/Kit/SGRTokens.m "$SRC"/Redesigned/Kit/SGRPalette.m "$SRC"/Redesigned/Kit/SGRField.m "$SRC"/Redesigned/Kit/SGRFlow.m "$SRC"/Redesigned/Kit/SGRFluid.m "$SRC"/Shared/AnimatedArtwork/SGMotionCatalog.m "$SRC"/Shared/AnimatedArtwork/SGMotionStore.m \
- "$SRC"/Shared/AnimatedArtwork/SGMotionFollower.m "$SRC"/Shared/AnimatedArtwork/SGMotionClip.m \
+ "$SRC"/Shared/AnimatedArtwork/SGMotionFollower.m "$SRC"/Shared/AnimatedArtwork/SGMotionClip.m "$SRC"/Shared/Player/SGLastTrack.m \
"$SRC"/Redesigned/Kit/SGRGlass.m "$SRC"/Settings/SGMarquee.m "$SRC"/Redesigned/Kit/SGRGlyph.m "$SRC"/Redesigned/Kit/SGRRestyle.m \
"$SRC"/Redesigned/Kit/SGRedesign.m \
"$SRC"/Redesigned/Player/PlayerSettings.m "$SRC"/Redesigned/Player/PlayerVisualiser.m "$SRC"/Redesigned/Player/SGRSpectrum.m "$SRC"/Redesigned/NowPlayingBar/NowPlayingBarSettings.m \
diff --git a/harness/player/main.m b/harness/player/main.m
index 8f448001..8986bda8 100644
--- a/harness/player/main.m
+++ b/harness/player/main.m
@@ -608,6 +608,8 @@ static UIViewController *unitOf(UIView *view) {
return [next isKindOfClass:UIViewController.class] ? (UIViewController *)next : nil;
}
+static UIView *firstOfClass(UIView *root, NSString *name);
+
static void after(NSTimeInterval seconds, dispatch_block_t block) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(seconds * NSEC_PER_SEC)), dispatch_get_main_queue(), block);
}
@@ -632,6 +634,21 @@ static void after(NSTimeInterval seconds, dispatch_block_t block) {
UIImage *first = checks ? solid(UIColor.redColor) : _cover.image;
[self showOnScreen:first];
serve(imageURI(@"aaaa"), first, 0.2, NO);
+ // card: nothing plays; the Player page's card shows the last track played, or none.
+ if ([scenario() isEqualToString:@"card"]) {
+ after(1, ^{
+ UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:SGRPlayerSettingsPage(@[])];
+ nav.modalPresentationStyle = UIModalPresentationFullScreen;
+ [self.window.rootViewController presentViewController:nav animated:NO completion:nil];
+ after(2, ^{
+ UIView *card = firstOfClass(((UITableViewController *)nav.topViewController).tableView.tableHeaderView, @"SGRPlayerShowcase");
+ UIImageView *cover = [card valueForKey:@"_cover"];
+ NSLog(@"[harness] card: \"%@\", \"%@\", cover %.0fx%.0f", [[card valueForKey:@"_title"] text], [[card valueForKey:@"_artist"] text],
+ cover.image.size.width, cover.image.size.height);
+ });
+ });
+ return;
+ }
[self playTrack:@"spotify:track:harnessA" image:imageURI(@"aaaa")];
// The bar lays out once as the app comes up.
[_bar viewDidLayoutSubviews];
@@ -1589,6 +1606,22 @@ __attribute__((constructor(101))) static void sgr_harnessDefaults(void) {
setenv("HARNESS_CANVAS_DELAY", "2", 1);
[NSURLProtocol registerClass:SGRHarnessPictureServer.class];
}
+ // card: HARNESS_BACKGROUND (an index, Fluid if unset), and with HARNESS_LAST=1 a last track played whose cover is
+ // the picture server's first picture; without it, no track ever played.
+ if ([scenario() isEqualToString:@"card"]) {
+ NSUserDefaults *store = NSUserDefaults.standardUserDefaults;
+ const char *background = getenv("HARNESS_BACKGROUND");
+ [store setInteger:background ? atoi(background) : 2 forKey:@"spotifyglass.redesign.player.background"];
+ if (getenv("HARNESS_LAST")) {
+ [store setObject:@{@"uri": @"spotify:track:last", @"title": @"Holocene, the Long Version Recorded Live at the Old Church",
+ @"artist": @"Bon Iver", @"artwork": [@"https://i.scdn.co/image/" stringByAppendingString:[imageURI(@"aaaa") substringFromIndex:14]],
+ @"canvas": [NSString stringWithFormat:@"https://canvas.harness/last-%d.mp4", getpid()]}
+ forKey:@"spotifyglass.lastTrack"];
+ } else {
+ [store removeObjectForKey:@"spotifyglass.lastTrack"];
+ }
+ [NSURLProtocol registerClass:SGRHarnessPictureServer.class];
+ }
if ([scenario() isEqualToString:@"motion"] || [scenario() isEqualToString:@"settings"]) {
[NSUserDefaults.standardUserDefaults setInteger:3 forKey:@"spotifyglass.redesign.player.background"];
setenv("HARNESS_CANVAS", "https://canvas.harness/clip.mp4", 1);
diff --git a/tweak/Sources/Redesigned/Player/PlayerMotion.x b/tweak/Sources/Redesigned/Player/PlayerMotion.x
index 51f0c62a..309d74da 100644
--- a/tweak/Sources/Redesigned/Player/PlayerMotion.x
+++ b/tweak/Sources/Redesigned/Player/PlayerMotion.x
@@ -30,6 +30,7 @@
#import "Redesigned/Kit/SGRKit.h"
#import "Shared/AnimatedArtwork/AnimatedArtwork.h"
#import "Shared/Player/PlayerState.h"
+#import "Shared/Player/SGLastTrack.h"
#import "Shared/Player/SpeedPitch.h"
#import "Player.h"
@@ -352,6 +353,7 @@ static UIView *previewOf(NSURL *file, UIImage *poster) {
// The playing track's clip the Player page looked up itself while the player had none, and its poster; the
// file is nil while the walk is out or after it found nothing. The walk is the player's (SGMotionClipFor, at
// the size SGMotionFollower asks for), so its file lands in the store, where the player's own walk finds it.
+// With no track playing, the track is the last one played (Shared/Player/SGLastTrack.h).
static NSString *sg_previewTrack;
static NSURL *sg_previewFile;
static UIImage *sg_previewPoster;
@@ -359,8 +361,8 @@ static void (^sg_previewArrived)(void);
UIView *SGRPlayerMotionPreview(void (^arrived)(void)) {
if (sg_motionFile) return previewOf(sg_motionFile, sg_motionPoster);
- SPTPlayerState *state = SGPlayerState();
- NSString *track = SGURIString(state.track.URI);
+ SGShownTrack *shown = SGShownTrackNow();
+ NSString *track = shown.uri;
if (!track) return nil;
BOOL asked = [track isEqualToString:sg_previewTrack];
if (asked && sg_previewFile) return previewOf(sg_previewFile, sg_previewPoster);
@@ -371,9 +373,8 @@ UIView *SGRPlayerMotionPreview(void (^arrived)(void)) {
sg_previewTrack = track;
sg_previewFile = nil;
sg_previewPoster = nil;
- NSDictionary *metadata = [state.track.metadata isKindOfClass:NSDictionary.class] ? state.track.metadata : nil;
- SGLog(@"redesign player: the Player page looks up the clip of %@", track);
- SGMotionClipFor(track, SGMotionCanvasIn(metadata), state.track.artistName, metadata[@"album_title"], SGMotionTall, SGMotionPixels(),
+ SGLog(@"redesign player: the Player page looks up the clip of %@%@", track, shown.current ? @"" : @", the last played");
+ SGMotionClipFor(track, shown.canvasURL, shown.artist, shown.album, SGMotionTall, SGMotionPixels(),
^(NSURL *file, NSString *source) {
if (![track isEqualToString:sg_previewTrack]) return;
// Nothing found is not kept: the page asks again the next time it shows Animated.
diff --git a/tweak/Sources/Redesigned/Player/PlayerSettings.m b/tweak/Sources/Redesigned/Player/PlayerSettings.m
index 6bcab36b..9456f242 100644
--- a/tweak/Sources/Redesigned/Player/PlayerSettings.m
+++ b/tweak/Sources/Redesigned/Player/PlayerSettings.m
@@ -1,8 +1,10 @@
// The redesign's Player page in Mod Settings (App/Pages.m opens it in place of the native look's).
//
// It leads with a card of the player as the now playing track shows on it: the background chosen on the
-// page edge to edge, and over its foot the cover, the title, the artist and how far the track has played.
-// The progress is where the track was when the page appeared.
+// page edge to edge, and over its foot the cover, the title and the artist (gliding when too long) and how
+// far the track has played. The progress is where the track was when the page appeared. With no track, the
+// card shows the last one played (Shared/Player/SGLastTrack.h), its cover fetched and its Canvas looked up
+// as the playing one's would be, and with none ever played, Not Playing over a gradient of the accent.
//
// The background is the player's own: a field of the same kind (Still, Colours, Fluid), for Animated
// the clip the player is playing (SGRPlayerMotionPreview) in place of the field, or, while the player has
@@ -26,6 +28,7 @@
#import "Redesigned/Kit/SGRKit.h"
#import "Redesigned/NowPlayingBar/NowPlayingBar.h"
#import "Shared/AnimatedArtwork/AnimatedArtwork.h"
+#import "Shared/Player/SGLastTrack.h"
#import "Player.h"
// The card's height as a share of its width, kept between the two bounds.
@@ -53,9 +56,10 @@ static NSArray<NSString *> *backgroundNotes(void) {
SGRArtworkField *_field;
UIView *_motion, *_visualiser;
UIImageView *_cover;
- UILabel *_title, *_artist;
+ SGMarqueeLabel *_title, *_artist;
UIView *_progress, *_progressFill;
CGFloat _position;
+ NSString *_artworkOf; // the last track whose cover the card asked for
}
- (instancetype)initWithFrame:(CGRect)frame {
@@ -84,13 +88,16 @@ static NSArray<NSString *> *backgroundNotes(void) {
_cover.preferredSymbolConfiguration = [UIImageSymbolConfiguration configurationWithPointSize:22 weight:UIImageSymbolWeightRegular];
[self addSubview:_cover];
- _title = [UILabel new];
+ // The card reads as one image; the words glide as the player's own do.
+ _title = [SGMarqueeLabel new];
_title.textColor = SGRPrimary();
_title.font = [UIFont systemFontOfSize:17 weight:UIFontWeightSemibold];
+ _title.isAccessibilityElement = NO;
[self addSubview:_title];
- _artist = [UILabel new];
+ _artist = [SGMarqueeLabel new];
_artist.textColor = SGRSecondary();
_artist.font = [UIFont systemFontOfSize:15];
+ _artist.isAccessibilityElement = NO;
[self addSubview:_artist];
// The player's slider as it is drawn at rest: a track, and in it a fill up to where the song is.
@@ -120,26 +127,48 @@ static NSArray<NSString *> *backgroundNotes(void) {
- (void)artworkChanged {
NSString *identity = nil;
UIImage *image = SGRNowPlayingArtwork(NULL, &identity);
- if (!image) return;
- _cover.image = image;
+ if (image) [self showArtwork:image identity:identity];
+}
+
+// The cover and the field from `image`, or from the placeholder for nil.
+- (void)showArtwork:(UIImage *)image identity:(NSString *)identity {
+ static UIImage *placeholder;
+ static UIColor *tint;
+ if (!image && (!placeholder || ![tint isEqual:SGGreen()])) {
+ tint = SGGreen();
+ placeholder = SGPlaceholderArtwork(tint);
+ }
+ _cover.image = image ?: placeholder;
_cover.contentMode = UIViewContentModeScaleAspectFill;
- [_field setArtwork:image identity:identity animated:self.window != nil];
+ [_field setArtwork:_cover.image identity:image ? identity : @"placeholder" animated:self.window != nil];
}
// The track, where it is and whether it plays, read again.
- (void)reloadTrack {
SPTPlayerState *state = SGPlayerState();
- SPTPlayerTrack *track = state.track;
- _title.text = track.trackTitle.length ? track.trackTitle : @"Not Playing";
- _artist.text = track.artistName ?: @"";
- _position = state.duration > 0 ? MIN(1, MAX(0, state.position / state.duration)) : 0;
+ SGShownTrack *shown = SGShownTrackNow();
+ _title.text = shown.title ?: @"Not Playing";
+ _artist.text = shown.artist ?: @"";
+ _position = shown.current && state.duration > 0 ? MIN(1, MAX(0, state.position / state.duration)) : 0;
// The clip covers the field, and the hills move over it, which then holds still, as in the player.
_field.motionHeld = state.isPaused || _motion != nil || _visualiser != nil;
- if (SGRNowPlayingArtwork(NULL, NULL)) {
+ if (shown.current && SGRNowPlayingArtwork(NULL, NULL)) {
[self artworkChanged];
+ } else if (!shown.current && shown.artworkURL) {
+ // The last track's cover, the placeholder until it comes.
+ NSString *uri = shown.uri;
+ if (![_artworkOf isEqualToString:uri]) [self showArtwork:nil identity:nil];
+ _artworkOf = uri;
+ __weak SGRPlayerShowcase *weakSelf = self;
+ SGShownTrackArtwork(shown, ^(UIImage *image) {
+ SGRPlayerShowcase *showcase = weakSelf;
+ SGShownTrack *now = SGShownTrackNow();
+ if (image && !now.current && [now.uri isEqualToString:uri]) [showcase showArtwork:image identity:[@"last:" stringByAppendingString:uri]];
+ });
} else {
- _cover.image = [UIImage systemImageNamed:@"music.note"];
- _cover.contentMode = UIViewContentModeCenter;
+ // Nothing ever played, or the playing track's cover still coming.
+ _artworkOf = nil;
+ [self showArtwork:nil identity:nil];
}
[self setNeedsLayout];
}
@@ -301,12 +330,12 @@ UIViewController *SGRPlayerSettingsPage(NSArray *more) {
NSMutableArray<SGModSection *> *sections = [NSMutableArray arrayWithObjects:
SGSection(nil, @[sources, lowData]),
SGNotedSection(@"Mini player", SGRNowPlayingBarRows(),
- @"Apple Music style shrinks the tab bar to two tabs as a page scrolls down and puts the now "
- "playing bar between them; scrolling back up undoes it. There the bar keeps its cover, title "
- "and play button, and the device button too when it is on. Apple Music style applies at once, the device button "
- "the next time the bar shrinks."), nil];
+ @"Apple Music style moves the now playing bar in between two tabs as you scroll down."), nil];
[sections addObjectsFromArray:more];
- SGRPlayerPage *page = [[SGRPlayerPage alloc] initWithTitle:@"Player" intro:nil sections:sections footer:SGRestartNote];
+ // Fluid, Animated and Visualiser share the field (PlayerMotion.x reads the choice on every track, PlayerVisualiser.m
+ // on the field's layout); Still and Colours are a field of another kind, made once a launch (PlayerField.x).
+ NSString *footer = @"Fluid, Animated and Visualiser change with the next song. Still, Colours and Hide on the player apply after you restart Spotify.";
+ SGRPlayerPage *page = [[SGRPlayerPage alloc] initWithTitle:@"Player" intro:nil sections:sections footer:footer];
page.showcase = showcase;
page.backgrounds = backgrounds;
[backgrounds addTarget:page action:@selector(backgroundPicked) forControlEvents:UIControlEventValueChanged];
diff --git a/tweak/Sources/Shared/Player/SGLastTrack.h b/tweak/Sources/Shared/Player/SGLastTrack.h
new file mode 100644
index 00000000..67f1423c
--- /dev/null
+++ b/tweak/Sources/Shared/Player/SGLastTrack.h
@@ -0,0 +1,27 @@
+// The track the settings pages' previews show (the Player page's card, the Sing page's card): the one Spotify has
+// now, playing or paused; with none, the last one played, kept across launches; with none ever, nothing, and the
+// preview draws SGPlaceholderArtwork under "Not Playing".
+//
+// The last track is stored when the player reports a new one (a player state observer of its own, from launch):
+// its title, artist, album, the picture its metadata names and its Canvas's address, nothing of the sound.
+//
+// Threading: main thread only; the artwork is fetched and decoded off it and handed back on it.
+#import <UIKit/UIKit.h>
+
+#define SGKeyLastTrack @"spotifyglass.lastTrack"
+
+@interface SGShownTrack : NSObject
+@property (nonatomic, copy, readonly) NSString *uri, *title, *artist, *album;
+// The cover's address (i.scdn.co, or a local file's cover on the phone) and the Canvas video's; nil for none.
+@property (nonatomic, readonly) NSURL *artworkURL, *canvasURL;
+// Spotify has it now, playing or paused; NO for the last track played.
+@property (nonatomic, readonly) BOOL current;
+@end
+
+// nil when Spotify has no track and none was ever played.
+SGShownTrack *SGShownTrackNow(void);
+// The track's cover, fetched (from the URL cache when it is there) and decoded off the main thread, then `done`
+// on it with the image, or nil when there is none or it did not come. The last one is kept for the next ask.
+void SGShownTrackArtwork(SGShownTrack *track, void (^done)(UIImage *image));
+// The artwork of no track: a calm gradient of `tint`, a faint note in its middle.
+UIImage *SGPlaceholderArtwork(UIColor *tint);
diff --git a/tweak/Sources/Shared/Player/SGLastTrack.m b/tweak/Sources/Shared/Player/SGLastTrack.m
new file mode 100644
index 00000000..014064be
--- /dev/null
+++ b/tweak/Sources/Shared/Player/SGLastTrack.m
@@ -0,0 +1,148 @@
+// SGLastTrack.h says what this is for.
+#import "Core/SGCore.h"
+#import "Shared/AnimatedArtwork/AnimatedArtwork.h"
+#import "Shared/LocalFiles/LocalFiles.h"
+#import "PlayerState.h"
+#import "SGLastTrack.h"
+
+// The cover a track's metadata names, largest first: a local file's cover on the phone, or Spotify's picture on
+// i.scdn.co.
+static NSString *artworkIn(NSDictionary *metadata) {
+ for (NSString *field in @[@"image_xlarge_url", @"image_large_url", @"image_url"]) {
+ id value = metadata[field];
+ if (![value isKindOfClass:NSString.class] || ![value length]) continue;
+ NSString *local = SGLocalFileCoverInURL(value);
+ if (local) return [NSURL fileURLWithPath:local].absoluteString;
+ if ([value hasPrefix:@"https://"]) return value;
+ if ([value hasPrefix:@"spotify:image:"]) return [@"https://i.scdn.co/image/" stringByAppendingString:[value substringFromIndex:14]];
+ }
+ return nil;
+}
+
+// A track as stored: strings only, nil for none or an ad.
+static NSDictionary<NSString *, NSString *> *describe(SPTPlayerTrack *track) {
+ NSString *uri = SGURIString(track.URI);
+ if (!uri.length || [uri hasPrefix:@"spotify:ad:"]) return nil;
+ NSDictionary *metadata = [track respondsToSelector:@selector(metadata)] && [track.metadata isKindOfClass:NSDictionary.class] ? track.metadata : nil;
+ NSMutableDictionary *described = [@{@"uri": uri} mutableCopy];
+ described[@"title"] = track.trackTitle.length ? track.trackTitle : nil;
+ described[@"artist"] = [track.artistName isKindOfClass:NSString.class] ? track.artistName : nil;
+ described[@"album"] = [metadata[@"album_title"] isKindOfClass:NSString.class] ? metadata[@"album_title"] : nil;
+ described[@"artwork"] = artworkIn(metadata);
+ described[@"canvas"] = SGMotionCanvasIn(metadata).absoluteString;
+ return described;
+}
+
+@implementation SGShownTrack
+
+- (instancetype)initWith:(NSDictionary<NSString *, NSString *> *)described current:(BOOL)current {
+ if (!(self = [super init])) return nil;
+ _uri = described[@"uri"];
+ _title = described[@"title"];
+ _artist = described[@"artist"];
+ _album = described[@"album"];
+ _artworkURL = described[@"artwork"] ? [NSURL URLWithString:described[@"artwork"]] : nil;
+ _canvasURL = described[@"canvas"] ? [NSURL URLWithString:described[@"canvas"]] : nil;
+ _current = current;
+ return self;
+}
+
+@end
+
+static NSDictionary *stored(void) {
+ NSDictionary *value = [NSUserDefaults.standardUserDefaults dictionaryForKey:SGKeyLastTrack];
+ return [value[@"uri"] isKindOfClass:NSString.class] && [value[@"title"] isKindOfClass:NSString.class] ? value : nil;
+}
+
+SGShownTrack *SGShownTrackNow(void) {
+ NSDictionary *now = describe(SGPlayerState().track);
+ if (now) return [[SGShownTrack alloc] initWith:now current:YES];
+ NSDictionary *last = stored();
+ return last ? [[SGShownTrack alloc] initWith:last current:NO] : nil;
+}
+
+#pragma mark - the last track, stored
+
+@interface SGLastTrackRecorder : NSObject <SGPlayerStateObserver>
+@end
+
+@implementation SGLastTrackRecorder {
+ NSDictionary *_last;
+}
+
+// Written only when it changes: a new track, or its metadata filled in (a Canvas that came late). A track with no
+// title yet (still loading) is not kept.
+- (void)playerStateDidChange:(SPTPlayerState *)state {
+ NSDictionary *track = describe(state.track);
+ if (!track[@"title"] || [track isEqualToDictionary:_last ?: stored()]) return;
+ _last = track;
+ [NSUserDefaults.standardUserDefaults setObject:track forKey:SGKeyLastTrack];
+}
+
+@end
+
+__attribute__((constructor)) static void sg_recordLastTrack(void) {
+ static SGLastTrackRecorder *recorder; // the observers are held weakly
+ recorder = [SGLastTrackRecorder new];
+ SGAddPlayerStateObserver(recorder);
+}
+
+#pragma mark - the artwork
+
+static NSURL *sg_artworkURL;
+static UIImage *sg_artwork;
+
+void SGShownTrackArtwork(SGShownTrack *track, void (^done)(UIImage *image)) {
+ NSURL *url = track.artworkURL;
+ if (!url) {
+ done(nil);
+ return;
+ }
+ if (sg_artwork && [url isEqual:sg_artworkURL]) {
+ done(sg_artwork);
+ return;
+ }
+ void (^decode)(NSData *) = ^(NSData *data) {
+ UIImage *image = data.length ? [UIImage imageWithData:data] : nil;
+ image = image.imageByPreparingForDisplay ?: image;
+ dispatch_async(dispatch_get_main_queue(), ^{
+ if (image) {
+ sg_artworkURL = url;
+ sg_artwork = image;
+ }
+ done(image);
+ });
+ };
+ if (url.isFileURL) {
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ decode([NSData dataWithContentsOfURL:url]); });
+ return;
+ }
+ [[NSURLSession.sharedSession dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
+ NSInteger status = [response isKindOfClass:NSHTTPURLResponse.class] ? ((NSHTTPURLResponse *)response).statusCode : 0;
+ decode(status == 200 ? data : nil);
+ }] resume];
+}
+
+UIImage *SGPlaceholderArtwork(UIColor *tint) {
+ CGFloat side = 240;
+ UIGraphicsImageRendererFormat *format = [UIGraphicsImageRendererFormat preferredFormat];
+ format.scale = 1;
+ format.opaque = YES;
+ return [[[UIGraphicsImageRenderer alloc] initWithSize:CGSizeMake(side, side) format:format] imageWithActions:^(UIGraphicsImageRendererContext *context) {
+ // The tint, muted and dim, at the top left to near black at the bottom right, so the fields made from it (Colours,
+ // Fluid) have two calm colours to move between rather than the accent at full strength.
+ CGFloat h = 0, s = 0, b = 0, a = 0;
+ [tint getHue:&h saturation:&s brightness:&b alpha:&a];
+ UIColor *light = [UIColor colorWithHue:h saturation:s * 0.55 brightness:b * 0.5 alpha:1];
+ UIColor *dark = [UIColor colorWithHue:fmod(h + 0.06, 1) saturation:s * 0.6 brightness:b * 0.16 alpha:1];
+ CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
+ CGGradientRef gradient = CGGradientCreateWithColors(space, (__bridge CFArrayRef)@[(id)light.CGColor, (id)dark.CGColor], NULL);
+ CGContextDrawLinearGradient(context.CGContext, gradient, CGPointZero, CGPointMake(side, side), 0);
+ CGGradientRelease(gradient);
+ CGColorSpaceRelease(space);
+ UIImageSymbolConfiguration *weight = [UIImageSymbolConfiguration configurationWithPointSize:side * 0.32 weight:UIImageSymbolWeightMedium];
+ UIImage *note = [[UIImage systemImageNamed:@"music.note" withConfiguration:weight] imageWithTintColor:[UIColor colorWithWhite:1 alpha:0.45]
+ renderingMode:UIImageRenderingModeAlwaysOriginal];
+ [note drawAtPoint:CGPointMake((side - note.size.width) / 2, (side - note.size.height) / 2)];
+ }];
+}