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: Edit info changes a local file's title, artist, album and cover

My-Name-Is-Jeffd9d6e0f3add0
diff --git a/docs/tweaks.md b/docs/tweaks.md
index 9dd3012e..ab4a5d01 100644
--- a/docs/tweaks.md
+++ b/docs/tweaks.md
@@ -112,6 +112,17 @@ Shared:
artwork (LockScreenMotion.x). With Every song, a song with neither gets its cover over copies of it
blurred and swaying, a seamless 8 s 3:4 loop drawn on the CPU only when the lock screen asks for it
and kept per picture (SGFluidClip.m). Rendered on the Mac against harness/fluid-clip/
+ LocalFiles/ local files (LocalFiles.h lists its files): Edit info in the player's ⋯ menu, the table's footer
+ under Speed and pitch, which closes the menu and opens a form sheet (the three names, the cover
+ with a menu to change it, Restore file's info; nothing is stored before Save, and a swipe away
+ with changes asks first), storing a title, artist, album and cover by the file's URI and laying them
+ over -[SPTPlayerTrack metadata] and the cover's image request (the redesign's artwork reads the
+ stored cover itself, Redesigned/Kit/SGRBridges.x); the file is never written. Their
+ lyrics are kept under the URI and asked of the sources by name, since Spotify never asks for them;
+ with no source switched on, of LRCLIB alone, which then gets the file's title, artist, album and
+ length. A rename gives a new key (a cover alone does not), asked for at once while the file plays.
+ A miss is asked again a few times, in case it was a lost request. The model is checked on the Mac
+ against harness/local-files/, the row and the editor in the simulator against its sim/
Navigation/ the page transition fix (PageTransition.x) and opening a spotify: link (Links.x)
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
diff --git a/harness/local-files/README.md b/harness/local-files/README.md
new file mode 100644
index 00000000..1d98bf55
--- /dev/null
+++ b/harness/local-files/README.md
@@ -0,0 +1,28 @@
+# Local files check
+
+`./build.sh` checks `Shared/LocalFiles/LocalFiles.m` as the tweak compiles it: a `spotify:local:` URI
+read back into its names (form decoded, a `%3A` in a title too), an edit laid over them, and the lyrics
+key each edit gives. A rename gets a new key (`<uri>#<number>`), the same names saved again or a new
+cover with them keep it, a cover alone on an unedited file leaves the bare URI, and names back to the
+file's own go back to it. It also checks a stored cover's `spotify:localfileimage:` address and its way
+back, that no other path comes back through it, and that a replaced or dropped cover's file is removed.
+
+It runs on the Mac as a Mac Catalyst binary with `CFFIXED_USER_HOME` set to `build/home`, so its
+defaults and its covers never reach the Mac's own.
+
+It does not cover the hooks in `LocalFileInfo.x` or the lyrics engine asking for the
+new key (`Shared/Lyrics/KaraokeSource.x`).
+
+## Edit info in the simulator
+
+`sim/build-sim.sh <udid>` builds `EditInfoMenu.x` and `LocalFiles.m` as the tweak compiles them into an
+app with a mock of Spotify's context menu sheet over a player that plays a local file, runs it, and saves
+a screenshot at each step into `build/sim/shots/`. The script taps Edit info, which closes the menu and
+brings up the editor sheet. Then it types a name and picks a cover (neither is stored before Save),
+saves, opens the editor again, restores the file's info and saves, and last tries to swipe away
+unsaved changes, which must ask first. Each step logs `PASS` or `FAIL`. `large` runs it once at the
+largest accessibility text size, where each label goes above its field, and sets the size back.
+
+ THEOS=$HOME/theos sim/build-sim.sh <udid> [large]
+
+It does not cover the pickers themselves, the keyboard over the sheet, or Spotify's own menu closing.
diff --git a/harness/local-files/build.sh b/harness/local-files/build.sh
new file mode 100755
index 00000000..7bce901b
--- /dev/null
+++ b/harness/local-files/build.sh
@@ -0,0 +1,12 @@
+#!/bin/sh
+# build.sh: builds check.m against this checkout's LocalFiles.m as a Mac Catalyst binary and runs it with
+# a home of its own under build/, so its defaults and its covers never reach the Mac's.
+set -e
+HERE=$(cd "$(dirname "$0")" && pwd)
+SRC=$(cd "$HERE/../../tweak/Sources" && pwd)
+SDK=$(xcrun --sdk macosx --show-sdk-path)
+mkdir -p "$HERE/build/home"
+xcrun -sdk macosx clang -target arm64-apple-ios17.0-macabi -isysroot "$SDK" -iframework "$SDK/System/iOSSupport/System/Library/Frameworks" \
+ -fobjc-arc -g -Wall -Werror -I"$SRC" "$HERE/check.m" "$SRC/Shared/LocalFiles/LocalFiles.m" \
+ -framework UIKit -framework CoreGraphics -framework Foundation -o "$HERE/build/check"
+CFFIXED_USER_HOME="$HERE/build/home" "$HERE/build/check"
diff --git a/harness/local-files/check.m b/harness/local-files/check.m
new file mode 100644
index 00000000..76880d9a
--- /dev/null
+++ b/harness/local-files/check.m
@@ -0,0 +1,74 @@
+// Checks LocalFiles.m as the tweak compiles it: a URI read back into names, an edit laid over them, the
+// lyrics key an edit gives (a new one for a rename only), and a stored cover's address and its way back.
+// Runs in its own defaults domain and Application Support, so nothing of the Mac's is touched. Exits
+// non-zero on the first wrong answer.
+#import <UIKit/UIKit.h>
+#import "Shared/LocalFiles/LocalFiles.h"
+
+#define CHECK(cond) do { if (!(cond)) { fprintf(stderr, "FAILED line %d: %s\n", __LINE__, #cond); exit(1); } } while (0)
+
+static UIImage *square(void) {
+ return [[[UIGraphicsImageRenderer alloc] initWithSize:CGSizeMake(4, 4)] imageWithActions:^(UIGraphicsImageRendererContext *context) {
+ [UIColor.redColor setFill];
+ UIRectFill(CGRectMake(0, 0, 4, 4));
+ }];
+}
+
+int main(void) {
+ @autoreleasepool {
+ [NSUserDefaults.standardUserDefaults removeObjectForKey:SGKeyLocalFileEdits];
+ NSString *uri = @"spotify:local:Daft+Punk:Discovery:One+More+Time%3A+Remix:320";
+
+ // The URI's own names, form decoded, and the bare URI as the key.
+ NSDictionary *tags = SGLocalFileTags(uri);
+ CHECK([tags[@"title"] isEqualToString:@"One More Time: Remix"] && [tags[@"artist"] isEqualToString:@"Daft Punk"]);
+ CHECK([tags[@"seconds"] integerValue] == 320);
+ CHECK([SGLocalFileLyricsKey(uri) isEqualToString:uri]);
+ CHECK(!SGLocalFileLyricsKey(@"spotify:track:4uLU6hMCjMI75M1A2tKUQC"));
+
+ // A cover alone keeps the key: no rename, so the lyrics stay where they are.
+ SGLocalFileSaveEdit(uri, @{@"title": @"One More Time: Remix", @"artist": @"", @"album": @"Discovery"}, square(), YES);
+ NSDictionary *edit = SGLocalFileEditFor(uri);
+ CHECK(edit[@"cover"] && !edit[@"number"] && !edit[@"title"]);
+ CHECK([SGLocalFileLyricsKey(uri) isEqualToString:uri]);
+ NSString *cover = SGLocalFileCoverPath(edit);
+ CHECK([NSFileManager.defaultManager fileExistsAtPath:cover]);
+ CHECK([SGLocalFileCoverInURL(SGLocalFileCoverURL(cover)) isEqualToString:cover]);
+ CHECK(![SGLocalFileCoverURL(cover) containsString:@"/"]);
+ CHECK(!SGLocalFileCoverInURL(@"spotify:localfileimage:%2Fetc%2Fpasswd"));
+
+ // A rename gives a new key, and the names reach the sources through it.
+ SGLocalFileSaveEdit(uri, @{@"title": @"One More Time", @"artist": @"Daft Punk"}, nil, YES);
+ edit = SGLocalFileEditFor(uri);
+ NSString *renamed = SGLocalFileLyricsKey(uri);
+ CHECK(edit[@"number"] && edit[@"cover"] && [renamed hasPrefix:[uri stringByAppendingString:@"#"]]);
+ CHECK([SGLocalFileInfo(renamed)[@"title"] isEqualToString:@"One More Time"]);
+ CHECK([SGLocalFileInfo(renamed)[@"seconds"] integerValue] == 320);
+
+ // The same names saved again, or a new cover with them, keep that key.
+ [NSThread sleepForTimeInterval:0.01];
+ SGLocalFileSaveEdit(uri, @{@"title": @"One More Time ", @"artist": @"Daft Punk"}, nil, YES);
+ CHECK([SGLocalFileLyricsKey(uri) isEqualToString:renamed]);
+ SGLocalFileSaveEdit(uri, @{@"title": @"One More Time"}, square(), YES);
+ CHECK([SGLocalFileLyricsKey(uri) isEqualToString:renamed]);
+ CHECK(![NSFileManager.defaultManager fileExistsAtPath:cover]); // the replaced cover is gone
+ cover = SGLocalFileCoverPath(SGLocalFileEditFor(uri));
+
+ // Another rename, another key.
+ [NSThread sleepForTimeInterval:0.01];
+ SGLocalFileSaveEdit(uri, @{@"title": @"One More Time (Live)"}, nil, YES);
+ NSString *again = SGLocalFileLyricsKey(uri);
+ CHECK(![again isEqualToString:renamed] && [again hasPrefix:uri]);
+
+ // Back to the file's own names with the cover kept: the bare URI again.
+ SGLocalFileSaveEdit(uri, @{@"title": @"One More Time: Remix"}, nil, YES);
+ CHECK([SGLocalFileLyricsKey(uri) isEqualToString:uri] && SGLocalFileEditFor(uri)[@"cover"]);
+
+ // Nothing left over: the edit and its cover go.
+ SGLocalFileSaveEdit(uri, @{}, nil, NO);
+ CHECK(!SGLocalFileEditFor(uri) && ![NSFileManager.defaultManager fileExistsAtPath:cover]);
+ CHECK(!SGLocalFileInfo(@"spotify:local:too:few:parts"));
+ printf("local files: all checks passed\n");
+ }
+ return 0;
+}
diff --git a/harness/local-files/sim/build-sim.sh b/harness/local-files/sim/build-sim.sh
new file mode 100755
index 00000000..d04d38e4
--- /dev/null
+++ b/harness/local-files/sim/build-sim.sh
@@ -0,0 +1,52 @@
+#!/bin/sh
+# build-sim.sh: builds the Edit info harness for the simulator (EditInfoMenu.x and LocalFiles.m as the
+# tweak compiles them) and, given a booted simulator's UDID, installs it, runs it and saves a screenshot
+# at each SHOT into ../build/sim/shots/. `large` as a second argument runs it once at the largest accessibility
+# text size and sets the size back after.
+#
+# THEOS=$HOME/theos ./build-sim.sh [<udid> [large]]
+set -e
+HERE=$(cd "$(dirname "$0")" && pwd)
+SRC=$(cd "$HERE/../../../tweak/Sources" && pwd)
+OUT="$HERE/../build/sim" # harness/*/build/ is ignored
+rm -rf "$OUT/gen" "$OUT/EditInfoHarness.app"; mkdir -p "$OUT/gen" "$OUT/EditInfoHarness.app" "$OUT/shots"
+"$THEOS/bin/logos.pl" -c generator=internal "$SRC/Shared/LocalFiles/EditInfoMenu.x" > "$OUT/gen/EditInfoMenu.m"
+SDK=$(xcrun --sdk iphonesimulator --show-sdk-path)
+xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-arc -g -O0 -Wall \
+ -I"$SRC" -I"$SRC/Shared/LocalFiles" -isysroot "$SDK" -Wno-deprecated-declarations \
+ "$HERE/main.m" "$HERE/../../scene.m" "$OUT/gen/EditInfoMenu.m" "$SRC/Shared/LocalFiles/LocalFiles.m" "$SRC/Core/SGLog.m" \
+ -framework UIKit -framework QuartzCore -framework CoreGraphics -framework UniformTypeIdentifiers -framework Foundation \
+ -o "$OUT/EditInfoHarness.app/EditInfoHarness"
+cat > "$OUT/EditInfoHarness.app/Info.plist" <<'PLIST'
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0"><dict>
+<key>CFBundleExecutable</key><string>EditInfoHarness</string>
+<key>CFBundleIdentifier</key><string>com.vitrine.editinfoharness</string>
+<key>CFBundleName</key><string>EditInfoHarness</string>
+<key>CFBundleVersion</key><string>1</string>
+<key>CFBundleShortVersionString</key><string>1.0</string>
+<key>UIUserInterfaceStyle</key><string>Dark</string>
+<key>UILaunchScreen</key><dict/>
+<key>UIApplicationSceneManifest</key><dict>
+ <key>UIApplicationSupportsMultipleScenes</key><false/>
+ <key>UISceneConfigurations</key><dict>
+ <key>UIWindowSceneSessionRoleApplication</key><array><dict>
+ <key>UISceneConfigurationName</key><string>Default</string>
+ <key>UISceneDelegateClassName</key><string>SGRHarnessScene</string>
+ </dict></array>
+ </dict>
+</dict>
+</dict></plist>
+PLIST
+echo "built $OUT/EditInfoHarness.app"
+[ -n "$1" ] || exit 0
+UDID=$1
+xcrun simctl install "$UDID" "$OUT/EditInfoHarness.app"
+[ "$2" = large ] && xcrun simctl ui "$UDID" content_size accessibility-extra-extra-extra-large
+xcrun simctl launch --console-pty "$UDID" com.vitrine.editinfoharness $2 2>&1 | tr -ud '\r' | while IFS= read -r line; do
+ echo "$line"
+ case "$line" in *"[harness] SHOT "*) xcrun simctl io "$UDID" screenshot "$OUT/shots/${line##*SHOT }.png" >/dev/null 2>&1 & ;; esac
+done
+[ "$2" = large ] && xcrun simctl ui "$UDID" content_size large
+exit 0
diff --git a/harness/local-files/sim/main.m b/harness/local-files/sim/main.m
new file mode 100644
index 00000000..f6a246ce
--- /dev/null
+++ b/harness/local-files/sim/main.m
@@ -0,0 +1,193 @@
+// Edit info in the simulator: EditInfoMenu.x and LocalFiles.m as the tweak compiles them, on a mock of
+// Spotify's context menu sheet presented over a player that plays a local file. The script taps the row,
+// which closes the menu and brings up the editor, then types, picks a cover, saves, opens it again,
+// restores the file's info, and tries to swipe away unsaved changes. It logs PASS or FAIL for each step
+// and `[harness] SHOT <name>` when the screen is worth a screenshot (build-sim.sh takes them).
+#import <UIKit/UIKit.h>
+#import "Shared/LocalFiles/LocalFiles.h"
+
+static NSString *const kURI = @"spotify:local:Daft+Punk:Discovery:One+More+Time:320";
+static int sg_failures;
+
+#define CHECK(what, cond) do { BOOL ok = (cond); if (!ok) sg_failures++; NSLog(@"[harness] %@ %@", ok ? @"PASS" : @"FAIL", what); } while (0)
+
+// What EditInfoMenu.x reads of the player: the track playing, and that the menu is the player's.
+@interface SGHarnessTrack : NSObject
+@property (nonatomic, strong) id URI;
+@end
+@implementation SGHarnessTrack
+@end
+@interface SGHarnessState : NSObject
+@property (nonatomic, strong) SGHarnessTrack *track;
+@end
+@implementation SGHarnessState
+@end
+
+id SGPlayerState(void) {
+ SGHarnessState *state = [SGHarnessState new];
+ state.track = [SGHarnessTrack new];
+ state.track.URI = [NSURL URLWithString:kURI];
+ return state;
+}
+NSString *SGURIString(id uri) {
+ return [uri isKindOfClass:NSURL.class] ? [(NSURL *)uri absoluteString] : uri;
+}
+BOOL SGPlayerMenuIsPlayers(UIViewController *menu) {
+ return YES;
+}
+
+// Spotify's context menu sheet, as far as the hook goes: a table whose layout runs the hook.
+@interface _TtC24ContextMenu_InternalImpl25ContextMenuViewController : UIViewController <UITableViewDataSource>
+@property (nonatomic, strong) UITableView *table;
+@end
+@implementation _TtC24ContextMenu_InternalImpl25ContextMenuViewController
+- (void)viewDidLoad {
+ [super viewDidLoad];
+ self.table = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
+ self.table.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
+ self.table.dataSource = self;
+ [self.view addSubview:self.table];
+}
+- (void)viewDidLayoutSubviews {
+ [super viewDidLayoutSubviews];
+}
+- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
+ return 3;
+}
+- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
+ UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
+ cell.textLabel.text = @[@"Add to playlist", @"Go to queue", @"Share"][(NSUInteger)indexPath.row];
+ return cell;
+}
+@end
+
+static void after(double seconds, dispatch_block_t block) {
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(seconds * NSEC_PER_SEC)), dispatch_get_main_queue(), block);
+}
+
+static void shot(NSString *name) {
+ NSLog(@"[harness] SHOT %@", name);
+}
+
+static UIImage *redSquare(void) {
+ return [[[UIGraphicsImageRenderer alloc] initWithSize:CGSizeMake(300, 300)] imageWithActions:^(UIGraphicsImageRendererContext *context) {
+ [UIColor.systemRedColor setFill];
+ UIRectFill(CGRectMake(0, 0, 300, 300));
+ }];
+}
+
+@interface SGHarnessApp : UIResponder <UIApplicationDelegate>
+@property (nonatomic, strong) UIWindow *window;
+@end
+@implementation SGHarnessApp
+- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)options {
+ [NSUserDefaults.standardUserDefaults removeObjectForKey:SGKeyLocalFileEdits];
+ self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
+ UIViewController *player = [UIViewController new];
+ player.view.backgroundColor = UIColor.blackColor;
+ self.window.rootViewController = player;
+ [self.window makeKeyAndVisible];
+ [self runOn:player];
+ return YES;
+}
+
+- (UIViewController *)editorOver:(UIViewController *)player {
+ UINavigationController *navigation = (UINavigationController *)player.presentedViewController;
+ if (![navigation isKindOfClass:UINavigationController.class]) return nil;
+ UIViewController *editor = navigation.viewControllers.firstObject;
+ return [NSStringFromClass(editor.class) isEqualToString:@"SGLocalFileEditor"] ? editor : nil;
+}
+
+- (void)runOn:(UIViewController *)player {
+ BOOL large = [NSProcessInfo.processInfo.arguments containsObject:@"large"];
+ __block UIViewController *menu;
+ after(1, ^{
+ menu = [_TtC24ContextMenu_InternalImpl25ContextMenuViewController new];
+ UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:menu];
+ navigation.navigationBarHidden = YES;
+ navigation.sheetPresentationController.detents = @[UISheetPresentationControllerDetent.mediumDetent];
+ [player presentViewController:navigation animated:YES completion:nil];
+ });
+ after(2.5, ^{
+ UIView *footer = ((_TtC24ContextMenu_InternalImpl25ContextMenuViewController *)menu).table.tableFooterView;
+ CHECK(@"the menu has the Edit info row", [NSStringFromClass(footer.class) isEqualToString:@"SGEditInfoRow"]);
+ shot(@"menu");
+ [(UIControl *)footer sendActionsForControlEvents:UIControlEventTouchUpInside];
+ });
+ after(4.5, ^{
+ UIViewController *editor = [self editorOver:player];
+ CHECK(@"the menu closed and the editor came up over the player", editor != nil);
+ CHECK(@"the editor is dark", editor.navigationController.overrideUserInterfaceStyle == UIUserInterfaceStyleDark);
+ NSArray<UITextField *> *fields = [editor valueForKey:@"fields"];
+ CHECK(@"the fields show the file's names", [fields[0].text isEqualToString:@"One More Time"] && [fields[1].text isEqualToString:@"Daft Punk"]);
+ CHECK(@"Save is off with nothing changed", !editor.navigationItem.rightBarButtonItem.enabled && !editor.modalInPresentation);
+ shot(large ? @"editor-large" : @"editor");
+ if (large) after(2, ^{ exit(sg_failures ? 1 : 0); });
+ });
+ if (large) return;
+ after(6, ^{
+ UIViewController *editor = [self editorOver:player];
+ NSArray<UITextField *> *fields = [editor valueForKey:@"fields"];
+ fields[0].text = @"One More Time (Edit)";
+ [fields[0] sendActionsForControlEvents:UIControlEventEditingChanged];
+ CHECK(@"a typed name turns Save on and holds a swipe", editor.navigationItem.rightBarButtonItem.enabled && editor.modalInPresentation);
+ [editor performSelector:@selector(useCover:) withObject:redSquare()];
+ CHECK(@"a picked cover is not stored before Save", !SGLocalFileEditFor(kURI));
+ });
+ after(7, ^{ shot(@"edited"); });
+ after(8, ^{
+ UIViewController *editor = [self editorOver:player];
+ UIBarButtonItem *save = editor.navigationItem.rightBarButtonItem;
+ [[UIApplication sharedApplication] sendAction:save.action to:save.target from:save forEvent:nil];
+ NSDictionary *edit = SGLocalFileEditFor(kURI);
+ CHECK(@"Save stores the name and the cover", [edit[@"title"] isEqualToString:@"One More Time (Edit)"] && SGLocalFileCoverPath(edit));
+ CHECK(@"the rename gives a new lyrics key", [SGLocalFileLyricsKey(kURI) containsString:@"#"]);
+ });
+ after(9.5, ^{ SGLocalFilePresentEditor(player, kURI); });
+ after(11, ^{
+ UIViewController *editor = [self editorOver:player];
+ NSArray<UITextField *> *fields = [editor valueForKey:@"fields"];
+ UITableViewCell *restore = [editor valueForKey:@"restoreCell"];
+ CHECK(@"opened again, it shows the edit and offers the restore", [fields[0].text isEqualToString:@"One More Time (Edit)"] && restore.userInteractionEnabled);
+ shot(@"reopened");
+ });
+ after(12.5, ^{
+ UIViewController *editor = [self editorOver:player];
+ NSArray<UITextField *> *fields = [editor valueForKey:@"fields"];
+ UITableViewCell *restore = [editor valueForKey:@"restoreCell"];
+ [(UITableViewController *)editor tableView:[(UITableViewController *)editor tableView] didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
+ CHECK(@"Restore puts the file's names back, unsaved", [fields[0].text isEqualToString:@"One More Time"] && SGLocalFileEditFor(kURI)
+ && editor.navigationItem.rightBarButtonItem.enabled && !restore.userInteractionEnabled);
+ UIBarButtonItem *save = editor.navigationItem.rightBarButtonItem;
+ [[UIApplication sharedApplication] sendAction:save.action to:save.target from:save forEvent:nil];
+ CHECK(@"saved, the edit and its cover are gone", !SGLocalFileEditFor(kURI) && [SGLocalFileLyricsKey(kURI) isEqualToString:kURI]);
+ });
+ after(14, ^{ SGLocalFilePresentEditor(player, kURI); });
+ after(15.5, ^{
+ UIViewController *editor = [self editorOver:player];
+ NSArray<UITextField *> *fields = [editor valueForKey:@"fields"];
+ UITableViewCell *restore = [editor valueForKey:@"restoreCell"];
+ CHECK(@"with no edit, Restore is off", !restore.userInteractionEnabled);
+ fields[2].text = @"Homework";
+ [fields[2] sendActionsForControlEvents:UIControlEventEditingChanged];
+ [(id<UIAdaptivePresentationControllerDelegate>)editor presentationControllerDidAttemptToDismiss:editor.navigationController.presentationController];
+ });
+ after(17, ^{
+ UIViewController *editor = [self editorOver:player];
+ UIAlertController *confirm = (UIAlertController *)editor.presentedViewController;
+ CHECK(@"a swipe away with changes asks first", [confirm isKindOfClass:UIAlertController.class] && confirm.preferredStyle == UIAlertControllerStyleActionSheet
+ && [confirm.actions.firstObject.title isEqualToString:@"Discard changes"]);
+ shot(@"discard");
+ });
+ after(19, ^{
+ NSLog(@"[harness] %@: %d failed", sg_failures ? @"FAIL" : @"PASS", sg_failures);
+ exit(sg_failures ? 1 : 0);
+ });
+}
+@end
+
+int main(int argc, char *argv[]) {
+ @autoreleasepool {
+ return UIApplicationMain(argc, argv, nil, NSStringFromClass(SGHarnessApp.class));
+ }
+}
diff --git a/tweak/Sources/Headers/SPTLocalAVAssetImageLoaderRequest.h b/tweak/Sources/Headers/SPTLocalAVAssetImageLoaderRequest.h
new file mode 100644
index 00000000..52fad7e0
--- /dev/null
+++ b/tweak/Sources/Headers/SPTLocalAVAssetImageLoaderRequest.h
@@ -0,0 +1,9 @@
+// Spotify's image request for a local file's cover: -loadLocalFileImage reads it out of the file at the
+// path its spotify:localfileimage: address names, and -dispatchSuccess: hands the bytes to the delegate's
+// imageLoaderRequest:didLoadImageData: on the main queue.
+#import <Foundation/Foundation.h>
+
+@interface SPTLocalAVAssetImageLoaderRequest : NSObject
+@property (nonatomic, readonly) NSURL *URL;
+- (void)dispatchSuccess:(NSData *)data;
+@end
diff --git a/tweak/Sources/Redesigned/Kit/SGRBridges.x b/tweak/Sources/Redesigned/Kit/SGRBridges.x
index 2310c825..e781e80a 100644
--- a/tweak/Sources/Redesigned/Kit/SGRBridges.x
+++ b/tweak/Sources/Redesigned/Kit/SGRBridges.x
@@ -2,6 +2,7 @@
// links are Shared's (Shared/Player/PlayerState.h, Shared/Player/PlayerEvents.h,
// Shared/Navigation/Links.h). SGRBridges.h names the hook and why it is the one.
#import "Core/SGCore.h"
+#import "Shared/LocalFiles/LocalFiles.h"
#import "Shared/Player/PlayerEvents.h"
#import "SGRBridges.h"
#import "SGRedesign.h"
@@ -46,11 +47,18 @@ static NSString *imageIDIn(id value) {
return nil;
}
-// The picture a track names, largest first, and where it can be fetched from.
+// The picture a track names, largest first, and where it can be fetched from. A local file's cover the
+// user picked (Shared/LocalFiles) is a file of its own, named afresh for every new one, so its name is
+// the picture.
static NSString *pictureOf(SPTPlayerTrack *track, NSURL **url) {
NSDictionary *metadata = [track respondsToSelector:@selector(metadata)] ? track.metadata : nil;
if (![metadata isKindOfClass:NSDictionary.class]) return nil;
for (NSString *field in @[@"image_xlarge_url", @"image_large_url", @"image_url", @"image_small_url"]) {
+ NSString *stored = SGLocalFileCoverInURL(metadata[field]);
+ if (stored) {
+ if (url) *url = [NSURL fileURLWithPath:stored];
+ return [@"local:" stringByAppendingString:stored.lastPathComponent];
+ }
NSString *value = metadata[field], *identifier = imageIDIn(value);
if (!identifier) continue;
if (url) *url = [value hasPrefix:@"https://"] ? [NSURL URLWithString:value]
@@ -91,7 +99,23 @@ static NSURLSession *artworkSession(void) {
return session;
}
+// A stored cover is read and decoded off the main thread; there is nothing to try again.
+static void loadStoredPicture(NSString *key, NSURL *url) {
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
+ UIImage *image = [UIImage imageWithContentsOfFile:url.path];
+ image = image.imageByPreparingForDisplay ?: image;
+ dispatch_async(dispatch_get_main_queue(), ^{
+ if (!image) artworkLog(@"%@ not read, the screens stand in", key);
+ else if ([key isEqualToString:sg_wantedKey]) publish(image, key, SGRArtworkQualityExact);
+ });
+ });
+}
+
static void fetchPicture(NSString *key, NSURL *url, NSUInteger attempt) {
+ if (url.isFileURL) {
+ loadStoredPicture(key, url);
+ return;
+ }
CFTimeInterval started = CACurrentMediaTime();
sg_fetch = [artworkSession() dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSInteger status = [response isKindOfClass:NSHTTPURLResponse.class] ? ((NSHTTPURLResponse *)response).statusCode : 0;
@@ -285,6 +309,14 @@ void SGRObservePlayerTransition(id owner, void (^began)(id owner), void (^ended)
SGAddPlayerStateObserver(sg_follower);
sg_barWatcher = [SGRBarArtworkWatcher new];
SGAddPlayerStateObserver(sg_barWatcher);
+ // A cover picked or removed for the local file playing changes the picture with no new track, so the
+ // track is looked at again. Posted on the main thread.
+ [NSNotificationCenter.defaultCenter addObserverForName:SGLocalFileEditsDidChangeNotification object:nil queue:nil
+ usingBlock:^(NSNotification *note) {
+ if (![note.object isEqual:sg_wantedURI]) return;
+ sg_wantedURI = nil;
+ followPlayer();
+ }];
%init(SGRBarArtworkHooks);
SGRequireClasses(@[@"_TtC18NowPlaying_BarImpl27NowPlayingBarViewController"]);
}
diff --git a/tweak/Sources/Shared/LocalFiles/EditInfoMenu.x b/tweak/Sources/Shared/LocalFiles/EditInfoMenu.x
new file mode 100644
index 00000000..6afb0c67
--- /dev/null
+++ b/tweak/Sources/Shared/LocalFiles/EditInfoMenu.x
@@ -0,0 +1,518 @@
+// Edit info, in the player's ⋯ menu while a local file plays, under either look: a row that opens an
+// editor for the file's title, artist, album and cover, stored by the mod (LocalFiles.h).
+//
+// The menu is Spotify's context menu sheet, ContextMenu_InternalImpl.ContextMenuViewController, whose
+// rows come from Swift item factories with no way in (Shared/Player/SpeedPitchMenu.x says more). So the
+// row is the table's footer, as Speed and pitch is its header, and the sheet is the player's by
+// Speed and pitch's own test. Speed and pitch takes the footer when Spotify has a header of its own in
+// the table, so then the footer is left to it and Edit info is left out.
+//
+// The menu says nothing of the track it is for, so the row is only offered on the player's own menu,
+// which is for the track playing.
+#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
+#import <objc/runtime.h>
+#import "Core/SGCore.h"
+#import "Shared/Player/PlayerState.h"
+#import "Shared/Player/SpeedPitch.h"
+#import "LocalFiles.h"
+
+// The sheet's own measures, as Speed and pitch has them.
+static const CGFloat kRowHeight = 56, kSideMargin = 16, kIconSide = 24;
+
+static char kRowKey, kDecidedKey;
+
+static UIFont *rowFont(void) {
+ UIContentSizeCategory current = UIApplication.sharedApplication.preferredContentSizeCategory;
+ if (UIContentSizeCategoryCompareToCategory(current, UIContentSizeCategoryExtraLarge) == NSOrderedDescending) current = UIContentSizeCategoryExtraLarge;
+ UITraitCollection *traits = [UITraitCollection traitCollectionWithPreferredContentSizeCategory:current];
+ return [UIFont systemFontOfSize:[UIFont preferredFontForTextStyle:UIFontTextStyleBody compatibleWithTraitCollection:traits].pointSize];
+}
+
+#pragma mark - the editor
+
+// A form sheet over the player: the three names, the cover with a menu to change it, and a row that puts
+// the file's own info back. Nothing is stored until Save, so Cancel undoes everything, a cover picked
+// or removed and a restore too; a swipe down with changes asks first.
+
+typedef NS_ENUM(NSInteger, SGCoverChange) { SGCoverKept, SGCoverPicked, SGCoverRemoved };
+
+static NSArray<NSString *> *fieldKeys(void) {
+ return @[@"title", @"artist", @"album"];
+}
+
+static NSArray<NSString *> *fieldLabels(void) {
+ return @[@"Title", @"Artist", @"Album"];
+}
+
+static NSString *trimmed(NSString *text) {
+ return [text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet] ?: @"";
+}
+
+@interface SGLocalFileEditor : UITableViewController <UITextFieldDelegate, UIAdaptivePresentationControllerDelegate,
+ UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIDocumentPickerDelegate>
+- (instancetype)initWithURI:(NSString *)uri;
+@end
+
+@implementation SGLocalFileEditor {
+ NSString *_uri;
+ NSDictionary<NSString *, id> *_tags, *_shown; // the file's own names, and the ones it goes by now
+ NSArray<UITextField *> *_fields;
+ NSArray<UILabel *> *_labels;
+ NSArray<UIStackView *> *_stacks;
+ NSArray<NSLayoutConstraint *> *_labelWidths;
+ UITableViewCell *_coverCell, *_restoreCell;
+ UIButton *_coverButton;
+ UIImage *_cover; // the cover the row shows: the stored one, or the one just picked
+ SGCoverChange _coverChange;
+ BOOL _hasStoredCover;
+}
+
+- (instancetype)initWithURI:(NSString *)uri {
+ if (!(self = [super initWithStyle:UITableViewStyleInsetGrouped])) return nil;
+ _uri = [uri copy];
+ _tags = SGLocalFileTags(uri) ?: @{};
+ _shown = SGLocalFileInfo(uri) ?: @{};
+ NSString *path = SGLocalFileCoverPath(SGLocalFileEditFor(uri));
+ _cover = path ? [UIImage imageWithContentsOfFile:path] : nil;
+ _hasStoredCover = _cover != nil;
+
+ NSMutableArray *fields = [NSMutableArray array], *labels = [NSMutableArray array], *stacks = [NSMutableArray array], *widths = [NSMutableArray array];
+ for (NSUInteger i = 0; i < fieldKeys().count; i++) {
+ NSString *key = fieldKeys()[i];
+ UILabel *label = [UILabel new];
+ label.text = fieldLabels()[i];
+ label.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
+ label.adjustsFontForContentSizeCategory = YES;
+ label.isAccessibilityElement = NO; // the field reads its own label
+ UITextField *field = [UITextField new];
+ field.text = _shown[key];
+ field.placeholder = _tags[key] ?: fieldLabels()[i];
+ field.accessibilityLabel = fieldLabels()[i];
+ field.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
+ field.adjustsFontForContentSizeCategory = YES;
+ field.clearButtonMode = UITextFieldViewModeWhileEditing;
+ field.autocapitalizationType = UITextAutocapitalizationTypeWords;
+ field.returnKeyType = i + 1 < fieldKeys().count ? UIReturnKeyNext : UIReturnKeyDone;
+ field.delegate = self;
+ [field addTarget:self action:@selector(changed) forControlEvents:UIControlEventEditingChanged];
+ [field setContentHuggingPriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];
+ UIStackView *stack = [[UIStackView alloc] initWithArrangedSubviews:@[label, field]];
+ stack.spacing = 12;
+ stack.translatesAutoresizingMaskIntoConstraints = NO;
+ [fields addObject:field];
+ [labels addObject:label];
+ [stacks addObject:stack];
+ [widths addObject:[label.widthAnchor constraintEqualToConstant:0]];
+ }
+ _fields = fields;
+ _labels = labels;
+ _stacks = stacks;
+ _labelWidths = widths;
+
+ self.title = @"Edit info";
+ self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancel)];
+ self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(save)];
+ return self;
+}
+
+- (void)viewDidLoad {
+ [super viewDidLoad];
+ _coverCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
+ _coverCell.selectionStyle = UITableViewCellSelectionStyleNone;
+ UIButtonConfiguration *change = [UIButtonConfiguration plainButtonConfiguration];
+ change.title = @"Change";
+ _coverButton = [UIButton buttonWithConfiguration:change primaryAction:nil];
+ _coverButton.showsMenuAsPrimaryAction = YES;
+ _coverButton.accessibilityLabel = @"Change cover";
+ _coverCell.accessoryView = _coverButton;
+ _restoreCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
+ [self fitLabels];
+ [self showCover];
+ [self changed];
+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(fitLabels) name:UIContentSizeCategoryDidChangeNotification object:nil];
+}
+
+- (void)dealloc {
+ [NSNotificationCenter.defaultCenter removeObserver:self];
+}
+
+// The names' labels share one width so the fields line up; at the accessibility sizes each label goes
+// above its field instead.
+- (void)fitLabels {
+ BOOL stacked = UIContentSizeCategoryIsAccessibilityCategory(self.traitCollection.preferredContentSizeCategory);
+ UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody compatibleWithTraitCollection:self.traitCollection];
+ CGFloat widest = 0;
+ for (NSString *text in fieldLabels()) widest = MAX(widest, ceil([text sizeWithAttributes:@{NSFontAttributeName: font}].width));
+ for (NSUInteger i = 0; i < _stacks.count; i++) {
+ _stacks[i].axis = stacked ? UILayoutConstraintAxisVertical : UILayoutConstraintAxisHorizontal;
+ _stacks[i].alignment = stacked ? UIStackViewAlignmentFill : UIStackViewAlignmentFirstBaseline;
+ _labelWidths[i].constant = widest;
+ _labelWidths[i].active = !stacked;
+ }
+}
+
+#pragma mark - state
+
+- (NSDictionary<NSString *, NSString *> *)names {
+ NSMutableDictionary<NSString *, NSString *> *names = [NSMutableDictionary dictionary];
+ for (NSUInteger i = 0; i < _fields.count; i++) names[fieldKeys()[i]] = _fields[i].text ?: @"";
+ return names;
+}
+
+// A name the way it would be stored: an empty field is the file's own.
+- (NSString *)effectiveName:(NSUInteger)i {
+ NSString *typed = trimmed(_fields[i].text);
+ return typed.length ? typed : _tags[fieldKeys()[i]] ?: @"";
+}
+
+- (BOOL)isDirty {
+ if (_coverChange != SGCoverKept) return YES;
+ for (NSUInteger i = 0; i < _fields.count; i++) {
+ if (![[self effectiveName:i] isEqualToString:_shown[fieldKeys()[i]] ?: @""]) return YES;
+ }
+ return NO;
+}
+
+- (BOOL)differsFromFile {
+ if (_cover) return YES;
+ for (NSUInteger i = 0; i < _fields.count; i++) {
+ if (![[self effectiveName:i] isEqualToString:_tags[fieldKeys()[i]] ?: @""]) return YES;
+ }
+ return NO;
+}
+
+- (void)changed {
+ BOOL dirty = self.isDirty;
+ self.navigationItem.rightBarButtonItem.enabled = dirty;
+ // A swipe down then asks before the changes go (presentationControllerDidAttemptToDismiss:).
+ self.modalInPresentation = dirty;
+ BOOL restorable = self.differsFromFile;
+ UIListContentConfiguration *content = [UIListContentConfiguration cellConfiguration];
+ content.text = @"Restore file's info";
+ content.textProperties.color = restorable ? UIColor.systemRedColor : UIColor.tertiaryLabelColor;
+ _restoreCell.contentConfiguration = content;
+ _restoreCell.userInteractionEnabled = restorable;
+ _restoreCell.accessibilityTraits = UIAccessibilityTraitButton | (restorable ? 0 : UIAccessibilityTraitNotEnabled);
+}
+
+- (void)showCover {
+ UIListContentConfiguration *content = [UIListContentConfiguration subtitleCellConfiguration];
+ content.text = @"Cover";
+ content.secondaryText = !_cover ? @"The file's own" : _coverChange == SGCoverPicked ? @"New picture" : @"Your picture";
+ content.secondaryTextProperties.color = UIColor.secondaryLabelColor;
+ content.image = _cover ?: [UIImage systemImageNamed:@"music.note"];
+ content.imageProperties.preferredSymbolConfiguration = [UIImageSymbolConfiguration configurationWithTextStyle:UIFontTextStyleTitle2];
+ content.imageProperties.tintColor = UIColor.secondaryLabelColor;
+ content.imageProperties.maximumSize = CGSizeMake(56, 56);
+ content.imageProperties.reservedLayoutSize = CGSizeMake(56, 56);
+ content.imageProperties.cornerRadius = 8;
+ content.imageProperties.accessibilityIgnoresInvertColors = YES;
+ _coverCell.contentConfiguration = content;
+
+ __weak typeof(self) weakSelf = self;
+ NSMutableArray<UIMenuElement *> *items = [NSMutableArray arrayWithArray:@[
+ [UIAction actionWithTitle:@"Choose from Photos" image:[UIImage systemImageNamed:@"photo.on.rectangle"] identifier:nil handler:^(UIAction *action) {
+ [weakSelf pickCoverFromFiles:NO];
+ }],
+ [UIAction actionWithTitle:@"Choose from Files" image:[UIImage systemImageNamed:@"folder"] identifier:nil handler:^(UIAction *action) {
+ [weakSelf pickCoverFromFiles:YES];
+ }],
+ ]];
+ if (_cover) {
+ UIAction *remove = [UIAction actionWithTitle:@"Remove cover" image:[UIImage systemImageNamed:@"trash"] identifier:nil handler:^(UIAction *action) {
+ [weakSelf useCover:nil];
+ }];
+ remove.attributes = UIMenuElementAttributesDestructive;
+ [items addObject:remove];
+ }
+ _coverButton.menu = [UIMenu menuWithChildren:items];
+ [_coverButton sizeToFit];
+}
+
+// nil removes the cover: the stored one goes on Save, a picked one goes at once.
+- (void)useCover:(UIImage *)image {
+ _cover = image;
+ _coverChange = image ? SGCoverPicked : _hasStoredCover ? SGCoverRemoved : SGCoverKept;
+ [self showCover];
+ [self changed];
+}
+
+#pragma mark - the actions
+
+- (void)restore {
+ for (NSUInteger i = 0; i < _fields.count; i++) _fields[i].text = _tags[fieldKeys()[i]];
+ [self.view endEditing:YES];
+ [self useCover:nil];
+}
+
+- (void)save {
+ [self.view endEditing:YES];
+ SGLocalFileSaveEdit(_uri, self.names, _coverChange == SGCoverPicked ? _cover : nil, _coverChange != SGCoverRemoved);
+ [self dismissViewControllerAnimated:YES completion:nil];
+}
+
+- (void)cancel {
+ if (self.isDirty) [self confirmDiscard];
+ else [self dismissViewControllerAnimated:YES completion:nil];
+}
+
+- (void)confirmDiscard {
+ UIAlertController *sheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
+ [sheet addAction:[UIAlertAction actionWithTitle:@"Discard changes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
+ [self dismissViewControllerAnimated:YES completion:nil];
+ }]];
+ [sheet addAction:[UIAlertAction actionWithTitle:@"Keep editing" style:UIAlertActionStyleCancel handler:nil]];
+ sheet.popoverPresentationController.barButtonItem = self.navigationItem.leftBarButtonItem;
+ [self presentViewController:sheet animated:YES completion:nil];
+}
+
+- (void)presentationControllerDidAttemptToDismiss:(UIPresentationController *)presentationController {
+ [self confirmDiscard];
+}
+
+- (void)pickCoverFromFiles:(BOOL)files {
+ [self.view endEditing:YES];
+ UIViewController *picker;
+ if (files) {
+ // A copy, so it is the app's own to read.
+ UIDocumentPickerViewController *documents = [[UIDocumentPickerViewController alloc] initForOpeningContentTypes:@[UTTypeImage] asCopy:YES];
+ documents.delegate = self;
+ picker = documents;
+ } else {
+ // Runs out of the app's process, so no Photos permission is asked.
+ UIImagePickerController *photos = [UIImagePickerController new];
+ photos.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
+ photos.delegate = self;
+ picker = photos;
+ }
+ [self presentViewController:picker animated:YES completion:nil];
+}
+
+- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info {
+ UIImage *image = info[UIImagePickerControllerOriginalImage];
+ if (image) [self useCover:image];
+ [picker dismissViewControllerAnimated:YES completion:nil];
+}
+
+- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
+ [picker dismissViewControllerAnimated:YES completion:nil];
+}
+
+- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
+ NSData *data = urls.firstObject ? [NSData dataWithContentsOfURL:urls.firstObject] : nil;
+ UIImage *image = data ? [UIImage imageWithData:data] : nil;
+ if (image) {
+ [self useCover:image];
+ return;
+ }
+ SGLog(@"local files: %@ is not an image", urls.firstObject.lastPathComponent);
+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Not an image" message:@"Pick a JPEG, PNG or HEIC file."
+ preferredStyle:UIAlertControllerStyleAlert];
+ [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
+ [self presentViewController:alert animated:YES completion:nil];
+}
+
+- (BOOL)textFieldShouldReturn:(UITextField *)field {
+ NSUInteger i = [_fields indexOfObject:field];
+ if (i != NSNotFound && i + 1 < _fields.count) [_fields[i + 1] becomeFirstResponder];
+ else [field resignFirstResponder];
+ return NO;
+}
+
+#pragma mark - the table
+
+- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
+ return 3;
+}
+
+- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
+ return section == 0 ? (NSInteger)_fields.count : 1;
+}
+
+- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
+ return section == 0 ? @"Kept by Vitrine for this file. The file itself is not changed." : nil;
+}
+
+- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
+ if (indexPath.section == 1) return _coverCell;
+ if (indexPath.section == 2) return _restoreCell;
+ // One cell per name, made once: the field keeps what was typed while the table scrolls.
+ UIStackView *stack = _stacks[(NSUInteger)indexPath.row];
+ if (stack.superview) return (UITableViewCell *)stack.superview.superview;
+ UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
+ cell.selectionStyle = UITableViewCellSelectionStyleNone;
+ [cell.contentView addSubview:stack];
+ UILayoutGuide *margins = cell.contentView.layoutMarginsGuide;
+ [NSLayoutConstraint activateConstraints:@[
+ [stack.leadingAnchor constraintEqualToAnchor:margins.leadingAnchor],
+ [stack.trailingAnchor constraintEqualToAnchor:margins.trailingAnchor],
+ [stack.topAnchor constraintEqualToAnchor:margins.topAnchor],
+ [stack.bottomAnchor constraintEqualToAnchor:margins.bottomAnchor],
+ ]];
+ return cell;
+}
+
+- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
+ [tableView deselectRowAtIndexPath:indexPath animated:YES];
+ if (indexPath.section == 0) [_fields[(NSUInteger)indexPath.row] becomeFirstResponder];
+ if (indexPath.section == 2) [self restore];
+}
+
+@end
+
+static UIViewController *topOf(UIViewController *presenter) {
+ UIViewController *top = presenter;
+ while (top.presentedViewController && !top.presentedViewController.isBeingDismissed) top = top.presentedViewController;
+ return top;
+}
+
+void SGLocalFilePresentEditor(UIViewController *presenter, NSString *uri) {
+ if (!presenter || !SGLocalFileIs(uri)) return;
+ SGLocalFileEditor *editor = [[SGLocalFileEditor alloc] initWithURI:uri];
+ UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:editor];
+ navigation.modalPresentationStyle = UIModalPresentationFormSheet;
+ // Outside Spotify's navigation stacks a sheet takes the system's appearance, light in light mode.
+ navigation.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;
+ navigation.presentationController.delegate = editor;
+ UISheetPresentationController *sheet = navigation.sheetPresentationController;
+ sheet.detents = @[UISheetPresentationControllerDetent.mediumDetent, UISheetPresentationControllerDetent.largeDetent];
+ sheet.prefersGrabberVisible = YES;
+ [topOf(presenter) presentViewController:navigation animated:YES completion:nil];
+}
+
+#pragma mark - the row
+
+@interface SGEditInfoRow : UIControl
+@property (nonatomic, copy) NSString *uri;
+@property (nonatomic, weak) UIViewController *menu;
+@end
+
+@implementation SGEditInfoRow {
+ UIImageView *_icon;
+ UILabel *_title;
+}
+
+- (instancetype)initWithFrame:(CGRect)frame {
+ if (!(self = [super initWithFrame:frame])) return nil;
+ UIColor *secondary = [UIColor colorWithWhite:1 alpha:UIAccessibilityDarkerSystemColorsEnabled() ? 0.80 : 0.65];
+ UIImage *glyph = [UIImage systemImageNamed:@"pencil" withConfiguration:[UIImageSymbolConfiguration configurationWithPointSize:20 weight:UIImageSymbolWeightRegular]];
+ // Colours drawn in, so nothing passes through the sheet's tint.
+ _icon = [[UIImageView alloc] initWithImage:[glyph imageWithTintColor:secondary renderingMode:UIImageRenderingModeAlwaysOriginal]];
+ _icon.contentMode = UIViewContentModeCenter;
+ _title = [UILabel new];
+ _title.font = rowFont();
+ _title.textColor = UIColor.whiteColor;
+ _title.text = @"Edit info";
+ for (UIView *view in @[_icon, _title]) {
+ view.userInteractionEnabled = NO;
+ [self addSubview:view];
+ }
+ self.isAccessibilityElement = YES;
+ self.accessibilityTraits = UIAccessibilityTraitButton;
+ self.accessibilityLabel = @"Edit info";
+ [self addTarget:self action:@selector(open) forControlEvents:UIControlEventTouchUpInside];
+ [self addTarget:self action:@selector(highlight) forControlEvents:UIControlEventTouchDown | UIControlEventTouchDragEnter];
+ [self addTarget:self action:@selector(unhighlight) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside | UIControlEventTouchCancel | UIControlEventTouchDragExit];
+ return self;
+}
+
+- (void)layoutSubviews {
+ [super layoutSubviews];
+ CGFloat width = self.bounds.size.width;
+ _icon.frame = CGRectMake(kSideMargin, (kRowHeight - kIconSide) / 2, kIconSide, kIconSide);
+ CGFloat titleX = kSideMargin + kIconSide + kSideMargin;
+ _title.frame = CGRectMake(titleX, 0, MAX(0, width - titleX - kSideMargin), kRowHeight);
+}
+
+- (void)highlight {
+ self.backgroundColor = [UIColor colorWithWhite:1 alpha:0.08];
+}
+
+- (void)unhighlight {
+ [UIView animateWithDuration:0.2 animations:^{ self.backgroundColor = UIColor.clearColor; }];
+}
+
+// One sheet at a time: Spotify's menu goes before the editor comes up over what presented it.
+- (void)open {
+ UIViewController *menu = self.menu, *host = menu.presentingViewController;
+ NSString *uri = self.uri;
+ if (!host) {
+ SGLocalFilePresentEditor(menu, uri);
+ return;
+ }
+ [menu dismissViewControllerAnimated:YES completion:^{ SGLocalFilePresentEditor(host, uri); }];
+}
+
+@end
+
+#pragma mark - the menu
+
+static UITableView *findTable(UIView *root, int depth) {
+ if ([root isKindOfClass:UITableView.class]) return (UITableView *)root;
+ if (depth > 5) return nil;
+ for (UIView *child in root.subviews) {
+ UITableView *table = findTable(child, depth + 1);
+ if (table) return table;
+ }
+ return nil;
+}
+
+static BOOL freeSlot(UIView *view) {
+ return !view || view.bounds.size.height < 1;
+}
+
+static void decide(UIViewController *menu, BOOL offered) {
+ objc_setAssociatedObject(menu, &kDecidedKey, @(offered), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+static void install(UIViewController *menu) {
+ UIView *root = menu.viewIfLoaded;
+ if (!root || [objc_getAssociatedObject(menu, &kDecidedKey) isEqual:@NO]) return;
+ UITableView *table = findTable(root, 0);
+ CGFloat width = table.bounds.size.width;
+ if (width <= 0) return;
+ SGEditInfoRow *row = objc_getAssociatedObject(menu, &kRowKey);
+ if (!row) {
+ NSString *uri = SGURIString(SGPlayerState().track.URI);
+ if (!SGLocalFileIs(uri) || !SGPlayerMenuIsPlayers(menu)) {
+ decide(menu, NO);
+ return;
+ }
+ // A header of Spotify's own sends Speed and pitch to the footer.
+ UIView *header = table.tableHeaderView;
+ BOOL headerOurs = freeSlot(header) || [NSStringFromClass(header.class) hasPrefix:@"SG"];
+ if (!headerOurs || !freeSlot(table.tableFooterView)) {
+ SGLog(@"local files: the menu's table has %@ and %@, Edit info left out",
+ header ? NSStringFromClass(header.class) : @"no header", table.tableFooterView ? NSStringFromClass(table.tableFooterView.class) : @"no footer");
+ decide(menu, NO);
+ return;
+ }
+ decide(menu, YES);
+ row = [[SGEditInfoRow alloc] initWithFrame:CGRectMake(0, 0, width, kRowHeight)];
+ row.uri = uri;
+ row.menu = menu;
+ objc_setAssociatedObject(menu, &kRowKey, row, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ table.tableFooterView = row;
+ [table invalidateIntrinsicContentSize];
+ SGLog(@"local files: Edit info offered for %@", uri);
+ return;
+ }
+ // Spotify replaced the footer, or the table changed width: put it back at the table's width.
+ if (table.tableFooterView != row || fabs(row.frame.size.width - width) > 0.5) {
+ row.frame = CGRectMake(0, row.frame.origin.y, width, kRowHeight);
+ table.tableFooterView = row;
+ [table invalidateIntrinsicContentSize];
+ }
+}
+
+%hook _TtC24ContextMenu_InternalImpl25ContextMenuViewController
+- (void)viewDidLayoutSubviews {
+ %orig;
+ install((UIViewController *)self);
+}
+%end
+
+%ctor {
+ %init;
+ SGRequireClasses(@[@"_TtC24ContextMenu_InternalImpl25ContextMenuViewController"]);
+}
diff --git a/tweak/Sources/Shared/LocalFiles/LocalFileInfo.x b/tweak/Sources/Shared/LocalFiles/LocalFileInfo.x
new file mode 100644
index 00000000..ddea3ccc
--- /dev/null
+++ b/tweak/Sources/Shared/LocalFiles/LocalFileInfo.x
@@ -0,0 +1,114 @@
+// A local file's edit laid over what Spotify read from it (LocalFiles.h).
+//
+// -[SPTPlayerTrack metadata] is the one place: trackTitle, artistName, albumTitle and imageURL each read
+// self.metadata and take title, artist_name, album_title and image_url from it (their code in the
+// binary, through NSDictionary's spt_metadata_* in IDZKAdditions), and the player, the now playing bar
+// and the system's now playing info are built from the player's track. So the names go in there, and
+// the cover as an image address of the kind Spotify gives a local file, spotify:localfileimage:<path>.
+//
+// Spotify's loader hands such an address (three parts, no ipod-library in it) to
+// SPTLocalAVAssetImageLoaderRequest, whose -loadLocalFileImage reads the cover out of the file at the
+// path with AVAsset and passes its bytes to -dispatchSuccess:, which gives them to the delegate's
+// imageLoaderRequest:didLoadImageData:. The request caches nothing (preventInMemoryCaching and
+// preventPersistentCaching answer YES), so a stored cover is read from disk each time and passed on
+// the same way. The system's now playing artwork is added too, in case Spotify fetches it apart.
+#import <MediaPlayer/MediaPlayer.h>
+#import "Core/SGCore.h"
+#import "Headers/SPTLocalAVAssetImageLoaderRequest.h"
+#import "Headers/SPTPlayer.h"
+#import "Shared/Player/NowPlayingExtras.h"
+#import "Shared/Player/PlayerState.h"
+#import "LocalFiles.h"
+
+// Called for every track in every list many times a second: one prefix check for any other track.
+static NSDictionary *withEdit(NSDictionary *metadata, NSString *uri) {
+ NSDictionary *edit = SGLocalFileEditFor(uri);
+ if (!edit) return metadata;
+ NSMutableDictionary *edited = metadata ? [metadata mutableCopy] : [NSMutableDictionary dictionary];
+ if ([edit[@"title"] length]) edited[@"title"] = edit[@"title"];
+ if ([edit[@"artist"] length]) edited[@"artist_name"] = edit[@"artist"];
+ if ([edit[@"album"] length]) edited[@"album_title"] = edit[@"album"];
+ NSString *cover = SGLocalFileCoverURL(SGLocalFileCoverPath(edit));
+ // Every size, since a reader may take any of them: Spotify's loader, and the redesign's artwork bridge
+ // (Redesigned/Kit/SGRBridges.x), which reads the stored file itself.
+ if (cover) {
+ for (NSString *field in @[@"image_small_url", @"image_url", @"image_large_url", @"image_xlarge_url"]) edited[field] = cover;
+ }
+ return edited;
+}
+
+#pragma mark - the system's now playing artwork
+
+@interface SGLocalFileNowPlaying : NSObject <SGPlayerStateObserver>
+@end
+
+@implementation SGLocalFileNowPlaying {
+ NSString *_track;
+}
+
+// Spotify's info is matched by its title, which is the edited one when Spotify built it from the
+// player's track and the file's own when it did not, so the artwork rides on either.
+- (void)show:(SPTPlayerState *)state {
+ NSString *uri = SGURIString(state.track.URI);
+ NSString *path = SGLocalFileCoverPath(SGLocalFileEditFor(uri));
+ UIImage *cover = path ? [UIImage imageWithContentsOfFile:path] : nil;
+ if (!cover) {
+ SGNowPlayingSetExtras(@"localFiles", nil, nil);
+ SGNowPlayingSetExtras(@"localFiles.tags", nil, nil);
+ return;
+ }
+ MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithBoundsSize:cover.size requestHandler:^UIImage *(CGSize size) {
+ return cover;
+ }];
+ SGNowPlayingSetExtras(@"localFiles", @{MPMediaItemPropertyArtwork: artwork}, SGLocalFileInfo(uri)[@"title"]);
+ SGNowPlayingSetExtras(@"localFiles.tags", @{MPMediaItemPropertyArtwork: artwork}, SGLocalFileTags(uri)[@"title"]);
+}
+
+- (void)playerStateDidChange:(SPTPlayerState *)state {
+ NSString *track = SGURIString(state.track.URI);
+ if (!track || [track isEqualToString:_track]) return;
+ _track = track;
+ [self show:state];
+}
+
+- (void)editsChanged:(NSNotification *)note {
+ if ([note.object isEqual:_track]) [self show:SGPlayerState()];
+}
+
+@end
+
+#pragma mark - hooks
+
+%hook SPTPlayerTrack
+- (NSDictionary *)metadata {
+ NSDictionary *metadata = %orig;
+ NSString *uri = SGURIString(self.URI);
+ return SGLocalFileIs(uri) ? withEdit(metadata, uri) : metadata;
+}
+%end
+
+%hook SPTLocalAVAssetImageLoaderRequest
+- (void)loadLocalFileImage {
+ NSString *path = SGLocalFileCoverInURL(self.URL.absoluteString);
+ if (!path) {
+ %orig;
+ return;
+ }
+ NSData *data = [NSData dataWithContentsOfFile:path];
+ if (!data) {
+ SGLog(@"local files: the cover %@ is gone, the track shows none", path.lastPathComponent);
+ %orig;
+ return;
+ }
+ [self dispatchSuccess:data];
+}
+%end
+
+%ctor {
+ %init;
+ static SGLocalFileNowPlaying *nowPlaying;
+ nowPlaying = [SGLocalFileNowPlaying new];
+ SGAddPlayerStateObserver(nowPlaying);
+ [NSNotificationCenter.defaultCenter addObserver:nowPlaying selector:@selector(editsChanged:) name:SGLocalFileEditsDidChangeNotification object:nil];
+ SGRequireClasses(@[@"SPTPlayerTrack", @"SPTLocalAVAssetImageLoaderRequest"]);
+}
diff --git a/tweak/Sources/Shared/LocalFiles/LocalFiles.h b/tweak/Sources/Shared/LocalFiles/LocalFiles.h
index f29033c7..743e4bf0 100644
--- a/tweak/Sources/Shared/LocalFiles/LocalFiles.h
+++ b/tweak/Sources/Shared/LocalFiles/LocalFiles.h
@@ -19,8 +19,10 @@
// A local file's URI, or a lyrics key made from one.
BOOL SGLocalFileIs(NSString *uri);
-// What the lyrics engine keeps a local file under: its URI, and once it is edited the edit's number
-// after a "#", so an edit reads as a new track and its lyrics are looked up again under the new names.
+// What the lyrics engine keeps a local file under: its URI, and once its names are edited the edit's
+// number after a "#", so a rename reads as a new track and its lyrics are looked up again under the new
+// names. A new cover alone keeps the key. Posting SGLocalFileEditsDidChangeNotification is what has the
+// lyrics engine ask for the new key while the file plays.
// nil for anything but a local file.
NSString *SGLocalFileLyricsKey(NSString *uri);
// The names a local file goes by, the user's edits over its own tags: title, artist, album (each
@@ -32,9 +34,9 @@ NSDictionary<NSString *, id> *SGLocalFileTags(NSString *uri);
// The user's edit of a local file, nil when there is none. Safe from any thread.
NSDictionary<NSString *, id> *SGLocalFileEditFor(NSString *uri);
// Stores the names (an empty or missing one, or one the file already has, falls back to the file's
-// own) and a new cover when `cover` is set; `keepCover` NO drops the stored one. Main thread.
+// own) and a new cover when `cover` is set; `keepCover` NO drops the stored one. The file's own names
+// with no cover remove the edit. Main thread.
void SGLocalFileSaveEdit(NSString *uri, NSDictionary<NSString *, NSString *> *names, UIImage *cover, BOOL keepCover);
-void SGLocalFileForget(NSString *uri);
// Where the stored covers are, and the one an edit names; nil when it names none.
NSString *SGLocalFileCoversDirectory(void);
NSString *SGLocalFileCoverPath(NSDictionary<NSString *, id> *edit);
diff --git a/tweak/Sources/Shared/LocalFiles/LocalFiles.m b/tweak/Sources/Shared/LocalFiles/LocalFiles.m
index 6d5e8584..44c1c8d1 100644
--- a/tweak/Sources/Shared/LocalFiles/LocalFiles.m
+++ b/tweak/Sources/Shared/LocalFiles/LocalFiles.m
@@ -113,7 +113,8 @@ NSString *SGLocalFileCoverURL(NSString *path) {
static dispatch_once_t once;
dispatch_once(&once, ^{
NSMutableCharacterSet *set = [NSCharacterSet.URLPathAllowedCharacterSet mutableCopy];
- [set removeCharactersInString:@":"];
+ // -[NSURL spotifyURIComponents] splits the address on ":"; "/" goes too, so the path is one plain part.
+ [set removeCharactersInString:@":/"];
allowed = set;
});
NSString *escaped = [path stringByAddingPercentEncodingWithAllowedCharacters:allowed];
@@ -167,10 +168,18 @@ void SGLocalFileSaveEdit(NSString *uri, NSDictionary<NSString *, NSString *> *na
else if (keepCover && oldCover) edit[@"cover"] = old[@"cover"];
if (oldCover && ![edit[@"cover"] isEqual:old[@"cover"]]) [NSFileManager.defaultManager removeItemAtPath:oldCover error:nil];
+ // The lyrics key changes with the names only: a cover alone leaves the lyrics where they are, and the
+ // file's own names go back to the bare URI, whose lyrics may still be kept.
+ BOOL named = NO, renamed = NO;
+ for (NSString *field in @[@"title", @"artist", @"album"]) {
+ named = named || edit[field];
+ renamed = renamed || !(edit[field] == old[field] || [edit[field] isEqual:old[field]]);
+ }
+ // Milliseconds, so no two renames of a track share a lyrics key, a reset in between or not.
+ if (named) edit[@"number"] = renamed || !old[@"number"] ? @((long long)(NSDate.date.timeIntervalSince1970 * 1000)) : old[@"number"];
+
NSMutableDictionary *edits = [allEdits() mutableCopy];
if (edit.count) {
- // Milliseconds, so no two edits of a track share a lyrics key, a reset in between or not.
- edit[@"number"] = @((long long)(NSDate.date.timeIntervalSince1970 * 1000));
edits[uri] = edit;
} else {
[edits removeObjectForKey:uri];
@@ -179,15 +188,3 @@ void SGLocalFileSaveEdit(NSString *uri, NSDictionary<NSString *, NSString *> *na
SGLog(@"local files: %@ %@", uri, edit.count ? [NSString stringWithFormat:@"edited: %@", edit] : @"back to its own tags");
changed(uri);
}
-
-void SGLocalFileForget(NSString *uri) {
- NSDictionary *old = SGLocalFileEditFor(uri);
- if (!old) return;
- NSString *cover = SGLocalFileCoverPath(old);
- if (cover) [NSFileManager.defaultManager removeItemAtPath:cover error:nil];
- NSMutableDictionary *edits = [allEdits() mutableCopy];
- [edits removeObjectForKey:uri];
- storeEdits(edits);
- SGLog(@"local files: %@ back to its own tags", uri);
- changed(uri);
-}
diff --git a/tweak/Sources/Shared/Lyrics/KaraokeSource.x b/tweak/Sources/Shared/Lyrics/KaraokeSource.x
index e203cabd..467ebd7d 100644
--- a/tweak/Sources/Shared/Lyrics/KaraokeSource.x
+++ b/tweak/Sources/Shared/Lyrics/KaraokeSource.x
@@ -207,29 +207,68 @@ void SGKaraokeAskSpotifyForTiming(NSString *trackID) {
});
}
+// A local file the sources had nothing for is asked again this many times, on askAgainLater's pauses:
+// nothing may mean a request was lost, and LRCLIB asked alone cannot say which it was, so a song it has
+// nothing for is not asked for every minute while it plays. ponytail: an outage longer than the pauses
+// (about two minutes) leaves the file without lyrics until its names are edited or Spotify restarts; a
+// source answer that tells "lost" from "none" would lift that.
+static const NSUInteger kLocalTries = 4;
+
+// With no source of the mod's switched on, a local file still gets LRCLIB, the open and keyless floor of
+// the order, by the names it goes by: spclient has nothing for it, and without this the redesign's
+// lyrics, the lock screen and the Live Activity would have nothing to show. Answers NO, asking nothing,
+// when the file has no title and artist to search with.
+static BOOL askLrcLib(NSString *trackID, void (^done)(SGLyricsResult *lyrics)) {
+ NSDictionary *info = SGLocalFileInfo(trackID);
+ SGLyricsProvider *lrclib = SGLyricsProviderFor(@"lrclib");
+ if (!lrclib.ask || ![info[@"title"] length] || ![info[@"artist"] length]) return NO;
+ SGLyricsQuery *query = [SGLyricsQuery new];
+ query.trackID = trackID;
+ query.title = info[@"title"];
+ query.artist = info[@"artist"];
+ query.album = info[@"album"];
+ query.seconds = [info[@"seconds"] integerValue];
+ SGLog(@"karaoke: no source is on, asking LRCLIB for the local file \"%@\" by \"%@\"", query.title, query.artist);
+ lrclib.ask(query, ^(SGLyricsResult *lyrics) {
+ if (lyrics.karaokeLines && !lyrics.provider) lyrics.provider = lrclib.name;
+ done(lyrics);
+ });
+ return YES;
+}
+
+// Main queue only.
void SGKaraokeRequestLyrics(NSString *trackID) {
if (!trackID || sg_lyrics[trackID] || [sg_requested containsObject:trackID]) return;
// spclient has nothing for a local file, which only the sources can name.
BOOL local = SGLocalFileIs(trackID);
- if (!sg_ownSources) {
- if (!local) requestFromSpotify(trackID);
+ if (!sg_ownSources && !local) {
+ requestFromSpotify(trackID);
return;
}
[sg_requested addObject:trackID];
[sg_asking addObject:trackID];
- SGLyricsFetch(trackID, ^(SGLyricsResult *lyrics) {
- [sg_asking removeObject:trackID];
+ void (^answered)(SGLyricsResult *) = ^(SGLyricsResult *lyrics) {
if (lyrics.karaokeLines) {
- keep(trackID, lyrics.karaokeLines); // on the main queue, where the fetch answers
+ [sg_asking removeObject:trackID];
+ [sg_losses removeObjectForKey:trackID];
+ keep(trackID, lyrics.karaokeLines); // on the main queue, where the sources answer
SGLyricsSetCredit(trackID, lyrics.provider);
- // Plain text is shown while Spotify is asked whether it has the song timed.
- if (SGKaraokeLinesTiming(lyrics.karaokeLines) != SGKaraokeTimingNone) return;
+ // Plain text is shown while Spotify is asked whether it has the song timed; it has no local file.
+ if (local || SGKaraokeLinesTiming(lyrics.karaokeLines) != SGKaraokeTimingNone) return;
+ } else if (local) {
+ // Asked again after a pause; a miss the sources keep answers at once then. An instrumental, or
+ // a file out of tries, is left asked for: the readers ask on every tick, and an edit of its
+ // names gives it a new key.
+ if (!lyrics.instrumental && sg_losses[trackID].unsignedIntegerValue < kLocalTries) askAgainLater(trackID);
+ else [sg_asking removeObject:trackID];
+ return;
}
- // Left asked for: the readers ask on every tick, and an edit of its names gives it a new key.
- if (local) return;
+ [sg_asking removeObject:trackID];
[sg_requested removeObject:trackID];
requestFromSpotify(trackID);
- });
+ };
+ if (sg_ownSources) SGLyricsFetch(trackID, answered);
+ else if (!askLrcLib(trackID, answered)) [sg_asking removeObject:trackID];
}
id SGKaraokePlayer(void) {
@@ -294,11 +333,13 @@ void SGKaraokeRememberTrack(SPTPlayerTrack *track) {
// beat of starting it and gives its card list about a second to load, so an answer that is already
// in is what puts the card there. The track is named here, so no walk waits for a name.
static void prefetch(SPTPlayerTrack *track, NSString *trackID, SPTPlayerState *state) {
+ // Spotify never asks for a local file's lyrics, so they are asked for and kept here, a source of the
+ // mod's on or not (SGKaraokeRequestLyrics). The state is read on any thread, and the kept lines are
+ // the main queue's.
+ BOOL local = SGLocalFileIs(trackID);
+ if (local) dispatch_async(dispatch_get_main_queue(), ^{ SGKaraokeRequestLyrics(trackID); });
if (!sg_ownSources) return;
- // Spotify never asks for a local file's lyrics, so they are asked for and kept here. The state is
- // read on any thread, and the kept lines are the main queue's.
- if (SGLocalFileIs(trackID)) dispatch_async(dispatch_get_main_queue(), ^{ SGKaraokeRequestLyrics(trackID); });
- else SGLyricsPrefetch(trackID);
+ if (!local) SGLyricsPrefetch(trackID);
SPTPlayerTrack *next = upNextIn(state);
NSString *nextID = idOf(next);
if (!nextID || [nextID isEqualToString:trackID]) return;
@@ -357,6 +398,14 @@ static void prefetch(SPTPlayerTrack *track, NSString *trackID, SPTPlayerState *s
sg_asking = [NSMutableSet set];
sg_losses = [NSMutableDictionary dictionary];
sg_ownSources = SGLyricsEnabled();
+ // A rename gives the file playing a new lyrics key at once, with no new state from the player to
+ // bring it here, so the new key is asked for now; the redesign's lyrics view shows what comes in.
+ // Posted on the main thread.
+ [NSNotificationCenter.defaultCenter addObserverForName:SGLocalFileEditsDidChangeNotification object:nil queue:nil
+ usingBlock:^(NSNotification *note) {
+ NSString *key = SGLocalFileLyricsKey(note.object);
+ if (key && [key isEqualToString:SGKaraokePlayingTrack()]) SGKaraokeRequestLyrics(key);
+ }];
%init;
SGLog(@"karaoke: on");
SGRequireClasses(@[
diff --git a/tweak/Sources/Shared/Player/SpeedPitch.h b/tweak/Sources/Shared/Player/SpeedPitch.h
index a4357202..3127ff96 100644
--- a/tweak/Sources/Shared/Player/SpeedPitch.h
+++ b/tweak/Sources/Shared/Player/SpeedPitch.h
@@ -16,6 +16,8 @@
// a menu presented from a now playing controller is taken for the player's without it, which is how the
// native look's player gets the block.
void SGPlayerMenuWatchMoreButton(UIView *button);
+// Whether a context menu sheet is the player's, by the same test; decided once per menu.
+BOOL SGPlayerMenuIsPlayers(UIViewController *menu);
// The speed Spotify's sound plays at, 1 when normal.
double SGPlayerSpeed(void);
// Whether speed can apply: Spotify's output was taken over when it wired it.
diff --git a/tweak/Sources/Shared/Player/SpeedPitchMenu.x b/tweak/Sources/Shared/Player/SpeedPitchMenu.x
index 2a29b5c1..e385bc77 100644
--- a/tweak/Sources/Shared/Player/SpeedPitchMenu.x
+++ b/tweak/Sources/Shared/Player/SpeedPitchMenu.x
@@ -581,6 +581,10 @@ static BOOL isPlayerMenu(UIViewController *menu) {
return ours;
}
+BOOL SGPlayerMenuIsPlayers(UIViewController *menu) {
+ return isPlayerMenu(menu);
+}
+
#pragma mark - Spotify's rows
// The sheet keeps its spinner up until Spotify's rows are in, and they are in when every item factory